Imported Upstream version 0.9.1 upstream/0.9.1
authorYoungjae Shin <yj99.shin@samsung.com>
Fri, 26 Jun 2015 06:26:23 +0000 (15:26 +0900)
committerYoungjae Shin <yj99.shin@samsung.com>
Fri, 3 Jul 2015 05:49:32 +0000 (14:49 +0900)
1638 files changed:
.gitignore
LICENSE.md [new file with mode: 0644]
NOTICE.md [new file with mode: 0644]
Readme.scons.txt
SConstruct
android/Base/app/build.gradle [deleted file]
android/Base/app/jni/Android.mk [deleted file]
android/Base/app/jni/Application.mk [deleted file]
android/Base/app/jni/ocheaderoption-jni.cpp [deleted file]
android/Base/app/jni/ocplatform-jni.cpp [deleted file]
android/Base/app/jni/ocrepresentation-jni.cpp [deleted file]
android/Base/app/jni/ocresource-jni.cpp [deleted file]
android/Base/app/jni/ocstack-jni.cpp [deleted file]
android/Base/app/jni/ocstack-jni.h [deleted file]
android/Base/app/jni/platformcfg-jni.cpp [deleted file]
android/Base/app/proguard-rules.pro [deleted file]
android/Base/app/src/androidTest/java/org/iotivity/base/ApplicationTest.java [deleted file]
android/Base/app/src/main/AndroidManifest.xml [deleted file]
android/Base/app/src/main/java/org/iotivity/base/AbstractDeleteCallback.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/AbstractFindCallback.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/AbstractGetCallback.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/AbstractObserveCallback.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/AbstractPostCallback.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/AbstractPutCallback.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/AbstractSubscriberCallback.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/EntityHandler.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/NativeInstance.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/OCHeaderOption.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/OCPlatform.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/OCRepresentation.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/OCResource.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/OCResourceRequest.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/OCResourceResponse.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/OCStackResult.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/ObserveType.java [deleted file]
android/Base/app/src/main/java/org/iotivity/base/PlatformConfig.java [deleted file]
android/Base/app/src/main/res/values/strings.xml [deleted file]
android/Base/app/src/main/res/values/styles.xml [deleted file]
android/Base/build.gradle [deleted file]
android/Base/gradle.properties [deleted file]
android/Base/gradlew [deleted file]
android/Base/settings.gradle [deleted file]
android/BuildInstructionsForAndroidAPI.txt [new file with mode: 0644]
android/SimpleClient/app/build.gradle [deleted file]
android/SimpleClient/app/proguard-rules.pro [deleted file]
android/SimpleClient/app/src/androidTest/java/org/iotivity/simpleclient/ApplicationTest.java [deleted file]
android/SimpleClient/app/src/main/AndroidManifest.xml [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/FoundResource.java [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnGet.java [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnObserve.java [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost.java [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost2.java [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPut.java [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleClient.java [deleted file]
android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleToast.java [deleted file]
android/SimpleClient/app/src/main/res/layout/activity_simple_client.xml [deleted file]
android/SimpleClient/app/src/main/res/menu/simple_client.xml [deleted file]
android/SimpleClient/app/src/main/res/values-w820dp/dimens.xml [deleted file]
android/SimpleClient/app/src/main/res/values/dimens.xml [deleted file]
android/SimpleClient/app/src/main/res/values/strings.xml [deleted file]
android/SimpleClient/app/src/main/res/values/styles.xml [deleted file]
android/SimpleClient/build.gradle [deleted file]
android/SimpleClient/gradle.properties [deleted file]
android/SimpleClient/gradlew [deleted file]
android/SimpleClient/settings.gradle [deleted file]
android/android_api/.gitignore [new file with mode: 0644]
android/android_api/SConscript [new file with mode: 0644]
android/android_api/android_api.iml [new file with mode: 0755]
android/android_api/base/.gitignore [new file with mode: 0644]
android/android_api/base/base.iml [new file with mode: 0755]
android/android_api/base/build.gradle [new file with mode: 0755]
android/android_api/base/jni/Android.mk [new file with mode: 0644]
android/android_api/base/jni/Application.mk [new file with mode: 0644]
android/android_api/base/jni/JniCaInterface.c [new file with mode: 0644]
android/android_api/base/jni/JniCaInterface.h [new file with mode: 0644]
android/android_api/base/jni/JniEntityHandler.cpp [new file with mode: 0644]
android/android_api/base/jni/JniEntityHandler.h [new file with mode: 0644]
android/android_api/base/jni/JniListenerManager.cpp [new file with mode: 0644]
android/android_api/base/jni/JniListenerManager.h [new file with mode: 0644]
android/android_api/base/jni/JniOcPlatform.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcPlatform.h [new file with mode: 0644]
android/android_api/base/jni/JniOcPresenceHandle.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcPresenceHandle.h [new file with mode: 0644]
android/android_api/base/jni/JniOcRepresentation.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcRepresentation.h [new file with mode: 0644]
android/android_api/base/jni/JniOcRequestHandle.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcRequestHandle.h [new file with mode: 0644]
android/android_api/base/jni/JniOcResource.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcResource.h [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceHandle.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceHandle.h [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceIdentifier.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceIdentifier.h [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceRequest.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceRequest.h [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceResponse.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcResourceResponse.h [new file with mode: 0644]
android/android_api/base/jni/JniOcStack.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcStack.h [new file with mode: 0644]
android/android_api/base/jni/JniOnDeleteListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnDeleteListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnDeviceInfoListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnDeviceInfoListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnGetListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnGetListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnObserveListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnObserveListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnPostListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnPostListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnPresenceListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnPresenceListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnPutListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnPutListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnResourceFoundListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnResourceFoundListener.h [new file with mode: 0644]
android/android_api/base/jni/JniUtils.cpp [new file with mode: 0644]
android/android_api/base/jni/JniUtils.h [new file with mode: 0644]
android/android_api/base/proguard-rules.pro [new file with mode: 0755]
android/android_api/base/src/androidTest/AndroidManifest.xml [new file with mode: 0755]
android/android_api/base/src/androidTest/java/org/iotivity/base/OcRepresentationTest.java [new file with mode: 0644]
android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java [new file with mode: 0644]
android/android_api/base/src/main/AndroidManifest.xml [new file with mode: 0755]
android/android_api/base/src/main/java/org/iotivity/base/EntityHandlerResult.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/ErrorCode.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/ModeType.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/ObservationInfo.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/ObserveAction.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/ObserveType.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcConnectivityType.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcException.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcHeaderOption.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcPlatformStatus.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcPresenceHandle.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcPresenceStatus.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcRepresentation.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcRequestHandle.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcResource.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcResourceHandle.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcResourceIdentifier.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcResourceRequest.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcResourceResponse.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/PlatformConfig.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/QualityOfService.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/RequestHandlerFlag.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/RequestType.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/ResourceProperty.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/ServiceType.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/ca/CaInterface.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/ca/CaWiFiInterface.java [new file with mode: 0644]
android/android_api/build.gradle [new file with mode: 0755]
android/android_api/gradle.properties [new file with mode: 0755]
android/android_api/gradle/wrapper/gradle-wrapper.jar [new file with mode: 0755]
android/android_api/gradle/wrapper/gradle-wrapper.properties [new file with mode: 0755]
android/android_api/gradlew [new file with mode: 0755]
android/android_api/gradlew.bat [moved from android/SimpleClient/gradlew.bat with 100% similarity, mode: 0755]
android/android_api/settings.gradle [new file with mode: 0755]
android/examples/build.gradle [new file with mode: 0755]
android/examples/examples.iml [new file with mode: 0755]
android/examples/fridgeclient/.gitignore [new file with mode: 0644]
android/examples/fridgeclient/build.gradle [new file with mode: 0755]
android/examples/fridgeclient/fridgeclient.iml [new file with mode: 0755]
android/examples/fridgeclient/src/main/AndroidManifest.xml [new file with mode: 0755]
android/examples/fridgeclient/src/main/java/org/iotivity/base/examples/fridgeclient/FridgeClient.java [new file with mode: 0644]
android/examples/fridgeclient/src/main/java/org/iotivity/base/examples/fridgeclient/StringConstants.java [new file with mode: 0644]
android/examples/fridgeclient/src/main/res/drawable-hdpi/ic_launcher.png [moved from android/SimpleClient/app/src/main/res/drawable-hdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeclient/src/main/res/drawable-mdpi/ic_launcher.png [moved from android/SimpleClient/app/src/main/res/drawable-mdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeclient/src/main/res/drawable-xhdpi/ic_launcher.png [moved from android/SimpleClient/app/src/main/res/drawable-xhdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeclient/src/main/res/drawable-xxhdpi/ic_launcher.png [moved from android/SimpleClient/app/src/main/res/drawable-xxhdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeclient/src/main/res/layout/activity_fridge_client.xml [new file with mode: 0755]
android/examples/fridgeclient/src/main/res/menu/menu_fridge_client.xml [new file with mode: 0755]
android/examples/fridgeclient/src/main/res/values-w820dp/dimens.xml [new file with mode: 0755]
android/examples/fridgeclient/src/main/res/values/dimens.xml [new file with mode: 0755]
android/examples/fridgeclient/src/main/res/values/strings.xml [new file with mode: 0755]
android/examples/fridgeclient/src/main/res/values/styles.xml [new file with mode: 0755]
android/examples/fridgeserver/.gitignore [new file with mode: 0644]
android/examples/fridgeserver/build.gradle [new file with mode: 0755]
android/examples/fridgeserver/fridgeserver.iml [new file with mode: 0755]
android/examples/fridgeserver/src/main/AndroidManifest.xml [new file with mode: 0755]
android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/DeviceResource.java [new file with mode: 0644]
android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/DoorResource.java [new file with mode: 0644]
android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/FridgeServer.java [new file with mode: 0644]
android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/LightResource.java [new file with mode: 0644]
android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/Refrigerator.java [new file with mode: 0644]
android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/Resource.java [new file with mode: 0644]
android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/StringConstants.java [new file with mode: 0644]
android/examples/fridgeserver/src/main/res/drawable-hdpi/ic_launcher.png [moved from android/Base/app/src/main/res/drawable-hdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeserver/src/main/res/drawable-mdpi/ic_launcher.png [moved from android/Base/app/src/main/res/drawable-mdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeserver/src/main/res/drawable-xhdpi/ic_launcher.png [moved from android/Base/app/src/main/res/drawable-xhdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeserver/src/main/res/drawable-xxhdpi/ic_launcher.png [moved from android/Base/app/src/main/res/drawable-xxhdpi/ic_launcher.png with 100% similarity, mode: 0755]
android/examples/fridgeserver/src/main/res/layout/activity_fridge_server.xml [new file with mode: 0755]
android/examples/fridgeserver/src/main/res/menu/menu_fridge_server.xml [new file with mode: 0755]
android/examples/fridgeserver/src/main/res/values-w820dp/dimens.xml [new file with mode: 0755]
android/examples/fridgeserver/src/main/res/values/dimens.xml [new file with mode: 0755]
android/examples/fridgeserver/src/main/res/values/strings.xml [new file with mode: 0755]
android/examples/fridgeserver/src/main/res/values/styles.xml [new file with mode: 0755]
android/examples/gradle/wrapper/gradle-wrapper.jar [new file with mode: 0755]
android/examples/gradle/wrapper/gradle-wrapper.properties [new file with mode: 0755]
android/examples/gradlew [new file with mode: 0755]
android/examples/gradlew.bat [moved from android/Base/gradlew.bat with 100% similarity, mode: 0755]
android/examples/message/.gitignore [new file with mode: 0644]
android/examples/message/build.gradle [new file with mode: 0755]
android/examples/message/message.iml [new file with mode: 0755]
android/examples/message/src/main/AndroidManifest.xml [new file with mode: 0755]
android/examples/message/src/main/java/base/iotivity/org/examples/message/IMessageLogger.java [new file with mode: 0644]
android/examples/settings.gradle [new file with mode: 0755]
android/examples/simpleclient/.gitignore [new file with mode: 0644]
android/examples/simpleclient/build.gradle [new file with mode: 0755]
android/examples/simpleclient/simpleclient.iml [new file with mode: 0755]
android/examples/simpleclient/src/main/AndroidManifest.xml [new file with mode: 0755]
android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/Light.java [new file with mode: 0644]
android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/SimpleClient.java [new file with mode: 0644]
android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/StringConstants.java [new file with mode: 0644]
android/examples/simpleclient/src/main/res/drawable-hdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleclient/src/main/res/drawable-mdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleclient/src/main/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleclient/src/main/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleclient/src/main/res/layout/activity_main.xml [new file with mode: 0755]
android/examples/simpleclient/src/main/res/menu/menu_main.xml [new file with mode: 0755]
android/examples/simpleclient/src/main/res/values-w820dp/dimens.xml [new file with mode: 0755]
android/examples/simpleclient/src/main/res/values/dimens.xml [new file with mode: 0755]
android/examples/simpleclient/src/main/res/values/strings.xml [new file with mode: 0755]
android/examples/simpleclient/src/main/res/values/styles.xml [new file with mode: 0755]
android/examples/simpleserver/.gitignore [new file with mode: 0644]
android/examples/simpleserver/build.gradle [new file with mode: 0755]
android/examples/simpleserver/simpleserver.iml [new file with mode: 0755]
android/examples/simpleserver/src/main/AndroidManifest.xml [new file with mode: 0755]
android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/LightRepThread.java [new file with mode: 0644]
android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/LightResource.java [new file with mode: 0644]
android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/SimpleServer.java [new file with mode: 0644]
android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/StringConstants.java [new file with mode: 0644]
android/examples/simpleserver/src/main/res/drawable-hdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleserver/src/main/res/drawable-mdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleserver/src/main/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleserver/src/main/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0755]
android/examples/simpleserver/src/main/res/layout/activity_main.xml [new file with mode: 0755]
android/examples/simpleserver/src/main/res/menu/menu_main.xml [new file with mode: 0755]
android/examples/simpleserver/src/main/res/values-w820dp/dimens.xml [new file with mode: 0755]
android/examples/simpleserver/src/main/res/values/dimens.xml [new file with mode: 0755]
android/examples/simpleserver/src/main/res/values/strings.xml [new file with mode: 0755]
android/examples/simpleserver/src/main/res/values/styles.xml [new file with mode: 0755]
arduino.scons
auto_build.sh
build_common/SConscript
build_common/android/SConscript
build_common/android/compatibility/android_cpp11_compat.cpp
build_common/android/compatibility/android_cpp11_compat.h
build_common/arduino/SConscript
build_common/darwin/SConscript
build_common/external_libs.scons [new file with mode: 0644]
build_common/iotivityconfig/__init__.py [new file with mode: 0644]
build_common/iotivityconfig/compiler/__init__.py [new file with mode: 0644]
build_common/iotivityconfig/compiler/configuration.py [new file with mode: 0644]
build_common/iotivityconfig/compiler/default_configuration.py [new file with mode: 0644]
build_common/iotivityconfig/compiler/factory.py [new file with mode: 0644]
build_common/iotivityconfig/compiler/gcc_configuration.py [new file with mode: 0644]
build_common/linux/SConscript
build_common/tizen/SConscript [new file with mode: 0644]
build_common/tools/UnpackAll.py [new file with mode: 0644]
examples/OICMiddle/Client.cpp
examples/OICMiddle/LineInput.cpp
examples/OICMiddle/SConscript [new file with mode: 0644]
examples/OICMiddle/Server.cpp
examples/OICMiddle/makefile [deleted file]
examples/OICSensorBoard/SConstruct
extlibs/android/gradle/SConscript [new file with mode: 0644]
extlibs/android/ndk/SConscript [new file with mode: 0644]
extlibs/android/sdk/SConscript [new file with mode: 0644]
extlibs/arduino/SConscript [new file with mode: 0644]
extlibs/boost/SConscript [new file with mode: 0644]
extlibs/cereal/SConscript [new file with mode: 0644]
extlibs/expat/SConscript [new file with mode: 0644]
extlibs/gtest/SConscript [new file with mode: 0644]
extlibs/hippomocks.scons [new file with mode: 0644]
extlibs/rapidxml/rapidxml.hpp [new file with mode: 0644]
extlibs/rapidxml/rapidxml_iterators.hpp [new file with mode: 0644]
extlibs/rapidxml/rapidxml_print.hpp [new file with mode: 0644]
extlibs/rapidxml/rapidxml_utils.hpp [new file with mode: 0644]
extlibs/timer/timer.c [new file with mode: 0644]
extlibs/timer/timer.h [new file with mode: 0644]
extlibs/tinydtls/0001-Added-support-in-tinyDTLS-to-support-rehandshake.patch [new file with mode: 0644]
extlibs/tinydtls/0001-Adding-autoconf-generated-files-in-tinydtls-repo.patch [new file with mode: 0644]
extlibs/tinydtls/0001-Bug-Fix-in-earlier-rehandhsake-implementation.patch [new file with mode: 0644]
extlibs/tinydtls/0001-Fixed-issue-to-pass-PSK-identity-hint-to-application.patch [new file with mode: 0644]
extlibs/tinydtls/0001-Updated-tinyDTLS-test-apps-to-use-identity-hint.patch [new file with mode: 0644]
extlibs/tinydtls/Android.mk [new file with mode: 0644]
extlibs/tinydtls/LICENSE [new file with mode: 0644]
extlibs/tinydtls/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/Makefile.tinydtls [new file with mode: 0644]
extlibs/tinydtls/README [new file with mode: 0644]
extlibs/tinydtls/SConscript [new file with mode: 0644]
extlibs/tinydtls/aes/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/aes/rijndael.c [new file with mode: 0644]
extlibs/tinydtls/aes/rijndael.h [new file with mode: 0644]
extlibs/tinydtls/alert.h [new file with mode: 0644]
extlibs/tinydtls/ccm.c [new file with mode: 0644]
extlibs/tinydtls/ccm.h [new file with mode: 0644]
extlibs/tinydtls/configure.in [new file with mode: 0644]
extlibs/tinydtls/crypto.c [new file with mode: 0644]
extlibs/tinydtls/crypto.h [new file with mode: 0644]
extlibs/tinydtls/debug.c [new file with mode: 0644]
extlibs/tinydtls/debug.h [new file with mode: 0644]
extlibs/tinydtls/doc/Doxyfile.in [new file with mode: 0644]
extlibs/tinydtls/doc/DoxygenLayout.xml [new file with mode: 0644]
extlibs/tinydtls/doc/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/dtls.c [new file with mode: 0644]
extlibs/tinydtls/dtls.h [new file with mode: 0644]
extlibs/tinydtls/dtls_config.h [new file with mode: 0644]
extlibs/tinydtls/dtls_config.h.in [new file with mode: 0644]
extlibs/tinydtls/dtls_time.c [new file with mode: 0644]
extlibs/tinydtls/dtls_time.h [new file with mode: 0644]
extlibs/tinydtls/ecc/LICENSE.txt [new file with mode: 0644]
extlibs/tinydtls/ecc/Makefile.contiki [new file with mode: 0644]
extlibs/tinydtls/ecc/Makefile.ecc [new file with mode: 0644]
extlibs/tinydtls/ecc/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/ecc/README.md [new file with mode: 0644]
extlibs/tinydtls/ecc/asm_arm.inc [new file with mode: 0755]
extlibs/tinydtls/ecc/asm_avr.inc [new file with mode: 0755]
extlibs/tinydtls/ecc/ecc.c [new file with mode: 0644]
extlibs/tinydtls/ecc/ecc.h [new file with mode: 0644]
extlibs/tinydtls/ecc/test/ecc_test/ecc_test.ino [new file with mode: 0755]
extlibs/tinydtls/ecc/test/emk_rules.py [new file with mode: 0755]
extlibs/tinydtls/ecc/test/test_ecdh.c [new file with mode: 0644]
extlibs/tinydtls/ecc/test/test_ecdsa.c [new file with mode: 0644]
extlibs/tinydtls/ecc/test_helper.c [new file with mode: 0644]
extlibs/tinydtls/ecc/test_helper.h [new file with mode: 0644]
extlibs/tinydtls/ecc/testecc.c [new file with mode: 0644]
extlibs/tinydtls/ecc/testfield.c [new file with mode: 0644]
extlibs/tinydtls/examples/contiki/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/examples/contiki/dtls-client.c [new file with mode: 0644]
extlibs/tinydtls/examples/contiki/dtls-server.c [new file with mode: 0644]
extlibs/tinydtls/global.h [new file with mode: 0644]
extlibs/tinydtls/hmac.c [new file with mode: 0644]
extlibs/tinydtls/hmac.h [new file with mode: 0644]
extlibs/tinydtls/netq.c [new file with mode: 0644]
extlibs/tinydtls/netq.h [new file with mode: 0644]
extlibs/tinydtls/numeric.h [new file with mode: 0644]
extlibs/tinydtls/peer.c [new file with mode: 0644]
extlibs/tinydtls/peer.h [new file with mode: 0644]
extlibs/tinydtls/platform-specific/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/platform-specific/config-cc2538dk.h [new file with mode: 0644]
extlibs/tinydtls/platform-specific/config-econotag.h [new file with mode: 0644]
extlibs/tinydtls/platform-specific/config-minimal-net.h [new file with mode: 0644]
extlibs/tinydtls/platform-specific/config-sky.h [new file with mode: 0644]
extlibs/tinydtls/platform-specific/config-wismote.h [new file with mode: 0644]
extlibs/tinydtls/prng.h [new file with mode: 0644]
extlibs/tinydtls/session.c [new file with mode: 0644]
extlibs/tinydtls/session.h [new file with mode: 0644]
extlibs/tinydtls/sha2/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/sha2/README [new file with mode: 0644]
extlibs/tinydtls/sha2/sha2.c [new file with mode: 0644]
extlibs/tinydtls/sha2/sha2.h [new file with mode: 0644]
extlibs/tinydtls/sha2/sha2prog.c [new file with mode: 0644]
extlibs/tinydtls/sha2/sha2speed.c [new file with mode: 0644]
extlibs/tinydtls/sha2/sha2test.pl [new file with mode: 0755]
extlibs/tinydtls/sha2/testvectors/vector001.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector001.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector002.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector002.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector003.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector003.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector004.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector004.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector005.dat [moved from service/soft-sensor-manager/build/tizen/Makefile with 100% similarity]
extlibs/tinydtls/sha2/testvectors/vector005.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector006.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector006.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector007.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector007.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector008.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector008.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector009.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector009.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector010.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector010.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector011.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector011.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector012.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector012.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector013.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector013.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector014.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector014.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector015.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector015.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector016.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector016.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector017.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector017.info [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector018.dat [new file with mode: 0644]
extlibs/tinydtls/sha2/testvectors/vector018.info [new file with mode: 0644]
extlibs/tinydtls/state.h [new file with mode: 0644]
extlibs/tinydtls/t_list.h [new file with mode: 0644]
extlibs/tinydtls/tests/Makefile.in [new file with mode: 0644]
extlibs/tinydtls/tests/cbc_aes128-test.c [new file with mode: 0644]
extlibs/tinydtls/tests/cbc_aes128-testdata.c [new file with mode: 0644]
extlibs/tinydtls/tests/ccm-test.c [new file with mode: 0644]
extlibs/tinydtls/tests/ccm-testdata.c [new file with mode: 0644]
extlibs/tinydtls/tests/dsrv-test.c [new file with mode: 0644]
extlibs/tinydtls/tests/dtls-client.c [new file with mode: 0644]
extlibs/tinydtls/tests/dtls-server.c [new file with mode: 0644]
extlibs/tinydtls/tests/netq-test.c [new file with mode: 0644]
extlibs/tinydtls/tests/pcap.c [new file with mode: 0644]
extlibs/tinydtls/tests/prf-test.c [new file with mode: 0644]
extlibs/tinydtls/tests/secure-server.c [new file with mode: 0644]
extlibs/tinydtls/tinydtls.h [new file with mode: 0644]
extlibs/tinydtls/tinydtls.h.in [new file with mode: 0644]
extlibs/tinydtls/uthash.h [new file with mode: 0644]
extlibs/tinydtls/utlist.h [new file with mode: 0644]
extra_options.scons
gbsbuild.sh [new file with mode: 0644]
resource/README.setup.txt [deleted file]
resource/SConscript
resource/android/OCAndroid.cpp
resource/android/SConscript
resource/artifact_output_locations.txt
resource/buildScript.mk [deleted file]
resource/csdk/README [deleted file]
resource/csdk/SConscript
resource/csdk/arduinomega.properties
resource/csdk/connectivity/RELEASE v0.1 [deleted file]
resource/csdk/connectivity/RELEASE v0.7 [new file with mode: 0644]
resource/csdk/connectivity/SConscript [new file with mode: 0644]
resource/csdk/connectivity/SConstruct [new file with mode: 0644]
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/api/cainterface.h
resource/csdk/connectivity/build/How_To_Build.txt [new file with mode: 0644]
resource/csdk/connectivity/build/SConscript [new file with mode: 0644]
resource/csdk/connectivity/build/android/Makefile [new file with mode: 0644]
resource/csdk/connectivity/build/android/README.txt [new file with mode: 0644]
resource/csdk/connectivity/build/android/SConscript [new file with mode: 0644]
resource/csdk/connectivity/build/android/jni/Android.mk [new file with mode: 0644]
resource/csdk/connectivity/build/android/jni/Application.mk [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/Arduino_Setup_README.txt [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/Makefile [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/README.txt [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/SConscript [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/arduino.scons [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/arduinomega.properties [new file with mode: 0755]
resource/csdk/connectivity/build/arduino/build.sh [new file with mode: 0755]
resource/csdk/connectivity/build/arduino/local.properties [new file with mode: 0755]
resource/csdk/connectivity/build/common.mk [new file with mode: 0644]
resource/csdk/connectivity/build/linux/Makefile [deleted file]
resource/csdk/connectivity/build/linux/SConscript [new file with mode: 0644]
resource/csdk/connectivity/build/linux/common.mk [deleted file]
resource/csdk/connectivity/build/tizen/Makefile [new file with mode: 0644]
resource/csdk/connectivity/build/tizen/SConscript [new file with mode: 0644]
resource/csdk/connectivity/build/tizen/SConstruct [new file with mode: 0644]
resource/csdk/connectivity/build/tizen/com.oic.ca.manifest [new file with mode: 0644]
resource/csdk/connectivity/build/tizen/com.oic.ca.pc [new file with mode: 0644]
resource/csdk/connectivity/build/tizen/gbsbuild.sh [new file with mode: 0755]
resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec [new file with mode: 0644]
resource/csdk/connectivity/build/tizen/scons/SConscript [new file with mode: 0644]
resource/csdk/connectivity/common/SConscript [new file with mode: 0644]
resource/csdk/connectivity/common/inc/camutex.h [new file with mode: 0644]
resource/csdk/connectivity/common/inc/cathreadpool.h [new file with mode: 0644]
resource/csdk/connectivity/common/inc/logger.h
resource/csdk/connectivity/common/inc/oic_console_logger.h
resource/csdk/connectivity/common/inc/oic_logger.h
resource/csdk/connectivity/common/inc/oic_logger_types.h
resource/csdk/connectivity/common/inc/oic_malloc.h
resource/csdk/connectivity/common/inc/oic_string.h [new file with mode: 0644]
resource/csdk/connectivity/common/inc/uarraylist.h
resource/csdk/connectivity/common/inc/umutex.h [deleted file]
resource/csdk/connectivity/common/inc/uqueue.h
resource/csdk/connectivity/common/inc/uthreadpool.h [deleted file]
resource/csdk/connectivity/common/src/camutex_pthreads.c [new file with mode: 0644]
resource/csdk/connectivity/common/src/cathreadpool_pthreads.c [new file with mode: 0644]
resource/csdk/connectivity/common/src/logger.c
resource/csdk/connectivity/common/src/oic_console_logger.c
resource/csdk/connectivity/common/src/oic_logger.c
resource/csdk/connectivity/common/src/oic_malloc.c
resource/csdk/connectivity/common/src/oic_string.c [new file with mode: 0644]
resource/csdk/connectivity/common/src/uarraylist.c
resource/csdk/connectivity/common/src/umutex.c [deleted file]
resource/csdk/connectivity/common/src/uqueue.c
resource/csdk/connectivity/common/src/uthreadpool.c [deleted file]
resource/csdk/connectivity/external/inc/ocsecurityconfig.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caadapterinterface.h
resource/csdk/connectivity/inc/caadapternetdtls.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caadapterutils.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caedradapter.h
resource/csdk/connectivity/inc/caedradapter_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caedrinterface.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caerrorcode.h [deleted file]
resource/csdk/connectivity/inc/caethernetadapter.h [deleted file]
resource/csdk/connectivity/inc/cainterfacecontroller.h
resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caipadapter.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caipadapter_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caipinterface.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caipinterface_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caleadapter.h
resource/csdk/connectivity/inc/caleadapter_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caleinterface.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caleinterface_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/camessagehandler.h
resource/csdk/connectivity/inc/camessagehandler_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/camsgparser.h [new file with mode: 0644]
resource/csdk/connectivity/inc/canetworkconfigurator.h
resource/csdk/connectivity/inc/caprotocolmessage.h
resource/csdk/connectivity/inc/caqueueingthread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caremotehandler.h
resource/csdk/connectivity/inc/caretransmission.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caretransmission_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/cawifiadapter.h [deleted file]
resource/csdk/connectivity/inc/cawificore.h [deleted file]
resource/csdk/connectivity/inc/cawifiethernetadapter.h [deleted file]
resource/csdk/connectivity/lib/android/jni/Android.mk [new file with mode: 0644]
resource/csdk/connectivity/lib/android/jni/Application.mk [new file with mode: 0644]
resource/csdk/connectivity/lib/arduino/RBL_nRF8001.patch [new file with mode: 0644]
resource/csdk/connectivity/lib/arduino/arduino_due_ble.patch [new file with mode: 0644]
resource/csdk/connectivity/lib/arduino/arduino_libraries.patch [new file with mode: 0644]
resource/csdk/connectivity/lib/arduino/arduinomega.properties [new file with mode: 0644]
resource/csdk/connectivity/lib/arduino/local.properties [new file with mode: 0644]
resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile [deleted file]
resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript [new file with mode: 0644]
resource/csdk/connectivity/lib/libcoap-4.1.1/address.h
resource/csdk/connectivity/lib/libcoap-4.1.1/async.h
resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h
resource/csdk/connectivity/lib/libcoap-4.1.1/block.c
resource/csdk/connectivity/lib/libcoap-4.1.1/block.h
resource/csdk/connectivity/lib/libcoap-4.1.1/coap.h
resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.c
resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.h
resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h
resource/csdk/connectivity/lib/libcoap-4.1.1/config.h
resource/csdk/connectivity/lib/libcoap-4.1.1/config.status [deleted file]
resource/csdk/connectivity/lib/libcoap-4.1.1/configure [deleted file]
resource/csdk/connectivity/lib/libcoap-4.1.1/configure.in
resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c
resource/csdk/connectivity/lib/libcoap-4.1.1/debug.h
resource/csdk/connectivity/lib/libcoap-4.1.1/encode.c
resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h
resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile [deleted file]
resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile.in
resource/csdk/connectivity/lib/libcoap-4.1.1/examples/client.c
resource/csdk/connectivity/lib/libcoap-4.1.1/examples/etsi_iot_01.c
resource/csdk/connectivity/lib/libcoap-4.1.1/examples/rd.c
resource/csdk/connectivity/lib/libcoap-4.1.1/examples/server.c
resource/csdk/connectivity/lib/libcoap-4.1.1/examples/tiny.c
resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.c
resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.h
resource/csdk/connectivity/lib/libcoap-4.1.1/makefile_arduino.mak [new file with mode: 0644]
resource/csdk/connectivity/lib/libcoap-4.1.1/mem.h
resource/csdk/connectivity/lib/libcoap-4.1.1/net.c
resource/csdk/connectivity/lib/libcoap-4.1.1/net.h
resource/csdk/connectivity/lib/libcoap-4.1.1/option.c
resource/csdk/connectivity/lib/libcoap-4.1.1/option.h
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h
resource/csdk/connectivity/lib/libcoap-4.1.1/prng.h
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.h
resource/csdk/connectivity/lib/libcoap-4.1.1/str.c
resource/csdk/connectivity/lib/libcoap-4.1.1/str.h
resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.c
resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.h
resource/csdk/connectivity/lib/libcoap-4.1.1/t_list.h
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile [deleted file]
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile.in
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.c
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.h
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.c
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.h
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.h
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.c
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.h
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.c
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.h
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.c
resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.h
resource/csdk/connectivity/lib/libcoap-4.1.1/uri.c
resource/csdk/connectivity/lib/libcoap-4.1.1/uri.h
resource/csdk/connectivity/lib/libcoap-4.1.1/uthash.h
resource/csdk/connectivity/lib/libcoap-4.1.1/utlist.h
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth.h [new file with mode: 0644]
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_private.h [new file with mode: 0644]
resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_type.h [new file with mode: 0644]
resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_product.h [new file with mode: 0644]
resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_type_product.h [new file with mode: 0644]
resource/csdk/connectivity/samples/android/SConscript [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/AndroidManifest.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/jni/Android.mk [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/jni/Application.mk [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/jni/org_iotivity_service_RMInterface.h [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/proguard-project.txt [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/project.properties [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/layout/activity_main.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/menu/main.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/values-v11/styles.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/values-v14/styles.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/values-w820dp/dimens.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/values/dimens.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/values/strings.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/res/values/styles.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/ca/CaIpInterface.java [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/CALeInterface.java [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/caipinterface.java [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/DLog.java [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/MainActivity.java [new file with mode: 0644]
resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/RMInterface.java [new file with mode: 0644]
resource/csdk/connectivity/samples/arduino/SConscript [new file with mode: 0644]
resource/csdk/connectivity/samples/arduino/casample.cpp [new file with mode: 0644]
resource/csdk/connectivity/samples/linux/.gitignore [deleted file]
resource/csdk/connectivity/samples/linux/Makefile [deleted file]
resource/csdk/connectivity/samples/linux/README
resource/csdk/connectivity/samples/linux/SConscript [new file with mode: 0644]
resource/csdk/connectivity/samples/linux/sample.sh [changed mode: 0644->0755]
resource/csdk/connectivity/samples/linux/sample_main.c
resource/csdk/connectivity/samples/linux/threadpool/Makefile [deleted file]
resource/csdk/connectivity/samples/linux/threadpool/main.c
resource/csdk/connectivity/samples/tizen/README.txt [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/SConscript [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/SConstruct [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/casample.c [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.manifest [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.xml [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/gbsbuild.sh [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/packaging/com.oic.ca.sample.spec [new file with mode: 0644]
resource/csdk/connectivity/samples/tizen/scons/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c [new file with mode: 0644]
resource/csdk/connectivity/src/adapter_util/caadapterutils.c [new file with mode: 0644]
resource/csdk/connectivity/src/adapter_util/camsgparser.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/android/org_iotivity_jar_caedrinterface.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrclient.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrdevicelist.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrdevicelist.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrserver.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_jar_caleclientinterface.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_jar_caleserverinterface.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/caleadapter_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/linux/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cablenwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c [new file with mode: 0644]
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.h [new file with mode: 0644]
resource/csdk/connectivity/src/caconnectivitymanager.c
resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/cainterfacecontroller.c
resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/camessagehandler_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/canetworkconfigurator.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/caqueueingthread.c [new file with mode: 0644]
resource/csdk/connectivity/src/caremotehandler.c
resource/csdk/connectivity/src/caretransmission.c [new file with mode: 0644]
resource/csdk/connectivity/src/caretransmission_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetadapter.c [deleted file]
resource/csdk/connectivity/src/ip_adapter/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/android/org_iotivity_ca_CaIpInterface.h [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.h [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_eth.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_wifi.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/caipadapter.c [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/caipadapter_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/caipclient.c [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/caipserver.c [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/wifi_adapter/cawifiethernetadapter.c [deleted file]
resource/csdk/connectivity/src/wifi_adapter/linux/cawifiadapter.c [deleted file]
resource/csdk/connectivity/src/wifi_adapter/linux/cawificore.c [deleted file]
resource/csdk/connectivity/test/SConscript [new file with mode: 0644]
resource/csdk/connectivity/test/ca_api_unittest.cpp [new file with mode: 0644]
resource/csdk/connectivity/test/camutex_tests.cpp [new file with mode: 0644]
resource/csdk/connectivity/test/caprotocolmessagetest.cpp [new file with mode: 0644]
resource/csdk/connectivity/test/catests.cpp [new file with mode: 0644]
resource/csdk/connectivity/unittests/linux/sample1_unittest.cc [deleted file]
resource/csdk/doc/Doxyfile [new file with mode: 0644]
resource/csdk/libcoap [deleted symlink]
resource/csdk/libcoap-4.1.1/ChangeLog [deleted file]
resource/csdk/libcoap-4.1.1/LICENSE.BSD [deleted file]
resource/csdk/libcoap-4.1.1/LICENSE.GPL [deleted file]
resource/csdk/libcoap-4.1.1/Makefile.in [deleted file]
resource/csdk/libcoap-4.1.1/README [deleted file]
resource/csdk/libcoap-4.1.1/SConscript [deleted file]
resource/csdk/libcoap-4.1.1/address.h [deleted file]
resource/csdk/libcoap-4.1.1/async.c [deleted file]
resource/csdk/libcoap-4.1.1/async.h [deleted file]
resource/csdk/libcoap-4.1.1/bits.h [deleted file]
resource/csdk/libcoap-4.1.1/block.c [deleted file]
resource/csdk/libcoap-4.1.1/block.h [deleted file]
resource/csdk/libcoap-4.1.1/coap.h [deleted file]
resource/csdk/libcoap-4.1.1/coap_list.c [deleted file]
resource/csdk/libcoap-4.1.1/coap_list.h [deleted file]
resource/csdk/libcoap-4.1.1/coap_time.h [deleted file]
resource/csdk/libcoap-4.1.1/config.h [deleted file]
resource/csdk/libcoap-4.1.1/config.h.in [deleted file]
resource/csdk/libcoap-4.1.1/configure [deleted file]
resource/csdk/libcoap-4.1.1/configure.in [deleted file]
resource/csdk/libcoap-4.1.1/debug.c [deleted file]
resource/csdk/libcoap-4.1.1/debug.h [deleted file]
resource/csdk/libcoap-4.1.1/doc/Doxyfile [deleted file]
resource/csdk/libcoap-4.1.1/doc/Doxyfile.in [deleted file]
resource/csdk/libcoap-4.1.1/doc/Makefile.in [deleted file]
resource/csdk/libcoap-4.1.1/doc/makefile [deleted file]
resource/csdk/libcoap-4.1.1/encode.c [deleted file]
resource/csdk/libcoap-4.1.1/encode.h [deleted file]
resource/csdk/libcoap-4.1.1/examples/client.c [deleted file]
resource/csdk/libcoap-4.1.1/examples/makefile [deleted file]
resource/csdk/libcoap-4.1.1/examples/rd.c [deleted file]
resource/csdk/libcoap-4.1.1/examples/server.c [deleted file]
resource/csdk/libcoap-4.1.1/examples/tiny.c [deleted file]
resource/csdk/libcoap-4.1.1/hashkey.c [deleted file]
resource/csdk/libcoap-4.1.1/hashkey.h [deleted file]
resource/csdk/libcoap-4.1.1/makefile [deleted file]
resource/csdk/libcoap-4.1.1/mem.h [deleted file]
resource/csdk/libcoap-4.1.1/net.c [deleted file]
resource/csdk/libcoap-4.1.1/net.h [deleted file]
resource/csdk/libcoap-4.1.1/option.c [deleted file]
resource/csdk/libcoap-4.1.1/option.h [deleted file]
resource/csdk/libcoap-4.1.1/pdu.c [deleted file]
resource/csdk/libcoap-4.1.1/pdu.h [deleted file]
resource/csdk/libcoap-4.1.1/prng.h [deleted file]
resource/csdk/libcoap-4.1.1/resource.c [deleted file]
resource/csdk/libcoap-4.1.1/resource.h [deleted file]
resource/csdk/libcoap-4.1.1/sec/netdtls.c [deleted file]
resource/csdk/libcoap-4.1.1/sec/netdtls.h [deleted file]
resource/csdk/libcoap-4.1.1/str.c [deleted file]
resource/csdk/libcoap-4.1.1/str.h [deleted file]
resource/csdk/libcoap-4.1.1/subscribe.c [deleted file]
resource/csdk/libcoap-4.1.1/subscribe.h [deleted file]
resource/csdk/libcoap-4.1.1/t_list.h [deleted file]
resource/csdk/libcoap-4.1.1/uri.c [deleted file]
resource/csdk/libcoap-4.1.1/uri.h [deleted file]
resource/csdk/libcoap-4.1.1/uthash.h [deleted file]
resource/csdk/libcoap-4.1.1/utlist.h [deleted file]
resource/csdk/logger/makefile [deleted file]
resource/csdk/logger/src/logger.c
resource/csdk/makefile [deleted file]
resource/csdk/occoap/README.txt [deleted file]
resource/csdk/occoap/include/occoap.h [deleted file]
resource/csdk/occoap/include/occoaphelper.h [deleted file]
resource/csdk/occoap/include/occoaptoken.h [deleted file]
resource/csdk/occoap/makefile [deleted file]
resource/csdk/occoap/src/occoap.c [deleted file]
resource/csdk/occoap/src/occoaphelper.c [deleted file]
resource/csdk/occoap/test/occoaptests.cpp [deleted file]
resource/csdk/ocmalloc/test/linux/makefile [deleted file]
resource/csdk/ocrandom/include/ocrandom.h
resource/csdk/ocrandom/src/ocrandom.c
resource/csdk/ocrandom/test/SConscript [new file with mode: 0644]
resource/csdk/ocrandom/test/android/makefile [deleted file]
resource/csdk/ocrandom/test/android/randomtest.cpp
resource/csdk/ocrandom/test/arduino/makefile [deleted file]
resource/csdk/ocrandom/test/linux/makefile [deleted file]
resource/csdk/ocrandom/test/linux/randomtest.cpp
resource/csdk/ocsocket/README.txt [deleted file]
resource/csdk/ocsocket/include/ocsocket.h [deleted file]
resource/csdk/ocsocket/src/ocsocket.c [deleted file]
resource/csdk/ocsocket/src/ocsocket_arduino.cpp [deleted file]
resource/csdk/ocsocket/src/ocsocket_arduino_wifi.cpp [deleted file]
resource/csdk/ocsocket/test/android/makefile [deleted file]
resource/csdk/ocsocket/test/android/ocsocket_gtest.cpp [deleted file]
resource/csdk/ocsocket/test/arduino/makefile [deleted file]
resource/csdk/ocsocket/test/arduino/ocsocket_test.cpp [deleted file]
resource/csdk/ocsocket/test/arduino/ocsocket_wifi_test.cpp [deleted file]
resource/csdk/ocsocket/test/linux/makefile [deleted file]
resource/csdk/ocsocket/test/linux/ocsocket_gtest.cpp [deleted file]
resource/csdk/ocsocket/test/makefile [deleted file]
resource/csdk/ocsocket/test/sendrecv.cpp [deleted file]
resource/csdk/ocsocket/test/sendrecv_README.txt [deleted file]
resource/csdk/security/include/internal/ocsecurityinternal.h [new file with mode: 0644]
resource/csdk/security/include/ocsecurity.h [new file with mode: 0644]
resource/csdk/security/include/ocsecurityconfig.h [new file with mode: 0644]
resource/csdk/security/src/ocsecurity.c [new file with mode: 0644]
resource/csdk/stack/include/internal/occlientcb.h
resource/csdk/stack/include/internal/ocobserve.h
resource/csdk/stack/include/internal/ocresource.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/internal/oicgroup.h
resource/csdk/stack/include/ocsecurity.h [deleted file]
resource/csdk/stack/include/ocsecurityconfig.h [deleted file]
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/include/ocstackconfig.h
resource/csdk/stack/include/octypes.h [new file with mode: 0644]
resource/csdk/stack/samples/arduino/SimpleClientServer/makefile [deleted file]
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile [deleted file]
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/SConscript [new file with mode: 0644]
resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/makefile [deleted file]
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 [new file with mode: 0644]
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 [deleted file]
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/ocsecurity.c [deleted file]
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 [new file with mode: 0644]
resource/csdk/stack/test/android/README
resource/csdk/stack/test/arduino/README
resource/csdk/stack/test/arduino/makefile [deleted file]
resource/csdk/stack/test/arduino/ocserver.cpp
resource/csdk/stack/test/gtest_helper.h [new file with mode: 0644]
resource/csdk/stack/test/linux/makefile [deleted file]
resource/csdk/stack/test/linux/occlient.c
resource/csdk/stack/test/linux/ocserver.c
resource/csdk/stack/test/makefile [deleted file]
resource/csdk/stack/test/stacktests.cpp
resource/docs/Doxyfile
resource/docs/devdocs.doxyfile [new file with mode: 0644]
resource/docs/devdox/ca_functional.dox [new file with mode: 0644]
resource/docs/devdox/ca_overview.dox [new file with mode: 0644]
resource/docs/devdox/dot/ca_arch.gv [new file with mode: 0644]
resource/docs/devdox/dot/ca_arch_sketch.gv [new file with mode: 0644]
resource/docs/devdox/dot/ca_overview.gv [new file with mode: 0644]
resource/docs/devdox/mainpage.dox [new file with mode: 0644]
resource/docs/doxygenLayout.xml
resource/docs/guides/AboutOIC.txt [deleted file]
resource/docs/guides/Home.txt
resource/docs/guides/HowToGuidesIndex.txt [deleted file]
resource/docs/guides/ProgrammersGuide.txt [deleted file]
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 [changed mode: 0755->0644]
resource/examples/groupserver.cpp [changed mode: 0755->0644]
resource/examples/lightserver.cpp [changed mode: 0755->0644]
resource/examples/makefile [deleted file]
resource/examples/ocicuc/.gitignore [deleted file]
resource/examples/ocicuc/Makefile [deleted file]
resource/examples/ocicuc/README [deleted file]
resource/examples/ocicuc/SConscript [deleted file]
resource/examples/ocicuc/client.cpp [deleted file]
resource/examples/ocicuc/demo_client.hpp [deleted file]
resource/examples/ocicuc/driver.cpp [deleted file]
resource/examples/ocicuc/exec.hpp [deleted file]
resource/examples/ocicuc/light_resource.cpp [deleted file]
resource/examples/ocicuc/light_resource.hpp [deleted file]
resource/examples/ocicuc/monoprocess.cpp [deleted file]
resource/examples/ocicuc/server.cpp [deleted file]
resource/examples/ocicuc/small_example.cpp [deleted file]
resource/examples/ocicuc/utility.cpp [deleted file]
resource/examples/ocicuc/utility.hpp [deleted file]
resource/examples/old_tests/MyMultiResourceHandler.cpp [deleted file]
resource/examples/old_tests/MyMultiResourceHandler.h [deleted file]
resource/examples/old_tests/MyObserverHandler.cpp [deleted file]
resource/examples/old_tests/MyObserverHandler.h [deleted file]
resource/examples/old_tests/MyResourceHandler.cpp [deleted file]
resource/examples/old_tests/MyResourceHandler.h [deleted file]
resource/examples/old_tests/OCWrapper/makefile [deleted file]
resource/examples/old_tests/OCWrapper/parsetest.cpp [deleted file]
resource/examples/old_tests/OCWrapper/testClient.cpp [deleted file]
resource/examples/old_tests/OCWrapper/testServer.cpp [deleted file]
resource/examples/old_tests/OCWrapper/testServerApp.cpp [deleted file]
resource/examples/old_tests/multiple_resources.cpp [deleted file]
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/AttributeValue.h
resource/include/IClientWrapper.h
resource/include/IServerWrapper.h
resource/include/InProcClientWrapper.h
resource/include/InProcServerWrapper.h
resource/include/InitializeException.h
resource/include/OCAndroid.h
resource/include/OCApi.h
resource/include/OCException.h
resource/include/OCHeaderOption.h
resource/include/OCPlatform.h
resource/include/OCPlatform_impl.h
resource/include/OCRepresentation.h
resource/include/OCResource.h
resource/include/OCResourceRequest.h
resource/include/OCResourceResponse.h
resource/include/OCSecurityModel.h [deleted file]
resource/include/OCSerialization.h
resource/include/OCUtilities.h
resource/include/OicJsonSerializer.hpp
resource/include/OutOfProcClientWrapper.h
resource/include/OutOfProcServerWrapper.h
resource/include/StringConstants.h
resource/makefile [deleted file]
resource/oc_logger/Makefile [deleted file]
resource/oc_logger/SConscript
resource/oc_logger/c/Makefile [deleted file]
resource/oc_logger/c/oc_logger.c
resource/oc_logger/cpp/Makefile [deleted file]
resource/oc_logger/examples/Makefile [deleted file]
resource/oc_logger/examples/SConscript
resource/oc_logger/include/oc_logger_types.h
resource/oc_logger/samples/linux/makefile [deleted file]
resource/patches/user-config-arm-linux-androideabi.jam [new file with mode: 0644]
resource/patches/user-config-x86.jam [new file with mode: 0644]
resource/releaseNotes/Feb1st2015.txt [new file with mode: 0644]
resource/releaseNotes/Jan17th2015.txt [new file with mode: 0644]
resource/src/InProcClientWrapper.cpp
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/OCResourceRequest.cpp [new file with mode: 0644]
resource/src/OCSecurityModel.cpp [deleted file]
resource/src/OCUtilities.cpp
resource/src/SConscript
resource/third_party_libs.scons
resource/unit_tests.scons [new file with mode: 0644]
resource/unittests/ConstructResourceTest.cpp [new file with mode: 0644]
resource/unittests/OCExceptionTest.cpp [new file with mode: 0644]
resource/unittests/OCHeaderOptionTest.cpp [new file with mode: 0644]
resource/unittests/OCPlatformTest.cpp [new file with mode: 0644]
resource/unittests/OCRepresentationTest.cpp [new file with mode: 0644]
resource/unittests/OCResourceResponseTest.cpp [new file with mode: 0644]
resource/unittests/OCResourceTest.cpp [new file with mode: 0644]
resource/unittests/README
resource/unittests/SConscript [new file with mode: 0644]
resource/unittests/makefile [deleted file]
resource/unittests/tests.cpp [deleted file]
scons_script_how_to.txt
service/SConscript
service/docs/Control Manager-Programmer's guide_v0.9.0.pdf [deleted file]
service/docs/NM Programmer_s Guide v0.9.1 for Android.pdf [new file with mode: 0644]
service/docs/NM Programmer_s Guide v0.9.1 for Linux.pdf [new file with mode: 0644]
service/docs/PPM - Programmer's Guide_v0.9.0.pdf [deleted file]
service/docs/PPM Programmer_s Guide v0.9.1 for Android.pdf [new file with mode: 0644]
service/docs/PPM Programmer_s Guide v0.9.1 for Linux.pdf [new file with mode: 0644]
service/docs/PPM Programmer_s Guide v0.9.1 for Tizen.pdf [new file with mode: 0644]
service/docs/SSM - Programmer's guide_v0.9.0.pdf [deleted file]
service/docs/SSM Programmer_s Guide v0.9.1 for Android.pdf [new file with mode: 0644]
service/docs/SSM Programmer_s Guide v0.9.1 for Linux.pdf [new file with mode: 0644]
service/docs/TM Programmer_s Guide v0.9.1 for Android.pdf [new file with mode: 0644]
service/docs/TM Programmer_s Guide v0.9.1 for Linux.pdf [new file with mode: 0644]
service/docs/Things Manager - Programmer's guide_v0.9.0.pdf [deleted file]
service/notification-manager/.gitignore
service/notification-manager/NotificationManager/build/linux/Makefile [deleted file]
service/notification-manager/NotificationManager/include/HostingConfig.h [deleted file]
service/notification-manager/NotificationManager/include/HostingHandler.h [deleted file]
service/notification-manager/NotificationManager/include/HostingInterface.h [deleted file]
service/notification-manager/NotificationManager/include/NotificationManager.h [deleted file]
service/notification-manager/NotificationManager/include/OICPlatformConfig.h [deleted file]
service/notification-manager/NotificationManager/include/RegistrationManager.h [deleted file]
service/notification-manager/NotificationManager/include/ResourceManager.h [deleted file]
service/notification-manager/NotificationManager/include/VirtualRepresentation.h [deleted file]
service/notification-manager/NotificationManager/include/hosting.h [new file with mode: 0644]
service/notification-manager/NotificationManager/src/HostingHandler.cpp [deleted file]
service/notification-manager/NotificationManager/src/HostingInterface.cpp [deleted file]
service/notification-manager/NotificationManager/src/NotificationManager.cpp [deleted file]
service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp [deleted file]
service/notification-manager/NotificationManager/src/RegistrationManager.cpp [deleted file]
service/notification-manager/NotificationManager/src/ResourceManager.cpp [deleted file]
service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp [deleted file]
service/notification-manager/NotificationManager/src/hosting.c [new file with mode: 0644]
service/notification-manager/NotificationManager/src/linux/main.cpp [deleted file]
service/notification-manager/NotificationManager/src/requestHandler.c [new file with mode: 0644]
service/notification-manager/NotificationManager/src/resourceCoordinator_JNI.cpp [new file with mode: 0644]
service/notification-manager/NotificationManager/src/resourceCoordinator_JNI.h [new file with mode: 0644]
service/notification-manager/NotificationManager/src/virtualResource.c [new file with mode: 0644]
service/notification-manager/NotificationManager/src/virtualResource.h [new file with mode: 0644]
service/notification-manager/SConscript
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/.classpath [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/.project [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/AndroidManifest.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/ic_launcher-web.png [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/Android.mk [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/Application.mk [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/armeabi [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/project.properties [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/layout/activity_main.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values-v11/styles.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values-v14/styles.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values/strings.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values/styles.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/ResourceHostingSampleApp/src/com/example/resourcehostingsampleapp/ResourceHosting.java [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleConsumer/.classpath [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleConsumer/.project [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleConsumer/AndroidManifest.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleConsumer/project.properties [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleConsumer/res/layout/sampleconsumer_layout.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleConsumer/res/values/strings.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleConsumer/src/com/example/sample/consumer/SampleConsumer.java [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/.classpath [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/.project [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/AndroidManifest.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/jni/Android.mk [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/jni/Application.mk [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/project.properties [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/res/layout/sampleprovider_layout.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/res/values/strings.xml [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/IMessageLogger.java [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/SampleProvider.java [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/StringConstants.java [new file with mode: 0644]
service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/TemperatureResource.java [new file with mode: 0644]
service/notification-manager/SampleApp/arduino/SConscript [deleted file]
service/notification-manager/SampleApp/arduino/Time/DateStrings.cpp [deleted file]
service/notification-manager/SampleApp/arduino/Time/Readme.txt [deleted file]
service/notification-manager/SampleApp/arduino/Time/Time.cpp [deleted file]
service/notification-manager/SampleApp/arduino/Time/Time.h [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/readme.txt [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeArduinoDue/TimeArduinoDue.ino [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeGPS/TimeGPS.ino [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeNTP/TimeNTP.ino [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeRTC/TimeRTC.pde [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCLog/TimeRTCLog.pde [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCSet/TimeRTCSet.ino [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeSerial/TimeSerial.ino [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino [deleted file]
service/notification-manager/SampleApp/arduino/Time/examples/TimeTeensy3/TimeTeensy3.ino [deleted file]
service/notification-manager/SampleApp/arduino/Time/keywords.txt [deleted file]
service/notification-manager/SampleApp/arduino/local.properties [deleted file]
service/notification-manager/SampleApp/arduino/makefile [deleted file]
service/notification-manager/SampleApp/arduino/readme.txt [deleted file]
service/notification-manager/SampleApp/arduino/thserver.cpp [deleted file]
service/notification-manager/SampleApp/linux/SConscript
service/notification-manager/SampleApp/linux/notificationManager/main.c [new file with mode: 0644]
service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp
service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp
service/notification-manager/SampleApp/tizen/NMSampleApp/.cproject [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/.exportMap [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/.project [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/.tproject [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/edc_resource/hosting_control.edc [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/inc/nmsampleapp.h [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/inc/nmutil.h [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/res/ui_controls.edc [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/shared/res/nmsampleapp.png [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/src/main.cpp [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/src/nmsampleapp.cpp [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/src/nmutil.cpp [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/NMSampleApp/tizen-manifest.xml [new file with mode: 0644]
service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-client.cpp
service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-log.h
service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.c
service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.h
service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-utils.h
service/notification-manager/build/linux/makefile/Makefile [deleted file]
service/notification-manager/build/tizen/CMakeLists.txt
service/protocol-plugin/SConscript
service/protocol-plugin/build/linux/Makefile [deleted file]
service/protocol-plugin/config.mk [deleted file]
service/protocol-plugin/lib/cpluff/doc/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/doc/img/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/docsrc/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/examples/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/libcpluff/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/libcpluff/cpluffdef.h
service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/libcpluff/pcontrol.c
service/protocol-plugin/lib/cpluff/libcpluff/ploader.c
service/protocol-plugin/lib/cpluff/libcpluff/pscan.c
service/protocol-plugin/lib/cpluff/libcpluff/psymbol.c
service/protocol-plugin/lib/cpluff/loader/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/po/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/test/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/test/plugins-source/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/test/plugins-source/callbackcounter/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/test/plugins-source/symprovider/Makefile [deleted file]
service/protocol-plugin/lib/cpluff/test/plugins-source/symuser/Makefile [deleted file]
service/protocol-plugin/lib/rapidxml/rapidxml.hpp [deleted file]
service/protocol-plugin/lib/rapidxml/rapidxml_iterators.hpp [deleted file]
service/protocol-plugin/lib/rapidxml/rapidxml_print.hpp [deleted file]
service/protocol-plugin/lib/rapidxml/rapidxml_utils.hpp [deleted file]
service/protocol-plugin/plugin-manager/SConscript
service/protocol-plugin/plugin-manager/build/linux/Makefile [deleted file]
service/protocol-plugin/plugin-manager/src/Android/.classpath [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/.project [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/AndroidManifest.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/assets/files/pluginmanager.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/ic_launcher-web.png [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/jni/Android.mk [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/jni/Application.mk [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/jni/PluginManager.cpp [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/jni/PluginManager.h [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/jni/SConscript [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/lint.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/proguard-project.txt [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/project.properties [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/layout/activity_main.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/layout/fragment_main.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/menu/main.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/values-v11/styles.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/values-v14/styles.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/values-w820dp/dimens.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/values/dimens.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/values/strings.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/res/values/styles.xml [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/FelixManager.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/FoundResource.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/MainActivity.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetBelkinplug.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetGear.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetHuebulb.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutBelkinplug.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutGear.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutHuebulb.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/Plugin.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/PluginManager.java [new file with mode: 0644]
service/protocol-plugin/plugin-manager/src/Config.cpp
service/protocol-plugin/plugin-manager/src/Config.h
service/protocol-plugin/plugin-manager/src/CpluffAdapter.cpp
service/protocol-plugin/plugin-manager/src/CpluffAdapter.h
service/protocol-plugin/plugin-manager/src/FelixAdapter.cpp
service/protocol-plugin/plugin-manager/src/FelixAdapter.h
service/protocol-plugin/plugin-manager/src/Plugin.h
service/protocol-plugin/plugin-manager/src/PluginManager.cpp
service/protocol-plugin/plugin-manager/src/PluginManager.h
service/protocol-plugin/plugin-manager/src/PluginManagerImpl.cpp
service/protocol-plugin/plugin-manager/src/PluginManagerImpl.h
service/protocol-plugin/plugin-manager/src/pluginmanager.xml [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/.classpath [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/META-INF/MANIFEST.MF [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/build.properties [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/gson.jar [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/richnotification.jar [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/sdk.jar [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/Activator.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/EntityHandlerNoti.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/IExample.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/SmallHeaderExample.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/.classpath [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/META-INF/MANIFEST.MF [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/build.properties [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/lib/huelocalsdk.jar [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/lib/huesdkresources.jar [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/AccessPointListAdapter.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/Activator.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/EntityHandlerHue.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/HueSharedPreferences.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.wemo/.classpath [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.wemo/META-INF/MANIFEST.MF [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.wemo/build.properties [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.wemo/lib/wemosdk.jar [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.wemo/src/oic/plugin/wemo/Activator.java [new file with mode: 0644]
service/protocol-plugin/plugins/Android/plugin.wemo/src/oic/plugin/wemo/EntityHandlerWemo.java [new file with mode: 0644]
service/protocol-plugin/plugins/SConscript
service/protocol-plugin/plugins/mqtt-fan/build/linux/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-fan/lib/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-fan/lib/SConscript
service/protocol-plugin/plugins/mqtt-fan/lib/cpp/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-fan/lib/cpp/mosquittopp.cpp
service/protocol-plugin/plugins/mqtt-fan/lib/cpp/mosquittopp.h
service/protocol-plugin/plugins/mqtt-fan/lib/dummypthread.h
service/protocol-plugin/plugins/mqtt-fan/lib/memory_mosq.c
service/protocol-plugin/plugins/mqtt-fan/lib/messages_mosq.h
service/protocol-plugin/plugins/mqtt-fan/lib/mosquitto.c
service/protocol-plugin/plugins/mqtt-fan/lib/mosquitto.h
service/protocol-plugin/plugins/mqtt-fan/lib/mosquitto_internal.h
service/protocol-plugin/plugins/mqtt-fan/lib/net_mosq.c
service/protocol-plugin/plugins/mqtt-fan/lib/net_mosq.h
service/protocol-plugin/plugins/mqtt-fan/lib/python/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-fan/lib/send_mosq.h
service/protocol-plugin/plugins/mqtt-fan/lib/time_mosq.c
service/protocol-plugin/plugins/mqtt-fan/lib/tls_mosq.c
service/protocol-plugin/plugins/mqtt-fan/lib/will_mosq.h
service/protocol-plugin/plugins/mqtt-fan/src/fanserver.cpp
service/protocol-plugin/plugins/mqtt-light/build/linux/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-light/lib/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-light/lib/cpp/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-light/lib/cpp/mosquittopp.cpp
service/protocol-plugin/plugins/mqtt-light/lib/cpp/mosquittopp.h
service/protocol-plugin/plugins/mqtt-light/lib/dummypthread.h
service/protocol-plugin/plugins/mqtt-light/lib/messages_mosq.h
service/protocol-plugin/plugins/mqtt-light/lib/mosquitto.h
service/protocol-plugin/plugins/mqtt-light/lib/mosquitto_internal.h
service/protocol-plugin/plugins/mqtt-light/lib/net_mosq.h
service/protocol-plugin/plugins/mqtt-light/lib/python/Makefile [deleted file]
service/protocol-plugin/plugins/mqtt-light/lib/send_mosq.h
service/protocol-plugin/plugins/mqtt-light/lib/will_mosq.h
service/protocol-plugin/plugins/mqtt-light/src/lightserver.cpp
service/protocol-plugin/sample-app/SConscript
service/protocol-plugin/sample-app/linux/SConscript
service/protocol-plugin/sample-app/linux/mqtt/Makefile [deleted file]
service/protocol-plugin/sample-app/linux/mqtt/mqttclient.cpp
service/protocol-plugin/sample-app/tizen/PPMSampleApp/.cproject [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/.exportMap [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/.project [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/inc/ppmsampleapp.h [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/pluginmanager.xml [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/plugins/mqtt-fan/plugin.xml [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/plugins/mqtt-light/plugin.xml [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/shared/res/sampleapp.png [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/src/ppmsampleapp.cpp [new file with mode: 0644]
service/protocol-plugin/sample-app/tizen/PPMSampleApp/tizen-manifest.xml [new file with mode: 0644]
service/soft-sensor-manager/SConscript
service/soft-sensor-manager/SDK/cpp/build/linux/Makefile [deleted file]
service/soft-sensor-manager/SDK/cpp/include/SSMInterface.h
service/soft-sensor-manager/SDK/cpp/src/InprocSSMCore.cpp
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/CoreController.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/DataReader.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IQueryEngineEvent.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IReportReceiver.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/ModelData.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/QueryEngine.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/SSMInterface.java
service/soft-sensor-manager/SSMCore/build/linux/Makefile [deleted file]
service/soft-sensor-manager/SSMCore/include/SSMInterface.h
service/soft-sensor-manager/SSMCore/src/Common/InternalInterface.h
service/soft-sensor-manager/SSMCore/src/Common/ObjectManager.h
service/soft-sensor-manager/SSMCore/src/Common/PlatformLayer.h
service/soft-sensor-manager/SSMCore/src/Common/ThreadManager.cpp
service/soft-sensor-manager/SSMCore/src/Common/ThreadManager.h
service/soft-sensor-manager/SSMCore/src/Common/rapidxml.hpp [deleted file]
service/soft-sensor-manager/SSMCore/src/Common/rapidxml_iterators.hpp [deleted file]
service/soft-sensor-manager/SSMCore/src/Common/rapidxml_print.hpp [deleted file]
service/soft-sensor-manager/SSMCore/src/Common/rapidxml_utils.hpp [deleted file]
service/soft-sensor-manager/SSMCore/src/QueryProcessor/CQLParser.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/CQLParser.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ConditionedModel.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ConditionedModel.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ConditionedQuery.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ConditionedQuery.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ConditionedQueryResult.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ConditionedQueryResult.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ContextModel.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ContextModel.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ContextQuery.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ContextQuery.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/DataReader.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/DataReader.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/EvaluationEngine.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/EvaluationEngine.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ModelData.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ModelData.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/PropagationEngine.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/PropagationEngine.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/QueryEngine.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/QueryEngine.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore.cpp
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/SSMInterface/SSMResourceServer.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SoftSensorManager.cpp
service/soft-sensor-manager/SSMCore/src/SSMInterface/SoftSensorManager.h
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextDataReader.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextDataReader.h
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextExecutor.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextExecutor.h
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextRepository.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextRepository.h
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ResourceFinder.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ResourceFinder.h
service/soft-sensor-manager/SSMCore/src/SensorProcessor/SensingEngine.h
service/soft-sensor-manager/SampleApp/Readme_ITScenario.txt [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/SConscript
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/AndroidManifest.xml [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/jni/Android.mk [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/jni/Application.mk [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_action_search.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_action_search.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_launcher.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_action_search.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_action_search.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/layout/activity_main.xml [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/menu/activity_main.xml [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values-v11/styles.xml [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values-v14/styles.xml [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values/strings.xml [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values/styles.xml [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/android/SSMTesterApp/src/org/iotivity/service/ssm/sample/MainActivity.java [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Makefile [deleted file]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile [deleted file]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.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/Reference_Thing/src/reference.cpp
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/trackee.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/makefile [deleted file]
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/src/thserver.cpp
service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/readme.txt [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/thserver.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile [deleted file]
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/arduino/environment.mk [deleted file]
service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/SConscript [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/include/HeightSensorApp.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/src/HeightSensorApp.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/linux/Makefile [deleted file]
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/SConscript
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/build/Makefile [deleted file]
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/include/SSMTestApp.h
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/src/SSMTestApp.cpp
service/soft-sensor-manager/SampleApp/linux/THSensorApp/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp/build/Makefile [deleted file]
service/soft-sensor-manager/SampleApp/linux/THSensorApp/include/ThingResourceServer.h
service/soft-sensor-manager/SampleApp/linux/THSensorApp/src/ThingResourceServer.cpp
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/build/Makefile [deleted file]
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/include/ThingResourceServer1.h
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/src/ThingResourceServer1.cpp
service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/SConscript [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/include/WeightSensorApp.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/src/WeightSensorApp.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.cproject [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.exportMap [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.gitignore [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.project [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.rds_delta [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.sdk_delta.info [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.tproject [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/CMakeLists.txt
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/README
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/RELEASE.txt
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/inc/ssmtesterapp.h [new file with mode: 0644]
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 [deleted file]
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/SampleApp/tizen/SSMTesterApp/res/ui_controls.edc [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/shared/res/ssmtesterapp.png [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/src/ssmtesterapp.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/tizen-manifest.xml [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/BMISensor/include/BMISensor.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/BMISensor/include/SysTimer.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/BMISensor/src/BMISensor.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/BMISensor/src/SysTimer.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/build/linux/Makefile [deleted file]
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/include/DiscomfortIndexSensor.h
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/GeneralData.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/SysTimer.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/Trajectory.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/lib_proximity.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_CbleDevice.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_ble_bgthread.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_log.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_proximity.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_public_ble.h [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/SysTimer.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/lib_proximity.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_CbleDevice.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_ble_bgthread.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_proximity.cpp [new file with mode: 0644]
service/soft-sensor-manager/SoftSensorPlugin/SoftSensorDescription.xml
service/soft-sensor-manager/build/arduino/Makefile [deleted file]
service/soft-sensor-manager/build/arduino/environment.mk [deleted file]
service/soft-sensor-manager/build/linux/Makefile [deleted file]
service/soft-sensor-manager/build/linux/environment.mk [deleted file]
service/things-manager/.gitignore
service/things-manager/Readme.txt [changed mode: 0755->0644]
service/things-manager/SConscript
service/things-manager/build/linux/makefile [deleted file]
service/things-manager/sampleapp/SConscript
service/things-manager/sampleapp/android/Sample/.classpath [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/.project [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/AndroidManifest.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/ic_launcher-web.png [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/project.properties [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/iot.jpg [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/layout/activity_main.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/layout/configapis.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/layout/custom_dialog.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/layout/groupapis.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/layout/userinputforregionvalue.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/menu/main.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/values-v11/styles.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/values-v14/styles.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/values-w820dp/dimens.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/values/dimens.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/values/strings.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/res/values/styles.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ActionListener.java [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ConfigurationApiActivity.java [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ConfigurationListener.java [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/src/com/tm/sample/DiagnosticListener.java [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/src/com/tm/sample/GroupApiActivity.java [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/src/com/tm/sample/GroupClient.java [new file with mode: 0644]
service/things-manager/sampleapp/android/Sample/src/com/tm/sample/MainActivity.java [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/.classpath [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/.project [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/AndroidManifest.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/ic_launcher-web.png [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/project.properties [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/layout/activity_main.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/menu/main.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/values-v11/styles.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/values-v14/styles.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/values-w820dp/dimens.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/values/dimens.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/values/strings.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/res/values/styles.xml [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/src/com/example/con_server/ConfigurationResource.java [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/src/com/example/con_server/ConfigurationServer.java [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/src/com/example/con_server/DiagnosticsResource.java [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/src/com/example/con_server/FactorySetResource.java [new file with mode: 0644]
service/things-manager/sampleapp/android/con-server/src/com/example/con_server/MainActivity.java [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.cpp
service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.h
service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.cpp
service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.h
service/things-manager/sampleapp/linux/configuration/FactorySetCollection.cpp
service/things-manager/sampleapp/linux/configuration/FactorySetCollection.h
service/things-manager/sampleapp/linux/configuration/SConscript
service/things-manager/sampleapp/linux/configuration/bootstrapserver.cpp
service/things-manager/sampleapp/linux/configuration/con-client.cpp
service/things-manager/sampleapp/linux/configuration/con-server.cpp [changed mode: 0755->0644]
service/things-manager/sampleapp/linux/configuration/makefile [deleted file]
service/things-manager/sampleapp/linux/groupaction/SConscript
service/things-manager/sampleapp/linux/groupaction/bookmark.cpp
service/things-manager/sampleapp/linux/groupaction/groupserver.cpp
service/things-manager/sampleapp/linux/groupaction/lightserver.cpp
service/things-manager/sampleapp/linux/groupaction/makefile [deleted file]
service/things-manager/sampleapp/linux/groupsyncaction/SConscript
service/things-manager/sampleapp/linux/groupsyncaction/group.cpp
service/things-manager/sampleapp/linux/groupsyncaction/makefile [deleted file]
service/things-manager/sampleapp/linux/groupsyncaction/musicplayer.cpp
service/things-manager/sampleapp/linux/groupsyncaction/phone.cpp
service/things-manager/sampleapp/linux/groupsyncaction/speaker.cpp
service/things-manager/sampleapp/linux/makefile [deleted file]
service/things-manager/sampleapp/tizen/ConServerApp/.cproject [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/.exportMap [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/.project [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/inc/configurationresource.h [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/inc/conserverapp.h [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/inc/diagnosticsresource.h [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/inc/factorysetresource.h [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/res/ui_controls.edc [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/shared/res/conserverapp.png [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/src/configurationresource.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/src/conserverapp.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/src/diagnosticsresource.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/src/factorysetresource.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/ConServerApp/tizen-manifest.xml [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/.cproject [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/.exportMap [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/.project [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/edc_resource/configuration_control.edc [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/edc_resource/group_control.edc [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/inc/tmsampleapp.h [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/inc/tmutil.h [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/res/ui_controls.edc [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/shared/res/tmsampleapp.png [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/src/configuration.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/src/group.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/src/tmsampleapp.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/src/tmutil.cpp [new file with mode: 0644]
service/things-manager/sampleapp/tizen/TMSampleApp/tizen-manifest.xml [new file with mode: 0644]
service/things-manager/sdk/build/linux/Makefile [deleted file]
service/things-manager/sdk/inc/ActionSet.h [new file with mode: 0644]
service/things-manager/sdk/inc/ThingsManager.h
service/things-manager/sdk/java/AndroidManifest.xml [new file with mode: 0644]
service/things-manager/sdk/java/jni/Android.mk [new file with mode: 0644]
service/things-manager/sdk/java/jni/Application.mk [new file with mode: 0644]
service/things-manager/sdk/java/jni/SConscript [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/inc/jni_getter.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/inc/jni_object.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/inc/jni_setter.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/inc/jni_string.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/inc/jni_things_manager_jvm.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/src/jni_getter.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/src/jni_object.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/src/jni_setter.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/src/jni_string.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/jniutil/src/jni_things_manager_jvm.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/inc/jni_action.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/inc/jni_action_set.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/inc/jni_capability.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/inc/jni_things_manager.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/inc/jni_things_manager_callbacks.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/inc/jni_things_manager_util.h [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/src/jni_action.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/src/jni_action_set.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/src/jni_capability.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/src/jni_things_manager.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/src/jni_things_manager_callbacks.cpp [new file with mode: 0644]
service/things-manager/sdk/java/jni/tm/src/jni_things_manager_util.cpp [new file with mode: 0644]
service/things-manager/sdk/java/project.properties [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/Action.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/ActionSet.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/Capability.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/IActionListener.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/IConfigurationListener.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/IDiagnosticsListener.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/IFindCandidateResourceListener.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/IFindGroupListener.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/ISubscribePresenceListener.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/OCStackResult.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManager.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerCallback.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerInterface.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerNativeInterface.java [new file with mode: 0644]
service/things-manager/sdk/java/src/org/iotivity/service/tm/Time.java [new file with mode: 0644]
service/things-manager/sdk/src/ActionSet.cpp [new file with mode: 0644]
service/things-manager/sdk/src/GroupManager.cpp
service/things-manager/sdk/src/GroupManager.h
service/things-manager/sdk/src/GroupSynchronization.cpp
service/things-manager/sdk/src/GroupSynchronization.h
service/things-manager/sdk/src/ThingsConfiguration.cpp [changed mode: 0755->0644]
service/things-manager/sdk/src/ThingsConfiguration.h
service/things-manager/sdk/src/ThingsDiagnostics.cpp
service/things-manager/sdk/src/ThingsDiagnostics.h
service/things-manager/sdk/src/ThingsManager.cpp
service/third_party_libs.scons
tools/Readme.scons.txt [deleted file]
tools/SConstruct [deleted file]
tools/arduino.scons [deleted file]
tools/auto_build.sh [deleted file]
tools/darwin/build-ios.sh [new file with mode: 0755]
tools/darwin/mkfwk_ios.sh [new file with mode: 0755]
tools/darwin/mkfwk_osx.sh [new file with mode: 0755]
tools/extra_options.scons [deleted file]
tools/scons/BoostBootstrap.py [new file with mode: 0644]
tools/scons/BoostBuild.py [new file with mode: 0644]
tools/scons/Configure.py [new file with mode: 0644]
tools/scons/URLDownload.py [new file with mode: 0644]
tools/scons/UnpackAll.py [new file with mode: 0644]
tools/scons_script_how_to.txt [deleted file]
tools/style/astyle-clean-cpp-format.sh [new file with mode: 0755]
tools/style/astyle-cpp-format.sh [new file with mode: 0755]
tools/style/iotivity_cpp_astyle.cfg [new file with mode: 0644]
tools/style/iotivity_cpp_style.xml [new file with mode: 0644]
tools/style/iotivity_java_style.xml [new file with mode: 0644]
tools/tizen/.gbs.conf [new file with mode: 0644]
tools/tizen/iotivity.spec
tools/tizen/scons-2.1.0-3.1.slp.noarch.rpm [new file with mode: 0644]
tools/vagrant/README.md [new file with mode: 0644]
tools/vagrant/Vagrantfile [new file with mode: 0644]
tools/vagrant/bootstrap.sh [new file with mode: 0644]
tools/vagrant/iotivity-setup.sh [new file with mode: 0644]

index 04161af..d0fbb21 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 # Ignore output dirs
 /release
 resource/release
@@ -22,6 +42,9 @@ resource/oc_logger/lib/
 resource/oc_logger/samples/linux/release/
 resource/oc_logger/samples/linux/debug
 
+resource/unittests/release/
+resource/unittests/debug/
+
 service/things-manager/build/linux/release
 service/things-manager/build/linux/debug
 service/things-manager/sdk/build/linux/
@@ -32,9 +55,9 @@ service/things-manager/sdk/build/linux/
 
 # Ignore Eclipse workspace files
 *.settings/
-*.cproject
-*.project
 
+# Ignore CTags default data
+tags
 # Ignore dependencies folder, which should be generated
 dependencies/
 
@@ -53,8 +76,24 @@ out/
 platform
 
 # Ignore downloaded dependencies
-extlibs/gtest*
+extlibs/gtest/gtest-*
+extlibs/hippomocks-master/
+extlibs/master.zip
+extlibs/cereal/cereal
+extlibs/expat/expat*
 extlibs/cereal
+extlibs/android/gradle/gradle-2.2.1
+extlibs/android/ndk/android-ndk-r10d
+extlibs/android/sdk/android-sdk_r24.2
+extlibs/boost/boost_1_58_0
+*.tgz
+*.zip
+extlibs/arduino/arduino-1.5.8
+build_common/arduino/extlibs/arduino/arduino-1.5.8
 
+# Ignore editor (e.g. Emacs) backup and autosave files
 *~
-cscope.out
+*#*#
+
+# Ignore byte-compiled Python scripts
+*.pyc
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644 (file)
index 0000000..e9e1f02
--- /dev/null
@@ -0,0 +1,195 @@
+Copyright (c) 2014, 2015 IoTivity
+<http://www.iotivity.com/>
+
+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.
+
+```
+-------------------------------------------------------------------------
+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+```
diff --git a/NOTICE.md b/NOTICE.md
new file mode 100644 (file)
index 0000000..6d243f8
--- /dev/null
+++ b/NOTICE.md
@@ -0,0 +1,59 @@
+IoTivity
+Copyright (c) 2014, 2015 IoTivity
+
+This product includes software developed as part of
+the IoTivity (http://www.iotivity.org/) project.
+
+Tools and Utilities
+===================
+
+Software construction is provided by SCons a python-based software
+constrution tools which is open source software with copyright
+by The SCons Foundation with an MIT license. The original software
+is available from
+  http://scons.org/download.php
+
+Android binaries are created using the Android SDK and NDK provided
+by Google. The original software can be found at
+  https://developer.android.com/sdk
+
+Libraries
+=========
+
+The CoAP protocol is provided by the libcoap package,
+which is open source software, written and copyright by Olaf Bergmann
+with a BSD and GPLv2 license. The original software is available from
+  http://sourceforge.net/projects/libcoap/
+
+The DTLS protocol is provided by the tinyDTLS package,
+which is open source software, written and copyright by Olaf Bergmann
+with an MIT license. The tinyDTLS library relies on algorithms whose
+source is under a BSD license. The additional licenses can be viewed at
+  http://tinydtls.sourceforge.net/
+The original software is available from
+  http://sourceforge.net/projects/tinydtls/
+
+This project relies on utilities in the Boost C++library which is open
+source software with a Boost Software License v1.0. The details of the
+license can be found at
+  http://www.boost.org/users/license.html
+The original software is available from
+  http://sourceforge.net/projects/boost/files/boost
+
+JSON serialization is provided by the cereal package,
+which is open source software, written by Philip Hazel, and copyright
+by the University of Cambridge, England. The original software is
+available from
+  ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/
+
+JSON serialization is provided by the cjson package,
+which is open source software, written and copyright by Dave Gamble
+with an MIT license. The original software is available from
+  http://sourceforge.net/projects/cjson/
+
+JSON serialization is provided by the rapidjson package,
+which is open source software, written and copyright by Milo Yip
+with an MIT license. The original software is available from
+  http://code.google.com/p/rapidjson/
+
+
index 2129efe..d433b3b 100644 (file)
@@ -1,3 +1,33 @@
+== Quick guide: build and run IoTivity projects on Ubuntu ==
+
+1. Build
+       Go to the top directory of 'iotivity' project(Note: should always run 'scons'
+command in this directory)
+
+    Install external libraries:
+      $ sudo apt-get install libboost-dev libboost-program-options-dev libexpat1-dev libboost-thread-dev uuid-dev
+
+    Build release binaries:
+      $ scons
+(Note: C++ sdk requires cereal. Please follow the instruction in the build
+message to install cereal)
+
+    Build debug binaries:
+      $scons RELEASE=false
+
+    Help:
+      $ scons -h
+
+    Clear:
+      $ scons -c
+
+2. Run the samples
+      $ export LD_LIBRARY_PATH=<iotivity>/out/linux/x86_64/release
+      Run the c++ samples in <iotivity>/out/linux/x86_64/release/resource/examples
+      Run the c samples in <iotivity>/out/linux/x86_64/release/resource/csdk/stack/samples/linux/SimpleClientServer
+('<iotivity>' is the path to 'iotivity' project. If your device is x86, arm,
+or arm64, please change 'x86_64' to the proper arch)
+
 == How to build IoTivity projects ==
 
 IoTivity includes a series of projects. You can find all these projects here:
@@ -8,7 +38,7 @@ Linux, Tizen, Android, Arduino, Windows, MAC OSX, IOS ...).
 The output of the build is in:
   <top directory of the project>/out/<target_os>/<target_arch>/<build_type>/
 e.g.
-       oic-resource/out/android/armeabi-v7a/release/.
+       iotivity/out/android/armeabi-v7a/release/.
 
 This document takes 'iotivity' project as example, the way to build other
 projects is almost the same.
@@ -26,7 +56,16 @@ information(include build options). To see the help information:
       $ scons [options] -h
 
 Note: If no value is specified for an option, the default value will be used.
-The change of options value may impact the output.
+The change of options value may impact the help information and the behavior
+of the building.
+
+Generally, it's required to specify the target OS and target ARCH, that's to say
+tell Scons which OS and which ARCH you'd like build this project for. By default,
+the target OS and ARCH is the same as the host.
+
+Some more options may be required, please care the 'error' notification when build.
+For help about how to set an option, please run:
+     $ scons TARGET_OS=xxx TARGET_ARCH=yyy [XXX=zzz ...] -h
 
 
 === Prerequites ===
@@ -46,7 +85,7 @@ To build for Android, Andorid NDK and SDK are required.
   Android NDK: http://developer.android.com/tools/sdk/ndk/index.html
   Android SDK: http://developer.android.com/sdk/index.html
 (Note: as in some IoTivity projects, C++11 features are used, recommend Android
- NDK >= r10, according to our test result r10c is the best one currently)
+ NDK >= r10)
 
 Arduino:
 To build for Arduino, Arduino IDE is required.
@@ -76,33 +115,32 @@ Java codes, this isn't required)
 so you don't need to add it in command line each time. The build script will
 guide you to do that.)
 
-* 3. External libraries
-For Android and IOS build, most of the external libraries are provided as
-binary in oic-utilities project (https://oic-review.01.org/gerrit/oic-utilities).
-Please download it in the same directory as other IoTivity projects. If it's
-in different directory, an additional option (OIC_UITLS) will be required. The
-build command should be:
-      $ scons OIC_UITLS=<path to oic-utilities> [other options] [target]
+Tizen:
+To build for tizen platform cereal library is needed.
+Please download cereal if it is not present in extlibs/cereal folder
+and apply the patch as following:
+       $ git clone https://github.com/USCiLab/cereal.git extlibs/cereal/cereal
+       $ cd  extlibs/cereal/cereal
+       $ git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245
+       $ git apply ../../../resource/patches/cereal_gcc46.patch
 
-(Note: for convenience, you can also add it in environment variable. So you
-don't need to add this option in command line each time.)
-  e.g.:
-      $ export OIC_UITLS=<path to oic-utilities project>
 
+* 3. External libraries
+IoTivity project depends on some external libraries, such as boost, expat ...
+During building, the existence of external library will be checked, if it doesn't
+exist, the build script will try to download, unpack and build the library or
+notify user to install it.
 
-=== Build IoTivity project on Linux(Ubuntu) ===
+Downloading and unpacking may fail due to network problem or required unpacking
+tool isn't installed. An message will be displayed, please follow the message
+to skip it.
 
-Generally, it's required to specify the target OS and target ARCH, that's to say
-tell Scons which OS and which ARCH you'd like build this project for. By default,
-the target OS and ARCH is the same as the host.
 
-Some more options may be required, please care the 'error' notification when build.
-For help about how to set an option, please run:
-       $ scons TARGET_OS=xxx TARGET_ARCH=yyy [XXX=zzz ...] -h
+=== Build IoTivity project on Linux(Ubuntu) ===
 
 1. Build IoTivity project for Linux
       $ cd <top directory of the project>
-      $ sudo apt-get install libboost-dev libboost-program-options-dev libexpat1-dev
+      $ sudo apt-get install libboost-dev libexpat1-dev libboost-thread-dev
       $ scons
 
 2. Build IoTivity project for Android
@@ -111,10 +149,6 @@ For help about how to set an option, please run:
 (xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard. To see all of its
 allowed value, please execute command 'scons TARGET_OS=android -Q -h')
 
-Note: Currently as x86_64/arm64_v8a external library binaries aren't provided,
-you may meet link problem if build executable binary which depends on external
-library for x86_64/arm64_v8a.
-
 3. Build IoTivity project for Arduino
       $ cd <top directory of the project>
       $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy
@@ -127,13 +161,13 @@ it's unnecessary to specify it)
 
 4. Build Iotivity project for Tizen
       $ cd <top directory of the project>
-      $ gbs build -A xxx --packaging-dir tools/tizen/
-(xxx can be i586 or armv7l, we provide the spec file required by gbs tool at
-toools/tizen directory. gbs is default build tool for Tizen platfrom, we can
-refer the following wiki to setup Tizen development environment:
+      $ sh gbsbuild.sh
+(we provide the spec file required by gbs tool at toools/tizen directory.
+gbs is default build tool for Tizen platfrom, we can refer the following
+wiki to setup Tizen development environment:
 https://source.tizen.org/documentation/developer-guide/getting-started-guide)
 
-=== Build IoTivity project on Windows ===
+=== Build IoTivity project on Android ===
 
 1. Build IoTivity project for Android(It's the same as on Ubuntu)
       $ cd <top directory of the project>
@@ -183,7 +217,7 @@ Note:
 at once. Following is the usage:
 
 To build:
-     $ auto_build.sh <path-to-android-ndk> <path-to-arduino-home>
+     $ auto_build.sh <path-to-android-ndk>
 To clean:
      $ auto_build.sh -c
 
index 92eac38..bbe03d1 100644 (file)
@@ -1,18 +1,47 @@
+#******************************************************************
+#
+# 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
 #
 ##
+import os
 
 # Load common build config
 SConscript('build_common/SConscript')
 
+Import('env')
+
+if os.environ.get('TERM') != None:
+       env['ENV']['TERM'] = os.environ['TERM']
+
 # Load extra options
 SConscript('extra_options.scons')
-Import('env')
 
 target_os = env.get('TARGET_OS')
 if target_os == 'arduino':
        SConscript('arduino.scons')
+
+if target_os == 'android':
+       SConscript('android/android_api/SConscript')
+
 # By default, src_dir is current dir, the build_dir is:
 #     ./out/<target_os>/<target_arch>/<release or debug>/
 #
@@ -27,6 +56,9 @@ build_dir = env.get('BUILD_DIR')
 # Build 'resource' sub-project
 SConscript(build_dir + 'resource/SConscript')
 
+if target_os not in ['arduino','darwin','ios', 'android']:
+       SConscript(build_dir + 'examples/OICMiddle/SConscript')
+
 # Build 'service' sub-project
 SConscript(build_dir + 'service/SConscript')
 
@@ -37,3 +69,4 @@ env.PrintTargets()
 # Print bin upload command line (arduino only)
 if target_os == 'arduino':
        env.UploadHelp()
+
diff --git a/android/Base/app/build.gradle b/android/Base/app/build.gradle
deleted file mode 100644 (file)
index 31d66bb..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-apply plugin: 'com.android.library'
-
-android {
-    compileSdkVersion 19
-    buildToolsVersion "19.1.0"
-
-    defaultConfig {
-        applicationId "org.iotivity.base"
-        minSdkVersion 19
-        targetSdkVersion 19
-        versionCode 1
-        versionName "1.0"
-    }
-    buildTypes {
-        release {
-            runProguard false
-            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
-        }
-    }
-}
-
-dependencies {
-    compile fileTree(dir: 'libs', include: ['*.jar'])
-}
-
-
-//////////////
-// NDK Support
-//////////////
-// If using this, Android studio will fail run the following to set the environment variable for android studio:
-// launchctl setenv ANDROID_NDK_HOME /Users/boos_patrick/Development/Android/android-ndk-r8e
-// otherwise remove the dependsOn part and run ./gradlew buildNative from the command line
-task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {
-    dependsOn 'buildNative'
-    from(new File('libs')) { include '**/*.so' }
-    into new File(buildDir, 'native-libs')
-}
-
-tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }
-
-clean.dependsOn 'cleanCopyNativeLibs'
-
-tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
-    pkgTask.jniFolders = new HashSet<File>()
-    pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))
-}
-
-task buildNative(type: Exec) {
-    if (System.env.ANDROID_NDK_HOME != null) {
-        def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
-        commandLine ndkBuild
-    } else {
-        doLast {
-            println '##################'
-            println 'Skipping NDK build'
-            println 'Reason: ANDROID_NDK_HOME not set.'
-            println '##################'
-        }
-    }
-}
diff --git a/android/Base/app/jni/Android.mk b/android/Base/app/jni/Android.mk
deleted file mode 100644 (file)
index 58e9a36..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
-LOCAL_MODULE := libandroid-oc_logger
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger.a
-include $(PREBUILT_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
-LOCAL_MODULE := libandroid-octbstack
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.a
-include $(PREBUILT_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
-LOCAL_MODULE := libandroid-oc
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.a
-include $(PREBUILT_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
-LOCAL_MODULE := libandroid-coap
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libcoap.a
-include $(PREBUILT_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
-LOCAL_MODULE := libandroid-compatibility
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libcompatibility.a
-include $(PREBUILT_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_SRC_PATH := ../../../resource
-OIC_OUT_PATH := ../../../out
-LOCAL_MODULE    := ocstack-jni
-LOCAL_SRC_FILES := ocstack-jni.cpp \
-                   ocheaderoption-jni.cpp \
-                   ocrepresentation-jni.cpp \
-                   ocresource-jni.cpp \
-                   ocplatform-jni.cpp \
-                   platformcfg-jni.cpp
-LOCAL_LDLIBS := -llog
-LOCAL_STATIC_LIBRARIES := android-oc
-LOCAL_STATIC_LIBRARIES += android-octbstack
-LOCAL_STATIC_LIBRARIES += android-coap
-LOCAL_STATIC_LIBRARIES += android-oc_logger
-LOCAL_STATIC_LIBRARIES += libandroid-compatibility
-LOCAL_CPPFLAGS += -std=c++0x -frtti -fexceptions
-LOCAL_C_INCLUDES := $(OIC_SRC_PATH)/include
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/stack/include
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/ocsocket/include
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/oc_logger/include
-LOCAL_C_INCLUDES += $(OIC_OUT_PATH)/android/include
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/dependencies/cereal/include
-include $(BUILD_SHARED_LIBRARY)
-
diff --git a/android/Base/app/jni/Application.mk b/android/Base/app/jni/Application.mk
deleted file mode 100644 (file)
index 4450fdf..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-NDK_TOOLCHAIN_VERSION := 4.9
-APP_STL               := gnustl_static
diff --git a/android/Base/app/jni/ocheaderoption-jni.cpp b/android/Base/app/jni/ocheaderoption-jni.cpp
deleted file mode 100644 (file)
index 7dcd320..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocstack-jni.h"
-
-static const char* TAG = "OCHEADEROPTION-JNI";
-
-JNIEXPORT jint JNICALL getOptionID(JNIEnv *env, jobject jobj)
-{
-    OC::HeaderOption::OCHeaderOption *option = getHandle<OC::HeaderOption::OCHeaderOption>(env, jobj);
-    return option->getOptionID();
-}
-
-JNIEXPORT jstring JNICALL getOptionData(JNIEnv *env, jobject jobj)
-{
-    OC::HeaderOption::OCHeaderOption *option = getHandle<OC::HeaderOption::OCHeaderOption>(env, jobj);
-    std::string data = option->getOptionData();
-    return env->NewStringUTF(data.c_str());
-}
-
-JNIEXPORT jlong JNICALL OCHeaderOptionConstructor(JNIEnv *env, jobject jobj, jint joption, jstring jdata)
-{
-    OC::HeaderOption::OCHeaderOption *option = new OC::HeaderOption::OCHeaderOption(joption, env->GetStringUTFChars(jdata, 0));
-    jlong instptr = reinterpret_cast<jlong>(option);
-    return instptr;
-}
-
diff --git a/android/Base/app/jni/ocplatform-jni.cpp b/android/Base/app/jni/ocplatform-jni.cpp
deleted file mode 100644 (file)
index a69ac2d..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocstack-jni.h"
-
-static const char* TAG = "OCPLATFORM-JNI";
-
-JNIEXPORT void JNICALL configure(JNIEnv *env, jobject obj, jobject jcfg)
-{
-    OC::PlatformConfig *cfg = getHandle<OC::PlatformConfig>(env, jcfg);
-
-    __android_log_print(ANDROID_LOG_INFO, TAG, "service : %d\n", (int) cfg->serviceType);
-    __android_log_print(ANDROID_LOG_INFO, TAG, "mode    : %d\n", (int) cfg->mode);
-    __android_log_print(ANDROID_LOG_INFO, TAG, "IP      : %s\n", (cfg->ipAddress).c_str());
-    __android_log_print(ANDROID_LOG_INFO, TAG, "port    : %d\n", cfg->port);
-    __android_log_print(ANDROID_LOG_INFO, TAG, "QOS     : %d\n", (int) cfg->QoS);
-
-    OC::OCPlatform::Configure(*cfg);
-}
-
-
-JNIEXPORT jint JNICALL findResource(JNIEnv* env, jobject obj, jstring jhost, jstring juri, jobject found)
-{
-       string host = env->GetStringUTFChars(jhost,0);
-       string uri = env->GetStringUTFChars(juri,0);
-
-    JNICallBackContext *callbackContext;
-    string key = uri + "/FIND";
-    std:map<std::string, JNICallBackContext*>::iterator iter = gJNICallBackContextList.find(key);
-    if(iter == gJNICallBackContextList.end()) {
-        gJNICallBackContextList[key] = new JNICallBackContext(env->NewGlobalRef(found));
-        callbackContext = gJNICallBackContextList[key];
-        __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str());
-    }
-    else
-        callbackContext = iter->second;
-
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "Calling oic base findresource()\n");
-    try {
-        OC::OCPlatform::findResource(host, uri,
-            [callbackContext](std::shared_ptr<OC::OCResource> resource)
-            {
-                 JNIEnv * env;
-
-                // Attach to JavaVM
-                // double check it's all ok
-                int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6);
-                if (getEnvStat == JNI_EDETACHED) {
-                    __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached");
-                    if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) {
-                    __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach");
-                    }
-                    else
-                        __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK");
-                } else if (getEnvStat == JNI_OK) {
-                //
-                } else if (getEnvStat == JNI_EVERSION) {
-                    __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported");
-                }
-
-                // save the C++ resource ptr now
-                jmethodID resource_constructor = env->GetMethodID(g_ocresource_clazz, "<init>", "(J)V");
-
-                callbackContext->m_resource = resource;
-                jobject jresource = env->NewObject(g_ocresource_clazz, resource_constructor, \
-                                        (jlong) reinterpret_cast<jlong>(&callbackContext->m_resource));
-
-                if(jresource == NULL) {
-                    __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCResource class");
-                    return;
-                }
-
-                jclass clazz = env->GetObjectClass(callbackContext->m_callBackFunction);
-                if (clazz == NULL) {
-                    __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class");
-                }
-
-                // Find Callback function
-                jmethodID mid = env->GetMethodID(clazz, "Callback", \
-                        "(Lorg/iotivity/base/OCResource;)V");
-                if(mid == NULL) {
-                    __android_log_print(ANDROID_LOG_ERROR, TAG, "FoundResource.Callback() is not defined in JAVA");
-                    return;
-                }
-
-                __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA FindCallback");
-                try {
-                    env->CallVoidMethod(callbackContext->m_callBackFunction, mid, jresource);
-                } catch(OC::OCException& e) {
-                    __android_log_print(ANDROID_LOG_ERROR, TAG, "callbackContext() exception : %s", e.reason(e).c_str());
-                }
-
-                __android_log_print(ANDROID_LOG_INFO, TAG, "fineResourceCB detach");
-                env->DeleteLocalRef(jresource);
-                g_JavaVM->DetachCurrentThread();
-
-            }
-        );
-    }
-    catch(OC::OCException& e) {
-        __android_log_print(ANDROID_LOG_ERROR, TAG, "FindCB() exception : %s", e.reason(e).c_str());
-    }
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "Called oic base findresource()\n");
-
-    return 0;
-}
-
diff --git a/android/Base/app/jni/ocrepresentation-jni.cpp b/android/Base/app/jni/ocrepresentation-jni.cpp
deleted file mode 100644 (file)
index d7c894d..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocstack-jni.h"
-
-static const char* TAG = "OCREPRESENTATION-JNI";
-
-JNIEXPORT jlong JNICALL OCRepresentationConstructor(JNIEnv *env, jobject jobj)
-{
-    OC::OCRepresentation *rep = new OC::OCRepresentation();
-    jlong instptr = reinterpret_cast<jlong>(rep);
-    return instptr;
-}
-
-JNIEXPORT jstring JNICALL getUri(JNIEnv *env, jobject jobj)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-    string uri = rep->getUri();
-    __android_log_print(ANDROID_LOG_INFO, TAG, "getUri() URI : %s", uri.c_str());
-    return env->NewStringUTF(uri.c_str());
-}
-
-JNIEXPORT jint JNICALL getValueInt(JNIEnv *env, jobject jobj, jstring jstr)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-       string str = env->GetStringUTFChars(jstr,0);
-       int val;
-    rep->getValue(str, val);
-    __android_log_print(ANDROID_LOG_INFO, TAG, "getValueInt() : %d", val);
-    return((jint) val);
-}
-
-
-JNIEXPORT jboolean JNICALL getValueBool(JNIEnv *env, jobject jobj, jstring jstr)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-       string str = env->GetStringUTFChars(jstr,0);
-    bool val;
-    rep->getValue(str, val);
-    __android_log_print(ANDROID_LOG_INFO, TAG, "getValueBool() : %d", val);
-    return((jboolean) val);
-}
-
-JNIEXPORT jstring JNICALL getValueString(JNIEnv *env, jobject jobj, jstring jstr)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-       string str = env->GetStringUTFChars(jstr,0);
-       string get_val;
-    rep->getValue(str, get_val);
-
-    __android_log_print(ANDROID_LOG_INFO, TAG, "getValueString() : %s", get_val.c_str());
-    return env->NewStringUTF(get_val.c_str());
-}
-
-JNIEXPORT void JNICALL setValueInt(JNIEnv *env, jobject jobj, jstring jstr, jint jval)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-       string str = env->GetStringUTFChars(jstr,0);
-    rep->setValue(str, jval);
-}
-
-JNIEXPORT void JNICALL setValueBool(JNIEnv *env, jobject jobj, jstring jstr, jboolean jval)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-       string str = env->GetStringUTFChars(jstr,0);
-    rep->setValue(str, (bool) jval);
-}
-
-JNIEXPORT void JNICALL setValueString(JNIEnv *env, jobject jobj, jstring jstr, jstring jval)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-       string str = env->GetStringUTFChars(jstr,0);
-       string val = env->GetStringUTFChars(jval,0);
-
-    rep->setValue(str, val);
-}
-
-JNIEXPORT jboolean JNICALL hasAttribute(JNIEnv *env, jobject jobj, jstring jstr)
-{
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jobj);
-       string str = env->GetStringUTFChars(jstr,0);
-
-    return rep->hasAttribute(str);
-}
diff --git a/android/Base/app/jni/ocresource-jni.cpp b/android/Base/app/jni/ocresource-jni.cpp
deleted file mode 100644 (file)
index 95c2c39..0000000
+++ /dev/null
@@ -1,445 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocstack-jni.h"
-
-static const char* TAG = "OCRESOURCE-JNI";
-
-JNIEXPORT jobject JNICALL jniOicGet(JNIEnv *env, jobject jobj, jobject jattributeHandler)
-{
-
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "get() resource = %p\n", resource);
-
-    JNICallBackContext *callbackContext;
-    string key = (*resource)->uri() + "/GET";
-    std:map<std::string, JNICallBackContext*>::iterator iter = gJNICallBackContextList.find(key);
-    if(iter == gJNICallBackContextList.end()) {
-        gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler));
-        callbackContext = gJNICallBackContextList[key];
-        __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str());
-    }
-    else {
-        iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler);
-        callbackContext = iter->second;
-    }
-
-       OC::QueryParamsMap test;
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base get()\n");
-
-    (*resource)->get(test,
-        [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode)
-        {
-             JNIEnv * env;
-
-            // Attach to JavaVM
-            // double check it's all ok
-            int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6);
-            if (getEnvStat == JNI_EDETACHED) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached");
-                if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach");
-                }
-                else
-                    __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK");
-            } else if (getEnvStat == JNI_OK) {
-            //
-            } else if (getEnvStat == JNI_EVERSION) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported");
-            }
-
-            // save C++ ocheaderoption ptr now
-            jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "<init>", "(J)V");
-            int size = headerOptions.size();
-            jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0);
-            for (int n=0; n<size;n++) {
-                jobject jelem = env->NewObject(g_ocheaderoption_clazz, option_constructor, \
-                                            (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu",  (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                env->SetObjectArrayElement(joptions, n, jelem);
-                env->DeleteLocalRef(jelem);
-            }
-
-            // save C++ ocrepresentation ptr now
-            jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "<init>", "(J)V");
-            jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \
-                                    (jlong) reinterpret_cast<jlong>(&rep));
-            if(jrepresentation == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class");
-                return;
-            }
-
-            jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction);
-            if (cb_clazz == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class");
-            }
-
-            // Find Callback function
-            jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \
-                    "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;I)V");
-            if(cb_mid == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "onGet.Callback() is not defined in JAVA");
-                return;
-            }
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA GetCallback");
-            env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode);
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "getCB detach");
-            g_JavaVM->DetachCurrentThread();
-
-        }
-        );
-    return NULL;
-
-}
-
-JNIEXPORT jobject JNICALL jniOicPut(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler)
-{
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "put1() resource = %p\n", resource);
-
-    JNICallBackContext *callbackContext;
-    string key = (*resource)->uri() + "/PUT";
-    std:map<std::string, JNICallBackContext*>::iterator iter = gJNICallBackContextList.find(key);
-    if(iter == gJNICallBackContextList.end()) {
-        gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler));
-        callbackContext = gJNICallBackContextList[key];
-        __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str());
-    }
-    else {
-        iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler);
-        callbackContext = iter->second;
-    }
-
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jocrepresentation);
-       OC::QueryParamsMap test;
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base put()\n");
-
-    (*resource)->put(*rep, test,
-        [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode)
-        {
-             JNIEnv * env;
-
-            // Attach to JavaVM
-            // double check it's all ok
-            int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6);
-            if (getEnvStat == JNI_EDETACHED) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached");
-                if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach");
-                }
-                else
-                    __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK");
-            } else if (getEnvStat == JNI_OK) {
-            //
-            } else if (getEnvStat == JNI_EVERSION) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported");
-            }
-
-            // save C++ ocheaderoption ptr now
-            jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "<init>", "(J)V");
-            int size = headerOptions.size();
-            jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0);
-            for (int n=0; n<size;n++) {
-                jobject jelem = env->NewObject(g_ocheaderoption_clazz, option_constructor, \
-                                            (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu",  (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                env->SetObjectArrayElement(joptions, n, jelem);
-                env->DeleteLocalRef(jelem);
-            }
-
-            // save C++ ocrepresentation ptr now
-            jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "<init>", "(J)V");
-            jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \
-                                    (jlong) reinterpret_cast<jlong>(&rep));
-            if(jrepresentation == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class");
-                return;
-            }
-
-            jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction);
-            if (cb_clazz == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class");
-            }
-
-            // Find Callback function
-            jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \
-                    "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;I)V");
-            if(cb_mid == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "onPut.Callback() is not defined in JAVA");
-                return;
-            }
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA PutCallback");
-            env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode);
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "putCB detach");
-            g_JavaVM->DetachCurrentThread();
-        }
-        );
-    return NULL;
-}
-
-JNIEXPORT jobject JNICALL jniOicPost(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler)
-{
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "post1() resource = %p\n", resource);
-
-    JNICallBackContext *callbackContext;
-    string key = (*resource)->uri() + "/POST";
-    std:map<std::string, JNICallBackContext*>::iterator iter = gJNICallBackContextList.find(key);
-    if(iter == gJNICallBackContextList.end()) {
-        gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler));
-        callbackContext = gJNICallBackContextList[key];
-        __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str());
-    }
-    else {
-        iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler);
-        callbackContext = iter->second;
-    }
-
-    OC::OCRepresentation *rep = getHandle<OC::OCRepresentation>(env, jocrepresentation);
-       OC::QueryParamsMap test;
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base post()\n");
-
-    (*resource)->post(*rep, test,
-        [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode)
-        {
-             JNIEnv * env;
-
-            // Attach to JavaVM
-            // double check it's all ok
-            int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6);
-            if (getEnvStat == JNI_EDETACHED) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached");
-                if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach");
-                }
-                else
-                    __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK");
-            } else if (getEnvStat == JNI_OK) {
-            //
-            } else if (getEnvStat == JNI_EVERSION) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported");
-            }
-
-            // save C++ ocheaderoption ptr now
-            jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "<init>", "(J)V");
-            int size = headerOptions.size();
-            jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0);
-            for (int n=0; n<size;n++) {
-                jobject jelem = env->NewObject(g_ocheaderoption_clazz, option_constructor, \
-                                            (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu",  (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                env->SetObjectArrayElement(joptions, n, jelem);
-                env->DeleteLocalRef(jelem);
-            }
-
-            // save C++ ocrepresentation ptr now
-            jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "<init>", "(J)V");
-            jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \
-                                    (jlong) reinterpret_cast<jlong>(&rep));
-            if(jrepresentation == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class");
-                return;
-            }
-
-            jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction);
-            if (cb_clazz == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class");
-            }
-
-            // Find Callback function
-            jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \
-                    "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;I)V");
-            if(cb_mid == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "onPost.Callback() is not defined in JAVA");
-                return;
-            }
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA PostCallback");
-            env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode);
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "postCB detach");
-            g_JavaVM->DetachCurrentThread();
-
-            }
-    );
-    return NULL;
-}
-
-JNIEXPORT jobject JNICALL jniOicObserve(JNIEnv *env, jobject jobj, jint jobservetype, jobject jattributeHandler)
-{
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "observe1() resource = %p\n", resource);
-
-    JNICallBackContext *callbackContext;
-    string key = (*resource)->uri() + "/OBSERVE";
-    std:map<std::string, JNICallBackContext*>::iterator iter = gJNICallBackContextList.find(key);
-    if(iter == gJNICallBackContextList.end()) {
-        gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler));
-        callbackContext = gJNICallBackContextList[key];
-        __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str());
-    }
-    else {
-        iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler);
-        callbackContext = iter->second;
-    }
-
-       OC::QueryParamsMap test;
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base observe()\n");
-
-    (*resource)->observe((OC::ObserveType) jobservetype, test,
-        [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode, const int seqNum)
-        {
-             JNIEnv * env;
-
-            // Attach to JavaVM
-            // double check it's all ok
-            int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6);
-            if (getEnvStat == JNI_EDETACHED) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached");
-                if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach");
-                }
-                else
-                    __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK");
-            } else if (getEnvStat == JNI_OK) {
-            //
-            } else if (getEnvStat == JNI_EVERSION) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported");
-            }
-
-            // save C++ ocheaderoption ptr now
-            jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "<init>", "(J)V");
-            int size = headerOptions.size();
-            jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0);
-            for (int n=0; n<size;n++) {
-                jobject jelem = env->NewObject(g_ocheaderoption_clazz, option_constructor, \
-                                            (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu",  (jlong) reinterpret_cast<jlong>(&headerOptions[n]));
-
-                env->SetObjectArrayElement(joptions, n, jelem);
-                env->DeleteLocalRef(jelem);
-            }
-
-            // save C++ ocrepresentation ptr now
-            jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "<init>", "(J)V");
-            jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \
-                                    (jlong) reinterpret_cast<jlong>(&rep));
-            if(jrepresentation == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class");
-                return;
-            }
-
-            jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction);
-            if (cb_clazz == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class");
-            }
-
-            // Find Callback function
-            jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \
-                    "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;II)V");
-            if(cb_mid == NULL) {
-                __android_log_print(ANDROID_LOG_ERROR, TAG, "onObserve.Callback() is not defined in JAVA");
-                return;
-            }
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA ObserveCallback");
-            env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode, seqNum);
-
-            __android_log_print(ANDROID_LOG_INFO, TAG, "observeCB detach");
-            g_JavaVM->DetachCurrentThread();
-
-        }
-    );
-    return NULL;
-}
-
-JNIEXPORT jobject JNICALL jniOicCancelObserve(JNIEnv *env, jobject jobj)
-{
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "cancelObserve1() resource = %p\n", resource);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base cancelObserve()\n");
-
-    (*resource)->cancelObserve();
-    return NULL;
-}
-
-JNIEXPORT jstring JNICALL uri(JNIEnv *env, jobject jobj)
-{
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "uri()");
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-    return env->NewStringUTF((*resource)->uri().c_str());
-}
-
-JNIEXPORT jstring JNICALL host(JNIEnv *env, jobject jobj)
-{
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "host()");
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-    return env->NewStringUTF((*resource)->host().c_str());
-}
-
-JNIEXPORT jobjectArray JNICALL getResourceTypes(JNIEnv *env, jobject jobj)
-{
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "getResourceTypes()");
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-
-    std::vector<std::string> resourceTypes = (*resource)->getResourceTypes();
-
-    int size = resourceTypes.size();
-    jclass clazz = env->FindClass("java/lang/String");
-    jobjectArray jresourceTypes = env->NewObjectArray(size, clazz, 0);
-
-    for (int n=0; n<size;n++) {
-        jstring jstr = env->NewStringUTF(resourceTypes[n].c_str());
-        env->SetObjectArrayElement(jresourceTypes, n, jstr);
-    }
-
-    return jresourceTypes;
-}
-
-JNIEXPORT jobjectArray JNICALL getResourceInterfaces(JNIEnv *env, jobject jobj)
-{
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "getResourceInterfaces()");
-    std::shared_ptr<OC::OCResource> *resource = getHandle<std::shared_ptr<OC::OCResource>>(env, jobj);
-
-    std::vector<std::string> resourceInterfaces = (*resource)->getResourceInterfaces();
-
-    int size = resourceInterfaces.size();
-    jclass clazz = env->FindClass("java/lang/String");
-    jobjectArray jresourceInterfaces = env->NewObjectArray(size, clazz, 0);
-
-    for (int n=0; n<size;n++) {
-        jstring jstr = env->NewStringUTF(resourceInterfaces[n].c_str());
-        env->SetObjectArrayElement(jresourceInterfaces, n, jstr);
-    }
-
-    return jresourceInterfaces;
-}
-
diff --git a/android/Base/app/jni/ocstack-jni.cpp b/android/Base/app/jni/ocstack-jni.cpp
deleted file mode 100644 (file)
index d9ae850..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocstack-jni.h"
-
-// Global map to maintain callback functions and ocresource
-// with key = URL + callback operation
-// e.g. key = /a/light/GET
-std::map<string, JNICallBackContext*> gJNICallBackContextList;
-
-JavaVM* g_JavaVM = NULL;
-
-jclass g_ocplatform_clazz;
-jclass g_ocresource_clazz;
-jclass g_ocheaderoption_clazz;
-jclass g_ocrepresentation_clazz;
-jclass g_platformcfg_clazz;
-
-static const char* TAG = "OCSTACK-JNI";
-
-static JNINativeMethod ocplatform_method_table[] = {
-  { "configure", "(Lorg/iotivity/base/PlatformConfig;)V", (void *) configure},
-  { "findResource", "(Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/AbstractFindCallback;)I", (void *) findResource }
-};
-
-static int ocplatform_method_table_size = sizeof(ocplatform_method_table) / sizeof(ocplatform_method_table[0]);
-
-static JNINativeMethod platformconfig_method_table[] = {
-  { "createNativeInstance", "(IILjava/lang/String;II)J", (void *) createNativeInstance },
-};
-
-static int platformconfig_method_table_size = sizeof(platformconfig_method_table) / sizeof(platformconfig_method_table[0]);
-
-static JNINativeMethod ocresource_method_table[] = {
-  { "get", "(Lorg/iotivity/base/AbstractGetCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicGet},
-
-  { "put", "(Lorg/iotivity/base/OCRepresentation;Lorg/iotivity/base/AbstractPutCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicPut},
-  { "post", "(Lorg/iotivity/base/OCRepresentation;Lorg/iotivity/base/AbstractPostCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicPost},
-  { "observe", "(ILorg/iotivity/base/AbstractObserveCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicObserve},
-  { "cancelObserve", "()Lorg/iotivity/base/OCStackResult;", (void *) jniOicCancelObserve},
-  { "uri", "()Ljava/lang/String;", (void *) uri},
-  { "host", "()Ljava/lang/String;", (void *) host},
-  { "getResourceTypes", "()[Ljava/lang/String;", (void *) getResourceTypes},
-  { "getResourceInterfaces", "()[Ljava/lang/String;", (void *) getResourceInterfaces},
-};
-
-static int ocresource_method_table_size = sizeof(ocresource_method_table) / sizeof(ocresource_method_table[0]);
-
-static JNINativeMethod ocheaderoption_method_table[] = {
-  { "getOptionID", "()I", (void *) getOptionID},
-  { "getOptionData", "()Ljava/lang/String;", (void *) getOptionData},
-  { "OCHeaderOptionConstructor", "(ILjava/lang/String;)J", (void *) OCHeaderOptionConstructor},
-};
-
-static int ocheaderoption_method_table_size = sizeof(ocheaderoption_method_table) / sizeof(ocheaderoption_method_table[0]);
-
-static JNINativeMethod ocrepresentation_method_table[] = {
-  { "OCRepresentationConstructor", "()J", (void *) OCRepresentationConstructor},
-  { "getUri", "()Ljava/lang/String;", (void *) getUri},
-  { "getValueInt", "(Ljava/lang/String;)I", (void *) getValueInt},
-  { "getValueBool", "(Ljava/lang/String;)Z", (void *) getValueBool},
-  { "getValueString", "(Ljava/lang/String;)Ljava/lang/String;", (void *) getValueString},
-  { "setValueInt", "(Ljava/lang/String;I)V", (void *) setValueInt},
-  { "setValueBool", "(Ljava/lang/String;Z)V", (void *) setValueBool},
-  { "setValueString", "(Ljava/lang/String;Ljava/lang/String;)V", (void *) setValueString},
-  { "hasAttribute", "(Ljava/lang/String;)Z", (void *) hasAttribute},
-};
-
-static int ocrepresentation_method_table_size = sizeof(ocrepresentation_method_table) / sizeof(ocrepresentation_method_table[0]);
-
-// JNI OnLoad
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
-{
-  JNIEnv* env;
-
-  g_JavaVM = vm;
-  __android_log_print(ANDROID_LOG_ERROR, TAG, "g_JavaVM = %p\n", g_JavaVM);
-
-  if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
-    return JNI_ERR;
-  } else {
-    jint ret;
-    jclass clazz;
-
-    clazz = env->FindClass("org/iotivity/base/OCPlatform");
-    g_ocplatform_clazz = (jclass) env->NewGlobalRef(clazz);
-    env->DeleteLocalRef(clazz);
-    ret = env->RegisterNatives(g_ocplatform_clazz, ocplatform_method_table, ocplatform_method_table_size);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocplatform = %d\n", ret);
-
-    clazz = env->FindClass("org/iotivity/base/OCResource");
-    g_ocresource_clazz = (jclass) env->NewGlobalRef(clazz);
-    env->DeleteLocalRef(clazz);
-    ret = env->RegisterNatives(g_ocresource_clazz, ocresource_method_table, ocresource_method_table_size);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocresource = %d\n", ret);
-
-    clazz = env->FindClass("org/iotivity/base/PlatformConfig");
-    g_platformcfg_clazz = (jclass) env->NewGlobalRef(clazz);
-    env->DeleteLocalRef(clazz);
-    ret = env->RegisterNatives(g_platformcfg_clazz, platformconfig_method_table, platformconfig_method_table_size);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "load platformconfig = %d\n", ret);
-
-    clazz = env->FindClass("org/iotivity/base/OCHeaderOption");
-    g_ocheaderoption_clazz = (jclass) env->NewGlobalRef(clazz);
-    env->DeleteLocalRef(clazz);
-    ret = env->RegisterNatives(g_ocheaderoption_clazz, ocheaderoption_method_table, ocheaderoption_method_table_size);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocheaderoption = %d\n", ret);
-
-    clazz = env->FindClass("org/iotivity/base/OCRepresentation");
-    g_ocrepresentation_clazz = (jclass) env->NewGlobalRef(clazz);
-    env->DeleteLocalRef(clazz);
-    ret = env->RegisterNatives(g_ocrepresentation_clazz, ocrepresentation_method_table, ocrepresentation_method_table_size);
-    __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocrepresentation = %d\n", ret);
-
-    return JNI_VERSION_1_6;
-  }
-}
diff --git a/android/Base/app/jni/ocstack-jni.h b/android/Base/app/jni/ocstack-jni.h
deleted file mode 100644 (file)
index dd55aa4..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef _Included_org_iotivity_base_ocstack
-#define _Included_org_iotivity_base_ocstack
-
-#include <jni.h>
-#include <android/log.h>
-#include "OCApi.h"
-#include "OCPlatform.h"
-
-class JNICallBackContext {
-    public:
-
-    std::shared_ptr<OC::OCResource> m_resource;
-    jobject m_callBackFunction;
-
-    JNICallBackContext(jobject callback) {
-        m_resource = NULL;
-        m_callBackFunction = callback;
-    }
-
-    JNICallBackContext(std::shared_ptr<OC::OCResource> rsrc,
-        jobject callback) {
-        m_resource = rsrc;
-        m_callBackFunction = callback;
-    }
-};
-
-extern std::map<string, JNICallBackContext*> gJNICallBackContextList;
-
-extern JavaVM* g_JavaVM;
-
-extern jclass g_ocplatform_clazz;
-extern jclass g_ocresource_clazz;
-extern jclass g_ocheaderoption_clazz;
-extern jclass g_ocrepresentation_clazz;
-extern jclass g_platformcfg_clazz;
-
-template <typename T>
-T *getHandle(JNIEnv *env, jobject obj)
-{
-    jclass cls = env->GetObjectClass(obj);
-    jfieldID fid = env->GetFieldID(cls, "nativeHandle", "J");
-    jlong handle = env->GetLongField(obj, fid);
-    return reinterpret_cast<T *>(handle);
-}
-
-// ocplatform-jni
-extern JNIEXPORT void JNICALL configure(JNIEnv *env, jobject obj, jobject jcfg);
-extern JNIEXPORT jint JNICALL findResource(JNIEnv* env, jobject obj, jstring jhost, jstring juri, jobject found);
-
-// platformcfg-jni
-extern JNIEXPORT jlong JNICALL createNativeInstance
-  (JNIEnv *env, jobject obj, jint jServiceType, jint jModeType, jstring jIpAddress, jint port, jint jQOS);
-
-// ocheaderoption-jni
-extern JNIEXPORT jint JNICALL getOptionID(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jstring JNICALL getOptionData(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jlong JNICALL OCHeaderOptionConstructor(JNIEnv *env, jobject jobj, jint joption, jstring jdata);
-
-// ocrepresentation-jni
-extern JNIEXPORT jlong JNICALL OCRepresentationConstructor(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jstring JNICALL getUri(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jint JNICALL getValueInt(JNIEnv *env, jobject jobj, jstring jstr);
-extern JNIEXPORT jboolean JNICALL getValueBool(JNIEnv *env, jobject jobj, jstring jstr);
-extern JNIEXPORT jstring JNICALL getValueString(JNIEnv *env, jobject jobj, jstring jstr);
-extern JNIEXPORT void JNICALL setValueInt(JNIEnv *env, jobject jobj, jstring jstr, jint jval);
-extern JNIEXPORT void JNICALL setValueBool(JNIEnv *env, jobject jobj, jstring jstr, jboolean jval);
-extern JNIEXPORT void JNICALL setValueString(JNIEnv *env, jobject jobj, jstring jstr, jstring jval);
-extern JNIEXPORT jboolean JNICALL hasAttribute(JNIEnv *env, jobject jobj, jstring jstr);
-
-// ocresource-jni
-extern JNIEXPORT jobject JNICALL jniOicGet(JNIEnv *env, jobject jobj, jobject jattributeHandler);
-extern JNIEXPORT jobject JNICALL jniOicPut(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler);
-extern JNIEXPORT jobject JNICALL jniOicPost(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler);
-extern JNIEXPORT jobject JNICALL jniOicObserve(JNIEnv *env, jobject jobj, jint jobservetype, jobject jattributeHandler);
-extern JNIEXPORT jobject JNICALL jniOicCancelObserve(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jstring JNICALL uri(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jstring JNICALL host(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jobjectArray JNICALL getResourceTypes(JNIEnv *env, jobject jobj);
-extern JNIEXPORT jobjectArray JNICALL getResourceInterfaces(JNIEnv *env, jobject jobj);
-
-#endif
diff --git a/android/Base/app/jni/platformcfg-jni.cpp b/android/Base/app/jni/platformcfg-jni.cpp
deleted file mode 100644 (file)
index 73d40f9..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocstack-jni.h"
-
-static const char* TAG = "PLATFORMCFG-JNI";
-
-OC::ServiceType getServiceType(int type)
-{
-    switch (type) {
-        case 0:
-            return OC::ServiceType::InProc;
-        case 1:
-        default:
-            return OC::ServiceType::OutOfProc;
-    };
-}
-
-OC::ModeType getModeType(int type)
-{
-    switch (type) {
-        case 0:
-            return OC::ModeType::Server;
-        case 1:
-            return OC::ModeType::Client;
-        case 2:
-        default:
-            return OC::ModeType::Both;
-    };
-}
-
-OC::QualityOfService getQOS(int type)
-{
-    switch (type) {
-        case 0:
-            return OC::QualityOfService::LowQos;
-        case 1:
-            return OC::QualityOfService::MidQos;
-        case 2:
-            return OC::QualityOfService::HighQos;
-        case 3:
-        default:
-            return OC::QualityOfService::NaQos;
-    };
-}
-
-OC::PlatformConfig *g_cfg;
-
-JNIEXPORT jlong JNICALL createNativeInstance
-  (JNIEnv *env, jobject obj, jint jServiceType, jint jModeType, jstring jIpAddress, jint port, jint jQOS)
-{
-
-    g_cfg = new OC::PlatformConfig{getServiceType(jServiceType),
-                            getModeType(jModeType),
-                            env->GetStringUTFChars(jIpAddress, 0),
-                            (uint16_t) port,
-                            getQOS(jQOS)
-    };
-
-
-    jlong instptr = reinterpret_cast<jlong>(g_cfg);
-    return instptr;
-}
diff --git a/android/Base/app/proguard-rules.pro b/android/Base/app/proguard-rules.pro
deleted file mode 100644 (file)
index 0e559b0..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in /home/vchen/ubuntu_sw/adt-bundle-linux-x86_64/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-#   http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-#   public *;
-#}
diff --git a/android/Base/app/src/androidTest/java/org/iotivity/base/ApplicationTest.java b/android/Base/app/src/androidTest/java/org/iotivity/base/ApplicationTest.java
deleted file mode 100644 (file)
index ac4bdc3..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-import android.app.Application;
-import android.test.ApplicationTestCase;
-
-/**
- * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
- */
-public class ApplicationTest extends ApplicationTestCase<Application> {
-    public ApplicationTest() {
-        super(Application.class);
-    }
-}
diff --git a/android/Base/app/src/main/AndroidManifest.xml b/android/Base/app/src/main/AndroidManifest.xml
deleted file mode 100644 (file)
index 32cf1c1..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="org.iotivity.base">
-
-    <application android:allowBackup="true"
-        android:label="@string/app_name"
-        android:icon="@drawable/ic_launcher"
-        android:theme="@style/AppTheme">
-
-    </application>
-
-</manifest>
diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractDeleteCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractDeleteCallback.java
deleted file mode 100644 (file)
index d1c26b4..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public abstract class AbstractDeleteCallback {
-    public abstract void Callback(OCHeaderOption options, int a);
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractFindCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractFindCallback.java
deleted file mode 100644 (file)
index 132b1a8..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public abstract class AbstractFindCallback {
-    public abstract void Callback(OCResource resource);
-//    public OCResource ocresource = new OCResource();
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractGetCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractGetCallback.java
deleted file mode 100644 (file)
index 6ba339b..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public abstract class AbstractGetCallback {
-    public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a);
-//    public OCHeaderOption[] ocoptions;
-//    public OCRepresentation ocrep = new OCRepresentation();
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractObserveCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractObserveCallback.java
deleted file mode 100644 (file)
index 6c90561..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public abstract class AbstractObserveCallback {
-    public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a, int b);
-//    public OCHeaderOption[] ocoptions;
-//    public OCRepresentation ocrep = new OCRepresentation();
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractPostCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractPostCallback.java
deleted file mode 100644 (file)
index 20acbea..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public abstract class AbstractPostCallback {
-    public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a);
-//    public OCHeaderOption[] ocoptions;
-//    public OCRepresentation ocrep = new OCRepresentation();
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractPutCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractPutCallback.java
deleted file mode 100644 (file)
index 46f2a19..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.iotivity.base;
-
-public abstract class AbstractPutCallback {
-    public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a);
-//    public OCHeaderOption[] ocoptions;
-//    public OCRepresentation ocrep = new OCRepresentation();
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractSubscriberCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractSubscriberCallback.java
deleted file mode 100644 (file)
index 1f996cb..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public abstract class AbstractSubscriberCallback {
-    public abstract void Callback(OCStackResult result, int a);
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/EntityHandler.java b/android/Base/app/src/main/java/org/iotivity/base/EntityHandler.java
deleted file mode 100644 (file)
index 779543c..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public interface EntityHandler {
-    public abstract void Callback(OCResourceRequest request, OCResourceResponse response);
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/NativeInstance.java b/android/Base/app/src/main/java/org/iotivity/base/NativeInstance.java
deleted file mode 100644 (file)
index f6d02bb..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public abstract class NativeInstance
-{
-    protected long nativeHandle = 0;
-
-    public NativeInstance()
-    {
-    }
-
-    public long getHandle() { return nativeHandle;}
-
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCHeaderOption.java b/android/Base/app/src/main/java/org/iotivity/base/OCHeaderOption.java
deleted file mode 100644 (file)
index c169870..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class OCHeaderOption extends NativeInstance {
-    final private static String TAG = "OCHeaderOption";
-    static {
-        System.loadLibrary("ocstack-jni");
-    }
-
-    public OCHeaderOption(long instPtr) {
-        super.nativeHandle = instPtr;
-    }
-
-    public native int getOptionID();
-    public native String getOptionData();
-    public native long OCHeaderOptionConstructor(int optionID, String optionData);
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCPlatform.java b/android/Base/app/src/main/java/org/iotivity/base/OCPlatform.java
deleted file mode 100644 (file)
index e4424a6..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class OCPlatform {
-    final private static String TAG = "OCPlatform";
-    static {
-        System.loadLibrary("ocstack-jni");
-    }
-
-    public static native void configure(PlatformConfig cfg);
-    public static native int findResource(String host, String Uri, AbstractFindCallback found);
-
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCRepresentation.java b/android/Base/app/src/main/java/org/iotivity/base/OCRepresentation.java
deleted file mode 100644 (file)
index 06a2156..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class OCRepresentation extends NativeInstance {
-    final private static String TAG = "OCRepresentation";
-    static {
-        System.loadLibrary("ocstack-jni");
-    }
-
-    public OCRepresentation(long instPtr) {
-        super.nativeHandle = instPtr;
-    }
-    public OCRepresentation() {
-        super.nativeHandle = OCRepresentationConstructor();
-    }
-
-    public native long OCRepresentationConstructor();
-
-    public native int getValueInt(String str);
-    public native boolean getValueBool(String str);
-    public native String getValueString(String str);
-
-    public native void setValueInt (String str, int val);
-    public native void setValueBool (String str, boolean val);
-    public native void setValueString (String str, String val);
-
-    public native String getUri();
-
-    public native boolean hasAttribute(String str);
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCResource.java b/android/Base/app/src/main/java/org/iotivity/base/OCResource.java
deleted file mode 100644 (file)
index 7a7f6c8..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class OCResource extends NativeInstance {
-    final private static String TAG = "OCResource";
-    static {
-        System.loadLibrary("ocstack-jni");
-    }
-
-    public native OCStackResult get(AbstractGetCallback attributeHandler);
-//    public native OCStackResult get(AbstractGetCallback attributeHandler, PlatformConfig.QualityOfService QoS);
-
-    public native OCStackResult get(String resourceType, String resourceInterface, AbstractGetCallback attributeHandler);
-//    public native OCStackResult get(String resourceType, String resourceInterface, AbstractGetCallback attributeHandler, PlatformConfig.QualityOfService QoS);
-
-    public native OCStackResult put(OCRepresentation rep, AbstractPutCallback attributeHandler);
-//    public native OCStackResult put(OCRepresentation rep, AbstractPutCallback attributeHandler, PlatformConfig.QualityOfService QoS);
-//    public native OCStackResult put(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPutCallback attributeHandler);
-//    public native OCStackResult put(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPutCallback attributeHandler, PlatformConfig.QualityOfService QoS);
-
-    public native OCStackResult post(OCRepresentation rep, AbstractPostCallback attributeHandler);
-//    public native OCStackResult post(OCRepresentation rep, AbstractPostCallback attributeHandler, PlatformConfig.QualityOfService QoS);
-//    public native OCStackResult post(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPostCallback attributeHandler);
-//    public native OCStackResult post(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPostCallback attributeHandler, PlatformConfig.QualityOfService QoS);
-
-    public native OCStackResult observe(int observeType, AbstractObserveCallback observerHandler);
-//    public native OCStackResult observe(int observeType, AbstractObserveCallback observerHandler, PlatformConfig.QualityOfService QoS);
-
-    public native OCStackResult cancelObserve();
-//    public native OCStackResult cancelObserve(PlatformConfig.QualityOfService QoS);
-
-    public native String uri();
-    public native String host();
-
-    public native String[] getResourceInterfaces();
-    public native String[] getResourceTypes();
-
-    public OCResource(long instPtr) {
-        super.nativeHandle = instPtr;
-    }
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCResourceRequest.java b/android/Base/app/src/main/java/org/iotivity/base/OCResourceRequest.java
deleted file mode 100644 (file)
index 87c406e..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class OCResourceRequest {
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCResourceResponse.java b/android/Base/app/src/main/java/org/iotivity/base/OCResourceResponse.java
deleted file mode 100644 (file)
index 283d8de..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class OCResourceResponse {
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCStackResult.java b/android/Base/app/src/main/java/org/iotivity/base/OCStackResult.java
deleted file mode 100644 (file)
index 10440b6..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class OCStackResult {
-    /* Success status code - START HERE */
-    static final public int  OC_STACK_OK                    = 0;
-    static final public int  OC_STACK_RESOURCE_CREATED      = 1;
-    static final public int  OC_STACK_RESOURCE_DELETED      = 2;
-    /* Success status code - END HERE */
-    /* Error status code - START HERE */
-    static final public int  OC_STACK_INVALID_URI           = 3;
-    static final public int  OC_STACK_INVALID_QUERY         = 4;
-    static final public int  OC_STACK_INVALID_IP            = 5;
-    static final public int  OC_STACK_INVALID_PORT          = 6;
-    static final public int  OC_STACK_INVALID_CALLBACK      = 7;
-    static final public int  OC_STACK_INVALID_METHOD        = 8;
-    static final public int  OC_STACK_INVALID_PARAM         = 9;
-    static final public int  OC_STACK_INVALID_OBSERVE_PARAM = 10;
-    static final public int  OC_STACK_NO_MEMORY             = 11;
-    static final public int  OC_STACK_COMM_ERROR            = 12;
-    static final public int  OC_STACK_NOTIMPL               = 13;
-    static final public int  OC_STACK_NO_RESOURCE           = 14;               /* resource not found */
-    static final public int  OC_STACK_RESOURCE_ERROR        = 15;            /* ex: not supported method or interface */
-    static final public int  OC_STACK_SLOW_RESOURCE         = 16;
-    static final public int  OC_STACK_NO_OBSERVERS          = 17;              /* resource has no registered observers */
-    static final public int  OC_STACK_OBSERVER_NOT_FOUND    = 18;
-    static final public int  OC_STACK_OBSERVER_NOT_ADDED    = 19;
-    static final public int  OC_STACK_OBSERVER_NOT_REMOVED  = 20;
-    static final public int  OC_STACK_PRESENCE_STOPPED      = 21;
-    static final public int  OC_STACK_PRESENCE_DO_NOT_HANDLE = 22;
-    static final public int  OC_STACK_INVALID_OPTION        = 23;
-    static final public int  OC_STACK_MALFORMED_RESPONSE    = 24;        /* the remote reply contained malformed data */
-    static final public int  OC_STACK_ERROR                 = 25;
-    /* Error status code - END HERE */
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/ObserveType.java b/android/Base/app/src/main/java/org/iotivity/base/ObserveType.java
deleted file mode 100644 (file)
index f61c5d8..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class ObserveType {
-    static final public int Observe    = 0;
-    static final public int ObserveAll = 1;
-}
diff --git a/android/Base/app/src/main/java/org/iotivity/base/PlatformConfig.java b/android/Base/app/src/main/java/org/iotivity/base/PlatformConfig.java
deleted file mode 100755 (executable)
index 301cdde..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.base;
-
-public class PlatformConfig extends NativeInstance
-{
-    final private static String TAG = "PlatformConfig";
-    static {
-        System.loadLibrary("ocstack-jni");
-    }
-
-    // ENUM definition. Need to match with OCApi.h
-    public class ServiceType
-    {
-        static final public int INPROC  = 0;
-        static final public int OUTPROC = 1;
-    };
-
-    public class ModeType
-    {
-        static final public int SERVER = 0;
-        static final public int CLIENT = 1;
-        static final public int BOTH   = 2;
-
-    };
-
-    public class QualityOfService
-    {
-        static final public int LO_QOS  = 0;
-        static final public int ME_QOS  = 1;
-        static final public int HI_QOS  = 2;
-        static final public int NA_QOS  = 3;
-    }
-
-    public PlatformConfig(int serviceType,
-                          int mode,
-                          String ipAddress,
-                          int port,
-                          int QoS)
-    {
-        super.nativeHandle = createNativeInstance(serviceType, mode, ipAddress, port, QoS);
-    }
-   
-
-    protected native long createNativeInstance(int serviceType,
-             int mode,
-             String ipAddress,
-             int port,
-             int QoS);
-}
diff --git a/android/Base/app/src/main/res/values/strings.xml b/android/Base/app/src/main/res/values/strings.xml
deleted file mode 100644 (file)
index 73ef225..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<resources>
-    <string name="app_name">Base</string>
-</resources>
diff --git a/android/Base/app/src/main/res/values/styles.xml b/android/Base/app/src/main/res/values/styles.xml
deleted file mode 100644 (file)
index ff6c9d2..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<resources>
-
-    <!-- Base application theme. -->
-    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
-        <!-- Customize your theme here. -->
-    </style>
-
-</resources>
diff --git a/android/Base/build.gradle b/android/Base/build.gradle
deleted file mode 100644 (file)
index 9b8abe4..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
-    repositories {
-        jcenter()
-    }
-    dependencies {
-        classpath 'com.android.tools.build:gradle:0.12.2'
-
-        // NOTE: Do not place your application dependencies here; they belong
-        // in the individual module build.gradle files
-    }
-}
-
-allprojects {
-    repositories {
-        jcenter()
-    }
-}
diff --git a/android/Base/gradle.properties b/android/Base/gradle.properties
deleted file mode 100644 (file)
index 5d08ba7..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Settings specified in this file will override any Gradle settings
-# configured through the IDE.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
\ No newline at end of file
diff --git a/android/Base/gradlew b/android/Base/gradlew
deleted file mode 100755 (executable)
index 91a7e26..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-#!/usr/bin/env bash
-
-##############################################################################
-##
-##  Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
-    echo "$*"
-}
-
-die ( ) {
-    echo
-    echo "$*"
-    echo
-    exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
-  CYGWIN* )
-    cygwin=true
-    ;;
-  Darwin* )
-    darwin=true
-    ;;
-  MINGW* )
-    msys=true
-    ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
-    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
-    ls=`ls -ld "$PRG"`
-    link=`expr "$ls" : '.*-> \(.*\)$'`
-    if expr "$link" : '/.*' > /dev/null; then
-        PRG="$link"
-    else
-        PRG=`dirname "$PRG"`"/$link"
-    fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
-    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
-        # IBM's JDK on AIX uses strange locations for the executables
-        JAVACMD="$JAVA_HOME/jre/sh/java"
-    else
-        JAVACMD="$JAVA_HOME/bin/java"
-    fi
-    if [ ! -x "$JAVACMD" ] ; then
-        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-    fi
-else
-    JAVACMD="java"
-    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
-    MAX_FD_LIMIT=`ulimit -H -n`
-    if [ $? -eq 0 ] ; then
-        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
-            MAX_FD="$MAX_FD_LIMIT"
-        fi
-        ulimit -n $MAX_FD
-        if [ $? -ne 0 ] ; then
-            warn "Could not set maximum file descriptor limit: $MAX_FD"
-        fi
-    else
-        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
-    fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
-    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
-    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
-    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
-    # We build the pattern for arguments to be converted via cygpath
-    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
-    SEP=""
-    for dir in $ROOTDIRSRAW ; do
-        ROOTDIRS="$ROOTDIRS$SEP$dir"
-        SEP="|"
-    done
-    OURCYGPATTERN="(^($ROOTDIRS))"
-    # Add a user-defined pattern to the cygpath arguments
-    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
-        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
-    fi
-    # Now convert the arguments - kludge to limit ourselves to /bin/sh
-    i=0
-    for arg in "$@" ; do
-        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
-        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
-
-        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
-            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
-        else
-            eval `echo args$i`="\"$arg\""
-        fi
-        i=$((i+1))
-    done
-    case $i in
-        (0) set -- ;;
-        (1) set -- "$args0" ;;
-        (2) set -- "$args0" "$args1" ;;
-        (3) set -- "$args0" "$args1" "$args2" ;;
-        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
-        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
-        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
-        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
-        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
-        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
-    esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
-    JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/android/Base/settings.gradle b/android/Base/settings.gradle
deleted file mode 100644 (file)
index e7b4def..0000000
+++ /dev/null
@@ -1 +0,0 @@
-include ':app'
diff --git a/android/BuildInstructionsForAndroidAPI.txt b/android/BuildInstructionsForAndroidAPI.txt
new file mode 100644 (file)
index 0000000..8dda6db
--- /dev/null
@@ -0,0 +1,45 @@
+Build Instructions for Android-API:\r
+\r
+1.Verify that you have the latest JDK (you might need to set the JDK_HOME variable)\r
+2.Clone the latest iotivity codebase.\r
+3.set environment variables:\r
+    a.platform=android\r
+    b.If running in windows, change the following line in the build.gradle file (<iotivity>/android/android_api/base/build.gradle):\r
+        def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')\r
+            to\r
+        def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')\r
+\r
+4.Build scons for android and your targeted architecture (This will also build Android API):\r
+    a.scons TARGET_OS=android TARGET_ARCH=<target arch> TARGET_TRANSPORT=IP RELEASE=1 \r
+               where <target arch> can be armeabi, armeabi-v7a, x86.\r
+               Note: To build in debug mode, use RELEASE=0.\r
+               Note: The minimum SDK version supported is 21.\r
+               Note: Only TARGET_TRANSPORT currently supported is IP\r
+    b.If the project is setup correctly, you should see a BUILD SUCCESSFUL message on the terminal\r
+    c.You should see the .aar files generated inside of '<iotivity>/android/android_api/base/build/outputs/aar' directory. The .aar files contain jni directory and also a .jar file\r
+\r
+\r
+TO RUN UNIT TESTS IN ANDROID-API\r
+\r
+5.The '<iotivity>/android/android_api/base/src/androidTest/...' directory contains tests which can be used to get an idea about the Android API usage.\r
+\r
+\r
+TO USE THE .AAR FILE IN <iotivity>/android/examples project\r
+\r
+6. Verify that 9 different *.so files exist inside <iotivity>/android/android-api/base/libs/<TARGET_ARCH> directory. (They should already be present in the *.aar file.)\r
+7. Import Project 'Examples' into android-studio.\r
+8.To add an .aar file to the 'Examples' project,\r
+   a.Right click on Examples->New->Module->Import .JAR or .AAR Package\r
+   b.Select the .aar file from the location in step 6e above\r
+   c.Right click on Examples->Open Module Settings\r
+   d.Select each sample app module under 'Modules'->Dependencies->Add->Module Dependency\r
+   e.The .aar file selected in step 10b above should be present. Select it.\r
+   f.Repeat steps d and e for each sample app module.\r
+\r
+\r
+TO USE THE .AAR FILE IN A DIFFERENT PROJECT\r
+\r
+9. Verify that 9 different *.so files exist inside <iotivity base>/android/android-api/base/libs/<TARGET_ARCH> directory.\r
+10. Import the .aar file in your project to use it\r
+\r
+\r
diff --git a/android/SimpleClient/app/build.gradle b/android/SimpleClient/app/build.gradle
deleted file mode 100644 (file)
index bf753bf..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-apply plugin: 'com.android.application'
-
-android {
-    compileSdkVersion 20
-    buildToolsVersion "19.1.0"
-
-    defaultConfig {
-        applicationId "org.iotivity.simpleclient"
-        minSdkVersion 19
-        targetSdkVersion 20
-        versionCode 1
-        versionName "1.0"
-    }
-    buildTypes {
-        release {
-            runProguard false
-            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
-        }
-    }
-}
-
-dependencies {
-    compile fileTree(dir: 'libs', include: ['*.jar'])
-}
-
-repositories {
-    mavenCentral()
-    flatDir {
-        dirs 'libs'
-    }
-}
-
-
-dependencies {
-    compile fileTree(dir: 'libs', include: ['*.jar'])
-    compile fileTree(dir: 'libs', include: ['*.so'])
-    compile fileTree(dir: 'libs', include: ['**/*.so'])
-//    compile(name: 'OicLib', ext:'aar')
-    compile 'org.iotivity.Base:app:1.0@aar'
-}
\ No newline at end of file
diff --git a/android/SimpleClient/app/proguard-rules.pro b/android/SimpleClient/app/proguard-rules.pro
deleted file mode 100644 (file)
index 0e559b0..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in /home/vchen/ubuntu_sw/adt-bundle-linux-x86_64/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-#   http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-#   public *;
-#}
diff --git a/android/SimpleClient/app/src/androidTest/java/org/iotivity/simpleclient/ApplicationTest.java b/android/SimpleClient/app/src/androidTest/java/org/iotivity/simpleclient/ApplicationTest.java
deleted file mode 100644 (file)
index a2b6778..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.app.Application;
-import android.test.ApplicationTestCase;
-
-/**
- * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
- */
-public class ApplicationTest extends ApplicationTestCase<Application> {
-    public ApplicationTest() {
-        super(Application.class);
-    }
-}
diff --git a/android/SimpleClient/app/src/main/AndroidManifest.xml b/android/SimpleClient/app/src/main/AndroidManifest.xml
deleted file mode 100644 (file)
index 08329da..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="org.iotivity.simpleclient" >
-
-    <uses-permission android:name="android.permission.INTERNET" />
-
-    <application
-        android:allowBackup="true"
-        android:icon="@drawable/ic_launcher"
-        android:label="@string/app_name"
-        android:theme="@style/AppTheme" >
-        <activity
-            android:name=".SimpleClient"
-            android:label="@string/app_name" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-
-</manifest>
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/FoundResource.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/FoundResource.java
deleted file mode 100644 (file)
index cd558f4..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.util.Log;
-
-import org.iotivity.base.AbstractFindCallback;
-import org.iotivity.base.OCResource;
-
-public class FoundResource extends AbstractFindCallback {
-    final private static String TAG = "FoundResource";
-
-
-    public void Callback(OCResource resource) {
-
-        if(SimpleClient.curResource != null) {
-            Log.e(TAG, "Found another resource, ignoring");
-        }
-
-        String resourceURI;
-        String hostAddress;
-
-        if(resource != null) {
-            Log.i(TAG, "DISCOVERED Resource");
-
-            resourceURI = resource.uri();
-            Log.i(TAG, "URI of the resource: " + resourceURI);
-
-            hostAddress = resource.host();
-            Log.i(TAG, "Host address of the resource: " + hostAddress);
-
-            new SimpleToast().execute("URI of the resource: " + resourceURI + "\nHost address of the resource: " + hostAddress);
-
-            String[] resourceTypes = resource.getResourceTypes();
-            for(int i=0; i<resourceTypes.length; i++) {
-                Log.i(TAG, "[" + i + "] : " + resourceTypes[i]);
-            }
-
-            String[] resourceInterfaces = resource.getResourceInterfaces();
-            for(int i=0; i<resourceInterfaces.length; i++) {
-                Log.i(TAG, "[" + i + "] : " + resourceInterfaces[i]);
-            }
-
-            if(resourceURI.equals("/a/light")) {
-                SimpleClient.curResource = resource;
-                SimpleClient.getLightRepresentation(resource);
-            }
-        }
-        else {
-            Log.e(TAG, "Resource is invalid");
-        }
-    }
-
-}
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnGet.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnGet.java
deleted file mode 100644 (file)
index 428c65b..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.util.Log;
-
-import org.iotivity.base.AbstractGetCallback;
-import org.iotivity.base.OCHeaderOption;
-import org.iotivity.base.OCRepresentation;
-import org.iotivity.base.OCStackResult;
-
-public class OnGet extends AbstractGetCallback {
-    final private static String TAG = "OnGet";
-    public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode) {
-        if(eCode == OCStackResult.OC_STACK_OK) {
-
-            Log.i(TAG, "GET request was successful");
-            Log.i(TAG, "Resource URI : " + rep.getUri());
-
-            SimpleClient.mylight.m_state = rep.getValueBool("state");
-            Log.i(TAG, "state : " + SimpleClient.mylight.m_state);
-            SimpleClient.mylight.m_power = rep.getValueInt("power");
-            Log.i(TAG, "power : " + SimpleClient.mylight.m_power);
-            SimpleClient.mylight.m_name = rep.getValueString("name");
-            Log.i(TAG, "name  : " + SimpleClient.mylight.m_name);
-
-            new SimpleToast().execute(
-                    "state : " + SimpleClient.mylight.m_state +
-                            "\npower : " + SimpleClient.mylight.m_power +
-                            "\nname  : " + SimpleClient.mylight.m_name
-            );
-
-            SimpleClient.putLightRepresentation(SimpleClient.curResource);
-        }
-        else {
-           Log.e(TAG, "onGet Response error : " + eCode);
-        }
-    }
-
-}
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnObserve.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnObserve.java
deleted file mode 100644 (file)
index 5a06cbc..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.util.Log;
-
-import org.iotivity.base.AbstractObserveCallback;
-import org.iotivity.base.OCHeaderOption;
-import org.iotivity.base.OCRepresentation;
-import org.iotivity.base.OCStackResult;
-
-public class OnObserve extends AbstractObserveCallback {
-    final private static String TAG = "OnObserve";
-
-    public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode, int seqNum) {
-        if(eCode == OCStackResult.OC_STACK_OK) {
-            {
-                Log.i(TAG, "OBSERVE RESULT :");
-                Log.i(TAG, "SequenceNumber : " + seqNum);
-
-                SimpleClient.mylight.m_state = rep.getValueBool("state");
-                Log.i(TAG, "state : " + SimpleClient.mylight.m_state);
-                SimpleClient.mylight.m_power = rep.getValueInt("power");
-                Log.i(TAG, "power : " + SimpleClient.mylight.m_power);
-                SimpleClient.mylight.m_name = rep.getValueString("name");
-                Log.i(TAG, "name  : " + SimpleClient.mylight.m_name);
-
-                new SimpleToast().execute(
-                        "state : " + SimpleClient.mylight.m_state +
-                                "\npower : " + SimpleClient.mylight.m_power +
-                                "\nname  : " + SimpleClient.mylight.m_name
-                );
-
-                if(SimpleClient.observe_count() > 5) {
-                    Log.i(TAG, "Cancelling Observe ...");
-                    OCStackResult result = SimpleClient.curResource.cancelObserve();
-                    Log.i(TAG, "Cancel result : " + result);
-                    try {
-                        Thread.sleep(10000); // 10 sec
-                    } catch (InterruptedException e) {
-                        // TODO Auto-generated catch block
-                        e.printStackTrace();
-                    }
-                    Log.i(TAG, "DONE");
-                    new SimpleToast().execute(
-                            "DONE"
-                    );
-                }
-
-            }
-        }
-        else {
-            Log.e(TAG, "onPut Response error : " + eCode);
-        }
-
-    }
-}
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost.java
deleted file mode 100644 (file)
index ca7e1ae..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.util.Log;
-
-import org.iotivity.base.AbstractPostCallback;
-import org.iotivity.base.OCHeaderOption;
-import org.iotivity.base.OCRepresentation;
-
-public class OnPost extends AbstractPostCallback {
-
-    final private static String TAG = "OnPost";
-
-    public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode) {
-//FIXME : Need to check why ocstack is returning error code 28 to us after 12/6/14 rebase
-//        if(eCode == OCStackResult.OC_STACK_OK || eCode == OCStackResult.OC_STACK_RESOURCE_CREATED) {
-        if(true) {
-                Log.i(TAG, "POST request was successful");
-
-            if(rep.hasAttribute("createduri")) {
-                Log.i(TAG, "Uri of the created resource : " + rep.getValueString("createduri"));
-            }
-            else {
-                SimpleClient.mylight.m_state = rep.getValueBool("state");
-                Log.i(TAG, "state : " + SimpleClient.mylight.m_state);
-                SimpleClient.mylight.m_power = rep.getValueInt("power");
-                Log.i(TAG, "power : " + SimpleClient.mylight.m_power);
-                SimpleClient.mylight.m_name = rep.getValueString("name");
-                Log.i(TAG, "name  : " + SimpleClient.mylight.m_name);
-
-                new SimpleToast().execute(
-                        "state : " + SimpleClient.mylight.m_state +
-                                "\npower : " + SimpleClient.mylight.m_power +
-                                "\nname  : " + SimpleClient.mylight.m_name
-                );
-            }
-
-            OCRepresentation rep2 = new OCRepresentation();
-
-            Log.e(TAG, "Posting Light Representation ...");
-
-            SimpleClient.mylight.m_state = true;
-            SimpleClient.mylight.m_power = 55;
-
-            Log.i(TAG, "setValueBool : " + SimpleClient.mylight.m_state);
-            Log.i(TAG, "setValueInt  : " + SimpleClient.mylight.m_power);
-            rep2.setValueBool("state", SimpleClient.mylight.m_state);
-            rep2.setValueInt("power", SimpleClient.mylight.m_power);
-
-            OnPost2 onPost2 = new OnPost2();
-            SimpleClient.curResource.post(rep2, onPost2);
-        }
-        else {
-            Log.e(TAG, "onPost Response error : " + eCode);
-        }
-
-    }
-}
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost2.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost2.java
deleted file mode 100644 (file)
index cfc6ae6..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.util.Log;
-
-import org.iotivity.base.AbstractPostCallback;
-import org.iotivity.base.OCHeaderOption;
-import org.iotivity.base.OCRepresentation;
-import org.iotivity.base.OCStackResult;
-import org.iotivity.base.ObserveType;
-
-public class OnPost2 extends AbstractPostCallback {
-
-    final private static String TAG = "OnPost2";
-
-    public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode) {
-//FIXME : Need to check why ocstack is returning error code 28 to us after 12/6/14 rebase
-//        if(eCode == OCStackResult.OC_STACK_OK || eCode == OCStackResult.OC_STACK_RESOURCE_CREATED) {
-        if(true) {
-
-            Log.i(TAG, "POST2 request was successful");
-
-            if(rep.hasAttribute("createduri")) {
-                String createdUri =  rep.getValueString("createduri");
-                Log.i(TAG, "Uri of the created resource : " + createdUri); // FIXME
-                new SimpleToast().execute(
-                        "Uri of the created resource : " + createdUri
-                );
-            }
-            else {
-                SimpleClient.mylight.m_state = rep.getValueBool("state");
-                Log.i(TAG, "state : " + SimpleClient.mylight.m_state);
-                SimpleClient.mylight.m_power = rep.getValueInt("power");
-                Log.i(TAG, "power : " + SimpleClient.mylight.m_power);
-                SimpleClient.mylight.m_name = rep.getValueString("name");
-                Log.i(TAG, "name  : " + SimpleClient.mylight.m_name);
-                new SimpleToast().execute(
-                        "state : " + SimpleClient.mylight.m_state +
-                                "\npower : " + SimpleClient.mylight.m_power +
-                                "\nname  : " + SimpleClient.mylight.m_name
-                );
-            }
-
-            if(SimpleClient.OBSERVE_TYPE_TO_USE == ObserveType.Observe)
-                Log.i(TAG, "Observe is used");
-            else if(SimpleClient.OBSERVE_TYPE_TO_USE == ObserveType.ObserveAll)
-                Log.i(TAG, "ObserveAll is used");
-
-            OnObserve onObserve = new OnObserve();
-            SimpleClient.curResource.observe(SimpleClient.OBSERVE_TYPE_TO_USE, onObserve);
-        }
-        else {
-            Log.e(TAG, "onPost Response error : " + eCode);
-        }
-    }
-}
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPut.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPut.java
deleted file mode 100644 (file)
index fa8410c..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.util.Log;
-
-import org.iotivity.base.AbstractPutCallback;
-import org.iotivity.base.OCHeaderOption;
-import org.iotivity.base.OCRepresentation;
-import org.iotivity.base.OCStackResult;
-
-public class OnPut extends AbstractPutCallback {
-
-    final private static String TAG = "OnGet";
-
-    public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode) {
-        if(eCode == OCStackResult.OC_STACK_OK) {
-            {
-                Log.i(TAG, "PUT request was successful");
-
-                SimpleClient.mylight.m_state = rep.getValueBool("state");
-                Log.i(TAG, "state : " + SimpleClient.mylight.m_state);
-                SimpleClient.mylight.m_power = rep.getValueInt("power");
-                Log.i(TAG, "power : " + SimpleClient.mylight.m_power);
-                SimpleClient.mylight.m_name = rep.getValueString("name");
-                Log.i(TAG, "name  : " + SimpleClient.mylight.m_name);
-                new SimpleToast().execute(
-                        "state : " + SimpleClient.mylight.m_state +
-                        "\npower : " + SimpleClient.mylight.m_power +
-                        "\nname  : " + SimpleClient.mylight.m_name
-                );
-
-                SimpleClient.postLightRepresentation(SimpleClient.curResource);
-            }
-        }
-        else {
-            Log.e(TAG, "onPut Response error : " + eCode);
-        }
-
-    }
-}
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleClient.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleClient.java
deleted file mode 100644 (file)
index 7413ca2..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-
-import org.iotivity.base.OCPlatform;
-import org.iotivity.base.OCRepresentation;
-import org.iotivity.base.OCResource;
-import org.iotivity.base.ObserveType;
-import org.iotivity.base.PlatformConfig;
-
-
-public class SimpleClient extends Activity {
-    final private static String TAG = "SimpleClient";
-
-    class Light {
-        public boolean m_state;
-        public int m_power;
-        public String m_name;
-
-        public Light() {
-            m_state = false;
-            m_power = 0;
-            m_name = "vincent";
-        }
-    }
-
-    static int OBSERVE_TYPE_TO_USE = ObserveType.Observe;
-
-    public static Light mylight;
-    public static OCResource curResource;
-    static int oc = 0;
-    static Activity mActivity;
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        mActivity = this;
-
-        mylight = new Light();
-
-               PlatformConfig cfg = new PlatformConfig(PlatformConfig.ServiceType.INPROC,
-                                                               PlatformConfig.ModeType.CLIENT,
-                                                               "0.0.0.0",
-                                                               0,
-                                                               PlatformConfig.QualityOfService.LO_QOS);
-
-        OCPlatform.configure(cfg);
-        FoundResource foundResource = new FoundResource();
-        OCPlatform.findResource("", "coap://224.0.1.187/oc/core?rt=core.light", foundResource);
-
-        setContentView(R.layout.activity_simple_client);
-    }
-
-
-    @Override
-    public boolean onCreateOptionsMenu(Menu menu) {
-        // Inflate the menu; this adds items to the action bar if it is present.
-        getMenuInflater().inflate(R.menu.simple_client, menu);
-        return true;
-    }
-
-    @Override
-    public boolean onOptionsItemSelected(MenuItem item) {
-        // Handle action bar item clicks here. The action bar will
-        // automatically handle clicks on the Home/Up button, so long
-        // as you specify a parent activity in AndroidManifest.xml.
-        int id = item.getItemId();
-        if (id == R.id.action_settings) {
-            return true;
-        }
-        return super.onOptionsItemSelected(item);
-    }
-
-    protected static void getLightRepresentation(OCResource resource) {
-        if(resource != null) {
-            Log.e(TAG, "Getting Light Representation ...");
-
-            OnGet onGet = new OnGet();
-            resource.get(onGet);
-        }
-    }
-
-    protected static void putLightRepresentation(OCResource resource) {
-        if(resource != null) {
-
-            OCRepresentation rep = new OCRepresentation();
-
-            Log.e(TAG, "Putting Light Representation ...");
-
-            mylight.m_state = true;
-            mylight.m_power = 15;
-
-            Log.i(TAG, "setValueBool : " + SimpleClient.mylight.m_state);
-            Log.i(TAG, "setValueInt  : " + SimpleClient.mylight.m_power);
-            rep.setValueBool("state", mylight.m_state);
-            rep.setValueInt("power", mylight.m_power);
-
-            OnPut onPut = new OnPut();
-            resource.put(rep, onPut);
-        }
-    }
-
-    protected static void postLightRepresentation(OCResource resource) {
-        if(resource != null) {
-
-            OCRepresentation rep = new OCRepresentation();
-
-            Log.e(TAG, "Posting Light Representation ...");
-
-            mylight.m_state = false;
-            mylight.m_power = 105;
-
-            Log.i(TAG, "setValueBool : " + SimpleClient.mylight.m_state);
-            Log.i(TAG, "setValueInt  : " + SimpleClient.mylight.m_power);
-            rep.setValueBool("state", mylight.m_state);
-            rep.setValueInt("power", mylight.m_power);
-
-            OnPost onPost = new OnPost();
-            resource.post(rep, onPost);
-        }
-    }
-
-    protected static int observe_count() {
-        return ++oc;
-    }
-
-}
diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleToast.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleToast.java
deleted file mode 100644 (file)
index 8f7d672..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.simpleclient;
-
-import android.os.AsyncTask;
-import android.widget.Toast;
-
-public class SimpleToast extends AsyncTask<String, String, String> {
-    String toastMessage;
-
-    @Override
-    protected String doInBackground(String... params) {
-        toastMessage = params[0];
-        return toastMessage;
-    }
-
-    protected void OnProgressUpdate(String... values) {
-        super.onProgressUpdate(values);
-    }
-   // This is executed in the context of the main GUI thread
-    protected void onPostExecute(String result){
-           Toast toast = Toast.makeText(SimpleClient.mActivity, result, Toast.LENGTH_SHORT);
-           toast.show();
-    }
-
-}
diff --git a/android/SimpleClient/app/src/main/res/layout/activity_simple_client.xml b/android/SimpleClient/app/src/main/res/layout/activity_simple_client.xml
deleted file mode 100644 (file)
index f347f6c..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:paddingLeft="@dimen/activity_horizontal_margin"
-    android:paddingRight="@dimen/activity_horizontal_margin"
-    android:paddingTop="@dimen/activity_vertical_margin"
-    android:paddingBottom="@dimen/activity_vertical_margin"
-    tools:context=".SimpleClient">
-
-    <TextView
-        android:text="@string/hello_world"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content" />
-
-</RelativeLayout>
diff --git a/android/SimpleClient/app/src/main/res/menu/simple_client.xml b/android/SimpleClient/app/src/main/res/menu/simple_client.xml
deleted file mode 100644 (file)
index 1a65997..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    tools:context=".SimpleClient" >
-    <item android:id="@+id/action_settings"
-        android:title="@string/action_settings"
-        android:orderInCategory="100"
-        android:showAsAction="never" />
-</menu>
diff --git a/android/SimpleClient/app/src/main/res/values-w820dp/dimens.xml b/android/SimpleClient/app/src/main/res/values-w820dp/dimens.xml
deleted file mode 100644 (file)
index 63fc816..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-<resources>
-    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
-         (such as screen margins) for screens with more than 820dp of available width. This
-         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
-    <dimen name="activity_horizontal_margin">64dp</dimen>
-</resources>
diff --git a/android/SimpleClient/app/src/main/res/values/dimens.xml b/android/SimpleClient/app/src/main/res/values/dimens.xml
deleted file mode 100644 (file)
index 47c8224..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<resources>
-    <!-- Default screen margins, per the Android Design guidelines. -->
-    <dimen name="activity_horizontal_margin">16dp</dimen>
-    <dimen name="activity_vertical_margin">16dp</dimen>
-</resources>
diff --git a/android/SimpleClient/app/src/main/res/values/strings.xml b/android/SimpleClient/app/src/main/res/values/strings.xml
deleted file mode 100644 (file)
index 532e40d..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-
-    <string name="app_name">SimpleClient</string>
-    <string name="hello_world">Hello world!</string>
-    <string name="action_settings">Settings</string>
-
-</resources>
diff --git a/android/SimpleClient/app/src/main/res/values/styles.xml b/android/SimpleClient/app/src/main/res/values/styles.xml
deleted file mode 100644 (file)
index ff6c9d2..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<resources>
-
-    <!-- Base application theme. -->
-    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
-        <!-- Customize your theme here. -->
-    </style>
-
-</resources>
diff --git a/android/SimpleClient/build.gradle b/android/SimpleClient/build.gradle
deleted file mode 100644 (file)
index 9b8abe4..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
-    repositories {
-        jcenter()
-    }
-    dependencies {
-        classpath 'com.android.tools.build:gradle:0.12.2'
-
-        // NOTE: Do not place your application dependencies here; they belong
-        // in the individual module build.gradle files
-    }
-}
-
-allprojects {
-    repositories {
-        jcenter()
-    }
-}
diff --git a/android/SimpleClient/gradle.properties b/android/SimpleClient/gradle.properties
deleted file mode 100644 (file)
index 5d08ba7..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Settings specified in this file will override any Gradle settings
-# configured through the IDE.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
\ No newline at end of file
diff --git a/android/SimpleClient/gradlew b/android/SimpleClient/gradlew
deleted file mode 100755 (executable)
index 91a7e26..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-#!/usr/bin/env bash
-
-##############################################################################
-##
-##  Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
-    echo "$*"
-}
-
-die ( ) {
-    echo
-    echo "$*"
-    echo
-    exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
-  CYGWIN* )
-    cygwin=true
-    ;;
-  Darwin* )
-    darwin=true
-    ;;
-  MINGW* )
-    msys=true
-    ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
-    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
-    ls=`ls -ld "$PRG"`
-    link=`expr "$ls" : '.*-> \(.*\)$'`
-    if expr "$link" : '/.*' > /dev/null; then
-        PRG="$link"
-    else
-        PRG=`dirname "$PRG"`"/$link"
-    fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
-    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
-        # IBM's JDK on AIX uses strange locations for the executables
-        JAVACMD="$JAVA_HOME/jre/sh/java"
-    else
-        JAVACMD="$JAVA_HOME/bin/java"
-    fi
-    if [ ! -x "$JAVACMD" ] ; then
-        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-    fi
-else
-    JAVACMD="java"
-    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
-    MAX_FD_LIMIT=`ulimit -H -n`
-    if [ $? -eq 0 ] ; then
-        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
-            MAX_FD="$MAX_FD_LIMIT"
-        fi
-        ulimit -n $MAX_FD
-        if [ $? -ne 0 ] ; then
-            warn "Could not set maximum file descriptor limit: $MAX_FD"
-        fi
-    else
-        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
-    fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
-    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
-    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
-    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
-    # We build the pattern for arguments to be converted via cygpath
-    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
-    SEP=""
-    for dir in $ROOTDIRSRAW ; do
-        ROOTDIRS="$ROOTDIRS$SEP$dir"
-        SEP="|"
-    done
-    OURCYGPATTERN="(^($ROOTDIRS))"
-    # Add a user-defined pattern to the cygpath arguments
-    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
-        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
-    fi
-    # Now convert the arguments - kludge to limit ourselves to /bin/sh
-    i=0
-    for arg in "$@" ; do
-        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
-        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
-
-        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
-            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
-        else
-            eval `echo args$i`="\"$arg\""
-        fi
-        i=$((i+1))
-    done
-    case $i in
-        (0) set -- ;;
-        (1) set -- "$args0" ;;
-        (2) set -- "$args0" "$args1" ;;
-        (3) set -- "$args0" "$args1" "$args2" ;;
-        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
-        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
-        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
-        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
-        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
-        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
-    esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
-    JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/android/SimpleClient/settings.gradle b/android/SimpleClient/settings.gradle
deleted file mode 100644 (file)
index e7b4def..0000000
+++ /dev/null
@@ -1 +0,0 @@
-include ':app'
diff --git a/android/android_api/.gitignore b/android/android_api/.gitignore
new file mode 100644 (file)
index 0000000..e86e67c
--- /dev/null
@@ -0,0 +1,10 @@
+.gradle\r
+/local.properties\r
+/.idea/workspace.xml\r
+/.idea/libraries\r
+.DS_Store\r
+/build/*\r
+/base/build/*\r
+/base/obj/*\r
+/base/libs/*\r
+/sample/*\r
diff --git a/android/android_api/SConscript b/android/android_api/SConscript
new file mode 100644 (file)
index 0000000..2575c97
--- /dev/null
@@ -0,0 +1,48 @@
+import os\r
+import platform\r
+Import('env')\r
+\r
+android_home = env.get('ANDROID_HOME')\r
+\r
+ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')\r
+if env.get('RELEASE'):\r
+       ANDROID_RELEASE="release"\r
+else:\r
+       ANDROID_RELEASE="debug"\r
+\r
+os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')\r
+os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')\r
+\r
+if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):\r
+    print '''\r
+***************************************** Info ********************************\r
+*   Either 'Android API 21' is not installed or 'Android SDK Build Tools      *\r
+*   20.0.0' is not installed. The Android SDK Manager will now open. Please   *\r
+*   be sure to deselect all options, then select the following 2 packages:    *\r
+*       1. Under "Tools" select "Android SDK Build-tools" Revision 20.        *\r
+*       2. Under "Android 5.0.1 (API 21)" select "SDK Platform"               *\r
+*       3. Continue by selecting "Install 2 Packages"                         *\r
+*                                                                             *\r
+*   NOTE: If you have an http proxy, please press ctrl+c now and edit/create  *\r
+*         the following file in your $HOME directory as follows:              *\r
+*                                                                             *\r
+* Edit/Create file: "$HOME/.android/androidtool.cfg"                          *\r
+*                                                                             *\r
+*    http.proxyPort=<YOUR_PORT_NUMBER>                                        *\r
+*    sdkman.monitor.density=108                                               *\r
+*    http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS>                                 *\r
+*    sdkman.show.update.only=true                                             *\r
+*    sdkman.ask.adb.restart=false                                             *\r
+*    sdkman.force.http=true                                                   *\r
+*    sdkman.show.updateonly=true                                              *\r
+*                                                                             *\r
+*******************************************************************************\r
+\r
+...Opening Android SDK Manager now. Once you are finished, the build will continue.\r
+'''\r
+    os.system(android_home + '/tools/android')\r
+\r
+jdk_env = Environment(ENV=os.environ)\r
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE))\r
+jdk_env.Gradle(target="base/objs", source="base/src/main/java/org/iotivity/base/OcResource.java")\r
+\r
diff --git a/android/android_api/android_api.iml b/android/android_api/android_api.iml
new file mode 100755 (executable)
index 0000000..8d49284
--- /dev/null
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="java-gradle" name="Java-Gradle">\r
+      <configuration>\r
+        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="true">\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <excludeFolder url="file://$MODULE_DIR$/.gradle" />\r
+    </content>\r
+    <orderEntry type="inheritedJdk" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/android_api/base/.gitignore b/android/android_api/base/.gitignore
new file mode 100644 (file)
index 0000000..6e8872c
--- /dev/null
@@ -0,0 +1,5 @@
+.gradle/\r
+.idea/\r
+sample/\r
+base/build/\r
+base/obj/\r
diff --git a/android/android_api/base/base.iml b/android/android_api/base/base.iml
new file mode 100755 (executable)
index 0000000..36cf651
--- /dev/null
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="android_api" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="android-gradle" name="Android-Gradle">\r
+      <configuration>\r
+        <option name="GRADLE_PROJECT_PATH" value=":base" />\r
+      </configuration>\r
+    </facet>\r
+    <facet type="android" name="Android">\r
+      <configuration>\r
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
+        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
+        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="" />\r
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
+        <option name="LIBRARY_PROJECT" value="true" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="false">\r
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/native-libs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
+    </content>\r
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/android_api/base/build.gradle b/android/android_api/base/build.gradle
new file mode 100755 (executable)
index 0000000..9cbdaf8
--- /dev/null
@@ -0,0 +1,115 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+apply plugin: 'com.android.library'\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion "20.0.0"\r
+    archivesBaseName = "iotivity"\r
+\r
+    libraryVariants.all { variant ->\r
+        variant.outputs.each { output ->\r
+            def outputFile = output.outputFile\r
+            if (outputFile != null && outputFile.name.endsWith('.aar')) {\r
+                def fileName = "${archivesBaseName}-${TARGET_ARCH}-${outputFile.name}"\r
+                output.outputFile = new File(outputFile.parent, fileName)\r
+            }\r
+        }\r
+    }\r
+\r
+    defaultConfig {\r
+        minSdkVersion 21\r
+        targetSdkVersion 21\r
+        versionCode 1\r
+        versionName "0.9"\r
+    }\r
+    buildTypes {\r
+        release {\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+        }\r
+    }\r
+\r
+    lintOptions {\r
+       abortOnError false\r
+    }\r
+\r
+    sourceSets {\r
+        main {\r
+            manifest.srcFile 'src/main/AndroidManifest.xml'\r
+            jniLibs.srcDir 'libs'\r
+            jni.srcDirs = [] //disable automatic ndk-build call\r
+        }\r
+    }\r
+}\r
+\r
+\r
+dependencies {\r
+    compile fileTree(dir: 'libs', include: ['*.jar'])\r
+}\r
+\r
+////////////////\r
+////NDK Support\r
+////////////////\r
+//If using this, Android studio will fail run the following to set the environment variable for android studio:\r
+//launchctl setenv ANDROID_NDK_HOME /Users/boos_patrick/Development/Android/android-ndk-r8e\r
+//otherwise remove the dependsOn part and run ./gradlew buildNative from the command line\r
+\r
+task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {\r
+    dependsOn 'buildNative'\r
+    from(new File('libs')) { include '**/*.so' }\r
+    into new File(buildDir, 'native-libs')\r
+}\r
+\r
+tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }\r
+\r
+clean.dependsOn 'cleanCopyNativeLibs'\r
+\r
+tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->\r
+    pkgTask.jniFolders = new HashSet<File>()\r
+    pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))\r
+}\r
+\r
+task buildNative(type: Exec) {\r
+    if (System.env.ANDROID_NDK_HOME != null) {\r
+        //for windows use 'ndk-build.cmd'\r
+        //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')\r
+        def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')\r
+        commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE"\r
+    } else {\r
+        println '##################'\r
+        println 'Skipping NDK build'\r
+        println 'Reason: ANDROID_NDK_HOME not set.'\r
+        println '##################'\r
+    }\r
+}\r
+//\r
+//task (copyARR, type: Copy) {\r
+//    copy {\r
+//        from 'build/outputs/aar/'\r
+//        into '../../../out/android/'\r
+//        include '**/*.aar'\r
+//    }\r
+//}\r
+//build.finalizedBy(copyARR)\r
+\r
+\r
diff --git a/android/android_api/base/jni/Android.mk b/android/android_api/base/jni/Android.mk
new file mode 100644 (file)
index 0000000..aa2cbae
--- /dev/null
@@ -0,0 +1,78 @@
+LOCAL_PATH := $(call my-dir)\r
+TARGET_ARCH_ABI := $(APP_ABI)\r
+\r
+include $(CLEAR_VARS)\r
+OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
+LOCAL_MODULE := libandroid-oc_logger\r
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger.so\r
+include $(PREBUILT_SHARED_LIBRARY)\r
+\r
+include $(CLEAR_VARS)\r
+OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
+LOCAL_MODULE := libandroid-octbstack\r
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so\r
+include $(PREBUILT_SHARED_LIBRARY)\r
+\r
+include $(CLEAR_VARS)\r
+OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
+LOCAL_MODULE := libandroid-oc\r
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so\r
+include $(PREBUILT_SHARED_LIBRARY)\r
+\r
+include $(CLEAR_VARS)\r
+OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
+LOCAL_MODULE := libandroid-ca\r
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so\r
+include $(PREBUILT_SHARED_LIBRARY)\r
+\r
+include $(CLEAR_VARS)\r
+OIC_SRC_PATH := ../../../resource\r
+LOCAL_MODULE := libca-interface\r
+LOCAL_SRC_FILES := JniCaInterface.c\r
+LOCAL_STATIC_LIBRARIES := libandroid-ca\r
+LOCAL_LDLIBS := -llog\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/api\r
+include $(BUILD_SHARED_LIBRARY)\r
+\r
+include $(CLEAR_VARS)\r
+OIC_SRC_PATH := ../../../resource\r
+OIC_OUT_PATH := ../../../out\r
+LOCAL_MODULE    := ocstack-jni\r
+LOCAL_SRC_FILES :=  JniOcStack.cpp \\r
+                    JniUtils.cpp \\r
+                    JniEntityHandler.cpp \\r
+                    JniOnResourceFoundListener.cpp \\r
+                    JniOnDeviceInfoListener.cpp \\r
+                    JniOnPresenceListener.cpp \\r
+                    JniOnGetListener.cpp \\r
+                    JniOnPutListener.cpp \\r
+                    JniOnPostListener.cpp \\r
+                    JniOnDeleteListener.cpp \\r
+                    JniOnObserveListener.cpp \\r
+                    JniOcRepresentation.cpp \\r
+                    JniOcResourceHandle.cpp \\r
+                    JniOcPresenceHandle.cpp \\r
+                    JniOcRequestHandle.cpp \\r
+                    JniOcResourceRequest.cpp \\r
+                    JniOcResourceResponse.cpp \\r
+                    JniOcPlatform.cpp \\r
+                    JniOcResource.cpp \\r
+                    JniOcResourceIdentifier.cpp\r
+\r
+LOCAL_LDLIBS := -llog\r
+LOCAL_STATIC_LIBRARIES := android-oc\r
+LOCAL_STATIC_LIBRARIES += android-octbstack\r
+LOCAL_STATIC_LIBRARIES += android-coap\r
+LOCAL_STATIC_LIBRARIES += android-oc_logger\r
+LOCAL_STATIC_LIBRARIES += android-ca\r
+LOCAL_STATIC_LIBRARIES += android_cpp11_compat\r
+\r
+LOCAL_CPPFLAGS += -std=c++0x\r
+LOCAL_CPP_FEATURES := rtti exceptions\r
+LOCAL_C_INCLUDES := $(OIC_SRC_PATH)/include\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/stack/include\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/ocsocket/include\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/oc_logger/include\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../extlibs/boost/boost_1_58_0\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../build_common/android/compatibility\r
+include $(BUILD_SHARED_LIBRARY)\r
diff --git a/android/android_api/base/jni/Application.mk b/android/android_api/base/jni/Application.mk
new file mode 100644 (file)
index 0000000..089c9b3
--- /dev/null
@@ -0,0 +1,2 @@
+NDK_TOOLCHAIN_VERSION := 4.9\r
+APP_STL               := gnustl_shared
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniCaInterface.c b/android/android_api/base/jni/JniCaInterface.c
new file mode 100644 (file)
index 0000000..eb1e07a
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+* //******************************************************************
+* //
+* // Copyright 2015 Intel Corporation.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* //      http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+
+#include <jni.h>
+#include <android/log.h>
+#include <stdio.h>
+#include "cainterface.h"
+#include "JniCaInterface.h"
+
+#define  LOG_TAG   "JNI_CA_INTERFACE"
+#define  LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
+#define  LOGE(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
+
+JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
+{
+    LOGI("CaInterface_initialize");
+    CANativeJNISetJavaVM(jvm);
+
+    return JNI_VERSION_1_6;
+}
+
+void JNI_OnUnload(JavaVM *jvm, void *reserved)
+{
+    return;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_initialize
+(JNIEnv *env, jclass clazz, jobject context)
+{
+    LOGI("CaInterface_initialize");
+
+    CANativeJNISetContext(env, context);
+
+    CAResult_t res = CAInitialize();
+
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not Initialize");
+    }
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniCaInterface.h b/android/android_api/base/jni/JniCaInterface.h
new file mode 100644 (file)
index 0000000..ee77a97
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+* //******************************************************************
+* //
+* // Copyright 2015 Intel Corporation.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* //      http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include <jni.h>
+// THIS FILE IS SUBJECT TO CHANGE DUE TO THE ONGOING DEVELOPMENT OF THE CA FOR ANDROID
+// DO NOT REVIEW THIS FILE
+
+/* Header for class org_iotivity_ca_CaInterface */
+
+#ifndef _Included_org_iotivity_ca_CaInterface
+#define _Included_org_iotivity_ca_CaInterface
+#ifdef __cplusplus
+extern "C" {
+#endif
+    /*
+     * Class:     org_iotivity_ca_CaInterface_Initialize
+     * Method:    Initialize
+     * Signature: (Landroid/content/Context;)V
+     */
+    JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_initialize
+        (JNIEnv *, jclass, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniEntityHandler.cpp b/android/android_api/base/jni/JniEntityHandler.cpp
new file mode 100644 (file)
index 0000000..860d52b
--- /dev/null
@@ -0,0 +1,111 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniEntityHandler.h"\r
+#include "JniOcResourceRequest.h"\r
+#include "JniOcResourceResponse.h"\r
+#include "JniUtils.h"\r
+\r
+JniEntityHandler::JniEntityHandler(JNIEnv *env, jobject entityHandler)\r
+{\r
+    m_jListener = env->NewGlobalRef(entityHandler);\r
+}\r
+\r
+JniEntityHandler::~JniEntityHandler()\r
+{\r
+    LOGD("~JniEntityHandler");\r
+    if (m_jListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+        env->DeleteGlobalRef(m_jListener);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+OCEntityHandlerResult JniEntityHandler::handleEntity(const std::shared_ptr<OCResourceRequest> request)\r
+{\r
+    LOGD("JniEntityHandler_handleEntity");\r
+    jint envRet;\r
+    JNIEnv *env = GetJNIEnv(envRet);\r
+    if (NULL == env) return OC_EH_ERROR;\r
+\r
+    JniOcResourceRequest* jniResReq = new JniOcResourceRequest(request);\r
+    jlong reqHandle = reinterpret_cast<jlong>(jniResReq);\r
+    jobject jResourceRequest = env->NewObject(g_cls_OcResourceRequest, g_mid_OcResourceRequest_N_ctor,\r
+        reqHandle);\r
+    if (!jResourceRequest)\r
+    {\r
+        LOGE("Failed to create OcResourceRequest");\r
+        delete jniResReq;\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+\r
+    jclass clsL = env->GetObjectClass(m_jListener);\r
+    if (!clsL)\r
+    {\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+    jmethodID midL = env->GetMethodID(clsL, "handleEntity",\r
+        "(Lorg/iotivity/base/OcResourceRequest;)Lorg/iotivity/base/EntityHandlerResult;");\r
+    if (!midL)\r
+    {\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+    jobject entityHandlerResult = env->CallObjectMethod(m_jListener, midL, jResourceRequest);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+    if (!entityHandlerResult)\r
+    {\r
+        ThrowOcException(JNI_INVALID_VALUE, "EntityHandlerResult cannot be null");\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+    jclass clsResult = env->GetObjectClass(entityHandlerResult);\r
+    if (!clsResult)\r
+    {\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+    jmethodID getValue_ID = env->GetMethodID(clsResult, "getValue", "()I");\r
+    if (!getValue_ID)\r
+    {\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+    jint jResult = env->CallIntMethod(entityHandlerResult, getValue_ID);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Java exception is thrown");\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return OC_EH_ERROR;\r
+    }\r
+\r
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+    return JniUtils::getOCEntityHandlerResult(env, static_cast<int>(jResult));\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniEntityHandler.h b/android/android_api/base/jni/JniEntityHandler.h
new file mode 100644 (file)
index 0000000..8cf3373
--- /dev/null
@@ -0,0 +1,39 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_JniEntityHandler\r
+#define _Included_org_iotivity_base_JniEntityHandler\r
+\r
+class JniEntityHandler\r
+{\r
+public:\r
+    JniEntityHandler(JNIEnv *env, jobject listener);\r
+    ~JniEntityHandler();\r
+\r
+    OCEntityHandlerResult handleEntity(const std::shared_ptr<OC::OCResourceRequest> request);\r
+\r
+private:\r
+    jobject m_jListener;\r
+};\r
+\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniListenerManager.cpp b/android/android_api/base/jni/JniListenerManager.cpp
new file mode 100644 (file)
index 0000000..c9ccaa3
--- /dev/null
@@ -0,0 +1,103 @@
+///*\r
+//* //******************************************************************\r
+//* //\r
+//* // Copyright 2015 Intel Corporation.\r
+//* //\r
+//* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//* //\r
+//* // Licensed under the Apache License, Version 2.0 (the "License");\r
+//* // you may not use this file except in compliance with the License.\r
+//* // You may obtain a copy of the License at\r
+//* //\r
+//* //      http://www.apache.org/licenses/LICENSE-2.0\r
+//* //\r
+//* // Unless required by applicable law or agreed to in writing, software\r
+//* // distributed under the License is distributed on an "AS IS" BASIS,\r
+//* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+//* // See the License for the specific language governing permissions and\r
+//* // limitations under the License.\r
+//* //\r
+//* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//*/\r
+//\r
+//#include "JniListenerManager.h"\r
+//\r
+//#include "JniOnGetListener.h"\r
+//\r
+//template<class T>\r
+//T* JniListenerManager<T>::addListener(JNIEnv* env, jobject jListener)\r
+//{\r
+//     T *onEventListener = NULL;\r
+//\r
+//     m_mapMutex.lock();\r
+//\r
+//     for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)\r
+//     {\r
+//             if (env->IsSameObject(jListener, it->first))\r
+//             {\r
+//                     auto refPair = it->second;\r
+//                     onEventListener = refPair.first;\r
+//                     refPair.second++;\r
+//                     it->second = refPair;\r
+//                     m_listenerMap.insert(*it);\r
+//                     LOGD("OnEventListener: ref. count is incremented");\r
+//                     break;\r
+//             }\r
+//     }\r
+//\r
+//     if (!onEventListener)\r
+//     {\r
+//             onEventListener = new T(env, jListener, this);\r
+//             jobject jgListener = env->NewGlobalRef(jListener);\r
+//\r
+//             m_listenerMap.insert(std::pair<jobject, std::pair<T*, int>>(jgListener, std::pair<T*, int>(onEventListener, 1)));\r
+//             LOGD("OnEventListener: new listener");\r
+//     }\r
+//\r
+//     m_mapMutex.unlock();\r
+//\r
+//     return onEventListener;\r
+//}\r
+//\r
+//template<class T>\r
+//void JniListenerManager<T>::removeListener(JNIEnv* env, jobject jListener)\r
+//{\r
+//     m_mapMutex.lock();\r
+//\r
+//     bool isFound = false;\r
+//\r
+//     for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)\r
+//     {\r
+//             if (env->IsSameObject(jListener, it->first))\r
+//             {\r
+//                     auto refPair = it->second;\r
+//                     if (refPair.second > 1)\r
+//                     {\r
+//                             refPair.second--;\r
+//                             it->second = refPair;\r
+//                             m_listenerMap.insert(*it);\r
+//                             LOGI("OnEventListener: ref. count is decremented");\r
+//                     }\r
+//                     else\r
+//                     {\r
+//                             env->DeleteGlobalRef(it->first);\r
+//                             T* listener = refPair.first;\r
+//                             delete listener;\r
+//                             m_listenerMap.erase(it);\r
+//\r
+//                             LOGI("OnEventListener is removed");\r
+//                     }\r
+//\r
+//                     isFound = true;\r
+//                     break;\r
+//             }\r
+//     }\r
+//\r
+//     if (!isFound)\r
+//     {\r
+//             ThrowOcException(JNI_EXCEPTION, "OnEventListener isn't found");\r
+//     }\r
+//\r
+//     m_mapMutex.unlock();\r
+//}\r
+//\r
diff --git a/android/android_api/base/jni/JniListenerManager.h b/android/android_api/base/jni/JniListenerManager.h
new file mode 100644 (file)
index 0000000..a43ea82
--- /dev/null
@@ -0,0 +1,125 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+\r
+#include "JniOcStack.h"\r
+#include <mutex>\r
+\r
+#ifndef _JniListenerManager\r
+#define _JniListenerManager\r
+\r
+class JniOcResource;\r
+\r
+template <class T>\r
+class JniListenerManager\r
+{\r
+public:\r
+    T* addListener(JNIEnv* env, jobject jListener, JniOcResource* owner)\r
+    {\r
+        T *onEventListener = NULL;\r
+\r
+        m_mapMutex.lock();\r
+\r
+        for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)\r
+        {\r
+            if (env->IsSameObject(jListener, it->first))\r
+            {\r
+                auto refPair = it->second;\r
+                onEventListener = refPair.first;\r
+                refPair.second++;\r
+                it->second = refPair;\r
+                m_listenerMap.insert(*it);\r
+                LOGD("OnEventListener: ref. count is incremented");\r
+                break;\r
+            }\r
+        }\r
+        if (!onEventListener)\r
+        {\r
+            onEventListener = new T(env, jListener, owner);\r
+            jobject jgListener = env->NewGlobalRef(jListener);\r
+\r
+            if (jgListener)\r
+            {\r
+                m_listenerMap.insert(std::pair<jobject, std::pair<T*, int>>(jgListener, std::pair<T*, int>(onEventListener, 1)));\r
+            }\r
+            else\r
+            {\r
+                LOGD("OnEventListener: Failed to create global listener ref.");\r
+                delete onEventListener;\r
+            }\r
+            LOGD("OnEventListener: new listener");\r
+        }\r
+        m_mapMutex.unlock();\r
+        return onEventListener;\r
+    }\r
+\r
+    void removeListener(JNIEnv* env, jobject jListener)\r
+    {\r
+        m_mapMutex.lock();\r
+        for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)\r
+        {\r
+            if (env->IsSameObject(jListener, it->first))\r
+            {\r
+                auto refPair = it->second;\r
+                if (refPair.second > 1)\r
+                {\r
+                    refPair.second--;\r
+                    it->second = refPair;\r
+                    m_listenerMap.insert(*it);\r
+                    LOGI("OnEventListener: ref. count is decremented");\r
+                }\r
+                else\r
+                {\r
+                    env->DeleteGlobalRef(it->first);\r
+                    T* listener = refPair.first;\r
+                    delete listener;\r
+                    m_listenerMap.erase(it);\r
+\r
+                    LOGI("OnEventListener is removed");\r
+                }\r
+                break;\r
+            }\r
+        }\r
+        m_mapMutex.unlock();\r
+    }\r
+\r
+    void removeAllListeners(JNIEnv* env)\r
+    {\r
+        m_mapMutex.lock();\r
+\r
+        for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)\r
+        {\r
+            env->DeleteGlobalRef(it->first);\r
+            auto refPair = it->second;\r
+            T* listener = refPair.first;\r
+            delete listener;\r
+            m_listenerMap.erase(it);\r
+        }\r
+\r
+        m_mapMutex.unlock();\r
+    }\r
+\r
+private:\r
+    std::map<jobject, std::pair<T*, int>> m_listenerMap;\r
+    std::mutex m_mapMutex;\r
+};\r
+\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOcPlatform.cpp b/android/android_api/base/jni/JniOcPlatform.cpp
new file mode 100644 (file)
index 0000000..0a50d8e
--- /dev/null
@@ -0,0 +1,1591 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcPlatform.h"\r
+#include "OCPlatform.h"\r
+#include "JniOcResource.h"\r
+#include "JniOcResourceHandle.h"\r
+#include "JniOcPresenceHandle.h"\r
+#include "JniOcResourceResponse.h"\r
+#include "JniUtils.h"\r
+\r
+using namespace OC;\r
+\r
+JniOnResourceFoundListener* AddOnResourceFoundListener(JNIEnv* env, jobject jListener)\r
+{\r
+    JniOnResourceFoundListener *onResourceFoundListener = NULL;\r
+\r
+    resourceFoundMapLock.lock();\r
+\r
+    for (auto it = onResourceFoundListenerMap.begin(); it != onResourceFoundListenerMap.end(); ++it)\r
+    {\r
+        if (env->IsSameObject(jListener, it->first))\r
+        {\r
+            auto refPair = it->second;\r
+            onResourceFoundListener = refPair.first;\r
+            refPair.second++;\r
+            it->second = refPair;\r
+            onResourceFoundListenerMap.insert(*it);\r
+            LOGD("OnResourceFoundListener: ref. count incremented");\r
+            break;\r
+        }\r
+    }\r
+\r
+    if (!onResourceFoundListener)\r
+    {\r
+        onResourceFoundListener = new JniOnResourceFoundListener(env, jListener, RemoveOnResourceFoundListener);\r
+        jobject jgListener = env->NewGlobalRef(jListener);\r
+\r
+        onResourceFoundListenerMap.insert(std::pair < jobject, std::pair < JniOnResourceFoundListener*,\r
+            int >> (jgListener, std::pair<JniOnResourceFoundListener*, int>(onResourceFoundListener, 1)));\r
+        LOGD("OnResourceFoundListener: new listener");\r
+    }\r
+    resourceFoundMapLock.unlock();\r
+    return onResourceFoundListener;\r
+}\r
+\r
+void RemoveOnResourceFoundListener(JNIEnv* env, jobject jListener)\r
+{\r
+    resourceFoundMapLock.lock();\r
+\r
+    for (auto it = onResourceFoundListenerMap.begin(); it != onResourceFoundListenerMap.end(); ++it)\r
+    {\r
+        if (env->IsSameObject(jListener, it->first))\r
+        {\r
+            auto refPair = it->second;\r
+            if (refPair.second > 1)\r
+            {\r
+                refPair.second--;\r
+                it->second = refPair;\r
+                onResourceFoundListenerMap.insert(*it);\r
+                LOGI("OnResourceFoundListener: ref. count decremented");\r
+            }\r
+            else\r
+            {\r
+                env->DeleteGlobalRef(it->first);\r
+                JniOnResourceFoundListener* listener = refPair.first;\r
+                delete listener;\r
+                onResourceFoundListenerMap.erase(it);\r
+                LOGI("OnResourceFoundListener removed");\r
+            }\r
+            break;\r
+        }\r
+    }\r
+    resourceFoundMapLock.unlock();\r
+}\r
+\r
+JniOnDeviceInfoListener* AddOnDeviceInfoListener(JNIEnv* env, jobject jListener)\r
+{\r
+    JniOnDeviceInfoListener *onDeviceInfoListener = NULL;\r
+\r
+    deviceInfoMapLock.lock();\r
+\r
+    for (auto it = onDeviceInfoListenerMap.begin(); it != onDeviceInfoListenerMap.end(); ++it)\r
+    {\r
+        if (env->IsSameObject(jListener, it->first))\r
+        {\r
+            auto refPair = it->second;\r
+            onDeviceInfoListener = refPair.first;\r
+            refPair.second++;\r
+            it->second = refPair;\r
+            onDeviceInfoListenerMap.insert(*it);\r
+            LOGD("OnDeviceInfoListener: ref. count incremented");\r
+            break;\r
+        }\r
+    }\r
+\r
+    if (!onDeviceInfoListener)\r
+    {\r
+        onDeviceInfoListener = new JniOnDeviceInfoListener(env, jListener, RemoveOnDeviceInfoListener);\r
+        jobject jgListener = env->NewGlobalRef(jListener);\r
+\r
+        onDeviceInfoListenerMap.insert(std::pair < jobject, std::pair < JniOnDeviceInfoListener*,\r
+            int >> (jgListener, std::pair<JniOnDeviceInfoListener*, int>(onDeviceInfoListener, 1)));\r
+        LOGI("OnDeviceInfoListener: new listener");\r
+    }\r
+\r
+    deviceInfoMapLock.unlock();\r
+    return onDeviceInfoListener;\r
+}\r
+\r
+void RemoveOnDeviceInfoListener(JNIEnv* env, jobject jListener)\r
+{\r
+    deviceInfoMapLock.lock();\r
+    bool isFound = false;\r
+    for (auto it = onDeviceInfoListenerMap.begin(); it != onDeviceInfoListenerMap.end(); ++it)\r
+    {\r
+        if (env->IsSameObject(jListener, it->first))\r
+        {\r
+            auto refPair = it->second;\r
+            if (refPair.second > 1)\r
+            {\r
+                refPair.second--;\r
+                it->second = refPair;\r
+                onDeviceInfoListenerMap.insert(*it);\r
+                LOGI("OnDeviceInfoListener: ref. count decremented");\r
+            }\r
+            else\r
+            {\r
+                env->DeleteGlobalRef(it->first);\r
+                JniOnDeviceInfoListener* listener = refPair.first;\r
+                delete listener;\r
+                onDeviceInfoListenerMap.erase(it);\r
+\r
+                LOGI("OnDeviceInfoListener removed");\r
+            }\r
+\r
+            isFound = true;\r
+            break;\r
+        }\r
+    }\r
+\r
+    if (!isFound)\r
+    {\r
+        ThrowOcException(JNI_EXCEPTION, "OnDeviceInfoListenet not found");\r
+    }\r
+    deviceInfoMapLock.unlock();\r
+}\r
+\r
+JniOnPresenceListener* AddOnPresenceListener(JNIEnv* env, jobject jListener)\r
+{\r
+    JniOnPresenceListener *onPresenceListener = NULL;\r
+\r
+    presenceMapLock.lock();\r
+\r
+    for (auto it = onPresenceListenerMap.begin(); it != onPresenceListenerMap.end(); ++it)\r
+    {\r
+        if (env->IsSameObject(jListener, it->first))\r
+        {\r
+            auto refPair = it->second;\r
+            onPresenceListener = refPair.first;\r
+            refPair.second++;\r
+            it->second = refPair;\r
+            onPresenceListenerMap.insert(*it);\r
+            LOGD("OnPresenceListener: ref. count incremented");\r
+            break;\r
+        }\r
+    }\r
+    if (!onPresenceListener)\r
+    {\r
+        onPresenceListener = new JniOnPresenceListener(env, jListener, RemoveOnPresenceListener);\r
+        jobject jgListener = env->NewGlobalRef(jListener);\r
+        onPresenceListenerMap.insert(std::pair < jobject, std::pair < JniOnPresenceListener*,\r
+            int >> (jgListener, std::pair<JniOnPresenceListener*, int>(onPresenceListener, 1)));\r
+        LOGI("OnPresenceListener: new listener");\r
+    }\r
+    presenceMapLock.unlock();\r
+    return onPresenceListener;\r
+}\r
+\r
+void RemoveOnPresenceListener(JNIEnv* env, jobject jListener)\r
+{\r
+    presenceMapLock.lock();\r
+    bool isFound = false;\r
+    for (auto it = onPresenceListenerMap.begin(); it != onPresenceListenerMap.end(); ++it)\r
+    {\r
+        if (env->IsSameObject(jListener, it->first))\r
+        {\r
+            auto refPair = it->second;\r
+            if (refPair.second > 1)\r
+            {\r
+                refPair.second--;\r
+                it->second = refPair;\r
+                onPresenceListenerMap.insert(*it);\r
+                LOGI("OnPresenceListener: ref. count decremented");\r
+            }\r
+            else\r
+            {\r
+                env->DeleteGlobalRef(it->first);\r
+                JniOnPresenceListener* listener = refPair.first;\r
+                delete listener;\r
+                onPresenceListenerMap.erase(it);\r
+                LOGI("OnPresenceListener is removed");\r
+            }\r
+            isFound = true;\r
+            break;\r
+        }\r
+    }\r
+    if (!isFound)\r
+    {\r
+        ThrowOcException(JNI_EXCEPTION, "OnPresenceListener not found");\r
+    }\r
+    presenceMapLock.unlock();\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    configure\r
+* Signature: (IILjava/lang/String;II)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_configure\r
+(JNIEnv *env, jclass clazz, jint jServiceType, jint jModeType, jstring jIpAddress, jint jPort, jint jQOS)\r
+{\r
+    LOGI("OcPlatform_configure");\r
+\r
+    std::string ipAddress;\r
+    if (jIpAddress)\r
+    {\r
+        ipAddress = env->GetStringUTFChars(jIpAddress, NULL);\r
+    }\r
+    uint16_t port;\r
+    if (jPort > 0)\r
+    {\r
+        port = static_cast<uint16_t>(jPort);\r
+    }\r
+    PlatformConfig cfg{\r
+        JniUtils::getServiceType(env, jServiceType),\r
+        JniUtils::getModeType(env, jModeType),\r
+        ipAddress,\r
+        port,\r
+        JniUtils::getQOS(env, static_cast<int>(jQOS))\r
+    };\r
+\r
+    OCPlatform::Configure(cfg);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    notifyAllObservers0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers0\r
+(JNIEnv *env, jclass clazz, jobject jResourceHandle)\r
+{\r
+    LOGI("OcPlatform_notifyAllObservers");\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::notifyAllObservers(jniOcResourceHandle->getOCResourceHandle());\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to notify all observers");\r
+            return;\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    notifyAllObservers1\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers1\r
+(JNIEnv *env, jclass clazz, jobject jResourceHandle, jint jQoS)\r
+{\r
+    LOGI("OcPlatform_notifyAllObservers1");\r
+\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    try{\r
+        OCStackResult result = OCPlatform::notifyAllObservers(\r
+            jniOcResourceHandle->getOCResourceHandle(),\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to notify all observers");\r
+            return;\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    notifyListOfObservers2\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;[Ljava/lang/Byte;Lorg/iotivity/base/OcResourceResponse;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyListOfObservers2\r
+(JNIEnv *env, jclass clazz, jobject jResourceHandle, jbyteArray jObservationIdArr, jobject jResourceResponse)\r
+{\r
+    LOGD("OcPlatform_notifyListOfObservers2");\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+    if (!jObservationIdArr)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "observationIdList cannot be null");\r
+        return;\r
+    }\r
+    if (!jResourceResponse)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceResponse cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    JniOcResourceResponse* jniOcResourceResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(\r
+        env, jResourceResponse);\r
+    if (!jniOcResourceResponse) return;\r
+\r
+    int len = env->GetArrayLength(jObservationIdArr);\r
+    uint8_t* bArr = (uint8_t*)env->GetByteArrayElements(jObservationIdArr, 0);\r
+\r
+    ObservationIds observationIds;\r
+    for (int i = 0; i < len; ++i)\r
+    {\r
+        observationIds.push_back(bArr[i]);\r
+    }\r
+\r
+    env->ReleaseByteArrayElements(jObservationIdArr, (jbyte*)bArr, 0);\r
+\r
+    try{\r
+        OCStackResult result = OCPlatform::notifyListOfObservers(\r
+            jniOcResourceHandle->getOCResourceHandle(),\r
+            observationIds,\r
+            jniOcResourceResponse->getOCResourceResponse());\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to notify all observers");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    notifyListOfObservers3\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;[Ljava/lang/Byte;Lorg/iotivity/base/OcResourceResponse;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyListOfObservers3\r
+(JNIEnv *env, jclass clazz, jobject jResourceHandle, jbyteArray jObservationIdArr, jobject jResourceResponse, jint jQoS)\r
+{\r
+    LOGD("OcPlatform_notifyListOfObservers3");\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+    if (!jObservationIdArr)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "observationIdList cannot be null");\r
+        return;\r
+    }\r
+    if (!jResourceResponse)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceResponse cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    JniOcResourceResponse* jniOcResourceResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(\r
+        env, jResourceResponse);\r
+    if (!jniOcResourceResponse) return;\r
+\r
+    int len = env->GetArrayLength(jObservationIdArr);\r
+    uint8_t* bArr = (uint8_t*)env->GetByteArrayElements(jObservationIdArr, 0);\r
+\r
+    ObservationIds observationIds;\r
+    for (int i = 0; i < len; ++i)\r
+    {\r
+        observationIds.push_back(bArr[i]);\r
+    }\r
+\r
+    env->ReleaseByteArrayElements(jObservationIdArr, (jbyte*)bArr, 0);\r
+\r
+    try{\r
+        OCStackResult result = OCPlatform::notifyListOfObservers(\r
+            jniOcResourceHandle->getOCResourceHandle(),\r
+            observationIds,\r
+            jniOcResourceResponse->getOCResourceResponse(),\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to notify all observers");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    findResource0\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnResourceFoundListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource0\r
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jResourceUri, jint jConnectivityType, jobject jListener)\r
+{\r
+    LOGD("OcPlatform_findResource");\r
+    std::string host;\r
+    if (jHost)\r
+    {\r
+        host = env->GetStringUTFChars(jHost, NULL);\r
+    }\r
+    std::string resourceUri;\r
+    if (jResourceUri)\r
+    {\r
+        resourceUri = env->GetStringUTFChars(jResourceUri, NULL);\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onResourceFoundListener cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOnResourceFoundListener *onResFoundListener = AddOnResourceFoundListener(env, jListener);\r
+\r
+    FindCallback findCallback = [onResFoundListener](std::shared_ptr<OCResource> resource)\r
+    {\r
+        onResFoundListener->foundResourceCallback(resource);\r
+    };\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::findResource(\r
+            host,\r
+            resourceUri,\r
+            JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),\r
+            findCallback);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Find resource has failed");\r
+            return;\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    findResource1\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnResourceFoundListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource1\r
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jResourceUri, jint jConnectivityType, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcPlatform_findResource");\r
+    std::string host;\r
+    if (jHost)\r
+    {\r
+        host = env->GetStringUTFChars(jHost, NULL);\r
+    }\r
+    std::string resourceUri;\r
+    if (jResourceUri)\r
+    {\r
+        resourceUri = env->GetStringUTFChars(jResourceUri, NULL);\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onResourceFoundListener cannot be null");\r
+        return;\r
+    }\r
+    JniOnResourceFoundListener *onResFoundListener = AddOnResourceFoundListener(env, jListener);\r
+\r
+    FindCallback findCallback = [onResFoundListener](std::shared_ptr<OCResource> resource)\r
+    {\r
+        onResFoundListener->foundResourceCallback(resource);\r
+    };\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::findResource(\r
+            host,\r
+            resourceUri,\r
+            JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),\r
+            findCallback,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Find resource has failed");\r
+            return;\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    getDeviceInfo0\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnDeviceFoundListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDeviceInfo0\r
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jResourceUri, jint jConnectivityType, jobject jListener)\r
+{\r
+    LOGD("OcPlatform_getDeviceInfo0");\r
+    std::string host;\r
+    if (jHost)\r
+    {\r
+        host = env->GetStringUTFChars(jHost, NULL);\r
+    }\r
+    std::string resourceUri;\r
+    if (jResourceUri)\r
+    {\r
+        resourceUri = env->GetStringUTFChars(jResourceUri, NULL);\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onDeviceFoundListener cannot be null");\r
+        return;\r
+    }\r
+    JniOnDeviceInfoListener *onDeviceInfoListener = AddOnDeviceInfoListener(env, jListener);\r
+\r
+    FindDeviceCallback findDeviceCallback = [onDeviceInfoListener](const OCRepresentation& ocRepresentation)\r
+    {\r
+        onDeviceInfoListener->foundDeviceCallback(ocRepresentation);\r
+    };\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::getDeviceInfo(\r
+            host,\r
+            resourceUri,\r
+            JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),\r
+            findDeviceCallback);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Find device has failed");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    getDeviceInfo1\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnDeviceFoundListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDeviceInfo1\r
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jResourceUri, jint jConnectivityType, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcPlatform_getDeviceInfo1");\r
+    std::string host;\r
+    if (jHost)\r
+    {\r
+        host = env->GetStringUTFChars(jHost, NULL);\r
+    }\r
+    std::string resourceUri;\r
+    if (jResourceUri)\r
+    {\r
+        resourceUri = env->GetStringUTFChars(jResourceUri, NULL);\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onDeviceFoundListener cannot be null");\r
+        return;\r
+    }\r
+    JniOnDeviceInfoListener *onDeviceInfoListener = AddOnDeviceInfoListener(env, jListener);\r
+\r
+    FindDeviceCallback findDeviceCallback = [onDeviceInfoListener](const OCRepresentation& ocRepresentation)\r
+    {\r
+        onDeviceInfoListener->foundDeviceCallback(ocRepresentation);\r
+    };\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::getDeviceInfo(\r
+            host,\r
+            resourceUri,\r
+            JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),\r
+            findDeviceCallback,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Find device has failed");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    registerResource0\r
+* Signature: (Lorg/iotivity/base/OcResource;)Lorg/iotivity/base/OcResourceHandle;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_registerResource0\r
+(JNIEnv *env, jclass clazz, jobject jResource)\r
+{\r
+    LOGD("OcPlatform_registerResource");\r
+    if (!jResource)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "Resource cannot be null");\r
+        return nullptr;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, jResource);\r
+    if (!resource) return nullptr;\r
+\r
+    OCResourceHandle resourceHandle;\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::registerResource(\r
+            resourceHandle,\r
+            resource->getOCResource());\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "register resource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+        return nullptr;\r
+    }\r
+\r
+    JniOcResourceHandle* jniHandle = new JniOcResourceHandle(resourceHandle);\r
+    jlong handle = reinterpret_cast<jlong>(jniHandle);\r
+    jobject jResourceHandle = env->NewObject(g_cls_OcResourceHandle, g_mid_OcResourceHandle_N_ctor, handle);\r
+    if (!jResourceHandle)\r
+    {\r
+        LOGE("Failed to create OcResourceHandle");\r
+        delete jniHandle;\r
+    }\r
+    return jResourceHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    registerResource1\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcPlatform/EntityHandler;I)Lorg/iotivity/base/OcResourceHandle;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_registerResource1\r
+(JNIEnv *env, jclass clazz, jstring jResourceUri, jstring jResourceTypeName, jstring jResourceInterface,\r
+jobject jListener, jint jResourceProperty)\r
+{\r
+    LOGI("OcPlatform_registerResource1");\r
+    std::string resourceUri;\r
+    if (jResourceUri)\r
+    {\r
+        resourceUri = env->GetStringUTFChars(jResourceUri, NULL);\r
+    }\r
+    std::string resourceTypeName;\r
+    if (jResourceTypeName)\r
+    {\r
+        resourceTypeName = env->GetStringUTFChars(jResourceTypeName, NULL);\r
+    }\r
+    std::string resourceInterface;\r
+    if (jResourceInterface)\r
+    {\r
+        resourceInterface = env->GetStringUTFChars(jResourceInterface, NULL);\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "entityHandler cannot be null");\r
+        return nullptr;\r
+    }\r
+    JniEntityHandler* entityHandler = new JniEntityHandler(env, jListener);\r
+    EntityHandler handleEntityCallback = [entityHandler](const std::shared_ptr<OCResourceRequest> request) ->\r
+        OCEntityHandlerResult{\r
+        return entityHandler->handleEntity(request);\r
+    };\r
+\r
+    OCResourceHandle resourceHandle;\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::registerResource(\r
+            resourceHandle,\r
+            resourceUri,\r
+            resourceTypeName,\r
+            resourceInterface,\r
+            handleEntityCallback,\r
+            static_cast<int>(jResourceProperty));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            delete entityHandler;\r
+            ThrowOcException(result, "register resource");\r
+            return nullptr;\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        delete entityHandler;\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+        return nullptr;\r
+    }\r
+\r
+    JniOcResourceHandle* jniHandle = new JniOcResourceHandle(resourceHandle);\r
+    jlong handle = reinterpret_cast<jlong>(jniHandle);\r
+    jobject jResourceHandle = env->NewObject(g_cls_OcResourceHandle, g_mid_OcResourceHandle_N_ctor, handle);\r
+    if (!jResourceHandle)\r
+    {\r
+        LOGE("Failed to create OcResourceHandle");\r
+        delete jniHandle;\r
+    }\r
+\r
+    return jResourceHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    registerDeviceInfo0\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0\r
+(JNIEnv *env,\r
+jclass clazz,\r
+jstring jDeviceName,\r
+jstring jHostName,\r
+jstring jDeviceUUID,\r
+jstring jContentType,\r
+jstring jVersion,\r
+jstring jManufacturerName,\r
+jstring jManufacturerUrl,\r
+jstring jModelNumber,\r
+jstring jDateOfManufacture,\r
+jstring jPlatformVersion,\r
+jstring jFirmwareVersion,\r
+jstring jSupportUrl)\r
+{\r
+    LOGI("OcPlatform_registerDeviceInfo");\r
+\r
+    std::string deviceName;\r
+    if (jDeviceName)\r
+    {\r
+        deviceName = env->GetStringUTFChars(jDeviceName, NULL);\r
+    }\r
+    std::string hostName;\r
+    if (jHostName)\r
+    {\r
+        hostName = env->GetStringUTFChars(jHostName, NULL);\r
+    }\r
+    std::string deviceUUID;\r
+    if (jDeviceUUID)\r
+    {\r
+        deviceUUID = env->GetStringUTFChars(jDeviceUUID, NULL);\r
+    }\r
+    std::string contentType;\r
+    if (jContentType)\r
+    {\r
+        contentType = env->GetStringUTFChars(jContentType, NULL);\r
+    }\r
+    std::string version;\r
+    if (jVersion)\r
+    {\r
+        version = env->GetStringUTFChars(jVersion, NULL);\r
+    }\r
+    std::string manufacturerName;\r
+    if (jManufacturerName)\r
+    {\r
+        manufacturerName = env->GetStringUTFChars(jManufacturerName, NULL);\r
+    }\r
+    std::string manufacturerUrl;\r
+    if (jManufacturerUrl)\r
+    {\r
+        manufacturerUrl = env->GetStringUTFChars(jManufacturerUrl, NULL);\r
+    }\r
+    std::string modelNumber;\r
+    if (jModelNumber)\r
+    {\r
+        modelNumber = env->GetStringUTFChars(jModelNumber, NULL);\r
+    }\r
+    std::string dateOfManufacture;\r
+    if (jDateOfManufacture)\r
+    {\r
+        dateOfManufacture = env->GetStringUTFChars(jDateOfManufacture, NULL);\r
+    }\r
+    std::string platformVersion;\r
+    if (jPlatformVersion)\r
+    {\r
+        platformVersion = env->GetStringUTFChars(jPlatformVersion, NULL);\r
+    }\r
+    std::string firmwareVersion;\r
+    if (jFirmwareVersion)\r
+    {\r
+        firmwareVersion = env->GetStringUTFChars(jFirmwareVersion, NULL);\r
+    }\r
+    std::string supportUrl;\r
+    if (jSupportUrl)\r
+    {\r
+        supportUrl = env->GetStringUTFChars(jSupportUrl, NULL);\r
+    }\r
+\r
+    OCDeviceInfo deviceInfo;\r
+    try\r
+    {\r
+        DuplicateString(&deviceInfo.contentType, contentType);\r
+        DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture);\r
+        DuplicateString(&deviceInfo.deviceName, deviceName);\r
+        DuplicateString(&deviceInfo.deviceUUID, deviceUUID);\r
+        DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion);\r
+        DuplicateString(&deviceInfo.hostName, hostName);\r
+        DuplicateString(&deviceInfo.manufacturerName, manufacturerName);\r
+        DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl);\r
+        DuplicateString(&deviceInfo.modelNumber, modelNumber);\r
+        DuplicateString(&deviceInfo.platformVersion, platformVersion);\r
+        DuplicateString(&deviceInfo.supportUrl, supportUrl);\r
+        DuplicateString(&deviceInfo.version, version);\r
+    }\r
+    catch (std::exception &e)\r
+    {\r
+        ThrowOcException(JNI_EXCEPTION, "Failed to register device info");\r
+        return;\r
+    }\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::registerDeviceInfo(deviceInfo);\r
+\r
+        delete deviceInfo.contentType;\r
+        delete deviceInfo.dateOfManufacture;\r
+        delete deviceInfo.deviceName;\r
+        delete deviceInfo.deviceUUID;\r
+        delete deviceInfo.firmwareVersion;\r
+        delete deviceInfo.hostName;\r
+        delete deviceInfo.manufacturerName;\r
+        delete deviceInfo.manufacturerUrl;\r
+        delete deviceInfo.modelNumber;\r
+        delete deviceInfo.platformVersion;\r
+        delete deviceInfo.supportUrl;\r
+        delete deviceInfo.version;\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to register device info");\r
+            return;\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    unregisterResource0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unregisterResource0\r
+(JNIEnv *env, jclass clazz, jobject jResourceHandle)\r
+{\r
+    LOGI("OcPlatform_unregisterResource");\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    try\r
+    {\r
+        OCResourceHandle resHandle = jniOcResourceHandle->getOCResourceHandle();\r
+        OCStackResult result = OCPlatform::unregisterResource(resHandle);\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to unregister resource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    bindResource0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;Lorg/iotivity/base/OcResourceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResource0\r
+(JNIEnv *env, jclass clazz, jobject jResourceCollectionHandle, jobject jResourceHandle)\r
+{\r
+    LOGI("OcPlatform_bindResource");\r
+    if (!jResourceCollectionHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceCollectionHandle cannot be null");\r
+        return;\r
+    }\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+    JniOcResourceHandle* jniOcResourceCollectionHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceCollectionHandle);\r
+    if (!jniOcResourceCollectionHandle) return;\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::bindResource(\r
+            jniOcResourceCollectionHandle->getOCResourceHandle(),\r
+            jniOcResourceHandle->getOCResourceHandle()\r
+            );\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to bind resource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    bindResources0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;[Lorg/iotivity/base/OcResourceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResources0\r
+(JNIEnv *env, jclass clazz, jobject jResourceCollectionHandle, jobjectArray jResourceHandleArray)\r
+{\r
+    LOGI("OcPlatform_bindResources");\r
+\r
+    if (!jResourceCollectionHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceCollectionHandle cannot be null");\r
+        return;\r
+    }\r
+    if (!jResourceHandleArray)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandleList cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceCollectionHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceCollectionHandle);\r
+    if (!jniOcResourceCollectionHandle) return;\r
+\r
+    std::vector<OCResourceHandle> resourceHandleList;\r
+    int len = env->GetArrayLength(jResourceHandleArray);\r
+    for (int i = 0; i < len; ++i)\r
+    {\r
+        jobject jResourceHandle = env->GetObjectArrayElement(jResourceHandleArray, i);\r
+        if (!jResourceHandle)\r
+        {\r
+            ThrowOcException(JNI_EXCEPTION, "resource handle cannot be null");\r
+            return;\r
+        }\r
+\r
+        JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+            env, jResourceHandle);\r
+        if (!jniOcResourceHandle) return;\r
+\r
+        resourceHandleList.push_back(\r
+            jniOcResourceHandle->getOCResourceHandle());\r
+    }\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::bindResources(\r
+            jniOcResourceCollectionHandle->getOCResourceHandle(),\r
+            resourceHandleList\r
+            );\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to bind resources");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    unbindResource0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;Lorg/iotivity/base/OcResourceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unbindResource0\r
+(JNIEnv *env, jclass clazz, jobject jResourceCollectionHandle, jobject jResourceHandle)\r
+{\r
+    LOGI("OcPlatform_unbindResource");\r
+    if (!jResourceCollectionHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceCollectionHandle cannot be null");\r
+        return;\r
+    }\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceCollectionHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceCollectionHandle);\r
+    if (!jniOcResourceCollectionHandle) return;\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::unbindResource(\r
+            jniOcResourceCollectionHandle->getOCResourceHandle(),\r
+            jniOcResourceHandle->getOCResourceHandle()\r
+            );\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to unbind resource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    unbindResources0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;[Lorg/iotivity/base/OcResourceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unbindResources0\r
+(JNIEnv *env, jclass clazz, jobject jResourceCollectionHandle, jobjectArray jResourceHandleArray)\r
+{\r
+    LOGI("OcPlatform_unbindResources");\r
+    if (!jResourceCollectionHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceCollectionHandle cannot be null");\r
+        return;\r
+    }\r
+    if (!jResourceHandleArray)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandleList cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceCollectionHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceCollectionHandle);\r
+    if (!jniOcResourceCollectionHandle) return;\r
+\r
+    std::vector<OCResourceHandle> resourceHandleList;\r
+    int len = env->GetArrayLength(jResourceHandleArray);\r
+    for (int i = 0; i < len; ++i)\r
+    {\r
+        jobject jResourceHandle = env->GetObjectArrayElement(jResourceHandleArray, i);\r
+        if (!jResourceHandle)\r
+        {\r
+            ThrowOcException(JNI_EXCEPTION, "resource handle cannot be null");\r
+            return;\r
+        }\r
+\r
+        JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+            env, jResourceHandle);\r
+        if (!jniOcResourceHandle) return;\r
+\r
+        resourceHandleList.push_back(\r
+            jniOcResourceHandle->getOCResourceHandle());\r
+    }\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::unbindResources(\r
+            jniOcResourceCollectionHandle->getOCResourceHandle(),\r
+            resourceHandleList\r
+            );\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to unbind resources");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    bindTypeToResource0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindTypeToResource0\r
+(JNIEnv *env, jclass clazz, jobject jResourceHandle, jstring jResourceTypeName)\r
+{\r
+    LOGI("OcPlatform_bindTypeToResource");\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+    std::string typeName;\r
+    if (jResourceTypeName)\r
+    {\r
+        typeName = env->GetStringUTFChars(jResourceTypeName, NULL);\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::bindTypeToResource(\r
+            jniOcResourceHandle->getOCResourceHandle(),\r
+            typeName\r
+            );\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to bind type to resource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    bindInterfaceToResource0\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindInterfaceToResource0\r
+(JNIEnv *env, jclass clazz, jobject jResourceHandle, jstring jResourceInterfaceName)\r
+{\r
+    LOGI("OcPlatform_bindInterfaceToResource");\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+    std::string interfaceName;\r
+    if (jResourceInterfaceName)\r
+    {\r
+        interfaceName = env->GetStringUTFChars(jResourceInterfaceName, NULL);\r
+    }\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(\r
+        env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::bindInterfaceToResource(\r
+            jniOcResourceHandle->getOCResourceHandle(),\r
+            interfaceName\r
+            );\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to bind interface to resource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    startPresence0\r
+* Signature: (I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_startPresence0\r
+(JNIEnv *env, jclass clazz, jint ttl)\r
+{\r
+    LOGI("OcPlatform_startPresence");\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::startPresence((unsigned int)ttl);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to start presence");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    stopPresence0\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_stopPresence0\r
+(JNIEnv *env, jclass clazz)\r
+{\r
+    LOGI("OcPlatform_stopPresence");\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::stopPresence();\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "Failed to stop presence");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    subscribePresence0\r
+* Signature: (Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnPresenceListener;)Lorg/iotivity/base/OcPresenceHandle;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_subscribePresence0\r
+(JNIEnv *env, jclass clazz, jstring jHost, jint jConnectivityType, jobject jListener)\r
+{\r
+    LOGD("OcPlatform_subscribePresence");\r
+    std::string host;\r
+    if (jHost)\r
+    {\r
+        host = env->GetStringUTFChars(jHost, NULL);\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPresenceListener cannot be null");\r
+        return nullptr;\r
+    }\r
+\r
+    JniOnPresenceListener *onPresenceListener = AddOnPresenceListener(env, jListener);\r
+\r
+    SubscribeCallback subscribeCallback = [onPresenceListener](OCStackResult result, const unsigned int nonce,\r
+        const std::string& hostAddress)\r
+    {\r
+        onPresenceListener->onPresenceCallback(result, nonce, hostAddress);\r
+    };\r
+\r
+    OCPlatform::OCPresenceHandle presenceHandle;\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::subscribePresence(\r
+            presenceHandle,\r
+            host,\r
+            JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),\r
+            subscribeCallback);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "subscribe presence has failed");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+        return nullptr;\r
+    }\r
+\r
+    JniOcPresenceHandle* jniPresenceHandle = new JniOcPresenceHandle(onPresenceListener, presenceHandle);\r
+    jlong jhandle = reinterpret_cast<jlong>(jniPresenceHandle);\r
+    jobject jPresenceHandle = env->NewObject(g_cls_OcPresenceHandle, g_mid_OcPresenceHandle_N_ctor, jhandle);\r
+    if (!jPresenceHandle)\r
+    {\r
+        LOGE("Failed to create OcPresenceHandle");\r
+        delete jniPresenceHandle;\r
+    }\r
+\r
+    return jPresenceHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    subscribePresence1\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;I\r
+Lorg/iotivity/base/OcPlatform/OnPresenceListener;)Lorg/iotivity/base/OcPresenceHandle;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_subscribePresence1\r
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jResourceType, jint jConnectivityType, jobject jListener)\r
+{\r
+    LOGD("OcPlatform_subscribePresence1");\r
+    std::string host;\r
+    if (jHost)\r
+    {\r
+        host = env->GetStringUTFChars(jHost, NULL);\r
+    }\r
+    std::string resourceType;\r
+    if (jResourceType)\r
+    {\r
+        resourceType = env->GetStringUTFChars(jResourceType, NULL);\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPresenceListener cannot be null");\r
+        return nullptr;\r
+    }\r
+\r
+    JniOnPresenceListener *onPresenceListener = AddOnPresenceListener(env, jListener);\r
+\r
+    SubscribeCallback subscribeCallback = [onPresenceListener](OCStackResult result,\r
+        const unsigned int nonce, const std::string& hostAddress)\r
+    {\r
+        onPresenceListener->onPresenceCallback(result, nonce, hostAddress);\r
+    };\r
+\r
+    OCPlatform::OCPresenceHandle presenceHandle;\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::subscribePresence(\r
+            presenceHandle,\r
+            host,\r
+            resourceType,\r
+            JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),\r
+            subscribeCallback);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "subscribe presence has failed");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+        return nullptr;\r
+    }\r
+\r
+    JniOcPresenceHandle* jniPresenceHandle = new JniOcPresenceHandle(onPresenceListener, presenceHandle);\r
+    jlong jhandle = reinterpret_cast<jlong>(jniPresenceHandle);\r
+    jobject jPresenceHandle = env->NewObject(g_cls_OcPresenceHandle, g_mid_OcPresenceHandle_N_ctor, jhandle);\r
+    if (!jPresenceHandle)\r
+    {\r
+        LOGE("Failed to create OcPresenceHandle");\r
+        delete jniPresenceHandle;\r
+    }\r
+    return jPresenceHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    unsubscribePresence0\r
+* Signature: (Lorg/iotivity/base/OcPresenceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unsubscribePresence0\r
+(JNIEnv *env, jclass clazz, jobject jPresenceHandle)\r
+{\r
+    LOGD("OcPlatform_unsubscribePresence");\r
+    if (!jPresenceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "presenceHandle cannot be null");\r
+        return;\r
+    }\r
+    JniOcPresenceHandle* jniPresenceHandle = JniOcPresenceHandle::getJniOcPresenceHandlePtr(env, jPresenceHandle);\r
+    if (!jniPresenceHandle) return;\r
+\r
+    OCPresenceHandle presenceHandle = jniPresenceHandle->getOCPresenceHandle();\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::unsubscribePresence(presenceHandle);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "unsubscribe presence has failed");\r
+            return;\r
+        }\r
+        jweak jwOnPresenceListener = jniPresenceHandle->getJniOnPresenceListener()->getJWListener();\r
+        if (jwOnPresenceListener)\r
+        {\r
+            RemoveOnPresenceListener(env, jwOnPresenceListener);\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    constructResourceObject0\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;IZ[Ljava/lang/String;[Ljava/lang/String;)\r
+Lorg/iotivity/base/OcResource;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_constructResourceObject0\r
+(JNIEnv *env, jclass clazz, jstring jHost, jstring jUri, jint jConnectivityType,\r
+jboolean jIsObservable, jobjectArray jResourceTypeArray, jobjectArray jInterfaceArray)\r
+{\r
+    LOGD("OcPlatform_constructResourceObject");\r
+    std::string host;\r
+    if (jHost)\r
+    {\r
+        host = env->GetStringUTFChars(jHost, NULL);\r
+    }\r
+    std::string uri;\r
+    if (jUri)\r
+    {\r
+        uri = env->GetStringUTFChars(jUri, NULL);\r
+    }\r
+    if (!jResourceTypeArray)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceTypeList cannot be null");\r
+        return nullptr;\r
+    }\r
+    if (!jInterfaceArray)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "interfaceList cannot be null");\r
+        return nullptr;\r
+    }\r
+\r
+    std::vector<std::string> resourceTypes;\r
+    JniUtils::convertJavaStrArrToStrVector(env, jResourceTypeArray, resourceTypes);\r
+\r
+    std::vector<std::string> interfaces;\r
+    JniUtils::convertJavaStrArrToStrVector(env, jInterfaceArray, interfaces);\r
+\r
+    std::shared_ptr<OCResource> resource = OCPlatform::constructResourceObject(\r
+        host,\r
+        uri,\r
+        JniUtils::getConnectivityType(env, static_cast<int>(jConnectivityType)),\r
+        static_cast<bool>(jIsObservable),\r
+        resourceTypes,\r
+        interfaces);\r
+\r
+    if (!resource)\r
+    {\r
+        ThrowOcException(OC_STACK_ERROR, "Failed to create OCResource");\r
+        return nullptr;\r
+    }\r
+\r
+    JniOcResource *jniOcResource = new JniOcResource(resource);\r
+    jlong handle = reinterpret_cast<jlong>(jniOcResource);\r
+\r
+    jobject jResource = env->NewObject(g_cls_OcResource, g_mid_OcResource_ctor);\r
+    if (!jResource)\r
+    {\r
+        delete jniOcResource;\r
+        return nullptr;\r
+    }\r
+    SetHandle<JniOcResource>(env, jResource, jniOcResource);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        delete jniOcResource;\r
+        return nullptr;\r
+    }\r
+    return jResource;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPlatform\r
+* Method:    sendResponse0\r
+* Signature: (Lorg/iotivity/base/OcResourceResponse;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_sendResponse0\r
+(JNIEnv *env, jclass clazz, jobject jResourceResponse)\r
+{\r
+    LOGD("OcPlatform_sendResponse");\r
+    if (!jResourceResponse)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceResponse cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(\r
+        env, jResourceResponse);\r
+    if (!jniResponse) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = OCPlatform::sendResponse(jniResponse->getOCResourceResponse());\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "failed to send response");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcPlatform.h b/android/android_api/base/jni/JniOcPlatform.h
new file mode 100644 (file)
index 0000000..1019147
--- /dev/null
@@ -0,0 +1,264 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include "JniOnResourceFoundListener.h"\r
+#include "JniOnDeviceInfoListener.h"\r
+#include "JniOnPresenceListener.h"\r
+#include <mutex>\r
+\r
+#ifndef _Included_org_iotivity_base_OcPlatform\r
+#define _Included_org_iotivity_base_OcPlatform\r
+\r
+using namespace OC;\r
+\r
+JniOnResourceFoundListener* AddOnResourceFoundListener(JNIEnv* env, jobject jListener);\r
+void RemoveOnResourceFoundListener(JNIEnv* env, jobject jListener);\r
+\r
+JniOnDeviceInfoListener* AddOnDeviceInfoListener(JNIEnv* env, jobject jListener);\r
+void RemoveOnDeviceInfoListener(JNIEnv* env, jobject jListener);\r
+\r
+JniOnPresenceListener* AddOnPresenceListener(JNIEnv* env, jobject jListener);\r
+void RemoveOnPresenceListener(JNIEnv* env, jobject jListener);\r
+\r
+std::map<jobject, std::pair<JniOnResourceFoundListener*, int>> onResourceFoundListenerMap;\r
+std::map<jobject, std::pair<JniOnDeviceInfoListener*, int>> onDeviceInfoListenerMap;\r
+std::map<jobject, std::pair<JniOnPresenceListener*, int>> onPresenceListenerMap;\r
+\r
+std::mutex resourceFoundMapLock;\r
+std::mutex deviceInfoMapLock;\r
+std::mutex presenceMapLock;\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    configure\r
+    * Signature: (IILjava/lang/String;II)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_configure\r
+        (JNIEnv *, jclass, jint, jint, jstring, jint, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    notifyAllObservers0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers0\r
+        (JNIEnv *, jclass, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    notifyAllObservers1\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers1\r
+        (JNIEnv *, jclass, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    notifyListOfObservers2\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;[BLorg/iotivity/base/OcResourceResponse;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyListOfObservers2\r
+        (JNIEnv *, jclass, jobject, jbyteArray, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    notifyListOfObservers3\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;[BLorg/iotivity/base/OcResourceResponse;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyListOfObservers3\r
+        (JNIEnv *, jclass, jobject, jbyteArray, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    findResource0\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnResourceFoundListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource0\r
+        (JNIEnv *, jclass, jstring, jstring, jint, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    findResource1\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnResourceFoundListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource1\r
+        (JNIEnv *, jclass, jstring, jstring, jint, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    getDeviceInfo0\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnDeviceFoundListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDeviceInfo0\r
+        (JNIEnv *, jclass, jstring, jstring, jint, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    getDeviceInfo1\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnDeviceFoundListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDeviceInfo1\r
+        (JNIEnv *, jclass, jstring, jstring, jint, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    registerResource0\r
+    * Signature: (Lorg/iotivity/base/OcResource;)Lorg/iotivity/base/OcResourceHandle;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_registerResource0\r
+        (JNIEnv *, jclass, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    registerResource1\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcPlatform/EntityHandler;I)Lorg/iotivity/base/OcResourceHandle;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_registerResource1\r
+        (JNIEnv *, jclass, jstring, jstring, jstring, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    registerDeviceInfo0\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0\r
+        (JNIEnv *, jclass, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    unregisterResource0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unregisterResource0\r
+        (JNIEnv *, jclass, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    bindResource0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;Lorg/iotivity/base/OcResourceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResource0\r
+        (JNIEnv *, jclass, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    bindResources0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;[Lorg/iotivity/base/OcResourceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResources0\r
+        (JNIEnv *, jclass, jobject, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    unbindResource0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;Lorg/iotivity/base/OcResourceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unbindResource0\r
+        (JNIEnv *, jclass, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    unbindResources0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;[Lorg/iotivity/base/OcResourceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unbindResources0\r
+        (JNIEnv *, jclass, jobject, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    bindTypeToResource0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindTypeToResource0\r
+        (JNIEnv *, jclass, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    bindInterfaceToResource0\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindInterfaceToResource0\r
+        (JNIEnv *, jclass, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    startPresence0\r
+    * Signature: (I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_startPresence0\r
+        (JNIEnv *, jclass, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    stopPresence0\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_stopPresence0\r
+        (JNIEnv *, jclass);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    subscribePresence0\r
+    * Signature: (Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnPresenceListener;)Lorg/iotivity/base/OcPresenceHandle;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_subscribePresence0\r
+        (JNIEnv *, jclass, jstring, jint, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    subscribePresence1\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnPresenceListener;)Lorg/iotivity/base/OcPresenceHandle;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_subscribePresence1\r
+        (JNIEnv *, jclass, jstring, jstring, jint, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    unsubscribePresence0\r
+    * Signature: (Lorg/iotivity/base/OcPresenceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unsubscribePresence0\r
+        (JNIEnv *, jclass, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform\r
+    * Method:    constructResourceObject0\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;IZ[Ljava/lang/String;[Ljava/lang/String;)Lorg/iotivity/base/OcResource;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_constructResourceObject0\r
+        (JNIEnv *, jclass, jstring, jstring, jint, jboolean, jobjectArray, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPlatform0\r
+    * Method:    sendResponse0\r
+    * Signature: (Lorg/iotivity/base/OcResourceResponse;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_sendResponse0\r
+        (JNIEnv *, jclass, jobject);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOcPresenceHandle.cpp b/android/android_api/base/jni/JniOcPresenceHandle.cpp
new file mode 100644 (file)
index 0000000..83950bc
--- /dev/null
@@ -0,0 +1,73 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcPresenceHandle.h"\r
+#include "OCPlatform.h"\r
+\r
+JniOcPresenceHandle::JniOcPresenceHandle(JniOnPresenceListener* jniListener, OCPresenceHandle presenceHandle)\r
+    : m_jniListener(jniListener), m_presenceHandle(presenceHandle)\r
+{}\r
+\r
+JniOcPresenceHandle::~JniOcPresenceHandle()\r
+{\r
+    LOGD("~JniOcPresenceHandle()");\r
+\r
+    //delete m_jniListener;\r
+    m_presenceHandle = nullptr;\r
+}\r
+\r
+JniOcPresenceHandle* JniOcPresenceHandle::getJniOcPresenceHandlePtr\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    JniOcPresenceHandle *handle = GetHandle<JniOcPresenceHandle>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from OcPresenceHandle");\r
+    }\r
+    if (!handle)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return handle;\r
+}\r
+\r
+OCPresenceHandle JniOcPresenceHandle::getOCPresenceHandle()\r
+{\r
+    return this->m_presenceHandle;\r
+}\r
+\r
+JniOnPresenceListener* JniOcPresenceHandle::getJniOnPresenceListener()\r
+{\r
+    return this->m_jniListener;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcPresenceHandle\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPresenceHandle_dispose\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcPresenceHandle_dispose");\r
+    JniOcPresenceHandle *presenceHandle = JniOcPresenceHandle::getJniOcPresenceHandlePtr(env, thiz);\r
+    delete presenceHandle;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcPresenceHandle.h b/android/android_api/base/jni/JniOcPresenceHandle.h
new file mode 100644 (file)
index 0000000..26f6a8d
--- /dev/null
@@ -0,0 +1,65 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include "JniOnPresenceListener.h"\r
+#include "OCPlatform.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcPresenceHandle\r
+#define _Included_org_iotivity_base_OcPresenceHandle\r
+\r
+using namespace OC::OCPlatform;\r
+\r
+class JniOcPresenceHandle\r
+{\r
+public:\r
+\r
+    JniOcPresenceHandle(JniOnPresenceListener* jniListener, OCPresenceHandle presenceHandle);\r
+    ~JniOcPresenceHandle();\r
+    JniOcPresenceHandle(const JniOcPresenceHandle &) = delete;\r
+    void operator=(const JniOcPresenceHandle &) = delete;\r
+\r
+    static JniOcPresenceHandle* getJniOcPresenceHandlePtr(JNIEnv *env, jobject thiz);\r
+\r
+    OCPresenceHandle getOCPresenceHandle();\r
+    JniOnPresenceListener* getJniOnPresenceListener();\r
+\r
+private:\r
+    JniOnPresenceListener* m_jniListener;\r
+    OCPresenceHandle m_presenceHandle;\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcPresenceHandle\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPresenceHandle_dispose\r
+        (JNIEnv *, jobject);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOcRepresentation.cpp b/android/android_api/base/jni/JniOcRepresentation.cpp
new file mode 100644 (file)
index 0000000..e2c2cd0
--- /dev/null
@@ -0,0 +1,1040 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcRepresentation.h"\r
+#include "JniUtils.h"\r
+\r
+using namespace OC;\r
+\r
+OCRepresentation* JniOcRepresentation::getOCRepresentationPtr(JNIEnv *env, jobject thiz)\r
+{\r
+    OCRepresentation *rep = GetHandle<OCRepresentation>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from OcRepresentation");\r
+    }\r
+    if (!rep)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return rep;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    getValueN\r
+* Signature: (Ljava/lang/String;)Ljava/lang/Object;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValueN\r
+(JNIEnv *env, jobject thiz, jstring jKey)\r
+{\r
+    LOGD("OcRepresentation_getValue");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "attributeKey cannot be null");\r
+        return nullptr;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return nullptr;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+\r
+    AttributeValue attrValue;\r
+    if (!rep->getAttributeValue(key.c_str(), attrValue))\r
+    {\r
+        ThrowOcException(JNI_NO_SUCH_KEY, " attribute key does not exist");\r
+        return nullptr;\r
+    }\r
+    return boost::apply_visitor(JObjectConverter(env), attrValue);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueInteger\r
+* Signature: (Ljava/lang/String;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger\r
+(JNIEnv *env, jobject thiz, jstring jKey, jint jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueInteger");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string str = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(str, static_cast<int>(jValue));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueDouble\r
+* Signature: (Ljava/lang/String;D)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble\r
+(JNIEnv *env, jobject thiz, jstring jKey, jdouble jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueDouble");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string str = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(str, static_cast<double>(jValue));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueBoolean\r
+* Signature: (Ljava/lang/String;Z)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean\r
+(JNIEnv *env, jobject thiz, jstring jKey, jboolean jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueBoolean");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string str = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(str, static_cast<bool>(jValue));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueStringN\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringN\r
+(JNIEnv *env, jobject thiz, jstring jKey, jstring jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueString");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    std::string value = env->GetStringUTFChars(jValue, NULL);\r
+\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueRepresentation\r
+* Signature: (Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentation\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobject jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueRepresentation");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    OCRepresentation *value = JniOcRepresentation::getOCRepresentationPtr(env, jValue);\r
+    if (!value) return;\r
+\r
+    rep->setValue(key, *value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueIntegerArray\r
+* Signature: (Ljava/lang/String;[I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueIntegerArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jintArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueIntegerArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+\r
+    const jsize len = env->GetArrayLength(jValue);\r
+    jint* ints = env->GetIntArrayElements(jValue, NULL);\r
+\r
+    std::vector<int> value;\r
+    for (jsize i = 0; i < len; ++i)\r
+    {\r
+        value.push_back(static_cast<int>(ints[i]));\r
+    }\r
+    env->ReleaseIntArrayElements(jValue, ints, JNI_ABORT);\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueInteger2DArray\r
+* Signature: (Ljava/lang/String;[[I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger2DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation__setValueInteger2DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<int>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize j = 0; j < lenOuter; ++j)\r
+    {\r
+        jintArray jInnerArray = static_cast<jintArray>(env->GetObjectArrayElement(jValue, j));\r
+        jint* ints = env->GetIntArrayElements(jInnerArray, NULL);\r
+        std::vector<int> innerVector;\r
+        const jsize lenInner = env->GetArrayLength(jInnerArray);\r
+        for (jsize i = 0; i < lenInner; ++i)\r
+        {\r
+            innerVector.push_back(static_cast<int>(ints[i]));\r
+        }\r
+        env->ReleaseIntArrayElements(jInnerArray, ints, JNI_ABORT);\r
+        env->DeleteLocalRef(jInnerArray);\r
+        value.push_back(innerVector);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueInteger3DArray\r
+* Signature: (Ljava/lang/String;[[[I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger3DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueInteger3DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<std::vector<int>>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize k = 0; k < lenOuter; ++k)\r
+    {\r
+        jobjectArray jMiddleArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jValue, k));\r
+        const jsize lenMiddle = env->GetArrayLength(jMiddleArray);\r
+        std::vector<std::vector<int>> middleArray;\r
+        for (jsize j = 0; j < lenMiddle; ++j)\r
+        {\r
+            jintArray jInnerArray = static_cast<jintArray>(env->GetObjectArrayElement(jMiddleArray, j));\r
+            jint* ints = env->GetIntArrayElements(jInnerArray, NULL);\r
+            std::vector<int> innerVector;\r
+            const jsize lenInner = env->GetArrayLength(jInnerArray);\r
+            for (jsize i = 0; i < lenInner; ++i)\r
+            {\r
+                innerVector.push_back(static_cast<int>(ints[i]));\r
+            }\r
+            env->ReleaseIntArrayElements(jInnerArray, ints, JNI_ABORT);\r
+            env->DeleteLocalRef(jInnerArray);\r
+            middleArray.push_back(innerVector);\r
+        }\r
+        env->DeleteLocalRef(jMiddleArray);\r
+        value.push_back(middleArray);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueDoubleArray\r
+* Signature: (Ljava/lang/String;[D)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDoubleArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jdoubleArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueDoubleArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+\r
+    const jsize len = env->GetArrayLength(jValue);\r
+    jdouble* doubles = env->GetDoubleArrayElements(jValue, NULL);\r
+\r
+    std::vector<double> value;\r
+    for (jsize i = 0; i < len; ++i)\r
+    {\r
+        value.push_back(static_cast<double>(doubles[i]));\r
+    }\r
+    env->ReleaseDoubleArrayElements(jValue, doubles, JNI_ABORT);\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueDouble2DArray\r
+* Signature: (Ljava/lang/String;[[D)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble2DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueDouble2DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<double>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize j = 0; j < lenOuter; ++j)\r
+    {\r
+        jdoubleArray jInnerArray = static_cast<jdoubleArray>(env->GetObjectArrayElement(jValue, j));\r
+        jdouble* doubles = env->GetDoubleArrayElements(jInnerArray, NULL);\r
+        std::vector<double> innerVector;\r
+        const jsize lenInner = env->GetArrayLength(jInnerArray);\r
+        for (jsize i = 0; i < lenInner; ++i)\r
+        {\r
+            innerVector.push_back(static_cast<double>(doubles[i]));\r
+        }\r
+        env->ReleaseDoubleArrayElements(jInnerArray, doubles, JNI_ABORT);\r
+        env->DeleteLocalRef(jInnerArray);\r
+        value.push_back(innerVector);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueDouble3DArray\r
+* Signature: (Ljava/lang/String;[[[D)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble3DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueDouble3DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<std::vector<double>>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize k = 0; k < lenOuter; ++k)\r
+    {\r
+        jobjectArray jMiddleArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jValue, k));\r
+        const jsize lenMiddle = env->GetArrayLength(jMiddleArray);\r
+        std::vector<std::vector<double>> middleArray;\r
+        for (jsize j = 0; j < lenMiddle; ++j)\r
+        {\r
+            jdoubleArray jInnerArray = static_cast<jdoubleArray>(env->GetObjectArrayElement(jMiddleArray, j));\r
+            jdouble* doubles = env->GetDoubleArrayElements(jInnerArray, NULL);\r
+            std::vector<double> innerVector;\r
+            const jsize lenInner = env->GetArrayLength(jInnerArray);\r
+            for (jsize i = 0; i < lenInner; ++i)\r
+            {\r
+                innerVector.push_back(static_cast<double>(doubles[i]));\r
+            }\r
+            env->ReleaseDoubleArrayElements(jInnerArray, doubles, JNI_ABORT);\r
+            env->DeleteLocalRef(jInnerArray);\r
+            middleArray.push_back(innerVector);\r
+        }\r
+        env->DeleteLocalRef(jMiddleArray);\r
+        value.push_back(middleArray);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueBooleanArray\r
+* Signature: (Ljava/lang/String;[Z)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBooleanArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jbooleanArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueBooleanArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+\r
+    const jsize len = env->GetArrayLength(jValue);\r
+    jboolean* booleans = env->GetBooleanArrayElements(jValue, NULL);\r
+\r
+    std::vector<bool> value;\r
+    for (jsize i = 0; i < len; ++i)\r
+    {\r
+        value.push_back(static_cast<bool>(booleans[i]));\r
+    }\r
+    env->ReleaseBooleanArrayElements(jValue, booleans, JNI_ABORT);\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueBoolean2DArray\r
+* Signature: (Ljava/lang/String;[[Z)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean2DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueBoolean2DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<bool>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize j = 0; j < lenOuter; ++j)\r
+    {\r
+        jbooleanArray jInnerArray = static_cast<jbooleanArray>(env->GetObjectArrayElement(jValue, j));\r
+        const jsize lenInner = env->GetArrayLength(jInnerArray);\r
+        jboolean* booleans = env->GetBooleanArrayElements(jInnerArray, NULL);\r
+\r
+        std::vector<bool> innerVector;\r
+        for (jsize i = 0; i < lenInner; ++i)\r
+        {\r
+            innerVector.push_back(static_cast<bool>(booleans[i]));\r
+        }\r
+        env->ReleaseBooleanArrayElements(jInnerArray, booleans, JNI_ABORT);\r
+        env->DeleteLocalRef(jInnerArray);\r
+        value.push_back(innerVector);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueBoolean3DArray\r
+* Signature: (Ljava/lang/String;[[[Z)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean3DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueBoolean3DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<std::vector<bool>>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize k = 0; k < lenOuter; ++k)\r
+    {\r
+        jobjectArray jMiddleArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jValue, k));\r
+        const jsize lenMiddle = env->GetArrayLength(jMiddleArray);\r
+        std::vector<std::vector<bool>> middleArray;\r
+        for (jsize j = 0; j < lenMiddle; ++j)\r
+        {\r
+            jbooleanArray jInnerArray = static_cast<jbooleanArray>(env->GetObjectArrayElement(jMiddleArray, j));\r
+            const jsize lenInner = env->GetArrayLength(jInnerArray);\r
+            jboolean* booleans = env->GetBooleanArrayElements(jInnerArray, NULL);\r
+\r
+            std::vector<bool> innerVector;\r
+            for (jsize i = 0; i < lenInner; ++i)\r
+            {\r
+                innerVector.push_back(static_cast<bool>(booleans[i]));\r
+            }\r
+            env->ReleaseBooleanArrayElements(jInnerArray, booleans, JNI_ABORT);\r
+            env->DeleteLocalRef(jInnerArray);\r
+            middleArray.push_back(innerVector);\r
+        }\r
+        env->DeleteLocalRef(jMiddleArray);\r
+        value.push_back(middleArray);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueStringArray\r
+* Signature: (Ljava/lang/String;[Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueStringArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+\r
+    std::vector<std::string> value;\r
+    JniUtils::convertJavaStrArrToStrVector(env, jValue, value);\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueString2DArray\r
+* Signature: (Ljava/lang/String;[[Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString2DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueString2DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<std::string>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize j = 0; j < lenOuter; ++j)\r
+    {\r
+        jobjectArray jInnerArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jValue, j));\r
+        std::vector<std::string> innerVector;\r
+        JniUtils::convertJavaStrArrToStrVector(env, jInnerArray, innerVector);\r
+        env->DeleteLocalRef(jInnerArray);\r
+        value.push_back(innerVector);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueString3DArray\r
+* Signature: (Ljava/lang/String;[[[Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString3DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueString3DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<std::vector<std::string>>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize k = 0; k < lenOuter; ++k)\r
+    {\r
+        jobjectArray jMiddleArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jValue, k));\r
+        const jsize lenMiddle = env->GetArrayLength(jMiddleArray);\r
+        std::vector<std::vector<std::string>> middleArray;\r
+        for (jsize j = 0; j < lenMiddle; ++j)\r
+        {\r
+            jobjectArray jInnerArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jMiddleArray, j));\r
+            std::vector<std::string> innerVector;\r
+            JniUtils::convertJavaStrArrToStrVector(env, jInnerArray, innerVector);\r
+            env->DeleteLocalRef(jInnerArray);\r
+            middleArray.push_back(innerVector);\r
+        }\r
+        env->DeleteLocalRef(jMiddleArray);\r
+        value.push_back(middleArray);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueRepresentationArray\r
+* Signature: (Ljava/lang/String;[Lorg/iotivity/base/OcRepresentation;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentationArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueRepresentationArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+\r
+    std::vector<OCRepresentation> value;\r
+    JniUtils::convertJavaRepresentationArrToVector(env, jValue, value);\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueRepresentation2DArray\r
+* Signature: (Ljava/lang/String;[[Lorg/iotivity/base/OcRepresentation;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentation2DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueRepresentation2DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<OCRepresentation>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize j = 0; j < lenOuter; ++j)\r
+    {\r
+        jobjectArray jInnerArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jValue, j));\r
+        std::vector<OCRepresentation> innerVector;\r
+        JniUtils::convertJavaRepresentationArrToVector(env, jInnerArray, innerVector);\r
+        env->DeleteLocalRef(jInnerArray);\r
+        value.push_back(innerVector);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setValueRepresentation3DArray\r
+* Signature: (Ljava/lang/String;[[[Lorg/iotivity/base/OcRepresentation;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentation3DArray\r
+(JNIEnv *env, jobject thiz, jstring jKey, jobjectArray jValue)\r
+{\r
+    LOGD("OcRepresentation_setValueRepresentation3DArray");\r
+    if (!jKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "key cannot be null");\r
+        return;\r
+    }\r
+    std::vector<std::vector<std::vector<OCRepresentation>>> value;\r
+    const jsize lenOuter = env->GetArrayLength(jValue);\r
+    for (jsize k = 0; k < lenOuter; ++k)\r
+    {\r
+        jobjectArray jMiddleArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jValue, k));\r
+        const jsize lenMiddle = env->GetArrayLength(jMiddleArray);\r
+        std::vector<std::vector<OCRepresentation>> middleArray;\r
+        for (jsize j = 0; j < lenMiddle; ++j)\r
+        {\r
+            jobjectArray jInnerArray = static_cast<jobjectArray>(env->GetObjectArrayElement(jMiddleArray, j));\r
+            std::vector<OCRepresentation> innerVector;\r
+            JniUtils::convertJavaRepresentationArrToVector(env, jInnerArray, innerVector);\r
+            env->DeleteLocalRef(jInnerArray);\r
+            middleArray.push_back(innerVector);\r
+        }\r
+        env->DeleteLocalRef(jMiddleArray);\r
+        value.push_back(middleArray);\r
+    }\r
+\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string key = env->GetStringUTFChars(jKey, NULL);\r
+    rep->setValue(key, value);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    getJSONRepresentation\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getJSONRepresentation\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_getJSONRepresentation");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return nullptr;\r
+\r
+    std::string jsonStr = rep->getJSONRepresentation();\r
+    return env->NewStringUTF(jsonStr.c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    addChild\r
+* Signature: (Lorg/iotivity/base/OcRepresentation;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_addChild\r
+(JNIEnv *env, jobject thiz, jobject jOcRepresentation)\r
+{\r
+    LOGD("OcRepresentation_addChild");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    OCRepresentation *child = JniOcRepresentation::getOCRepresentationPtr(env, jOcRepresentation);\r
+    if (!child) return;\r
+\r
+    rep->addChild(*child);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    clearChildren\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_clearChildren\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_clearChildren");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    rep->clearChildren();\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    getChildrenArray\r
+* Signature: ()[Lorg/iotivity/base/OcRepresentation;\r
+*/\r
+JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcRepresentation_getChildrenArray\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_getChildrenArray");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return nullptr;\r
+\r
+    return JniUtils::convertRepresentationVectorToJavaArray(env, rep->getChildren());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    getUri\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getUri\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_getUri");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return nullptr;\r
+\r
+    std::string uri(rep->getUri());\r
+    return env->NewStringUTF(uri.c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setUri\r
+* Signature: (Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setUri\r
+(JNIEnv *env, jobject thiz, jstring jUri)\r
+{\r
+    LOGD("OcRepresentation_setUri");\r
+    if (!jUri)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "uri cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    rep->setUri(env->GetStringUTFChars(jUri, NULL));\r
+}\r
+\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_hasAttribute\r
+(JNIEnv *env, jobject thiz, jstring jstr)\r
+{\r
+    LOGD("OcRepresentation_hasAttribute");\r
+    if (!jstr)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "attributeKey cannot be null");\r
+        return false;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return false;\r
+\r
+    std::string str = env->GetStringUTFChars(jstr, NULL);\r
+    return rep->hasAttribute(str);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    getResourceTypes\r
+* Signature: ()Ljava/util/List;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceTypes\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_getResourceTypes");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return nullptr;\r
+\r
+    std::vector<std::string> resourceTypes = rep->getResourceTypes();\r
+    return JniUtils::convertStrVectorToJavaStrList(env, resourceTypes);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setResourceTypeArray\r
+* Signature: ([Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceTypeArray\r
+(JNIEnv *env, jobject thiz, jobjectArray jResourceTypeArray)\r
+{\r
+    LOGD("OcRepresentation_setResourceTypeArray");\r
+    if (!jResourceTypeArray)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceTypeList cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::vector<std::string> resourceTypes;\r
+    JniUtils::convertJavaStrArrToStrVector(env, jResourceTypeArray, resourceTypes);\r
+    rep->setResourceTypes(resourceTypes);\r
+}\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    getResourceInterfaces\r
+* Signature: ()Ljava/util/List;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceInterfaces\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_getResourceInterfaces");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return nullptr;\r
+\r
+    std::vector<std::string> resourceInterfaces = rep->getResourceInterfaces();\r
+    return JniUtils::convertStrVectorToJavaStrList(env, resourceInterfaces);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setResourceInterfaceArray\r
+* Signature: ([Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceInterfaceArray\r
+(JNIEnv *env, jobject thiz, jobjectArray jResourceInterfaceArray)\r
+{\r
+    LOGD("OcRepresentation_setResourceInterfaceArray");\r
+    if (!jResourceInterfaceArray)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceInterfaceList cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::vector<std::string> resourceInterfaces;\r
+    JniUtils::convertJavaStrArrToStrVector(env, jResourceInterfaceArray, resourceInterfaces);\r
+    rep->setResourceInterfaces(resourceInterfaces);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    isEmpty\r
+* Signature: ()Z\r
+*/\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isEmpty\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_isEmpty");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return false;\r
+\r
+    return static_cast<jboolean>(rep->empty());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    size\r
+* Signature: ()I\r
+*/\r
+JNIEXPORT jint JNICALL Java_org_iotivity_base_OcRepresentation_size\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_size");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return -1;\r
+\r
+    return static_cast<jint>(rep->numberOfAttributes());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    remove\r
+* Signature: (Ljava/lang/String;)Z\r
+*/\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_remove\r
+(JNIEnv *env, jobject thiz, jstring jAttributeKey)\r
+{\r
+    LOGD("OcRepresentation_remove");\r
+    if (!jAttributeKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "attributeKey cannot be null");\r
+        return false;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return false;\r
+\r
+    std::string attributeKey = env->GetStringUTFChars(jAttributeKey, NULL);\r
+    return static_cast<jboolean>(rep->erase(attributeKey));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    setNull\r
+* Signature: (Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setNull\r
+(JNIEnv *env, jobject thiz, jstring jAttributeKey)\r
+{\r
+    LOGD("OcRepresentation_setNull");\r
+    if (!jAttributeKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "attributeKey cannot be null");\r
+        return;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return;\r
+\r
+    std::string attributeKey = env->GetStringUTFChars(jAttributeKey, NULL);\r
+    rep->setNULL(attributeKey);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    isNull\r
+* Signature: (Ljava/lang/String;)Z\r
+*/\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isNull\r
+(JNIEnv *env, jobject thiz, jstring jAttributeKey)\r
+{\r
+    LOGD("OcRepresentation_isNull");\r
+    if (!jAttributeKey)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "attributeKey cannot be null");\r
+        return false;\r
+    }\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+    if (!rep) return false;\r
+\r
+    std::string attributeKey = env->GetStringUTFChars(jAttributeKey, NULL);\r
+    return static_cast<jboolean>(rep->isNULL(attributeKey));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    create\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_create\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRepresentation_create");\r
+    OCRepresentation *rep = new OCRepresentation();\r
+    SetHandle<OCRepresentation>(env, thiz, rep);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to set native handle for OcRepresentation");\r
+        delete rep;\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRepresentation\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_dispose\r
+(JNIEnv *env, jobject thiz, jboolean jNeedsDelete)\r
+{\r
+    LOGD("OcRepresentation_dispose");\r
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);\r
+\r
+    if (jNeedsDelete)\r
+    {\r
+        delete rep;\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcRepresentation.h b/android/android_api/base/jni/JniOcRepresentation.h
new file mode 100644 (file)
index 0000000..3f25c29
--- /dev/null
@@ -0,0 +1,769 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include <AttributeValue.h>\r
+\r
+#ifndef _Included_org_iotivity_base_OcRepresentation\r
+#define _Included_org_iotivity_base_OcRepresentation\r
+\r
+using namespace OC;\r
+\r
+class JniOcRepresentation\r
+{\r
+public:\r
+    static OCRepresentation* getOCRepresentationPtr(JNIEnv *env, jobject thiz);\r
+};\r
+\r
+struct JObjectConverter : boost::static_visitor < jobject >\r
+{\r
+    JObjectConverter(JNIEnv *env) : env(env){}\r
+\r
+    jobject operator()(const NullType&) const { return nullptr; }
+    jobject operator()(const int& val) const
+    {
+        jobject jobj = env->NewObject(
+            g_cls_Integer,
+            g_mid_Integer_ctor,
+            static_cast<jint>(val));
+        return jobj;
+    }
+    jobject operator()(const double& val) const
+    {
+        jobject jobj = env->NewObject(
+            g_cls_Double,
+            g_mid_Double_ctor,
+            static_cast<jdouble>(val));
+        return jobj;
+    }
+    jobject operator()(const bool& val) const
+    {
+        jobject jobj = env->NewObject(
+            g_cls_Boolean,
+            g_mid_Boolean_ctor,
+            static_cast<jboolean>(val));
+        return jobj;
+    }
+    jobject operator()(const std::string& val) const
+    {
+        jstring jstr = env->NewStringUTF(val.c_str());
+        return static_cast<jobject>(jstr);
+    }
+    jobject operator()(const OC::OCRepresentation& val) const
+    {
+        OCRepresentation * rep = new OCRepresentation(val);\r
+        jlong handle = reinterpret_cast<jlong>(rep);\r
+        jobject jRepresentation = env->NewObject(
+            g_cls_OcRepresentation,
+            g_mid_OcRepresentation_N_ctor_bool,
+            handle, true);
+        if (!jRepresentation)
+        {
+            delete rep;
+        }
+        return jRepresentation;
+    }
+
+    // Sequences:
+    jobject operator()(const std::vector<int>& val) const
+    {
+        size_t len = val.size();
+        jintArray jIntArray = env->NewIntArray(len);\r
+        if (!jIntArray) return nullptr;\r
+        const int* ints = &val[0];\r
+        env->SetIntArrayRegion(jIntArray, 0, len, reinterpret_cast<const jint*>(ints));
+        return jIntArray;
+    }
+    jobject operator()(const std::vector<double>& val) const
+    {
+        size_t len = val.size();
+        jdoubleArray jDoubleArray = env->NewDoubleArray(len);\r
+        if (!jDoubleArray) return nullptr;\r
+        const double* doubles = &val[0];\r
+        env->SetDoubleArrayRegion(jDoubleArray, 0, len, reinterpret_cast<const jdouble*>(doubles));
+        return jDoubleArray;
+    }
+    jobject operator()(const std::vector<bool>& val) const
+    {
+        size_t len = val.size();
+        jbooleanArray jBooleanArray = env->NewBooleanArray(len);\r
+        if (!jBooleanArray) return nullptr;\r
+        jboolean* booleans = new jboolean[len];\r
+        for (size_t i = 0; i < len; ++i) {\r
+            booleans[i] = static_cast<jboolean>(val[i]);\r
+        }\r
+        env->SetBooleanArrayRegion(jBooleanArray, 0, len, booleans);
+        if (env->ExceptionCheck()) return nullptr;
+        env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
+        return jBooleanArray;
+    }
+    jobject operator()(const std::vector<std::string>& val) const
+    {
+        size_t len = val.size();\r
+        jobjectArray strArr = env->NewObjectArray(len, g_cls_String, NULL);\r
+        if (!strArr) return nullptr;\r
+        for (size_t i = 0; i < len; ++i)\r
+        {\r
+            jstring jString = env->NewStringUTF(val[i].c_str());\r
+            env->SetObjectArrayElement(strArr, static_cast<jsize>(i), jString);\r
+            if (env->ExceptionCheck()) return nullptr;\r
+            env->DeleteLocalRef(jString);\r
+        }\r
+        return strArr;
+    }
+    jobject operator()(const std::vector<OC::OCRepresentation>& val) const
+    {
+        jsize len = static_cast<jsize>(val.size());\r
+        jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, NULL);\r
+        if (!repArr) return nullptr;\r
+        for (jsize i = 0; i < len; ++i)\r
+        {\r
+            OCRepresentation* rep = new OCRepresentation(val[i]);\r
+            jlong handle = reinterpret_cast<jlong>(rep);\r
+            jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+                handle, true);\r
+            if (!jRepresentation)\r
+            {\r
+                delete rep;\r
+                return nullptr;\r
+            }\r
+            env->SetObjectArrayElement(repArr, i, jRepresentation);\r
+            if (env->ExceptionCheck())\r
+            {\r
+                delete rep;\r
+                return nullptr;\r
+            }\r
+            env->DeleteLocalRef(jRepresentation);\r
+        }\r
+        return repArr;
+    }
+
+    // Nested sequences:
+    jobject operator()(const std::vector<std::vector<int>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_int1DArray, NULL);\r
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }\r
+        for (jsize i = 0; i < lenOuter; ++i)\r
+        {
+            size_t lenInner = val[i].size();
+            jintArray jIntArray = env->NewIntArray(lenInner);\r
+            if (!jIntArray) return nullptr;\r
+            const int* ints = &val[i][0];\r
+            env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
+            if (env->ExceptionCheck()) return nullptr;
+            env->SetObjectArrayElement(jOuterArr, i, static_cast<jobject>(jIntArray));
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jIntArray);
+        }
+        return jOuterArr;
+    }
+    jobject operator()(const std::vector<std::vector<std::vector<int>>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_int2DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize k = 0; k < lenOuter; ++k)\r
+        {\r
+            jsize lenMiddle = static_cast<jsize>(val[k].size());\r
+            jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_int1DArray, NULL);\r
+            if (!jMiddleArr) return nullptr;\r
+            for (jsize i = 0; i < lenMiddle; ++i)\r
+            {
+                jsize lenInner = static_cast<jsize>(val[k][i].size());
+                jintArray jIntArray = env->NewIntArray(lenInner);\r
+                if (!jIntArray) return nullptr;\r
+                const int* ints = &val[k][i][0];\r
+                env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
+                if (env->ExceptionCheck()) return nullptr;
+                env->SetObjectArrayElement(jMiddleArr, i, jIntArray);
+                if (env->ExceptionCheck()) return nullptr;
+                env->DeleteLocalRef(jIntArray);
+            }
+            env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jMiddleArr);
+        }
+        return jOuterArr;
+    }
+
+    jobject operator()(const std::vector<std::vector<double>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double1DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize i = 0; i < lenOuter; ++i)\r
+        {
+            size_t lenInner = val[i].size();
+            jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);\r
+            if (!jDoubleArray) return nullptr;\r
+            const double* doubles = &val[i][0];\r
+            env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
+            if (env->ExceptionCheck()) return nullptr;
+            env->SetObjectArrayElement(jOuterArr, i, jDoubleArray);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jDoubleArray);
+        }
+
+        return jOuterArr;
+    }
+    jobject operator()(const std::vector<std::vector<std::vector<double>>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double2DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize k = 0; k < lenOuter; ++k)\r
+        {\r
+            jsize lenMiddle = static_cast<jsize>(val[k].size());\r
+            jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_double1DArray, NULL);\r
+            if (!jMiddleArr) return nullptr;\r
+            for (jsize i = 0; i < lenMiddle; ++i)\r
+            {
+                jsize lenInner = static_cast<jsize>(val[k][i].size());
+                jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);\r
+                if (!jDoubleArray) return nullptr;\r
+                const double* doubles = &val[k][i][0];\r
+                env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
+                if (env->ExceptionCheck()) return nullptr;
+                env->SetObjectArrayElement(jMiddleArr, i, jDoubleArray);
+                if (env->ExceptionCheck()) return nullptr;
+                env->DeleteLocalRef(jDoubleArray);
+            }
+            env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jMiddleArr);
+        }
+        return jOuterArr;
+    }
+
+    jobject operator()(const std::vector<std::vector<bool>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean1DArray, 0);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize i = 0; i < lenOuter; ++i)\r
+        {
+            size_t lenInner = val[i].size();
+            jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);\r
+            if (!jBooleanArray) return nullptr;\r
+            jboolean* booleans = new jboolean[lenInner];\r
+            for (size_t j = 0; j < lenInner; ++j) {\r
+                booleans[j] = static_cast<jboolean>(val[i][j]);\r
+            }\r
+            env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
+            if (env->ExceptionCheck()) return nullptr;
+            env->SetObjectArrayElement(jOuterArr, i, jBooleanArray);
+            if (env->ExceptionCheck()) return nullptr;
+            env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jBooleanArray);
+        }
+        return jOuterArr;
+    }
+    jobject operator()(const std::vector<std::vector<std::vector<bool>>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean2DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize k = 0; k < lenOuter; ++k)\r
+        {\r
+            jsize lenMiddle = static_cast<jsize>(val[k].size());\r
+            jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_boolean1DArray, NULL);\r
+            if (!jMiddleArr) return nullptr;\r
+            for (jsize i = 0; i < lenMiddle; ++i)\r
+            {
+                size_t lenInner = val[k][i].size();
+                jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);\r
+                jboolean* booleans = new jboolean[lenInner];\r
+                for (size_t j = 0; j < lenInner; ++j) {\r
+                    booleans[j] = val[k][i][j];\r
+                }\r
+                env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
+                if (env->ExceptionCheck()) return nullptr;
+                env->SetObjectArrayElement(jMiddleArr, i, jBooleanArray);\r
+                if (env->ExceptionCheck()) return nullptr;\r
+                env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
+                if (env->ExceptionCheck()) return nullptr;
+                env->DeleteLocalRef(jBooleanArray);
+            }
+            env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jMiddleArr);
+        }
+        return jOuterArr;
+    }
+
+    jobject operator()(const std::vector<std::vector<std::string>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String1DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize i = 0; i < lenOuter; ++i)\r
+        {
+            jsize lenInner = static_cast<jsize>(val[i].size());\r
+            jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, NULL);\r
+            if (!strArr) return nullptr;\r
+            for (jsize j = 0; j < lenInner; ++j)\r
+            {\r
+                jstring jString = env->NewStringUTF(val[i][j].c_str());\r
+                env->SetObjectArrayElement(strArr, j, jString);\r
+                if (env->ExceptionCheck()) return nullptr;\r
+                env->DeleteLocalRef(jString);\r
+            }
+            env->SetObjectArrayElement(jOuterArr, i, strArr);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(strArr);
+        }
+
+        return jOuterArr;
+    }
+    jobject operator()(const std::vector<std::vector<std::vector<std::string>>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String2DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize k = 0; k < lenOuter; ++k)\r
+        {\r
+            jsize lenMiddle = static_cast<jsize>(val[k].size());\r
+            jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_String1DArray, NULL);\r
+            if (!jMiddleArr) return nullptr;\r
+            for (jsize i = 0; i < lenMiddle; ++i)\r
+            {
+                jsize lenInner = static_cast<jsize>(val[k][i].size());\r
+                jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, NULL);\r
+                if (!strArr) return nullptr;\r
+                for (jsize j = 0; j < lenInner; ++j)\r
+                {\r
+                    jstring jString = env->NewStringUTF(val[k][i][j].c_str());\r
+                    env->SetObjectArrayElement(strArr, j, jString);\r
+                    if (env->ExceptionCheck()) return nullptr;\r
+                    env->DeleteLocalRef(jString);\r
+                }
+                env->SetObjectArrayElement(jMiddleArr, i, strArr);
+                if (env->ExceptionCheck()) return nullptr;
+                env->DeleteLocalRef(strArr);
+            }
+            env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jMiddleArr);
+        }
+        return jOuterArr;
+    }
+
+    jobject operator()(const std::vector<std::vector<OC::OCRepresentation>>& val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation1DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize i = 0; i < lenOuter; ++i)\r
+        {
+            jsize lenInner = static_cast<jsize>(val[i].size());\r
+            jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, NULL);\r
+            if (!repArr) return nullptr;\r
+            for (jsize j = 0; j < lenInner; ++j)\r
+            {\r
+                OCRepresentation* rep = new OCRepresentation(val[i][j]);\r
+                jlong handle = reinterpret_cast<jlong>(rep);\r
+                jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+                    handle, true);\r
+                if (!jRepresentation)\r
+                {\r
+                    delete rep;\r
+                    return nullptr;\r
+                }\r
+                env->SetObjectArrayElement(repArr, j, jRepresentation);\r
+                if (env->ExceptionCheck()) return nullptr;\r
+                env->DeleteLocalRef(jRepresentation);\r
+            }
+            env->SetObjectArrayElement(jOuterArr, i, repArr);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(repArr);
+        }
+        return jOuterArr;
+    }
+    jobject operator()(const std::vector<std::vector<std::vector<OC::OCRepresentation>>>& val) const\r
+    {\r
+        jsize lenOuter = static_cast<jsize>(val.size());\r
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation2DArray, NULL);\r
+        if (!jOuterArr) return nullptr;\r
+        for (jsize k = 0; k < lenOuter; ++k)\r
+        {\r
+            jsize lenMiddle = static_cast<jsize>(val[k].size());\r
+            jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_OcRepresentation1DArray, NULL);\r
+            if (!jMiddleArr) return nullptr;\r
+            for (jsize i = 0; i < lenMiddle; ++i)\r
+            {
+                jsize lenInner = static_cast<jsize>(val[k][i].size());\r
+                jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, NULL);\r
+                if (!repArr) return nullptr;\r
+                for (jsize j = 0; j < lenInner; ++j)\r
+                {\r
+                    OCRepresentation* rep = new OCRepresentation(val[k][i][j]);\r
+                    jlong handle = reinterpret_cast<jlong>(rep);\r
+                    jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+                        handle, true);\r
+                    if (!jRepresentation)\r
+                    {\r
+                        delete rep;\r
+                        return nullptr;\r
+                    }\r
+                    env->SetObjectArrayElement(repArr, j, jRepresentation);\r
+                    if (env->ExceptionCheck()) return nullptr;\r
+                    env->DeleteLocalRef(jRepresentation);\r
+                }
+                env->SetObjectArrayElement(jMiddleArr, i, repArr);
+                if (env->ExceptionCheck()) return nullptr;
+                env->DeleteLocalRef(repArr);
+            }
+            env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
+            if (env->ExceptionCheck()) return nullptr;
+            env->DeleteLocalRef(jMiddleArr);
+        }
+        return jOuterArr;\r
+    }\r
+\r
+private:\r
+    JNIEnv *env;\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    getValueN\r
+    * Signature: (Ljava/lang/String;)Ljava/lang/Object;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValueN\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueInteger\r
+    * Signature: (Ljava/lang/String;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger\r
+        (JNIEnv *, jobject, jstring, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueDouble\r
+    * Signature: (Ljava/lang/String;D)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble\r
+        (JNIEnv *, jobject, jstring, jdouble);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueBoolean\r
+    * Signature: (Ljava/lang/String;Z)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean\r
+        (JNIEnv *, jobject, jstring, jboolean);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueStringN\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringN\r
+        (JNIEnv *, jobject, jstring, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueRepresentation\r
+    * Signature: (Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentation\r
+        (JNIEnv *, jobject, jstring, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueIntegerArray\r
+    * Signature: (Ljava/lang/String;[I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueIntegerArray\r
+        (JNIEnv *, jobject, jstring, jintArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueInteger2DArray\r
+    * Signature: (Ljava/lang/String;[[I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger2DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueInteger3DArray\r
+    * Signature: (Ljava/lang/String;[[[I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger3DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueDoubleArray\r
+    * Signature: (Ljava/lang/String;[D)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDoubleArray\r
+        (JNIEnv *, jobject, jstring, jdoubleArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueDouble2DArray\r
+    * Signature: (Ljava/lang/String;[[D)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble2DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueDouble3DArray\r
+    * Signature: (Ljava/lang/String;[[[D)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble3DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueBooleanArray\r
+    * Signature: (Ljava/lang/String;[Z)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBooleanArray\r
+        (JNIEnv *, jobject, jstring, jbooleanArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueBoolean2DArray\r
+    * Signature: (Ljava/lang/String;[[Z)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean2DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueBoolean3DArray\r
+    * Signature: (Ljava/lang/String;[[[Z)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean3DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueStringArray\r
+    * Signature: (Ljava/lang/String;[Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueString2DArray\r
+    * Signature: (Ljava/lang/String;[[Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString2DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueString3DArray\r
+    * Signature: (Ljava/lang/String;[[[Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString3DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueRepresentationArray\r
+    * Signature: (Ljava/lang/String;[Lorg/iotivity/base/OcRepresentation;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentationArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueRepresentation2DArray\r
+    * Signature: (Ljava/lang/String;[[Lorg/iotivity/base/OcRepresentation;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentation2DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setValueRepresentation3DArray\r
+    * Signature: (Ljava/lang/String;[[[Lorg/iotivity/base/OcRepresentation;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresentation3DArray\r
+        (JNIEnv *, jobject, jstring, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    getJSONRepresentation\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getJSONRepresentation\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    addChild\r
+    * Signature: (Lorg/iotivity/base/OcRepresentation;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_addChild\r
+        (JNIEnv *, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    clearChildren\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_clearChildren\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    getChildrenArray\r
+    * Signature: ()[Lorg/iotivity/base/OcRepresentation;\r
+    */\r
+    JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcRepresentation_getChildrenArray\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    getUri\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getUri\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setUri\r
+    * Signature: (Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setUri\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    getResourceTypes\r
+    * Signature: ()Ljava/util/List;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceTypes\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setResourceTypeArray\r
+    * Signature: ([Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceTypeArray\r
+        (JNIEnv *, jobject, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    getResourceInterfaces\r
+    * Signature: ()Ljava/util/List;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceInterfaces\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setResourceInterfaceArray\r
+    * Signature: ([Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceInterfaceArray\r
+        (JNIEnv *, jobject, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    isEmpty\r
+    * Signature: ()Z\r
+    */\r
+    JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isEmpty\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    size\r
+    * Signature: ()I\r
+    */\r
+    JNIEXPORT jint JNICALL Java_org_iotivity_base_OcRepresentation_size\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    remove\r
+    * Signature: (Ljava/lang/String;)Z\r
+    */\r
+    JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_remove\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    hasAttribute\r
+    * Signature: (Ljava/lang/String;)Z\r
+    */\r
+    JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_hasAttribute\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    setNull\r
+    * Signature: (Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setNull\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    isNull\r
+    * Signature: (Ljava/lang/String;)Z\r
+    */\r
+    JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isNull\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    create\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_create\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRepresentation\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_dispose\r
+        (JNIEnv *, jobject, jboolean);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcRequestHandle.cpp b/android/android_api/base/jni/JniOcRequestHandle.cpp
new file mode 100644 (file)
index 0000000..444689d
--- /dev/null
@@ -0,0 +1,63 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcRequestHandle.h"\r
+\r
+JniOcRequestHandle::JniOcRequestHandle(OCRequestHandle requestHandle) : m_requestHandle(requestHandle)\r
+{}\r
+\r
+JniOcRequestHandle::~JniOcRequestHandle()\r
+{\r
+    LOGD("~JniOcRequestHandle()");\r
+}\r
+\r
+JniOcRequestHandle* JniOcRequestHandle::getJniOcRequestHandlePtr\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    JniOcRequestHandle *handle = GetHandle<JniOcRequestHandle>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from OcRequestHandle");\r
+    }\r
+    if (!handle)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return handle;\r
+}\r
+\r
+OCRequestHandle JniOcRequestHandle::getOCRequestHandle()\r
+{\r
+    return this->m_requestHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcRequestHandle\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcRequestHandle_dispose\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcRequestHandle_dispose");\r
+    JniOcRequestHandle *handle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, thiz);\r
+    delete handle;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcRequestHandle.h b/android/android_api/base/jni/JniOcRequestHandle.h
new file mode 100644 (file)
index 0000000..2160728
--- /dev/null
@@ -0,0 +1,58 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include "ocstack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcRequestHandle\r
+#define _Included_org_iotivity_base_OcRequestHandle\r
+\r
+class JniOcRequestHandle\r
+{\r
+public:\r
+\r
+    JniOcRequestHandle(OCRequestHandle request);\r
+    ~JniOcRequestHandle();\r
+\r
+    static JniOcRequestHandle* getJniOcRequestHandlePtr(JNIEnv *env, jobject thiz);\r
+\r
+    OCRequestHandle getOCRequestHandle();\r
+\r
+private:\r
+    OCRequestHandle m_requestHandle;\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcRequestHandle\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcRequestHandle_dispose\r
+        (JNIEnv *, jobject);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOcResource.cpp b/android/android_api/base/jni/JniOcResource.cpp
new file mode 100644 (file)
index 0000000..2850d65
--- /dev/null
@@ -0,0 +1,1520 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+\r
+#include "JniOcResource.h"\r
+#include "JniOcRepresentation.h"\r
+#include "JniUtils.h"\r
+\r
+JniOcResource::JniOcResource(std::shared_ptr<OCResource> resource)\r
+    : m_sharedResource(resource)\r
+{}\r
+\r
+JniOcResource::~JniOcResource()\r
+{\r
+    LOGD("~JniOcResource()");\r
+    m_sharedResource = NULL;\r
+\r
+    jint envRet;\r
+    JNIEnv *env = GetJNIEnv(envRet);\r
+    if (NULL == env) return;\r
+\r
+    m_onGetManager.removeAllListeners(env);\r
+    m_onPutManager.removeAllListeners(env);\r
+    m_onPostManager.removeAllListeners(env);\r
+    m_onDeleteManager.removeAllListeners(env);\r
+    m_onObserveManager.removeAllListeners(env);\r
+\r
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+OCStackResult JniOcResource::get(JNIEnv* env, const QueryParamsMap &queryParametersMap, jobject jListener)\r
+{\r
+    JniOnGetListener *onGetListener = addOnGetListener(env, jListener);\r
+\r
+    GetCallback getCallback = [onGetListener](\r
+        const HeaderOptions& opts,\r
+        const OCRepresentation& rep,\r
+        const int eCode)\r
+    {\r
+        onGetListener->onGetCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->get(queryParametersMap, getCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::get(JNIEnv* env, const QueryParamsMap &queryParametersMap, jobject jListener,\r
+    QualityOfService QoS)\r
+{\r
+    JniOnGetListener *onGetListener = addOnGetListener(env, jListener);\r
+\r
+    GetCallback getCallback = [onGetListener](const HeaderOptions& opts, const OCRepresentation& rep,\r
+        const int eCode)\r
+    {\r
+        onGetListener->onGetCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->get(queryParametersMap, getCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::get(\r
+    JNIEnv* env,\r
+    const std::string &resourceType,\r
+    const std::string &resourceInterface,\r
+    const QueryParamsMap &queryParametersMap,\r
+    jobject jListener)\r
+{\r
+    JniOnGetListener *onGetListener = addOnGetListener(env, jListener);\r
+\r
+    GetCallback getCallback = [onGetListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onGetListener->onGetCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->get(resourceType, resourceInterface, queryParametersMap,\r
+        getCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::get(JNIEnv* env, const std::string &resourceType,\r
+    const std::string &resourceInterface, const QueryParamsMap &queryParametersMap,\r
+    jobject jListener, QualityOfService QoS)\r
+{\r
+    JniOnGetListener *onGetListener = addOnGetListener(env, jListener);\r
+\r
+    GetCallback getCallback = [onGetListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onGetListener->onGetCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->get(resourceType, resourceInterface, queryParametersMap,\r
+        getCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::put(JNIEnv* env, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener)\r
+{\r
+    JniOnPutListener *onPutListener = addOnPutListener(env, jListener);\r
+\r
+    PutCallback putCallback = [onPutListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPutListener->onPutCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->put(representation, queryParametersMap, putCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::put(JNIEnv* env, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS)\r
+{\r
+    JniOnPutListener *onPutListener = addOnPutListener(env, jListener);\r
+\r
+    PutCallback putCallback = [onPutListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPutListener->onPutCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->put(representation, queryParametersMap, putCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::put(JNIEnv* env, const std::string &resourceType,\r
+    const std::string &resourceInterface, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener)\r
+{\r
+    JniOnPutListener *onPutListener = addOnPutListener(env, jListener);\r
+\r
+    PutCallback putCallback = [onPutListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPutListener->onPutCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->put(resourceType, resourceInterface, representation,\r
+        queryParametersMap, putCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::put(JNIEnv* env, const std::string &resourceType,\r
+    const std::string &resourceInterface, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS)\r
+{\r
+    JniOnPutListener *onPutListener = addOnPutListener(env, jListener);\r
+\r
+    PutCallback putCallback = [onPutListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPutListener->onPutCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->put(resourceType, resourceInterface, representation,\r
+        queryParametersMap, putCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::post(JNIEnv* env, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener)\r
+{\r
+    JniOnPostListener *onPostListener = addOnPostListener(env, jListener);\r
+\r
+    PostCallback postCallback = [onPostListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPostListener->onPostCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->post(representation, queryParametersMap, postCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::post(JNIEnv* env, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS)\r
+{\r
+    JniOnPostListener *onPostListener = addOnPostListener(env, jListener);\r
+\r
+    PostCallback postCallback = [onPostListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPostListener->onPostCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->post(representation, queryParametersMap, postCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::post(JNIEnv* env, const std::string &resourceType,\r
+    const std::string &resourceInterface, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener)\r
+{\r
+    JniOnPostListener *onPostListener = addOnPostListener(env, jListener);\r
+\r
+    PostCallback postCallback = [onPostListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPostListener->onPostCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->post(resourceType, resourceInterface, representation,\r
+        queryParametersMap, postCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::post(JNIEnv* env, const std::string &resourceType,\r
+    const std::string &resourceInterface, const OCRepresentation &representation,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS)\r
+{\r
+    JniOnPostListener *onPostListener = addOnPostListener(env, jListener);\r
+\r
+    PostCallback postCallback = [onPostListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int eCode)\r
+    {\r
+        onPostListener->onPostCallback(opts, rep, eCode);\r
+    };\r
+\r
+    return m_sharedResource->post(resourceType, resourceInterface, representation,\r
+        queryParametersMap, postCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::deleteResource(JNIEnv* env, jobject jListener)\r
+{\r
+    JniOnDeleteListener *onDeleteListener = addOnDeleteListener(env, jListener);\r
+\r
+    DeleteCallback deleteCallback = [onDeleteListener](const HeaderOptions& opts,\r
+        const int eCode)\r
+    {\r
+        onDeleteListener->onDeleteCallback(opts, eCode);\r
+    };\r
+\r
+    return m_sharedResource->deleteResource(deleteCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::deleteResource(JNIEnv* env, jobject jListener, QualityOfService QoS)\r
+{\r
+    JniOnDeleteListener *onDeleteListener = addOnDeleteListener(env, jListener);\r
+\r
+    DeleteCallback deleteCallback = [onDeleteListener](const HeaderOptions& opts, const int eCode)\r
+    {\r
+        onDeleteListener->onDeleteCallback(opts, eCode);\r
+    };\r
+\r
+    return m_sharedResource->deleteResource(deleteCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::observe(JNIEnv* env, ObserveType observeType,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener)\r
+{\r
+    JniOnObserveListener *onObserveListener = addOnObserveListener(env, jListener);\r
+\r
+    ObserveCallback observeCallback = [onObserveListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int& eCode, const int& sequenceNumber)\r
+    {\r
+        onObserveListener->onObserveCallback(opts, rep, eCode, sequenceNumber);\r
+    };\r
+\r
+    return m_sharedResource->observe(observeType, queryParametersMap, observeCallback);\r
+}\r
+\r
+OCStackResult JniOcResource::observe(JNIEnv* env, ObserveType observeType,\r
+    const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS)\r
+{\r
+    JniOnObserveListener *onObserveListener = addOnObserveListener(env, jListener);\r
+\r
+    ObserveCallback observeCallback = [onObserveListener](const HeaderOptions& opts,\r
+        const OCRepresentation& rep, const int& eCode, const int& sequenceNumber)\r
+    {\r
+        onObserveListener->onObserveCallback(opts, rep, eCode, sequenceNumber);\r
+    };\r
+\r
+    return m_sharedResource->observe(observeType, queryParametersMap, observeCallback, QoS);\r
+}\r
+\r
+OCStackResult JniOcResource::cancelObserve(JNIEnv* env)\r
+{\r
+    this->m_onObserveManager.removeAllListeners(env);\r
+    return m_sharedResource->cancelObserve();\r
+}\r
+\r
+OCStackResult JniOcResource::cancelObserve(JNIEnv* env, QualityOfService qos)\r
+{\r
+    //TODO confirm behavior\r
+    //add removal of java listeners by qos\r
+    this->m_onObserveManager.removeAllListeners(env);\r
+    return m_sharedResource->cancelObserve(qos);\r
+}\r
+\r
+void JniOcResource::setHeaderOptions(const HeaderOptions &headerOptions)\r
+{\r
+    m_sharedResource->setHeaderOptions(headerOptions);\r
+}\r
+\r
+void JniOcResource::unsetHeaderOptions()\r
+{\r
+    m_sharedResource->unsetHeaderOptions();\r
+}\r
+\r
+std::string JniOcResource::host()\r
+{\r
+    return m_sharedResource->host();\r
+}\r
+\r
+std::string JniOcResource::uri()\r
+{\r
+    return m_sharedResource->uri();\r
+}\r
+\r
+OCConnectivityType JniOcResource::connectivityType() const\r
+{\r
+    return m_sharedResource->connectivityType();\r
+}\r
+\r
+bool JniOcResource::isObservable()\r
+{\r
+    return m_sharedResource->isObservable();\r
+}\r
+\r
+std::vector< std::string > JniOcResource::getResourceTypes() const\r
+{\r
+    return m_sharedResource->getResourceTypes();\r
+}\r
+\r
+std::vector< std::string > JniOcResource::getResourceInterfaces(void) const\r
+{\r
+    return m_sharedResource->getResourceInterfaces();\r
+}\r
+\r
+OCResourceIdentifier JniOcResource::uniqueIdentifier() const\r
+{\r
+    return m_sharedResource->uniqueIdentifier();\r
+}\r
+\r
+std::string JniOcResource::sid() const\r
+{\r
+    return m_sharedResource->sid();\r
+}\r
+\r
+JniOnGetListener* JniOcResource::addOnGetListener(JNIEnv* env, jobject jListener)\r
+{\r
+    return this->m_onGetManager.addListener(env, jListener, this);\r
+}\r
+\r
+JniOnPutListener* JniOcResource::addOnPutListener(JNIEnv* env, jobject jListener)\r
+{\r
+    return this->m_onPutManager.addListener(env, jListener, this);\r
+}\r
+\r
+JniOnPostListener* JniOcResource::addOnPostListener(JNIEnv* env, jobject jListener)\r
+{\r
+    return this->m_onPostManager.addListener(env, jListener, this);\r
+}\r
+\r
+JniOnDeleteListener* JniOcResource::addOnDeleteListener(JNIEnv* env, jobject jListener)\r
+{\r
+    return this->m_onDeleteManager.addListener(env, jListener, this);\r
+}\r
+\r
+JniOnObserveListener* JniOcResource::addOnObserveListener(JNIEnv* env, jobject jListener)\r
+{\r
+    return this->m_onObserveManager.addListener(env, jListener, this);\r
+}\r
+\r
+void JniOcResource::removeOnGetListener(JNIEnv* env, jobject jListener)\r
+{\r
+    this->m_onGetManager.removeListener(env, jListener);\r
+}\r
+\r
+void JniOcResource::removeOnPutListener(JNIEnv* env, jobject jListener)\r
+{\r
+    this->m_onPutManager.removeListener(env, jListener);\r
+}\r
+\r
+void JniOcResource::removeOnPostListener(JNIEnv* env, jobject jListener)\r
+{\r
+    this->m_onPostManager.removeListener(env, jListener);\r
+}\r
+\r
+void JniOcResource::removeOnDeleteListener(JNIEnv* env, jobject jListener)\r
+{\r
+    this->m_onDeleteManager.removeListener(env, jListener);\r
+}\r
+\r
+void JniOcResource::removeOnObserveListener(JNIEnv* env, jobject jListener)\r
+{\r
+    this->m_onObserveManager.removeListener(env, jListener);\r
+}\r
+\r
+std::shared_ptr<OCResource> JniOcResource::getOCResource()\r
+{\r
+    return this->m_sharedResource;\r
+}\r
+\r
+JniOcResource* JniOcResource::getJniOcResourcePtr(JNIEnv *env, jobject thiz)\r
+{\r
+    JniOcResource *resource = GetHandle<JniOcResource>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from OcResource");\r
+    }\r
+    if (!resource)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return resource;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    get\r
+* Signature: (Ljava/util/Map;Lorg/iotivity/base/OcResource/OnGetListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get\r
+(JNIEnv *env, jobject thiz, jobject jQueryParamsMap, jobject jListener)\r
+{\r
+    LOGD("OcResource_get");\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onGetListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->get(\r
+            env,\r
+            qpm,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_get");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    get1\r
+* Signature: (Ljava/util/Map;Lorg/iotivity/base/OcResource/OnGetListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get1\r
+(JNIEnv *env, jobject thiz, jobject jQueryParamsMap, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_get");\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onGetListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->get(\r
+            env,\r
+            qpm,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_get");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    get2\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;\r
+Lorg/iotivity/base/OcResource/OnGetListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get2\r
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,\r
+jobject jQueryParamsMap, jobject jListener)\r
+{\r
+    LOGD("OcResource_get");\r
+    std::string resourceType;\r
+    if (jResourceType)\r
+    {\r
+        resourceType = env->GetStringUTFChars(jResourceType, NULL);\r
+    }\r
+    std::string resourceInterface;\r
+    if (jResourceInterface)\r
+    {\r
+        resourceInterface = env->GetStringUTFChars(jResourceInterface, NULL);\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onGetListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+    try\r
+    {\r
+        OCStackResult result = resource->get(\r
+            env,\r
+            resourceType,\r
+            resourceInterface,\r
+            qpm,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_get");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    get3\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;\r
+Lorg/iotivity/base/OcResource/OnGetListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get3\r
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,\r
+jobject jQueryParamsMap, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_get");\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onGetListener cannot be null");\r
+        return;\r
+    }\r
+    std::string resourceType;\r
+    if (jResourceType)\r
+    {\r
+        resourceType = env->GetStringUTFChars(jResourceType, NULL);\r
+    }\r
+    std::string resourceInterface;\r
+    if (jResourceInterface)\r
+    {\r
+        resourceInterface = env->GetStringUTFChars(jResourceInterface, NULL);\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->get(\r
+            env,\r
+            resourceType,\r
+            resourceInterface,\r
+            qpm,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_get");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    put\r
+* Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;\r
+Lorg/iotivity/base/OcResource/OnPutListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put\r
+(JNIEnv *env, jobject thiz, jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)\r
+{\r
+    LOGD("OcResource_put");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPutListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->put(\r
+            env,\r
+            *representation,\r
+            qpm,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_put");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    put1\r
+* Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;\r
+Lorg/iotivity/base/OcResource/OnPutListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put1\r
+(JNIEnv *env, jobject thiz, jobject jRepresentation, jobject jQueryParamsMap,\r
+jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_put");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPutListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->put(\r
+            env,\r
+            *representation,\r
+            qpm,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_put");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    put2\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;\r
+Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPutListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put2\r
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,\r
+jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)\r
+{\r
+    LOGD("OcResource_put");\r
+    std::string resourceType;\r
+    if (jResourceType)\r
+    {\r
+        resourceType = env->GetStringUTFChars(jResourceType, NULL);\r
+    }\r
+    std::string resourceInterface;\r
+    if (jResourceInterface)\r
+    {\r
+        resourceInterface = env->GetStringUTFChars(jResourceInterface, NULL);\r
+    }\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPutListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->put(\r
+            env,\r
+            resourceType,\r
+            resourceInterface,\r
+            *representation,\r
+            qpm,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_put");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    put3\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;\r
+Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPutListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put3\r
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface, jobject jRepresentation,\r
+jobject jQueryParamsMap, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_put");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "representation cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPutListener cannot be null");\r
+        return;\r
+    }\r
+    std::string resourceType;\r
+    if (jResourceType)\r
+    {\r
+        resourceType = env->GetStringUTFChars(jResourceType, NULL);\r
+    }\r
+    std::string resourceInterface;\r
+    if (jResourceInterface)\r
+    {\r
+        resourceInterface = env->GetStringUTFChars(jResourceInterface, NULL);\r
+    }\r
+\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->put(\r
+            env,\r
+            resourceType,\r
+            resourceInterface,\r
+            *representation,\r
+            qpm,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_put");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    post\r
+* Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post\r
+(JNIEnv *env, jobject thiz, jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)\r
+{\r
+    LOGD("OcResource_post");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "representation cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPostListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->post(\r
+            env,\r
+            *representation,\r
+            qpm,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_post");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    post1\r
+* Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post1\r
+(JNIEnv *env, jobject thiz, jobject jRepresentation, jobject jQueryParamsMap, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_post");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "representation cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPostListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->post(\r
+            env,\r
+            *representation,\r
+            qpm,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_post");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    post2\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;\r
+Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post2\r
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,\r
+jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)\r
+{\r
+    LOGD("OcResource_post");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "representation cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPostListener cannot be null");\r
+        return;\r
+    }\r
+    std::string resourceType;\r
+    if (jResourceType)\r
+    {\r
+        resourceType = env->GetStringUTFChars(jResourceType, NULL);\r
+    }\r
+    std::string resourceInterface;\r
+    if (jResourceInterface)\r
+    {\r
+        resourceInterface = env->GetStringUTFChars(jResourceInterface, NULL);\r
+    }\r
+\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->post(\r
+            env,\r
+            resourceType,\r
+            resourceInterface,\r
+            *representation,\r
+            qpm,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_post");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    post3\r
+* Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;\r
+Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post3\r
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,\r
+jobject jRepresentation, jobject jQueryParamsMap, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_post");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "representation cannot be null");\r
+        return;\r
+    }\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onPostListener cannot be null");\r
+        return;\r
+    }\r
+    std::string resourceType;\r
+    if (jResourceType)\r
+    {\r
+        resourceType = env->GetStringUTFChars(jResourceType, NULL);\r
+    }\r
+    std::string resourceInterface;\r
+    if (jResourceInterface)\r
+    {\r
+        resourceInterface = env->GetStringUTFChars(jResourceInterface, NULL);\r
+    }\r
+\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);\r
+    if (!representation) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->post(\r
+            env,\r
+            resourceType,\r
+            resourceInterface,\r
+            *representation,\r
+            qpm,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_post");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    deleteResource\r
+* Signature: (Lorg/iotivity/base/OcResource/OnDeleteListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource\r
+(JNIEnv *env, jobject thiz, jobject jListener)\r
+{\r
+    LOGD("OcResource_deleteResource");\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onDeleteListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->deleteResource(\r
+            env,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_deleteResource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    deleteResource1\r
+* Signature: (Lorg/iotivity/base/OcResource/OnDeleteListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource1\r
+(JNIEnv *env, jobject thiz, jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_deleteResource");\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onDeleteListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->deleteResource(\r
+            env,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_deleteResource");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    observe\r
+* Signature: (Lorg/iotivity/base/ObserveType;Ljava/util/Map;\r
+Lorg/iotivity/base/OcResource/OnObserveListener;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_observe\r
+(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener)\r
+{\r
+    LOGD("OcResource_observe");\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onObserveListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->observe(\r
+            env,\r
+            JniUtils::getObserveType(env, static_cast<int>(observeType)),\r
+            qpm,\r
+            jListener);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_observe");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    observe1\r
+* Signature: (Lorg/iotivity/base/ObserveType;Ljava/util/Map;\r
+Lorg/iotivity/base/OcResource/OnObserveListener;I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_observe1\r
+(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap,\r
+jobject jListener, jint jQoS)\r
+{\r
+    LOGD("OcResource_observe");\r
+    if (!jQueryParamsMap)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "queryParamsMap cannot be null");\r
+        return;\r
+    }\r
+    if (!jListener)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onObserveListener cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    QueryParamsMap qpm;\r
+    JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->observe(\r
+            env,\r
+            JniUtils::getObserveType(env, static_cast<int>(observeType)),\r
+            qpm,\r
+            jListener,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_observe");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    cancelObserve\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_cancelObserve");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->cancelObserve(env);\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_cancelObserve");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    cancelObserve1\r
+* Signature: I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve1\r
+(JNIEnv *env, jobject thiz, jint jQoS)\r
+{\r
+    LOGD("OcResource_cancelObserve1");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    try\r
+    {\r
+        OCStackResult result = resource->cancelObserve(\r
+            env,\r
+            JniUtils::getQOS(env, static_cast<int>(jQoS)));\r
+\r
+        if (OC_STACK_OK != result)\r
+        {\r
+            ThrowOcException(result, "OcResource_cancelObserve");\r
+        }\r
+    }\r
+    catch (OCException& e)\r
+    {\r
+        LOGE("%s", e.reason().c_str());\r
+        ThrowOcException(e.code(), e.reason().c_str());\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    setHeaderOptions\r
+* Signature: ([Lorg/iotivity/OcHeaderOption;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_setHeaderOptions\r
+(JNIEnv *env, jobject thiz, jobjectArray jheaderOptionArr)\r
+{\r
+    LOGD("OcResource_setHeaderOptions");\r
+    if (!jheaderOptionArr)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "headerOptionList cannot be null");\r
+        return;\r
+    }\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    HeaderOptions headerOptions;\r
+    JniUtils::convertJavaHeaderOptionsArrToVector(env, jheaderOptionArr, headerOptions);\r
+\r
+    resource->setHeaderOptions(headerOptions);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    unsetHeaderOptions\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_unsetHeaderOptions\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_unsetHeaderOptions");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return;\r
+\r
+    resource->unsetHeaderOptions();\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    getHost\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getHost\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_getHost");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return nullptr;\r
+\r
+    return env->NewStringUTF(resource->host().c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    getUri\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getUri\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_getUri");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return nullptr;\r
+\r
+    return env->NewStringUTF(resource->uri().c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    getConnectivityTypeN\r
+* Signature: ()I\r
+*/\r
+JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResource_getConnectivityTypeN\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_getConnectivityType");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return -1;\r
+\r
+    OCConnectivityType connectivityType = resource->connectivityType();\r
+    return static_cast<jint>(connectivityType);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    isObservable\r
+* Signature: ()Z\r
+*/\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResource_isObservable\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_isObservable");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    return (jboolean)resource->isObservable();\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    getResourceTypes\r
+* Signature: ()Ljava/util/List;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceTypes\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_getResourceTypes");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return nullptr;\r
+\r
+    std::vector<std::string> resourceTypes = resource->getResourceTypes();\r
+\r
+    return JniUtils::convertStrVectorToJavaStrList(env, resourceTypes);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    getResourceInterfaces\r
+* Signature: ()Ljava/util/List;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceInterfaces\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_getResourceInterfaces");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return nullptr;\r
+\r
+    std::vector<std::string> resourceInterfaces = resource->getResourceInterfaces();\r
+\r
+    return JniUtils::convertStrVectorToJavaStrList(env, resourceInterfaces);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    getUniqueIdentifier\r
+* Signature: ()Lorg/iotivity/base/OcResourceIdentifier;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getUniqueIdentifier\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_getUniqueIdentifier");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return nullptr;\r
+\r
+    JniOcResourceIdentifier *jniResourceIdentifier =\r
+        new JniOcResourceIdentifier(resource->uniqueIdentifier());\r
+    if (!jniResourceIdentifier) return nullptr;\r
+\r
+    jlong handle = reinterpret_cast<jlong>(jniResourceIdentifier);\r
+    jobject jResourceIdentifier = env->NewObject(g_cls_OcResourceIdentifier,\r
+        g_mid_OcResourceIdentifier_N_ctor, handle);\r
+    if (!jResourceIdentifier)\r
+    {\r
+        delete jniResourceIdentifier;\r
+    }\r
+    return jResourceIdentifier;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    getServerId\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getServerId\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_getServerId");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    if (!resource) return nullptr;\r
+\r
+    return env->NewStringUTF(resource->sid().c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResource\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_dispose\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResource_dispose");\r
+    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);\r
+    delete resource;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResource.h b/android/android_api/base/jni/JniOcResource.h
new file mode 100644 (file)
index 0000000..737dd5f
--- /dev/null
@@ -0,0 +1,359 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+\r
+#include "JniOcStack.h"\r
+#include "OCResource.h"\r
+#include "JniListenerManager.h"\r
+#include "JniOnGetListener.h"\r
+#include "JniOnPutListener.h"\r
+#include "JniOnPostListener.h"\r
+#include "JniOnDeleteListener.h"\r
+#include "JniOnObserveListener.h"\r
+#include "JniOcResourceIdentifier.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResource\r
+#define _Included_org_iotivity_base_OcResource\r
+\r
+using namespace OC;\r
+\r
+class JniOcResource\r
+{\r
+public:\r
+    JniOcResource(std::shared_ptr<OCResource> resource);\r
+    ~JniOcResource();\r
+\r
+    OCStackResult get(JNIEnv* env, const QueryParamsMap &queryParametersMap, jobject jListener);\r
+    OCStackResult get(JNIEnv* env, const QueryParamsMap &queryParametersMap, jobject jListener,\r
+        QualityOfService QoS);\r
+    OCStackResult get(JNIEnv* env, const std::string &resourceType, const std::string &resourceInterface,\r
+        const QueryParamsMap &queryParametersMap, jobject jListener);\r
+    OCStackResult get(JNIEnv* env, const std::string &resourceType, const std::string &resourceInterface,\r
+        const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS);\r
+\r
+    OCStackResult put(JNIEnv* env, const OCRepresentation &representation, const QueryParamsMap &queryParametersMap,\r
+        jobject jListener);\r
+    OCStackResult put(JNIEnv* env, const OCRepresentation &representation, const QueryParamsMap &queryParametersMap,\r
+        jobject jListener, QualityOfService QoS);\r
+    OCStackResult put(JNIEnv* env, const std::string &resourceType, const std::string &resourceInterface,\r
+        const OCRepresentation &representation, const QueryParamsMap &queryParametersMap, jobject jListener);\r
+    OCStackResult put(JNIEnv* env, const std::string &resourceType, const std::string &resourceInterface,\r
+        const OCRepresentation &representation, const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS);\r
+\r
+    OCStackResult post(JNIEnv* env, const OCRepresentation &representation, const QueryParamsMap &queryParametersMap,\r
+        jobject jListener);\r
+    OCStackResult post(JNIEnv* env, const OCRepresentation &representation, const QueryParamsMap &queryParametersMap,\r
+        jobject jListener, QualityOfService QoS);\r
+    OCStackResult post(JNIEnv* env, const std::string &resourceType, const std::string &resourceInterface,\r
+        const OCRepresentation &representation, const QueryParamsMap &queryParametersMap, jobject jListener);\r
+    OCStackResult post(JNIEnv* env, const std::string &resourceType, const std::string &resourceInterface,\r
+        const OCRepresentation &representation, const QueryParamsMap &queryParametersMap, jobject jListener, QualityOfService QoS);\r
+\r
+    OCStackResult deleteResource(JNIEnv* env, jobject jListener);\r
+    OCStackResult deleteResource(JNIEnv* env, jobject jListener, QualityOfService QoS);\r
+\r
+    OCStackResult observe(JNIEnv* env, ObserveType observeType, const QueryParamsMap &queryParametersMap,\r
+        jobject jListener);\r
+    OCStackResult observe(JNIEnv* env, ObserveType observeType, const QueryParamsMap &queryParametersMap,\r
+        jobject jListener, QualityOfService qos);\r
+\r
+    OCStackResult cancelObserve(JNIEnv* env);\r
+    OCStackResult cancelObserve(JNIEnv* env, QualityOfService qos);\r
+\r
+    void setHeaderOptions(const HeaderOptions &headerOptions);\r
+    void unsetHeaderOptions();\r
+    std::string host();\r
+    std::string uri();\r
+    OCConnectivityType connectivityType() const;\r
+    bool isObservable();\r
+    std::vector< std::string >         getResourceTypes() const;\r
+    std::vector< std::string >         getResourceInterfaces(void) const;\r
+    OCResourceIdentifier uniqueIdentifier() const;\r
+    std::string sid() const;\r
+\r
+    JniOnGetListener* addOnGetListener(JNIEnv* env, jobject jListener);\r
+    JniOnPutListener* addOnPutListener(JNIEnv* env, jobject jListener);\r
+    JniOnPostListener* addOnPostListener(JNIEnv* env, jobject jListener);\r
+    JniOnDeleteListener* addOnDeleteListener(JNIEnv* env, jobject jListener);\r
+    JniOnObserveListener* addOnObserveListener(JNIEnv* env, jobject jListener);\r
+\r
+    void removeOnGetListener(JNIEnv* env, jobject jListener);\r
+    void removeOnPutListener(JNIEnv* env, jobject jListener);\r
+    void removeOnPostListener(JNIEnv* env, jobject jListener);\r
+    void removeOnDeleteListener(JNIEnv* env, jobject jListener);\r
+    void removeOnObserveListener(JNIEnv* env, jobject jListener);\r
+\r
+    std::shared_ptr<OCResource> getOCResource();\r
+\r
+    static JniOcResource* getJniOcResourcePtr(JNIEnv *env, jobject thiz);\r
+\r
+private:\r
+    JniListenerManager<JniOnGetListener> m_onGetManager;\r
+    JniListenerManager<JniOnPutListener> m_onPutManager;\r
+    JniListenerManager<JniOnPostListener> m_onPostManager;\r
+    JniListenerManager<JniOnDeleteListener> m_onDeleteManager;\r
+    JniListenerManager<JniOnObserveListener> m_onObserveManager;\r
+\r
+    std::shared_ptr<OCResource> m_sharedResource;\r
+};\r
+\r
+/* DO NOT EDIT THIS FILE BEYOND THIS LINE - it is machine generated */\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    get\r
+    * Signature: (Ljava/util/Map;Lorg/iotivity/base/OcResource/OnGetListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get\r
+        (JNIEnv *, jobject, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    get1\r
+    * Signature: (Ljava/util/Map;Lorg/iotivity/base/OcResource/OnGetListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get1\r
+        (JNIEnv *, jobject, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    get2\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnGetListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get2\r
+        (JNIEnv *, jobject, jstring, jstring, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    get3\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnGetListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get3\r
+        (JNIEnv *, jobject, jstring, jstring, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    put\r
+    * Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPutListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put\r
+        (JNIEnv *, jobject, jobject, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    put1\r
+    * Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPutListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put1\r
+        (JNIEnv *, jobject, jobject, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    put2\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPutListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put2\r
+        (JNIEnv *, jobject, jstring, jstring, jobject, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    put3\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPutListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put3\r
+        (JNIEnv *, jobject, jstring, jstring, jobject, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    post\r
+    * Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post\r
+        (JNIEnv *, jobject, jobject, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    post1\r
+    * Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post1\r
+        (JNIEnv *, jobject, jobject, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    post2\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post2\r
+        (JNIEnv *, jobject, jstring, jstring, jobject, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    post3\r
+    * Signature: (Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/OcRepresentation;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnPostListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post3\r
+        (JNIEnv *, jobject, jstring, jstring, jobject, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    deleteResource\r
+    * Signature: (Lorg/iotivity/base/OcResource/OnDeleteListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource\r
+        (JNIEnv *, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    deleteResource1\r
+    * Signature: (Lorg/iotivity/base/OcResource/OnDeleteListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource1\r
+        (JNIEnv *, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    observe\r
+    * Signature: (Lorg/iotivity/base/ObserveType;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnObserveListener;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_observe\r
+        (JNIEnv *, jobject, jint, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    observe1\r
+    * Signature: (Lorg/iotivity/base/ObserveType;Ljava/util/Map;Lorg/iotivity/base/OcResource/OnObserveListener;I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_observe1\r
+        (JNIEnv *, jobject, jint, jobject, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    cancelObserve\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    cancelObserve1\r
+    * Signature: (I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve1\r
+        (JNIEnv *, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    setHeaderOptions\r
+    * Signature: ([Lorg/iotivity/OcHeaderOption;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_setHeaderOptions\r
+        (JNIEnv *, jobject, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    unsetHeaderOptions\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_unsetHeaderOptions\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    getHost\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getHost\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    getUri\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getUri\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    getConnectivityTypeN\r
+    * Signature: ()I\r
+    */\r
+    JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResource_getConnectivityTypeN\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    isObservable\r
+    * Signature: ()Z\r
+    */\r
+    JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResource_isObservable\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    getResourceTypes\r
+    * Signature: ()Ljava/util/List;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceTypes\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    getResourceInterfaces\r
+    * Signature: ()Ljava/util/List;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceInterfaces\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    getUniqueIdentifier\r
+    * Signature: ()Lorg/iotivity/base/OcResourceIdentifier;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getUniqueIdentifier\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    getServerId\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getServerId\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResource\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_dispose\r
+        (JNIEnv *, jobject);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResourceHandle.cpp b/android/android_api/base/jni/JniOcResourceHandle.cpp
new file mode 100644 (file)
index 0000000..84f748e
--- /dev/null
@@ -0,0 +1,66 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcResourceHandle.h"\r
+\r
+using namespace OC;\r
+\r
+JniOcResourceHandle::JniOcResourceHandle(OCResourceHandle resourceHandle)\r
+    : m_resourceHandle(resourceHandle)\r
+{}\r
+\r
+JniOcResourceHandle::~JniOcResourceHandle()\r
+{\r
+    LOGD("~JniOcResourceHandle()");\r
+}\r
+\r
+JniOcResourceHandle* JniOcResourceHandle::getJniOcResourceHandlePtr\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    JniOcResourceHandle *handle = GetHandle<JniOcResourceHandle>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from OcResourceHandle");\r
+    }\r
+    if (!handle)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return handle;\r
+}\r
+\r
+OCResourceHandle JniOcResourceHandle::getOCResourceHandle()\r
+{\r
+    return this->m_resourceHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceHandle\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceHandle_dispose\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceHandle_dispose");\r
+    JniOcResourceHandle *resourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, thiz);\r
+    delete resourceHandle;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResourceHandle.h b/android/android_api/base/jni/JniOcResourceHandle.h
new file mode 100644 (file)
index 0000000..b8b4e1c
--- /dev/null
@@ -0,0 +1,56 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include "JniEntityHandler.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResourceHandle\r
+#define _Included_org_iotivity_base_OcResourceHandle\r
+\r
+class JniOcResourceHandle\r
+{\r
+public:\r
+    JniOcResourceHandle(OCResourceHandle resourceHandle);\r
+    ~JniOcResourceHandle();\r
+\r
+    static JniOcResourceHandle* getJniOcResourceHandlePtr(JNIEnv *env, jobject thiz);\r
+\r
+    OCResourceHandle getOCResourceHandle();\r
+private:\r
+    OCResourceHandle m_resourceHandle;\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceHandle\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceHandle_dispose\r
+        (JNIEnv *, jobject);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOcResourceIdentifier.cpp b/android/android_api/base/jni/JniOcResourceIdentifier.cpp
new file mode 100644 (file)
index 0000000..59b918c
--- /dev/null
@@ -0,0 +1,89 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+\r
+#include "JniOcResourceIdentifier.h"\r
+\r
+JniOcResourceIdentifier::JniOcResourceIdentifier(OC::OCResourceIdentifier resourceIdentifier)\r
+    : m_resourceIdentifier(resourceIdentifier)\r
+{}\r
+\r
+JniOcResourceIdentifier::~JniOcResourceIdentifier()\r
+{\r
+    LOGD("~JniOcResourceIdentifier()");\r
+}\r
+\r
+OC::OCResourceIdentifier JniOcResourceIdentifier::getOCResourceIdentifier()\r
+{\r
+    return this->m_resourceIdentifier;\r
+}\r
+\r
+JniOcResourceIdentifier* JniOcResourceIdentifier::getJniOcResourceIdentifierPtr\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    JniOcResourceIdentifier *identifier = GetHandle<JniOcResourceIdentifier>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from OcResourceIdentifier");\r
+    }\r
+    if (!identifier)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return identifier;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceIdentifier\r
+* Method:    equalsN\r
+* Signature: (Lorg/iotivity/base/OcResourceIdentifier;)Z\r
+*/\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResourceIdentifier_equalsN\r
+(JNIEnv *env, jobject jThiz, jobject jOther)\r
+{\r
+    JniOcResourceIdentifier *thiz = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jThiz);\r
+    if (!thiz) return false;\r
+\r
+    JniOcResourceIdentifier *other = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jOther);\r
+    if (!other) return false;\r
+\r
+    if (thiz->getOCResourceIdentifier() == other->getOCResourceIdentifier())\r
+    {\r
+        return true;\r
+    }\r
+    else\r
+    {\r
+        return false;\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceIdentifier\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceIdentifier_dispose\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("JniOcResourceIdentifier_dispose");\r
+    JniOcResourceIdentifier *identifier = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, thiz);\r
+    delete identifier;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResourceIdentifier.h b/android/android_api/base/jni/JniOcResourceIdentifier.h
new file mode 100644 (file)
index 0000000..9c7651a
--- /dev/null
@@ -0,0 +1,65 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include "OCResource.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResourceIdentifier\r
+#define _Included_org_iotivity_base_OcResourceIdentifier\r
+\r
+class JniOcResourceIdentifier\r
+{\r
+public:\r
+\r
+    JniOcResourceIdentifier(OC::OCResourceIdentifier identifier);\r
+    ~JniOcResourceIdentifier();\r
+\r
+    static JniOcResourceIdentifier* getJniOcResourceIdentifierPtr(JNIEnv *env, jobject thiz);\r
+\r
+    OC::OCResourceIdentifier getOCResourceIdentifier();\r
+\r
+private:\r
+    OC::OCResourceIdentifier m_resourceIdentifier;\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceIdentifier\r
+    * Method:    equalsN\r
+    * Signature: (Lorg/iotivity/base/OcResourceIdentifier;)Z\r
+    */\r
+    JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResourceIdentifier_equalsN\r
+        (JNIEnv *, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceIdentifier\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceIdentifier_dispose\r
+        (JNIEnv *, jobject);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResourceRequest.cpp b/android/android_api/base/jni/JniOcResourceRequest.cpp
new file mode 100644 (file)
index 0000000..b1d981c
--- /dev/null
@@ -0,0 +1,321 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcResourceRequest.h"\r
+#include "OCResourceRequest.h"\r
+#include "JniOcResourceHandle.h"\r
+#include "JniOcRequestHandle.h"\r
+#include "JniUtils.h"\r
+\r
+using namespace OC;\r
+\r
+JniOcResourceRequest::JniOcResourceRequest(const std::shared_ptr<OCResourceRequest> request)\r
+    : m_request(request)\r
+{}\r
+\r
+JniOcResourceRequest::~JniOcResourceRequest()\r
+{}\r
+\r
+std::string\r
+JniOcResourceRequest::getRequestType()\r
+{\r
+    return m_request->getRequestType();\r
+}\r
+\r
+const QueryParamsMap&\r
+JniOcResourceRequest::getQueryParameters() const\r
+{\r
+    return m_request->getQueryParameters();\r
+}\r
+\r
+int\r
+JniOcResourceRequest::getRequestHandlerFlag() const\r
+{\r
+    return m_request->getRequestHandlerFlag();\r
+}\r
+\r
+const OCRepresentation&\r
+JniOcResourceRequest::getResourceRepresentation() const\r
+{\r
+    return m_request->getResourceRepresentation();\r
+}\r
+\r
+const ObservationInfo&\r
+JniOcResourceRequest::getObservationInfo() const\r
+{\r
+    return m_request->getObservationInfo();\r
+}\r
+\r
+void\r
+JniOcResourceRequest::setResourceUri(const std::string resourceUri)\r
+{\r
+    m_request->setResourceUri(resourceUri);\r
+}\r
+\r
+std::string\r
+JniOcResourceRequest::getResourceUri(void)\r
+{\r
+    return m_request->getResourceUri();\r
+}\r
+\r
+const HeaderOptions&\r
+JniOcResourceRequest::getHeaderOptions() const\r
+{\r
+    return m_request->getHeaderOptions();\r
+}\r
+\r
+const OCRequestHandle&\r
+JniOcResourceRequest::getRequestHandle() const\r
+{\r
+    return m_request->getRequestHandle();\r
+}\r
+\r
+const OCResourceHandle&\r
+JniOcResourceRequest::getResourceHandle() const\r
+{\r
+    return m_request->getResourceHandle();\r
+}\r
+\r
+JniOcResourceRequest* JniOcResourceRequest::getJniOcResourceRequestPtr\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    JniOcResourceRequest *request = GetHandle<JniOcResourceRequest>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from OcResourceRequest");\r
+    }\r
+    if (!request)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return request;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getRequestTypeNative\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestTypeNative\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getRequestTypeNative");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    std::string requestType = request->getRequestType();\r
+    return env->NewStringUTF(requestType.c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getQueryParameters\r
+* Signature: ()Ljava/util/Map;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getQueryParameters\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getQueryParameters");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    return JniUtils::convertQueryParamsMapToJavaMap(env, request->getQueryParameters());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getRequestHandlerFlagNative\r
+* Signature: ()I\r
+*/\r
+JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHandlerFlagNative\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getRequestHandlerFlagNative");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return -1;\r
+\r
+    return static_cast<jint>(request->getRequestHandlerFlag());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getResourceRepresentation\r
+* Signature: ()Lorg/iotivity/base/OcRepresentation;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceRepresentation\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getResourceRepresentation");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    OCRepresentation *ocRepresentation = new OCRepresentation(request->getResourceRepresentation());\r
+    if (!ocRepresentation) return nullptr;\r
+\r
+    jlong handle = reinterpret_cast<jlong>(ocRepresentation);\r
+    jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+        handle, true);\r
+    if (!jRepresentation)\r
+    {\r
+        LOGE("Failed to create OcRepresentation");\r
+        delete ocRepresentation;\r
+    }\r
+\r
+    return jRepresentation;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getObservationInfo\r
+* Signature: ()Lorg/iotivity/base/ObservationInfo;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getObservationInfo\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getObservationInfo");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    ObservationInfo oInfo = request->getObservationInfo();\r
+\r
+    jobject jObservationInfo = env->NewObject(g_cls_ObservationInfo, g_mid_ObservationInfo_N_ctor,\r
+        (jint)oInfo.action, (jbyte)oInfo.obsId);\r
+\r
+    if (!jObservationInfo)\r
+    {\r
+        LOGE("Failed to create ObservationInfo");\r
+    }\r
+\r
+    return jObservationInfo;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    setResourceUri\r
+* Signature: (Ljava/lang/String);\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_setResourceUri\r
+(JNIEnv *env, jobject thiz, jstring jUri)\r
+{\r
+    LOGD("OcResourceRequest_setResourceUri");\r
+    if (!jUri)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "URI cannot be null");\r
+        return;\r
+    }\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return;\r
+\r
+    request->setResourceUri(env->GetStringUTFChars(jUri, 0));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getResourceUri\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceUri\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getResourceUri");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    std::string requestUri = request->getResourceUri();\r
+    return env->NewStringUTF(requestUri.c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getHeaderOptions\r
+* Signature: ()Ljava/util/List;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getHeaderOptions\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getHeaderOptions");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    return JniUtils::convertHeaderOptionsVectorToJavaList(env, request->getHeaderOptions());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getRequestHandle\r
+* Signature: ()Lorg/iotivity/base/OcRequestHandle;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHandle\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getRequestHandle");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    JniOcRequestHandle* jniHandle = new JniOcRequestHandle(request->getRequestHandle());\r
+    jlong handle = reinterpret_cast<jlong>(jniHandle);\r
+    jobject jRequestHandle = env->NewObject(g_cls_OcRequestHandle, g_mid_OcRequestHandle_N_ctor, handle);\r
+    if (!jRequestHandle)\r
+    {\r
+        LOGE("Failed to create OcRequestHandle");\r
+        delete jniHandle;\r
+    }\r
+\r
+    return jRequestHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    getResourceHandle\r
+* Signature: ()Lorg/iotivity/base/OcResourceHandle;\r
+*/\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceHandle\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_getResourceHandle");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    if (!request) return nullptr;\r
+\r
+    JniOcResourceHandle* jniHandle = new JniOcResourceHandle(\r
+        request->getResourceHandle());\r
+    jlong handle = reinterpret_cast<jlong>(jniHandle);\r
+    jobject jResourceHandle = env->NewObject(g_cls_OcResourceHandle, g_mid_OcResourceHandle_N_ctor, handle);\r
+    if (!jResourceHandle)\r
+    {\r
+        LOGE("Failed to create OcResourceHandle");\r
+        delete jniHandle;\r
+    }\r
+\r
+    return jResourceHandle;\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceRequest\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_dispose\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceRequest_dispose");\r
+    JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);\r
+    delete request;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResourceRequest.h b/android/android_api/base/jni/JniOcResourceRequest.h
new file mode 100644 (file)
index 0000000..5b58f0c
--- /dev/null
@@ -0,0 +1,158 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResourceRequest\r
+#define _Included_org_iotivity_base_OcResourceRequest\r
+\r
+using namespace OC;\r
+\r
+class JniOcResourceRequest\r
+{\r
+public:\r
+    JniOcResourceRequest(const std::shared_ptr<OCResourceRequest> resourceRequest);\r
+\r
+    ~JniOcResourceRequest();\r
+\r
+    std::string getRequestType();\r
+\r
+    const QueryParamsMap& getQueryParameters() const;\r
+\r
+    int getRequestHandlerFlag() const;\r
+\r
+    const OCRepresentation& getResourceRepresentation() const;\r
+\r
+    const ObservationInfo& getObservationInfo() const;\r
+\r
+    void setResourceUri(const std::string resourceUri);\r
+\r
+    std::string getResourceUri(void);\r
+\r
+    const HeaderOptions& getHeaderOptions() const;\r
+\r
+    const OCRequestHandle& getRequestHandle() const;\r
+\r
+    const OCResourceHandle& getResourceHandle() const;\r
+\r
+    static JniOcResourceRequest* getJniOcResourceRequestPtr\r
+        (JNIEnv *env, jobject thiz);\r
+\r
+private:\r
+    std::shared_ptr<OCResourceRequest> m_request;\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getRequestTypeNative\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestTypeNative\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getQueryParameters\r
+    * Signature: ()Ljava/util/Map;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getQueryParameters\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getRequestHandlerFlagNative\r
+    * Signature: ()I\r
+    */\r
+    JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHandlerFlagNative\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getResourceRepresentation\r
+    * Signature: ()Lorg/iotivity/base/OcRepresentation;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceRepresentation\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getObservationInfo\r
+    * Signature: ()Lorg/iotivity/base/ObservationInfo;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getObservationInfo\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    setResourceUri\r
+    * Signature: (Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_setResourceUri\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getResourceUri\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceUri\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getHeaderOptions\r
+    * Signature: ()Ljava/util/List;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getHeaderOptions\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getRequestHandle\r
+    * Signature: ()Lorg/iotivity/base/OcRequestHandle;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHandle\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    getResourceHandle\r
+    * Signature: ()Lorg/iotivity/base/OcResourceHandle;\r
+    */\r
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceHandle\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceRequest\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_dispose\r
+        (JNIEnv *, jobject);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResourceResponse.cpp b/android/android_api/base/jni/JniOcResourceResponse.cpp
new file mode 100644 (file)
index 0000000..f8771c3
--- /dev/null
@@ -0,0 +1,320 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcResourceResponse.h"\r
+#include "OCResourceResponse.h"\r
+#include "JniOcRepresentation.h"\r
+#include "JniOcRequestHandle.h"\r
+#include "JniOcResourceHandle.h"\r
+#include "JniUtils.h"\r
+\r
+using namespace OC;\r
+\r
+JniOcResourceResponse::JniOcResourceResponse\r
+(std::shared_ptr<OCResourceResponse> resourceResponse)\r
+: m_response(resourceResponse){}\r
+\r
+JniOcResourceResponse::~JniOcResourceResponse()\r
+{}\r
+\r
+void JniOcResourceResponse::setErrorCode(const int eCode)\r
+{\r
+    this->m_response->setErrorCode(eCode);\r
+}\r
+\r
+std::string JniOcResourceResponse::getNewResourceUri(void)\r
+{\r
+    this->m_response->getNewResourceUri();\r
+}\r
+\r
+void\r
+JniOcResourceResponse::setNewResourceUri(const std::string newResourceUri)\r
+{\r
+    this->m_response->setNewResourceUri(newResourceUri);\r
+}\r
+\r
+void JniOcResourceResponse::setHeaderOptions(const HeaderOptions& headerOptions)\r
+{\r
+    this->m_response->setHeaderOptions(headerOptions);\r
+}\r
+\r
+void JniOcResourceResponse::setRequestHandle(const OCRequestHandle& requestHandle)\r
+{\r
+    this->m_response->setRequestHandle(requestHandle);\r
+}\r
+\r
+void JniOcResourceResponse::setResourceHandle(const OCResourceHandle& resourceHandle)\r
+{\r
+    this->m_response->setResourceHandle(resourceHandle);\r
+}\r
+\r
+void JniOcResourceResponse::setResponseResult(const OCEntityHandlerResult& responseResult)\r
+{\r
+    this->m_response->setResponseResult(responseResult);\r
+}\r
+\r
+void JniOcResourceResponse::setResourceRepresentation(OCRepresentation& rep,\r
+    std::string interfaceStr)\r
+{\r
+    this->m_response->setResourceRepresentation(rep, interfaceStr);\r
+}\r
+\r
+void JniOcResourceResponse::setResourceRepresentation(OCRepresentation& rep)\r
+{\r
+    this->m_response->setResourceRepresentation(rep);\r
+}\r
+\r
+std::shared_ptr<OCResourceResponse> JniOcResourceResponse::getOCResourceResponse()\r
+{\r
+    return this->m_response;\r
+}\r
+\r
+JniOcResourceResponse* JniOcResourceResponse::getJniOcResourceResponsePtr\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    JniOcResourceResponse *request = GetHandle<JniOcResourceResponse>(env, thiz);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to get native handle from JniOcResourceResponse");\r
+    }\r
+    if (!request)\r
+    {\r
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");\r
+    }\r
+    return request;\r
+}\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setErrorCode\r
+* Signature: (I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setErrorCode\r
+(JNIEnv *env, jobject thiz, jint eCode)\r
+{\r
+    LOGD("OcResourceResponse_setErrorCode");\r
+    JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!response) return;\r
+\r
+    response->setErrorCode(static_cast<int>(eCode));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    getNewResourceUri\r
+* Signature: ()Ljava/lang/String;\r
+*/\r
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceResponse_getNewResourceUri\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceResponse_getNewResourceUri");\r
+    JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!response) return nullptr;\r
+\r
+    return env->NewStringUTF(response->getNewResourceUri().c_str());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setNewResourceUri\r
+* Signature: (Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setNewResourceUri\r
+(JNIEnv *env, jobject thiz, jstring jstr)\r
+{\r
+    LOGD("OcResourceResponse_setNewResourceUri");\r
+    JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!response) return;\r
+\r
+    response->setNewResourceUri(env->GetStringUTFChars(jstr, 0));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setHeaderOptions\r
+* Signature: (Ljava/util/List;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setHeaderOptions\r
+(JNIEnv *env, jobject thiz, jobjectArray jHeaderOptions)\r
+{\r
+    LOGD("OcResourceResponse_setHeaderOptions");\r
+    if (!jHeaderOptions)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "headerOptionList cannot be null");\r
+        return;\r
+    }\r
+    JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!jniResponse) return;\r
+\r
+    HeaderOptions headerOptions;\r
+    JniUtils::convertJavaHeaderOptionsArrToVector(env, jHeaderOptions, headerOptions);\r
+\r
+    jniResponse->setHeaderOptions(headerOptions);\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setRequestHandle\r
+* Signature: (Lorg/iotivity/base/OcRequestHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setRequestHandle\r
+(JNIEnv *env, jobject thiz, jobject jRequestHandle)\r
+{\r
+    LOGI("OcResourceResponse_setRequestHandle");\r
+    if (!jRequestHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "requestHandle cannot be null");\r
+        return;\r
+    }\r
+    JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!jniResponse) return;\r
+\r
+    JniOcRequestHandle* jniOcRequestHandle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, jRequestHandle);\r
+    if (!jniOcRequestHandle) return;\r
+\r
+    jniResponse->setRequestHandle(jniOcRequestHandle->getOCRequestHandle());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setResourceHandle\r
+* Signature: (Lorg/iotivity/base/OcResourceHandle;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceHandle\r
+(JNIEnv *env, jobject thiz, jobject jResourceHandle)\r
+{\r
+    LOGI("OcResourceResponse_setResourceHandle");\r
+    if (!jResourceHandle)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");\r
+        return;\r
+    }\r
+    JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!jniResponse) return;\r
+\r
+    JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);\r
+    if (!jniOcResourceHandle) return;\r
+\r
+    jniResponse->setResourceHandle(jniOcResourceHandle->getOCResourceHandle());\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setResponseResult\r
+* Signature: (I)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResponseResult\r
+(JNIEnv *env, jobject thiz, jint responseResult)\r
+{\r
+    LOGD("OcResourceResponse_setResponseResult");\r
+    JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!response) return;\r
+\r
+    response->setResponseResult(JniUtils::getOCEntityHandlerResult(env, static_cast<int>(responseResult)));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setResourceRepresentation\r
+* Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/lang/String;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation\r
+(JNIEnv *env, jobject thiz, jobject jRepresentation, jstring jstr)\r
+{\r
+    LOGD("OcResourceResponse_setResourceRepresentation");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "Representation cannot be null");\r
+        return;\r
+    }\r
+    if (!jstr)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "interface cannot be null");\r
+        return;\r
+    }\r
+\r
+    JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env,\r
+        thiz);\r
+    if (!response) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,\r
+        jRepresentation);\r
+    if (!representation) return;\r
+\r
+    response->setResourceRepresentation(*representation, env->GetStringUTFChars(jstr, 0));\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    setResourceRepresentation1\r
+* Signature: (Lorg/iotivity/base/OcRepresentation;)V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation1\r
+(JNIEnv *env, jobject thiz, jobject jRepresentation)\r
+{\r
+    LOGD("OcResourceResponse_setResourceRepresentation");\r
+    if (!jRepresentation)\r
+    {\r
+        ThrowOcException(OC_STACK_INVALID_PARAM, "Representation cannot be null");\r
+        return;\r
+    }\r
+    JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    if (!response) return;\r
+\r
+    OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,\r
+        jRepresentation);\r
+\r
+    if (representation)\r
+    {\r
+        response->setResourceRepresentation(*representation);\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    create\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_create\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGI("OcResourceResponse_create");\r
+    auto pResponse = std::make_shared<OC::OCResourceResponse>();\r
+    JniOcResourceResponse* jniResourceResponse = new JniOcResourceResponse(pResponse);\r
+    SetHandle<JniOcResourceResponse>(env, thiz, jniResourceResponse);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Failed to create OcResourceResponse");\r
+        delete jniResourceResponse;\r
+    }\r
+}\r
+\r
+/*\r
+* Class:     org_iotivity_base_OcResourceResponse\r
+* Method:    dispose\r
+* Signature: ()V\r
+*/\r
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_dispose\r
+(JNIEnv *env, jobject thiz)\r
+{\r
+    LOGD("OcResourceResponse_dispose");\r
+    JniOcResourceResponse *resp = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);\r
+    delete resp;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcResourceResponse.h b/android/android_api/base/jni/JniOcResourceResponse.h
new file mode 100644 (file)
index 0000000..acabdf6
--- /dev/null
@@ -0,0 +1,144 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include "OCResourceResponse.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResourceResponse\r
+#define _Included_org_iotivity_base_OcResourceResponse\r
+\r
+using namespace OC;\r
+\r
+class JniOcResourceResponse\r
+{\r
+public:\r
+    JniOcResourceResponse(std::shared_ptr<OCResourceResponse> resourceResponse);\r
+    ~JniOcResourceResponse();\r
+    void setErrorCode(const int eCode);\r
+    std::string getNewResourceUri(void);\r
+    void setNewResourceUri(const std::string newResourceUri);\r
+    void setHeaderOptions(const HeaderOptions& headerOptions);\r
+    void setRequestHandle(const OCRequestHandle& requestHandle);\r
+    void setResourceHandle(const OCResourceHandle& resourceHandle);\r
+    void setResponseResult(const OCEntityHandlerResult& responseResult);\r
+    void setResourceRepresentation(OCRepresentation& rep, std::string interfaceStr);\r
+    void setResourceRepresentation(OCRepresentation& rep);\r
+    std::shared_ptr<OCResourceResponse> getOCResourceResponse();\r
+    static JniOcResourceResponse* getJniOcResourceResponsePtr(JNIEnv *env, jobject thiz);\r
+private:\r
+    std::shared_ptr<OCResourceResponse> m_response;\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setErrorCode\r
+    * Signature: (I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setErrorCode\r
+        (JNIEnv *, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    getNewResourceUri\r
+    * Signature: ()Ljava/lang/String;\r
+    */\r
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceResponse_getNewResourceUri\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setNewResourceUri\r
+    * Signature: (Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setNewResourceUri\r
+        (JNIEnv *, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setHeaderOptions\r
+    * Signature: (Ljava/util/List;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setHeaderOptions\r
+        (JNIEnv *, jobject, jobjectArray);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setRequestHandle\r
+    * Signature: (Lorg/iotivity/base/OcRequestHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setRequestHandle\r
+        (JNIEnv *, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setResourceHandle\r
+    * Signature: (Lorg/iotivity/base/OcResourceHandle;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceHandle\r
+        (JNIEnv *, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setResponseResult\r
+    * Signature: (I)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResponseResult\r
+        (JNIEnv *, jobject, jint);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setResourceRepresentation\r
+    * Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/lang/String;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation\r
+        (JNIEnv *, jobject, jobject, jstring);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    setResourceRepresentation1\r
+    * Signature: (Lorg/iotivity/base/OcRepresentation;)V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation1\r
+        (JNIEnv *, jobject, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    create\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_create\r
+        (JNIEnv *, jobject);\r
+\r
+    /*\r
+    * Class:     org_iotivity_base_OcResourceResponse\r
+    * Method:    dispose\r
+    * Signature: ()V\r
+    */\r
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_dispose\r
+        (JNIEnv *, jobject);\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcStack.cpp b/android/android_api/base/jni/JniOcStack.cpp
new file mode 100644 (file)
index 0000000..5f6c1d4
--- /dev/null
@@ -0,0 +1,449 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include "OCApi.h"\r
+#include "OCPlatform.h"\r
+#include "OCRepresentation.h"\r
+#include "JniUtils.h"\r
+\r
+JavaVM* g_jvm = NULL;\r
+\r
+jclass g_cls_Integer = NULL;\r
+jclass g_cls_int1DArray = NULL;\r
+jclass g_cls_int2DArray = NULL;\r
+jclass g_cls_Double = NULL;\r
+jclass g_cls_double1DArray = NULL;\r
+jclass g_cls_double2DArray = NULL;\r
+jclass g_cls_Boolean = NULL;\r
+jclass g_cls_boolean1DArray = NULL;\r
+jclass g_cls_boolean2DArray = NULL;\r
+jclass g_cls_String = NULL;\r
+jclass g_cls_String1DArray = NULL;\r
+jclass g_cls_String2DArray = NULL;\r
+jclass g_cls_LinkedList = NULL;\r
+jclass g_cls_Map = NULL;\r
+jclass g_cls_MapEntry = NULL;\r
+jclass g_cls_Set = NULL;\r
+jclass g_cls_Iterator = NULL;\r
+jclass g_cls_HashMap = NULL;\r
+jclass g_cls_OcException = NULL;\r
+jclass g_cls_OcResource = NULL;\r
+jclass g_cls_OcRepresentation = NULL;\r
+jclass g_cls_OcRepresentation1DArray = NULL;\r
+jclass g_cls_OcRepresentation2DArray = NULL;\r
+jclass g_cls_OcResourceRequest = NULL;\r
+jclass g_cls_OcResourceResponse = NULL;\r
+jclass g_cls_OcResourceHandle = NULL;\r
+jclass g_cls_OcPresenceHandle = NULL;\r
+jclass g_cls_OcRequestHandle = NULL;\r
+jclass g_cls_OcPresenceStatus = NULL;\r
+jclass g_cls_OcHeaderOption = NULL;\r
+jclass g_cls_ObservationInfo = NULL;\r
+jclass g_cls_OcResourceIdentifier = NULL;\r
+\r
+jmethodID g_mid_Integer_ctor = NULL;\r
+jmethodID g_mid_Double_ctor = NULL;\r
+jmethodID g_mid_Boolean_ctor = NULL;\r
+jmethodID g_mid_LinkedList_ctor = NULL;\r
+jmethodID g_mid_LinkedList_add_object = NULL;\r
+jmethodID g_mid_Map_entrySet = NULL;\r
+jmethodID g_mid_MapEntry_getKey = NULL;\r
+jmethodID g_mid_MapEntry_getValue = NULL;\r
+jmethodID g_mid_Set_iterator = NULL;\r
+jmethodID g_mid_Iterator_hasNext = NULL;\r
+jmethodID g_mid_Iterator_next = NULL;\r
+jmethodID g_mid_HashMap_ctor = NULL;\r
+jmethodID g_mid_HashMap_put = NULL;\r
+jmethodID g_mid_OcException_ctor = NULL;\r
+jmethodID g_mid_OcException_setNativeExceptionLocation = NULL;\r
+jmethodID g_mid_OcResource_ctor = NULL;\r
+jmethodID g_mid_OcRepresentation_N_ctor = NULL;\r
+jmethodID g_mid_OcRepresentation_N_ctor_bool = NULL;\r
+jmethodID g_mid_OcResourceRequest_N_ctor = NULL;\r
+jmethodID g_mid_OcResourceResponse_N_ctor = NULL;\r
+jmethodID g_mid_OcResourceHandle_N_ctor = NULL;\r
+jmethodID g_mid_OcPresenceHandle_N_ctor = NULL;\r
+jmethodID g_mid_OcRequestHandle_N_ctor = NULL;\r
+jmethodID g_mid_OcHeaderOption_ctor = NULL;\r
+jmethodID g_mid_OcHeaderOption_get_id = NULL;\r
+jmethodID g_mid_OcHeaderOption_get_data = NULL;\r
+jmethodID g_mid_ObservationInfo_N_ctor = NULL;\r
+jmethodID g_mid_OcPresenceStatus_get = NULL;\r
+jmethodID g_mid_OcResourceIdentifier_N_ctor = NULL;\r
+\r
+jobject getOcException(JNIEnv* env, const char* file, const char* functionName,\r
+    const int line, const int code, const char* message)\r
+{\r
+    std::string codeStr = JniUtils::stackResultToStr(code);\r
+    if (codeStr.empty())\r
+    {\r
+        codeStr = JniUtils::stackResultToStr(JNI_INVALID_VALUE);\r
+    }\r
+    jobject ex = env->NewObject(g_cls_OcException,\r
+        g_mid_OcException_ctor,\r
+        env->NewStringUTF(codeStr.c_str()),\r
+        env->NewStringUTF(message));\r
+    if (!ex)\r
+    {\r
+        return nullptr;\r
+    }\r
+    env->CallVoidMethod(ex,\r
+        g_mid_OcException_setNativeExceptionLocation,\r
+        env->NewStringUTF(file),\r
+        env->NewStringUTF(functionName),\r
+        line);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        return nullptr;\r
+    }\r
+    return ex;\r
+}\r
+\r
+void throwOcException(JNIEnv* env, jobject ex)\r
+{\r
+    env->Throw((jthrowable)ex);\r
+}\r
+\r
+// JNI OnLoad\r
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)\r
+{\r
+    LOGI("JNI_OnLoad");\r
+    JNIEnv* env;\r
+    g_jvm = vm;\r
+\r
+    if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)\r
+    {\r
+        LOGE("Failed to get the environment using GetEnv()");\r
+        return JNI_ERR;\r
+    }\r
+\r
+    jclass clazz = nullptr;\r
+\r
+    //Integer\r
+    clazz = env->FindClass("java/lang/Integer");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_Integer = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_Integer_ctor = env->GetMethodID(g_cls_Integer, "<init>", "(I)V");\r
+    if (!g_mid_Integer_ctor) return JNI_ERR;\r
+\r
+    clazz = env->FindClass("[I");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_int1DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    clazz = env->FindClass("[[I");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_int2DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    //Double\r
+    clazz = env->FindClass("java/lang/Double");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_Double = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_Double_ctor = env->GetMethodID(g_cls_Double, "<init>", "(D)V");\r
+    if (!g_mid_Double_ctor) return JNI_ERR;\r
+\r
+    clazz = env->FindClass("[D");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_double1DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    clazz = env->FindClass("[[D");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_double2DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    //Boolean\r
+    clazz = env->FindClass("java/lang/Boolean");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_Boolean = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_Boolean_ctor = env->GetMethodID(g_cls_Boolean, "<init>", "(Z)V");\r
+    if (!g_mid_Boolean_ctor) return JNI_ERR;\r
+\r
+    clazz = env->FindClass("[Z");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_boolean1DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    clazz = env->FindClass("[[Z");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_boolean2DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    //String\r
+    clazz = env->FindClass("java/lang/String");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_String = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    clazz = env->FindClass("[Ljava/lang/String;");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_String1DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    clazz = env->FindClass("[[Ljava/lang/String;");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_String2DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    //LinkedList\r
+    clazz = env->FindClass("java/util/LinkedList");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_LinkedList = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_LinkedList_ctor = env->GetMethodID(g_cls_LinkedList, "<init>", "()V");\r
+    if (!g_mid_LinkedList_ctor) return JNI_ERR;\r
+\r
+    g_mid_LinkedList_add_object = env->GetMethodID(g_cls_LinkedList, "add", "(Ljava/lang/Object;)Z");\r
+    if (!g_mid_LinkedList_add_object) return JNI_ERR;\r
+\r
+    //Map\r
+    clazz = env->FindClass("java/util/Map");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_Map = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()Ljava/util/Set;");\r
+    if (!g_mid_Map_entrySet) return JNI_ERR;\r
+\r
+    //MapEntry\r
+    clazz = env->FindClass("java/util/Map$Entry");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_MapEntry = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey", "()Ljava/lang/Object;");\r
+    if (!g_mid_MapEntry_getKey) return JNI_ERR;\r
+    g_mid_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue", "()Ljava/lang/Object;");\r
+    if (!g_mid_MapEntry_getValue) return JNI_ERR;\r
+\r
+    //Set\r
+    clazz = env->FindClass("java/util/Set");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_Set = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_Set_iterator = env->GetMethodID(g_cls_Set, "iterator", "()Ljava/util/Iterator;");\r
+    if (!g_mid_Set_iterator) return JNI_ERR;\r
+\r
+    //Iterator\r
+    clazz = env->FindClass("java/util/Iterator");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_Iterator = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");\r
+    if (!g_mid_Iterator_hasNext) return JNI_ERR;\r
+\r
+    g_mid_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()Ljava/lang/Object;");\r
+    if (!g_mid_Iterator_next) return JNI_ERR;\r
+\r
+    //HashMap\r
+    clazz = env->FindClass("java/util/HashMap");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_HashMap = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_HashMap_ctor = env->GetMethodID(g_cls_HashMap, "<init>", "()V");\r
+    if (!g_mid_HashMap_ctor) return JNI_ERR;\r
+\r
+    g_mid_HashMap_put = env->GetMethodID(g_cls_HashMap, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");\r
+    if (!g_mid_HashMap_put) return JNI_ERR;\r
+\r
+    //OcException\r
+    clazz = env->FindClass("org/iotivity/base/OcException");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcException = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_OcException_ctor = env->GetMethodID(g_cls_OcException, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");\r
+    if (!g_mid_OcException_ctor) return JNI_ERR;\r
+\r
+    g_mid_OcException_setNativeExceptionLocation = env->GetMethodID(g_cls_OcException, "setNativeExceptionLocation",\r
+        "(Ljava/lang/String;""Ljava/lang/String;""I)V");\r
+    if (!g_mid_OcException_setNativeExceptionLocation) return JNI_ERR;\r
+\r
+    //OcResource\r
+    clazz = env->FindClass("org/iotivity/base/OcResource");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcResource = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_OcResource_ctor = env->GetMethodID(g_cls_OcResource, "<init>", "(J)V");\r
+    if (!g_mid_OcResource_ctor) return JNI_ERR;\r
+\r
+    //OcRepresentation\r
+    clazz = env->FindClass("org/iotivity/base/OcRepresentation");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcRepresentation = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_OcRepresentation_N_ctor = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(J)V");\r
+    if (!g_mid_OcRepresentation_N_ctor) return JNI_ERR;\r
+\r
+    g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");\r
+    if (!g_mid_OcRepresentation_N_ctor_bool) return JNI_ERR;\r
+\r
+    clazz = env->FindClass("[Lorg/iotivity/base/OcRepresentation;");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcRepresentation1DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    clazz = env->FindClass("[[Lorg/iotivity/base/OcRepresentation;");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcRepresentation2DArray = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    //HeaderOptions\r
+    clazz = env->FindClass("org/iotivity/base/OcHeaderOption");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcHeaderOption = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+    g_mid_OcHeaderOption_ctor = env->GetMethodID(g_cls_OcHeaderOption, "<init>", "(ILjava/lang/String;)V");\r
+    if (!g_mid_OcHeaderOption_ctor) return JNI_ERR;\r
+\r
+    g_mid_OcHeaderOption_get_id = env->GetMethodID(g_cls_OcHeaderOption, "getOptionId", "()I");\r
+    if (!g_mid_OcHeaderOption_get_id) return JNI_ERR;\r
+\r
+    g_mid_OcHeaderOption_get_data = env->GetMethodID(g_cls_OcHeaderOption, "getOptionData", "()Ljava/lang/String;");\r
+    if (!g_mid_OcHeaderOption_get_data) return JNI_ERR;\r
+\r
+    //OcResourceRequest\r
+    clazz = env->FindClass("org/iotivity/base/OcResourceRequest");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcResourceRequest = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_OcResourceRequest_N_ctor = env->GetMethodID(g_cls_OcResourceRequest, "<init>", "(J)V");\r
+    if (!g_mid_OcResourceRequest_N_ctor) return JNI_ERR;\r
+\r
+    //OcResourceResponse\r
+    clazz = env->FindClass("org/iotivity/base/OcResourceResponse");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcResourceResponse = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+\r
+    g_mid_OcResourceResponse_N_ctor = env->GetMethodID(g_cls_OcResourceResponse, "<init>", "(J)V");\r
+    if (!g_mid_OcResourceResponse_N_ctor) return JNI_ERR;\r
+\r
+    //OcResourceHandle\r
+    clazz = env->FindClass("org/iotivity/base/OcResourceHandle");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcResourceHandle = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+    g_mid_OcResourceHandle_N_ctor = env->GetMethodID(g_cls_OcResourceHandle, "<init>", "(J)V");\r
+    if (!g_mid_OcResourceHandle_N_ctor) return JNI_ERR;\r
+\r
+    //OcPresenceHandle\r
+    clazz = env->FindClass("org/iotivity/base/OcPresenceHandle");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcPresenceHandle = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+    g_mid_OcPresenceHandle_N_ctor = env->GetMethodID(g_cls_OcPresenceHandle, "<init>", "(J)V");\r
+    if (!g_mid_OcPresenceHandle_N_ctor) return JNI_ERR;\r
+\r
+    //OcRequestHandle\r
+    clazz = env->FindClass("org/iotivity/base/OcRequestHandle");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcRequestHandle = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+    g_mid_OcRequestHandle_N_ctor = env->GetMethodID(g_cls_OcRequestHandle, "<init>", "(J)V");\r
+    if (!g_mid_OcRequestHandle_N_ctor) return JNI_ERR;\r
+\r
+    //OcPresenceStatus\r
+    clazz = env->FindClass("org/iotivity/base/OcPresenceStatus");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcPresenceStatus = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+    g_mid_OcPresenceStatus_get = env->GetStaticMethodID(g_cls_OcPresenceStatus, "get",\r
+        "(Ljava/lang/String;)Lorg/iotivity/base/OcPresenceStatus;");\r
+    if (!g_mid_OcPresenceStatus_get) return JNI_ERR;\r
+\r
+    //ObservationInfo\r
+    clazz = env->FindClass("org/iotivity/base/ObservationInfo");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_ObservationInfo = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+    g_mid_ObservationInfo_N_ctor = env->GetMethodID(g_cls_ObservationInfo, "<init>", "(IB)V");\r
+    if (!g_mid_ObservationInfo_N_ctor) return JNI_ERR;\r
+\r
+    clazz = env->FindClass("org/iotivity/base/OcResourceIdentifier");\r
+    if (!clazz) return JNI_ERR;\r
+    g_cls_OcResourceIdentifier = (jclass)env->NewGlobalRef(clazz);\r
+    env->DeleteLocalRef(clazz);\r
+    g_mid_OcResourceIdentifier_N_ctor = env->GetMethodID(g_cls_OcResourceIdentifier, "<init>", "(J)V");\r
+    if (!g_mid_OcResourceIdentifier_N_ctor) return JNI_ERR;\r
+\r
+    return JNI_CURRENT_VERSION;\r
+}\r
+\r
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)\r
+{\r
+    LOGI("JNI_OnUnload");\r
+    JNIEnv* env;\r
+\r
+    if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)\r
+    {\r
+        LOGE("Failed to get the environment using GetEnv()");\r
+        return;\r
+    }\r
+\r
+    env->DeleteGlobalRef(g_cls_Integer);\r
+    env->DeleteGlobalRef(g_cls_int1DArray);\r
+    env->DeleteGlobalRef(g_cls_int2DArray);\r
+    env->DeleteGlobalRef(g_cls_Double);\r
+    env->DeleteGlobalRef(g_cls_double1DArray);\r
+    env->DeleteGlobalRef(g_cls_double2DArray);\r
+    env->DeleteGlobalRef(g_cls_Boolean);\r
+    env->DeleteGlobalRef(g_cls_boolean1DArray);\r
+    env->DeleteGlobalRef(g_cls_boolean2DArray);\r
+    env->DeleteGlobalRef(g_cls_String);\r
+    env->DeleteGlobalRef(g_cls_String1DArray);\r
+    env->DeleteGlobalRef(g_cls_String2DArray);\r
+    env->DeleteGlobalRef(g_cls_LinkedList);\r
+    env->DeleteGlobalRef(g_cls_Map);\r
+    env->DeleteGlobalRef(g_cls_MapEntry);\r
+    env->DeleteGlobalRef(g_cls_Set);\r
+    env->DeleteGlobalRef(g_cls_Iterator);\r
+    env->DeleteGlobalRef(g_cls_HashMap);\r
+    env->DeleteGlobalRef(g_cls_OcResource);\r
+    env->DeleteGlobalRef(g_cls_OcException);\r
+    env->DeleteGlobalRef(g_cls_OcRepresentation);\r
+    env->DeleteGlobalRef(g_cls_OcRepresentation1DArray);\r
+    env->DeleteGlobalRef(g_cls_OcRepresentation2DArray);\r
+    env->DeleteGlobalRef(g_cls_OcResourceRequest);\r
+    env->DeleteGlobalRef(g_cls_OcResourceResponse);\r
+    env->DeleteGlobalRef(g_cls_OcResourceHandle);\r
+    env->DeleteGlobalRef(g_cls_OcPresenceHandle);\r
+    env->DeleteGlobalRef(g_cls_OcRequestHandle);\r
+    env->DeleteGlobalRef(g_cls_OcPresenceStatus);\r
+    env->DeleteGlobalRef(g_cls_OcHeaderOption);\r
+    env->DeleteGlobalRef(g_cls_ObservationInfo);\r
+    env->DeleteGlobalRef(g_cls_OcResourceIdentifier);\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOcStack.h b/android/android_api/base/jni/JniOcStack.h
new file mode 100644 (file)
index 0000000..bd0ddd5
--- /dev/null
@@ -0,0 +1,169 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include <jni.h>\r
+#include <android/log.h>\r
+#include "OCApi.h"\r
+\r
+#ifndef _Included_org_iotivity_base_ocstack\r
+#define _Included_org_iotivity_base_ocstack\r
+\r
+#define TAG "OIC-JNI"\r
+\r
+#define JNI_CURRENT_VERSION JNI_VERSION_1_6\r
+\r
+#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)\r
+#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)\r
+#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)\r
+\r
+#define JNI_EXCEPTION 1000\r
+#define JNI_NO_NATIVE_POINTER 1001\r
+#define JNI_INVALID_VALUE 1002\r
+#define JNI_NO_SUCH_KEY 1003\r
+\r
+jobject getOcException(JNIEnv* env, const char* file, const char* functionName, const int line,\r
+    const int code, const char* message);\r
+void throwOcException(JNIEnv* env, jobject ex);\r
+#define GetOcException(code, message) getOcException (env,__FILE__,__func__,__LINE__,code,message)\r
+#define ThrowOcException(code, message) throwOcException (env, GetOcException(code, message))\r
+\r
+extern JavaVM* g_jvm;\r
+\r
+extern jclass g_cls_Integer;\r
+extern jclass g_cls_int1DArray;\r
+extern jclass g_cls_int2DArray;\r
+extern jclass g_cls_Double;\r
+extern jclass g_cls_double1DArray;\r
+extern jclass g_cls_double2DArray;\r
+extern jclass g_cls_Boolean;\r
+extern jclass g_cls_boolean1DArray;\r
+extern jclass g_cls_boolean2DArray;\r
+extern jclass g_cls_String;\r
+extern jclass g_cls_String1DArray;\r
+extern jclass g_cls_String2DArray;\r
+extern jclass g_cls_LinkedList;\r
+extern jclass g_cls_Map;\r
+extern jclass g_cls_MapEntry;\r
+extern jclass g_cls_Set;\r
+extern jclass g_cls_Iterator;\r
+extern jclass g_cls_HashMap;\r
+extern jclass g_cls_OcException;\r
+extern jclass g_cls_OcResource;\r
+extern jclass g_cls_OcRepresentation;\r
+extern jclass g_cls_OcRepresentation1DArray;\r
+extern jclass g_cls_OcRepresentation2DArray;\r
+extern jclass g_cls_OcResourceRequest;\r
+extern jclass g_cls_OcResourceResponse;\r
+extern jclass g_cls_OcResourceHandle;\r
+extern jclass g_cls_OcPresenceHandle;\r
+extern jclass g_cls_OcRequestHandle;\r
+extern jclass g_cls_OcPresenceStatus;\r
+extern jclass g_cls_OcHeaderOption;\r
+extern jclass g_cls_ObservationInfo;\r
+extern jclass g_cls_OcResourceIdentifier;\r
+\r
+extern jmethodID g_mid_Integer_ctor;\r
+extern jmethodID g_mid_Double_ctor;\r
+extern jmethodID g_mid_Boolean_ctor;\r
+extern jmethodID g_mid_LinkedList_ctor;\r
+extern jmethodID g_mid_LinkedList_add_object;\r
+extern jmethodID g_mid_Map_entrySet;\r
+extern jmethodID g_mid_MapEntry_getKey;\r
+extern jmethodID g_mid_MapEntry_getValue;\r
+extern jmethodID g_mid_Set_iterator;\r
+extern jmethodID g_mid_Iterator_hasNext;\r
+extern jmethodID g_mid_Iterator_next;\r
+extern jmethodID g_mid_HashMap_ctor;\r
+extern jmethodID g_mid_HashMap_put;\r
+extern jmethodID g_mid_OcException_ctor;\r
+extern jmethodID g_mid_OcException_setNativeExceptionLocation;\r
+extern jmethodID g_mid_OcResource_ctor;\r
+extern jmethodID g_mid_OcRepresentation_N_ctor;\r
+extern jmethodID g_mid_OcRepresentation_N_ctor_bool;\r
+extern jmethodID g_mid_OcResourceRequest_N_ctor;\r
+extern jmethodID g_mid_OcResourceResponse_N_ctor;\r
+extern jmethodID g_mid_OcResourceHandle_N_ctor;\r
+extern jmethodID g_mid_OcPresenceHandle_N_ctor;\r
+extern jmethodID g_mid_OcRequestHandle_N_ctor;\r
+extern jmethodID g_mid_OcHeaderOption_ctor;\r
+extern jmethodID g_mid_OcHeaderOption_get_id;\r
+extern jmethodID g_mid_OcHeaderOption_get_data;\r
+extern jmethodID g_mid_ObservationInfo_N_ctor;\r
+extern jmethodID g_mid_OcPresenceStatus_get;\r
+extern jmethodID g_mid_OcResourceIdentifier_N_ctor;\r
+\r
+typedef void(*RemoveListenerCallback)(JNIEnv* env, jobject jListener);\r
+\r
+static jfieldID GetHandleField(JNIEnv *env, jobject jobj)\r
+{\r
+    jclass cls = env->GetObjectClass(jobj);\r
+    return env->GetFieldID(cls, "mNativeHandle", "J");\r
+}\r
+\r
+template <typename T>\r
+static T *GetHandle(JNIEnv *env, jobject jobj)\r
+{\r
+    jlong handle = env->GetLongField(jobj, GetHandleField(env, jobj));\r
+    return reinterpret_cast<T *>(handle);\r
+}\r
+\r
+template <typename T>\r
+static void SetHandle(JNIEnv *env, jobject jobj, T *type)\r
+{\r
+    jlong handle = reinterpret_cast<jlong>(type);\r
+\r
+    env->SetLongField(jobj, GetHandleField(env, jobj), handle);\r
+}\r
+\r
+static JNIEnv* GetJNIEnv(jint& ret)\r
+{\r
+    JNIEnv *env = NULL;\r
+\r
+    ret = g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION);\r
+    switch (ret) {\r
+    case JNI_OK:\r
+        return env;\r
+    case JNI_EDETACHED:\r
+        if (g_jvm->AttachCurrentThread(&env, NULL) < 0)\r
+        {\r
+            LOGE("Failed to get the environment");\r
+            return nullptr;\r
+        }\r
+        else\r
+        {\r
+            return env;\r
+        }\r
+\r
+    case JNI_EVERSION:\r
+        LOGE("JNI version not supported");\r
+    default:\r
+        LOGE("Failed to get the environment");\r
+        return nullptr;\r
+    }\r
+}\r
+\r
+static void DuplicateString(char ** targetString, std::string sourceString)\r
+{\r
+    *targetString = new char[sourceString.length() + 1];\r
+    strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));\r
+}\r
+\r
+#endif // _Included_org_iotivity_base_ocstack
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnDeleteListener.cpp b/android/android_api/base/jni/JniOnDeleteListener.cpp
new file mode 100644 (file)
index 0000000..ed39e3b
--- /dev/null
@@ -0,0 +1,121 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+\r
+#include "JniOnDeleteListener.h"\r
+#include "JniOcResource.h"\r
+#include "JniUtils.h"\r
+\r
+JniOnDeleteListener::JniOnDeleteListener(JNIEnv *env, jobject jListener, JniOcResource* owner)\r
+    : m_ownerResource(owner)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+}\r
+\r
+JniOnDeleteListener::~JniOnDeleteListener()\r
+{\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, const int eCode)\r
+{\r
+    jint envRet;\r
+    JNIEnv *env = GetJNIEnv(envRet);\r
+    if (NULL == env) return;\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+    if (!clsL)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    if (OC_STACK_RESOURCE_DELETED != eCode)\r
+    {\r
+        jobject ex = GetOcException(eCode, "stack error in onDeleteCallback");\r
+        if (!ex)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        jmethodID midL = env->GetMethodID(clsL, "onDeleteFailed", "(Ljava/lang/Throwable;)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        env->CallVoidMethod(jListener, midL, ex);\r
+    }\r
+    else\r
+    {\r
+        jobject jHeaderOptionList = JniUtils::convertHeaderOptionsVectorToJavaList(env, headerOptions);\r
+        if (!jHeaderOptionList)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        jmethodID midL = env->GetMethodID(clsL, "onDeleteCompleted", "(Ljava/util/List;)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        env->CallVoidMethod(jListener, midL, jHeaderOptionList);\r
+    }\r
+\r
+    checkExAndRemoveListener(env);\r
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnDeleteListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_ownerResource->removeOnDeleteListener(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_ownerResource->removeOnDeleteListener(env, m_jwListener);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnDeleteListener.h b/android/android_api/base/jni/JniOnDeleteListener.h
new file mode 100644 (file)
index 0000000..45ae34b
--- /dev/null
@@ -0,0 +1,45 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResource_OnDeleteListener\r
+#define _Included_org_iotivity_base_OcResource_OnDeleteListener\r
+\r
+using namespace OC;\r
+\r
+class JniOcResource;\r
+\r
+class JniOnDeleteListener\r
+{\r
+public:\r
+    JniOnDeleteListener(JNIEnv *env, jobject jListener, JniOcResource* owner);\r
+    ~JniOnDeleteListener();\r
+\r
+    void onDeleteCallback(const HeaderOptions&, const int eCode);\r
+\r
+private:\r
+    jweak m_jwListener;\r
+    JniOcResource* m_ownerResource;\r
+    void checkExAndRemoveListener(JNIEnv *env);\r
+};\r
+\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnDeviceInfoListener.cpp b/android/android_api/base/jni/JniOnDeviceInfoListener.cpp
new file mode 100644 (file)
index 0000000..483fac6
--- /dev/null
@@ -0,0 +1,113 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOnDeviceInfoListener.h"\r
+#include "JniOcRepresentation.h"\r
+\r
+JniOnDeviceInfoListener::JniOnDeviceInfoListener(JNIEnv *env, jobject jListener,\r
+    RemoveListenerCallback removeListenerCallback)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+    m_removeListenerCallback = removeListenerCallback;\r
+}\r
+\r
+JniOnDeviceInfoListener::~JniOnDeviceInfoListener()\r
+{\r
+    LOGI("~JniOnDeviceInfoListener");\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& ocRepresentation)\r
+{\r
+    jint ret;\r
+    JNIEnv *env = GetJNIEnv(ret);\r
+    if (NULL == env) return;\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        LOGI("Java onDeviceInfoListener object is already destroyed, quiting");\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    OCRepresentation* rep = new OCRepresentation(ocRepresentation);\r
+    jlong handle = reinterpret_cast<jlong>(rep);\r
+    jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+        handle, true);\r
+    if (!jRepresentation)\r
+    {\r
+        delete rep;\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+    if (!clsL)\r
+    {\r
+        delete rep;\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jmethodID midL = env->GetMethodID(clsL, "onDeviceFound", "(Lorg/iotivity/base/OcRepresentation;)V");\r
+    if (!midL)\r
+    {\r
+        delete rep;\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    env->CallVoidMethod(jListener, midL, jRepresentation);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Java exception is thrown");\r
+        delete rep;\r
+        checkExAndRemoveListener(env);\r
+    }\r
+\r
+    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_removeListenerCallback(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_removeListenerCallback(env, m_jwListener);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnDeviceInfoListener.h b/android/android_api/base/jni/JniOnDeviceInfoListener.h
new file mode 100644 (file)
index 0000000..152ca8c
--- /dev/null
@@ -0,0 +1,42 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include <jni.h>\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcPlatform_OnDeviceFoundListener\r
+#define _Included_org_iotivity_base_OcPlatform_OnDeviceFoundListener\r
+\r
+class JniOnDeviceInfoListener\r
+{\r
+public:\r
+    JniOnDeviceInfoListener(JNIEnv *env, jobject jListener, RemoveListenerCallback removeListener);\r
+    ~JniOnDeviceInfoListener();\r
+\r
+    void foundDeviceCallback(const OC::OCRepresentation& ocRepresentation);\r
+\r
+private:\r
+    jweak m_jwListener;\r
+    RemoveListenerCallback m_removeListenerCallback;\r
+    void checkExAndRemoveListener(JNIEnv* env);\r
+};\r
+\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOnGetListener.cpp b/android/android_api/base/jni/JniOnGetListener.cpp
new file mode 100644 (file)
index 0000000..4ac19bc
--- /dev/null
@@ -0,0 +1,144 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOnGetListener.h"\r
+#include "JniOcResource.h"\r
+#include "JniOcRepresentation.h"\r
+#include "JniUtils.h"\r
+\r
+JniOnGetListener::JniOnGetListener(JNIEnv *env, jobject jListener, JniOcResource* owner)\r
+    : m_ownerResource(owner)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+}\r
+\r
+JniOnGetListener::~JniOnGetListener()\r
+{\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,\r
+    const OCRepresentation& ocRepresentation, const int eCode)\r
+{\r
+    jint envRet;\r
+    JNIEnv *env = GetJNIEnv(envRet);\r
+    if (NULL == env) return;\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+\r
+    if (!clsL)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    if (OC_STACK_OK != eCode)\r
+    {\r
+        jobject ex = GetOcException(eCode, "stack error in onGetCallback");\r
+        if (!ex)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        jmethodID midL = env->GetMethodID(clsL, "onGetFailed", "(Ljava/lang/Throwable;)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        env->CallVoidMethod(jListener, midL, ex);\r
+    }\r
+    else\r
+    {\r
+        jobject jHeaderOptionList = JniUtils::convertHeaderOptionsVectorToJavaList(env, headerOptions);\r
+        if (!jHeaderOptionList)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        OCRepresentation* rep = new OCRepresentation(ocRepresentation);\r
+        jlong handle = reinterpret_cast<jlong>(rep);\r
+        jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+            handle, true);\r
+        if (!jRepresentation)\r
+        {\r
+            delete rep;\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        jmethodID midL = env->GetMethodID(clsL, "onGetCompleted",\r
+            "(Ljava/util/List;Lorg/iotivity/base/OcRepresentation;)V");\r
+        if (!midL)\r
+        {\r
+            delete rep;\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation);\r
+        if (env->ExceptionCheck())\r
+        {\r
+            LOGE("Java exception is thrown");\r
+            delete rep;\r
+        }\r
+    }\r
+\r
+    checkExAndRemoveListener(env);\r
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnGetListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_ownerResource->removeOnGetListener(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_ownerResource->removeOnGetListener(env, m_jwListener);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnGetListener.h b/android/android_api/base/jni/JniOnGetListener.h
new file mode 100644 (file)
index 0000000..af69f1b
--- /dev/null
@@ -0,0 +1,43 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResource_OnGetListener\r
+#define _Included_org_iotivity_base_OcResource_OnGetListener\r
+\r
+using namespace OC;\r
+\r
+class JniOcResource;\r
+\r
+class JniOnGetListener\r
+{\r
+public:\r
+    JniOnGetListener(JNIEnv *env, jobject listener, JniOcResource* resource);\r
+    ~JniOnGetListener();\r
+    void onGetCallback(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);\r
+private:\r
+    jweak m_jwListener;\r
+    JniOcResource* m_ownerResource;\r
+    void checkExAndRemoveListener(JNIEnv *env);\r
+};\r
+\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnObserveListener.cpp b/android/android_api/base/jni/JniOnObserveListener.cpp
new file mode 100644 (file)
index 0000000..7afb1e1
--- /dev/null
@@ -0,0 +1,147 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOnObserveListener.h"\r
+#include "JniOcResource.h"\r
+#include "JniOcRepresentation.h"\r
+#include "JniUtils.h"\r
+\r
+JniOnObserveListener::JniOnObserveListener(JNIEnv *env, jobject jListener, JniOcResource* owner)\r
+    : m_ownerResource(owner)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+}\r
+\r
+JniOnObserveListener::~JniOnObserveListener()\r
+{\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,\r
+    const OCRepresentation& ocRepresentation, const int& eCode, const int& sequenceNumber)\r
+{\r
+    jint envRet;\r
+    JNIEnv *env = GetJNIEnv(envRet);\r
+    if (NULL == env) return;\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+    if (!clsL)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode && OC_STACK_RESOURCE_DELETED != eCode)\r
+    {\r
+        jobject ex = GetOcException(eCode, "stack error in onObserveCallback");\r
+        if (!ex)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        jmethodID midL = env->GetMethodID(clsL, "onObserveFailed", "(Ljava/lang/Throwable;)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        env->CallVoidMethod(jListener, midL, ex);\r
+    }\r
+    else\r
+    {\r
+        jobject jHeaderOptionList = JniUtils::convertHeaderOptionsVectorToJavaList(env, headerOptions);\r
+        if (!jHeaderOptionList)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        OCRepresentation * rep = new OCRepresentation(ocRepresentation);\r
+        jlong handle = reinterpret_cast<jlong>(rep);\r
+        jobject jRepresentation = env->NewObject(g_cls_OcRepresentation,\r
+            g_mid_OcRepresentation_N_ctor_bool, handle, true);\r
+        if (!jRepresentation)\r
+        {\r
+            delete rep;\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        jmethodID midL = env->GetMethodID(clsL, "onObserveCompleted",\r
+            "(Ljava/util/List;Lorg/iotivity/base/OcRepresentation;I)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation,\r
+            static_cast<jint>(sequenceNumber));\r
+        if (env->ExceptionCheck())\r
+        {\r
+            LOGE("Java exception is thrown");\r
+            delete rep;\r
+            jthrowable ex = env->ExceptionOccurred();\r
+            env->ExceptionClear();\r
+            m_ownerResource->removeOnObserveListener(env, m_jwListener);\r
+            env->Throw((jthrowable)ex);\r
+        }\r
+    }\r
+\r
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_ownerResource->removeOnObserveListener(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_ownerResource->removeOnObserveListener(env, m_jwListener);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnObserveListener.h b/android/android_api/base/jni/JniOnObserveListener.h
new file mode 100644 (file)
index 0000000..ae1d042
--- /dev/null
@@ -0,0 +1,44 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResource_OnObserveListener\r
+#define _Included_org_iotivity_base_OcResource_OnObserveListener\r
+\r
+using namespace OC;\r
+\r
+class JniOcResource;\r
+\r
+class JniOnObserveListener\r
+{\r
+public:\r
+    JniOnObserveListener(JNIEnv *env, jobject jListener, JniOcResource* owner);\r
+    ~JniOnObserveListener();\r
+    void onObserveCallback(const HeaderOptions headerOptions, const OCRepresentation& rep,\r
+        const int& eCode, const int& sequenceNumber);\r
+private:\r
+    jweak m_jwListener;\r
+    JniOcResource* m_ownerResource;\r
+    void checkExAndRemoveListener(JNIEnv *env);\r
+};\r
+\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnPostListener.cpp b/android/android_api/base/jni/JniOnPostListener.cpp
new file mode 100644 (file)
index 0000000..b9eb997
--- /dev/null
@@ -0,0 +1,143 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOnPostListener.h"\r
+#include "JniOcResource.h"\r
+#include "JniOcRepresentation.h"\r
+#include "JniUtils.h"\r
+\r
+JniOnPostListener::JniOnPostListener(JNIEnv *env, jobject jListener, JniOcResource* owner)\r
+    : m_ownerResource(owner)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+}\r
+\r
+JniOnPostListener::~JniOnPostListener()\r
+{\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,\r
+    const OCRepresentation& ocRepresentation, const int eCode)\r
+{\r
+    jint envRet;\r
+    JNIEnv *env = GetJNIEnv(envRet);\r
+    if (NULL == env) return;\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+    if (!clsL)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode)\r
+    {\r
+        jobject ex = GetOcException(eCode, "stack error in onPostCallback");\r
+        if (!ex)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        jmethodID midL = env->GetMethodID(clsL, "onPostFailed", "(Ljava/lang/Throwable;)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        env->CallVoidMethod(jListener, midL, ex);\r
+    }\r
+    else\r
+    {\r
+        jobject jHeaderOptionList = JniUtils::convertHeaderOptionsVectorToJavaList(env, headerOptions);\r
+        if (!jHeaderOptionList)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        OCRepresentation * rep = new OCRepresentation(ocRepresentation);\r
+        jlong handle = reinterpret_cast<jlong>(rep);\r
+        jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+            handle, true);\r
+        if (!jRepresentation)\r
+        {\r
+            delete rep;\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        jmethodID midL = env->GetMethodID(clsL, "onPostCompleted",\r
+            "(Ljava/util/List;Lorg/iotivity/base/OcRepresentation;)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation);\r
+        if (env->ExceptionCheck())\r
+        {\r
+            LOGE("Java exception is thrown");\r
+            delete rep;\r
+        }\r
+    }\r
+\r
+    checkExAndRemoveListener(env);\r
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnPostListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_ownerResource->removeOnPostListener(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_ownerResource->removeOnPostListener(env, m_jwListener);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnPostListener.h b/android/android_api/base/jni/JniOnPostListener.h
new file mode 100644 (file)
index 0000000..9090507
--- /dev/null
@@ -0,0 +1,45 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResource_OnPostListener\r
+#define _Included_org_iotivity_base_OcResource_OnPostListener\r
+\r
+using namespace OC;\r
+\r
+class JniOcResource;\r
+\r
+class JniOnPostListener\r
+{\r
+public:\r
+    JniOnPostListener(JNIEnv *env, jobject jListener, JniOcResource* owner);\r
+    ~JniOnPostListener();\r
+\r
+    void onPostCallback(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);\r
+\r
+private:\r
+    jweak m_jwListener;\r
+    JniOcResource* m_ownerResource;\r
+    void checkExAndRemoveListener(JNIEnv *env);\r
+};\r
+\r
+#endif
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnPresenceListener.cpp b/android/android_api/base/jni/JniOnPresenceListener.cpp
new file mode 100644 (file)
index 0000000..7c99445
--- /dev/null
@@ -0,0 +1,133 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOnPresenceListener.h"\r
+#include "JniUtils.h"\r
+\r
+JniOnPresenceListener::JniOnPresenceListener(JNIEnv *env, jobject jListener,\r
+    RemoveListenerCallback removeListenerCallback)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+    m_removeListenerCallback = removeListenerCallback;\r
+}\r
+\r
+JniOnPresenceListener::~JniOnPresenceListener()\r
+{\r
+    LOGD("~JniOnPresenceListener");\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+        m_jwListener = nullptr;\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsigned int nonce,\r
+    const std::string& hostAddress)\r
+{\r
+    LOGI("JniOnPresenceListener::onPresenceCallback");\r
+    if (!m_jwListener) return;\r
+\r
+    jint ret;\r
+    JNIEnv *env = GetJNIEnv(ret);\r
+    if (NULL == env) return;\r
+\r
+    if (OC_STACK_OK != result && OC_STACK_PRESENCE_STOPPED != result &&\r
+        OC_STACK_PRESENCE_TIMEOUT != result &&  OC_STACK_PRESENCE_DO_NOT_HANDLE != result)\r
+    {\r
+        ThrowOcException(result, "onPresenceCallback: stack failure");\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    std::string enumField = JniUtils::stackResultToStr(result);\r
+    if (enumField.empty())\r
+    {\r
+        ThrowOcException(JNI_INVALID_VALUE, "Unexpected OCStackResult value");\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    jobject jPresenceStatus = env->CallStaticObjectMethod(g_cls_OcPresenceStatus,\r
+        g_mid_OcPresenceStatus_get, env->NewStringUTF(enumField.c_str()));\r
+    if (!jPresenceStatus)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+    if (!clsL)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jmethodID midL = env->GetMethodID(clsL, "onPresence",\r
+        "(Lorg/iotivity/base/OcPresenceStatus;ILjava/lang/String;)V");\r
+    if (!midL)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    env->CallVoidMethod(jListener, midL, jPresenceStatus,\r
+        (jint)nonce, env->NewStringUTF(hostAddress.c_str()));\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Java exception is thrown");\r
+        checkExAndRemoveListener(env);\r
+    }\r
+    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnPresenceListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_removeListenerCallback(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_removeListenerCallback(env, m_jwListener);\r
+    }\r
+}\r
+\r
+jweak JniOnPresenceListener::getJWListener()\r
+{\r
+    return this->m_jwListener;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnPresenceListener.h b/android/android_api/base/jni/JniOnPresenceListener.h
new file mode 100644 (file)
index 0000000..7cea026
--- /dev/null
@@ -0,0 +1,43 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+#include <mutex>\r
+\r
+#ifndef _Included_org_iotivity_base_OcPlatform_OnPresenceListener\r
+#define _Included_org_iotivity_base_OcPlatform_OnPresenceListener\r
+\r
+class JniOnPresenceListener\r
+{\r
+public:\r
+    JniOnPresenceListener(JNIEnv *env, jobject jListener, RemoveListenerCallback removeListener);\r
+    ~JniOnPresenceListener();\r
+\r
+    void onPresenceCallback(OCStackResult result, const unsigned int nonce, const std::string& hostAddress);\r
+    jweak getJWListener();\r
+\r
+private:\r
+    RemoveListenerCallback m_removeListenerCallback;\r
+    jweak m_jwListener;\r
+    void checkExAndRemoveListener(JNIEnv* env);\r
+};\r
+\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOnPutListener.cpp b/android/android_api/base/jni/JniOnPutListener.cpp
new file mode 100644 (file)
index 0000000..df18490
--- /dev/null
@@ -0,0 +1,144 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOnPutListener.h"\r
+#include "JniOcResource.h"\r
+#include "JniOcRepresentation.h"\r
+#include "JniUtils.h"\r
+\r
+JniOnPutListener::JniOnPutListener(JNIEnv *env, jobject jListener, JniOcResource* owner)\r
+    : m_ownerResource(owner)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+}\r
+\r
+JniOnPutListener::~JniOnPutListener()\r
+{\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,\r
+    const OCRepresentation& ocRepresentation, const int eCode)\r
+{\r
+    jint envRet;\r
+    JNIEnv *env = GetJNIEnv(envRet);\r
+    if (NULL == env) return;\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+    if (!clsL)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    if (OC_STACK_OK != eCode)\r
+    {\r
+        jobject ex = GetOcException(eCode, "stack error in onPutCallback");\r
+        if (!ex)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        jmethodID midL = env->GetMethodID(clsL, "onPutFailed", "(Ljava/lang/Throwable;)V");\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+        env->CallVoidMethod(jListener, midL, ex);\r
+    }\r
+    else\r
+    {\r
+        jobject jHeaderOptionList = JniUtils::convertHeaderOptionsVectorToJavaList(env, headerOptions);\r
+        if (!jHeaderOptionList)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        OCRepresentation * rep = new OCRepresentation(ocRepresentation);\r
+        jlong handle = reinterpret_cast<jlong>(rep);\r
+        jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+            handle, true);\r
+        if (!jRepresentation)\r
+        {\r
+            delete rep;\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        jmethodID midL = env->GetMethodID(clsL, "onPutCompleted",\r
+            "(Ljava/util/List;Lorg/iotivity/base/OcRepresentation;)V");\r
+\r
+        if (!midL)\r
+        {\r
+            checkExAndRemoveListener(env);\r
+            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+            return;\r
+        }\r
+\r
+        env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation);\r
+        if (env->ExceptionCheck())\r
+        {\r
+            LOGE("Java exception is thrown");\r
+            delete rep;\r
+        }\r
+    }\r
+\r
+    checkExAndRemoveListener(env);\r
+    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnPutListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_ownerResource->removeOnPutListener(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_ownerResource->removeOnPutListener(env, m_jwListener);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnPutListener.h b/android/android_api/base/jni/JniOnPutListener.h
new file mode 100644 (file)
index 0000000..f29e43f
--- /dev/null
@@ -0,0 +1,45 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcResource_OnPutListener\r
+#define _Included_org_iotivity_base_OcResource_OnPutListener\r
+\r
+using namespace OC;\r
+\r
+class JniOcResource;\r
+\r
+class JniOnPutListener\r
+{\r
+public:\r
+    JniOnPutListener(JNIEnv *env, jobject jListener, JniOcResource* resource);\r
+    ~JniOnPutListener();\r
+\r
+    void onPutCallback(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);\r
+\r
+private:\r
+    jweak m_jwListener;\r
+    JniOcResource* m_ownerResource;\r
+    void checkExAndRemoveListener(JNIEnv *env);\r
+};\r
+\r
+#endif\r
diff --git a/android/android_api/base/jni/JniOnResourceFoundListener.cpp b/android/android_api/base/jni/JniOnResourceFoundListener.cpp
new file mode 100644 (file)
index 0000000..652e0cb
--- /dev/null
@@ -0,0 +1,118 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include "JniOnResourceFoundListener.h"\r
+#include "JniOcResource.h"\r
+\r
+JniOnResourceFoundListener::JniOnResourceFoundListener(JNIEnv *env, jobject jListener,\r
+    RemoveListenerCallback removeListenerCallback)\r
+{\r
+    m_jwListener = env->NewWeakGlobalRef(jListener);\r
+    m_removeListenerCallback = removeListenerCallback;\r
+}\r
+\r
+JniOnResourceFoundListener::~JniOnResourceFoundListener()\r
+{\r
+    LOGI("~JniOnResourceFoundListener()");\r
+    if (m_jwListener)\r
+    {\r
+        jint ret;\r
+        JNIEnv *env = GetJNIEnv(ret);\r
+        if (NULL == env) return;\r
+        env->DeleteWeakGlobalRef(m_jwListener);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+    }\r
+}\r
+\r
+void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCResource> resource)\r
+{\r
+    jint ret;\r
+    JNIEnv *env = GetJNIEnv(ret);\r
+    if (NULL == env) return;\r
+\r
+    jobject jListener = env->NewLocalRef(m_jwListener);\r
+    if (!jListener)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    jobject jResource = env->NewObject(g_cls_OcResource, g_mid_OcResource_ctor);\r
+    if (!jResource)\r
+    {\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    JniOcResource *jniOcResource = new JniOcResource(resource);\r
+    SetHandle<JniOcResource>(env, jResource, jniOcResource);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        delete jniOcResource;\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jclass clsL = env->GetObjectClass(jListener);\r
+    if (!clsL)\r
+    {\r
+        delete jniOcResource;\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    jmethodID midL = env->GetMethodID(clsL, "onResourceFound", "(Lorg/iotivity/base/OcResource;)V");\r
+    if (!midL)\r
+    {\r
+        delete jniOcResource;\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+    env->CallVoidMethod(jListener, midL, jResource);\r
+    if (env->ExceptionCheck())\r
+    {\r
+        LOGE("Java exception is thrown");\r
+        delete jniOcResource;\r
+        checkExAndRemoveListener(env);\r
+        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+        return;\r
+    }\r
+\r
+    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();\r
+}\r
+\r
+void JniOnResourceFoundListener::checkExAndRemoveListener(JNIEnv* env)\r
+{\r
+    if (env->ExceptionCheck())\r
+    {\r
+        jthrowable ex = env->ExceptionOccurred();\r
+        env->ExceptionClear();\r
+        m_removeListenerCallback(env, m_jwListener);\r
+        env->Throw((jthrowable)ex);\r
+    }\r
+    else\r
+    {\r
+        m_removeListenerCallback(env, m_jwListener);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniOnResourceFoundListener.h b/android/android_api/base/jni/JniOnResourceFoundListener.h
new file mode 100644 (file)
index 0000000..2cb9749
--- /dev/null
@@ -0,0 +1,43 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+#include <jni.h>\r
+#include "JniOcStack.h"\r
+\r
+#ifndef _Included_org_iotivity_base_OcPlatform_OnResourceFoundListener\r
+#define _Included_org_iotivity_base_OcPlatform_OnResourceFoundListener\r
+\r
+class JniOnResourceFoundListener\r
+{\r
+public:\r
+    JniOnResourceFoundListener(JNIEnv *env, jobject jListener,\r
+        RemoveListenerCallback removeListenerCallback);\r
+    ~JniOnResourceFoundListener();\r
+\r
+    void foundResourceCallback(std::shared_ptr<OC::OCResource> resource);\r
+\r
+private:\r
+    RemoveListenerCallback m_removeListenerCallback;\r
+    jweak m_jwListener;\r
+    void checkExAndRemoveListener(JNIEnv* env);\r
+};\r
+\r
+#endif\r
diff --git a/android/android_api/base/jni/JniUtils.cpp b/android/android_api/base/jni/JniUtils.cpp
new file mode 100644 (file)
index 0000000..6ec806c
--- /dev/null
@@ -0,0 +1,193 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+\r
+#include "JniUtils.h"\r
+#include "JniOcRepresentation.h"\r
+\r
+jobject JniUtils::convertStrVectorToJavaStrList(JNIEnv *env, std::vector<std::string> &vector)\r
+{\r
+    jobject jList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);\r
+    if (!jList) return nullptr;\r
+    for (size_t i = 0; i < vector.size(); ++i)\r
+    {\r
+        jstring jStr = env->NewStringUTF(vector[i].c_str());\r
+        if (!jStr) return nullptr;\r
+        env->CallBooleanMethod(jList, g_mid_LinkedList_add_object, jStr);\r
+        if (env->ExceptionCheck()) return nullptr;\r
+        env->DeleteLocalRef(jStr);\r
+    }\r
+    return jList;\r
+}\r
+\r
+void JniUtils::convertJavaStrArrToStrVector(JNIEnv *env, jobjectArray jStrArr, std::vector<std::string> &vector)\r
+{\r
+    if (!jStrArr) return;\r
+\r
+    jsize len = env->GetArrayLength(jStrArr);\r
+    for (jsize i = 0; i < len; ++i)\r
+    {\r
+        jstring jStr = (jstring)env->GetObjectArrayElement(jStrArr, i);\r
+        if (!jStr) return;\r
+        vector.push_back(env->GetStringUTFChars(jStr, NULL));\r
+        if (env->ExceptionCheck()) return;\r
+        env->DeleteLocalRef(jStr);\r
+    }\r
+}\r
+\r
+void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHeaderOptions,\r
+    OC::HeaderOptions &headerOptions)\r
+{\r
+    if (!jHeaderOptions) return;\r
+\r
+    jsize len = env->GetArrayLength(jHeaderOptions);\r
+    for (jsize i = 0; i < len; ++i)\r
+    {\r
+        jobject header = env->GetObjectArrayElement(jHeaderOptions, i);\r
+        if (!header) nullptr;\r
+        jint jId = env->CallIntMethod(header, g_mid_OcHeaderOption_get_id);\r
+        jstring jData = (jstring)env->CallObjectMethod(header, g_mid_OcHeaderOption_get_data);\r
+        if (jData) return;\r
+\r
+        OC::HeaderOption::OCHeaderOption hopt(\r
+            static_cast<int>(jId),\r
+            env->GetStringUTFChars(jData, NULL));\r
+\r
+        headerOptions.push_back(hopt);\r
+\r
+        if (env->ExceptionCheck()) return;\r
+        env->DeleteLocalRef(header);\r
+        env->DeleteLocalRef(jData);\r
+    }\r
+}\r
+\r
+jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::HeaderOptions& headerOptions)\r
+{\r
+    jobject jHeaderOptionList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);\r
+    if (!jHeaderOptionList) return nullptr;\r
+\r
+    for (size_t i = 0; i < headerOptions.size(); ++i)\r
+    {\r
+        jobject jHeaderOption = env->NewObject(\r
+            g_cls_OcHeaderOption,\r
+            g_mid_OcHeaderOption_ctor,\r
+            static_cast<jint>(headerOptions[i].getOptionID()),\r
+            env->NewStringUTF(headerOptions[i].getOptionData().c_str())\r
+            );\r
+        if (!jHeaderOption) return nullptr;\r
+\r
+        env->CallBooleanMethod(jHeaderOptionList, g_mid_LinkedList_add_object, jHeaderOption);\r
+        if (env->ExceptionCheck()) return nullptr;\r
+        env->DeleteLocalRef(jHeaderOption);\r
+    }\r
+\r
+    return jHeaderOptionList;\r
+}\r
+\r
+void JniUtils::convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap, OC::QueryParamsMap &map)\r
+{\r
+    if (!hashMap) return;\r
+\r
+    jobject jEntrySet = env->CallObjectMethod(hashMap, g_mid_Map_entrySet);\r
+    jobject jIterator = env->CallObjectMethod(jEntrySet, g_mid_Set_iterator);\r
+    if (!jEntrySet || !jIterator || env->ExceptionCheck()) return;\r
+\r
+    while (env->CallBooleanMethod(jIterator, g_mid_Iterator_hasNext))\r
+    {\r
+        jobject jEntry = env->CallObjectMethod(jIterator, g_mid_Iterator_next);\r
+        if (!jEntry) return;\r
+        jstring jKey = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getKey);\r
+        if (!jKey) return;\r
+        jstring jValue = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getValue);\r
+        if (!jValue) return;\r
+\r
+        map.insert(std::make_pair(env->GetStringUTFChars(jKey, NULL),\r
+            env->GetStringUTFChars(jValue, NULL)));\r
+\r
+        if (env->ExceptionCheck()) return;\r
+        env->DeleteLocalRef(jEntry);\r
+        env->DeleteLocalRef(jKey);\r
+        env->DeleteLocalRef(jValue);\r
+    }\r
+}\r
+\r
+jobject JniUtils::convertQueryParamsMapToJavaMap(JNIEnv *env, const OC::QueryParamsMap &map)\r
+{\r
+    jobject hashMap = env->NewObject(g_cls_HashMap, g_mid_HashMap_ctor);\r
+    if (!hashMap) return nullptr;\r
+\r
+    for (auto it = map.begin(); it != map.end(); ++it)\r
+    {\r
+        std::string key = it->first;\r
+        std::string value = it->second;\r
+\r
+        env->CallObjectMethod(hashMap,\r
+            g_mid_HashMap_put,\r
+            env->NewStringUTF(key.c_str()),\r
+            env->NewStringUTF(value.c_str()));\r
+        if (env->ExceptionCheck()) return nullptr;\r
+    }\r
+\r
+    return hashMap;\r
+}\r
+\r
+void JniUtils::convertJavaRepresentationArrToVector(JNIEnv *env,\r
+    jobjectArray jRepresentationArray,\r
+    std::vector<OC::OCRepresentation>& representationVector)\r
+{\r
+    if (!jRepresentationArray) return;\r
+    jsize len = env->GetArrayLength(jRepresentationArray);\r
+\r
+    for (jsize i = 0; i < len; ++i)\r
+    {\r
+        jobject jRep = env->GetObjectArrayElement(jRepresentationArray, i);\r
+        if (!jRep) return;\r
+        OC::OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, jRep);\r
+        representationVector.push_back(*rep);\r
+        if (env->ExceptionCheck()) return;\r
+        env->DeleteLocalRef(jRep);\r
+    }\r
+}\r
+\r
+jobjectArray JniUtils::convertRepresentationVectorToJavaArray(JNIEnv *env,\r
+    const std::vector<OC::OCRepresentation>& representationVector)\r
+{\r
+    jsize len = static_cast<jsize>(representationVector.size());\r
+    jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, NULL);\r
+    if (!repArr) return nullptr;\r
+    for (jsize i = 0; i < len; ++i)\r
+    {\r
+        OCRepresentation* rep = new OCRepresentation(representationVector[i]);\r
+        jlong handle = reinterpret_cast<jlong>(rep);\r
+        jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
+            handle, true);\r
+        if (!jRepresentation)\r
+        {\r
+            delete rep;\r
+            return nullptr;\r
+        }\r
+        env->SetObjectArrayElement(repArr, i, jRepresentation);\r
+        if (env->ExceptionCheck()) return nullptr;\r
+        env->DeleteLocalRef(jRepresentation);\r
+    }\r
+\r
+    return repArr;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/jni/JniUtils.h b/android/android_api/base/jni/JniUtils.h
new file mode 100644 (file)
index 0000000..c4553ff
--- /dev/null
@@ -0,0 +1,230 @@
+/*\r
+* //******************************************************************\r
+* //\r
+* // Copyright 2015 Intel Corporation.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+* //\r
+* // Licensed under the Apache License, Version 2.0 (the "License");\r
+* // you may not use this file except in compliance with the License.\r
+* // You may obtain a copy of the License at\r
+* //\r
+* //      http://www.apache.org/licenses/LICENSE-2.0\r
+* //\r
+* // Unless required by applicable law or agreed to in writing, software\r
+* // distributed under the License is distributed on an "AS IS" BASIS,\r
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* // See the License for the specific language governing permissions and\r
+* // limitations under the License.\r
+* //\r
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+*/\r
+\r
+#include "JniOcStack.h"\r
+#include "OCRepresentation.h"\r
+\r
+class JniUtils\r
+{\r
+public:\r
+    static void convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap,\r
+        OC::QueryParamsMap &map);\r
+    static jobject convertQueryParamsMapToJavaMap(JNIEnv *env, const OC::QueryParamsMap &map);\r
+\r
+    static jobject convertStrVectorToJavaStrList(JNIEnv *env, std::vector<std::string> &vector);\r
+    static void convertJavaStrArrToStrVector(JNIEnv *env, jobjectArray jStrArr,\r
+        std::vector<std::string> &vector);\r
+\r
+    static void convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHeaderOptions,\r
+        OC::HeaderOptions& headerOptions);\r
+    static jobject convertHeaderOptionsVectorToJavaList(JNIEnv *env,\r
+        const OC::HeaderOptions& headerOptions);\r
+\r
+    static void convertJavaRepresentationArrToVector(JNIEnv *env,\r
+        jobjectArray jRepresentationArray,\r
+        std::vector<OC::OCRepresentation>& representationVector);\r
+    static jobjectArray convertRepresentationVectorToJavaArray(JNIEnv *env,\r
+        const std::vector<OC::OCRepresentation>& representationVector);\r
+\r
+    static OC::ServiceType getServiceType(JNIEnv *env, int type)\r
+    {\r
+        switch (type) {\r
+        case 0:\r
+            return OC::ServiceType::InProc;\r
+        case 1:\r
+            return OC::ServiceType::OutOfProc;\r
+        default:\r
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected service type");\r
+            return OC::ServiceType::OutOfProc;\r
+        };\r
+    }\r
+\r
+    static OC::ModeType getModeType(JNIEnv *env, int type)\r
+    {\r
+        switch (type) {\r
+        case 0:\r
+            return OC::ModeType::Server;\r
+        case 1:\r
+            return OC::ModeType::Client;\r
+        case 2:\r
+            return OC::ModeType::Both;\r
+        default:\r
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected mode type");\r
+            return OC::ModeType::Both;\r
+        };\r
+    }\r
+\r
+    static OC::QualityOfService getQOS(JNIEnv *env, int type)\r
+    {\r
+        switch (type) {\r
+        case 0:\r
+            return OC::QualityOfService::LowQos;\r
+        case 1:\r
+            return OC::QualityOfService::MidQos;\r
+        case 2:\r
+            return OC::QualityOfService::HighQos;\r
+        case 3:\r
+            return OC::QualityOfService::NaQos;\r
+        default:\r
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected quality of service");\r
+            return OC::QualityOfService::NaQos;\r
+        };\r
+    }\r
+\r
+    static OC::ObserveType getObserveType(JNIEnv *env, int type)\r
+    {\r
+        switch (type) {\r
+        case 0:\r
+            return OC::ObserveType::Observe;\r
+        case 1:\r
+            return OC::ObserveType::ObserveAll;\r
+        default:\r
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected observe type");\r
+            return OC::ObserveType::ObserveAll;\r
+        };\r
+    }\r
+\r
+    static OCEntityHandlerResult getOCEntityHandlerResult(JNIEnv *env, int type)\r
+    {\r
+        switch (type) {\r
+        case 0:\r
+            return OCEntityHandlerResult::OC_EH_OK;\r
+        case 1:\r
+            return OCEntityHandlerResult::OC_EH_ERROR;\r
+        case 2:\r
+            return OCEntityHandlerResult::OC_EH_RESOURCE_CREATED;\r
+        case 3:\r
+            return OCEntityHandlerResult::OC_EH_RESOURCE_DELETED;\r
+        case 4:\r
+            return OCEntityHandlerResult::OC_EH_SLOW;\r
+        case 5:\r
+            return OCEntityHandlerResult::OC_EH_FORBIDDEN;\r
+        default:\r
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");\r
+            return OCEntityHandlerResult::OC_EH_ERROR;\r
+        };\r
+    }\r
+\r
+    static OCConnectivityType getConnectivityType(JNIEnv *env, int type)\r
+    {\r
+        switch (type) {\r
+        case 0:\r
+            return OCConnectivityType::OC_IPV4;\r
+        case 1:\r
+            return OCConnectivityType::OC_IPV6;\r
+        case 2:\r
+            return OCConnectivityType::OC_EDR;\r
+        case 3:\r
+            return OCConnectivityType::OC_LE;\r
+        case 4:\r
+            return OCConnectivityType::OC_ALL;\r
+        default:\r
+            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected connectivity type");\r
+            return OCConnectivityType::OC_ALL;\r
+        };\r
+    }\r
+\r
+    static std::string stackResultToStr(const int result)\r
+    {\r
+        switch (result)\r
+        {\r
+        case OC_STACK_OK:\r
+            return "OK";\r
+        case OC_STACK_RESOURCE_CREATED:\r
+            return "RESOURCE_CREATED";\r
+        case OC_STACK_RESOURCE_DELETED:\r
+            return "RESOURCE_DELETED";\r
+        case OC_STACK_CONTINUE:\r
+            return "CONTINUE";\r
+            /* Success status code - END HERE */\r
+            /* Error status code - START HERE */\r
+        case OC_STACK_INVALID_URI:\r
+            return "INVALID_URI";\r
+        case OC_STACK_INVALID_QUERY:\r
+            return "INVALID_QUERY";\r
+        case OC_STACK_INVALID_IP:\r
+            return "INVALID_IP";\r
+\r
+        case OC_STACK_INVALID_PORT:\r
+            return "INVALID_PORT";\r
+        case OC_STACK_INVALID_CALLBACK:\r
+            return "INVALID_CALLBACK";\r
+        case OC_STACK_INVALID_METHOD:\r
+            return "INVALID_METHOD";\r
+        case OC_STACK_INVALID_PARAM:\r
+            return "INVALID_PARAM";\r
+        case OC_STACK_INVALID_OBSERVE_PARAM:\r
+            return "INVALID_OBSERVE_PARAM";\r
+        case OC_STACK_NO_MEMORY:\r
+            return "NO_MEMORY";\r
+        case OC_STACK_COMM_ERROR:\r
+            return "COMM_ERROR";\r
+        case OC_STACK_NOTIMPL:\r
+            return "NOTIMPL";\r
+        case OC_STACK_NO_RESOURCE:\r
+            return "NO_RESOURCE";\r
+        case  OC_STACK_RESOURCE_ERROR:\r
+            return "RESOURCE_ERROR";\r
+        case OC_STACK_SLOW_RESOURCE:\r
+            return "SLOW_RESOURCE";\r
+            //case OC_STACK_DUPLICATE_REQUEST:\r
+            //    return "DUPLICATE_REQUEST";\r
+        case OC_STACK_NO_OBSERVERS:\r
+            return "NO_OBSERVERS";\r
+        case OC_STACK_OBSERVER_NOT_FOUND:\r
+            return "OBSERVER_NOT_FOUND";\r
+        case OC_STACK_VIRTUAL_DO_NOT_HANDLE:\r
+            return "VIRTUAL_DO_NOT_HANDLE";\r
+        case OC_STACK_INVALID_OPTION:\r
+            return "INVALID_OPTION";\r
+        case OC_STACK_MALFORMED_RESPONSE:\r
+            return "MALFORMED_RESPONSE";\r
+        case OC_STACK_PERSISTENT_BUFFER_REQUIRED:\r
+            return "PERSISTENT_BUFFER_REQUIRED";\r
+        case OC_STACK_INVALID_REQUEST_HANDLE:\r
+            return "INVALID_REQUEST_HANDLE";\r
+        case OC_STACK_INVALID_DEVICE_INFO:\r
+            return "INVALID_DEVICE_INFO";\r
+            //case OC_STACK_INVALID_JSON:\r
+            //    return "INVALID_JSON";\r
+\r
+        case OC_STACK_PRESENCE_STOPPED:\r
+            return "PRESENCE_STOPPED";\r
+        case OC_STACK_PRESENCE_TIMEOUT:\r
+            return "PRESENCE_TIMEOUT";\r
+        case OC_STACK_PRESENCE_DO_NOT_HANDLE:\r
+            return "PRESENCE_DO_NOT_HANDLE";\r
+\r
+        case OC_STACK_ERROR:\r
+            return "ERROR";\r
+\r
+        case JNI_EXCEPTION:\r
+            return "JNI_EXCEPTION";\r
+        case JNI_NO_NATIVE_POINTER:\r
+            return "JNI_NO_NATIVE_POINTER";\r
+        case JNI_INVALID_VALUE:\r
+            return "JNI_INVALID_VALUE";\r
+        default:\r
+            return "";\r
+        }\r
+    }\r
+};\r
diff --git a/android/android_api/base/proguard-rules.pro b/android/android_api/base/proguard-rules.pro
new file mode 100755 (executable)
index 0000000..ea26467
--- /dev/null
@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.\r
+# By default, the flags in this file are appended to flags specified\r
+# in C:/android/sdk/tools/proguard/proguard-android.txt\r
+# You can edit the include path and order by changing the proguardFiles\r
+# directive in build.gradle.\r
+#\r
+# For more details, see\r
+#   http://developer.android.com/guide/developing/tools/proguard.html\r
+\r
+# Add any project specific keep options here:\r
+\r
+# If your project uses WebView with JS, uncomment the following\r
+# and specify the fully qualified class name to the JavaScript interface\r
+# class:\r
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\r
+#   public *;\r
+#}\r
diff --git a/android/android_api/base/src/androidTest/AndroidManifest.xml b/android/android_api/base/src/androidTest/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..183e674
--- /dev/null
@@ -0,0 +1,35 @@
+<!--\r
+  ~ //******************************************************************\r
+  ~ //\r
+  ~ // Copyright 2015 Intel Corporation.\r
+  ~ //\r
+  ~ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+  ~ //\r
+  ~ // Licensed under the Apache License, Version 2.0 (the "License");\r
+  ~ // you may not use this file except in compliance with the License.\r
+  ~ // You may obtain a copy of the License at\r
+  ~ //\r
+  ~ //      http://www.apache.org/licenses/LICENSE-2.0\r
+  ~ //\r
+  ~ // Unless required by applicable law or agreed to in writing, software\r
+  ~ // distributed under the License is distributed on an "AS IS" BASIS,\r
+  ~ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+  ~ // See the License for the specific language governing permissions and\r
+  ~ // limitations under the License.\r
+  ~ //\r
+  ~ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+  -->\r
+\r
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    package="org.iotivity.base">\r
+    <uses-permission android:name="android.permission.BLUETOOTH" />\r
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />\r
+    <uses-permission android:name="android.permission.INTERNET" />\r
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />\r
+    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />\r
+    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />\r
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />\r
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />\r
+\r
+    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="21" />\r
+</manifest>\r
diff --git a/android/android_api/base/src/androidTest/java/org/iotivity/base/OcRepresentationTest.java b/android/android_api/base/src/androidTest/java/org/iotivity/base/OcRepresentationTest.java
new file mode 100644 (file)
index 0000000..0834201
--- /dev/null
@@ -0,0 +1,593 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import android.test.InstrumentationTestCase;\r
+\r
+import java.security.InvalidParameterException;\r
+import java.util.Arrays;\r
+import java.util.LinkedList;\r
+import java.util.List;\r
+\r
+public class OcRepresentationTest extends InstrumentationTestCase {\r
+\r
+    private static final String TAG = "OcRepresentationTest";\r
+\r
+    @Override\r
+    protected void setUp() throws Exception {\r
+        super.setUp();\r
+    }\r
+\r
+    public void testChildrenManagement() throws OcException {\r
+        OcRepresentation representation = new OcRepresentation();\r
+\r
+        List<OcRepresentation> emptyList = representation.getChildren();\r
+        assertTrue(emptyList.isEmpty());\r
+\r
+        OcRepresentation child1 = new OcRepresentation();\r
+        OcRepresentation child2 = new OcRepresentation();\r
+        String key = "key";\r
+        int value = 75;\r
+\r
+        child1.setValue(key, value);\r
+        child2.setValue(key, value);\r
+        representation.addChild(child1);\r
+        representation.addChild(child2);\r
+        List<OcRepresentation> twoChildren = representation.getChildren();\r
+        assertEquals(2, twoChildren.size());\r
+        for (OcRepresentation rep : twoChildren) {\r
+            assertEquals(value, rep.getValue(key));\r
+        }\r
+\r
+        representation.clearChildren();\r
+        emptyList = representation.getChildren();\r
+        assertTrue(emptyList.isEmpty());\r
+    }\r
+\r
+    public void testUriGetSet() {\r
+        OcRepresentation representation = new OcRepresentation();\r
+\r
+        String emptyUri = representation.getUri();\r
+        assertTrue(emptyUri.isEmpty());\r
+\r
+        String expected = "a/resource/uri";\r
+        representation.setUri(expected);\r
+        String actual = representation.getUri();\r
+        assertEquals(expected, actual);\r
+    }\r
+\r
+    public void testJSONRepresentation() throws OcException {\r
+        OcRepresentation representation = new OcRepresentation();\r
+        String key = "key";\r
+        int value = 75;\r
+\r
+        String emptyJson1 = representation.getJSONRepresentation();\r
+        representation.setValue(key, value);\r
+        String intValue1 = representation.getJSONRepresentation();\r
+        representation.remove(key);\r
+        String emptyJson2 = representation.getJSONRepresentation();\r
+        assertEquals(emptyJson1, emptyJson2);\r
+        representation.setValue(key, value);\r
+        String intValue2 = representation.getJSONRepresentation();\r
+        assertEquals(intValue1, intValue2);\r
+    }\r
+\r
+    public void testResourceTypesGetSet() {\r
+        OcRepresentation representation = new OcRepresentation();\r
+\r
+        List<String> emptyResourceTypeList = representation.getResourceTypes();\r
+        assertTrue(emptyResourceTypeList.isEmpty());\r
+\r
+        representation.setResourceTypes(emptyResourceTypeList);\r
+        emptyResourceTypeList = representation.getResourceTypes();\r
+        assertTrue(emptyResourceTypeList.isEmpty());\r
+\r
+        List<String> resourceTypeListExpected = new LinkedList<String>();\r
+        resourceTypeListExpected.add("type1");\r
+        resourceTypeListExpected.add("type2");\r
+        resourceTypeListExpected.add("type3");\r
+\r
+        representation.setResourceTypes(resourceTypeListExpected);\r
+        List<String> resourceTypeListActual = representation.getResourceTypes();\r
+        assertEquals(resourceTypeListExpected.size(), resourceTypeListActual.size());\r
+        for (int i = 0; i < resourceTypeListExpected.size(); i++) {\r
+            assertEquals(resourceTypeListExpected.get(i), resourceTypeListActual.get(i));\r
+        }\r
+\r
+        boolean thrown = false;\r
+        try {\r
+            representation.setResourceTypes(null);\r
+        } catch (InvalidParameterException e) {\r
+            thrown = true;\r
+        }\r
+        assertTrue(thrown);\r
+    }\r
+\r
+    public void testResourceInterfacesGetSet() {\r
+        OcRepresentation representation = new OcRepresentation();\r
+\r
+        List<String> emptyResourceInterfaceList = representation.getResourceInterfaces();\r
+        assertTrue(emptyResourceInterfaceList.isEmpty());\r
+\r
+        representation.setResourceInterfaces(emptyResourceInterfaceList);\r
+        emptyResourceInterfaceList = representation.getResourceInterfaces();\r
+        assertTrue(emptyResourceInterfaceList.isEmpty());\r
+\r
+        List<String> resourceInterfaceListExpected = new LinkedList<String>();\r
+        resourceInterfaceListExpected.add("Interface1");\r
+        resourceInterfaceListExpected.add("Interface2");\r
+        resourceInterfaceListExpected.add("Interface3");\r
+\r
+        representation.setResourceInterfaces(resourceInterfaceListExpected);\r
+        List<String> resourceInterfaceListActual = representation.getResourceInterfaces();\r
+        assertEquals(resourceInterfaceListExpected.size(), resourceInterfaceListActual.size());\r
+        for (int i = 0; i < resourceInterfaceListExpected.size(); i++) {\r
+            assertEquals(resourceInterfaceListExpected.get(i), resourceInterfaceListActual.get(i));\r
+        }\r
+\r
+        boolean thrown = false;\r
+        try {\r
+            representation.setResourceInterfaces(null);\r
+        } catch (InvalidParameterException e) {\r
+            thrown = true;\r
+        }\r
+        assertTrue(thrown);\r
+    }\r
+\r
+    public void testAttributeManagement() {\r
+        OcRepresentation representation = new OcRepresentation();\r
+\r
+        assertTrue(representation.isEmpty());\r
+        assertEquals(0, representation.size());\r
+\r
+        try {\r
+            String integerKey = "integerKey";\r
+            int integerValue = 75;\r
+            representation.setValue(integerKey, integerValue);\r
+            assertFalse(representation.isEmpty());\r
+            assertEquals(1, representation.size());\r
+\r
+            int actualIntValue = representation.getValue(integerKey);\r
+            assertEquals(integerValue, actualIntValue);\r
+\r
+            String stringKey = "stringKey";\r
+            String stringValue = "stringValue";\r
+            representation.setValue(stringKey, stringValue);\r
+            assertEquals(2, representation.size());\r
+\r
+            assertTrue(representation.hasAttribute(integerKey));\r
+            representation.remove(integerKey);\r
+            assertFalse(representation.hasAttribute(integerKey));\r
+            assertEquals(1, representation.size());\r
+\r
+            representation.setValue(integerKey, integerValue);\r
+            assertFalse(representation.isNull(integerKey));\r
+            representation.setNull(integerKey);\r
+            assertTrue(representation.isNull(integerKey));\r
+        } catch (OcException e) {\r
+            assertTrue(false);\r
+        }\r
+\r
+        String nonexistentKey = "nonexistentKey";\r
+        assertFalse(representation.hasAttribute(nonexistentKey));\r
+        representation.setNull(nonexistentKey);\r
+        assertTrue(representation.isNull(nonexistentKey));\r
+\r
+        String nonexistentKey2 = "nonexistentKey2";\r
+        boolean thrown = false;\r
+        try {\r
+            boolean nonexistentValue = representation.getValue(nonexistentKey2);\r
+        } catch (OcException e) {\r
+            thrown = true;\r
+        }\r
+        assertTrue(thrown);\r
+    }\r
+\r
+    public void testAttributeAccessByType() throws OcException {\r
+        OcRepresentation rep = new OcRepresentation();\r
+\r
+        //integer\r
+        String intK = "intK";\r
+        int intV = 4;\r
+        rep.setValue(intK, intV);\r
+        int intVa = rep.getValue(intK);\r
+        assertEquals(intV, intVa);\r
+\r
+        //double\r
+        String doubleK = "doubleK";\r
+        double doubleV = 4.5;\r
+        rep.setValue(doubleK, doubleV);\r
+        double doubleVa = rep.getValue(doubleK);\r
+        assertEquals(doubleV, doubleVa);\r
+\r
+        //boolean\r
+        String booleanK = "booleanK";\r
+        boolean booleanV = true;\r
+        rep.setValue(booleanK, booleanV);\r
+        boolean booleanVa = rep.getValue(booleanK);\r
+        assertEquals(booleanV, booleanVa);\r
+\r
+        //String\r
+        String stringK = "stringK";\r
+        String stringV = "stringV";\r
+        rep.setValue(stringK, stringV);\r
+        String stringVa = rep.getValue(stringK);\r
+        assertEquals(stringV, stringVa);\r
+\r
+        //OcRepresentation\r
+        String repK = "repK";\r
+        OcRepresentation repV = new OcRepresentation();\r
+        repV.setValue(intK, intV);\r
+        rep.setValue(repK, repV);\r
+        OcRepresentation repVa = rep.getValue(repK);\r
+        assertEquals(intV, repVa.getValue(intK));\r
+    }\r
+\r
+    public void testAttributeAccessBySequenceType() throws OcException {\r
+        OcRepresentation rep = new OcRepresentation();\r
+\r
+        //integer\r
+        String intK = "intK";\r
+        int[] intArrV = {1, 2, 3, 4};\r
+        rep.setValue(intK, intArrV);\r
+        int[] intArrVa = rep.getValue(intK);\r
+        assertTrue(Arrays.equals(intArrV, intArrVa));\r
+\r
+        int[] intArrVEmpty = {};\r
+        rep.setValue(intK, intArrVEmpty);\r
+        int[] intArrVEmptyA = rep.getValue(intK);\r
+        assertTrue(Arrays.equals(intArrVEmpty, intArrVEmptyA));\r
+\r
+        //double\r
+        String doubleK = "doubleK";\r
+        double[] doubleArrV = {1.1, 2.2, 3.3, 4.4};\r
+        rep.setValue(doubleK, doubleArrV);\r
+        double[] doubleArrVa = rep.getValue(doubleK);\r
+        assertTrue(Arrays.equals(doubleArrV, doubleArrVa));\r
+\r
+        double[] doubleArrVEmpty = {};\r
+        rep.setValue(doubleK, doubleArrVEmpty);\r
+        double[] doubleArrVEmptyA = rep.getValue(doubleK);\r
+        assertTrue(Arrays.equals(doubleArrVEmpty, doubleArrVEmptyA));\r
+\r
+        //boolean\r
+        String booleanK = "booleanK";\r
+        boolean[] booleanArrV = {true, false, true, false};\r
+        rep.setValue(booleanK, booleanArrV);\r
+        boolean[] booleanArrVa = rep.getValue(booleanK);\r
+        assertTrue(Arrays.equals(booleanArrV, booleanArrVa));\r
+\r
+        boolean[] booleanArrVEmpty = {};\r
+        rep.setValue(booleanK, booleanArrVEmpty);\r
+        boolean[] booleanArrVEmptyA = rep.getValue(booleanK);\r
+        assertTrue(Arrays.equals(booleanArrVEmpty, booleanArrVEmptyA));\r
+\r
+        //String\r
+        String stringK = "stringK";\r
+        String[] stringArrV = {"aaa", "bbb", "ccc", "ddd"};\r
+        rep.setValue(stringK, stringArrV);\r
+        String[] stringArrVa = rep.getValue(stringK);\r
+        assertTrue(Arrays.equals(stringArrV, stringArrVa));\r
+\r
+        String[] stringArrVEmpty = {};\r
+        rep.setValue(stringK, stringArrVEmpty);\r
+        String[] stringArrVEmptyA = rep.getValue(stringK);\r
+        assertTrue(Arrays.equals(stringArrVEmpty, stringArrVEmptyA));\r
+\r
+        //OcRepresentation\r
+        String representationK = "representationK";\r
+        OcRepresentation[] representationArrV = {\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation()};\r
+        representationArrV[0].setValue(intK, 0);\r
+        representationArrV[1].setValue(intK, 1);\r
+        representationArrV[2].setValue(intK, 2);\r
+        representationArrV[3].setValue(intK, 3);\r
+\r
+        rep.setValue(representationK, representationArrV);\r
+        OcRepresentation[] representationArrVa = rep.getValue(representationK);\r
+\r
+        assertEquals(representationArrV.length, representationArrVa.length);\r
+        for (int i = 0; i < representationArrV.length; ++i) {\r
+            assertEquals(representationArrV[i].getValue(intK),\r
+                    representationArrVa[i].getValue(intK));\r
+        }\r
+\r
+        OcRepresentation[] representationArrVEmpty = {};\r
+        rep.setValue(representationK, representationArrVEmpty);\r
+        OcRepresentation[] representationArrVEmptyA = rep.getValue(representationK);\r
+        assertEquals(representationArrVEmpty.length, representationArrVEmptyA.length);\r
+    }\r
+\r
+    public void testAttributeAccessBy2DType() throws OcException {\r
+        OcRepresentation rep = new OcRepresentation();\r
+        //integer\r
+        String int2DK = "int2DK";\r
+        int[] intArrV1 = {1, 2, 3, 4};\r
+        int[] intArrV2 = {5, 6, 7, 8};\r
+        int[][] int2DArrV = {intArrV1, intArrV2};\r
+        rep.setValue(int2DK, int2DArrV);\r
+        int[][] int2DArrVa = rep.getValue(int2DK);\r
+        for (int i = 0; i < int2DArrV.length; i++) {\r
+            assertTrue(Arrays.equals(int2DArrV[i], int2DArrVa[i]));\r
+        }\r
+        //double\r
+        String double2DK = "double2DK";\r
+        double[] doubleArrV1 = {1.1, 2.2, 3.3, 4.4};\r
+        double[] doubleArrV2 = {5, 6, 7, 8};\r
+        double[][] double2DArrV = {doubleArrV1, doubleArrV2};\r
+        rep.setValue(double2DK, double2DArrV);\r
+        double[][] double2DArrVa = rep.getValue(double2DK);\r
+        for (int i = 0; i < double2DArrV.length; i++) {\r
+            assertTrue(Arrays.equals(double2DArrV[i], double2DArrVa[i]));\r
+        }\r
+        double[][] double2DArrVEmpty = {{}};\r
+        rep.setValue(double2DK, double2DArrVEmpty);\r
+        double[][] double2DArrVEmptyA = rep.getValue(double2DK);\r
+        for (int i = 0; i < double2DArrVEmpty.length; i++) {\r
+            assertTrue(Arrays.equals(double2DArrVEmpty[i], double2DArrVEmptyA[i]));\r
+        }\r
+        //boolean\r
+        String boolean2DK = "boolean2DK";\r
+        boolean[] booleanArrV1 = {true, true, false};\r
+        boolean[] booleanArrV2 = {true, false, false, true};\r
+        boolean[][] boolean2DArrV = {booleanArrV1, booleanArrV2};\r
+        rep.setValue(boolean2DK, boolean2DArrV);\r
+        boolean[][] boolean2DArrVa = rep.getValue(boolean2DK);\r
+        for (int i = 0; i < boolean2DArrV.length; i++) {\r
+            assertTrue(Arrays.equals(boolean2DArrV[i], boolean2DArrVa[i]));\r
+        }\r
+        boolean[][] boolean2DArrVEmpty = {{}};\r
+        rep.setValue(boolean2DK, boolean2DArrVEmpty);\r
+        boolean[][] boolean2DArrVEmptyA = rep.getValue(boolean2DK);\r
+        for (int i = 0; i < boolean2DArrVEmpty.length; i++) {\r
+            assertTrue(Arrays.equals(boolean2DArrVEmpty[i], boolean2DArrVEmptyA[i]));\r
+        }\r
+\r
+        //String\r
+        String string2DK = "string2DK";\r
+        String[] stringArrV1 = {"aaa", "bbb", "ccc"};\r
+        String[] stringArrV2 = {"111", "222", "333", "444"};\r
+        String[][] string2DArrV = {stringArrV1, stringArrV2};\r
+        rep.setValue(string2DK, string2DArrV);\r
+        String[][] string2DArrVa = rep.getValue(string2DK);\r
+        for (int i = 0; i < string2DArrV.length; i++) {\r
+            assertTrue(Arrays.equals(string2DArrV[i], string2DArrVa[i]));\r
+        }\r
+        String[][] string2DArrVEmpty = {{}};\r
+        rep.setValue(string2DK, string2DArrVEmpty);\r
+        String[][] string2DArrVEmptyA = rep.getValue(string2DK);\r
+        for (int i = 0; i < string2DArrVEmpty.length; i++) {\r
+            assertTrue(Arrays.equals(string2DArrVEmpty[i], string2DArrVEmptyA[i]));\r
+        }\r
+\r
+        //OcRepresentation\r
+        String intK = "intK";\r
+        String representation2DK = "representation2DK";\r
+        OcRepresentation[] representation2DArrV1 = {\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation()};\r
+        representation2DArrV1[0].setValue(intK, 0);\r
+        representation2DArrV1[1].setValue(intK, 1);\r
+        representation2DArrV1[2].setValue(intK, 2);\r
+        representation2DArrV1[3].setValue(intK, 3);\r
+\r
+        OcRepresentation[] representation2DArrV2 = {\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation()};\r
+        representation2DArrV2[0].setValue(intK, 4);\r
+        representation2DArrV2[1].setValue(intK, 5);\r
+        representation2DArrV2[2].setValue(intK, 6);\r
+        representation2DArrV2[3].setValue(intK, 7);\r
+\r
+        OcRepresentation[][] representation2DArrV = {representation2DArrV1, representation2DArrV2};\r
+        rep.setValue(representation2DK, representation2DArrV);\r
+        OcRepresentation[][] representation2DArrVa = rep.getValue(representation2DK);\r
+        assertEquals(representation2DArrV.length, representation2DArrVa.length);\r
+        for (int i = 0; i < representation2DArrV.length; ++i) {\r
+            OcRepresentation[] repArrV = representation2DArrV[i];\r
+            OcRepresentation[] repArrVa = representation2DArrVa[i];\r
+            assertEquals(repArrV.length, repArrVa.length);\r
+            for (int j = 0; j < representation2DArrV.length; ++j) {\r
+                assertEquals(repArrV[j].getValue(intK),\r
+                        repArrVa[j].getValue(intK));\r
+            }\r
+        }\r
+\r
+        OcRepresentation[][] representation2DArrVEmpty = {{}};\r
+        rep.setValue(representation2DK, representation2DArrVEmpty);\r
+        OcRepresentation[][] representation2DArrVEmptyA = rep.getValue(representation2DK);\r
+        assertEquals(representation2DArrVEmpty.length, representation2DArrVEmptyA.length);\r
+    }\r
+\r
+    public void testAttributeAccessBy3DType() throws OcException {\r
+        OcRepresentation rep = new OcRepresentation();\r
+        //integer\r
+        String int3DK = "int3DK";\r
+        int[] intArrV1 = {0, 1, 2, 3, 4};\r
+        int[] intArrV2 = {5, 6, 7, 8};\r
+        int[][] int2DArrV1 = {intArrV1, intArrV2};\r
+        int[] intArrV3 = {9, 10};\r
+        int[] intArrV4 = {11};\r
+        int[][] int2DArrV2 = {intArrV3, intArrV4};\r
+        int[][][] int3DArrV = {int2DArrV1, int2DArrV2};\r
+        rep.setValue(int3DK, int3DArrV);\r
+        int[][][] int3DArrVa = rep.getValue(int3DK);\r
+        assertEquals(int3DArrV.length, int3DArrVa.length);\r
+        for (int i = 0; i < int3DArrV.length; i++) {\r
+            int[][] int2DT = int3DArrV[i];\r
+            int[][] int2DTa = int3DArrVa[i];\r
+            assertEquals(int2DT.length, int2DTa.length);\r
+            for (int j = 0; j < int2DT.length; j++) {\r
+                assertTrue(Arrays.equals(int2DT[j], int2DTa[j]));\r
+            }\r
+        }\r
+        //double\r
+        String double3DK = "double3DK";\r
+        double[] doubleArrV1 = {0.0, 1.1, 2.2, 3.3, 4.4};\r
+        double[] doubleArrV2 = {5.5, 6.6, 7.7, 8.8};\r
+        double[][] double2DArrV1 = {doubleArrV1, doubleArrV2};\r
+        double[] doubleArrV3 = {9.9, 10.1};\r
+        double[] doubleArrV4 = {11.1};\r
+        double[][] double2DArrV2 = {doubleArrV3, doubleArrV4};\r
+        double[][][] double3DArrV = {double2DArrV1, double2DArrV2};\r
+        rep.setValue(double3DK, double3DArrV);\r
+        double[][][] double3DArrVa = rep.getValue(double3DK);\r
+        assertEquals(double3DArrV.length, double3DArrVa.length);\r
+        for (int i = 0; i < double3DArrV.length; i++) {\r
+            double[][] double2DT = double3DArrV[i];\r
+            double[][] double2DTa = double3DArrVa[i];\r
+            assertEquals(double2DT.length, double2DTa.length);\r
+            for (int j = 0; j < double2DT.length; j++) {\r
+                assertTrue(Arrays.equals(double2DT[j], double2DTa[j]));\r
+            }\r
+        }\r
+        double[][][] double3DArrVEmpty = {};\r
+        rep.setValue(double3DK, double3DArrVEmpty);\r
+        double[][][] double3DArrVEmptyA = rep.getValue(double3DK);\r
+        assertEquals(double3DArrVEmpty.length, double3DArrVEmptyA.length);\r
+        for (int i = 0; i < double3DArrVEmpty.length; i++) {\r
+            double[][] double2DT = double3DArrVEmpty[i];\r
+            double[][] double2DTa = double3DArrVEmptyA[i];\r
+            assertEquals(double2DT.length, double2DTa.length);\r
+            for (int j = 0; j < double2DT.length; j++) {\r
+                assertTrue(Arrays.equals(double2DT[j], double2DTa[j]));\r
+            }\r
+        }\r
+\r
+        //boolean\r
+        String boolean3DK = "boolean3DK";\r
+        boolean[] booleanArrV1 = {true, false, true, true, false};\r
+        boolean[] booleanArrV2 = {false, false, false, true};\r
+        boolean[][] boolean2DArrV1 = {booleanArrV1, booleanArrV2};\r
+        boolean[] booleanArrV3 = {true, true};\r
+        boolean[] booleanArrV4 = {false};\r
+        boolean[][] boolean2DArrV2 = {booleanArrV3, booleanArrV4};\r
+        boolean[][][] boolean3DArrV = {boolean2DArrV1, boolean2DArrV2};\r
+        rep.setValue(boolean3DK, boolean3DArrV);\r
+        boolean[][][] boolean3DArrVa = rep.getValue(boolean3DK);\r
+        assertEquals(boolean3DArrV.length, boolean3DArrVa.length);\r
+        for (int i = 0; i < boolean3DArrV.length; i++) {\r
+            boolean[][] boolean2DT = boolean3DArrV[i];\r
+            boolean[][] boolean2DTa = boolean3DArrVa[i];\r
+            assertEquals(boolean2DT.length, boolean2DTa.length);\r
+            for (int j = 0; j < boolean2DT.length; j++) {\r
+                assertTrue(Arrays.equals(boolean2DT[j], boolean2DTa[j]));\r
+            }\r
+        }\r
+        boolean[][][] boolean3DArrVEmpty = {};\r
+        rep.setValue(boolean3DK, boolean3DArrVEmpty);\r
+        boolean[][][] boolean3DArrVEmptyA = rep.getValue(boolean3DK);\r
+        assertEquals(boolean3DArrVEmpty.length, boolean3DArrVEmptyA.length);\r
+        for (int i = 0; i < boolean3DArrVEmpty.length; i++) {\r
+            boolean[][] boolean2DT = boolean3DArrVEmpty[i];\r
+            boolean[][] boolean2DTa = boolean3DArrVEmptyA[i];\r
+            assertEquals(boolean2DT.length, boolean2DTa.length);\r
+            for (int j = 0; j < boolean2DT.length; j++) {\r
+                assertTrue(Arrays.equals(boolean2DT[j], boolean2DTa[j]));\r
+            }\r
+        }\r
+\r
+        //String\r
+        String string3DK = "string3DK";\r
+        String[] stringArrV1 = {"a", "bb", "ccc", "dddd", "eeee"};\r
+        String[] stringArrV2 = {"f", "gg", "hhh", "ii"};\r
+        String[][] string2DArrV1 = {stringArrV1, stringArrV2};\r
+        String[] stringArrV3 = {"j", "jj"};\r
+        String[] stringArrV4 = {"jjj"};\r
+        String[][] string2DArrV2 = {stringArrV3, stringArrV4};\r
+        String[][][] string3DArrV = {string2DArrV1, string2DArrV2};\r
+        rep.setValue(string3DK, string3DArrV);\r
+        String[][][] string3DArrVa = rep.getValue(string3DK);\r
+        assertEquals(string3DArrV.length, string3DArrVa.length);\r
+        for (int i = 0; i < string3DArrV.length; i++) {\r
+            String[][] string2DT = string3DArrV[i];\r
+            String[][] string2DTa = string3DArrVa[i];\r
+            assertEquals(string2DT.length, string2DTa.length);\r
+            for (int j = 0; j < string2DT.length; j++) {\r
+                assertTrue(Arrays.equals(string2DT[j], string2DTa[j]));\r
+            }\r
+        }\r
+        String[][][] string3DArrVEmpty = {};\r
+        rep.setValue(string3DK, string3DArrVEmpty);\r
+        String[][][] string3DArrVEmptyA = rep.getValue(string3DK);\r
+        assertEquals(string3DArrVEmpty.length, string3DArrVEmptyA.length);\r
+        for (int i = 0; i < string3DArrVEmpty.length; i++) {\r
+            String[][] string2DT = string3DArrVEmpty[i];\r
+            String[][] string2DTa = string3DArrVEmptyA[i];\r
+            assertEquals(string2DT.length, string2DTa.length);\r
+            for (int j = 0; j < string2DT.length; j++) {\r
+                assertTrue(Arrays.equals(string2DT[j], string2DTa[j]));\r
+            }\r
+        }\r
+\r
+        //OcRepresentation\r
+        String intK = "intK";\r
+        String representation3DK = "representation3DK";\r
+        OcRepresentation[] representation2DArrV1 = {\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation()};\r
+        representation2DArrV1[0].setValue(intK, 0);\r
+        representation2DArrV1[1].setValue(intK, 1);\r
+        representation2DArrV1[2].setValue(intK, 2);\r
+        representation2DArrV1[3].setValue(intK, 3);\r
+\r
+        OcRepresentation[] representation2DArrV2 = {\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation(),\r
+                new OcRepresentation()};\r
+        representation2DArrV2[0].setValue(intK, 4);\r
+        representation2DArrV2[1].setValue(intK, 5);\r
+        representation2DArrV2[2].setValue(intK, 6);\r
+        representation2DArrV2[3].setValue(intK, 7);\r
+\r
+        OcRepresentation[][] representation2DArrV = {representation2DArrV1, representation2DArrV2};\r
+        OcRepresentation[][][] representation3DArrV = {representation2DArrV, representation2DArrV};\r
+\r
+        rep.setValue(representation3DK, representation3DArrV);\r
+        OcRepresentation[][][] representation3DArrVa = rep.getValue(representation3DK);\r
+        assertEquals(representation3DArrV.length, representation3DArrVa.length);\r
+        for (int i = 0; i < representation3DArrV.length; ++i) {\r
+            OcRepresentation[][] repArr2V = representation3DArrV[i];\r
+            OcRepresentation[][] repArr2Va = representation3DArrVa[i];\r
+            assertEquals(repArr2V.length, repArr2Va.length);\r
+            for (int j = 0; j < repArr2V.length; ++j) {\r
+                OcRepresentation[] repArrV = repArr2V[j];\r
+                OcRepresentation[] repArrVa = repArr2Va[j];\r
+                assertEquals(repArrV.length, repArrVa.length);\r
+                for (int k = 0; k < repArrV.length; ++k) {\r
+                    assertEquals(repArrV[k].getValue(intK), repArrVa[k].getValue(intK));\r
+                }\r
+            }\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java b/android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java
new file mode 100644 (file)
index 0000000..490496a
--- /dev/null
@@ -0,0 +1,1563 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base;
+
+import android.test.InstrumentationTestCase;
+import android.util.Log;
+
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class SmokeTest extends InstrumentationTestCase {
+    private static final String TAG = "SmokeTest";
+    private Random rnd = new Random();
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        PlatformConfig cfg = new PlatformConfig(
+                getInstrumentation().getContext(),
+                ServiceType.IN_PROC,
+                ModeType.CLIENT_SERVER,
+                "0.0.0.0",
+                0,
+                QualityOfService.LOW);
+
+        OcPlatform.Configure(cfg);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testResourceRegisterUnregister() throws InterruptedException {
+        final String resourceType = "unit.test.resource" +
+                new Date().getTime();
+        final CountDownLatch signal = new CountDownLatch(1);
+
+        OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+            @Override
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                return EntityHandlerResult.OK;
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        Log.i(TAG, "Host: " + resource.getHost());
+                        Log.i(TAG, "Server ID: " + resource.getServerId());
+                        Log.i(TAG, "Connectivity Type: " + resource.getConnectivityType());
+                        signal.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testStartStopListenForPresence() throws InterruptedException {
+        final String resourceType = "unit.test.resource" +
+                new Date().getTime();
+        final CountDownLatch signal = new CountDownLatch(1);
+
+        OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+            @Override
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                return EntityHandlerResult.OK;
+            }
+        };
+
+        final OcPlatform.OnPresenceListener presenceListener = new OcPlatform.OnPresenceListener() {
+            @Override
+            public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress) {
+                Log.i(TAG, "onPresence status " + ocPresenceStatus.toString() + " nonce " + nonce);
+                signal.countDown();
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        try {
+                            //client
+                            OcPresenceHandle presenceHandle = OcPlatform.subscribePresence(
+                                    resource.getHost(),
+                                    OcConnectivityType.IPV4,
+                                    presenceListener
+                            );
+
+                            //wait for onPresence event
+                            assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+                            //client
+                            OcPlatform.unsubscribePresence(presenceHandle);
+                        } catch (OcException e) {
+                            assertTrue(false);
+                        } catch (InterruptedException e) {
+                            assertTrue(false);
+                        }
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //server
+            OcPlatform.startPresence(OcPlatform.DEFAULT_PRESENCE_TTL);
+
+            //wait for onPresence event
+            assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.stopPresence();
+
+            //client
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testHandleGetRequest() throws InterruptedException {
+        final String someKey = "SomeKey";
+        final String someValue = "SomeValue";
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal1 = new CountDownLatch(1);
+        final CountDownLatch signal2 = new CountDownLatch(1);
+        final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+        //client
+        final OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
+            @Override
+            public void onGetCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+                if (!headerOptionList.isEmpty()) {
+                    for (OcHeaderOption headerOption : headerOptionList) {
+                        Log.i(TAG, "Header option " +
+                                headerOption.getOptionId() +
+                                " : " +
+                                headerOption.getOptionData());
+                    }
+                }
+                try {
+                    Log.i(TAG, "Power: " + ocRepresentation.getValue("power"));
+                } catch (OcException e) {
+                    Log.e(TAG, e.toString());
+                    assertTrue(false);
+                }
+                signal2.countDown();
+            }
+
+            @Override
+            public void onGetFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.e(TAG, ex.toString());
+                assertTrue(false);
+            }
+        };
+
+        //client
+        final OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        Map<String, String> queryParamsMap = new HashMap<String, String>();
+                        queryParamsMap.put(someKey, someValue);
+
+                        ocResourceList.add(resource);
+                        try {
+                            resource.get(queryParamsMap, onGetListener);
+                            //TODO there is a bug in the stack that prevents the usage of the following APIs
+//                            resource.get(resourceType, OcPlatform.DEFAULT_INTERFACE, queryParamsMap,
+//                                    onGetListener);
+//
+//                            resource.get(queryParamsMap, onGetListener, QualityOfService.LOW);
+//
+//                            resource.get(resourceType, OcPlatform.DEFAULT_INTERFACE,queryParamsMap,
+//                                    onGetListener, QualityOfService.LOW);
+                        } catch (OcException e) {
+                            Log.e(TAG, e.toString());
+                            assertTrue(false);
+                        }
+                        signal1.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    new OcPlatform.EntityHandler() {
+                        @Override
+                        public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                            EnumSet<RequestHandlerFlag> handlerFlagSet =
+                                    ocResourceRequest.getRequestHandlerFlagSet();
+
+                            RequestType requestType = ocResourceRequest.getRequestType();
+
+                            if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+                                OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                                ocResourceResponse.setRequestHandle(
+                                        ocResourceRequest.getRequestHandle());
+                                ocResourceResponse.setResourceHandle(
+                                        ocResourceRequest.getResourceHandle());
+
+                                switch (requestType) {
+                                    case GET:
+                                        Map<String, String> queryParams =
+                                                ocResourceRequest.getQueryParameters();
+//TODO after the merge with CA, the query params are missing
+//                                        if (!(queryParams.containsKey(someKey) &&
+//                                                someValue.equals(queryParams.get(someKey)))) {
+//                                            assertTrue(false);
+//                                        }
+
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+                                        ocResourceResponse.setResourceRepresentation(
+                                                getRepresentation(74));
+                                        break;
+                                }
+
+                                try {
+                                    OcPlatform.sendResponse(ocResourceResponse);
+                                } catch (OcException e) {
+                                    Log.e(TAG, e.getMessage());
+                                    return EntityHandlerResult.ERROR;
+                                }
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+                            }
+                            return EntityHandlerResult.OK;
+                        }
+                    },
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource(null,
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+            //wait for onGetCompleted event
+            assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testHandlePutRequest() throws InterruptedException {
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal1 = new CountDownLatch(1);
+        final CountDownLatch signal2 = new CountDownLatch(3);
+        final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+        final OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {
+            @Override
+            public void onPutCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+                if (!headerOptionList.isEmpty()) {
+                    for (OcHeaderOption headerOption : headerOptionList) {
+                        Log.i(TAG, "Header option " +
+                                headerOption.getOptionId() +
+                                " : " +
+                                headerOption.getOptionData());
+                    }
+                }
+                try {
+                    Log.i(TAG, "onPutCompleted Power: " + ocRepresentation.getValue("power"));
+                } catch (OcException e) {
+                    Log.e(TAG, e.getMessage());
+                    assertTrue(false);
+                }
+                Log.i(TAG, "onPutCompleted Uri: " + ocRepresentation.getUri());
+                signal2.countDown();
+            }
+
+            @Override
+            public void onPutFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.e(TAG, ex.toString());
+                assertTrue(false);
+            }
+        };
+
+        final OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        ocResourceList.add(resource);
+                        try {
+                            resource.put(
+                                    getRepresentation(),
+                                    new HashMap<String, String>(),
+                                    onPutListener);
+
+                            resource.put(
+                                    getRepresentation(),
+                                    new HashMap<String, String>(),
+                                    onPutListener);
+
+                            resource.put(
+                                    getRepresentation(),
+                                    new HashMap<String, String>(),
+                                    new OcResource.OnPutListener() {
+                                        @Override
+                                        public void onPutCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+                                            signal2.countDown();
+                                        }
+
+                                        @Override
+                                        public void onPutFailed(Throwable ex) {
+                                            if (ex instanceof OcException) {
+                                                OcException ocEx = (OcException) ex;
+                                                ErrorCode errCode = ocEx.getErrorCode();
+                                            }
+                                            Log.e(TAG, ex.toString());
+                                            assertTrue(false);
+                                        }
+                                    });
+
+                        } catch (OcException e) {
+                            assertTrue(false);
+                        }
+                        signal1.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    new OcPlatform.EntityHandler() {
+                        @Override
+                        public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                            EnumSet<RequestHandlerFlag> handlerFlagSet = ocResourceRequest.getRequestHandlerFlagSet();
+                            RequestType requestType = ocResourceRequest.getRequestType();
+
+                            if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+                                OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                                ocResourceResponse.setRequestHandle(
+                                        ocResourceRequest.getRequestHandle());
+                                ocResourceResponse.setResourceHandle(
+                                        ocResourceRequest.getResourceHandle());
+
+                                switch (requestType) {
+                                    case GET:
+                                        assertTrue(false);
+                                        break;
+                                    case PUT:
+                                        OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
+                                        try {
+                                            Log.i(TAG, "Put res. power: " + rep.getValue("power"));
+                                        } catch (OcException e) {
+                                            Log.e(TAG, e.toString());
+                                            assertTrue(false);
+                                        }
+                                        Log.i(TAG, "URI: " + rep.getUri());
+
+                                        ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResourceRepresentation(rep);
+                                        break;
+                                    case POST:
+                                        assertTrue(false);
+                                        break;
+                                    case DELETE:
+                                        break;
+                                }
+
+                                try {
+                                    OcPlatform.sendResponse(ocResourceResponse);
+                                } catch (OcException e) {
+                                    Log.e(TAG, e.getMessage());
+                                    return EntityHandlerResult.ERROR;
+                                }
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+                            }
+                            return EntityHandlerResult.OK;
+                        }
+                    },
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+            //wait for onGetCompleted event
+            assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testHandlePostRequest() throws InterruptedException {
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal1 = new CountDownLatch(1);
+        final CountDownLatch signal2 = new CountDownLatch(3);
+        final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+        final OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {
+            @Override
+            public void onPostCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+                if (!headerOptionList.isEmpty()) {
+                    for (OcHeaderOption headerOption : headerOptionList) {
+                        Log.i(TAG, "Header option " +
+                                headerOption.getOptionId() +
+                                " : " +
+                                headerOption.getOptionData());
+                    }
+                }
+                try {
+                    Log.i(TAG, "onPostCompleted Power: " + ocRepresentation.getValue("power"));
+                } catch (OcException e) {
+                    Log.e(TAG, e.toString());
+                    assertTrue(false);
+                }
+                Log.i(TAG, "onPostCompleted Uri: " + ocRepresentation.getUri());
+                signal2.countDown();
+            }
+
+            @Override
+            public void onPostFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.e(TAG, ex.toString());
+                assertTrue(false);
+            }
+        };
+
+        final OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        ocResourceList.add(resource);
+                        try {
+                            resource.post(
+                                    getRepresentation(),
+                                    new HashMap<String, String>(),
+                                    onPostListener);
+
+                            resource.post(
+                                    getRepresentation(),
+                                    new HashMap<String, String>(),
+                                    onPostListener);
+
+                            resource.post(
+                                    getRepresentation(),
+                                    new HashMap<String, String>(),
+                                    new OcResource.OnPostListener() {
+                                        @Override
+                                        public void onPostCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+                                            signal2.countDown();
+                                        }
+
+                                        @Override
+                                        public void onPostFailed(Throwable ex) {
+                                            if (ex instanceof OcException) {
+                                                OcException ocEx = (OcException) ex;
+                                                ErrorCode errCode = ocEx.getErrorCode();
+                                            }
+                                            Log.e(TAG, ex.toString());
+                                            assertTrue(false);
+                                        }
+                                    });
+
+                        } catch (OcException e) {
+                            assertTrue(false);
+                        }
+                        signal1.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    new OcPlatform.EntityHandler() {
+                        @Override
+                        public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                            EnumSet<RequestHandlerFlag> handlerFlagSet = ocResourceRequest.getRequestHandlerFlagSet();
+                            RequestType requestType = ocResourceRequest.getRequestType();
+
+                            if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+                                OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                                ocResourceResponse.setRequestHandle(
+                                        ocResourceRequest.getRequestHandle());
+                                ocResourceResponse.setResourceHandle(
+                                        ocResourceRequest.getResourceHandle());
+
+                                switch (requestType) {
+                                    case GET:
+                                        assertTrue(false);
+                                        break;
+                                    case PUT:
+                                        assertTrue(false);
+                                        break;
+                                    case POST:
+                                        OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
+                                        try {
+                                            Log.i(TAG, "Post res. power: " + rep.getValue("power"));
+                                        } catch (OcException e) {
+                                            Log.e(TAG, e.toString());
+                                            assertTrue(false);
+                                        }
+                                        Log.i(TAG, "URI: " + rep.getUri());
+
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+                                        ocResourceResponse.setResourceRepresentation(
+                                                getRepresentation(44));
+
+                                        break;
+                                    case DELETE:
+                                        assertTrue(false);
+                                        break;
+                                }
+
+                                try {
+                                    OcPlatform.sendResponse(ocResourceResponse);
+                                } catch (OcException e) {
+                                    Log.e(TAG, e.getMessage());
+                                    return EntityHandlerResult.ERROR;
+                                }
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+                            }
+                            return EntityHandlerResult.OK;
+                        }
+                    },
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+            //wait for onPostCompleted event
+            assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+
+    }
+
+    public void testHandleDeleteRequest() throws InterruptedException {
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal1 = new CountDownLatch(1);
+        final CountDownLatch signal2 = new CountDownLatch(1);
+        final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+        final OcResource.OnDeleteListener onDeleteListener = new OcResource.OnDeleteListener() {
+            @Override
+            public void onDeleteCompleted(List<OcHeaderOption> headerOptionList) {
+                signal2.countDown();
+            }
+
+            @Override
+            public void onDeleteFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.e(TAG, ex.toString());
+                assertTrue(false);
+            }
+        };
+
+        final OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        ocResourceList.add(resource);
+                        try {
+                            resource.deleteResource(onDeleteListener);
+                        } catch (OcException e) {
+                            assertTrue(false);
+                        }
+                        signal1.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    new OcPlatform.EntityHandler() {
+                        @Override
+                        public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                            EnumSet<RequestHandlerFlag> handlerFlagSet =
+                                    ocResourceRequest.getRequestHandlerFlagSet();
+                            RequestType requestType = ocResourceRequest.getRequestType();
+
+                            if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+                                OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                                ocResourceResponse.setRequestHandle(
+                                        ocResourceRequest.getRequestHandle());
+                                ocResourceResponse.setResourceHandle(
+                                        ocResourceRequest.getResourceHandle());
+
+                                switch (requestType) {
+                                    case DELETE:
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResponseResult(
+                                                EntityHandlerResult.RESOURCE_DELETED);
+                                        break;
+                                }
+
+                                try {
+                                    OcPlatform.sendResponse(ocResourceResponse);
+                                } catch (OcException e) {
+                                    Log.e(TAG, e.getMessage());
+                                    return EntityHandlerResult.ERROR;
+                                }
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+                            }
+                            return EntityHandlerResult.OK;
+                        }
+                    },
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+            //wait for onDeleteCompleted event
+            assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testHandleGetPutPostDeleteFailures() throws InterruptedException {
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal1 = new CountDownLatch(1);
+        final CountDownLatch signal2 = new CountDownLatch(1);
+        final CountDownLatch signal3 = new CountDownLatch(1);
+        final CountDownLatch signal4 = new CountDownLatch(1);
+        final CountDownLatch signal5 = new CountDownLatch(1);
+
+        final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+        final OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
+            @Override
+            public void onGetCompleted(List<OcHeaderOption> headerOptionList,
+                                       OcRepresentation ocRepresentation) {
+                assertTrue(false);
+            }
+
+            @Override
+            public void onGetFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.i(TAG, ex.toString());
+                signal2.countDown();
+            }
+        };
+
+        final OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {
+            @Override
+            public void onPutCompleted(List<OcHeaderOption> headerOptionList,
+                                       OcRepresentation ocRepresentation) {
+                assertTrue(false);
+            }
+
+            @Override
+            public void onPutFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.i(TAG, ex.toString());
+                signal3.countDown();
+            }
+        };
+        final OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {
+            @Override
+            public void onPostCompleted(List<OcHeaderOption> headerOptionList,
+                                        OcRepresentation ocRepresentation) {
+                assertTrue(false);
+            }
+
+            @Override
+            public void onPostFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.i(TAG, ex.toString());
+                signal4.countDown();
+            }
+        };
+
+        final OcResource.OnDeleteListener onDeleteListener = new OcResource.OnDeleteListener() {
+            @Override
+            public void onDeleteCompleted(List<OcHeaderOption> headerOptionList) {
+                assertTrue(false);
+            }
+
+            @Override
+            public void onDeleteFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.i(TAG, ex.toString());
+                signal5.countDown();
+            }
+        };
+
+        final OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        ocResourceList.add(resource);
+                        try {
+                            resource.get(new HashMap<String, String>(), onGetListener);
+                            resource.put(new OcRepresentation(), new HashMap<String, String>(),
+                                    onPutListener);
+                            resource.post(new OcRepresentation(), new HashMap<String, String>(),
+                                    onPostListener);
+                            resource.deleteResource(onDeleteListener);
+                        } catch (OcException e) {
+                            assertTrue(false);
+                        }
+                        signal1.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    new OcPlatform.EntityHandler() {
+                        @Override
+                        public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                            EnumSet<RequestHandlerFlag> handlerFlagSet =
+                                    ocResourceRequest.getRequestHandlerFlagSet();
+                            RequestType requestType = ocResourceRequest.getRequestType();
+
+                            if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+                                OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                                ocResourceResponse.setRequestHandle(
+                                        ocResourceRequest.getRequestHandle());
+                                ocResourceResponse.setResourceHandle(
+                                        ocResourceRequest.getResourceHandle());
+
+                                switch (requestType) {
+                                    case GET:
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResponseResult(
+                                                EntityHandlerResult.ERROR);
+                                        break;
+                                    case PUT:
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResponseResult(
+                                                EntityHandlerResult.ERROR);
+                                        break;
+                                    case POST:
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResponseResult(
+                                                EntityHandlerResult.ERROR);
+                                        break;
+                                    case DELETE:
+                                        ocResourceResponse.setErrorCode(200);
+                                        ocResourceResponse.setResponseResult(
+                                                EntityHandlerResult.ERROR);
+                                        break;
+                                }
+                                try {
+                                    OcPlatform.sendResponse(ocResourceResponse);
+                                } catch (OcException e) {
+                                    Log.e(TAG, e.getMessage());
+                                    return EntityHandlerResult.ERROR;
+                                }
+                            }
+                            if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+                            }
+                            return EntityHandlerResult.OK;
+                        }
+                    },
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal1.await(60, TimeUnit.SECONDS));
+            //wait for onGetCompleted event
+            assertTrue(signal2.await(60, TimeUnit.SECONDS));
+            //wait for onPutCompleted event
+            assertTrue(signal3.await(60, TimeUnit.SECONDS));
+            //wait for onPostCompleted event
+            assertTrue(signal4.await(60, TimeUnit.SECONDS));
+            //wait for onDeleteCompleted event
+            assertTrue(signal5.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testRegisterDeviceInfoGetDeviceInfo() throws InterruptedException {
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal = new CountDownLatch(1);
+
+        OcPlatform.OnDeviceFoundListener deviceFoundListener = new OcPlatform.OnDeviceFoundListener() {
+            @Override
+            public void onDeviceFound(OcRepresentation ocRepresentation) {
+                try {
+                    Log.i(TAG, "Device Name: " + ocRepresentation.getValue("dn"));
+                } catch (OcException e) {
+                    Log.e(TAG, e.toString());
+                    assertTrue(false);
+                }
+                boolean hasDeviceNameAtr = ocRepresentation.hasAttribute("dn");
+                assertTrue(hasDeviceNameAtr);
+                boolean hasNonExistingAtr = ocRepresentation.hasAttribute("NonExisting");
+                assertFalse(hasNonExistingAtr);
+                Log.i(TAG, "URI: " + ocRepresentation.getUri());
+                signal.countDown();
+            }
+        };
+
+        OcDeviceInfo devInfo = new OcDeviceInfo();
+
+        devInfo.setContentType("myContentType");
+        devInfo.setDateOfManufacture("myDateOfManufacture");
+        devInfo.setDeviceName("myDeviceName");
+        devInfo.setDeviceUuid("myDeviceUUID");
+        devInfo.setFirmwareVersion("myFirmwareVersion");
+        devInfo.setHostName("myHostName");
+        devInfo.setManufacturerName("myManufacturerNa");
+        devInfo.setManufacturerUrl("myManufacturerUrl");
+        devInfo.setModelNumber("myModelNumber");
+        devInfo.setPlatformVersion("myPlatformVersion");
+        devInfo.setSupportUrl("mySupportUrl");
+        devInfo.setVersion("myVersion");
+
+        try {
+            //server
+            OcPlatform.registerDeviceInfo(devInfo);
+
+            //client
+            OcPlatform.getDeviceInfo(
+                    "",
+                    OcPlatform.WELL_KNOWN_QUERY + "/d",
+                    OcConnectivityType.IPV4,
+                    deviceFoundListener);
+
+            //wait for onDeviceFound event
+            assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testBindUnbindResources() throws InterruptedException {
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal1 = new CountDownLatch(3);
+        final CountDownLatch signal2 = new CountDownLatch(2);
+        final CountDownLatch signal3 = new CountDownLatch(1);
+        final CountDownLatch signal4 = new CountDownLatch(3);
+        final CountDownLatch signal5 = new CountDownLatch(3);
+        final CountDownLatch signal6 = new CountDownLatch(1);
+
+        OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+            @Override
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                return EntityHandlerResult.OK;
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener1 = new OcPlatform.OnResourceFoundListener() {
+            @Override
+            public void onResourceFound(OcResource resource) {
+                signal1.countDown();
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener2 = new OcPlatform.OnResourceFoundListener() {
+            @Override
+            public void onResourceFound(OcResource resource) {
+                signal2.countDown();
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener3 = new OcPlatform.OnResourceFoundListener() {
+            @Override
+            public void onResourceFound(OcResource resource) {
+                signal3.countDown();
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener4 = new OcPlatform.OnResourceFoundListener() {
+            @Override
+            public void onResourceFound(OcResource resource) {
+                signal4.countDown();
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener5 = new OcPlatform.OnResourceFoundListener() {
+            @Override
+            public void onResourceFound(OcResource resource) {
+                signal5.countDown();
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener6 = new OcPlatform.OnResourceFoundListener() {
+            @Override
+            public void onResourceFound(OcResource resource) {
+                signal6.countDown();
+            }
+        };
+
+        try {
+
+            //server
+            OcResourceHandle resourceHandleCollection = OcPlatform.registerResource(
+                    "/a/unittest1",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            OcResourceHandle resourceHandle1 = OcPlatform.registerResource(
+                    "/a/unittest2",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            OcResourceHandle resourceHandle2 = OcPlatform.registerResource(
+                    "/a/unittest3",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener1);
+
+            //wait for onResourceFound event to find 3 registered resources
+            assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.bindResource(resourceHandleCollection, resourceHandle1);
+            OcPlatform.bindResource(resourceHandleCollection, resourceHandle2);
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener3);
+
+            //wait for onResourceFound event to find 1 collection resources
+            assertTrue(signal3.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unbindResource(resourceHandleCollection, resourceHandle1);
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener2);
+
+            //wait for onResourceFound event to find 2 resources
+            assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unbindResource(resourceHandleCollection, resourceHandle2);
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener4);
+
+            //wait for onResourceFound event to find 3 registered resources
+            assertTrue(signal4.await(60, TimeUnit.SECONDS));
+
+            //Bind/unbind a list of resource handles
+            List<OcResourceHandle> resourceHandleList = new LinkedList<OcResourceHandle>();
+            resourceHandleList.add(resourceHandle1);
+            resourceHandleList.add(resourceHandle2);
+            OcPlatform.bindResources(resourceHandleCollection, resourceHandleList);
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener6);
+
+            //wait for onResourceFound event to find 1 collection resources
+            assertTrue(signal6.await(60, TimeUnit.SECONDS));
+
+            OcPlatform.unbindResources(resourceHandleCollection, resourceHandleList);
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener5);
+
+            //wait for onResourceFound event to find 1 collection resources
+            assertTrue(signal5.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandleCollection);
+            OcPlatform.unregisterResource(resourceHandle1);
+            OcPlatform.unregisterResource(resourceHandle2);
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testResourceMethods() throws InterruptedException {
+        final String resourceType1 = "unit.test.resource" + new Date().getTime();
+        final String resourceType2 = "unit.test.resource" + new Date().getTime();
+
+        final CountDownLatch signal = new CountDownLatch(2);
+        final List<OcResource> resourceList = new LinkedList<OcResource>();
+
+        OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+            @Override
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                return EntityHandlerResult.OK;
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        resourceList.add(resource);
+                        Log.i(TAG, "Host: " + resource.getHost());
+                        Log.i(TAG, "Uri: " + resource.getUri());
+                        Log.i(TAG, "Observable: " + resource.isObservable());
+
+                        for (String resourceType : resource.getResourceTypes()) {
+                            Log.i(TAG, "Type: " + resourceType);
+                        }
+
+                        for (String resourceInterface : resource.getResourceInterfaces()) {
+                            Log.i(TAG, "Interface: " + resourceInterface);
+                        }
+
+                        List<OcHeaderOption> headerOptionList = new LinkedList<OcHeaderOption>();
+                        headerOptionList.add(new OcHeaderOption(2885, "OptionData1"));
+                        headerOptionList.add(new OcHeaderOption(2886, "OptionData2"));
+                        resource.setHeaderOptions(headerOptionList);
+
+                        resource.setHeaderOptions(headerOptionList);
+                        resource.unsetHeaderOptions();
+
+                        OcResourceIdentifier resourceIdentifier = resource.getUniqueIdentifier();
+                        OcResourceIdentifier resourceIdentifier2 = resource.getUniqueIdentifier();
+                        assertTrue(resourceIdentifier.equals(resourceIdentifier2));
+
+                        signal.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle1 = OcPlatform.registerResource(
+                    "/a/unittest1",
+                    resourceType1,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            OcResourceHandle resourceHandle2 = OcPlatform.registerResource(
+                    "/a/unittest2",
+                    resourceType2,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType1,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType2,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+            assertTrue(2 == resourceList.size());
+
+            OcResource res0 = resourceList.get(0);
+            OcResource res1 = resourceList.get(1);
+            assertFalse(res0.getUniqueIdentifier().equals(res1.getUniqueIdentifier()));
+            assertTrue(res0.getUniqueIdentifier().equals(res0.getUniqueIdentifier()));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle1);
+            OcPlatform.unregisterResource(resourceHandle2);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testCreateResourceProxy() throws InterruptedException {
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+        final CountDownLatch signal = new CountDownLatch(1);
+
+        OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+            @Override
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                return EntityHandlerResult.OK;
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+
+                        try {
+                            //client: construct resource proxy
+                            OcResource resourceProxy = OcPlatform.constructResourceObject(
+                                    resource.getHost(),
+                                    resource.getUri(),
+                                    OcConnectivityType.IPV4,
+                                    resource.isObservable(),
+                                    resource.getResourceTypes(),
+                                    resource.getResourceInterfaces());
+
+                            //client: register resource proxy
+                            OcResourceHandle resourceProxyHandle =
+                                    OcPlatform.registerResource(resourceProxy);
+
+                            OcPlatform.unregisterResource(resourceProxyHandle);
+                        } catch (OcException e) {
+                            assertTrue(false);
+                        }
+                        signal.countDown();
+                    }
+                };
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE)
+            );
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    public void testObserveClientServer() throws InterruptedException {
+        final int NUM_OBSERVES = 20;
+        final Timer timer = new Timer();
+        final List<OcResource> resourceList = new LinkedList<OcResource>();
+        final List<OcResourceHandle> resourceHandleList = new LinkedList<OcResourceHandle>();
+        final CountDownLatch signal1 = new CountDownLatch(1);
+        final CountDownLatch signal2 = new CountDownLatch(NUM_OBSERVES);
+        final CountDownLatch signal3 = new CountDownLatch(1);
+
+        final String resourceType = "unit.test.resource" + new Date().getTime();
+
+        final OcResource.OnObserveListener observeListener = new OcResource.OnObserveListener() {
+            @Override
+            public void onObserveCompleted(
+                    List<OcHeaderOption> headerOptionList,
+                    OcRepresentation ocRepresentation,
+                    int sequenceNumber) {
+
+                try {
+                    Log.i(TAG, "Observe #" + sequenceNumber + " power: " +
+                            ocRepresentation.getValue("power"));
+                } catch (OcException e) {
+                    Log.e(TAG, e.toString());
+                    assertTrue(false);
+                }
+                signal2.countDown();
+            }
+
+            @Override
+            public void onObserveFailed(Throwable ex) {
+                if (ex instanceof OcException) {
+                    OcException ocEx = (OcException) ex;
+                    ErrorCode errCode = ocEx.getErrorCode();
+                }
+                Log.e(TAG, ex.toString());
+                assertTrue(false);
+            }
+        };
+
+        final List<Byte> observationIdList = new LinkedList<Byte>();
+        OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+            @Override
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+                EnumSet<RequestHandlerFlag> handlerFlagSet = ocResourceRequest.getRequestHandlerFlagSet();
+                RequestType requestType = ocResourceRequest.getRequestType();
+
+                if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+
+                }
+                if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+                    OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                    ocResourceResponse.setRequestHandle(ocResourceRequest.getRequestHandle());
+                    ocResourceResponse.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+                    switch (requestType) {
+                        case GET:
+                            ocResourceResponse.setErrorCode(200);
+                            ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+                            ocResourceResponse.setResourceRepresentation(
+                                    getRepresentation(
+                                            rnd.nextInt(100)));
+                            try {
+                                OcPlatform.sendResponse(ocResourceResponse);
+                            } catch (OcException e) {
+                                Log.e(TAG, e.getMessage());
+                                return EntityHandlerResult.ERROR;
+                            }
+                            break;
+                    }
+                }
+
+                if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+                    ObservationInfo observationInfo = ocResourceRequest.getObservationInfo();
+
+                    switch (observationInfo.getObserveAction()) {
+                        case REGISTER:
+                            synchronized (observationIdList) {
+                                observationIdList.add(observationInfo.getOcObservationId());
+                                timer.schedule(new TimerTask() {
+                                    int numNotified = 1;
+
+                                    @Override
+                                    public void run() {
+                                        if (0 < resourceHandleList.size()) {
+                                            synchronized (observationIdList) {
+                                                if (numNotified > NUM_OBSERVES) {
+                                                    timer.cancel();
+                                                    timer.purge();
+                                                    signal3.countDown();
+                                                } else {
+                                                    try {
+                                                        OcPlatform.notifyAllObservers(
+                                                                resourceHandleList.get(0));
+                                                    } catch (OcException e) {
+                                                        if (ErrorCode.NO_OBSERVERS == e.getErrorCode()) {
+                                                            timer.cancel();
+                                                            timer.purge();
+                                                            signal3.countDown();
+                                                        }
+                                                        Log.e(TAG, e.getMessage());
+                                                    }
+                                                    numNotified++;
+                                                }
+                                            }
+                                        }
+
+                                    }
+                                }, 0, 100);
+                            }
+                            break;
+                        case UNREGISTER:
+                            //TODO unregister isn't implemented in C++ API, yet
+                            synchronized (observationIdList) {
+                                timer.cancel();
+                                break;
+                            }
+                    }
+                }
+                return EntityHandlerResult.OK;
+            }
+        };
+
+        OcPlatform.OnResourceFoundListener resourceFoundListener =
+                new OcPlatform.OnResourceFoundListener() {
+                    @Override
+                    public void onResourceFound(OcResource resource) {
+                        resourceList.add(resource);
+                        if (resource.isObservable()) {
+                            try {
+                                resource.observe(
+                                        ObserveType.OBSERVE,
+                                        new HashMap<String, String>(),
+                                        observeListener);
+
+                                signal1.countDown();
+                            } catch (OcException e) {
+                                Log.e(TAG, e.getMessage());
+                                assertTrue(false);
+                            }
+                        }
+                    }
+                };
+        try {
+            //server
+            OcResourceHandle resourceHandle = OcPlatform.registerResource(
+                    "/a/unittest",
+                    resourceType,
+                    OcPlatform.DEFAULT_INTERFACE,
+                    entityHandler,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE)
+            );
+
+            resourceHandleList.add(resourceHandle);
+
+            //client
+            OcPlatform.findResource("",
+                    OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+                    OcConnectivityType.IPV4,
+                    resourceFoundListener);
+
+            //wait for onResourceFound event
+            assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+            //wait for OnObserveListener event to observe 20 values
+            assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+            if (resourceList.size() > 0) {
+                OcResource resource = resourceList.get(0);
+                if (resource.isObservable()) {
+                    resource.cancelObserve();
+                }
+            }
+
+            //wait for server to finish
+            assertTrue(signal3.await(60, TimeUnit.SECONDS));
+
+            //server
+            OcPlatform.unregisterResource(resourceHandle);
+
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+            assertTrue(false);
+        }
+    }
+
+    private OcRepresentation getRepresentation(int value) {
+        OcRepresentation rep = new OcRepresentation();
+        try {
+            rep.setValue("power", value);
+        } catch (OcException e) {
+            Log.e(TAG, e.toString());
+            assertTrue(false);
+        }
+        return rep;
+    }
+
+    private OcRepresentation getRepresentation() {
+        return getRepresentation(74);
+    }
+}
diff --git a/android/android_api/base/src/main/AndroidManifest.xml b/android/android_api/base/src/main/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..183e674
--- /dev/null
@@ -0,0 +1,35 @@
+<!--\r
+  ~ //******************************************************************\r
+  ~ //\r
+  ~ // Copyright 2015 Intel Corporation.\r
+  ~ //\r
+  ~ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+  ~ //\r
+  ~ // Licensed under the Apache License, Version 2.0 (the "License");\r
+  ~ // you may not use this file except in compliance with the License.\r
+  ~ // You may obtain a copy of the License at\r
+  ~ //\r
+  ~ //      http://www.apache.org/licenses/LICENSE-2.0\r
+  ~ //\r
+  ~ // Unless required by applicable law or agreed to in writing, software\r
+  ~ // distributed under the License is distributed on an "AS IS" BASIS,\r
+  ~ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+  ~ // See the License for the specific language governing permissions and\r
+  ~ // limitations under the License.\r
+  ~ //\r
+  ~ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+  -->\r
+\r
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    package="org.iotivity.base">\r
+    <uses-permission android:name="android.permission.BLUETOOTH" />\r
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />\r
+    <uses-permission android:name="android.permission.INTERNET" />\r
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />\r
+    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />\r
+    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />\r
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />\r
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />\r
+\r
+    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="21" />\r
+</manifest>\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/EntityHandlerResult.java b/android/android_api/base/src/main/java/org/iotivity/base/EntityHandlerResult.java
new file mode 100644 (file)
index 0000000..d8ed2fb
--- /dev/null
@@ -0,0 +1,42 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum EntityHandlerResult {\r
+    OK(0),\r
+    ERROR(1),\r
+    RESOURCE_CREATED(2),\r
+    RESOURCE_DELETED(3),\r
+    SLOW(4),\r
+    FORBIDDEN(5);\r
+\r
+    private int value;\r
+\r
+    private EntityHandlerResult(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/ErrorCode.java b/android/android_api/base/src/main/java/org/iotivity/base/ErrorCode.java
new file mode 100644 (file)
index 0000000..d1862e0
--- /dev/null
@@ -0,0 +1,95 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum ErrorCode {\r
+    /* Success status code - START HERE */\r
+    OK("OK", ""),\r
+    RESOURCE_CREATED("RESOURCE_CREATED", ""),\r
+    RESOURCE_DELETED("RESOURCE_DELETED", ""),\r
+    CONTINUE("CONTINUE", ""),\r
+    /* Success status code - END HERE */\r
+        /* Error status code - START HERE */\r
+    INVALID_URI("INVALID_URI", ""),\r
+    INVALID_QUERY("INVALID_QUERY", ""),\r
+    INVALID_IP("INVALID_IP", ""),\r
+    INVALID_PORT("INVALID_PORT", ""),\r
+    INVALID_CALLBACK("INVALID_CALLBACK", ""),\r
+    INVALID_METHOD("INVALID_METHOD", ""),\r
+    INVALID_PARAM("INVALID_PARAM", ""),\r
+    INVALID_OBSERVE_PARAM("INVALID_OBSERVE_PARAM", ""),\r
+    NO_MEMORY("NO_MEMORY", ""),\r
+    COMM_ERROR("COMM_ERROR", ""),\r
+    NOT_IMPL("NOTIMPL", ""),\r
+    NO_RESOURCE("NO_RESOURCE", "Resource not found"),\r
+    RESOURCE_ERROR("RESOURCE_ERROR", "Not supported method or interface"),\r
+    SLOW_RESOURCE("SLOW_RESOURCE", ""),\r
+    NO_OBSERVERS("NO_OBSERVERS", "Resource has no registered observers"),\r
+    OBSERVER_NOT_FOUND("OBSERVER_NOT_FOUND", ""),\r
+    PRESENCE_STOPPED("PRESENCE_STOPPED", ""),\r
+    PRESENCE_TIMEOUT("PRESENCE_TIMEOUT", ""),\r
+    PRESENCE_DO_NOT_HANDLE("PRESENCE_DO_NOT_HANDLE", ""),\r
+    VIRTUAL_DO_NOT_HANDLE("VIRTUAL_DO_NOT_HANDLE", ""),\r
+    INVALID_OPTION("INVALID_OPTION", ""),\r
+    MALFORMED_RESPONSE("MALFORMED_RESPONSE", "Remote reply contained malformed data"),\r
+    PERSISTENT_BUFFER_REQUIRED("PERSISTENT_BUFFER_REQUIRED", ""),\r
+    INVALID_REQUEST_HANDLE("INVALID_REQUEST_HANDLE", ""),\r
+    INVALID_DEVICE_INFO("INVALID_DEVICE_INFO", ""),\r
+    ERROR("ERROR", "Generic error"),\r
+\r
+    JNI_EXCEPTION("JNI_EXCEPTION", "Generic Java binder error"),\r
+    JNI_NO_NATIVE_OBJECT("JNI_NO_NATIVE_OBJECT", ""),\r
+    JNI_INVALID_VALUE("JNI_INVALID_VALUE", ""),\r
+\r
+    INVALID_CLASS_CAST("INVALID_CLASS_CAST", ""),;\r
+\r
+    private String error;\r
+    private String description;\r
+\r
+    private ErrorCode(String error, String description) {\r
+        this.error = error;\r
+        this.description = description;\r
+    }\r
+\r
+    public String getError() {\r
+        return error;\r
+    }\r
+\r
+    public String getDescription() {\r
+        return description;\r
+    }\r
+\r
+    public static ErrorCode get(String errorCode) {\r
+        for (ErrorCode eCode : ErrorCode.values()) {\r
+            if (eCode.getError().equals(errorCode)) {\r
+                return eCode;\r
+            }\r
+        }\r
+        throw new IllegalArgumentException("Unexpected ErrorCode value");\r
+    }\r
+\r
+    @Override\r
+    public String toString() {\r
+        return error + (description.isEmpty() ? "" : " : " + description);\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/ModeType.java b/android/android_api/base/src/main/java/org/iotivity/base/ModeType.java
new file mode 100644 (file)
index 0000000..81ea7c7
--- /dev/null
@@ -0,0 +1,39 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum ModeType {\r
+    SERVER(0),\r
+    CLIENT(1),\r
+    CLIENT_SERVER(2),;\r
+\r
+    private int value;\r
+\r
+    private ModeType(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/ObservationInfo.java b/android/android_api/base/src/main/java/org/iotivity/base/ObservationInfo.java
new file mode 100644 (file)
index 0000000..483d4cb
--- /dev/null
@@ -0,0 +1,55 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public class ObservationInfo {\r
+\r
+    private ObserveAction mObserveAction;\r
+    private byte mOcObservationId;\r
+\r
+    private ObservationInfo(int observationAction, byte observationId) {\r
+        this.mObserveAction = ObserveAction.get(observationAction);\r
+        this.mOcObservationId = observationId;\r
+    }\r
+\r
+    public ObservationInfo(ObserveAction observeAction, byte observationId) {\r
+        this.mObserveAction = observeAction;\r
+        this.mOcObservationId = observationId;\r
+    }\r
+\r
+    public ObserveAction getObserveAction() {\r
+        return mObserveAction;\r
+    }\r
+\r
+    public void setObserveAction(ObserveAction observeAction) {\r
+        this.mObserveAction = observeAction;\r
+    }\r
+\r
+    public byte getOcObservationId() {\r
+        return mOcObservationId;\r
+    }\r
+\r
+    public void setOcObservationId(byte ocObservationId) {\r
+        this.mOcObservationId = ocObservationId;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/ObserveAction.java b/android/android_api/base/src/main/java/org/iotivity/base/ObserveAction.java
new file mode 100644 (file)
index 0000000..3e7c5ec
--- /dev/null
@@ -0,0 +1,47 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum ObserveAction {\r
+    REGISTER(0),\r
+    UNREGISTER(1),;\r
+\r
+    private int value;\r
+\r
+    private ObserveAction(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+\r
+    public static ObserveAction get(int val) {\r
+        for (ObserveAction observeAction : ObserveAction.values()) {\r
+            if (observeAction.getValue() == val)\r
+                return observeAction;\r
+        }\r
+\r
+        throw new IllegalArgumentException("Unexpected ObserveAction value");\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/ObserveType.java b/android/android_api/base/src/main/java/org/iotivity/base/ObserveType.java
new file mode 100644 (file)
index 0000000..3432a47
--- /dev/null
@@ -0,0 +1,38 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum ObserveType {\r
+    OBSERVE(0),\r
+    OBSERVE_ALL(1),;\r
+\r
+    private int value;\r
+\r
+    private ObserveType(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcConnectivityType.java b/android/android_api/base/src/main/java/org/iotivity/base/OcConnectivityType.java
new file mode 100644 (file)
index 0000000..db38881
--- /dev/null
@@ -0,0 +1,52 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.security.InvalidParameterException;\r
+\r
+public enum OcConnectivityType {\r
+    IPV4    (0),\r
+    IPV6    (1),\r
+    EDR     (2),\r
+    LE      (3),\r
+    ALL     (4),\r
+    ;\r
+\r
+    private int value;\r
+\r
+    private OcConnectivityType(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+\r
+    public static OcConnectivityType get(int val) {\r
+        for (OcConnectivityType v : OcConnectivityType.values()) {\r
+            if (v.getValue() == val)\r
+                return v;\r
+        }\r
+        throw new InvalidParameterException("Unexpected OcConnectivityType value:" + val);\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java b/android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java
new file mode 100644 (file)
index 0000000..65e1497
--- /dev/null
@@ -0,0 +1,177 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public class OcDeviceInfo {\r
+\r
+    private String deviceName;\r
+    private String hostName;\r
+    private String deviceUuid;\r
+    private String contentType;\r
+    private String version;\r
+    private String manufacturerName;\r
+    private String manufacturerUrl;\r
+    private String modelNumber;\r
+    private String dateOfManufacture;\r
+    private String platformVersion;\r
+    private String firmwareVersion;\r
+    private String supportUrl;\r
+\r
+    public OcDeviceInfo() {\r
+        deviceName = "";\r
+        hostName = "";\r
+        deviceUuid = "";\r
+        contentType = "";\r
+        version = "";\r
+        manufacturerName = "";\r
+        manufacturerUrl = "";\r
+        modelNumber = "";\r
+        dateOfManufacture = "";\r
+        platformVersion = "";\r
+        firmwareVersion = "";\r
+        supportUrl = "";\r
+    }\r
+\r
+    public OcDeviceInfo(\r
+            String deviceName,\r
+            String hostName,\r
+            String deviceUuid,\r
+            String contentType,\r
+            String version,\r
+            String manufacturerName,\r
+            String manufacturerUrl,\r
+            String modelNumber,\r
+            String dateOfManufacture,\r
+            String platformVersion,\r
+            String firmwareVersion,\r
+            String supportUrl) {\r
+        this.deviceName = deviceName;\r
+        this.hostName = hostName;\r
+        this.deviceUuid = deviceUuid;\r
+        this.contentType = contentType;\r
+        this.version = version;\r
+        this.manufacturerName = manufacturerName;\r
+        this.manufacturerUrl = manufacturerUrl;\r
+        this.modelNumber = modelNumber;\r
+        this.dateOfManufacture = dateOfManufacture;\r
+        this.platformVersion = platformVersion;\r
+        this.firmwareVersion = firmwareVersion;\r
+        this.supportUrl = supportUrl;\r
+    }\r
+\r
+    public String getDeviceName() {\r
+        return deviceName;\r
+    }\r
+\r
+    public void setDeviceName(String deviceName) {\r
+        this.deviceName = deviceName;\r
+    }\r
+\r
+    public String getHostName() {\r
+        return hostName;\r
+    }\r
+\r
+    public void setHostName(String hostName) {\r
+        this.hostName = hostName;\r
+    }\r
+\r
+    public String getDeviceUuid() {\r
+        return deviceUuid;\r
+    }\r
+\r
+    public void setDeviceUuid(String deviceUuid) {\r
+        this.deviceUuid = deviceUuid;\r
+    }\r
+\r
+    public String getContentType() {\r
+        return contentType;\r
+    }\r
+\r
+    public void setContentType(String contentType) {\r
+        this.contentType = contentType;\r
+    }\r
+\r
+    public String getVersion() {\r
+        return version;\r
+    }\r
+\r
+    public void setVersion(String version) {\r
+        this.version = version;\r
+    }\r
+\r
+    public String getManufacturerName() {\r
+        return manufacturerName;\r
+    }\r
+\r
+    public void setManufacturerName(String manufacturerName) {\r
+        this.manufacturerName = manufacturerName;\r
+    }\r
+\r
+    public String getManufacturerUrl() {\r
+        return manufacturerUrl;\r
+    }\r
+\r
+    public void setManufacturerUrl(String manufacturerUrl) {\r
+        this.manufacturerUrl = manufacturerUrl;\r
+    }\r
+\r
+    public String getModelNumber() {\r
+        return modelNumber;\r
+    }\r
+\r
+    public void setModelNumber(String modelNumber) {\r
+        this.modelNumber = modelNumber;\r
+    }\r
+\r
+    public String getDateOfManufacture() {\r
+        return dateOfManufacture;\r
+    }\r
+\r
+    public void setDateOfManufacture(String dateOfManufacture) {\r
+        this.dateOfManufacture = dateOfManufacture;\r
+    }\r
+\r
+    public String getPlatformVersion() {\r
+        return platformVersion;\r
+    }\r
+\r
+    public void setPlatformVersion(String platformVersion) {\r
+        this.platformVersion = platformVersion;\r
+    }\r
+\r
+    public String getFirmwareVersion() {\r
+        return firmwareVersion;\r
+    }\r
+\r
+    public void setFirmwareVersion(String firmwareVersion) {\r
+        this.firmwareVersion = firmwareVersion;\r
+    }\r
+\r
+    public String getSupportUrl() {\r
+        return supportUrl;\r
+    }\r
+\r
+    public void setSupportUrl(String supportUrl) {\r
+        this.supportUrl = supportUrl;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcException.java b/android/android_api/base/src/main/java/org/iotivity/base/OcException.java
new file mode 100644 (file)
index 0000000..f83bf6c
--- /dev/null
@@ -0,0 +1,58 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public class OcException extends Exception {\r
+\r
+    private ErrorCode errorCode;\r
+\r
+    public OcException(ErrorCode errorCode, String errMessage) {\r
+        super(errMessage + " " + errorCode.toString());\r
+        this.errorCode = errorCode;\r
+    }\r
+\r
+    private OcException(String error, String errMessage) {\r
+        super(errMessage + " " + error);\r
+        this.errorCode = ErrorCode.get(error);\r
+    }\r
+\r
+    public ErrorCode getErrorCode() {\r
+        return errorCode;\r
+    }\r
+\r
+    private static void addStackTrace(Throwable throwable,\r
+                                      String file,\r
+                                      String functionName,\r
+                                      int line) {\r
+        StackTraceElement[] stack = throwable.getStackTrace();\r
+        StackTraceElement[] newStack = new StackTraceElement[stack.length + 1];\r
+\r
+        System.arraycopy(stack, 0, newStack, 1, stack.length);\r
+        newStack[0] = new StackTraceElement("<native>", functionName, file, line);\r
+        throwable.setStackTrace(newStack);\r
+    }\r
+\r
+    private void setNativeExceptionLocation(String file, String functionName, int line) {\r
+        OcException.addStackTrace(this, file, functionName, line);\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcHeaderOption.java b/android/android_api/base/src/main/java/org/iotivity/base/OcHeaderOption.java
new file mode 100644 (file)
index 0000000..984bc27
--- /dev/null
@@ -0,0 +1,70 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.security.InvalidParameterException;\r
+\r
+/**\r
+ * OcHeaderOption class allows to create instances which comprises optionId\r
+ * and optionData as members. These are used in setting Header options.\r
+ * After creating instances of OcHeaderOptions, use setHeaderOptions API\r
+ * (in OcResource) to set header Options.\r
+ * NOTE: optionId  is an integer value which MUST be within\r
+ * range of 2048 to 3000 inclusive of lower and upper bound.\r
+ * HeaderOption instance creation fails if above condition is not satisfied.\r
+ */\r
+public class OcHeaderOption {\r
+\r
+    public static final int MIN_HEADER_OPTION_ID = 2048;\r
+    public static final int MAX_HEADER_OPTION_ID = 3000;\r
+\r
+    private int mOptionId;\r
+    private String mOptionData;\r
+\r
+    public OcHeaderOption(int optionId, String optionData) {\r
+        if (!(optionId >= MIN_HEADER_OPTION_ID && optionId <= MAX_HEADER_OPTION_ID)) {\r
+            throw new InvalidParameterException("Option ID range is invalid");\r
+        }\r
+\r
+        this.mOptionId = optionId;\r
+        this.mOptionData = optionData;\r
+    }\r
+\r
+    /**\r
+     * API to get Option ID\r
+     *\r
+     * @return option ID\r
+     */\r
+    public int getOptionId() {\r
+        return mOptionId;\r
+    }\r
+\r
+    /**\r
+     * API to get Option data\r
+     *\r
+     * @return option data\r
+     */\r
+    public String getOptionData() {\r
+        return mOptionData;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java b/android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java
new file mode 100644 (file)
index 0000000..f55269b
--- /dev/null
@@ -0,0 +1,777 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import org.iotivity.ca.CaInterface;\r
+\r
+import java.util.EnumSet;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+/**\r
+ * Contains the main entrance/functionality of the product. To set a custom configuration, the\r
+ * implementer must make a call to OcPlatform.Configure before the first usage of a function in this\r
+ * class.\r
+ */\r
+public final class OcPlatform {\r
+\r
+    static {\r
+        System.loadLibrary("oc_logger");\r
+        System.loadLibrary("octbstack");\r
+        System.loadLibrary("connectivity_abstraction");\r
+        System.loadLibrary("oc");\r
+        System.loadLibrary("ocstack-jni");\r
+    }\r
+\r
+    /**\r
+     * Default interface\r
+     */\r
+    public static final String DEFAULT_INTERFACE = "oc.mi.def";\r
+\r
+    /**\r
+     * Used in discovering (GET) links to other resources of a collection\r
+     */\r
+    public static final String LINK_INTERFACE = "oc.mi.ll";\r
+\r
+    /**\r
+     * Used in GET, PUT, POST, DELETE methods on links to other resources of a collection\r
+     */\r
+    public static final String BATCH_INTERFACE = "oc.mi.b";\r
+\r
+    /**\r
+     * Used in GET, PUT, POST methods on links to other remote resources of a group\r
+     */\r
+    public static final String GROUP_INTERFACE = "oc.mi.grp";\r
+\r
+    public static final String WELL_KNOWN_QUERY = "224.0.1.187:5683/oc/core";\r
+    public static final String MULTICAST_PREFIX = "224.0.1.187:5683";\r
+    public static final String MULTICAST_IP = "224.0.1.187";\r
+    public static final int MULTICAST_PORT = 5683;\r
+    public static final int DEFAULT_PRESENCE_TTL = 60;\r
+    public static final String PRESENCE_URI = "/oc/presence";\r
+\r
+    private static volatile boolean sIsPlatformInitialized = false;\r
+\r
+    private OcPlatform() {\r
+    }\r
+\r
+    /**\r
+     * API for setting the configuration of the OcPlatform.\r
+     * Note: Any calls made to this AFTER the first call to OcPlatform.Configure will have no affect\r
+     *\r
+     * @param platformConfig platform configuration\r
+     */\r
+    public synchronized static void Configure(PlatformConfig platformConfig) {\r
+        if (!sIsPlatformInitialized) {\r
+            CaInterface.initialize(platformConfig.getContext());\r
+\r
+            OcPlatform.configure(\r
+                    platformConfig.getServiceType().getValue(),\r
+                    platformConfig.getModeType().getValue(),\r
+                    platformConfig.getIpAddress(),\r
+                    platformConfig.getPort(),\r
+                    platformConfig.getQualityOfService().getValue()\r
+            );\r
+\r
+            sIsPlatformInitialized = true;\r
+        }\r
+    }\r
+\r
+    private static native void configure(int serviceType,\r
+                                         int modeType,\r
+                                         String ipAddress,\r
+                                         int port,\r
+                                         int qualityOfService);\r
+\r
+    /**\r
+     * API for notifying base that resource's attributes have changed.\r
+     *\r
+     * @param ocResourceHandle resource handle of the resource\r
+     * @throws OcException\r
+     */\r
+    public static void notifyAllObservers(\r
+            OcResourceHandle ocResourceHandle) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.notifyAllObservers0(ocResourceHandle);\r
+    }\r
+\r
+    private static native void notifyAllObservers0(\r
+            OcResourceHandle ocResourceHandle) throws OcException;\r
+\r
+    /**\r
+     * API for notifying base that resource's attributes have changed.\r
+     *\r
+     * @param ocResourceHandle resource handle of the resource\r
+     * @param qualityOfService the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public static void notifyAllObservers(\r
+            OcResourceHandle ocResourceHandle,\r
+            QualityOfService qualityOfService) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.notifyAllObservers1(ocResourceHandle, qualityOfService.getValue());\r
+    }\r
+\r
+    private static native void notifyAllObservers1(\r
+            OcResourceHandle ocResourceHandle,\r
+            int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * API for notifying only specific clients that resource's attributes have changed.\r
+     *\r
+     * @param ocResourceHandle    resource handle of the resource\r
+     * @param ocObservationIdList These set of ids are ones which which will be notified upon\r
+     *                            resource change.\r
+     * @param ocResourceResponse  OcResourceResponse object used by app to fill the response for\r
+     *                            this resource change\r
+     * @throws OcException\r
+     */\r
+    public static void notifyListOfObservers(\r
+            OcResourceHandle ocResourceHandle,\r
+            List<Byte> ocObservationIdList,\r
+            OcResourceResponse ocResourceResponse) throws OcException {\r
+        OcPlatform.initCheck();\r
+\r
+        byte[] idArr = new byte[ocObservationIdList.size()];\r
+        Iterator<Byte> it = ocObservationIdList.iterator();\r
+        int i = 0;\r
+        while (it.hasNext()) {\r
+            idArr[i++] = (byte) it.next();\r
+        }\r
+\r
+        OcPlatform.notifyListOfObservers2(\r
+                ocResourceHandle,\r
+                idArr,\r
+                ocResourceResponse);\r
+    }\r
+\r
+    private static native void notifyListOfObservers2(\r
+            OcResourceHandle ocResourceHandle,\r
+            byte[] ocObservationIdArray,\r
+            OcResourceResponse ocResourceResponse) throws OcException;\r
+\r
+    /**\r
+     * API for notifying only specific clients that resource's attributes have changed.\r
+     *\r
+     * @param ocResourceHandle    resource handle of the resource\r
+     * @param ocObservationIdList These set of ids are ones which which will be notified upon\r
+     *                            resource change.\r
+     * @param ocResourceResponse  OcResourceResponse object used by app to fill the response for\r
+     *                            this resource change\r
+     * @param qualityOfService    the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public static void notifyListOfObservers(\r
+            OcResourceHandle ocResourceHandle,\r
+            List<Byte> ocObservationIdList,\r
+            OcResourceResponse ocResourceResponse,\r
+            QualityOfService qualityOfService) throws OcException {\r
+        OcPlatform.initCheck();\r
+\r
+        byte[] idArr = new byte[ocObservationIdList.size()];\r
+        Iterator<Byte> it = ocObservationIdList.iterator();\r
+        int i = 0;\r
+        while (it.hasNext()) {\r
+            idArr[i++] = (byte) it.next();\r
+        }\r
+\r
+        OcPlatform.notifyListOfObservers3(\r
+                ocResourceHandle,\r
+                idArr,\r
+                ocResourceResponse,\r
+                qualityOfService.getValue()\r
+        );\r
+    }\r
+\r
+    private static native void notifyListOfObservers3(\r
+            OcResourceHandle ocResourceHandle,\r
+            byte[] ocObservationIdArray,\r
+            OcResourceResponse ocResourceResponse,\r
+            int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * API for Service and Resource Discovery. NOTE: This API applies to client side only\r
+     *\r
+     * @param host                    Host IP Address of a service to direct resource discovery query.\r
+     *                                If empty, performs multicast resource discovery query\r
+     * @param resourceUri             name of the resource. If null or empty, performs search for all\r
+     *                                resource names\r
+     * @param connectivityType        a type of connectivity indicating the interface. Example: IPV4,\r
+     *                                IPV6, ALL\r
+     * @param onResourceFoundListener Handles events, success states and failure states.\r
+     * @throws OcException\r
+     */\r
+    public static void findResource(\r
+            String host,\r
+            String resourceUri,\r
+            OcConnectivityType connectivityType,\r
+            OnResourceFoundListener onResourceFoundListener) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.findResource0(\r
+                host,\r
+                resourceUri,\r
+                connectivityType.getValue(),\r
+                onResourceFoundListener\r
+        );\r
+    }\r
+\r
+    private static native void findResource0(\r
+            String host,\r
+            String resourceUri,\r
+            int connectivityType,\r
+            OnResourceFoundListener onResourceFoundListener) throws OcException;\r
+\r
+    /**\r
+     * API for Service and Resource Discovery. NOTE: This API applies to client side only\r
+     *\r
+     * @param host                    Host IP Address of a service to direct resource discovery query.\r
+     *                                If empty, performs multicast resource discovery query\r
+     * @param resourceUri             name of the resource. If null or empty, performs search for all\r
+     *                                resource names\r
+     * @param connectivityType        a type of connectivity indicating the interface. Example: IPV4,\r
+     *                                IPV6, ALL\r
+     * @param onResourceFoundListener Handles events, success states and failure states.\r
+     * @param qualityOfService        the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public static void findResource(\r
+            String host,\r
+            String resourceUri,\r
+            OcConnectivityType connectivityType,\r
+            OnResourceFoundListener onResourceFoundListener,\r
+            QualityOfService qualityOfService) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.findResource1(host,\r
+                resourceUri,\r
+                connectivityType.getValue(),\r
+                onResourceFoundListener,\r
+                qualityOfService.getValue()\r
+        );\r
+    }\r
+\r
+    private static native void findResource1(\r
+            String host,\r
+            String resourceUri,\r
+            int connectivityType,\r
+            OnResourceFoundListener onResourceFoundListener,\r
+            int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * API for Device Discovery\r
+     *\r
+     * @param host                  Host IP Address. If null or empty, Multicast is performed.\r
+     * @param deviceUri             Uri containing address to the virtual device\r
+     * @param connectivityType      a type of connectivity indicating the interface. Example: IPV4,\r
+     *                              IPV6, ALL\r
+     * @param onDeviceFoundListener Handles events, success states and failure states.\r
+     * @throws OcException\r
+     */\r
+    public static void getDeviceInfo(\r
+            String host,\r
+            String deviceUri,\r
+            OcConnectivityType connectivityType,\r
+            OnDeviceFoundListener onDeviceFoundListener) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.getDeviceInfo0(\r
+                host,\r
+                deviceUri,\r
+                connectivityType.getValue(),\r
+                onDeviceFoundListener\r
+        );\r
+    }\r
+\r
+    private static native void getDeviceInfo0(\r
+            String host,\r
+            String deviceUri,\r
+            int connectivityType,\r
+            OnDeviceFoundListener onDeviceFoundListener) throws OcException;\r
+\r
+    /**\r
+     * API for Device Discovery\r
+     *\r
+     * @param host                  Host IP Address. If null or empty, Multicast is performed.\r
+     * @param deviceUri             Uri containing address to the virtual device\r
+     * @param connectivityType      a type of connectivity indicating the interface. Example: IPV4,\r
+     *                              IPV6, ALL\r
+     * @param onDeviceFoundListener Handles events, success states and failure states.\r
+     * @param qualityOfService      the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public static void getDeviceInfo(\r
+            String host,\r
+            String deviceUri,\r
+            OcConnectivityType connectivityType,\r
+            OnDeviceFoundListener onDeviceFoundListener,\r
+            QualityOfService qualityOfService) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.getDeviceInfo1(\r
+                host,\r
+                deviceUri,\r
+                connectivityType.getValue(),\r
+                onDeviceFoundListener,\r
+                qualityOfService.getValue()\r
+        );\r
+    }\r
+\r
+    private static native void getDeviceInfo1(\r
+            String host,\r
+            String deviceUri,\r
+            int connectivityType,\r
+            OnDeviceFoundListener onDeviceFoundListener,\r
+            int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * This API registers a resource with the server NOTE: This API applies to server side only.\r
+     *\r
+     * @param ocResource The instance of OcResource with all data filled\r
+     * @return resource handle\r
+     * @throws OcException\r
+     */\r
+    public static OcResourceHandle registerResource(\r
+            OcResource ocResource) throws OcException {\r
+        OcPlatform.initCheck();\r
+        return OcPlatform.registerResource0(ocResource);\r
+    }\r
+\r
+    private static native OcResourceHandle registerResource0(\r
+            OcResource ocResource) throws OcException;\r
+\r
+    /**\r
+     * This API registers a resource with the server NOTE: This API applies to server side only.\r
+     *\r
+     * @param resourceUri         The URI of the resource. Example: "a/light"\r
+     * @param resourceTypeName    The resource type. Example: "light"\r
+     * @param resourceInterface   The resource interface (whether it is collection etc).\r
+     * @param entityHandler       entity handler.\r
+     * @param resourcePropertySet indicates the property of the resource\r
+     * @return resource handle\r
+     * @throws OcException\r
+     */\r
+    public static OcResourceHandle registerResource(\r
+            String resourceUri,\r
+            String resourceTypeName,\r
+            String resourceInterface,\r
+            EntityHandler entityHandler,\r
+            EnumSet<ResourceProperty> resourcePropertySet) throws OcException {\r
+        OcPlatform.initCheck();\r
+\r
+        int resProperty = 0;\r
+\r
+        for (ResourceProperty prop : ResourceProperty.values()) {\r
+            if (resourcePropertySet.contains(prop))\r
+                resProperty |= prop.getValue();\r
+        }\r
+\r
+        return OcPlatform.registerResource1(resourceUri,\r
+                resourceTypeName,\r
+                resourceInterface,\r
+                entityHandler,\r
+                resProperty);\r
+    }\r
+\r
+    private static native OcResourceHandle registerResource1(\r
+            String resourceUri,\r
+            String resourceTypeName,\r
+            String resourceInterface,\r
+            EntityHandler entityHandler,\r
+            int resourceProperty) throws OcException;\r
+\r
+    /**\r
+     * Register Device Info\r
+     *\r
+     * @param ocDeviceInfo object containing all the device specific information\r
+     * @throws OcException\r
+     */\r
+    public static void registerDeviceInfo(\r
+            OcDeviceInfo ocDeviceInfo) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.registerDeviceInfo0(\r
+                ocDeviceInfo.getDeviceName(),\r
+                ocDeviceInfo.getHostName(),\r
+                ocDeviceInfo.getDeviceUuid(),\r
+                ocDeviceInfo.getContentType(),\r
+                ocDeviceInfo.getVersion(),\r
+                ocDeviceInfo.getManufacturerName(),\r
+                ocDeviceInfo.getManufacturerUrl(),\r
+                ocDeviceInfo.getModelNumber(),\r
+                ocDeviceInfo.getDateOfManufacture(),\r
+                ocDeviceInfo.getPlatformVersion(),\r
+                ocDeviceInfo.getFirmwareVersion(),\r
+                ocDeviceInfo.getSupportUrl()\r
+        );\r
+    }\r
+\r
+    private static native void registerDeviceInfo0(\r
+            String deviceName,\r
+            String hostName,\r
+            String deviceUUID,\r
+            String contentType,\r
+            String version,\r
+            String manufacturerName,\r
+            String manufacturerUrl,\r
+            String modelNumber,\r
+            String dateOfManufacture,\r
+            String platformVersion,\r
+            String firmwareVersion,\r
+            String supportUrl) throws OcException;\r
+\r
+    /**\r
+     * This API unregisters a resource with the server NOTE: This API applies to server side only.\r
+     *\r
+     * @param ocResourceHandle This is the resource handle which we which to unregister from the\r
+     *                         server\r
+     * @throws OcException\r
+     */\r
+    public static void unregisterResource(\r
+            OcResourceHandle ocResourceHandle) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.unregisterResource0(ocResourceHandle);\r
+    }\r
+\r
+    private static native void unregisterResource0(\r
+            OcResourceHandle ocResourceHandle) throws OcException;\r
+\r
+\r
+    /**\r
+     * Add a resource to a collection resource\r
+     *\r
+     * @param ocResourceCollectionHandle handle to the collection resource\r
+     * @param ocResourceHandle           handle to resource to be added to the collection resource\r
+     * @throws OcException\r
+     */\r
+    public static void bindResource(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            OcResourceHandle ocResourceHandle) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.bindResource0(ocResourceCollectionHandle, ocResourceHandle);\r
+    }\r
+\r
+    private static native void bindResource0(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            OcResourceHandle ocResourceHandle) throws OcException;\r
+\r
+    /**\r
+     * Add multiple resources to a collection resource.\r
+     *\r
+     * @param ocResourceCollectionHandle handle to the collection resource\r
+     * @param ocResourceHandleList       reference to list of resource handles to be added to the\r
+     *                                   collection resource\r
+     * @throws OcException\r
+     */\r
+    public static void bindResources(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            List<OcResourceHandle> ocResourceHandleList) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.bindResources0(\r
+                ocResourceCollectionHandle,\r
+                ocResourceHandleList.toArray(\r
+                        new OcResourceHandle[ocResourceHandleList.size()])\r
+        );\r
+    }\r
+\r
+    private static native void bindResources0(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            OcResourceHandle[] ocResourceHandleArray) throws OcException;\r
+\r
+    /**\r
+     * Unbind a resource from a collection resource.\r
+     *\r
+     * @param ocResourceCollectionHandle handle to the collection resource\r
+     * @param ocResourceHandle           resource handle to be unbound from the collection resource\r
+     * @throws OcException\r
+     */\r
+    public static void unbindResource(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            OcResourceHandle ocResourceHandle) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.unbindResource0(ocResourceCollectionHandle, ocResourceHandle);\r
+    }\r
+\r
+    private static native void unbindResource0(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            OcResourceHandle ocResourceHandle) throws OcException;\r
+\r
+    /**\r
+     * Unbind resources from a collection resource.\r
+     *\r
+     * @param ocResourceCollectionHandle Handle to the collection resource\r
+     * @param ocResourceHandleList       List of resource handles to be unbound from the collection\r
+     *                                   resource\r
+     * @throws OcException\r
+     */\r
+    public static void unbindResources(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            List<OcResourceHandle> ocResourceHandleList) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.unbindResources0(\r
+                ocResourceCollectionHandle,\r
+                ocResourceHandleList.toArray(\r
+                        new OcResourceHandle[ocResourceHandleList.size()])\r
+        );\r
+    }\r
+\r
+    private static native void unbindResources0(\r
+            OcResourceHandle ocResourceCollectionHandle,\r
+            OcResourceHandle[] ocResourceHandleArray) throws OcException;\r
+\r
+    /**\r
+     * Binds a type to a particular resource\r
+     *\r
+     * @param ocResourceHandle handle to the resource\r
+     * @param resourceTypeName new typename to bind to the resource\r
+     * @throws OcException\r
+     */\r
+    public static void bindTypeToResource(\r
+            OcResourceHandle ocResourceHandle,\r
+            String resourceTypeName) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.bindTypeToResource0(ocResourceHandle, resourceTypeName);\r
+    }\r
+\r
+    private static native void bindTypeToResource0(\r
+            OcResourceHandle ocResourceHandle,\r
+            String resourceTypeName) throws OcException;\r
+\r
+    /**\r
+     * Binds an interface to a particular resource\r
+     *\r
+     * @param ocResourceHandle      handle to the resource\r
+     * @param resourceInterfaceName new interface to bind to the resource\r
+     * @throws OcException\r
+     */\r
+    public static void bindInterfaceToResource(\r
+            OcResourceHandle ocResourceHandle,\r
+            String resourceInterfaceName) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.bindInterfaceToResource0(ocResourceHandle, resourceInterfaceName);\r
+    }\r
+\r
+    private static native void bindInterfaceToResource0(\r
+            OcResourceHandle ocResourceHandle,\r
+            String resourceInterfaceName) throws OcException;\r
+\r
+    /**\r
+     * Start Presence announcements.\r
+     *\r
+     * @param ttl time to live in seconds\r
+     * @throws OcException\r
+     */\r
+    public static void startPresence(int ttl) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.startPresence0(ttl);\r
+    }\r
+\r
+    private static native void startPresence0(int ttl) throws OcException;\r
+\r
+    /**\r
+     * Stop Presence announcements.\r
+     *\r
+     * @throws OcException\r
+     */\r
+    public static void stopPresence() throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.stopPresence0();\r
+    }\r
+\r
+    private static native void stopPresence0() throws OcException;\r
+\r
+    /**\r
+     * Subscribes to a server's presence change events. By making this subscription, every time a\r
+     * server adds/removes/alters a resource, starts or is intentionally stopped\r
+     *\r
+     * @param host               The IP address/addressable name of the server to subscribe to\r
+     * @param connectivityType   a type of connectivity indicating the interface. Example: IPV4,\r
+     *                           IPV6, ALL\r
+     * @param onPresenceListener listener that will receive notifications/subscription events\r
+     * @return a handle object that can be used to identify this subscription request. It can be\r
+     * used to unsubscribe from these events in the future\r
+     * @throws OcException\r
+     */\r
+    public static OcPresenceHandle subscribePresence(\r
+            String host,\r
+            OcConnectivityType connectivityType,\r
+            OnPresenceListener onPresenceListener) throws OcException {\r
+        OcPlatform.initCheck();\r
+        return OcPlatform.subscribePresence0(\r
+                host,\r
+                connectivityType.getValue(),\r
+                onPresenceListener\r
+        );\r
+    }\r
+\r
+    private static native OcPresenceHandle subscribePresence0(\r
+            String host,\r
+            int connectivityType,\r
+            OnPresenceListener onPresenceListener) throws OcException;\r
+\r
+    /**\r
+     * Subscribes to a server's presence change events. By making this subscription, every time a\r
+     * server adds/removes/alters a resource, starts or is intentionally stopped\r
+     *\r
+     * @param host               The IP address/addressable name of the server to subscribe to\r
+     * @param resourceType       a resource type specified as a filter for subscription events.\r
+     * @param connectivityType   a type of connectivity indicating the interface. Example: IPV4,\r
+     *                           IPV6, ALL\r
+     * @param onPresenceListener listener that will receive notifications/subscription events\r
+     * @return a handle object that can be used to identify this subscription request. It can be\r
+     * used to unsubscribe from these events in the future\r
+     * @throws OcException\r
+     */\r
+    public static OcPresenceHandle subscribePresence(\r
+            String host,\r
+            String resourceType,\r
+            OcConnectivityType connectivityType,\r
+            OnPresenceListener onPresenceListener) throws OcException {\r
+        OcPlatform.initCheck();\r
+        return OcPlatform.subscribePresence1(\r
+                host,\r
+                resourceType,\r
+                connectivityType.getValue(),\r
+                onPresenceListener);\r
+    }\r
+\r
+    private static native OcPresenceHandle subscribePresence1(\r
+            String host,\r
+            String resourceType,\r
+            int connectivityType,\r
+            OnPresenceListener onPresenceListener) throws OcException;\r
+\r
+    /**\r
+     * Unsubscribes from a previously subscribed server's presence events. Note that you may for\r
+     * a short time still receive events from the server since it may take time for the\r
+     * unsubscribe to take effect.\r
+     *\r
+     * @param ocPresenceHandle the handle object provided by the subscribePresence call that\r
+     *                         identifies this subscription\r
+     * @throws OcException\r
+     */\r
+    public static void unsubscribePresence(\r
+            OcPresenceHandle ocPresenceHandle) throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.unsubscribePresence0(ocPresenceHandle);\r
+    }\r
+\r
+    private static native void unsubscribePresence0(\r
+            OcPresenceHandle ocPresenceHandle) throws OcException;\r
+\r
+    /**\r
+     * Creates a resource proxy object so that get/put/observe functionality can be used without\r
+     * discovering the object in advance. Note that the consumer of this method needs to provide\r
+     * all of the details required to correctly contact and observe the object. If the consumer\r
+     * lacks any of this information, they should discover the resource object normally.\r
+     * Additionally, you can only create this object if OcPlatform was initialized to be a Client\r
+     * or Client/Server.\r
+     *\r
+     * @param host             a string containing a resolvable host address of the server holding\r
+     *                         the resource\r
+     * @param uri              the rest of the resource's URI that will permit messages to be\r
+     *                         properly routed.\r
+     *                         Example: /a/light\r
+     * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,\r
+     *                         IPV6, ALL\r
+     * @param isObservable     a boolean containing whether the resource supports observation\r
+     * @param resourceTypeList a collection of resource types implemented by the resource\r
+     * @param interfaceList    a collection of interfaces that the resource supports/implements\r
+     * @return new resource object\r
+     * @throws OcException\r
+     */\r
+    public static OcResource constructResourceObject(\r
+            String host,\r
+            String uri,\r
+            OcConnectivityType connectivityType,\r
+            boolean isObservable,\r
+            List<String> resourceTypeList,\r
+            List<String> interfaceList) throws OcException {\r
+        OcPlatform.initCheck();\r
+        return OcPlatform.constructResourceObject0(\r
+                host,\r
+                uri,\r
+                connectivityType.getValue(),\r
+                isObservable,\r
+                resourceTypeList.toArray(new String[resourceTypeList.size()]),\r
+                interfaceList.toArray(new String[interfaceList.size()])\r
+        );\r
+    }\r
+\r
+    private static native OcResource constructResourceObject0(\r
+            String host,\r
+            String uri,\r
+            int connectivityType,\r
+            boolean isObservable,\r
+            String[] resourceTypes,\r
+            String[] interfaces) throws OcException;\r
+\r
+    /**\r
+     * Allows application entity handler to send response to an incoming request.\r
+     *\r
+     * @param ocResourceResponse resource response\r
+     * @throws OcException\r
+     */\r
+    public static void sendResponse(OcResourceResponse ocResourceResponse)\r
+            throws OcException {\r
+        OcPlatform.initCheck();\r
+        OcPlatform.sendResponse0(ocResourceResponse);\r
+    }\r
+\r
+    private static native void sendResponse0(OcResourceResponse ocResourceResponse)\r
+            throws OcException;\r
+\r
+    /**\r
+     * An OnResourceFoundListener can be registered via the OcPlatform.findResource call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnResourceFoundListener {\r
+        public void onResourceFound(OcResource resource);\r
+    }\r
+\r
+    /**\r
+     * An OnDeviceFoundListener can be registered via the OcPlatform.getDeviceInfo call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnDeviceFoundListener {\r
+        public void onDeviceFound(OcRepresentation ocRepresentation);\r
+    }\r
+\r
+    /**\r
+     * An OnPresenceListener can be registered via the OcPlatform.subscribePresence call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnPresenceListener {\r
+        public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress);\r
+    }\r
+\r
+    /**\r
+     * An EntityHandler can be registered via the OcPlatform.registerResource call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface EntityHandler {\r
+        public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest);\r
+    }\r
+\r
+    private static void initCheck() {\r
+        if (!sIsPlatformInitialized) {\r
+            throw new IllegalStateException("OcPlatform must be configured by making a call to " +\r
+                    "OcPlatform.Configure before any other API calls are permitted");\r
+        }\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcPlatformStatus.java b/android/android_api/base/src/main/java/org/iotivity/base/OcPlatformStatus.java
new file mode 100644 (file)
index 0000000..4ef76da
--- /dev/null
@@ -0,0 +1,39 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+\r
+public enum OcPlatformStatus {\r
+    UP(0),\r
+    DOWN(1),;\r
+\r
+    private int value;\r
+\r
+    private OcPlatformStatus(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcPresenceHandle.java b/android/android_api/base/src/main/java/org/iotivity/base/OcPresenceHandle.java
new file mode 100644 (file)
index 0000000..184be8f
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public class OcPresenceHandle {\r
+\r
+    private OcPresenceHandle(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+    }\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose();\r
+    }\r
+\r
+    private native void dispose();\r
+\r
+    private long mNativeHandle;\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcPresenceStatus.java b/android/android_api/base/src/main/java/org/iotivity/base/OcPresenceStatus.java
new file mode 100644 (file)
index 0000000..ff2c7dc
--- /dev/null
@@ -0,0 +1,50 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.security.InvalidParameterException;\r
+\r
+public enum OcPresenceStatus {\r
+    OK("OK"),\r
+    STOPPED("PRESENCE_STOPPED"),\r
+    TIMEOUT("PRESENCE_TIMEOUT"),\r
+    DO_NOT_HANDLE("PRESENCE_DO_NOT_HANDLE");\r
+\r
+    private String value;\r
+\r
+    private OcPresenceStatus(String value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public static OcPresenceStatus get(String val) {\r
+        for (OcPresenceStatus v : OcPresenceStatus.values()) {\r
+            if (v.getValue().equals(val))\r
+                return v;\r
+        }\r
+        throw new InvalidParameterException("Unexpected OcPresenceStatus value");\r
+    }\r
+\r
+    public String getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcRepresentation.java b/android/android_api/base/src/main/java/org/iotivity/base/OcRepresentation.java
new file mode 100644 (file)
index 0000000..98ec0bc
--- /dev/null
@@ -0,0 +1,358 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.security.InvalidParameterException;\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+/**\r
+ *\r
+ */\r
+public class OcRepresentation {\r
+\r
+    static {\r
+        System.loadLibrary("oc");\r
+        System.loadLibrary("ocstack-jni");\r
+    }\r
+\r
+    public OcRepresentation() {\r
+        create();\r
+        //Native OCRepresentation object was created using "new" and needs to be deleted\r
+        this.mNativeNeedsDelete = true;\r
+    }\r
+\r
+    private OcRepresentation(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+        this.mNativeNeedsDelete = false;\r
+    }\r
+\r
+    private OcRepresentation(long nativeHandle, boolean nativeNeedsDelete) {\r
+        this.mNativeHandle = nativeHandle;\r
+        this.mNativeNeedsDelete = nativeNeedsDelete;\r
+    }\r
+\r
+    public <T> T getValue(String key) throws OcException {\r
+        Object obj = this.getValueN(key);\r
+        @SuppressWarnings("unchecked")\r
+        T t = (T) obj;\r
+        return t;\r
+    }\r
+\r
+    private native Object getValueN(String key);\r
+\r
+    public void setValue(String key, int value) throws OcException {\r
+        this.setValueInteger(key, value);\r
+    }\r
+\r
+    public void setValue(String key, double value) throws OcException {\r
+        this.setValueDouble(key, value);\r
+    }\r
+\r
+    public void setValue(String key, boolean value) throws OcException {\r
+        this.setValueBoolean(key, value);\r
+    }\r
+\r
+    public void setValue(String key, String value) throws OcException {\r
+        this.setValueStringN(key, value);\r
+    }\r
+\r
+    public void setValue(String key, OcRepresentation value) throws OcException {\r
+        this.setValueRepresentation(key, value);\r
+    }\r
+\r
+    public void setValue(String key, int[] value) throws OcException {\r
+        this.setValueIntegerArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, int[][] value) throws OcException {\r
+        this.setValueInteger2DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, int[][][] value) throws OcException {\r
+        this.setValueInteger3DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, double[] value) throws OcException {\r
+        this.setValueDoubleArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, double[][] value) throws OcException {\r
+        this.setValueDouble2DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, double[][][] value) throws OcException {\r
+        this.setValueDouble3DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, boolean[] value) throws OcException {\r
+        this.setValueBooleanArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, boolean[][] value) throws OcException {\r
+        this.setValueBoolean2DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, boolean[][][] value) throws OcException {\r
+        this.setValueBoolean3DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, String[] value) throws OcException {\r
+        this.setValueStringArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, String[][] value) throws OcException {\r
+        this.setValueString2DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, String[][][] value) throws OcException {\r
+        this.setValueString3DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, OcRepresentation[] value) throws OcException {\r
+        this.setValueRepresentationArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, OcRepresentation[][] value) throws OcException {\r
+        this.setValueRepresentation2DArray(key, value);\r
+    }\r
+\r
+    public void setValue(String key, OcRepresentation[][][] value) throws OcException {\r
+        this.setValueRepresentation3DArray(key, value);\r
+    }\r
+\r
+    private native void setValueInteger(String key, int value) throws OcException;\r
+\r
+    private native void setValueDouble(String key, double value) throws OcException;\r
+\r
+    private native void setValueBoolean(String key, boolean value) throws OcException;\r
+\r
+    private native void setValueStringN(String key, String value) throws OcException;\r
+\r
+    private native void setValueRepresentation(String key, OcRepresentation value) throws OcException;\r
+\r
+    private native void setValueIntegerArray(String key, int[] value) throws OcException;\r
+\r
+    private native void setValueInteger2DArray(String key, int[][] value) throws OcException;\r
+\r
+    private native void setValueInteger3DArray(String key, int[][][] value) throws OcException;\r
+\r
+    private native void setValueDoubleArray(String key, double[] value) throws OcException;\r
+\r
+    private native void setValueDouble2DArray(String key, double[][] value) throws OcException;\r
+\r
+    private native void setValueDouble3DArray(String key, double[][][] value) throws OcException;\r
+\r
+    private native void setValueBooleanArray(String key, boolean[] value) throws OcException;\r
+\r
+    private native void setValueBoolean2DArray(String key, boolean[][] value) throws OcException;\r
+\r
+    private native void setValueBoolean3DArray(String key, boolean[][][] value) throws OcException;\r
+\r
+    private native void setValueStringArray(String key, String[] value) throws OcException;\r
+\r
+    private native void setValueString2DArray(String key, String[][] value) throws OcException;\r
+\r
+    private native void setValueString3DArray(String key, String[][][] value) throws OcException;\r
+\r
+    private native void setValueRepresentationArray(String key, OcRepresentation[] value) throws OcException;\r
+\r
+    private native void setValueRepresentation2DArray(String key, OcRepresentation[][] value) throws OcException;\r
+\r
+    private native void setValueRepresentation3DArray(String key, OcRepresentation[][][] value) throws OcException;\r
+\r
+    /**\r
+     * @deprecated use {@link #getValue(String key)} instead.\r
+     */\r
+    @Deprecated\r
+    public int getValueInt(String key) {\r
+        int value = 0;\r
+        try {\r
+            value = this.getValue(key);\r
+        } catch (OcException e) {\r
+            //simply catching here for the deprecated APIs, so the older usages don't have to handle\r
+            //it in the code\r
+        }\r
+        return value;\r
+    }\r
+\r
+    /**\r
+     * @deprecated use {@link #getValue(String key)} instead.\r
+     */\r
+    @Deprecated\r
+    public boolean getValueBool(String key) {\r
+        boolean value = false;\r
+        try {\r
+            value = this.getValue(key);\r
+        } catch (OcException e) {\r
+            //simply catching here for the deprecated APIs, so the older usages don't have to handle\r
+            //it in the code\r
+        }\r
+        return value;\r
+    }\r
+\r
+    /**\r
+     * @deprecated use {@link #getValue(String key)} instead.\r
+     */\r
+    @Deprecated\r
+    public String getValueString(String key) {\r
+        String value = "";\r
+        try {\r
+            value = this.getValue(key);\r
+        } catch (OcException e) {\r
+            //simply catching here for the deprecated APIs, so the older usages don't have to handle\r
+            //it in the code\r
+        }\r
+        return value;\r
+    }\r
+\r
+    /**\r
+     * @deprecated use {@link #setValue(String key, int value)} instead.\r
+     */\r
+    @Deprecated\r
+    public void setValueInt(String key, int value) {\r
+        try {\r
+            this.setValue(key, value);\r
+        } catch (OcException e) {\r
+            //simply catching here for the deprecated APIs, so the older usages don't have to handle\r
+            //it in the code\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @deprecated use {@link #setValue(String key, boolean value)} instead.\r
+     */\r
+    @Deprecated\r
+    public void setValueBool(String key, boolean value) {\r
+        try {\r
+            this.setValue(key, value);\r
+        } catch (OcException e) {\r
+            //simply catching here for the deprecated APIs, so the older usages don't have to handle\r
+            //it in the code\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @deprecated use {@link #setValue(String key, String value)} instead.\r
+     */\r
+    @Deprecated\r
+    public void setValueString(String key, String value) {\r
+        try {\r
+            this.setValue(key, value);\r
+        } catch (OcException e) {\r
+            //simply catching here for the deprecated APIs, so the older usages don't have to handle\r
+            //it in the code\r
+        }\r
+    }\r
+\r
+    public native String getJSONRepresentation();\r
+\r
+    public native void addChild(OcRepresentation representation);\r
+\r
+    public native void clearChildren();\r
+\r
+    public List<OcRepresentation> getChildren() {\r
+        return Arrays.asList(\r
+                getChildrenArray());\r
+    }\r
+\r
+    private native OcRepresentation[] getChildrenArray();\r
+\r
+    public native String getUri();\r
+\r
+    public native void setUri(String uri);\r
+\r
+    /**\r
+     * Method to get the list of resource types\r
+     *\r
+     * @return List of resource types\r
+     */\r
+    public native List<String> getResourceTypes();\r
+\r
+    /**\r
+     * Method to set the list of resource types\r
+     *\r
+     * @param resourceTypeList list of resources\r
+     */\r
+    public void setResourceTypes(List<String> resourceTypeList) {\r
+        if (null == resourceTypeList) {\r
+            throw new InvalidParameterException("resourceTypeList cannot be null");\r
+        }\r
+\r
+        this.setResourceTypeArray(\r
+                resourceTypeList.toArray(\r
+                        new String[resourceTypeList.size()]));\r
+    }\r
+\r
+    private native void setResourceTypeArray(String[] resourceTypeArray);\r
+\r
+    /**\r
+     * Method to get the list of resource interfaces\r
+     *\r
+     * @return List of resource interface\r
+     */\r
+    public native List<String> getResourceInterfaces();\r
+\r
+    /**\r
+     * Method to set the list of resource interfaces\r
+     *\r
+     * @param resourceInterfaceList list of interfaces\r
+     */\r
+    public void setResourceInterfaces(List<String> resourceInterfaceList) {\r
+        if (null == resourceInterfaceList) {\r
+            throw new InvalidParameterException("resourceInterfaceList cannot be null");\r
+        }\r
+\r
+        this.setResourceInterfaceArray(\r
+                resourceInterfaceList.toArray(\r
+                        new String[resourceInterfaceList.size()]));\r
+    }\r
+\r
+    private native void setResourceInterfaceArray(String[] resourceInterfaceArray);\r
+\r
+    public native boolean isEmpty();\r
+\r
+    public native int size();\r
+\r
+    public native boolean remove(String key);\r
+\r
+    public native boolean hasAttribute(String key);\r
+\r
+    public native void setNull(String key);\r
+\r
+    public native boolean isNull(String key);\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose(this.mNativeNeedsDelete);\r
+    }\r
+\r
+    private native void create();\r
+\r
+    private native void dispose(boolean needsDelete);\r
+\r
+    private long mNativeHandle;\r
+    private boolean mNativeNeedsDelete;\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcRequestHandle.java b/android/android_api/base/src/main/java/org/iotivity/base/OcRequestHandle.java
new file mode 100644 (file)
index 0000000..73cd14b
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public class OcRequestHandle {\r
+\r
+    private OcRequestHandle(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+    }\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose();\r
+    }\r
+\r
+    private native void dispose();\r
+\r
+    private long mNativeHandle;\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcResource.java b/android/android_api/base/src/main/java/org/iotivity/base/OcResource.java
new file mode 100644 (file)
index 0000000..b3f4b08
--- /dev/null
@@ -0,0 +1,575 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+/**\r
+ * OcResource represents an OC resource. A resource could be a light controller, temperature sensor,\r
+ * smoke detector, etc. A resource comes with a well-defined contract or interface onto which you\r
+ * can perform different operations, such as turning on the light, getting the current temperature\r
+ * or subscribing for event notifications from the smoke detector. A resource can be composed of\r
+ * one or more resources.\r
+ */\r
+public class OcResource {\r
+\r
+    private OcResource(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+    }\r
+\r
+    /**\r
+     * Method to get the attributes of a resource.\r
+     *\r
+     * @param queryParamsMap map which can have the query parameter name and value\r
+     * @param onGetListener  The event handler will be invoked with a map of attribute name and\r
+     *                       values. The event handler will also have the result from this Get\r
+     *                       operation This will have error codes\r
+     * @throws OcException\r
+     */\r
+    public native void get(Map<String, String> queryParamsMap,\r
+                           OnGetListener onGetListener) throws OcException;\r
+\r
+    /**\r
+     * Method to get the attributes of a resource.\r
+     *\r
+     * @param queryParamsMap   map which can have the query parameter name and value\r
+     * @param onGetListener    The event handler will be invoked with a map of attribute name and\r
+     *                         values. The event handler will also have the result from this Get\r
+     *                         operation This will have error codes\r
+     * @param qualityOfService the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void get(Map<String, String> queryParamsMap,\r
+                    OnGetListener onGetListener,\r
+                    QualityOfService qualityOfService) throws OcException {\r
+        this.get1(queryParamsMap, onGetListener, qualityOfService.getValue());\r
+    }\r
+\r
+    private native void get1(Map<String, String> queryParamsMap,\r
+                             OnGetListener onGetListener,\r
+                             int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to get the attributes of a resource.\r
+     *\r
+     * @param resourceType      resourceType of the resource to operate on\r
+     * @param resourceInterface interface type of the resource to operate on\r
+     * @param queryParamsMap    map which can have the query parameter name and value\r
+     * @param onGetListener     The event handler will be invoked with a map of attribute name and\r
+     *                          values. The event handler will also have the result from this Get\r
+     *                          operation This will have error codes\r
+     * @throws OcException\r
+     */\r
+    public void get(String resourceType,\r
+                    String resourceInterface,\r
+                    Map<String, String> queryParamsMap,\r
+                    OnGetListener onGetListener) throws OcException {\r
+        this.get2(\r
+                resourceType,\r
+                resourceInterface,\r
+                queryParamsMap,\r
+                onGetListener);\r
+    }\r
+\r
+    private native void get2(String resourceType,\r
+                             String resourceInterface,\r
+                             Map<String, String> queryParamsMap,\r
+                             OnGetListener onGetListener) throws OcException;\r
+\r
+    /**\r
+     * Method to get the attributes of a resource.\r
+     *\r
+     * @param resourceType      resourceType of the resource to operate on\r
+     * @param resourceInterface interface type of the resource to operate on\r
+     * @param queryParamsMap    map which can have the query parameter name and value\r
+     * @param onGetListener     The event handler will be invoked with a map of attribute name and\r
+     *                          values. The event handler will also have the result from this Get\r
+     *                          operation This will have error codes\r
+     * @param qualityOfService  the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void get(String resourceType,\r
+                    String resourceInterface,\r
+                    Map<String, String> queryParamsMap,\r
+                    OnGetListener onGetListener,\r
+                    QualityOfService qualityOfService) throws OcException {\r
+        this.get3(\r
+                resourceType,\r
+                resourceInterface,\r
+                queryParamsMap,\r
+                onGetListener,\r
+                qualityOfService.getValue());\r
+    }\r
+\r
+    private native void get3(String resourceType,\r
+                             String resourceInterface,\r
+                             Map<String, String> queryParamsMap,\r
+                             OnGetListener onGetListener,\r
+                             int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to set the representation of a resource (via PUT)\r
+     *\r
+     * @param representation representation of the resource\r
+     * @param queryParamsMap Map which can have the query parameter name and value\r
+     * @param onPutListener  event handler The event handler will be invoked with a map of attribute\r
+     *                       name and values.\r
+     * @throws OcException\r
+     */\r
+    public native void put(OcRepresentation representation,\r
+                           Map<String, String> queryParamsMap,\r
+                           OnPutListener onPutListener) throws OcException;\r
+\r
+    /**\r
+     * Method to set the representation of a resource (via PUT)\r
+     *\r
+     * @param ocRepresentation representation of the resource\r
+     * @param queryParamsMap   Map which can have the query parameter name and value\r
+     * @param onPutListener    event handler The event handler will be invoked with a map of\r
+     *                         attribute name and values.\r
+     * @param qualityOfService the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void put(OcRepresentation ocRepresentation,\r
+                    Map<String, String> queryParamsMap,\r
+                    OnPutListener onPutListener,\r
+                    QualityOfService qualityOfService) throws OcException {\r
+        this.put1(\r
+                ocRepresentation,\r
+                queryParamsMap,\r
+                onPutListener,\r
+                qualityOfService.getValue());\r
+    }\r
+\r
+    private native void put1(OcRepresentation ocRepresentation,\r
+                             Map<String, String> queryParamsMap,\r
+                             OnPutListener onPutListener,\r
+                             int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to set the representation of a resource (via PUT)\r
+     *\r
+     * @param resourceType      resource type of the resource to operate on\r
+     * @param resourceInterface interface type of the resource to operate on\r
+     * @param ocRepresentation  representation of the resource\r
+     * @param queryParamsMap    Map which can have the query parameter name and value\r
+     * @param onPutListener     event handler The event handler will be invoked with a map of\r
+     *                          attribute name and values.\r
+     * @throws OcException\r
+     */\r
+    public void put(String resourceType,\r
+                    String resourceInterface,\r
+                    OcRepresentation ocRepresentation,\r
+                    Map<String, String> queryParamsMap,\r
+                    OnPutListener onPutListener) throws OcException {\r
+        this.put2(\r
+                resourceType,\r
+                resourceInterface,\r
+                ocRepresentation,\r
+                queryParamsMap,\r
+                onPutListener);\r
+    }\r
+\r
+    private native void put2(String resourceType,\r
+                             String resourceInterface,\r
+                             OcRepresentation ocRepresentation,\r
+                             Map<String, String> queryParamsMap,\r
+                             OnPutListener onPutListener) throws OcException;\r
+\r
+    /**\r
+     * Method to set the representation of a resource (via PUT)\r
+     *\r
+     * @param resourceType      resource type of the resource to operate on\r
+     * @param resourceInterface interface type of the resource to operate on\r
+     * @param ocRepresentation  representation of the resource\r
+     * @param queryParamsMap    Map which can have the query parameter name and value\r
+     * @param onPutListener     event handler The event handler will be invoked with a map of\r
+     *                          attribute name and values.\r
+     * @param qualityOfService  the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void put(String resourceType,\r
+                    String resourceInterface,\r
+                    OcRepresentation ocRepresentation,\r
+                    Map<String, String> queryParamsMap,\r
+                    OnPutListener onPutListener,\r
+                    QualityOfService qualityOfService) throws OcException {\r
+        this.put3(\r
+                resourceType,\r
+                resourceInterface,\r
+                ocRepresentation,\r
+                queryParamsMap,\r
+                onPutListener,\r
+                qualityOfService.getValue());\r
+    }\r
+\r
+    private native void put3(String resourceType,\r
+                             String resourceInterface,\r
+                             OcRepresentation ocRepresentation,\r
+                             Map<String, String> queryParamsMap,\r
+                             OnPutListener onPutListener,\r
+                             int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to POST on a resource\r
+     *\r
+     * @param ocRepresentation representation of the resource\r
+     * @param queryParamsMap   Map which can have the query parameter name and value\r
+     * @param onPostListener   event handler The event handler will be invoked with a map of\r
+     *                         attribute name and values.\r
+     * @throws OcException\r
+     */\r
+    public native void post(OcRepresentation ocRepresentation,\r
+                            Map<String, String> queryParamsMap,\r
+                            OnPostListener onPostListener) throws OcException;\r
+\r
+    /**\r
+     * Method to POST on a resource\r
+     *\r
+     * @param ocRepresentation representation of the resource\r
+     * @param queryParamsMap   Map which can have the query parameter name and value\r
+     * @param onPostListener   event handler The event handler will be invoked with a map of\r
+     *                         attribute name and values.\r
+     * @param qualityOfService the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void post(OcRepresentation ocRepresentation,\r
+                     Map<String, String> queryParamsMap,\r
+                     OnPostListener onPostListener,\r
+                     QualityOfService qualityOfService) throws OcException {\r
+        this.post1(\r
+                ocRepresentation,\r
+                queryParamsMap,\r
+                onPostListener,\r
+                qualityOfService.getValue());\r
+    }\r
+\r
+    private native void post1(OcRepresentation ocRepresentation,\r
+                              Map<String, String> queryParamsMap,\r
+                              OnPostListener onPostListener,\r
+                              int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to POST on a resource\r
+     *\r
+     * @param resourceType      resource type of the resource to operate on\r
+     * @param resourceInterface interface type of the resource to operate on\r
+     * @param ocRepresentation  representation of the resource\r
+     * @param queryParamsMap    Map which can have the query parameter name and value\r
+     * @param onPostListener    event handler The event handler will be invoked with a map of\r
+     *                          attribute name and values.\r
+     * @throws OcException\r
+     */\r
+    public void post(String resourceType,\r
+                     String resourceInterface,\r
+                     OcRepresentation ocRepresentation,\r
+                     Map<String, String> queryParamsMap,\r
+                     OnPostListener onPostListener) throws OcException {\r
+        this.post2(\r
+                resourceType,\r
+                resourceInterface,\r
+                ocRepresentation,\r
+                queryParamsMap,\r
+                onPostListener);\r
+    }\r
+\r
+    private native void post2(String resourceType,\r
+                              String resourceInterface,\r
+                              OcRepresentation ocRepresentation,\r
+                              Map<String, String> queryParamsMap,\r
+                              OnPostListener onPostListener) throws OcException;\r
+\r
+    /**\r
+     * Method to POST on a resource\r
+     *\r
+     * @param resourceType      resource type of the resource to operate on\r
+     * @param resourceInterface interface type of the resource to operate on\r
+     * @param ocRepresentation  representation of the resource\r
+     * @param queryParamsMap    Map which can have the query parameter name and value\r
+     * @param onPostListener    event handler The event handler will be invoked with a map of\r
+     *                          attribute name and values.\r
+     * @param qualityOfService  the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void post(String resourceType,\r
+                     String resourceInterface,\r
+                     OcRepresentation ocRepresentation,\r
+                     Map<String, String> queryParamsMap,\r
+                     OnPostListener onPostListener,\r
+                     QualityOfService qualityOfService) throws OcException {\r
+        this.post3(\r
+                resourceType,\r
+                resourceInterface,\r
+                ocRepresentation,\r
+                queryParamsMap,\r
+                onPostListener,\r
+                qualityOfService.getValue());\r
+    }\r
+\r
+    private native void post3(String resourceType,\r
+                              String resourceInterface,\r
+                              OcRepresentation ocRepresentation,\r
+                              Map<String, String> queryParamsMap,\r
+                              OnPostListener onPostListener,\r
+                              int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to perform DELETE operation\r
+     *\r
+     * @param onDeleteListener event handler The event handler will have headerOptionList\r
+     */\r
+    public native void deleteResource(OnDeleteListener onDeleteListener) throws OcException;\r
+\r
+    /**\r
+     * Method to perform DELETE operation\r
+     *\r
+     * @param onDeleteListener event handler The event handler will have headerOptionList\r
+     * @param qualityOfService the quality of communication\r
+     */\r
+    public void deleteResource(OnDeleteListener onDeleteListener,\r
+                               QualityOfService qualityOfService) throws OcException {\r
+        this.deleteResource1(onDeleteListener,\r
+                qualityOfService.getValue());\r
+    }\r
+\r
+    private native void deleteResource1(OnDeleteListener onDeleteListener,\r
+                                        int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to set observation on the resource\r
+     *\r
+     * @param observeType       allows the client to specify how it wants to observe\r
+     * @param queryParamsMap    map which can have the query parameter name and value\r
+     * @param onObserveListener event handler The handler method will be invoked with a map\r
+     *                          of attribute name and values.\r
+     * @throws OcException\r
+     */\r
+    public void observe(ObserveType observeType,\r
+                        Map<String, String> queryParamsMap,\r
+                        OnObserveListener onObserveListener) throws OcException {\r
+        this.observe(\r
+                observeType.getValue(),\r
+                queryParamsMap,\r
+                onObserveListener);\r
+    }\r
+\r
+    private synchronized native void observe(int observeType,\r
+                                             Map<String, String> queryParamsMap,\r
+                                             OnObserveListener onObserveListener) throws OcException;\r
+\r
+    /**\r
+     * Method to set observation on the resource\r
+     *\r
+     * @param observeType       allows the client to specify how it wants to observe\r
+     * @param queryParamsMap    map which can have the query parameter name and value\r
+     * @param onObserveListener event handler The handler method will be invoked with a map\r
+     *                          of attribute name and values.\r
+     * @param qualityOfService  the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void observe(ObserveType observeType,\r
+                        Map<String, String> queryParamsMap,\r
+                        OnObserveListener onObserveListener,\r
+                        QualityOfService qualityOfService) throws OcException {\r
+        this.observe1(\r
+                observeType.getValue(),\r
+                queryParamsMap,\r
+                onObserveListener,\r
+                qualityOfService.getValue());\r
+    }\r
+\r
+    private synchronized native void observe1(int observeType,\r
+                                              Map<String, String> queryParamsMap,\r
+                                              OnObserveListener onObserveListener,\r
+                                              int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to cancel the observation on the resource\r
+     *\r
+     * @throws OcException\r
+     */\r
+    public native void cancelObserve() throws OcException;\r
+\r
+    /**\r
+     * Method to cancel the observation on the resource\r
+     *\r
+     * @param qualityOfService the quality of communication\r
+     * @throws OcException\r
+     */\r
+    public void cancelObserve(QualityOfService qualityOfService) throws OcException {\r
+        this.cancelObserve1(qualityOfService.getValue());\r
+    }\r
+\r
+    private native void cancelObserve1(int qualityOfService) throws OcException;\r
+\r
+    /**\r
+     * Method to set header options\r
+     *\r
+     * @param headerOptionList List<OcHeaderOption> where header information(header optionID and\r
+     *                         optionData is passed\r
+     */\r
+    public void setHeaderOptions(List<OcHeaderOption> headerOptionList) {\r
+        this.setHeaderOptions(headerOptionList.toArray(\r
+                        new OcHeaderOption[headerOptionList.size()])\r
+        );\r
+    }\r
+\r
+    private native void setHeaderOptions(OcHeaderOption[] headerOptionList);\r
+\r
+    /**\r
+     * Method to unset header options\r
+     */\r
+    public native void unsetHeaderOptions();\r
+\r
+    /**\r
+     * Method to get the host address of this resource\r
+     *\r
+     * @return host address NOTE: This might or might not be exposed in future due to\r
+     * security concerns\r
+     */\r
+    public native String getHost();\r
+\r
+    /**\r
+     * Method to get the URI for this resource\r
+     *\r
+     * @return resource URI\r
+     */\r
+    public native String getUri();\r
+\r
+    /**\r
+     * Method to get the connectivity type of this resource\r
+     *\r
+     * @return OcConnectivityType connectivity type\r
+     */\r
+    public OcConnectivityType getConnectivityType() {\r
+        return OcConnectivityType.get(\r
+                this.getConnectivityTypeN()\r
+        );\r
+    }\r
+\r
+    private native int getConnectivityTypeN();\r
+\r
+    /**\r
+     * Method to provide ability to check if this resource is observable or not\r
+     *\r
+     * @return true indicates resource is observable; false indicates resource is not observable\r
+     */\r
+    public native boolean isObservable();\r
+\r
+    /**\r
+     * Method to get the list of resource types\r
+     *\r
+     * @return List of resource types\r
+     */\r
+    public native List<String> getResourceTypes();\r
+\r
+    /**\r
+     * Method to get the list of resource interfaces\r
+     *\r
+     * @return List of resource interface\r
+     */\r
+    public native List<String> getResourceInterfaces();\r
+\r
+    /**\r
+     * Method to get a unique identifier for this resource across network interfaces.  This will\r
+     * be guaranteed unique for every resource-per-server independent of how this was discovered.\r
+     *\r
+     * @return OcResourceIdentifier object, which can be used for all comparison and hashing\r
+     */\r
+    public native OcResourceIdentifier getUniqueIdentifier();\r
+\r
+    /**\r
+     * Method to get a string representation of the resource's server ID.\r
+     * * This is unique per- server independent on how it was discovered.\r
+     *\r
+     * @return server ID\r
+     */\r
+    public native String getServerId();\r
+\r
+    /**\r
+     * An OnGetListener can be registered via the resource get call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnGetListener {\r
+        public void onGetCompleted(List<OcHeaderOption> headerOptionList,\r
+                                   OcRepresentation ocRepresentation);\r
+\r
+        public void onGetFailed(Throwable ex);\r
+    }\r
+\r
+    /**\r
+     * An OnPutListener can be registered via the resource put call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnPutListener {\r
+        public void onPutCompleted(List<OcHeaderOption> headerOptionList,\r
+                                   OcRepresentation ocRepresentation);\r
+\r
+        public void onPutFailed(Throwable ex);\r
+    }\r
+\r
+    /**\r
+     * An OnPostListener can be registered via the resource post call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnPostListener {\r
+        public void onPostCompleted(List<OcHeaderOption> headerOptionList,\r
+                                    OcRepresentation ocRepresentation);\r
+\r
+        public void onPostFailed(Throwable ex);\r
+    }\r
+\r
+    /**\r
+     * An OnDeleteListener can be registered via the resource delete call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnDeleteListener {\r
+        public void onDeleteCompleted(List<OcHeaderOption> headerOptionList);\r
+\r
+        public void onDeleteFailed(Throwable ex);\r
+    }\r
+\r
+    /**\r
+     * An OnObserveListener can be registered via the resource observe call.\r
+     * Event listeners are notified asynchronously\r
+     */\r
+    public interface OnObserveListener {\r
+        public void onObserveCompleted(List<OcHeaderOption> headerOptionList,\r
+                                       OcRepresentation ocRepresentation,\r
+                                       int sequenceNumber);\r
+\r
+        public void onObserveFailed(Throwable ex);\r
+    }\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose();\r
+    }\r
+\r
+    private native void dispose();\r
+\r
+    private long mNativeHandle;\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcResourceHandle.java b/android/android_api/base/src/main/java/org/iotivity/base/OcResourceHandle.java
new file mode 100644 (file)
index 0000000..3bab82f
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public class OcResourceHandle {\r
+\r
+    private OcResourceHandle(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+    }\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose();\r
+    }\r
+\r
+    private native void dispose();\r
+\r
+    private long mNativeHandle;\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcResourceIdentifier.java b/android/android_api/base/src/main/java/org/iotivity/base/OcResourceIdentifier.java
new file mode 100644 (file)
index 0000000..a1de037
--- /dev/null
@@ -0,0 +1,51 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public class OcResourceIdentifier {\r
+    private OcResourceIdentifier(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+    }\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose();\r
+    }\r
+\r
+    @Override\r
+    public boolean equals(Object obj) {\r
+        if (!(obj instanceof OcResourceIdentifier)) {\r
+            return false;\r
+        }\r
+        OcResourceIdentifier other = (OcResourceIdentifier) obj;\r
+        return equalsN(other);\r
+    }\r
+\r
+    private native boolean equalsN(OcResourceIdentifier other);\r
+\r
+    private native void dispose();\r
+\r
+    private long mNativeHandle;\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcResourceRequest.java b/android/android_api/base/src/main/java/org/iotivity/base/OcResourceRequest.java
new file mode 100644 (file)
index 0000000..5a24b02
--- /dev/null
@@ -0,0 +1,135 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.util.EnumSet;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+/**\r
+ * OcResourceRequest provides APIs to extract details from a request\r
+ */\r
+public class OcResourceRequest {\r
+\r
+    private OcResourceRequest(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+    }\r
+\r
+    /**\r
+     * Retrieves the type of request for the entity handler function to operate\r
+     *\r
+     * @return request type. This could be 'GET'/'PUT'/'POST'/'DELETE'\r
+     */\r
+    public RequestType getRequestType() {\r
+        return RequestType.get(getRequestTypeNative());\r
+    }\r
+\r
+    private native String getRequestTypeNative();\r
+\r
+    /**\r
+     * Retrieves the query parameters from the request\r
+     *\r
+     * @return parameters in the request\r
+     */\r
+    public native Map<String, String> getQueryParameters();\r
+\r
+    /**\r
+     * Retrieves the request handler flag set. This can be INIT flag and/or REQUEST flag and/or\r
+     * OBSERVE flag.\r
+     * NOTE:\r
+     * INIT indicates that the vendor's entity handler should go and perform\r
+     * initialization operations\r
+     * REQUEST indicates that it is a request of certain type (GET/PUT/POST/DELETE) and entity\r
+     * handler needs to perform corresponding operations\r
+     * OBSERVE indicates that the request is of type Observe and entity handler needs to perform\r
+     * corresponding operations\r
+     *\r
+     * @return Set of handler flags\r
+     */\r
+    public EnumSet<RequestHandlerFlag> getRequestHandlerFlagSet() {\r
+        return RequestHandlerFlag.convertToEnumSet(getRequestHandlerFlagNative());\r
+    }\r
+\r
+    private native int getRequestHandlerFlagNative();\r
+\r
+    /**\r
+     * Provides the entire resource attribute representation\r
+     *\r
+     * @return OcRepresentation object containing the name value pairs representing\r
+     * the resource's attributes\r
+     */\r
+    public native OcRepresentation getResourceRepresentation();\r
+\r
+    /**\r
+     * Object provides observation information\r
+     *\r
+     * @return observation information\r
+     */\r
+    public native ObservationInfo getObservationInfo();\r
+\r
+    /**\r
+     * Specifies the resource uri\r
+     *\r
+     * @param resourceUri resource uri\r
+     */\r
+    public native void setResourceUri(String resourceUri);\r
+\r
+    /**\r
+     * Gets the resource URI\r
+     *\r
+     * @return resource URI\r
+     */\r
+    public native String getResourceUri();\r
+\r
+    /**\r
+     * This API retrieves a list of headerOptions which was sent from a client\r
+     *\r
+     * @return List of header options\r
+     */\r
+    public native List<OcHeaderOption> getHeaderOptions();\r
+\r
+    /**\r
+     * This API retrieves the request handle\r
+     *\r
+     * @return request handle\r
+     */\r
+    public native OcRequestHandle getRequestHandle();\r
+\r
+    /**\r
+     * This API retrieves the resource handle\r
+     *\r
+     * @return resource handle\r
+     */\r
+    public native OcResourceHandle getResourceHandle();\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose();\r
+    }\r
+\r
+    private native void dispose();\r
+\r
+    private long mNativeHandle;\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcResourceResponse.java b/android/android_api/base/src/main/java/org/iotivity/base/OcResourceResponse.java
new file mode 100644 (file)
index 0000000..263de42
--- /dev/null
@@ -0,0 +1,139 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.util.List;\r
+\r
+/**\r
+ * OcResourceResponse provides APIs to set the response details\r
+ */\r
+public class OcResourceResponse {\r
+\r
+    static {\r
+        System.loadLibrary("oc");\r
+        System.loadLibrary("ocstack-jni");\r
+    }\r
+\r
+    public OcResourceResponse() {\r
+        super();\r
+\r
+        create();\r
+    }\r
+\r
+    private OcResourceResponse(long nativeHandle) {\r
+        this.mNativeHandle = nativeHandle;\r
+    }\r
+\r
+    /**\r
+     * This API sets the error code for this response\r
+     *\r
+     * @param eCode error code to set\r
+     */\r
+    public native void setErrorCode(int eCode);\r
+\r
+    /**\r
+     * Gets new resource uri\r
+     *\r
+     * @return new resource uri\r
+     */\r
+    public native String getNewResourceUri();\r
+\r
+    /**\r
+     * Sets new resource uri\r
+     *\r
+     * @param newResourceUri new resource uri\r
+     */\r
+    public native void setNewResourceUri(String newResourceUri);\r
+\r
+    /**\r
+     * This API allows to set headerOptions in the response\r
+     *\r
+     * @param headerOptionList List of HeaderOption entries\r
+     */\r
+    public void setHeaderOptions(List<OcHeaderOption> headerOptionList) {\r
+        this.setHeaderOptions(headerOptionList.toArray(\r
+                        new OcHeaderOption[headerOptionList.size()])\r
+        );\r
+    }\r
+\r
+    private native void setHeaderOptions(OcHeaderOption[] headerOptionList);\r
+\r
+    /**\r
+     * This API allows to set request handle\r
+     *\r
+     * @param ocRequestHandle request handle\r
+     */\r
+    public native void setRequestHandle(OcRequestHandle ocRequestHandle);\r
+\r
+    /**\r
+     * This API allows to set the resource handle\r
+     *\r
+     * @param ocResourceHandle resource handle\r
+     */\r
+    public native void setResourceHandle(OcResourceHandle ocResourceHandle);\r
+\r
+    /**\r
+     * This API allows to set the EntityHandler response result\r
+     *\r
+     * @param responseResult OcEntityHandlerResult type to set the result value\r
+     */\r
+    public void setResponseResult(EntityHandlerResult responseResult) {\r
+        this.setResponseResult(responseResult.getValue());\r
+    }\r
+\r
+    private native void setResponseResult(int responseResult);\r
+\r
+    /**\r
+     * API to set the entire resource attribute representation\r
+     *\r
+     * @param ocRepresentation the name value pairs representing the resource's attributes\r
+     * @param interfaceStr     specifies the interface\r
+     */\r
+    public native void setResourceRepresentation(OcRepresentation ocRepresentation,\r
+                                                 String interfaceStr);\r
+\r
+    /**\r
+     * API to set the entire resource attribute representation\r
+     *\r
+     * @param representation object containing the name value pairs representing the\r
+     *                       resource's attributes\r
+     */\r
+    public void setResourceRepresentation(OcRepresentation representation) {\r
+        this.setResourceRepresentation1(representation);\r
+    }\r
+\r
+    private native void setResourceRepresentation1(OcRepresentation representation);\r
+\r
+    @Override\r
+    protected void finalize() throws Throwable {\r
+        super.finalize();\r
+\r
+        dispose();\r
+    }\r
+\r
+    private native void create();\r
+\r
+    private native void dispose();\r
+\r
+    private long mNativeHandle;\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/PlatformConfig.java b/android/android_api/base/src/main/java/org/iotivity/base/PlatformConfig.java
new file mode 100644 (file)
index 0000000..7fd9ac0
--- /dev/null
@@ -0,0 +1,88 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import android.content.Context;\r
+\r
+/**\r
+ * Data structure to provide the configuration.\r
+ */\r
+public class PlatformConfig {\r
+\r
+    private Context mContext;\r
+    private ServiceType mServiceType;\r
+    private ModeType mModeType;\r
+    private String mIpAddress;\r
+    private int mPort;\r
+    private QualityOfService mQualityOfService;\r
+\r
+    /**\r
+     * @param context          app context\r
+     * @param serviceType      indicate IN_PROC or OUT_OF_PROC\r
+     * @param modeType         indicate whether we want to do server, client or both\r
+     * @param ipAddress        ip address of server\r
+     *                         if you specify 0.0.0.0 : it listens on any interface\r
+     * @param port             port of server\r
+     *                         if you specifiy 0 : next available random port is used\r
+     *                         if you specify 5683 : client discovery can work even if they don't\r
+     *                         specify port\r
+     * @param qualityOfService quality of service\r
+     */\r
+    public PlatformConfig(Context context,\r
+                          ServiceType serviceType,\r
+                          ModeType modeType,\r
+                          String ipAddress,\r
+                          int port,\r
+                          QualityOfService qualityOfService) {\r
+        this.mContext = context;\r
+        this.mServiceType = serviceType;\r
+        this.mModeType = modeType;\r
+        this.mIpAddress = ipAddress;\r
+        this.mPort = port;\r
+        this.mQualityOfService = qualityOfService;\r
+    }\r
+\r
+    public Context getContext() {\r
+        return mContext;\r
+    }\r
+\r
+    public ServiceType getServiceType() {\r
+        return mServiceType;\r
+    }\r
+\r
+    public ModeType getModeType() {\r
+        return mModeType;\r
+    }\r
+\r
+    public String getIpAddress() {\r
+        return mIpAddress;\r
+    }\r
+\r
+    public int getPort() {\r
+        return mPort;\r
+    }\r
+\r
+    public QualityOfService getQualityOfService() {\r
+        return mQualityOfService;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/QualityOfService.java b/android/android_api/base/src/main/java/org/iotivity/base/QualityOfService.java
new file mode 100644 (file)
index 0000000..4c85981
--- /dev/null
@@ -0,0 +1,42 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+/**\r
+ */\r
+public enum QualityOfService {\r
+    LOW(0),\r
+    MEDIUM(1),\r
+    HIGH(2),\r
+    NA(3);\r
+\r
+    private int value;\r
+\r
+    private QualityOfService(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/RequestHandlerFlag.java b/android/android_api/base/src/main/java/org/iotivity/base/RequestHandlerFlag.java
new file mode 100644 (file)
index 0000000..5e1f5ee
--- /dev/null
@@ -0,0 +1,61 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+import java.util.EnumSet;\r
+\r
+public enum RequestHandlerFlag {\r
+    INIT(1 << 0),\r
+    REQUEST(1 << 1),\r
+    OBSERVER(1 << 2),;\r
+\r
+    private int value;\r
+\r
+    private RequestHandlerFlag(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+\r
+    public static EnumSet<RequestHandlerFlag> convertToEnumSet(int value) {\r
+        EnumSet<RequestHandlerFlag> flagSet = null;\r
+\r
+        for (RequestHandlerFlag v : values()) {\r
+            if (0 != (value & v.getValue())) {\r
+                if (flagSet == null) {\r
+                    flagSet = EnumSet.of(v);\r
+                } else {\r
+                    flagSet.add(v);\r
+                }\r
+            }\r
+        }\r
+\r
+        if (null == flagSet || flagSet.isEmpty()) {\r
+            throw new IllegalArgumentException("Unexpected RequestHandlerFlag value");\r
+        }\r
+\r
+        return flagSet;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/RequestType.java b/android/android_api/base/src/main/java/org/iotivity/base/RequestType.java
new file mode 100644 (file)
index 0000000..894429d
--- /dev/null
@@ -0,0 +1,48 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum RequestType {\r
+    GET("GET"),\r
+    PUT("PUT"),\r
+    POST("POST"),\r
+    DELETE("DELETE"),;\r
+    private String value;\r
+\r
+    private RequestType(String value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public String getValue() {\r
+        return this.value;\r
+    }\r
+\r
+    public static RequestType get(String value) {\r
+        for (RequestType v : values()) {\r
+            if (v.getValue().equals(value)) {\r
+                return v;\r
+            }\r
+        }\r
+        throw new IllegalArgumentException("Unexpected RequestType value");\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/ResourceProperty.java b/android/android_api/base/src/main/java/org/iotivity/base/ResourceProperty.java
new file mode 100644 (file)
index 0000000..64345db
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum ResourceProperty {\r
+    ACTIVE(1 << 0),\r
+    DISCOVERABLE(1 << 1),\r
+    OBSERVABLE(1 << 2),\r
+    SLOW(1 << 3),\r
+    SECURE(1 << 4);\r
+\r
+    private int value;\r
+\r
+    private ResourceProperty(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/ServiceType.java b/android/android_api/base/src/main/java/org/iotivity/base/ServiceType.java
new file mode 100644 (file)
index 0000000..6dc65a7
--- /dev/null
@@ -0,0 +1,38 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base;\r
+\r
+public enum ServiceType {\r
+    IN_PROC(0),\r
+    OUT_OF_PROC(1),;\r
+\r
+    private int value;\r
+\r
+    private ServiceType(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+}\r
diff --git a/android/android_api/base/src/main/java/org/iotivity/ca/CaInterface.java b/android/android_api/base/src/main/java/org/iotivity/ca/CaInterface.java
new file mode 100644 (file)
index 0000000..81c457c
--- /dev/null
@@ -0,0 +1,34 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.ca;\r
+\r
+import android.content.Context;\r
+\r
+public class CaInterface {\r
+    static {\r
+        System.loadLibrary("connectivity_abstraction");\r
+        System.loadLibrary("ca-interface");\r
+    }\r
+\r
+    public static native void initialize(Context context);\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java b/android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java
new file mode 100644 (file)
index 0000000..43d0ace
--- /dev/null
@@ -0,0 +1,70 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.ca;\r
+\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.content.IntentFilter;\r
+import android.net.ConnectivityManager;\r
+import android.net.NetworkInfo;\r
+import android.net.wifi.WifiManager;\r
+\r
+public class CaIpInterface {\r
+    private static Context mContext;\r
+\r
+    private CaIpInterface(Context context) {\r
+        mContext = context;\r
+        registerIpStateReceiver();\r
+    }\r
+\r
+    private void registerIpStateReceiver() {\r
+        IntentFilter intentFilter = new IntentFilter();\r
+        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);\r
+        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\r
+\r
+        mContext.registerReceiver(mReceiver, intentFilter);\r
+    }\r
+\r
+    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,\r
+                    WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {\r
+                stateDisabled();\r
+            } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {\r
+                ConnectivityManager manager = (ConnectivityManager)\r
+                        mContext.getSystemService(Context.CONNECTIVITY_SERVICE);\r
+                NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\r
+\r
+                if(nwInfo.isConnected()) {\r
+                    stateEnabled();\r
+                }\r
+            }\r
+        }\r
+    };\r
+\r
+    private native static void stateEnabled();\r
+\r
+    private native static void stateDisabled();\r
+}
\ No newline at end of file
diff --git a/android/android_api/base/src/main/java/org/iotivity/ca/CaWiFiInterface.java b/android/android_api/base/src/main/java/org/iotivity/ca/CaWiFiInterface.java
new file mode 100644 (file)
index 0000000..15cac58
--- /dev/null
@@ -0,0 +1,72 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.ca;\r
+\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.content.IntentFilter;\r
+import android.net.ConnectivityManager;\r
+import android.net.NetworkInfo;\r
+import android.net.wifi.WifiManager;\r
+\r
+public class CaWiFiInterface {\r
+\r
+    private static Context mContext;\r
+\r
+    private CaWiFiInterface(Context context) {\r
+        mContext = context;\r
+        registerWiFiStateReceiver();\r
+    }\r
+\r
+    private void registerWiFiStateReceiver() {\r
+        IntentFilter intentFilter = new IntentFilter();\r
+        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);\r
+        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\r
+\r
+        mContext.registerReceiver(mReceiver, intentFilter);\r
+    }\r
+\r
+    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {\r
+\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,\r
+                    WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {\r
+                CAWiFiStateDisabled();\r
+            } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {\r
+                ConnectivityManager manager = (ConnectivityManager)\r
+                        mContext.getSystemService(Context.CONNECTIVITY_SERVICE);\r
+                NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\r
+\r
+                if (nwInfo.isConnected()) {\r
+                    CAWiFiStateEnabled();\r
+                }\r
+            }\r
+        }\r
+    };\r
+\r
+    private native static void CAWiFiStateEnabled();\r
+\r
+    private native static void CAWiFiStateDisabled();\r
+}
\ No newline at end of file
diff --git a/android/android_api/build.gradle b/android/android_api/build.gradle
new file mode 100755 (executable)
index 0000000..478166f
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2014 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+\r
+buildscript {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+    dependencies {\r
+        classpath 'com.android.tools.build:gradle:1.0.0'\r
+\r
+        // NOTE: Do not place your application dependencies here; they belong\r
+        // in the individual module build.gradle files\r
+    }\r
+}\r
+\r
+allprojects {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+}\r
diff --git a/android/android_api/gradle.properties b/android/android_api/gradle.properties
new file mode 100755 (executable)
index 0000000..42a55d5
--- /dev/null
@@ -0,0 +1,40 @@
+#\r
+# //******************************************************************\r
+# //\r
+# // Copyright 2015 Intel Corporation.\r
+# //\r
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+# //\r
+# // Licensed under the Apache License, Version 2.0 (the "License");\r
+# // you may not use this file except in compliance with the License.\r
+# // You may obtain a copy of the License at\r
+# //\r
+# //      http://www.apache.org/licenses/LICENSE-2.0\r
+# //\r
+# // Unless required by applicable law or agreed to in writing, software\r
+# // distributed under the License is distributed on an "AS IS" BASIS,\r
+# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# // See the License for the specific language governing permissions and\r
+# // limitations under the License.\r
+# //\r
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+#\r
+\r
+# Project-wide Gradle settings.\r
+\r
+# IDE (e.g. Android Studio) users:\r
+# Gradle settings configured through the IDE *will override*\r
+# any settings specified in this file.\r
+\r
+# For more details on how to configure your build environment visit\r
+# http://www.gradle.org/docs/current/userguide/build_environment.html\r
+\r
+# Specifies the JVM arguments used for the daemon process.\r
+# The setting is particularly useful for tweaking memory settings.\r
+# Default value: -Xmx10248m -XX:MaxPermSize=256m\r
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8\r
+\r
+# When configured, Gradle will run in incubating parallel mode.\r
+# This option should only be used with decoupled projects. More details, visit\r
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\r
+# org.gradle.parallel=true\r
diff --git a/android/android_api/gradle/wrapper/gradle-wrapper.jar b/android/android_api/gradle/wrapper/gradle-wrapper.jar
new file mode 100755 (executable)
index 0000000..8c0fb64
Binary files /dev/null and b/android/android_api/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/android/android_api/gradle/wrapper/gradle-wrapper.properties b/android/android_api/gradle/wrapper/gradle-wrapper.properties
new file mode 100755 (executable)
index 0000000..c275376
--- /dev/null
@@ -0,0 +1,28 @@
+#\r
+# //******************************************************************\r
+# //\r
+# // Copyright 2014 Intel Corporation.\r
+# //\r
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+# //\r
+# // Licensed under the Apache License, Version 2.0 (the "License");\r
+# // you may not use this file except in compliance with the License.\r
+# // You may obtain a copy of the License at\r
+# //\r
+# //      http://www.apache.org/licenses/LICENSE-2.0\r
+# //\r
+# // Unless required by applicable law or agreed to in writing, software\r
+# // distributed under the License is distributed on an "AS IS" BASIS,\r
+# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# // See the License for the specific language governing permissions and\r
+# // limitations under the License.\r
+# //\r
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+#\r
+\r
+#Fri Dec 12 12:28:50 PST 2014\r
+distributionBase=GRADLE_USER_HOME\r
+distributionPath=wrapper/dists\r
+zipStoreBase=GRADLE_USER_HOME\r
+zipStorePath=wrapper/dists\r
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip\r
diff --git a/android/android_api/gradlew b/android/android_api/gradlew
new file mode 100755 (executable)
index 0000000..583ae08
--- /dev/null
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash\r
+\r
+##############################################################################\r
+##\r
+##  Gradle start up script for UN*X\r
+##\r
+##############################################################################\r
+\r
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r
+DEFAULT_JVM_OPTS=""\r
+\r
+APP_NAME="Gradle"\r
+APP_BASE_NAME=`basename "$0"`\r
+\r
+# Use the maximum available, or set MAX_FD != -1 to use that value.\r
+MAX_FD="maximum"\r
+\r
+warn ( ) {\r
+    echo "$*"\r
+}\r
+\r
+die ( ) {\r
+    echo\r
+    echo "$*"\r
+    echo\r
+    exit 1\r
+}\r
+\r
+# OS specific support (must be 'true' or 'false').\r
+cygwin=false\r
+msys=false\r
+darwin=false\r
+case "`uname`" in\r
+  CYGWIN* )\r
+    cygwin=true\r
+    ;;\r
+  Darwin* )\r
+    darwin=true\r
+    ;;\r
+  MINGW* )\r
+    msys=true\r
+    ;;\r
+esac\r
+\r
+# For Cygwin, ensure paths are in UNIX format before anything is touched.\r
+if $cygwin ; then\r
+    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`\r
+fi\r
+\r
+# Attempt to set APP_HOME\r
+# Resolve links: $0 may be a link\r
+PRG="$0"\r
+# Need this for relative symlinks.\r
+while [ -h "$PRG" ] ; do\r
+    ls=`ls -ld "$PRG"`\r
+    link=`expr "$ls" : '.*-> \(.*\)$'`\r
+    if expr "$link" : '/.*' > /dev/null; then\r
+        PRG="$link"\r
+    else\r
+        PRG=`dirname "$PRG"`"/$link"\r
+    fi\r
+done\r
+SAVED="`pwd`"\r
+cd "`dirname \"$PRG\"`/" >&-\r
+APP_HOME="`pwd -P`"\r
+cd "$SAVED" >&-\r
+\r
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\r
+\r
+# Determine the Java command to use to start the JVM.\r
+if [ -n "$JAVA_HOME" ] ; then\r
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then\r
+        # IBM's JDK on AIX uses strange locations for the executables\r
+        JAVACMD="$JAVA_HOME/jre/sh/java"\r
+    else\r
+        JAVACMD="$JAVA_HOME/bin/java"\r
+    fi\r
+    if [ ! -x "$JAVACMD" ] ; then\r
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\r
+\r
+Please set the JAVA_HOME variable in your environment to match the\r
+location of your Java installation."\r
+    fi\r
+else\r
+    JAVACMD="java"\r
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r
+\r
+Please set the JAVA_HOME variable in your environment to match the\r
+location of your Java installation."\r
+fi\r
+\r
+# Increase the maximum file descriptors if we can.\r
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then\r
+    MAX_FD_LIMIT=`ulimit -H -n`\r
+    if [ $? -eq 0 ] ; then\r
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then\r
+            MAX_FD="$MAX_FD_LIMIT"\r
+        fi\r
+        ulimit -n $MAX_FD\r
+        if [ $? -ne 0 ] ; then\r
+            warn "Could not set maximum file descriptor limit: $MAX_FD"\r
+        fi\r
+    else\r
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"\r
+    fi\r
+fi\r
+\r
+# For Darwin, add options to specify how the application appears in the dock\r
+if $darwin; then\r
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""\r
+fi\r
+\r
+# For Cygwin, switch paths to Windows format before running java\r
+if $cygwin ; then\r
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`\r
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`\r
+\r
+    # We build the pattern for arguments to be converted via cygpath\r
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\r
+    SEP=""\r
+    for dir in $ROOTDIRSRAW ; do\r
+        ROOTDIRS="$ROOTDIRS$SEP$dir"\r
+        SEP="|"\r
+    done\r
+    OURCYGPATTERN="(^($ROOTDIRS))"\r
+    # Add a user-defined pattern to the cygpath arguments\r
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then\r
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"\r
+    fi\r
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh\r
+    i=0\r
+    for arg in "$@" ; do\r
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`\r
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option\r
+\r
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\r
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`\r
+        else\r
+            eval `echo args$i`="\"$arg\""\r
+        fi\r
+        i=$((i+1))\r
+    done\r
+    case $i in\r
+        (0) set -- ;;\r
+        (1) set -- "$args0" ;;\r
+        (2) set -- "$args0" "$args1" ;;\r
+        (3) set -- "$args0" "$args1" "$args2" ;;\r
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;\r
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;\r
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;\r
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;\r
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;\r
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;\r
+    esac\r
+fi\r
+\r
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\r
+function splitJvmOpts() {\r
+    JVM_OPTS=("$@")\r
+}\r
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\r
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"\r
+\r
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"\r
old mode 100644 (file)
new mode 100755 (executable)
similarity index 100%
rename from android/SimpleClient/gradlew.bat
rename to android/android_api/gradlew.bat
diff --git a/android/android_api/settings.gradle b/android/android_api/settings.gradle
new file mode 100755 (executable)
index 0000000..d1bcc8a
--- /dev/null
@@ -0,0 +1,23 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+include ':base'\r
diff --git a/android/examples/build.gradle b/android/examples/build.gradle
new file mode 100755 (executable)
index 0000000..50e899c
--- /dev/null
@@ -0,0 +1,19 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+\r
+buildscript {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+    dependencies {\r
+        classpath 'com.android.tools.build:gradle:1.0.0'\r
+\r
+        // NOTE: Do not place your application dependencies here; they belong\r
+        // in the individual module build.gradle files\r
+    }\r
+}\r
+\r
+allprojects {\r
+    repositories {\r
+        jcenter()\r
+    }\r
+}\r
diff --git a/android/examples/examples.iml b/android/examples/examples.iml
new file mode 100755 (executable)
index 0000000..8d49284
--- /dev/null
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="java-gradle" name="Java-Gradle">\r
+      <configuration>\r
+        <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="true">\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <excludeFolder url="file://$MODULE_DIR$/.gradle" />\r
+    </content>\r
+    <orderEntry type="inheritedJdk" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/examples/fridgeclient/.gitignore b/android/examples/fridgeclient/.gitignore
new file mode 100644 (file)
index 0000000..3543521
--- /dev/null
@@ -0,0 +1 @@
+/build\r
diff --git a/android/examples/fridgeclient/build.gradle b/android/examples/fridgeclient/build.gradle
new file mode 100755 (executable)
index 0000000..975453f
--- /dev/null
@@ -0,0 +1,26 @@
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion "21.1.2"\r
+\r
+    defaultConfig {\r
+        applicationId "org.iotivity.base.examples.fridgeclient"\r
+        minSdkVersion 19\r
+        targetSdkVersion 21\r
+        versionCode 1\r
+        versionName "1.0"\r
+    }\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+        }\r
+    }\r
+}\r
+\r
+dependencies {\r
+    compile fileTree(dir: 'libs', include: ['*.jar'])\r
+    compile 'com.android.support:appcompat-v7:21.0.3'\r
+    compile project(':message')\r
+}\r
diff --git a/android/examples/fridgeclient/fridgeclient.iml b/android/examples/fridgeclient/fridgeclient.iml
new file mode 100755 (executable)
index 0000000..ea17290
--- /dev/null
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="android-gradle" name="Android-Gradle">\r
+      <configuration>\r
+        <option name="GRADLE_PROJECT_PATH" value=":fridgeclient" />\r
+      </configuration>\r
+    </facet>\r
+    <facet type="android" name="Android">\r
+      <configuration>\r
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
+        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
+        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />\r
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="false">\r
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
+    </content>\r
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+    <orderEntry type="library" exported="" name="iotivity-x86-base-debug-unspecified" level="project" />\r
+    <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
+    <orderEntry type="module" module-name="message" exported="" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/examples/fridgeclient/src/main/AndroidManifest.xml b/android/examples/fridgeclient/src/main/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..d560e70
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools"\r
+    package="org.iotivity.base.examples.fridgeclient" >\r
+    <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>\r
+\r
+    <application\r
+        android:allowBackup="true"\r
+        android:icon="@drawable/ic_launcher"\r
+        android:label="@string/app_name"\r
+        android:theme="@style/AppTheme">\r
+        <activity\r
+            android:name=".FridgeClient"\r
+            android:label="@string/app_name" >\r
+            <intent-filter>\r
+                <action android:name="android.intent.action.MAIN" />\r
+\r
+                <category android:name="android.intent.category.LAUNCHER" />\r
+            </intent-filter>\r
+        </activity>\r
+    </application>\r
+</manifest>\r
diff --git a/android/examples/fridgeclient/src/main/java/org/iotivity/base/examples/fridgeclient/FridgeClient.java b/android/examples/fridgeclient/src/main/java/org/iotivity/base/examples/fridgeclient/FridgeClient.java
new file mode 100644 (file)
index 0000000..a004c87
--- /dev/null
@@ -0,0 +1,362 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.fridgeclient;\r
+\r
+import android.app.Activity;\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.content.IntentFilter;\r
+import android.os.Bundle;\r
+import android.os.Message;\r
+import android.support.v4.content.LocalBroadcastManager;\r
+import android.text.method.ScrollingMovementMethod;\r
+import android.util.Log;\r
+import android.view.Menu;\r
+import android.view.MenuItem;\r
+import android.widget.LinearLayout;\r
+import android.widget.TextView;\r
+\r
+import org.iotivity.base.ErrorCode;\r
+import org.iotivity.base.ModeType;\r
+import org.iotivity.base.OcConnectivityType;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcHeaderOption;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.OcResource;\r
+import org.iotivity.base.PlatformConfig;\r
+import org.iotivity.base.QualityOfService;\r
+import org.iotivity.base.ServiceType;\r
+\r
+import java.util.HashMap;\r
+import java.util.LinkedList;\r
+import java.util.List;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * FridgeClient\r
+ * <p/>\r
+ * FridgeClient is a sample client app which should be started after the fridgeServer is started.\r
+ * It creates DeviceResource, DoorResource, LightResource and performs a get operation on them.\r
+ * This implements IMessageLogger to display messages on the screen\r
+ */\r
+public class FridgeClient extends Activity implements\r
+        OcPlatform.OnResourceFoundListener, IMessageLogger {\r
+    private static String TAG = "FridgeClient: ";\r
+\r
+    private MessageReceiver mMessageReceiver = new MessageReceiver();\r
+    private TextView mEventsTextView;\r
+    private String mDeviceName;\r
+    private int mDeviceCode;\r
+    private List<String> ifaces;\r
+    private final List<OcResource> resourceList = new LinkedList<OcResource>();\r
+\r
+    /**\r
+     * configure OIC platform and call findResource\r
+     */\r
+    private void initOICStack() {\r
+        PlatformConfig cfg = new PlatformConfig(\r
+                this,\r
+                ServiceType.IN_PROC,\r
+                ModeType.CLIENT,\r
+                "0.0.0.0", // bind to all available interfaces\r
+                0,\r
+                QualityOfService.LOW);\r
+\r
+        OcPlatform.Configure(cfg);\r
+        try {\r
+            OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",\r
+                    OcConnectivityType.WIFI, this);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + " init Error. " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * prints out the appropriate messages depending on the device code\r
+     *\r
+     * @param representation representation of the OcResource\r
+     * @param value          clientDeviceCode\r
+     */\r
+    private void getResponse(OcRepresentation representation, int value) {\r
+        switch (value) {\r
+            case 0:\r
+                // Get on device\r
+                try {\r
+                    logMessage(TAG + "Name of device: " +\r
+                            representation.getValue(StringConstants.DEVICE_NAME));\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                break;\r
+            case 1:\r
+                // get on fridge light\r
+                try {\r
+                    boolean lightOn = representation.getValue(StringConstants.ON);\r
+                    logMessage(TAG + "The fridge light is " +\r
+                            (lightOn ? "" : "not " + "on"));\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                break;\r
+            case 2:\r
+            case 3:\r
+                // get on fridge door(s)\r
+                try {\r
+                    boolean doorOpen = representation.getValue(StringConstants.OPEN);\r
+                    logMessage(TAG + "Door is " + (doorOpen ?\r
+                            "open" : "not open") + " and is on the " +\r
+                            representation.getValue(StringConstants.SIDE) + " side");\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                break;\r
+            case 4:\r
+                // get on fridge random door\r
+                try {\r
+                    logMessage("Name of fridge: " +\r
+                            representation.getValue(StringConstants.DEVICE_NAME));\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                break;\r
+            default:\r
+                logMessage("Unexpected State");\r
+                break;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * this method is used to wait for 1 second between calls to different resources.\r
+     * It is added for better readability\r
+     */\r
+    private void doWait() {\r
+        try {\r
+            Thread.sleep(StringConstants.WAIT_TIME);\r
+        } catch (InterruptedException e) {\r
+            logMessage(TAG + "doWait exception: " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    @Override\r
+    /**\r
+     *  callback when a resource is found. This method calls getResponse with the correct code\r
+     */\r
+    synchronized public void onResourceFound(OcResource ocResource) {\r
+        // eventHandler for onGetListener\r
+        resourceList.add(ocResource);\r
+        OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {\r
+            @Override\r
+            public void onGetCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation rep) {\r
+                logMessage(TAG + " Got a response from " + getClientDeviceName());\r
+                getResponse(rep, getClientDeviceCode());\r
+            }\r
+\r
+            @Override\r
+            public void onGetFailed(Throwable throwable) {\r
+                if (throwable instanceof OcException) {\r
+                    OcException ocEx = (OcException) throwable;\r
+                    ErrorCode errCode = ocEx.getErrorCode();\r
+                    //do something based on errorCode\r
+                }\r
+                Log.e(TAG, throwable.toString());\r
+            }\r
+        };\r
+\r
+        if (ocResource.getUri().equals(StringConstants.RESOURCE_URI)) {\r
+            logMessage(TAG + "Discovered a device with \nHost: " + ocResource.getHost() +\r
+                    ", Uri: " + ocResource.getUri());\r
+        }\r
+        List<String> lightTypes = new LinkedList<>();\r
+        lightTypes.add("intel.fridge.light");\r
+        try {\r
+            OcResource light = OcPlatform.constructResourceObject(ocResource.getHost(),\r
+                    StringConstants.LIGHT, OcConnectivityType.WIFI, false, lightTypes, ifaces);\r
+\r
+            List<String> doorTypes = new LinkedList<>();\r
+            doorTypes.add("intel.fridge.door");\r
+            OcResource leftDoor = OcPlatform.constructResourceObject(ocResource.getHost(),\r
+                    StringConstants.LEFT_DOOR, OcConnectivityType.WIFI, false, doorTypes, ifaces);\r
+\r
+            OcResource rightDoor = OcPlatform.constructResourceObject(ocResource.getHost(),\r
+                    StringConstants.RIGHT_DOOR, OcConnectivityType.WIFI, false, doorTypes, ifaces);\r
+\r
+            OcResource randomDoor = OcPlatform.constructResourceObject(ocResource.getHost(),\r
+                    StringConstants.RANDOM_DOOR, OcConnectivityType.WIFI, false, doorTypes, ifaces);\r
+\r
+            List<OcHeaderOption> headerOptions = new LinkedList<>();\r
+            OcHeaderOption apiVersion = new OcHeaderOption(StringConstants.API_VERSION_KEY,\r
+                    StringConstants.API_VERSION);\r
+            OcHeaderOption clientToken = new OcHeaderOption(StringConstants.CLIENT_VERSION_KEY,\r
+                    StringConstants.CLIENT_TOKEN);\r
+            headerOptions.add(apiVersion);\r
+            headerOptions.add(clientToken);\r
+            ocResource.setHeaderOptions(headerOptions);\r
+            /**\r
+             *  wait for 1 second before calling get on different resources.\r
+             *  It is done for better readability.\r
+             *  doWait() is called before each call to get\r
+             */\r
+            doWait();\r
+\r
+            setupClientOptions("Device", 0);\r
+            ocResource.get(new HashMap<String, String>(), onGetListener);\r
+            doWait();\r
+\r
+            setupClientOptions("Fridge Light", 1);\r
+            light.get(new HashMap<String, String>(), onGetListener);\r
+            doWait();\r
+\r
+            setupClientOptions("Left Door", 2);\r
+            leftDoor.get(new HashMap<String, String>(), onGetListener);\r
+            doWait();\r
+\r
+            setupClientOptions("Right Door", 3);\r
+            rightDoor.get(new HashMap<String, String>(), onGetListener);\r
+            doWait();\r
+\r
+            setupClientOptions("Random Door", 4);\r
+            randomDoor.get(new HashMap<String, String>(), onGetListener);\r
+            doWait();\r
+\r
+            resourceList.add(leftDoor);\r
+            leftDoor.deleteResource(new OcResource.OnDeleteListener() {\r
+                @Override\r
+                public void onDeleteCompleted(List<OcHeaderOption> ocHeaderOptions) {\r
+                    logMessage(TAG + "Delete resource successful");\r
+                }\r
+\r
+                @Override\r
+                public void onDeleteFailed(Throwable throwable) {\r
+                    if (throwable instanceof OcException) {\r
+                        OcException ocEx = (OcException) throwable;\r
+                        ErrorCode errCode = ocEx.getErrorCode();\r
+                        //do something based on errorCode\r
+                    }\r
+                    Log.e(TAG, throwable.toString());\r
+                }\r
+            });\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "onResourceFound Error. " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected void onCreate(Bundle savedInstanceState) {\r
+        super.onCreate(savedInstanceState);\r
+        setContentView(R.layout.activity_fridge_client);\r
+        registerReceiver(mMessageReceiver, new IntentFilter(StringConstants.INTENT));\r
+\r
+        mEventsTextView = new TextView(this);\r
+        mEventsTextView.setMovementMethod(new ScrollingMovementMethod());\r
+        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);\r
+        layout.addView(mEventsTextView, new LinearLayout.LayoutParams\r
+                (LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));\r
+        ifaces = new LinkedList<>();\r
+        ifaces.add(StringConstants.RESOURCE_INTERFACE);\r
+        mDeviceCode = -1;\r
+        mDeviceName = "";\r
+\r
+        initOICStack();\r
+    }\r
+\r
+    public class MessageReceiver extends BroadcastReceiver {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            final String message = intent.getStringExtra(StringConstants.MESSAGE);\r
+            logMessage(message);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void logMessage(final String text) {\r
+        if (StringConstants.ENABLE_PRINTING) {\r
+            runOnUiThread(new Runnable() {\r
+                public void run() {\r
+                    final Message msg = new Message();\r
+                    msg.obj = text;\r
+                    mEventsTextView.append("\n");\r
+                    mEventsTextView.append(text);\r
+                }\r
+            });\r
+            Log.i(TAG, text);\r
+        }\r
+    }\r
+\r
+\r
+    private void setupClientOptions(String name, int value) {\r
+        mDeviceName = name;\r
+        mDeviceCode = value;\r
+    }\r
+\r
+    private String getClientDeviceName() {\r
+        return mDeviceName;\r
+    }\r
+\r
+    private int getClientDeviceCode() {\r
+        return mDeviceCode;\r
+    }\r
+\r
+\r
+    //method to print the headerOptions received from the server\r
+    void printHeaderOptions(List<OcHeaderOption> headerOptions) {\r
+        for (OcHeaderOption headerOption : headerOptions) {\r
+            if (StringConstants.API_VERSION_KEY == headerOption.getOptionId()) {\r
+                logMessage(TAG + "Server API version in GET response: " +\r
+                        headerOption.getOptionData());\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public boolean onCreateOptionsMenu(Menu menu) {\r
+        getMenuInflater().inflate(R.menu.menu_fridge_client, menu);\r
+        return true;\r
+    }\r
+\r
+    @Override\r
+    public boolean onOptionsItemSelected(MenuItem item) {\r
+        int id = item.getItemId();\r
+        if (id == R.id.action_settings) {\r
+            return true;\r
+        }\r
+        return super.onOptionsItemSelected(item);\r
+    }\r
+\r
+    @Override\r
+    public void onDestroy() {\r
+        super.onDestroy();\r
+        onStop();\r
+    }\r
+\r
+    @Override\r
+    protected void onStop() {\r
+        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);\r
+        super.onStop();\r
+    }\r
+}\r
diff --git a/android/examples/fridgeclient/src/main/java/org/iotivity/base/examples/fridgeclient/StringConstants.java b/android/examples/fridgeclient/src/main/java/org/iotivity/base/examples/fridgeclient/StringConstants.java
new file mode 100644 (file)
index 0000000..da88e4d
--- /dev/null
@@ -0,0 +1,33 @@
+package org.iotivity.base.examples.fridgeclient;\r
+\r
+import org.iotivity.base.OcPlatform;\r
+\r
+/**\r
+ * StringConstant contains the fridgeclient specific constant values.  To add another supported\r
+ * Resource or Interface type to this app, begin by adding the new strings here, and then\r
+ * find the places throughout the app where Resource-specific case switches occur, and add\r
+ * the newly-supported type there.\r
+ */\r
+public interface StringConstants {\r
+    public static final String RESOURCE_URI = "/device";\r
+    public static final String DEVICE_NAME = "device_name";\r
+    public static final String LIGHT = "/light";\r
+    public static final String LEFT_DOOR = "/door/left";\r
+    public static final String RIGHT_DOOR = "/door/right";\r
+    public static final String RANDOM_DOOR = "/door/random";\r
+    public static final String MESSAGE = "message";\r
+    public static final String API_VERSION = "v.1.2";\r
+    public static final String CLIENT_TOKEN = "AaBbYyZz";\r
+    public static final String ON = "on";\r
+    public static final String OPEN = "open";\r
+    public static final String SIDE = "side";\r
+    public static final String INTENT = "org.iotivity.base.examples.fridgeclient";\r
+    public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE;\r
+\r
+    public static final int WAIT_TIME = 1000;\r
+    public static final int API_VERSION_KEY = 2048;\r
+    public static final int CLIENT_VERSION_KEY = 3000;\r
+\r
+    public static final boolean ENABLE_PRINTING = true; // change to false to disable printing\r
+                                                        // of messages on the console and the screen\r
+}\r
diff --git a/android/examples/fridgeclient/src/main/res/layout/activity_fridge_client.xml b/android/examples/fridgeclient/src/main/res/layout/activity_fridge_client.xml
new file mode 100755 (executable)
index 0000000..d813c8a
--- /dev/null
@@ -0,0 +1,18 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"\r
+    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"\r
+    android:paddingRight="@dimen/activity_horizontal_margin"\r
+    android:paddingTop="@dimen/activity_vertical_margin"\r
+    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".FridgeClient">\r
+\r
+    <TextView android:text="@string/app_name" android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content" />\r
+\r
+    <LinearLayout\r
+        android:layout_width="fill_parent"\r
+        android:layout_height="fill_parent"\r
+        android:orientation="vertical"\r
+        android:id="@+id/linearLayout" >\r
+    </LinearLayout>\r
+\r
+</RelativeLayout>\r
diff --git a/android/examples/fridgeclient/src/main/res/menu/menu_fridge_client.xml b/android/examples/fridgeclient/src/main/res/menu/menu_fridge_client.xml
new file mode 100755 (executable)
index 0000000..f812805
--- /dev/null
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:app="http://schemas.android.com/apk/res-auto"\r
+    xmlns:tools="http://schemas.android.com/tools" tools:context=".FridgeClient">\r
+    <item android:id="@+id/action_settings" android:title="@string/action_settings"\r
+        android:orderInCategory="100" app:showAsAction="never" />\r
+</menu>\r
diff --git a/android/examples/fridgeclient/src/main/res/values-w820dp/dimens.xml b/android/examples/fridgeclient/src/main/res/values-w820dp/dimens.xml
new file mode 100755 (executable)
index 0000000..62df187
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>\r
+    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r
+         (such as screen margins) for screens with more than 820dp of available width. This\r
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->\r
+    <dimen name="activity_horizontal_margin">64dp</dimen>\r
+</resources>\r
diff --git a/android/examples/fridgeclient/src/main/res/values/dimens.xml b/android/examples/fridgeclient/src/main/res/values/dimens.xml
new file mode 100755 (executable)
index 0000000..295b5a9
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>\r
+    <!-- Default screen margins, per the Android Design guidelines. -->\r
+    <dimen name="activity_horizontal_margin">16dp</dimen>\r
+    <dimen name="activity_vertical_margin">16dp</dimen>\r
+</resources>\r
diff --git a/android/examples/fridgeclient/src/main/res/values/strings.xml b/android/examples/fridgeclient/src/main/res/values/strings.xml
new file mode 100755 (executable)
index 0000000..152e2c9
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<resources>\r
+\r
+    <string name="app_name">FridgeClient</string>\r
+    <string name="hello_world">Hello world!</string>\r
+    <string name="action_settings">Settings</string>\r
+\r
+</resources>\r
diff --git a/android/examples/fridgeclient/src/main/res/values/styles.xml b/android/examples/fridgeclient/src/main/res/values/styles.xml
new file mode 100755 (executable)
index 0000000..084b42b
--- /dev/null
@@ -0,0 +1,8 @@
+<resources>\r
+\r
+    <!-- Base application theme. -->\r
+    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">\r
+        <!-- Customize your theme here. -->\r
+    </style>\r
+\r
+</resources>\r
diff --git a/android/examples/fridgeserver/.gitignore b/android/examples/fridgeserver/.gitignore
new file mode 100644 (file)
index 0000000..3543521
--- /dev/null
@@ -0,0 +1 @@
+/build\r
diff --git a/android/examples/fridgeserver/build.gradle b/android/examples/fridgeserver/build.gradle
new file mode 100755 (executable)
index 0000000..b7327b6
--- /dev/null
@@ -0,0 +1,26 @@
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion "21.1.2"\r
+\r
+    defaultConfig {\r
+        applicationId "org.iotivity.base.examples.fridgeserver"\r
+        minSdkVersion 19\r
+        targetSdkVersion 21\r
+        versionCode 1\r
+        versionName "1.0"\r
+    }\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+        }\r
+    }\r
+}\r
+\r
+dependencies {\r
+    compile fileTree(dir: 'libs', include: ['*.jar'])\r
+    compile 'com.android.support:appcompat-v7:21.0.3'\r
+    compile project(':message')\r
+}\r
diff --git a/android/examples/fridgeserver/fridgeserver.iml b/android/examples/fridgeserver/fridgeserver.iml
new file mode 100755 (executable)
index 0000000..65d2947
--- /dev/null
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="android-gradle" name="Android-Gradle">\r
+      <configuration>\r
+        <option name="GRADLE_PROJECT_PATH" value=":fridgeserver" />\r
+      </configuration>\r
+    </facet>\r
+    <facet type="android" name="Android">\r
+      <configuration>\r
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
+        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
+        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />\r
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="false">\r
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
+    </content>\r
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+    <orderEntry type="library" exported="" name="iotivity-x86-base-debug-unspecified" level="project" />\r
+    <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
+    <orderEntry type="module" module-name="message" exported="" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/examples/fridgeserver/src/main/AndroidManifest.xml b/android/examples/fridgeserver/src/main/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..cbcffd9
--- /dev/null
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools"\r
+    package="org.iotivity.base.examples.fridgeserver">\r
+\r
+    <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>\r
+\r
+    <application\r
+        android:allowBackup="true"\r
+        android:icon="@drawable/ic_launcher"\r
+        android:label="@string/app_name"\r
+        android:theme="@style/AppTheme" >\r
+        <activity\r
+            android:name=".FridgeServer"\r
+            android:label="@string/app_name" >\r
+            <intent-filter>\r
+                <action android:name="android.intent.action.MAIN" />\r
+\r
+                <category android:name="android.intent.category.LAUNCHER" />\r
+            </intent-filter>\r
+        </activity>\r
+    </application>\r
+\r
+</manifest>\r
diff --git a/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/DeviceResource.java b/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/DeviceResource.java
new file mode 100644 (file)
index 0000000..fc33258
--- /dev/null
@@ -0,0 +1,189 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.fridgeserver;\r
+\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.util.Log;\r
+\r
+import org.iotivity.base.EntityHandlerResult;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcHeaderOption;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcResourceRequest;\r
+import org.iotivity.base.OcResourceResponse;\r
+import org.iotivity.base.RequestHandlerFlag;\r
+import org.iotivity.base.ResourceProperty;\r
+\r
+import java.util.EnumSet;\r
+import java.util.LinkedList;\r
+import java.util.List;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * DeviceResource\r
+ * <p/>\r
+ * Creates a device resource and performs action based on client requests\r
+ */\r
+public class DeviceResource extends Resource implements IMessageLogger {\r
+    private Context mContext;\r
+\r
+    private static String TAG = "DeviceResource: ";\r
+\r
+    /**\r
+     * constructor\r
+     *\r
+     * @param context to enable sending of broadcast messages to be displayed on the user screen\r
+     */\r
+    DeviceResource(Context context) {\r
+        mContext = context;\r
+\r
+        // eventHandler for register deviceResource\r
+        OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {\r
+            @Override\r
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {\r
+                // this is where the main logic of DeviceResource is handled\r
+                return entityHandler(ocResourceRequest);\r
+            }\r
+        };\r
+\r
+        try {\r
+            logMessage(TAG + "RegisterDeviceResource " + StringConstants.DEVICE_URI + " : " +\r
+                    StringConstants.RESOURCE_TYPENAME + " : " + StringConstants.RESOURCE_INTERFACE);\r
+            mResourceHandle = OcPlatform.registerResource(StringConstants.DEVICE_URI,\r
+                    StringConstants.RESOURCE_TYPENAME, StringConstants.RESOURCE_INTERFACE,\r
+                    eh, EnumSet.of(ResourceProperty.DISCOVERABLE));\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "registerResource error: " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * update current state of device\r
+     *\r
+     * @return device representation\r
+     */\r
+    private void updateRepresentationValues() {\r
+        try {\r
+            mRepresentation.setValue(StringConstants.DEVICE_NAME,\r
+                    "Intel Powered 2 door, 1 light refrigerator");\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * unregister the resource\r
+     */\r
+    private void deleteDeviceResource() {\r
+        try {\r
+            OcPlatform.unregisterResource(mResourceHandle);\r
+            logMessage(TAG + "Unregister DeviceResource successful");\r
+        } catch (OcException e) {\r
+            logMessage(TAG + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * this is the main method which handles different incoming requests appropriately.\r
+     *\r
+     * @param request OcResourceRequest from the client\r
+     * @return EntityHandlerResult depending on whether the request was handled successfully or not\r
+     */\r
+    private EntityHandlerResult entityHandler(OcResourceRequest request) {\r
+        EntityHandlerResult result = EntityHandlerResult.ERROR;\r
+        if (null != request) {\r
+            List<OcHeaderOption> headerOptions = request.getHeaderOptions();\r
+            String clientAPIVersion = "";\r
+            String clientToken = "";\r
+\r
+            // search for header options map and look for API version and client token\r
+            for (OcHeaderOption headerOption : headerOptions) {\r
+                int optionId = headerOption.getOptionId();\r
+                if (StringConstants.API_VERSION_KEY == optionId) {\r
+                    clientAPIVersion = headerOption.getOptionData();\r
+                    logMessage(TAG + " Client API Version: " + clientAPIVersion);\r
+                } else if (StringConstants.CLIENT_VERSION_KEY == optionId) {\r
+                    clientToken = headerOption.getOptionData();\r
+                    logMessage(TAG + " Client Token: " + clientToken);\r
+                }\r
+            }\r
+            if (clientAPIVersion.equals(StringConstants.API_VERSION) &&\r
+                    clientToken.equals(StringConstants.CLIENT_TOKEN)) {\r
+                List<OcHeaderOption> serverHeaderOptions = new LinkedList<>();\r
+                OcHeaderOption apiVersion = new OcHeaderOption(StringConstants.API_VERSION_KEY,\r
+                        StringConstants.API_VERSION);\r
+                serverHeaderOptions.add(apiVersion);\r
+                try {\r
+                    if (request.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {\r
+                        OcResourceResponse response = new OcResourceResponse();\r
+                        response.setRequestHandle(request.getRequestHandle());\r
+                        response.setResourceHandle(request.getResourceHandle());\r
+                        response.setHeaderOptions(serverHeaderOptions);\r
+\r
+                        switch (request.getRequestType()) {\r
+                            case GET:\r
+                                response.setErrorCode(StringConstants.OK);\r
+                                response.setResponseResult(EntityHandlerResult.OK);\r
+                                updateRepresentationValues();\r
+                                response.setResourceRepresentation(mRepresentation);\r
+                                OcPlatform.sendResponse(response);\r
+                                break;\r
+                            case DELETE:\r
+                                deleteDeviceResource();\r
+                                response.setErrorCode(StringConstants.OK);\r
+                                response.setResponseResult(EntityHandlerResult.OK);\r
+                                break;\r
+                            case POST:\r
+                                response.setResponseResult(EntityHandlerResult.ERROR);\r
+                                OcPlatform.sendResponse(response);\r
+                                break;\r
+                        }\r
+                        result = EntityHandlerResult.OK;\r
+                    }\r
+                } catch (OcException e) {\r
+                    logMessage(TAG + e.getMessage());\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public void logMessage(String msg) {\r
+        logMsg(msg);\r
+        if (StringConstants.ENABLE_PRINTING) {\r
+            Log.i(TAG, msg);\r
+        }\r
+    }\r
+\r
+    public void logMsg(final String text) {\r
+        Intent intent = new Intent(StringConstants.INTENT);\r
+        intent.putExtra("message", text);\r
+        mContext.sendBroadcast(intent);\r
+    }\r
+}\r
diff --git a/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/DoorResource.java b/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/DoorResource.java
new file mode 100644 (file)
index 0000000..438022b
--- /dev/null
@@ -0,0 +1,178 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.fridgeserver;\r
+\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.util.Log;\r
+\r
+import org.iotivity.base.EntityHandlerResult;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.OcResourceRequest;\r
+import org.iotivity.base.OcResourceResponse;\r
+import org.iotivity.base.RequestHandlerFlag;\r
+import org.iotivity.base.ResourceProperty;\r
+\r
+import java.util.EnumSet;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * DoorResource\r
+ * <p/>\r
+ * Creates a door resource and performs action based on client requests\r
+ */\r
+public class DoorResource extends Resource implements IMessageLogger {\r
+    private Context mContext;\r
+\r
+    private static String TAG = "DoorResource: ";\r
+    private String mSide = StringConstants.LEFT;\r
+    private boolean mOpen;\r
+    private String resourceURI;\r
+\r
+    /**\r
+     * Constructor\r
+     *\r
+     * @param side    left or right side of the door\r
+     * @param context to enable sending of broadcast messages to be displayed on the user screen\r
+     */\r
+    DoorResource(String side, Context context) {\r
+        mContext = context;\r
+        mSide = side;\r
+\r
+        resourceURI = StringConstants.DOOR_URI + mSide;\r
+\r
+        // eventHandler for register doorResource\r
+        OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {\r
+            @Override\r
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {\r
+                // this is where the main logic of DoorResource is handled\r
+                return entityHandler(ocResourceRequest);\r
+            }\r
+        };\r
+        try {\r
+            logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " +\r
+                    StringConstants.RESOURCE_TYPEDOOR + " : " + StringConstants.RESOURCE_INTERFACE);\r
+            mResourceHandle = OcPlatform.registerResource(resourceURI,\r
+                    StringConstants.RESOURCE_TYPEDOOR, StringConstants.RESOURCE_INTERFACE,\r
+                    eh, EnumSet.of(ResourceProperty.DISCOVERABLE));\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "DoorResource registerResource error: " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * updates the current value of the door resource\r
+     *\r
+     * @return door representation\r
+     */\r
+    private void updateRepresentationValues() {\r
+        try {\r
+            mRepresentation.setValue(StringConstants.SIDE, mSide);\r
+            mRepresentation.setValue(StringConstants.OPEN, mOpen);\r
+            mRepresentation.setValue(StringConstants.DEVICE_NAME,\r
+                    "Intel Powered 2 door, 1 light refrigerator");\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * update the OPEN value of doorResource (door is open/ closed)\r
+     *\r
+     * @param representation get current state of door\r
+     */\r
+    private void put(OcRepresentation representation) {\r
+        try {\r
+            mOpen = representation.getValue(StringConstants.OPEN);\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        // Note, we won't let the user change the door side!\r
+    }\r
+\r
+    /**\r
+     * this is the main method which handles different incoming requests appropriately.\r
+     *\r
+     * @param request OcResourceRequest from the client\r
+     * @return EntityHandlerResult depending on whether the request was handled successfully or not\r
+     */\r
+    private EntityHandlerResult entityHandler(OcResourceRequest request) {\r
+        EntityHandlerResult result = EntityHandlerResult.ERROR;\r
+        if (null != request) {\r
+            try {\r
+                if (request.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {\r
+                    OcResourceResponse response = new OcResourceResponse();\r
+                    response.setRequestHandle(request.getRequestHandle());\r
+                    response.setResourceHandle(request.getResourceHandle());\r
+\r
+                    switch (request.getRequestType()) {\r
+                        case GET:\r
+                            response.setErrorCode(StringConstants.OK);\r
+                            updateRepresentationValues();\r
+                            response.setResourceRepresentation(mRepresentation);\r
+                            response.setResponseResult(EntityHandlerResult.OK);\r
+                            OcPlatform.sendResponse(response);\r
+                            break;\r
+                        case PUT:\r
+                            response.setErrorCode(StringConstants.OK);\r
+                            put(request.getResourceRepresentation());\r
+                            updateRepresentationValues();\r
+                            response.setResourceRepresentation(mRepresentation);\r
+                            response.setResponseResult(EntityHandlerResult.OK);\r
+                            OcPlatform.sendResponse(response);\r
+                            break;\r
+                        case DELETE:\r
+                            response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);\r
+                            response.setErrorCode(204);\r
+                            OcPlatform.sendResponse(response);\r
+                            break;\r
+                    }\r
+                    result = EntityHandlerResult.OK;\r
+                }\r
+            } catch (OcException e) {\r
+                logMessage(TAG + e.getMessage());\r
+                Log.e(TAG, e.getMessage());\r
+                return EntityHandlerResult.ERROR;\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public void logMessage(String msg) {\r
+        logMsg(msg);\r
+        if (StringConstants.ENABLE_PRINTING) {\r
+            Log.i(TAG, msg);\r
+        }\r
+    }\r
+\r
+    public void logMsg(final String text) {\r
+        Intent intent = new Intent(StringConstants.INTENT);\r
+        intent.putExtra(StringConstants.MESSAGE, text);\r
+        mContext.sendBroadcast(intent);\r
+    }\r
+}\r
diff --git a/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/FridgeServer.java b/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/FridgeServer.java
new file mode 100644 (file)
index 0000000..45971f7
--- /dev/null
@@ -0,0 +1,145 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.fridgeserver;\r
+\r
+import android.app.Activity;\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.content.IntentFilter;\r
+import android.os.Bundle;\r
+import android.os.Message;\r
+import android.support.v4.content.LocalBroadcastManager;\r
+import android.text.method.ScrollingMovementMethod;\r
+import android.util.Log;\r
+import android.view.Menu;\r
+import android.view.MenuItem;\r
+import android.widget.LinearLayout;\r
+import android.widget.TextView;\r
+\r
+import org.iotivity.base.ModeType;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.PlatformConfig;\r
+import org.iotivity.base.QualityOfService;\r
+import org.iotivity.base.ServiceType;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * FridgeServer\r
+ * <p/>\r
+ * This is the main fridgeServer class. This instantiates Refrigerator object\r
+ * which has different resources (DeviceResource, LightResource, DoorResource).\r
+ */\r
+public class FridgeServer extends Activity implements IMessageLogger {\r
+    private Context mContext;\r
+    private static String TAG = "FridgeServer: ";\r
+    private TextView mEventsTextView;\r
+    private MessageReceiver mMessageReceiver = new MessageReceiver();\r
+    private Refrigerator refrigerator;\r
+\r
+    /**\r
+     * configure OIC platform and call findResource\r
+     */\r
+    private void initOICStack() {\r
+        //create platform config\r
+        PlatformConfig cfg = new PlatformConfig(\r
+                this,\r
+                ServiceType.IN_PROC,\r
+                ModeType.SERVER,\r
+                "0.0.0.0", // bind to all available interfaces\r
+                0,\r
+                QualityOfService.LOW);\r
+        OcPlatform.Configure(cfg);\r
+        logMessage(TAG + "Creating refrigerator resources");\r
+\r
+        refrigerator = new Refrigerator(mContext);\r
+    }\r
+\r
+    @Override\r
+    protected void onCreate(Bundle savedInstanceState) {\r
+        super.onCreate(savedInstanceState);\r
+        setContentView(R.layout.activity_fridge_server);\r
+        registerReceiver(mMessageReceiver, new IntentFilter(StringConstants.INTENT));\r
+\r
+        mEventsTextView = new TextView(this);\r
+        mEventsTextView.setMovementMethod(new ScrollingMovementMethod());\r
+        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);\r
+        layout.addView(mEventsTextView, new LinearLayout.LayoutParams\r
+                (LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));\r
+        mContext = this;\r
+\r
+        initOICStack();\r
+    }\r
+\r
+    public class MessageReceiver extends BroadcastReceiver {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            final String message = intent.getStringExtra(StringConstants.MESSAGE);\r
+            logMessage(message);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void logMessage(final String text) {\r
+        if (StringConstants.ENABLE_PRINTING) {\r
+            runOnUiThread(new Runnable() {\r
+                public void run() {\r
+                    final Message msg = new Message();\r
+                    msg.obj = text;\r
+                    mEventsTextView.append("\n");\r
+                    mEventsTextView.append(text);\r
+                }\r
+            });\r
+            Log.i(TAG, text);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public boolean onCreateOptionsMenu(Menu menu) {\r
+        // Inflate the menu; this adds items to the action bar if it is present.\r
+        getMenuInflater().inflate(R.menu.menu_fridge_server, menu);\r
+        return true;\r
+    }\r
+\r
+    @Override\r
+    public boolean onOptionsItemSelected(MenuItem item) {\r
+        int id = item.getItemId();\r
+        if (id == R.id.action_settings) {\r
+            return true;\r
+        }\r
+        return super.onOptionsItemSelected(item);\r
+    }\r
+\r
+    @Override\r
+    public void onDestroy() {\r
+        super.onDestroy();\r
+        onStop();\r
+    }\r
+\r
+    @Override\r
+    protected void onStop() {\r
+        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);\r
+        super.onStop();\r
+    }\r
+}\r
diff --git a/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/LightResource.java b/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/LightResource.java
new file mode 100644 (file)
index 0000000..09b7f43
--- /dev/null
@@ -0,0 +1,164 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.fridgeserver;\r
+\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.util.Log;\r
+\r
+import org.iotivity.base.EntityHandlerResult;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.OcResourceRequest;\r
+import org.iotivity.base.OcResourceResponse;\r
+import org.iotivity.base.RequestHandlerFlag;\r
+import org.iotivity.base.ResourceProperty;\r
+\r
+import java.util.EnumSet;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * LightResource\r
+ * <p/>\r
+ * Creates a light resource and performs action based on client requests\r
+ */\r
+public class LightResource extends Resource implements IMessageLogger {\r
+    private Context mContext;\r
+\r
+    private static String TAG = "LightResource: ";\r
+\r
+    private boolean mIsOn = false;\r
+\r
+    /**\r
+     * constructor\r
+     *\r
+     * @param context to enable sending of broadcast messages to be displayed on the user screen\r
+     */\r
+    LightResource(Context context) {\r
+        mContext = context;\r
+        //eventHandler for register lightResource\r
+        OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {\r
+            @Override\r
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {\r
+                // this is where the main logic of LightResource is handled\r
+                return entityHandler(ocResourceRequest);\r
+            }\r
+        };\r
+        try {\r
+            logMessage(TAG + "RegisterLightResource " + StringConstants.LIGHT_URI + " : " +\r
+                    StringConstants.RESOURCE_TYPELIGHT + " : " + StringConstants.RESOURCE_INTERFACE);\r
+            mResourceHandle = OcPlatform.registerResource(StringConstants.LIGHT_URI,\r
+                    StringConstants.RESOURCE_TYPELIGHT, StringConstants.RESOURCE_INTERFACE,\r
+                    eh, EnumSet.of(ResourceProperty.DISCOVERABLE));\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "LightResource registerResource error: " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * updates the current state of the light (on/ off)\r
+     *\r
+     * @return light is on or off\r
+     */\r
+    private void updateRepresentationValues() {\r
+        try {\r
+            mRepresentation.setValue(StringConstants.ON, mIsOn);\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * update the value of mIsOn from the representation\r
+     *\r
+     * @param representation get current state of light\r
+     */\r
+    private void put(OcRepresentation representation) {\r
+        try {\r
+            mIsOn = representation.getValue(StringConstants.ON);\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * this is the main method which handles different incoming requests appropriately.\r
+     *\r
+     * @param request OcResourceRequest from the client\r
+     * @return EntityHandlerResult depending on whether the request was handled successfully or not\r
+     */\r
+    private EntityHandlerResult entityHandler(OcResourceRequest request) {\r
+        EntityHandlerResult result = EntityHandlerResult.ERROR;\r
+        if (null != request) {\r
+            try {\r
+                if (request.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {\r
+                    OcResourceResponse response = new OcResourceResponse();\r
+                    response.setRequestHandle(request.getRequestHandle());\r
+                    response.setResourceHandle(request.getResourceHandle());\r
+\r
+                    switch (request.getRequestType()) {\r
+                        case GET:\r
+                            response.setErrorCode(StringConstants.OK);\r
+                            updateRepresentationValues();\r
+                            response.setResourceRepresentation(mRepresentation);\r
+                            response.setResponseResult(EntityHandlerResult.OK);\r
+                            OcPlatform.sendResponse(response);\r
+                            result = EntityHandlerResult.OK;\r
+                            break;\r
+                        case PUT:\r
+                            response.setErrorCode(StringConstants.OK);\r
+                            put(request.getResourceRepresentation());\r
+                            updateRepresentationValues();\r
+                            response.setResourceRepresentation(mRepresentation);\r
+                            response.setResponseResult(EntityHandlerResult.OK);\r
+                            OcPlatform.sendResponse(response);\r
+                            result = EntityHandlerResult.OK;\r
+                            break;\r
+                    }\r
+                }\r
+            } catch (OcException e) {\r
+                logMessage(TAG + e.getMessage());\r
+                Log.e(TAG, e.getMessage());\r
+                return EntityHandlerResult.ERROR;\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public void logMessage(String msg) {\r
+        logMsg(msg);\r
+        if (StringConstants.ENABLE_PRINTING) {\r
+            Log.i(TAG, msg);\r
+        }\r
+    }\r
+\r
+    public void logMsg(final String text) {\r
+        Intent intent = new Intent(StringConstants.INTENT);\r
+        intent.putExtra(StringConstants.MESSAGE, text);\r
+        mContext.sendBroadcast(intent);\r
+    }\r
+}\r
diff --git a/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/Refrigerator.java b/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/Refrigerator.java
new file mode 100644 (file)
index 0000000..4432755
--- /dev/null
@@ -0,0 +1,57 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.fridgeserver;\r
+\r
+import android.content.Context;\r
+\r
+/**\r
+ * Refrigerator\r
+ * <p/>\r
+ * Refrigerator class has different objects (resources) which are instantiated when a\r
+ * Refrigerator object is created. Operations are performed on each of the individual resources.\r
+ */\r
+public class Refrigerator {\r
+    private Context mContext;\r
+\r
+    private LightResource mLight;\r
+    private DeviceResource mDevice;\r
+    private DoorResource mLeftDoor;\r
+    private DoorResource mRightDoor;\r
+    private DoorResource mRandomDoor;\r
+\r
+    /**\r
+     * constructor\r
+     *\r
+     * @param context needed by individual resources to be able to send broadcast\r
+     *                messages to be displayed on the user screen\r
+     */\r
+    Refrigerator(Context context) {\r
+        mContext = context;\r
+        mLight = new LightResource(context);\r
+        mDevice = new DeviceResource(context);\r
+        mLeftDoor = new DoorResource(StringConstants.LEFT, context);\r
+        mRightDoor = new DoorResource(StringConstants.RIGHT, context);\r
+        mRandomDoor = new DoorResource(StringConstants.RANDOM, context);\r
+    }\r
+\r
+}\r
diff --git a/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/Resource.java b/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/Resource.java
new file mode 100644 (file)
index 0000000..350cee0
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.fridgeserver;\r
+\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.OcResourceHandle;\r
+\r
+/**\r
+ * Resource\r
+ * <p/>\r
+ * Each of the other resource classes (DeviceResource, DoorResource and LightResource extend Resource\r
+ */\r
+public class Resource {\r
+    protected OcResourceHandle mResourceHandle;\r
+    protected OcRepresentation mRepresentation;\r
+\r
+    Resource() {\r
+        mResourceHandle = null;\r
+        mRepresentation = new OcRepresentation();\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/StringConstants.java b/android/examples/fridgeserver/src/main/java/org/iotivity/base/examples/fridgeserver/StringConstants.java
new file mode 100644 (file)
index 0000000..1afe25b
--- /dev/null
@@ -0,0 +1,37 @@
+package org.iotivity.base.examples.fridgeserver;\r
+\r
+import org.iotivity.base.OcPlatform;\r
+\r
+/**\r
+ * StringConstant contains the fridgeserver specific constant values.  To add another supported\r
+ * Resource or Interface type to this app, begin by adding the new strings here, and then\r
+ * find the places throughout the app where Resource-specific case switches occur, and add\r
+ * the newly-supported type there.\r
+ */\r
+public interface StringConstants {\r
+    public static final String DEVICE_URI = "/device";\r
+    public static final String LIGHT_URI = "/light";\r
+    public static final String DOOR_URI = "/door/";\r
+    public static final String DEVICE_NAME = "device_name";\r
+    public static final String RESOURCE_TYPENAME = "intel.fridge";\r
+    public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";\r
+    public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";\r
+    public static final String API_VERSION = "v.1.2";\r
+    public static final String CLIENT_TOKEN = "AaBbYyZz";\r
+    public static final String SIDE = "side";\r
+    public static final String OPEN = "open";\r
+    public static final String MESSAGE = "message";\r
+    public static final String LEFT = "left";\r
+    public static final String RIGHT = "right";\r
+    public static final String RANDOM = "random";\r
+    public static final String ON = "on";\r
+    public static final String INTENT = "org.iotivity.base.examples.fridgeserver";\r
+    public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE;\r
+\r
+    public static final int API_VERSION_KEY = 2048;\r
+    public static final int CLIENT_VERSION_KEY = 3000;\r
+    public static final int OK = 200;\r
+\r
+    public static final boolean ENABLE_PRINTING = true; // change to false to disable printing\r
+                                                        // of messages on the console and the screen\r
+}\r
diff --git a/android/examples/fridgeserver/src/main/res/layout/activity_fridge_server.xml b/android/examples/fridgeserver/src/main/res/layout/activity_fridge_server.xml
new file mode 100755 (executable)
index 0000000..39362b3
--- /dev/null
@@ -0,0 +1,18 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"\r
+    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"\r
+    android:paddingRight="@dimen/activity_horizontal_margin"\r
+    android:paddingTop="@dimen/activity_vertical_margin"\r
+    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".FridgeServer">\r
+\r
+    <TextView android:text="@string/app_name" android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content" />\r
+\r
+    <LinearLayout\r
+        android:layout_width="fill_parent"\r
+        android:layout_height="fill_parent"\r
+        android:orientation="vertical"\r
+        android:id="@+id/linearLayout" >\r
+    </LinearLayout>\r
+\r
+</RelativeLayout>\r
diff --git a/android/examples/fridgeserver/src/main/res/menu/menu_fridge_server.xml b/android/examples/fridgeserver/src/main/res/menu/menu_fridge_server.xml
new file mode 100755 (executable)
index 0000000..2895144
--- /dev/null
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:app="http://schemas.android.com/apk/res-auto"\r
+    xmlns:tools="http://schemas.android.com/tools" tools:context=".FridgeServer">\r
+    <item android:id="@+id/action_settings" android:title="@string/action_settings"\r
+        android:orderInCategory="100" app:showAsAction="never" />\r
+</menu>\r
diff --git a/android/examples/fridgeserver/src/main/res/values-w820dp/dimens.xml b/android/examples/fridgeserver/src/main/res/values-w820dp/dimens.xml
new file mode 100755 (executable)
index 0000000..62df187
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>\r
+    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r
+         (such as screen margins) for screens with more than 820dp of available width. This\r
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->\r
+    <dimen name="activity_horizontal_margin">64dp</dimen>\r
+</resources>\r
diff --git a/android/examples/fridgeserver/src/main/res/values/dimens.xml b/android/examples/fridgeserver/src/main/res/values/dimens.xml
new file mode 100755 (executable)
index 0000000..295b5a9
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>\r
+    <!-- Default screen margins, per the Android Design guidelines. -->\r
+    <dimen name="activity_horizontal_margin">16dp</dimen>\r
+    <dimen name="activity_vertical_margin">16dp</dimen>\r
+</resources>\r
diff --git a/android/examples/fridgeserver/src/main/res/values/strings.xml b/android/examples/fridgeserver/src/main/res/values/strings.xml
new file mode 100755 (executable)
index 0000000..3e317da
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<resources>\r
+\r
+    <string name="app_name">FridgeServer</string>\r
+    <string name="hello_world">Hello world!</string>\r
+    <string name="action_settings">Settings</string>\r
+\r
+</resources>\r
diff --git a/android/examples/fridgeserver/src/main/res/values/styles.xml b/android/examples/fridgeserver/src/main/res/values/styles.xml
new file mode 100755 (executable)
index 0000000..084b42b
--- /dev/null
@@ -0,0 +1,8 @@
+<resources>\r
+\r
+    <!-- Base application theme. -->\r
+    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">\r
+        <!-- Customize your theme here. -->\r
+    </style>\r
+\r
+</resources>\r
diff --git a/android/examples/gradle/wrapper/gradle-wrapper.jar b/android/examples/gradle/wrapper/gradle-wrapper.jar
new file mode 100755 (executable)
index 0000000..8c0fb64
Binary files /dev/null and b/android/examples/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/android/examples/gradle/wrapper/gradle-wrapper.properties b/android/examples/gradle/wrapper/gradle-wrapper.properties
new file mode 100755 (executable)
index 0000000..cdc433f
--- /dev/null
@@ -0,0 +1,6 @@
+#Wed Apr 10 15:27:10 PDT 2013\r
+distributionBase=GRADLE_USER_HOME\r
+distributionPath=wrapper/dists\r
+zipStoreBase=GRADLE_USER_HOME\r
+zipStorePath=wrapper/dists\r
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip\r
diff --git a/android/examples/gradlew b/android/examples/gradlew
new file mode 100755 (executable)
index 0000000..583ae08
--- /dev/null
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash\r
+\r
+##############################################################################\r
+##\r
+##  Gradle start up script for UN*X\r
+##\r
+##############################################################################\r
+\r
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r
+DEFAULT_JVM_OPTS=""\r
+\r
+APP_NAME="Gradle"\r
+APP_BASE_NAME=`basename "$0"`\r
+\r
+# Use the maximum available, or set MAX_FD != -1 to use that value.\r
+MAX_FD="maximum"\r
+\r
+warn ( ) {\r
+    echo "$*"\r
+}\r
+\r
+die ( ) {\r
+    echo\r
+    echo "$*"\r
+    echo\r
+    exit 1\r
+}\r
+\r
+# OS specific support (must be 'true' or 'false').\r
+cygwin=false\r
+msys=false\r
+darwin=false\r
+case "`uname`" in\r
+  CYGWIN* )\r
+    cygwin=true\r
+    ;;\r
+  Darwin* )\r
+    darwin=true\r
+    ;;\r
+  MINGW* )\r
+    msys=true\r
+    ;;\r
+esac\r
+\r
+# For Cygwin, ensure paths are in UNIX format before anything is touched.\r
+if $cygwin ; then\r
+    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`\r
+fi\r
+\r
+# Attempt to set APP_HOME\r
+# Resolve links: $0 may be a link\r
+PRG="$0"\r
+# Need this for relative symlinks.\r
+while [ -h "$PRG" ] ; do\r
+    ls=`ls -ld "$PRG"`\r
+    link=`expr "$ls" : '.*-> \(.*\)$'`\r
+    if expr "$link" : '/.*' > /dev/null; then\r
+        PRG="$link"\r
+    else\r
+        PRG=`dirname "$PRG"`"/$link"\r
+    fi\r
+done\r
+SAVED="`pwd`"\r
+cd "`dirname \"$PRG\"`/" >&-\r
+APP_HOME="`pwd -P`"\r
+cd "$SAVED" >&-\r
+\r
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\r
+\r
+# Determine the Java command to use to start the JVM.\r
+if [ -n "$JAVA_HOME" ] ; then\r
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then\r
+        # IBM's JDK on AIX uses strange locations for the executables\r
+        JAVACMD="$JAVA_HOME/jre/sh/java"\r
+    else\r
+        JAVACMD="$JAVA_HOME/bin/java"\r
+    fi\r
+    if [ ! -x "$JAVACMD" ] ; then\r
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\r
+\r
+Please set the JAVA_HOME variable in your environment to match the\r
+location of your Java installation."\r
+    fi\r
+else\r
+    JAVACMD="java"\r
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r
+\r
+Please set the JAVA_HOME variable in your environment to match the\r
+location of your Java installation."\r
+fi\r
+\r
+# Increase the maximum file descriptors if we can.\r
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then\r
+    MAX_FD_LIMIT=`ulimit -H -n`\r
+    if [ $? -eq 0 ] ; then\r
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then\r
+            MAX_FD="$MAX_FD_LIMIT"\r
+        fi\r
+        ulimit -n $MAX_FD\r
+        if [ $? -ne 0 ] ; then\r
+            warn "Could not set maximum file descriptor limit: $MAX_FD"\r
+        fi\r
+    else\r
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"\r
+    fi\r
+fi\r
+\r
+# For Darwin, add options to specify how the application appears in the dock\r
+if $darwin; then\r
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""\r
+fi\r
+\r
+# For Cygwin, switch paths to Windows format before running java\r
+if $cygwin ; then\r
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`\r
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`\r
+\r
+    # We build the pattern for arguments to be converted via cygpath\r
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\r
+    SEP=""\r
+    for dir in $ROOTDIRSRAW ; do\r
+        ROOTDIRS="$ROOTDIRS$SEP$dir"\r
+        SEP="|"\r
+    done\r
+    OURCYGPATTERN="(^($ROOTDIRS))"\r
+    # Add a user-defined pattern to the cygpath arguments\r
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then\r
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"\r
+    fi\r
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh\r
+    i=0\r
+    for arg in "$@" ; do\r
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`\r
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option\r
+\r
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\r
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`\r
+        else\r
+            eval `echo args$i`="\"$arg\""\r
+        fi\r
+        i=$((i+1))\r
+    done\r
+    case $i in\r
+        (0) set -- ;;\r
+        (1) set -- "$args0" ;;\r
+        (2) set -- "$args0" "$args1" ;;\r
+        (3) set -- "$args0" "$args1" "$args2" ;;\r
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;\r
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;\r
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;\r
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;\r
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;\r
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;\r
+    esac\r
+fi\r
+\r
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\r
+function splitJvmOpts() {\r
+    JVM_OPTS=("$@")\r
+}\r
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\r
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"\r
+\r
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"\r
old mode 100644 (file)
new mode 100755 (executable)
similarity index 100%
rename from android/Base/gradlew.bat
rename to android/examples/gradlew.bat
diff --git a/android/examples/message/.gitignore b/android/examples/message/.gitignore
new file mode 100644 (file)
index 0000000..1a94a02
--- /dev/null
@@ -0,0 +1,3 @@
+/build\r
+\r
+src/main/res
\ No newline at end of file
diff --git a/android/examples/message/build.gradle b/android/examples/message/build.gradle
new file mode 100755 (executable)
index 0000000..1ed1a39
--- /dev/null
@@ -0,0 +1,24 @@
+apply plugin: 'com.android.library'\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion "21.1.2"\r
+\r
+    defaultConfig {\r
+        minSdkVersion 19\r
+        targetSdkVersion 21\r
+        versionCode 1\r
+        versionName "1.0"\r
+    }\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+        }\r
+    }\r
+}\r
+\r
+dependencies {\r
+    compile fileTree(dir: 'libs', include: ['*.jar'])\r
+    compile 'com.android.support:appcompat-v7:21.0.3'\r
+}\r
diff --git a/android/examples/message/message.iml b/android/examples/message/message.iml
new file mode 100755 (executable)
index 0000000..e9cabc1
--- /dev/null
@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="android-gradle" name="Android-Gradle">\r
+      <configuration>\r
+        <option name="GRADLE_PROJECT_PATH" value=":message" />\r
+      </configuration>\r
+    </facet>\r
+    <facet type="android" name="Android">\r
+      <configuration>\r
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
+        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
+        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="" />\r
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
+        <option name="LIBRARY_PROJECT" value="true" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="false">\r
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
+    </content>\r
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+    <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/examples/message/src/main/AndroidManifest.xml b/android/examples/message/src/main/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..9922f58
--- /dev/null
@@ -0,0 +1,9 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    package="base.iotivity.org.examples.message"\r
+    xmlns:tools="http://schemas.android.com/tools">\r
+\r
+    <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>\r
+\r
+    <application android:allowBackup="true" ></application>\r
+\r
+</manifest>\r
diff --git a/android/examples/message/src/main/java/base/iotivity/org/examples/message/IMessageLogger.java b/android/examples/message/src/main/java/base/iotivity/org/examples/message/IMessageLogger.java
new file mode 100644 (file)
index 0000000..7ecd6b3
--- /dev/null
@@ -0,0 +1,27 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package base.iotivity.org.examples.message;\r
+\r
+public interface IMessageLogger {\r
+    public void logMessage(String msg);\r
+}\r
diff --git a/android/examples/settings.gradle b/android/examples/settings.gradle
new file mode 100755 (executable)
index 0000000..bf2b78b
--- /dev/null
@@ -0,0 +1 @@
+include ':simpleserver', ':simpleclient', ':message', ':fridgeserver', ':fridgeclient'
\ No newline at end of file
diff --git a/android/examples/simpleclient/.gitignore b/android/examples/simpleclient/.gitignore
new file mode 100644 (file)
index 0000000..3543521
--- /dev/null
@@ -0,0 +1 @@
+/build\r
diff --git a/android/examples/simpleclient/build.gradle b/android/examples/simpleclient/build.gradle
new file mode 100755 (executable)
index 0000000..07cc15b
--- /dev/null
@@ -0,0 +1,25 @@
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion "21.1.2"\r
+\r
+    defaultConfig {\r
+        applicationId "org.iotivity.base.examples.simpleclient"\r
+        minSdkVersion 19\r
+        targetSdkVersion 21\r
+        versionCode 1\r
+        versionName "1.0"\r
+    }\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+        }\r
+    }\r
+}\r
+\r
+dependencies {\r
+    compile project(':message')\r
+    compile 'com.android.support:appcompat-v7:21.0.3'\r
+}\r
diff --git a/android/examples/simpleclient/simpleclient.iml b/android/examples/simpleclient/simpleclient.iml
new file mode 100755 (executable)
index 0000000..4ba5a36
--- /dev/null
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="android-gradle" name="Android-Gradle">\r
+      <configuration>\r
+        <option name="GRADLE_PROJECT_PATH" value=":simpleclient" />\r
+      </configuration>\r
+    </facet>\r
+    <facet type="android" name="Android">\r
+      <configuration>\r
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
+        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
+        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />\r
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="false">\r
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
+    </content>\r
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+    <orderEntry type="library" exported="" name="iotivity-x86-base-debug-unspecified" level="project" />\r
+    <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
+    <orderEntry type="module" module-name="message" exported="" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/examples/simpleclient/src/main/AndroidManifest.xml b/android/examples/simpleclient/src/main/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..0345054
--- /dev/null
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    package="org.iotivity.base.examples.simpleclient"\r
+    xmlns:tools="http://schemas.android.com/tools">\r
+\r
+    <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>\r
+\r
+    <application\r
+        android:allowBackup="true"\r
+        android:icon="@drawable/ic_launcher"\r
+        android:label="@string/app_name"\r
+        android:theme="@style/AppTheme" >\r
+        <activity\r
+            android:name=".SimpleClient"\r
+            android:label="@string/app_name" >\r
+            <intent-filter>\r
+                <action android:name="android.intent.action.MAIN" />\r
+\r
+                <category android:name="android.intent.category.LAUNCHER" />\r
+            </intent-filter>\r
+        </activity>\r
+    </application>\r
+\r
+</manifest>\r
diff --git a/android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/Light.java b/android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/Light.java
new file mode 100644 (file)
index 0000000..2f981b3
--- /dev/null
@@ -0,0 +1,65 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.simpleclient;\r
+\r
+/**\r
+ * Light\r
+ *\r
+ * This class is used by simpleclient to create an object and update the values depending on the server response\r
+ */\r
+public class Light {\r
+    private boolean mState;\r
+    private int mPower;\r
+    private String mName;\r
+\r
+    // constructor\r
+    Light() {\r
+        mState = false;\r
+        mPower = 0;\r
+        mName = "";\r
+    }\r
+\r
+    // accessor methods\r
+    public boolean getState() {\r
+        return mState;\r
+    }\r
+    void setState(boolean state) {\r
+        mState = state;\r
+    }\r
+    int getPower() {\r
+        return mPower;\r
+    }\r
+    void setPower(int power) {\r
+        mPower = power;\r
+    }\r
+    String getName() {\r
+        return mName;\r
+    }\r
+    void setName(String name) {\r
+        mName = name;\r
+    }\r
+}\r
+\r
+\r
+\r
+\r
diff --git a/android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/SimpleClient.java b/android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/SimpleClient.java
new file mode 100644 (file)
index 0000000..b747c5a
--- /dev/null
@@ -0,0 +1,443 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.simpleclient;\r
+\r
+import android.app.Activity;\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.os.Bundle;\r
+import android.os.Message;\r
+import android.text.method.ScrollingMovementMethod;\r
+import android.util.Log;\r
+import android.widget.LinearLayout;\r
+import android.widget.TextView;\r
+\r
+import org.iotivity.base.ErrorCode;\r
+import org.iotivity.base.ModeType;\r
+import org.iotivity.base.ObserveType;\r
+import org.iotivity.base.OcConnectivityType;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcHeaderOption;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.OcResource;\r
+import org.iotivity.base.PlatformConfig;\r
+import org.iotivity.base.QualityOfService;\r
+import org.iotivity.base.ServiceType;\r
+\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * SimpleClient\r
+ * <p/>\r
+ * SimpleClient is a sample client app which should be started after the simpleServer is started.\r
+ * It finds resources advertised by the server and calls different operations on it (GET, PUT,\r
+ * POST and OBSERVE).\r
+ * This implements IMessageLogger to display messages on the screen\r
+ */\r
+public class SimpleClient extends Activity implements OcPlatform.OnResourceFoundListener,\r
+        IMessageLogger {\r
+    private static final String TAG = "SimpleClient: ";\r
+\r
+    private Light myLight;\r
+    private OcResource curResource;\r
+\r
+    //for display\r
+    private TextView mEventsTextView;\r
+    private static boolean printOnce = true;\r
+\r
+    /**\r
+     * configure OIC platform and call findResource\r
+     */\r
+    private void initOICStack() {\r
+        //create platform config\r
+        PlatformConfig cfg = new PlatformConfig(\r
+                this,\r
+                ServiceType.IN_PROC,\r
+                ModeType.CLIENT,\r
+                "0.0.0.0", // bind to all available interfaces\r
+                0,\r
+                QualityOfService.LOW);\r
+        OcPlatform.Configure(cfg);\r
+        try {\r
+            /**\r
+             * find all resources\r
+             */\r
+            OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "core.light",\r
+                    OcConnectivityType.WIFI, this);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "findResource error: " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    @Override\r
+    /**\r
+     *  callback when a resource is found. This method calls doGetLightRepresentation to get the\r
+     *  current values of myLight\r
+     */\r
+    synchronized public void onResourceFound(OcResource ocResource) {\r
+        /**\r
+         *  this may potentially be called by multiple threads at the same time\r
+         */\r
+        synchronized (this) {\r
+            String resourceUri;\r
+            String hostAddress;\r
+            resourceUri = ocResource.getUri();\r
+            hostAddress = ocResource.getHost();\r
+            logMessage(TAG + "Discovered Resource\nUri: " + resourceUri + " \n Host: " + hostAddress);\r
+            // get the resource types\r
+            if (resourceUri.equals(StringConstants.RESOURCE_URI0)) {\r
+                curResource = ocResource;\r
+                doGetLightRepresentation();\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * get myLight values after observe\r
+     */\r
+    private void doObserveLightRepresentation() {\r
+        // eventhandler for observe()\r
+        OcResource.OnObserveListener onObserveListener = new OcResource.OnObserveListener() {\r
+            @Override\r
+            public void onObserveCompleted(List<OcHeaderOption> ocHeaderOptions,\r
+                                           OcRepresentation ocRepresentation, int seqNum) {\r
+                if (printOnce) {\r
+                    logMessage(TAG + "OBSERVE request was successful");\r
+                    printOnce = false;\r
+                }\r
+                try {\r
+                    boolean state = ocRepresentation.getValue(StringConstants.STATE);\r
+                    int power = ocRepresentation.getValue(StringConstants.POWER);\r
+                    String name = ocRepresentation.getValue(StringConstants.NAME);\r
+                    myLight.setState(state);\r
+                    myLight.setPower(power);\r
+                    myLight.setName(name);\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                logMessage(TAG + "onObserve: Power: " + myLight.getPower());\r
+                if (seqNum > 20) {\r
+                    try {\r
+                        curResource.cancelObserve();\r
+                        logMessage(TAG + "Successfully cancelled observe");\r
+                   } catch (OcException e) {\r
+                        logMessage(TAG + "cancelObserve error. " + e.getMessage());\r
+                        Log.e(TAG, e.getMessage());\r
+                    }\r
+                }\r
+\r
+            }\r
+\r
+            @Override\r
+            public void onObserveFailed(Throwable throwable) {\r
+                if (throwable instanceof OcException) {\r
+                    OcException ocEx = (OcException) throwable;\r
+                    ErrorCode errCode = ocEx.getErrorCode();\r
+                    //do something based on errorCode\r
+                }\r
+                Log.e(TAG, throwable.toString());\r
+            }\r
+        };\r
+        try {\r
+            curResource.observe(ObserveType.OBSERVE, new HashMap<String, String>(), onObserveListener);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * get the current value of myLight after POST and call doObserveLightRepresentation\r
+     *\r
+     * @param ocRepresentation needed to invoke post()\r
+     */\r
+    private void doOnPost2(OcRepresentation ocRepresentation) {\r
+        // eventhandler for post()\r
+        OcResource.OnPostListener onPostListener2 = new OcResource.OnPostListener() {\r
+            @Override\r
+            public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions, OcRepresentation rep) {\r
+                logMessage(TAG + "POST request was successful");\r
+                String createdUri = rep.getUri();\r
+                if (createdUri.equals(StringConstants.RESOURCE_URI1)) {\r
+                    logMessage(TAG + "Uri of the created resource: " + createdUri);\r
+                } else {\r
+                    try {\r
+                        boolean state = rep.getValue(StringConstants.STATE);\r
+                        int power = rep.getValue(StringConstants.POWER);\r
+                        String name = rep.getValue(StringConstants.NAME);\r
+                        myLight.setState(state);\r
+                        myLight.setPower(power);\r
+                        myLight.setName(name);\r
+                    } catch (OcException e) {\r
+                        Log.e(TAG, e.getMessage());\r
+                    }\r
+                    logMessage(TAG + "onPost\nState: " + myLight.getState() + "\nPower: " +\r
+                            myLight.getPower() + "\nName: " + myLight.getName());\r
+                }\r
+                doObserveLightRepresentation();\r
+            }\r
+\r
+            @Override\r
+            public void onPostFailed(Throwable throwable) {\r
+                if (throwable instanceof OcException) {\r
+                    OcException ocEx = (OcException) throwable;\r
+                    ErrorCode errCode = ocEx.getErrorCode();\r
+                    //do something based on errorCode\r
+                }\r
+                Log.e(TAG, throwable.toString());\r
+            }\r
+        };\r
+        try {\r
+            curResource.post(ocRepresentation, new HashMap<String, String>(), onPostListener2);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * create a new resource and update its value.\r
+     */\r
+    private void doPostLightRepresentation() {\r
+        // eventhandler for post()\r
+        OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {\r
+            @Override\r
+            public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,\r
+                                        OcRepresentation ocRepresentation) {\r
+                String createdUri = "";\r
+                try {\r
+                    createdUri = ocRepresentation.getValue(StringConstants.CREATED_URI);\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                if (createdUri.equals(StringConstants.RESOURCE_URI1)) {\r
+                    logMessage(TAG + "Uri of the created resource: " + createdUri);\r
+                } else {\r
+                    boolean state = false;\r
+                    try {\r
+                        state = ocRepresentation.getValue(StringConstants.STATE);\r
+                        int power = ocRepresentation.getValue(StringConstants.POWER);\r
+                        String name = ocRepresentation.getValue(StringConstants.NAME);\r
+                        myLight.setState(state);\r
+                        myLight.setPower(power);\r
+                        myLight.setName(name);\r
+                    } catch (OcException e) {\r
+                        Log.e(TAG, e.getMessage());\r
+                    }\r
+                }\r
+                OcRepresentation rep = new OcRepresentation();\r
+                myLight.setState(true);\r
+                myLight.setPower(55);\r
+                try {\r
+                    rep.setValue(StringConstants.POWER, myLight.getPower());\r
+                    rep.setValue(StringConstants.STATE, myLight.getState());\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                doOnPost2(rep);\r
+            }\r
+\r
+            @Override\r
+            public void onPostFailed(Throwable throwable) {\r
+                if (throwable instanceof OcException) {\r
+                    OcException ocEx = (OcException) throwable;\r
+                    ErrorCode errCode = ocEx.getErrorCode();\r
+                    //do something based on errorCode\r
+                }\r
+                Log.e(TAG, throwable.toString());\r
+            }\r
+        };\r
+\r
+        OcRepresentation rep = new OcRepresentation();\r
+        myLight.setState(false);\r
+        myLight.setPower(105);\r
+        try {\r
+            rep.setValue(StringConstants.STATE, myLight.getState());\r
+            rep.setValue(StringConstants.POWER, myLight.getPower());\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        try {\r
+            curResource.post(rep, new HashMap<String, String>(), onPostListener);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * modify the current value of myLight and call doPostLightRepresentation\r
+     */\r
+    private void doPutLightRepresentation() {\r
+        // eventhandler for put()\r
+        OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {\r
+            @Override\r
+            public void onPutCompleted(List<OcHeaderOption> ocHeaderOptions,\r
+                                       OcRepresentation ocRepresentation) {\r
+                logMessage(TAG + "PUT resource was successful");\r
+                try {\r
+                    boolean state = ocRepresentation.getValue(StringConstants.STATE);\r
+                    int power = ocRepresentation.getValue(StringConstants.POWER);\r
+                    String name = ocRepresentation.getValue(StringConstants.NAME);\r
+                    myLight.setState(state);\r
+                    myLight.setPower(power);\r
+                    myLight.setName(name);\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+\r
+                logMessage(TAG + "onPutCompleted:\nState:" + myLight.getState() + "\nPower: " +\r
+                        myLight.getPower() + "\nName: " + myLight.getName());\r
+                doPostLightRepresentation();\r
+            }\r
+\r
+            @Override\r
+            public void onPutFailed(Throwable throwable) {\r
+\r
+                if (throwable instanceof OcException) {\r
+                    OcException ocEx = (OcException) throwable;\r
+                    ErrorCode errCode = ocEx.getErrorCode();\r
+                    //do something based on errorCode\r
+                }\r
+                Log.e(TAG, throwable.toString());\r
+            }\r
+        };\r
+\r
+        OcRepresentation rep = new OcRepresentation();\r
+        Log.d(TAG, "myLight settings: power = 15");\r
+        myLight.setState(true);\r
+        myLight.setPower(15);\r
+        try {\r
+            rep.setValue(StringConstants.STATE, myLight.getState());\r
+            rep.setValue(StringConstants.POWER, myLight.getPower());\r
+            rep.setValue(StringConstants.NAME, myLight.getName());\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        try {\r
+            Log.d(TAG, "before calling put");\r
+            curResource.put(rep, new HashMap<String, String>(), onPutListener);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        Log.d(TAG, "end of put call");\r
+    }\r
+\r
+    /**\r
+     * get the existing value of myLight and call doPutLightRepresentation() to modify the current values\r
+     */\r
+    private void doGetLightRepresentation() {\r
+        // eventhandler for get()\r
+        OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {\r
+            @Override\r
+            public void onGetCompleted(List<OcHeaderOption> headerOptionList,\r
+                                       OcRepresentation ocRepresentation) {\r
+                logMessage(TAG + "GET resource was successful " + StringConstants.STATE);\r
+                try {\r
+                    boolean state = ocRepresentation.getValue(StringConstants.STATE);\r
+                    int power = ocRepresentation.getValue(StringConstants.POWER);\r
+                    String name = ocRepresentation.getValue(StringConstants.NAME);\r
+                    myLight.setState(state);\r
+                    myLight.setPower(power);\r
+                    myLight.setName(name);\r
+                } catch (OcException e) {\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+                logMessage(TAG + "onGetCompleted\nState: " + myLight.getState() + "\nPower: " +\r
+                        myLight.getPower() + "\nName: " + myLight.getName());\r
+                doPutLightRepresentation();\r
+            }\r
+\r
+            @Override\r
+            public void onGetFailed(Throwable throwable) {\r
+                if (throwable instanceof OcException) {\r
+                    OcException ocEx = (OcException) throwable;\r
+                    ErrorCode errCode = ocEx.getErrorCode();\r
+                    //do something based on errorCode\r
+                }\r
+                Log.e(TAG, throwable.toString());\r
+            }\r
+        };\r
+\r
+        try {\r
+            curResource.get(new HashMap<String, String>(), onGetListener);\r
+        } catch (OcException e) {\r
+            logMessage(TAG + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * to display on SimpleClient screen\r
+     */\r
+    public class MessageReceiver extends BroadcastReceiver {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            final String message = intent.getStringExtra(StringConstants.MESSAGE);\r
+            logMessage(message);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected void onCreate(Bundle savedInstanceState) {\r
+        super.onCreate(savedInstanceState);\r
+        setContentView(R.layout.activity_main);\r
+        mEventsTextView = new TextView(this);\r
+        mEventsTextView.setMovementMethod(new ScrollingMovementMethod());\r
+        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);\r
+        layout.addView(mEventsTextView, new LinearLayout.LayoutParams(\r
+                LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)\r
+        );\r
+        myLight = new Light();\r
+\r
+        initOICStack();\r
+    }\r
+\r
+    @Override\r
+    public void logMessage(String text) {\r
+        logMsg(text);\r
+    }\r
+\r
+    public void logMsg(final String text) {\r
+        runOnUiThread(new Runnable() {\r
+            public void run() {\r
+                Message msg = new Message();\r
+                msg.obj = text;\r
+                mEventsTextView.append("\n");\r
+                mEventsTextView.append(text);\r
+            }\r
+        });\r
+        Log.i(TAG, text);\r
+        //to print on SimpleServer screen\r
+        Intent intent = new Intent("org.iotivity.base.examples.simpleclient");\r
+        intent.putExtra(StringConstants.MESSAGE, text);\r
+        sendBroadcast(intent);\r
+    }\r
+}\r
diff --git a/android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/StringConstants.java b/android/examples/simpleclient/src/main/java/org/iotivity/base/examples/simpleclient/StringConstants.java
new file mode 100644 (file)
index 0000000..f87c387
--- /dev/null
@@ -0,0 +1,17 @@
+package org.iotivity.base.examples.simpleclient;\r
+\r
+/**\r
+ * StringConstant contains the simpleclient specific constant values.  To add another supported\r
+ * Resource or Interface type to this app, begin by adding the new strings here, and then\r
+ * find the places throughout the app where Resource-specific case switches occur, and add\r
+ * the newly-supported type there.\r
+ */\r
+public interface StringConstants {\r
+    public static final String RESOURCE_URI0 = "/light0";\r
+    public static final String RESOURCE_URI1 = "/light1";\r
+    public static final String CREATED_URI = "createduri";\r
+    public static final String STATE = "state";\r
+    public static final String NAME = "name";\r
+    public static final String POWER = "power";\r
+    public static final String MESSAGE = "message";\r
+}\r
diff --git a/android/examples/simpleclient/src/main/res/drawable-hdpi/ic_launcher.png b/android/examples/simpleclient/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..96a442e
Binary files /dev/null and b/android/examples/simpleclient/src/main/res/drawable-hdpi/ic_launcher.png differ
diff --git a/android/examples/simpleclient/src/main/res/drawable-mdpi/ic_launcher.png b/android/examples/simpleclient/src/main/res/drawable-mdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..359047d
Binary files /dev/null and b/android/examples/simpleclient/src/main/res/drawable-mdpi/ic_launcher.png differ
diff --git a/android/examples/simpleclient/src/main/res/drawable-xhdpi/ic_launcher.png b/android/examples/simpleclient/src/main/res/drawable-xhdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..71c6d76
Binary files /dev/null and b/android/examples/simpleclient/src/main/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/android/examples/simpleclient/src/main/res/drawable-xxhdpi/ic_launcher.png b/android/examples/simpleclient/src/main/res/drawable-xxhdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..4df1894
Binary files /dev/null and b/android/examples/simpleclient/src/main/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/android/examples/simpleclient/src/main/res/layout/activity_main.xml b/android/examples/simpleclient/src/main/res/layout/activity_main.xml
new file mode 100755 (executable)
index 0000000..9aecf74
--- /dev/null
@@ -0,0 +1,18 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"\r
+    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"\r
+    android:paddingRight="@dimen/activity_horizontal_margin"\r
+    android:paddingTop="@dimen/activity_vertical_margin"\r
+    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"\r
+    android:label="@string/app_name">\r
+\r
+    <TextView android:text="@string/app_name" android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content" />\r
+\r
+    <LinearLayout\r
+        android:layout_width="fill_parent"\r
+        android:layout_height="fill_parent"\r
+        android:orientation="vertical"\r
+        android:id="@+id/linearLayout" >\r
+    </LinearLayout>\r
+</RelativeLayout>\r
diff --git a/android/examples/simpleclient/src/main/res/menu/menu_main.xml b/android/examples/simpleclient/src/main/res/menu/menu_main.xml
new file mode 100755 (executable)
index 0000000..a1045e9
--- /dev/null
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:app="http://schemas.android.com/apk/res-auto"\r
+    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">\r
+    <item android:id="@+id/action_settings" android:title="@string/action_settings"\r
+        android:orderInCategory="100" app:showAsAction="never" />\r
+</menu>\r
diff --git a/android/examples/simpleclient/src/main/res/values-w820dp/dimens.xml b/android/examples/simpleclient/src/main/res/values-w820dp/dimens.xml
new file mode 100755 (executable)
index 0000000..62df187
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>\r
+    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r
+         (such as screen margins) for screens with more than 820dp of available width. This\r
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->\r
+    <dimen name="activity_horizontal_margin">64dp</dimen>\r
+</resources>\r
diff --git a/android/examples/simpleclient/src/main/res/values/dimens.xml b/android/examples/simpleclient/src/main/res/values/dimens.xml
new file mode 100755 (executable)
index 0000000..295b5a9
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>\r
+    <!-- Default screen margins, per the Android Design guidelines. -->\r
+    <dimen name="activity_horizontal_margin">16dp</dimen>\r
+    <dimen name="activity_vertical_margin">16dp</dimen>\r
+</resources>\r
diff --git a/android/examples/simpleclient/src/main/res/values/strings.xml b/android/examples/simpleclient/src/main/res/values/strings.xml
new file mode 100755 (executable)
index 0000000..575b3e0
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<resources>\r
+\r
+    <string name="app_name">Starting Simple Client</string>\r
+    <string name="hello_world">Hello world!</string>\r
+    <string name="action_settings">Settings</string>\r
+\r
+</resources>\r
diff --git a/android/examples/simpleclient/src/main/res/values/styles.xml b/android/examples/simpleclient/src/main/res/values/styles.xml
new file mode 100755 (executable)
index 0000000..084b42b
--- /dev/null
@@ -0,0 +1,8 @@
+<resources>\r
+\r
+    <!-- Base application theme. -->\r
+    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">\r
+        <!-- Customize your theme here. -->\r
+    </style>\r
+\r
+</resources>\r
diff --git a/android/examples/simpleserver/.gitignore b/android/examples/simpleserver/.gitignore
new file mode 100644 (file)
index 0000000..3543521
--- /dev/null
@@ -0,0 +1 @@
+/build\r
diff --git a/android/examples/simpleserver/build.gradle b/android/examples/simpleserver/build.gradle
new file mode 100755 (executable)
index 0000000..3ecd031
--- /dev/null
@@ -0,0 +1,27 @@
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion "21.1.2"\r
+\r
+    defaultConfig {\r
+        applicationId "org.iotivity.base.examples.simpleserver"\r
+        minSdkVersion 19\r
+        targetSdkVersion 21\r
+        versionCode 1\r
+        versionName "1.0"\r
+    }\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+        }\r
+    }\r
+\r
+}\r
+\r
+dependencies {\r
+    //compile fileTree(dir: 'libs', include: ['*.so'])\r
+    compile project(':message')\r
+    compile 'com.android.support:appcompat-v7:21.0.3'\r
+}\r
diff --git a/android/examples/simpleserver/simpleserver.iml b/android/examples/simpleserver/simpleserver.iml
new file mode 100755 (executable)
index 0000000..c668fa1
--- /dev/null
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+  <component name="FacetManager">\r
+    <facet type="android-gradle" name="Android-Gradle">\r
+      <configuration>\r
+        <option name="GRADLE_PROJECT_PATH" value=":simpleserver" />\r
+      </configuration>\r
+    </facet>\r
+    <facet type="android" name="Android">\r
+      <configuration>\r
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
+        <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
+        <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />\r
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
+      </configuration>\r
+    </facet>\r
+  </component>\r
+  <component name="NewModuleRootManager" inherit-compiler-output="false">\r
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
+    <exclude-output />\r
+    <content url="file://$MODULE_DIR$">\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
+    </content>\r
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
+    <orderEntry type="sourceFolder" forTests="false" />\r
+    <orderEntry type="library" exported="" name="iotivity-x86-base-debug-unspecified" level="project" />\r
+    <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
+    <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
+    <orderEntry type="module" module-name="message" exported="" />\r
+  </component>\r
+</module>\r
+\r
diff --git a/android/examples/simpleserver/src/main/AndroidManifest.xml b/android/examples/simpleserver/src/main/AndroidManifest.xml
new file mode 100755 (executable)
index 0000000..43352f4
--- /dev/null
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
+    package="org.iotivity.base.examples.simpleserver"\r
+    xmlns:tools="http://schemas.android.com/tools">\r
+\r
+    <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>\r
+\r
+    <application\r
+        android:allowBackup="true"\r
+        android:icon="@drawable/ic_launcher"\r
+        android:label="@string/app_name"\r
+        android:theme="@style/AppTheme" >\r
+        <activity\r
+            android:name=".SimpleServer"\r
+            android:label="@string/app_name" >\r
+            <intent-filter>\r
+                <action android:name="android.intent.action.MAIN" />\r
+\r
+                <category android:name="android.intent.category.LAUNCHER" />\r
+            </intent-filter>\r
+        </activity>\r
+    </application>\r
+\r
+</manifest>\r
diff --git a/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/LightRepThread.java b/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/LightRepThread.java
new file mode 100644 (file)
index 0000000..0993995
--- /dev/null
@@ -0,0 +1,86 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+/*\r
+ * // Starts a new thread for OBSERVE. It increments the value of mPower by 10 every 3 seconds\r
+ */\r
+package org.iotivity.base.examples.simpleserver;\r
+\r
+import android.util.Log;\r
+\r
+import org.iotivity.base.EntityHandlerResult;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.OcResourceResponse;\r
+\r
+import java.util.List;\r
+\r
+/**\r
+ * LightRepThread\r
+ *\r
+ * Spawn a thread for OBSERVE. This increments the resource's power value by 10 every 3 seconds.\r
+ * If there is an observationList, call notifyListOfObservers(). Otherwise, call notifyAllObservers()\r
+ */\r
+public class LightRepThread extends Thread {\r
+    private static String TAG = "LightRepThread: ";\r
+\r
+    private LightResource mLightResource;\r
+    private List<Byte> mObservationList;\r
+    private static int count = 0;\r
+\r
+    LightRepThread(Object lr, List<Byte> observationList) {\r
+        mLightResource = (LightResource)lr;\r
+        mObservationList = observationList;\r
+    }\r
+\r
+    public void run() {\r
+        while(count < 20) {\r
+            try {\r
+                sleep(3000);\r
+            } catch (InterruptedException e) {\r
+                Log.e(TAG, e.getMessage());\r
+            }\r
+\r
+            // increment current power value by 10 every 3 seconds\r
+            mLightResource.setPower(mLightResource.getPower() + 10);\r
+            try {\r
+                // if observationList is not empty, call notifyListOfObservers\r
+                if (mObservationList.size() > 0) {\r
+                    OcResourceResponse ocResourceResponse = new OcResourceResponse();\r
+                    ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);\r
+                    ocResourceResponse.setResponseResult(EntityHandlerResult.OK);\r
+                    OcRepresentation r = mLightResource.get();\r
+                    ocResourceResponse.setResourceRepresentation\r
+                            (mLightResource.get(), OcPlatform.DEFAULT_INTERFACE);\r
+                    OcPlatform.notifyListOfObservers(mLightResource.getHandle(), mObservationList, ocResourceResponse);\r
+                } else {\r
+                    // notify all observers if mObservationList is empty\r
+                    OcPlatform.notifyAllObservers(mLightResource.getHandle());\r
+                }\r
+            } catch (OcException e) {\r
+                Log.e(TAG, e.getMessage());\r
+            }\r
+            ++count;\r
+        }\r
+    }\r
+}\r
diff --git a/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/LightResource.java b/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/LightResource.java
new file mode 100644 (file)
index 0000000..e8414a0
--- /dev/null
@@ -0,0 +1,308 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.simpleserver;\r
+\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.util.Log;\r
+\r
+import org.iotivity.base.EntityHandlerResult;\r
+import org.iotivity.base.ObservationInfo;\r
+import org.iotivity.base.OcException;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.OcResourceHandle;\r
+import org.iotivity.base.OcResourceRequest;\r
+import org.iotivity.base.OcResourceResponse;\r
+import org.iotivity.base.RequestHandlerFlag;\r
+import org.iotivity.base.RequestType;\r
+import org.iotivity.base.ResourceProperty;\r
+\r
+import java.util.EnumSet;\r
+import java.util.LinkedList;\r
+import java.util.List;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * LightResource\r
+ *\r
+ * class LightResource is the main class of the simpleServer. This creates resources and handles incoming requests from the client.\r
+ */\r
+public class LightResource implements IMessageLogger {\r
+    private Context mContext;\r
+    private static String TAG = "SimpleServer: ";\r
+\r
+    private String mName;\r
+    private Boolean mState;\r
+    private Integer mPower;\r
+    private OcRepresentation mLightRep;\r
+    private OcResourceHandle mResourceHandle;\r
+    private List<Byte> mObservationIds;\r
+    private static boolean doOnce; // used in POST\r
+    LightRepThread lightRepThread;\r
+\r
+    // constructor\r
+    LightResource(Context context) {\r
+        mContext = context;\r
+        mName = "John's light";\r
+        mState = false;\r
+        mPower = 0;\r
+        mObservationIds = new LinkedList<>();\r
+        mLightRep = new OcRepresentation();\r
+        try {\r
+            mLightRep.setValue(StringConstants.STATE, mState);\r
+            mLightRep.setValue(StringConstants.POWER, mPower);\r
+            mLightRep.setValue(StringConstants.NAME, mName);\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        doOnce = true; // used in post\r
+        lightRepThread = null;\r
+    }\r
+\r
+    //accessor methods\r
+    protected int getPower() {\r
+        return mPower;\r
+    }\r
+    protected void setPower(int power) {\r
+        mPower = power;\r
+    }\r
+    protected OcResourceHandle getHandle() {\r
+        return mResourceHandle;\r
+    }\r
+\r
+    /**\r
+     *  creates a resource. this method internally calls registerResource\r
+     * @return returns the OcResourceHandle after creating and registering the resource\r
+     */\r
+    protected OcResourceHandle createResource0() {\r
+        // entityhandler for registerResource\r
+        OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {\r
+            @Override\r
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {\r
+                // this is where the main logic of simpleserver is handled as different requests (GET, PUT, POST, OBSERVE, DELETE) are handled\r
+                return entityHandler(ocResourceRequest);\r
+            }\r
+        };\r
+\r
+        try {\r
+            mResourceHandle = OcPlatform.registerResource(StringConstants.RESOURCE_URI0, StringConstants.RESOURCE_TYPENAME,\r
+                StringConstants.RESOURCE_INTERFACE, eh,\r
+                EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "RegisterResource error. " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        logMessage(TAG + "Successfully registered resource");\r
+        return mResourceHandle;\r
+    }\r
+\r
+    /**\r
+     *  create another resource. this method internally calls registerResource\r
+     */\r
+    private void createResource1() {\r
+        // entityhandler for registerResource\r
+        OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {\r
+            @Override\r
+            public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {\r
+                // this is where the main logic of simpleserver is handled as different requests (GET, PUT, POST, OBSERVE, DELETE) are handled\r
+            return entityHandler(ocResourceRequest);\r
+            }\r
+        };\r
+\r
+        try {\r
+            OcPlatform.registerResource(StringConstants.RESOURCE_URI1, StringConstants.RESOURCE_TYPENAME,\r
+                StringConstants.RESOURCE_INTERFACE, eh,\r
+                EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));\r
+        } catch (OcException e) {\r
+            logMessage(TAG + "RegisterResource1 error: " + e.getMessage());\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        logMessage(TAG + "Successfully registered resource1");\r
+    }\r
+\r
+    /**\r
+     * post representation . Post can act like put or can create a new resource.\r
+     * Gets value from the representation and updates the internal state\r
+     * @param rep current OcRepresentation of the object\r
+     * @return updated OcRepresentation\r
+     */\r
+    private OcRepresentation post(OcRepresentation rep) {\r
+        //create a resource the first time\r
+        if (true == doOnce) {\r
+            createResource1();\r
+            OcRepresentation representation = rep;\r
+            try {\r
+                representation.setValue(StringConstants.CREATED_URI, StringConstants.RESOURCE_URI1);\r
+            } catch (OcException e) {\r
+                Log.e(TAG, e.getMessage());\r
+            }\r
+            doOnce = false;\r
+            return representation;\r
+        }\r
+        // from second time onwards, put\r
+        put(rep);\r
+        return get();\r
+    }\r
+\r
+    /**\r
+     * puts representation . Gets value from the representation and updates the internal state\r
+     * @param rep current OcRepresentation of the object\r
+     */\r
+    private void put(OcRepresentation rep) {\r
+        try {\r
+            mState = rep.getValue(StringConstants.STATE);\r
+            mPower = rep.getValue(StringConstants.POWER);\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        logMessage(TAG + "Put State: " +  mState + " Name: " + mName + " Power: " + mPower);\r
+    }\r
+\r
+    /**\r
+     *  gets the updated representation. Updates the representation with internal state before sending out\r
+     * @return OcRepresentation after updating the values of the lightRepresentation\r
+     */\r
+    protected OcRepresentation get() {\r
+        try {\r
+            mLightRep.setValue(StringConstants.STATE, mState);\r
+            mLightRep.setValue(StringConstants.POWER, mPower);\r
+            mLightRep.setValue(StringConstants.NAME, mName);\r
+        } catch (OcException e) {\r
+            Log.e(TAG, e.getMessage());\r
+        }\r
+        return mLightRep;\r
+    }\r
+\r
+    /**\r
+     * this is the main method which handles different incoming requests appropriately.\r
+     * Init is not supported currently.\r
+     * @param request OcResourceRequest from the client\r
+     * @return EntityHandlerResult depending on whether the request was handled successfully or not\r
+     */\r
+    private EntityHandlerResult entityHandler(OcResourceRequest request) {\r
+        EntityHandlerResult result = EntityHandlerResult.ERROR;\r
+        if (null != request) {\r
+            RequestType requestType = request.getRequestType();\r
+            EnumSet<RequestHandlerFlag> requestFlag = request.getRequestHandlerFlagSet();\r
+\r
+            if (requestFlag.contains(RequestHandlerFlag.INIT)) {\r
+                logMessage(TAG + "Init");\r
+            }\r
+            if (requestFlag.contains(RequestHandlerFlag.REQUEST)) {\r
+                try {\r
+                    logMessage(TAG + "Request");\r
+                    OcResourceResponse ocResourceResponse = new OcResourceResponse();\r
+                    ocResourceResponse.setRequestHandle(request.getRequestHandle());\r
+                    ocResourceResponse.setResourceHandle(request.getResourceHandle());\r
+\r
+                    switch (requestType) {\r
+                        // handle GET request\r
+                        case GET:\r
+                            logMessage("GET");\r
+                            ocResourceResponse.setResponseResult(EntityHandlerResult.OK);\r
+                            ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);\r
+                            ocResourceResponse.setResourceRepresentation(get());\r
+                            OcPlatform.sendResponse(ocResourceResponse);\r
+                            break;\r
+                        // handle PUT request\r
+                        case PUT:\r
+                            OcRepresentation rep = request.getResourceRepresentation();\r
+                            put(rep);\r
+                            ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);\r
+                            ocResourceResponse.setResponseResult(EntityHandlerResult.OK);\r
+                            ocResourceResponse.setResourceRepresentation(get());\r
+                            OcPlatform.sendResponse(ocResourceResponse);\r
+                            break;\r
+                        // handle POST request\r
+                        case POST:\r
+                            rep = request.getResourceRepresentation();\r
+                            OcRepresentation rep_post = post(rep);\r
+                            ocResourceResponse.setResourceRepresentation(rep_post);\r
+                            ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);\r
+                            if (rep_post.hasAttribute(StringConstants.CREATED_URI)) {\r
+                                String createdUri = rep_post.getValue(StringConstants.CREATED_URI);\r
+                                if (createdUri.equals(StringConstants.RESOURCE_URI1)) {\r
+                                    ocResourceResponse.setNewResourceUri(createdUri);\r
+                                    ocResourceResponse.setResponseResult\r
+                                            (EntityHandlerResult.RESOURCE_CREATED);\r
+                                } else {\r
+                                    ocResourceResponse.setResponseResult(EntityHandlerResult.OK);\r
+                                }\r
+                            }\r
+                            OcPlatform.sendResponse(ocResourceResponse);\r
+                            break;\r
+                        // handle DELETE request\r
+                        case DELETE:\r
+                            logMessage(TAG + "DELETE");\r
+                            OcPlatform.unregisterResource(getHandle());\r
+                            OcPlatform.unregisterResource(getHandle());\r
+                            break;\r
+\r
+                    }\r
+\r
+                    result = EntityHandlerResult.OK;\r
+                } catch(OcException e) {\r
+                    logMessage(TAG + "Error in Request " + e.getMessage());\r
+                    Log.e(TAG, e.getMessage());\r
+                }\r
+            }\r
+            // handle OBSERVER request\r
+            if (requestFlag.contains(RequestHandlerFlag.OBSERVER)) {\r
+                logMessage(TAG + "OBSERVER");\r
+                ObservationInfo observationInfo = request.getObservationInfo();\r
+\r
+                switch (observationInfo.getObserveAction()) {\r
+                    case REGISTER:\r
+                        synchronized (mObservationIds) {\r
+                            mObservationIds.add(observationInfo.getOcObservationId());\r
+                        }\r
+                        break;\r
+                    case UNREGISTER:\r
+                        synchronized (mObservationIds) {\r
+                            mObservationIds.remove(observationInfo.getOcObservationId());\r
+                        }\r
+                        break;\r
+                }\r
+                if (null == lightRepThread) {\r
+                    lightRepThread = new LightRepThread(this, mObservationIds);\r
+                    lightRepThread.run();\r
+                }\r
+                result = EntityHandlerResult.OK;\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public void logMessage(String msg) {\r
+        logMsg(msg);\r
+    }\r
+\r
+    public void logMsg(final String text) {\r
+        Intent intent = new Intent("org.iotivity.base.examples.simpleserver");\r
+        intent.putExtra(StringConstants.MESSAGE, text);\r
+        mContext.sendBroadcast(intent);\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/SimpleServer.java b/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/SimpleServer.java
new file mode 100644 (file)
index 0000000..31b5c6a
--- /dev/null
@@ -0,0 +1,145 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.base.examples.simpleserver;\r
+\r
+import android.app.Activity;\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.content.IntentFilter;\r
+import android.os.Bundle;\r
+import android.os.Message;\r
+import android.support.v4.content.LocalBroadcastManager;\r
+import android.text.method.ScrollingMovementMethod;\r
+import android.util.Log;\r
+import android.view.Menu;\r
+import android.view.MenuItem;\r
+import android.widget.LinearLayout;\r
+import android.widget.TextView;\r
+\r
+import org.iotivity.base.ModeType;\r
+import org.iotivity.base.OcPlatform;\r
+import org.iotivity.base.OcRepresentation;\r
+import org.iotivity.base.PlatformConfig;\r
+import org.iotivity.base.QualityOfService;\r
+import org.iotivity.base.ServiceType;\r
+\r
+import base.iotivity.org.examples.message.IMessageLogger;\r
+\r
+/**\r
+ * SimpleServer\r
+ *\r
+ * SimpleServer instantiates a TextView and creates and configures OICPlatform.\r
+ * It also creates a LightResource and waits for the incoming client requests to handle specific scenarios.\r
+ * This implements IMessageLogger to display messages on the screen\r
+ */\r
+\r
+public class SimpleServer extends Activity implements IMessageLogger {\r
+    private final static String TAG = "SimpleServer: ";\r
+    private TextView mEventsTextView;\r
+    private MessageReceiver mMessageReceiver = new MessageReceiver();\r
+\r
+    @Override\r
+    protected void onCreate(Bundle savedInstanceState) {\r
+        super.onCreate(savedInstanceState);\r
+        setContentView(R.layout.activity_main);\r
+        registerReceiver(mMessageReceiver, new IntentFilter("org.iotivity.base.examples.simpleserver"));\r
+\r
+        mEventsTextView = new TextView(this);\r
+        mEventsTextView.setMovementMethod(new ScrollingMovementMethod());\r
+        LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout);\r
+        layout.addView(mEventsTextView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));\r
+\r
+        OcRepresentation rep = new OcRepresentation();\r
+        rep.setValueBool("test", false);\r
+        boolean result = rep.getValueBool("test");\r
+\r
+        initOICStack();\r
+    }\r
+\r
+    /**\r
+     * configure OIC platform and call findResource\r
+     */\r
+    private void initOICStack() {\r
+        //create platform config\r
+        PlatformConfig cfg = new PlatformConfig(\r
+                this,\r
+                ServiceType.IN_PROC,\r
+                ModeType.SERVER,\r
+                "0.0.0.0", // bind to all available interfaces\r
+                0,\r
+                QualityOfService.LOW);\r
+        OcPlatform.Configure(cfg);\r
+        // Create instance of lightResource\r
+        LightResource myLight = new LightResource(this);\r
+        // create and register a resource\r
+        myLight.createResource0();\r
+    }\r
+\r
+    public class MessageReceiver extends BroadcastReceiver {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            final String message = intent.getStringExtra(StringConstants.MESSAGE);\r
+            logMessage(message);\r
+        }\r
+    }\r
+\r
+    public void logMessage(final String text) {\r
+        runOnUiThread(new Runnable() {\r
+            public void run() {\r
+                final Message msg = new Message();\r
+                msg.obj = text;\r
+                mEventsTextView.append("\n");\r
+                mEventsTextView.append(text);\r
+            }\r
+        });\r
+        Log.i(TAG, text);\r
+    }\r
+\r
+    @Override\r
+    public boolean onCreateOptionsMenu(Menu menu) {\r
+        getMenuInflater().inflate(R.menu.menu_main, menu);\r
+        return true;\r
+    }\r
+\r
+    @Override\r
+    public boolean onOptionsItemSelected(MenuItem item) {\r
+        int id = item.getItemId();\r
+        if (id == R.id.action_settings) {\r
+            return true;\r
+        }\r
+        return super.onOptionsItemSelected(item);\r
+    }\r
+\r
+    @Override\r
+    public void onDestroy() {\r
+        super.onDestroy();\r
+        onStop();\r
+    }\r
+\r
+    @Override\r
+    protected void onStop() {\r
+        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);\r
+        super.onStop();\r
+    }\r
+}
\ No newline at end of file
diff --git a/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/StringConstants.java b/android/examples/simpleserver/src/main/java/org/iotivity/base/examples/simpleserver/StringConstants.java
new file mode 100644 (file)
index 0000000..98f33d0
--- /dev/null
@@ -0,0 +1,21 @@
+package org.iotivity.base.examples.simpleserver;\r
+\r
+import org.iotivity.base.OcPlatform;\r
+/**\r
+ * StringConstants contains the simpleserver specific constant values.  To add another supported\r
+ * Resource or Interface type to this app, begin by adding the new strings here, and then\r
+ * find the places throughout the app where Resource-specific case switches occur, and add\r
+ * the newly-supported type there.\r
+ */\r
+public interface StringConstants {\r
+    public static final String RESOURCE_URI0 = "/light0";\r
+    public static final String RESOURCE_URI1 = "/light1";\r
+    public static final String RESOURCE_TYPENAME = "core.light";\r
+    public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE; //resource interface\r
+    public static final String CREATED_URI = "createduri";\r
+    public static final String STATE = "state";\r
+    public static final String NAME = "name";\r
+    public static final String POWER = "power";\r
+    public static final String MESSAGE = "message";\r
+    public static final int ERROR_CODE = 200;\r
+}\r
diff --git a/android/examples/simpleserver/src/main/res/drawable-hdpi/ic_launcher.png b/android/examples/simpleserver/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..96a442e
Binary files /dev/null and b/android/examples/simpleserver/src/main/res/drawable-hdpi/ic_launcher.png differ
diff --git a/android/examples/simpleserver/src/main/res/drawable-mdpi/ic_launcher.png b/android/examples/simpleserver/src/main/res/drawable-mdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..359047d
Binary files /dev/null and b/android/examples/simpleserver/src/main/res/drawable-mdpi/ic_launcher.png differ
diff --git a/android/examples/simpleserver/src/main/res/drawable-xhdpi/ic_launcher.png b/android/examples/simpleserver/src/main/res/drawable-xhdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..71c6d76
Binary files /dev/null and b/android/examples/simpleserver/src/main/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/android/examples/simpleserver/src/main/res/drawable-xxhdpi/ic_launcher.png b/android/examples/simpleserver/src/main/res/drawable-xxhdpi/ic_launcher.png
new file mode 100755 (executable)
index 0000000..4df1894
Binary files /dev/null and b/android/examples/simpleserver/src/main/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/android/examples/simpleserver/src/main/res/layout/activity_main.xml b/android/examples/simpleserver/src/main/res/layout/activity_main.xml
new file mode 100755 (executable)
index 0000000..ebe6ef7
--- /dev/null
@@ -0,0 +1,31 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"\r
+    android:layout_height="fill_parent" android:paddingLeft="@dimen/activity_horizontal_margin"\r
+    android:paddingRight="@dimen/activity_horizontal_margin"\r
+    android:paddingTop="@dimen/activity_vertical_margin"\r
+    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"\r
+    android:label="@string/app_name">\r
+\r
+    <ScrollView\r
+        android:layout_width="match_parent"\r
+        android:layout_height="match_parent"\r
+        android:id="@+id/scroll">\r
+\r
+        <TextView android:text="@string/simpleServer" android:layout_width="match_parent"\r
+            android:layout_height="match_parent"\r
+            android:id="@+id/textView"\r
+            android:scrollbars="vertical"\r
+            android:maxLines="10"/>\r
+\r
+    </ScrollView>\r
+\r
+    <LinearLayout\r
+        android:layout_width="match_parent"\r
+        android:layout_height="match_parent"\r
+        android:orientation="vertical"\r
+        android:id="@+id/linearLayout" >\r
+    </LinearLayout>\r
+\r
+\r
+</RelativeLayout>\r
+\r
diff --git a/android/examples/simpleserver/src/main/res/menu/menu_main.xml b/android/examples/simpleserver/src/main/res/menu/menu_main.xml
new file mode 100755 (executable)
index 0000000..a1045e9
--- /dev/null
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:app="http://schemas.android.com/apk/res-auto"\r
+    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">\r
+    <item android:id="@+id/action_settings" android:title="@string/action_settings"\r
+        android:orderInCategory="100" app:showAsAction="never" />\r
+</menu>\r
diff --git a/android/examples/simpleserver/src/main/res/values-w820dp/dimens.xml b/android/examples/simpleserver/src/main/res/values-w820dp/dimens.xml
new file mode 100755 (executable)
index 0000000..62df187
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>\r
+    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r
+         (such as screen margins) for screens with more than 820dp of available width. This\r
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->\r
+    <dimen name="activity_horizontal_margin">64dp</dimen>\r
+</resources>\r
diff --git a/android/examples/simpleserver/src/main/res/values/dimens.xml b/android/examples/simpleserver/src/main/res/values/dimens.xml
new file mode 100755 (executable)
index 0000000..295b5a9
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>\r
+    <!-- Default screen margins, per the Android Design guidelines. -->\r
+    <dimen name="activity_horizontal_margin">16dp</dimen>\r
+    <dimen name="activity_vertical_margin">16dp</dimen>\r
+</resources>\r
diff --git a/android/examples/simpleserver/src/main/res/values/strings.xml b/android/examples/simpleserver/src/main/res/values/strings.xml
new file mode 100755 (executable)
index 0000000..4414f1d
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<resources>\r
+\r
+    <string name="app_name">SimpleServer</string>\r
+    <string name="simpleServer">Starting Simple Server...</string>\r
+    <string name="action_settings">Settings</string>\r
+\r
+</resources>\r
diff --git a/android/examples/simpleserver/src/main/res/values/styles.xml b/android/examples/simpleserver/src/main/res/values/styles.xml
new file mode 100755 (executable)
index 0000000..084b42b
--- /dev/null
@@ -0,0 +1,8 @@
+<resources>\r
+\r
+    <!-- Base application theme. -->\r
+    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">\r
+        <!-- Customize your theme here. -->\r
+    </style>\r
+\r
+</resources>\r
index 4ab2aff..2f40e74 100644 (file)
@@ -1,11 +1,49 @@
+#******************************************************************
+#
+# 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
 ##
 Import('env')
 
-env.ImportLib('Time')
-if env.get('NET') == 'Ethernet':
+# Add 'SHIELD' build option, let user select board network connection type
+vars = Variables()
+if 'IP' in env.get('TARGET_TRANSPORT'):
+       vars.Add(EnumVariable('SHIELD', 'Network connection type', 'WIFI', ['ETH', 'WIFI']))
+elif 'BLE' in env.get('TARGET_TRANSPORT'):
+       vars.Add(EnumVariable('SHIELD', 'Network connection type', 'RBL_NRF8001', ['RBL_NRF8001']))
+vars.Update(env)
+Help(vars.GenerateHelpText(env))
+
+env.ImportLib('SPI')
+if 'ETH' in env.get('SHIELD'):
        env.ImportLib('Ethernet')
-else:
+if 'WIFI' in env.get('SHIELD'):
        env.ImportLib('WiFi')
-env.ImportLib('SPI')
\ No newline at end of file
+       env.AppendUnique(CPPDEFINES = ['ARDUINOWIFI'])
+if 'RBL_NRF8001' in env.get('SHIELD'):
+       env.ImportLib('BLE')
+       env.ImportLib('RBL_nRF8001')
+
+env.ImportLib('Time/Time')
+# we have variety of macros for arduino!!
+env.AppendUnique(CPPDEFINES = ['WITH_ARDUINO', '__ARDUINO__'])
+if env.get('LOGGING'):
+       env.AppendUnique(CPPDEFINES = ['TB_LOG'])
index 536331c..19c3440 100755 (executable)
@@ -17,37 +17,35 @@ function build()
         then
                echo "*********** Build for linux *************"
                scons RELEASE=$3
+
+               echo "*********** Build for linux with Security*************"
+               scons RELEASE=$3 SECURED=1
        fi
 
        # Note: for android, as oic-resource uses C++11 feature stoi and to_string,
        # it requires gcc-4.9, currently only android-ndk-r10(for linux)
        # and windows android-ndk-r10(64bit target version) support these features.
-       if [ "$BUILD_FOR_ANDROID" = "true" ]
-               then
-
-               echo "*********** Build Boost for android ***********"
-               pushd extlibs
-               ./buildDependencies.sh
-               popd
+       echo "*********** Build Boost for android ***********"
+       # disable parallel build for android as gradle depends on scons to finish first
+       export SCONSFLAGS="-Q"
 
-               echo "*********** Build for android x86 *************"
-               scons TARGET_OS=android TARGET_ARCH=x86 ANDROID_NDK=$1 RELEASE=$3
+       echo "*********** Build for android x86 *************"
+       scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=$3 TARGET_TRANSPORT=IP
 
-               echo "*********** Build for android armeabi *************"
-               scons TARGET_OS=android TARGET_ARCH=armeabi ANDROID_NDK=$1 RELEASE=$3
+       echo "*********** Build for android armeabi *************"
+       scons TARGET_OS=android TARGET_ARCH=armeabi RELEASE=$3 TARGET_TRANSPORT=IP
 
-               echo "*********** Build for android armeabi-v7a *************"
-               scons TARGET_OS=android TARGET_ARCH=armeabi-v7a ANDROID_NDK=$1 RELEASE=$3
+       # enable parallel build
+       export SCONSFLAGS="-Q -j 4"
 
-               echo "*********** Build for android armeabi-v7a-hard *************"
-               scons TARGET_OS=android TARGET_ARCH=armeabi-v7a-hard ANDROID_NDK=$1 RELEASE=$3
-       fi
-       
        echo "*********** Build for arduino avr *************"
-       scons TARGET_OS=arduino TARGET_ARCH=avr ARDUINO_HOME=$2 RELEASE=$3
+       scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=IP SHIELD=ETH RELEASE=$3
+       scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=IP SHIELD=WIFI RELEASE=$3
 
        echo "*********** Build for arduino arm *************"
-       scons TARGET_OS=arduino TARGET_ARCH=arm ARDUINO_HOME=$2 RELEASE=$3
+       scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=IP SHIELD=ETH RELEASE=$3
+       scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=IP SHIELD=WIFI RELEASE=$3
+
 
        if [ $(uname -s) = "Darwin" ]
        then
@@ -75,7 +73,7 @@ function  help()
 {
        echo "Usage:"
         echo "  build:"
-        echo "     `basename $0` <path-to-android-ndk> <path-to-arduino-home>"
+        echo "     `basename $0` <path-to-android-ndk>"
         echo "  clean:"
         echo "     `basename $0` -c"
 }
@@ -100,4 +98,9 @@ fi
 export SCONSFLAGS="-Q -j 4"
 build $1 $2 true
 build $1 $2 false
+scons resource RELEASE=false -c
+scons resource LOGGING=false RELEASE=false
+scons resource TEST=1 RELEASE=false
 echo "===================== done ====================="
+
+
index db23ac3..16a81f9 100644 (file)
@@ -15,14 +15,14 @@ host_target_map = {
 # Map of os and allowed archs (os: allowed archs)
 os_arch_map = {
                'linux': ['x86', 'x86_64', 'arm', 'arm64'],
-               'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
+               'tizen': ['x86', 'x86_64', 'arm', 'arm64', 'armeabi-v7a'],
                'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
                'windows': ['x86', 'amd64', 'arm'],
                'winrt': ['arm'],
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
-               'yocto': ['x86', 'x86_64'],
+               'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
                }
 
 host = platform.system().lower()
@@ -46,18 +46,42 @@ if default_arch not in os_arch_map[target_os]:
 
 target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
 
+# True if binary needs to be installed on board. (Might need root permissions)
+# set to 'no', 'false' or 0 for only compilation
+require_upload = ARGUMENTS.get('UPLOAD', False)
+
+if ARGUMENTS.get('TEST'):
+       logging_default = False
+else:
+       logging_default = (ARGUMENTS.get('RELEASE', True) == 'false')
+
+
+
 ######################################################################
 # Common build options (release, target os, target arch)
 ######################################################################
+targets_disallow_multitransport = ['arduino']
+
 help_vars = Variables()
+help_vars.Add(BoolVariable('VERBOSE', 'Show compilation', False))
 help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
 help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
-help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
 
+if target_os in targets_disallow_multitransport:
+    help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP']))
+else:
+    help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP']))
+
+help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
+help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
+help_vars.Add(EnumVariable('TEST', 'Run unit tests', '0', allowed_values=('0', '1')))
+help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', logging_default))
+help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
+help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
 ######################################################################
 # Platform(build target) specific options: SDK/NDK & toolchain
 ######################################################################
-targets_support_cc = ['linux', 'arduino']
+targets_support_cc = ['linux', 'arduino', 'tizen']
 
 if target_os in targets_support_cc:
        # Set cross compile toolchain
@@ -82,6 +106,12 @@ tc_set_msg = '''
 * cause inexplicable errors.                                                  *
 *******************************************************************************
 '''
+if env.get('VERBOSE') == False:
+       env['CCCOMSTR'] = "Compiling $TARGET"
+       env['CXXCOMSTR'] = "Compiling $TARGET"
+       env['LINKCOMSTR'] = "Linking $TARGET"
+       env['ARCOMSTR'] = "Archiving $TARGET"
+       env['RANLIBCOMSTR'] = "Indexing Archive $TARGET"
 
 if target_os in targets_support_cc:
        prefix = env.get('TC_PREFIX')
@@ -144,8 +174,10 @@ def __install(ienv, targets, name):
        Alias(name, i_n)
        env.AppendUnique(TS = [name])
 
-def __append_target(ienv, target):
-       env.AppendUnique(TS = [target])
+def __append_target(ienv, name, targets = None):
+       if targets:
+               env.Alias(name, targets)
+       env.AppendUnique(TS = [name])
 
 def __print_targets(env):
        Help('''
@@ -166,6 +198,7 @@ env.AddMethod(__src_to_obj, 'SrcToObj')
 env.AddMethod(__append_target, 'AppendTarget')
 env.AddMethod(__install, 'InstallTarget')
 env.SetDir(env.GetLaunchDir())
+env['ROOT_DIR']=env.GetLaunchDir()+'/..'
 
 Export('env')
 
@@ -174,8 +207,8 @@ Export('env')
 ######################################################################
 if target_os == "yocto":
     '''
-    This code injects Yocto cross-compilation tools+flags into scons' 
-    build environment in order to invoke the relevant tools while 
+    This code injects Yocto cross-compilation tools+flags into scons'
+    build environment in order to invoke the relevant tools while
     performing a build.
     '''
     import os.path
@@ -203,6 +236,7 @@ if target_os == "yocto":
                     if os.path.isfile(os.path.join(path, tools[tool])):
                         env[tool] = os.path.join(path, os.environ[tool])
                         break
+        env['CROSS_COMPILE'] = target_prefix[:len(target_prefix) - 1]
     except:
         print "ERROR in Yocto cross-toolchain environment"
         Exit(1)
@@ -213,19 +247,27 @@ if target_os == "yocto":
     env['TARGET_OS'] = 'linux'
     '''
     We want to preserve debug symbols to allow BitBake to generate both DEBUG and
-    RELEASE packages for OIC. 
+    RELEASE packages for OIC.
+    '''
+    env.AppendUnique(CCFLAGS = ['-g'])
+    '''
+    Additional flags to pass to the Yocto toolchain.
     '''
-    env['CCFLAGS'].append('-g')
+    if env.get('RELEASE'):
+        env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+    if env.get('LOGGING'):
+        env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+    env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE'])
+    env.AppendUnique(CFLAGS = ['-std=gnu99'])
+    env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+    env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
     Export('env')
 else:
     '''
     If target_os is not Yocto, continue with the regular build process
     '''
     # Load config of target os
-    if target_os in ['linux', 'tizen']:
-               env.SConscript('linux/SConscript')
-    else:
-               env.SConscript(target_os + '/SConscript')
+    env.SConscript(target_os + '/SConscript')
 
 # Delete the temp files of configuration
 if env.GetOption('clean'):
@@ -233,7 +275,30 @@ if env.GetOption('clean'):
 
        if os.path.exists(dir + '/config.log'):
                Execute(Delete(dir + '/config.log'))
+       if os.path.exists(dir + '/.sconsign.dblite'):
                Execute(Delete(dir + '/.sconsign.dblite'))
+       if os.path.exists(dir + '/.sconf_temp'):
                Execute(Delete(dir + '/.sconf_temp'))
 
+######################################################################
+# Check for PThreads support
+######################################################################
+import iotivityconfig
+from iotivityconfig import *
+
+conf = Configure(env,
+        custom_tests =
+        {
+            'CheckPThreadsSupport' : iotivityconfig.check_pthreads
+        } )
+
+# Identify whether we have pthreads support, which is necessary for
+# threading and mutexes.  This will set the environment variable
+# POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
+conf.CheckPThreadsSupport()
+
+env = conf.Finish()
+######################################################################
+
+env.SConscript('external_libs.scons')
 Return('env')
index 4ae0fe4..b90beb0 100644 (file)
@@ -6,22 +6,42 @@ import platform
 import subprocess
 
 Import('env')
+SConscript('../external_libs.scons')
+SConscript('../../extlibs/android/ndk/SConscript')
+SConscript('../../extlibs/android/gradle/SConscript')
+SConscript('../../extlibs/android/sdk/SConscript')
 
 help_vars = Variables()
-help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK root directory', os.environ.get('ANDROID_NDK')))
-help_vars.Update(env)
-Help(help_vars.GenerateHelpText(env))
+help_vars.Add(PathVariable('ANDROID_GRADLE', 'Android Gradle directory', os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'gradle', 'gradle-2.2.1/bin/gradle')))
+help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK root directory', os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'ndk', 'android-ndk-r10d')))
 
-android_ndk = env.get('ANDROID_NDK')
-if not android_ndk:
+if env.get('ANDROID_NDK'):
+       android_ndk = env.get('ANDROID_NDK')
+else:
        print '''
-*************************************** Error *********************************
-*    Android NDK path isn't set, you can set enviornment variable ANDROID_NDK *
-* or add it in command line as:                                               *
+*************************************** Info **********************************
+*    Android NDK path isn't set, the default will be used. You can set        *
+* environment variable ANDROID_NDK or add it in command line as:              *
 *      # scons ANDROID_NDK=<path to android NDK> ...                          *
 *******************************************************************************
 '''
-       Exit(1)
+       android_ndk = os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'ndk', 'android-ndk-r10d')
+
+if env.get('ANDROID_GRADLE'):
+       android_gradle = env.get('ANDROID_GRADLE')
+else:
+       print '''
+*************************************** Info **********************************
+*    Android Gradle path isn't set, the default will be used. You can set     *
+* environment variable ANDROID_GRADLE or add it in command line as:           *
+*      # scons ANDROID_GRADLE=<path to android GRADLE> ...                    *
+*******************************************************************************
+'''
+       android_gradle = os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'gradle', 'gradle-2.2.1', 'bin', 'gradle')
+
+help_vars.Update(env)
+Help(help_vars.GenerateHelpText(env))
+src_dir = env.get('SRC_DIR')
 
 # Overwrite suffixes and prefixes
 if env['HOST_OS'] == 'win32':
@@ -45,6 +65,7 @@ elif platform.system().lower() == 'darwin':
 
 # Android build system default cofig
 env.AppendUnique(CPPDEFINES = ['ANDROID'])
+env.AppendUnique(CFLAGS = ['-std=c99'])
 env.AppendUnique(SHCFLAGS = ['-Wa,--noexecstack'])
 env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections', '-Wl,-z,nocopyreloc'])
 
@@ -65,15 +86,17 @@ if not os.path.isfile(ndk_build_cmd):
 ''' % android_ndk
        Exit(1)
 
-ANDROID_HOME = os.environ.get('ANDROID_HOME')
-if ANDROID_HOME is not None:
-       ANDROID_HOME = os.path.abspath(ANDROID_HOME)
+# ANDROID_HOME build option
+help_vars = Variables()
+help_vars.Add(PathVariable('ANDROID_HOME', 'ANDROID SDK root directory', os.environ.get('ANDROID_HOME')))
+help_vars.Update(env)
+Help(help_vars.GenerateHelpText(env))
 
-if ANDROID_HOME is None or not os.path.exists(ANDROID_HOME):
-       print '''
-*************************************** Warning *******************************
-*   Enviornment variable ANDROID_HOME is not set properly. It should be the   *
-* root directory of android sdk. If you'd like build Java code, it's required.*
+print '''
+*************************************** Info **********************************
+*   Environment variable ANDROID_HOME will use default value. To override     *
+* root directory of android sdk, please specify ANDROID_HOME as follows:      *
+*       scons ANDROID_HOME= <path to Android SDK>                             *
 *******************************************************************************
 '''
 
@@ -81,13 +104,14 @@ target_arch = env.get('TARGET_ARCH')
 
 # Android ndk early version doesn't support C++11. Detect the toolchain version
 # to make sure proper toolchain is used
-for tc_ver in ['4.9', '4.8', '4.7', '']:
+for tc_ver in ['4.7', '4.8', '4.9', '']:
        if os.path.exists(android_ndk + '/toolchains/x86-' + tc_ver):
                break
 
 cmd = [ndk_build_cmd]
 cmd.append('APP_ABI=' + target_arch)
-cmd.append('APP_STL=gnustl_static')
+cmd.append('APP_PLATFORM=android-21')
+cmd.append('APP_STL=gnustl_shared')
 if env.get('RELEASE'):
        cmd.append('APP_OPTIM=release')
 else:
@@ -126,27 +150,46 @@ for flags in p.stdout.readlines():
        elif cmp(flags[0:8], 'SYSROOT=') == 0:
                sysroot = flags[8:].strip()
                env.AppendUnique(LINKFLAGS = ['--sysroot=' + sysroot])
-               env.AppendUnique(LIBPATH = [sysroot + '/usr/lib'])
 
        elif cmp(flags[0:8], 'LDFLAGS=') == 0:
                env.AppendUnique(LINKFLAGS = Split(flags[8:]))
 
        elif cmp(flags[0:7], 'TC_VER=') == 0:  # set gnustl library path
                ver = flags[7:].strip()
-               env.AppendUnique(LIBPATH = [android_ndk + '/sources/cxx-stl/gnu-libstdc++/'
-                               + ver + '/libs/' + target_arch])
+               stl_path = android_ndk + '/sources/cxx-stl/gnu-libstdc++/' + ver + '/libs/' + target_arch
+               if target_arch in ['armeabi', 'armeabi-v7a', 'armeabi-v7a-hard']:
+                       stl_path = stl_path + '/thumb/'
+
+               env.AppendUnique(LIBPATH = [stl_path])
+               env.Install(env.get('BUILD_DIR'), stl_path + '/libgnustl_shared.so')
 
        elif cmp(flags[0:9], 'PLATFORM=') == 0:  # get target platform: android-x
                platform_ver = flags[9+8:].strip()
                if not platform_ver.isdigit():
                        platform_ver = ''
 
+
+       elif cmp(flags[0:9], 'PLATFORM=') == 0:  # get target platform: android-x
+               platform_ver = flags[9+8:].strip()
+               if not platform_ver.isdigit():
+                       platform_ver = ''
+
+
+       elif cmp(flags[0:9], 'PLATFORM=') == 0:  # get target platform: android-x
+               platform_ver = flags[9+8:].strip()
+               if not platform_ver.isdigit():
+                       platform_ver = ''
+
+# Determine dependency faux SYS_ROOT
+dep_sys_root = os.path.join(env.get('SRC_DIR'), 'dep', 'android', target_arch, 'usr')
+dep_src_dir =  os.path.join(dep_sys_root, 'include')
+dep_lib_dir =  os.path.join(dep_sys_root, 'lib')
+
+env['DEP_SYS_ROOT'] = dep_sys_root
+
 # Add external libraries including boost
-env.AppendUnique(CPPPATH = [env.get('SRC_DIR') + '/out/android/include' ])
-if target_arch == 'x86':
-       env.AppendUnique(LIBPATH = [env.get('SRC_DIR') + '/out/android/lib/x86'])
-else:
-       env.AppendUnique(LIBPATH = [env.get('SRC_DIR') + '/out/android/lib/arm-linux-androideabi'])
+env.AppendUnique(CPPPATH = [ dep_src_dir ])
+env.AppendUnique(LIBPATH = [ dep_lib_dir ])
 
 ######################################################################
 # Set release/debug flags
@@ -158,6 +201,21 @@ if env.get('RELEASE'):
 else:
        env.AppendUnique(CCFLAGS = ['-g'])
 
+if env.get('LOGGING'):
+        env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+
+env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__ANDROID__'])
+env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+#env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
+
+env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+env.AppendUnique(LIBPATH = [src_dir + '/resource/csdk/connectivity/lib/android'])
+env.AppendUnique(LIBS = ['log', 'coap'])
+
+if env.get('SECURED') == '1':
+       env.AppendUnique(LIBS = ['tinydtls'])
+
 # From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'.
 # Due to the limitation of Scons, it's required to added it into the command line
 # directly (otherwise, it will also be added when build share library)
@@ -166,7 +224,11 @@ env.Replace(CXXCOM = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SO
 env.Replace(LINKCOM = '$LINK -o $TARGET -pie $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS')
 
 # Fix android-ndk compatibility issue, make applications build on new NDK can run on old platform
-#if platform_ver == '' or int(platform_ver) > 20:
-#      SConscript('compatibility/c_compat.scons')
-#
-#SConscript('compatibility/cpp11_compat.scons')
+if platform_ver == '' or int(platform_ver) > 20:
+       SConscript('compatibility/c_compat.scons')
+
+SConscript('compatibility/cpp11_compat.scons')
+
+# Make sure that boost for android is available
+SConscript(env.get('SRC_DIR') + '/extlibs/boost/SConscript')
+SConscript(env.get('SRC_DIR') + '/extlibs/expat/SConscript')
index dedc927..3d27cf9 100644 (file)
@@ -57,6 +57,12 @@ namespace std {
         return os.str();
     }
 
+    std::string to_string(long t) {
+        std::ostringstream os;
+            os << t;
+        return os.str();
+    }
+
     std::string to_string(double t) {
         std::ostringstream os;
             os << t;
index 78af522..adaa9fb 100644 (file)
@@ -15,6 +15,7 @@ namespace std {
     long double stold(const string& s);
 
     std::string to_string(int i);
+    std::string to_string(long t);
     std::string to_string(uint32_t i);
     std::string to_string(double d);
 }
index 4c3a01f..65c0a3b 100644 (file)
@@ -113,12 +113,28 @@ def __import_lib(env, lib):
        lib_src.extend(__search_files(lib_path, '*.c'))
        lib_src.extend(__search_files(lib_path, '*.cpp'))
 
+       lib_obj = __src_to_obj(env, lib_src)
        build_dir = env.get('BUILD_DIR')
        if build_dir:
-               lib_a = env.StaticLibrary(build_dir + lib, __src_to_obj(env, lib_src))
+               lib_a = env.StaticLibrary(build_dir + lib, lib_obj)
        else:
-               lib_a = env.StaticLibrary(lib, __src_to_obj(env, lib_src))
-       env.AppendUnique(LIBS = [File(lib_a[0])])
+               lib_a = env.StaticLibrary(lib, lib_obj)
+
+       # If we link libSPI.a, the final binary is not getting launched
+       # on the board.  Which is not the case if we directly use SPI.o.
+
+       if env.get('TARGET_ARCH') == 'arm':
+               if lib == 'SPI':
+                       for obj in lib_obj:
+                               if obj.name.endswith('SPI.o'):
+                                       env.PrependUnique(LIBS = [File(obj)])
+               else:
+
+                       env.AppendUnique(LIBS = [File(lib_a[0])])
+       else:
+               env.PrependUnique(LIBS = [File(lib_a[0])])
+
+       #env.AppendUnique(LIBS = [File(lib_a[0])])
 
 def __build_core(env):
        core_src = __search_files(core_folder, '*.S')
@@ -130,11 +146,14 @@ def __build_core(env):
        core_src.extend(__search_files(variant_folder, '*.cpp'))
 
        core_obj = __src_to_obj(env, core_src)
-       build_dir = env.get('BUILD_DIR')
-       if build_dir:
-               s_core = env.StaticLibrary(build_dir + 'core', core_obj)
-       else:
-               s_core = env.StaticLibrary('core', core_obj)
+
+       prefix = env.get('BOARD') + '_'
+       if env.get('CPU'):
+               prefix += env.get('CPU') + '_'
+
+       core = env.get('BUILD_DIR', '.') + '/arduino/' + prefix + 'core'
+       s_core = env.StaticLibrary(core, core_obj)
+
        env.AppendUnique(LIBS = [File(s_core[0])])
 
        # To avoid compiler issue. Otherewise there may be warnings:
@@ -153,6 +172,25 @@ def __create_bin(env, source):
        else:
                hex = env.Command(name + '.hex', source, 'arm-none-eabi-objcopy -O binary $SOURCE $TARGET')
 
+#Currently supporting only mega (ie. Arduino ATMega2560) and arduino_due_x/arduino_due_x_dbg (i.e. Arduino Due) builds
+def __upload(env, binary):
+        if target_arch == 'avr':
+                protocol = __get_board_info(board, '.upload.protocol')
+                speed = __get_board_info(board, '.upload.speed')
+                port = '/dev/ttyACM0'
+                upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -p' \
+                + mcu + ' -c' + protocol + ' -P' + port + ' -b' + speed + ' -D -Uflash:w:' + binary + ':i'
+                print "Upload command: %s" %upload_cmd
+                install_cmd = env.Command('install_cmd', None, upload_cmd)
+                env.Default('install_cmd')
+        elif target_arch == 'arm':
+                protocol = __get_board_info(board, '.upload.protocol')
+                speed = __get_board_info(board, '.upload.speed')
+                port = 'ttyACM0'
+                uu = __get_board_info(board, '.upload.native_usb')
+                os.system('stty -F /dev/' + port + ' speed 1200 cs8 -cstopb -parenb')
+                os.system(arduino_home + '/hardware/tools/bossac -i --port=' + port + ' -U false -e -w -b ' + binary + ' -R')
+
 # Print the command line that to upload binary to the board
 def __upload_help(env):
        if target_arch == 'avr':
@@ -182,16 +220,12 @@ help_vars.Update(env)
 Help(help_vars.GenerateHelpText(env))
 
 target_arch = env.get('TARGET_ARCH')
+
+# Verify that the arduino, time, red bear, and nordic libraries are
+# installed.  If not, get them and install them.
+SConscript(env.get('SRC_DIR') + '/extlibs/arduino/SConscript')
 arduino_home = env.get('ARDUINO_HOME')
-if not arduino_home:
-       print '''
-************************************* Error ***********************************
-*   Arduino root directory isn't set, you can set enviornment variable        *
-* ARDUINO_HOME or add it in command line as:                                  *
-*      # scons ARDUINO_HOME=<path to arduino root directory> ...              *
-*******************************************************************************
-'''
-       Exit(1)
+print 'ARDUINO_HOME = ' + env.get('ARDUINO_HOME')
 
 # Overwrite suffixes and prefixes
 if env['HOST_OS'] == 'win32':
@@ -221,7 +255,7 @@ else:
 # Get IDE version
 if os.path.exists(arduino_home + '/lib/version.txt'):
        vf = open(arduino_home + '/lib/version.txt', 'r')
-       version = vf.readline().replace('.', '')
+       version = vf.readline().replace('.', '').strip()
 else:
        print '''
 ************************************* Error ***********************************
@@ -310,7 +344,7 @@ core_folder = core_base + 'cores/' + core + '/'
 env.AppendUnique(CPPPATH = [core_folder])
 
 if is_1_0_x:
-       comm_flags = []
+       comm_flags = ['-std=c99']
        if mcu:
                comm_flags.extend(['-mmcu=' + mcu])
        if f_cpu:
@@ -344,9 +378,11 @@ else:
 
        comm_flag = [cpu_flag, '-DF_CPU=' + f_cpu, '-DARDUINO=' + version, '-DARDUINO_' + __get_board_info(board, '.build.board')]
        if target_arch == 'arm':
-               comm_flag.extend(['-DARDUINO_ARCH_SAM'])
+               # As of 1.5.8 the arduino headers for arm had _asm_ bugs with ARM and
+               # require gnu99 to be used
+               comm_flag.extend(['-std=gnu99', '-DARDUINO_ARCH_SAM'])
        else:
-               comm_flag.extend(['-DARDUINO_ARCH_AVR'])
+               comm_flag.extend(['-std=c99', '-DARDUINO_ARCH_AVR'])
 
        compiler_path = platform_info.get('compiler.path')
        compiler_path = compiler_path.replace('{runtime.ide.path}', arduino_home)
@@ -374,9 +410,8 @@ else:
 
        if target_arch == 'arm':
                env.AppendUnique(LINKFLAGS = ['-Os', '-Wl,--gc-sections', cpu_flag,
-                                       '-T' + variant_folder + '/' + __get_board_info(board, '.build.ldscript'),
-                                       '-Wl,-Map,' + env.get('BUILD_DIR') + 'arduino_prj.map'])
-               env.AppendUnique(LINKFLAGS = Split('-lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group'))
+                                       '-T' + variant_folder + '/' + __get_board_info(board, '.build.ldscript')])
+               env.AppendUnique(LINKFLAGS = Split('-lm -lgcc -mthumb -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group'))
 
                variant_system_lib = __get_board_info(board, '.build.variant_system_lib')
                if variant_system_lib:
@@ -392,9 +427,11 @@ else:
                env.AppendUnique(LIBS = 'm')
        env.Replace(ARCOM = '$AR ' + platform_info.get('compiler.ar.flags') + ' $TARGET $SOURCES')
 
+
 __build_core(env)
 
 env.AddMethod(__import_lib, "ImportLib") #import arduino library
-#env.AddMethod(__build_core, "BuildCore") #build arduino core
+env.AddMethod(__build_core, "BuildCore") #build arduino core
 env.AddMethod(__create_bin, "CreateBin") #create binary files(.eep and .hex)
+env.AddMethod(__upload, "Upload") #Upload binary to board
 env.AddMethod(__upload_help, "UploadHelp") #print the command line that to upload binary to the boardf
index 7d57774..2b0386a 100644 (file)
@@ -19,10 +19,12 @@ if sys_version is None:
        print '''
 *********************************** Error *************************************
 *   MAC OSX/IOS version isn't set, please set it in command line as :         *
-*      # scons SYS_VERSION=<version> ...                                      *
+*      # scons TARGET_ARCH=<arch> TARGET_OS=<os> SYS_VERSION=<version> ...    *
 *   To get the version, please see:                                                              *
 * /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/   *
 * /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/ *
+*   <arch> is 'armv7','armv7s','arm64','i386', 'x86_64'
+*   <os> is 'darwin','ios'
 *******************************************************************************
 '''
        Exit(1)
@@ -35,6 +37,7 @@ if env.get('RELEASE'):
        env.AppendUnique(CPPDEFINES = ['NDEBUG'])
 else:
        env.AppendUnique(CCFLAGS = ['-g'])
+       env.AppendUnique(LINKFLAGS = ['-g'])
 
 if target_os == 'darwin':
        sys_root = '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX' + sys_version + '.sdk/'
@@ -51,4 +54,4 @@ env.AppendUnique(LINKFLAGS = ['-arch', target_arch, '-isysroot', sys_root])
 if target_os == 'darwin':
        flag = '-mmacosx-version-min=' + sys_version
        env.AppendUnique(CCFLAGS = [flag])
-       env.AppendUnique(LINKFLAGS = [flag])
\ No newline at end of file
+       env.AppendUnique(LINKFLAGS = [flag])
diff --git a/build_common/external_libs.scons b/build_common/external_libs.scons
new file mode 100644 (file)
index 0000000..432bbe5
--- /dev/null
@@ -0,0 +1,128 @@
+##
+# This script manages external libraries
+#
+# Some methods are added to manage external packages:
+#    'PrepareLib': Checks the existence of an external library, if it
+# doesn't exist, calls the script user provided to download(if required)
+# and build the source code of the external library or notify user to
+# install the library.
+#   'Download': Download package from specify URL
+#   'UnpackAll': Unpack the package
+#   'Configure': Execute specify script(configure, bootstrap etc)
+#   'InstallHeadFile': Install head files
+#   'InstallLib': Install library binaries(.so, .a etc)
+#
+# By default, assume the script for an exteranl library is:
+#    <src_dir>/extlibs/<libname>/SConscript
+#
+# Note: After the external library is built:
+#   Head files should be installed to <src_dir>/deps/<target_os>/include
+#   lib(e.g .so, .a) should be installed to <src_dir>/deps/<target_os>/lib/<arch>
+#
+##
+import os, subprocess
+import urllib2, urlparse
+import SCons.Errors
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+target_arch = env.get('TARGET_ARCH')
+
+# for android, doesn't distinguish 'armeabi-v7a-hard' and 'armeabi-v7a' library
+if target_os == 'android':
+       if target_arch == 'armeabi-v7a-hard':
+               target_arch = 'armeabi-v7a'
+
+if target_os == 'darwin':
+       env.AppendUnique(CPPPATH = ['/usr/local/include'])
+       env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+
+# External library include files are in <src_dir>/deps/<target_os>/include
+# the library binaries are in <src_dir>/deps/<target_os>/lib/<arch>
+env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
+env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
+
+# Check whether a library exists, if not, notify user to install it or try to
+# download the source code and build it
+# @param libname - the name of the library try to prepare
+# @param lib - the lib(.so, .a etc) to check (a library may include more then
+#      one lib, e.g. boost, includes boost_thread, boost_system ...
+# @param path - the directory of the library building script, if it's not set,
+#                      by default, it's <src_dir>/extlibs/<libname>/
+# @param script - the building script, by default, it's 'SConscript'
+#
+def __prepare_lib(ienv, libname, lib = None, path = None, script = None):
+       p_env = ienv.Clone()
+       if p_env.GetOption('clean') or p_env.GetOption('help'):
+               return
+
+       conf = Configure(p_env)
+
+       if not lib:
+               lib = libname
+       if not conf.CheckLib(lib):
+               if path:
+                       dir = path
+               else:
+                       dir = os.path.join(env.get('SRC_DIR'), 'extlibs', libname)
+
+               # Execute the script to download(if required) and build source code
+               if script:
+                       st = os.path.join(dir, script)
+               else:
+                       st = os.path.join(dir, 'SConscript')
+
+               if os.path.exists(st):
+                       SConscript(st)
+               else:
+                       if target_os in ['linux', 'darwin', 'tizen']:
+                               print 'Don\'t find library(%s), please intall it, exit ...' % libname
+                       else:
+                               print 'Don\'t find library(%s) and don\'t find the process script (%s), exit ...' % (libname, st)
+                       Exit(1)
+
+       conf.Finish()
+
+# Run configure command (usually it's done before build a library)
+def __configure(env, cwd, cmd) :
+       print "Configuring using [%s/%s] ..." % (cwd, cmd)
+       # build it now (we need the shell, because some programs need it)
+       devnull = open(os.devnull, "wb")
+       handle  = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=devnull)
+
+       if handle.wait() <> 0 :
+               raise SCons.Errors.BuildError( "Run configuring script [%s]" % (cmd) )
+
+# Download from URL 'url', will save as 'target'
+def __download(ienv, target, url) :
+       if os.path.exists(target) :
+               return target
+
+       try :
+               print "Download %s from %s" % (target, url)
+               print "Downloading ..."
+               stream = urllib2.urlopen(url)
+               file = open(target, 'wb')
+               file.write(stream.read())
+               file.close()
+               print "Download %s from %s complete" % (target, url)
+               return target
+       except Exception, e :
+               raise SCons.Errors.StopError( '%s [%s]' % (e, url) )
+
+# Install header file(s) to <src_dir>/deps/<target_os>/include
+def __install_head_file(ienv, file):
+               return ienv.Install(os.path.join(env.get('SRC_DIR'), 'dep', target_os, target_arch, 'usr', 'include'), file)
+
+# Install library binaries to <src_dir>/deps/<target_os>/lib/<arch>
+def __install_lib(ienv, lib):
+               return ienv.Install(os.path.join(env.get('SRC_DIR'), 'dep', target_os, target_arch, 'usr', 'lib'), lib)
+
+SConscript('tools/UnpackAll.py')
+
+env.AddMethod(__prepare_lib, "PrepareLib")
+env.AddMethod(__configure, "Configure")
+env.AddMethod(__download, "Download")
+env.AddMethod(__install_head_file, "InstallHeadFile")
+env.AddMethod(__install_lib, "InstallLib")
diff --git a/build_common/iotivityconfig/__init__.py b/build_common/iotivityconfig/__init__.py
new file mode 100644 (file)
index 0000000..3a2ef6a
--- /dev/null
@@ -0,0 +1,110 @@
+# ------------------------------------------------------------------------
+# Copyright 2015 Intel Corporation
+#
+# 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 file contains compiler tests for use in scons 'Configure'
+# tests.
+
+from compiler import factory
+
+def _check_for_broken_gcc_headers(context, flag):
+    # Check for issue in some older (pre-C++11) C library headers that
+    # causes functions like snprintf() to remain undeclared when
+    # -std=c++0x or -ansi, for example, is added to the g++ command
+    # line flags, and despite the fact the appropriate feature test
+    # macro to make the prototypes visible is defined.
+    #
+    # Returns 1 if the broken headers were detected, 0 otherwise.
+    #
+    # This should only be called if the compiler is g++ (which it
+    # should be if we are here) and a flag was automatically appended
+    # to CXXFLAGS.
+
+    context.Message('Checking for broken GCC C headers when C++11 is enabled... ')
+    ret = '-std=gnu++' in flag
+    context.Result(ret)
+
+    if ret:
+        print('Warning: detected pre-C++11 GCC C header bugs.  See:')
+        print('           https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34032')
+        print('         for related details.')
+
+def _inform_user_of_broken_gcc_headers(context, flag):
+    # Informative tests used to inform the user of broken GCC headers.
+    # They are unnecessary for actual builds.
+    if flag is not 1 and flag is not 0:
+        # The flag is neither 1 nor 0, meaning it contains the
+        # automatically detected C++11 flag.
+
+        # Now verify that the compiler is actually GCC.
+        is_gcc = factory.check_for_gcc_cxx(context)
+        if is_gcc:
+            # This should only be called if the compiler is g++ and a
+            # flag was automatically appended to CXXFLAGS.
+            #
+            # We do not care if the user added a flag that triggers
+            # the header bug.  It's the user's responsibility to
+            # handle the issue in that case.
+            _check_for_broken_gcc_headers(context, flag)
+
+def check_c99_flags(context):
+    """
+    Check if command line flag is required to enable C99 support.
+
+    Returns 1 if no flag is required, 0 if no flag was found, or the
+    actual flag if one was found.
+    """
+
+    cc = context.env['CC']
+    context.Message('Checking for C99 flag for ' + cc + '... ')
+    config = factory.make_c_compiler_config(context)
+    ret = config.check_c99_flags()
+    context.Result(ret)
+
+    return ret
+
+def check_cxx11_flags(context):
+    """
+    Check if command line flag is required to enable C++11 support.
+
+    Returns 1 if no flag is required, 0 if no flag was found, or the
+    actual flag if one was found.
+    """
+
+    cxx = context.env['CXX']
+    context.Message('Checking for C++11 flag for ' + cxx + '... ')
+    config = factory.make_cxx_compiler_config(context)
+    ret = config.check_cxx11_flags()
+    context.Result(ret)
+
+    # Let the user know if a workaround was enabled for broken GCC C
+    # headers when C++11 is enabled.
+    _inform_user_of_broken_gcc_headers(context, ret)
+
+    return ret
+
+def check_pthreads(context):
+    """
+    Check if pthreads are supported for this platform.
+
+    Sets POSIX_SUPPORTED based on the result.
+    """
+    context.Message('Checking for POSIX Thread Support...')
+    config = factory.make_c_compiler_config(context)
+
+    ret = config.has_pthreads_support()
+    context.env['POSIX_SUPPORTED'] = ret
+    context.Result(ret)
+    return ret
diff --git a/build_common/iotivityconfig/compiler/__init__.py b/build_common/iotivityconfig/compiler/__init__.py
new file mode 100644 (file)
index 0000000..9f01a42
--- /dev/null
@@ -0,0 +1,17 @@
+# ------------------------------------------------------------------------
+# Copyright 2015 Intel Corporation
+#
+# 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.
+# ------------------------------------------------------------------------
+
+__all__ = [ "factory" ]
diff --git a/build_common/iotivityconfig/compiler/configuration.py b/build_common/iotivityconfig/compiler/configuration.py
new file mode 100644 (file)
index 0000000..3dbf4e1
--- /dev/null
@@ -0,0 +1,178 @@
+# ------------------------------------------------------------------------
+# Copyright 2015 Intel Corporation
+#
+# 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.
+# ------------------------------------------------------------------------
+
+class Configuration:
+    """Compiler-specific configuration abstract base class"""
+
+    def __init__(self, context):
+        """
+        Initialize the Configuration object
+
+        Arguments:
+        context -- the scons configure context
+        """
+
+        if type(self) is Configuration:
+            raise TypeError('abstract class cannot be instantiated')
+
+        self._context = context      # scons configure context
+        self._env     = context.env  # scons environment
+
+    def check_c99_flags(self):
+        """
+        Check if command line flag is required to enable C99
+        support.
+
+        Returns 1 if no flag is required, 0 if no flag was
+        found, and the actual flag if one was found.
+
+        CFLAGS will be updated with appropriate C99 flag,
+        accordingly.
+        """
+
+        return self._check_flags(self._c99_flags(),
+                                 self._c99_test_program(),
+                                 '.c',
+                                 'CFLAGS')
+
+    def check_cxx11_flags(self):
+        """
+        Check if command line flag is required to enable C++11
+        support.
+
+        Returns 1 if no flag is required, 0 if no flag was
+        found, and the actual flag if one was found.
+
+        CXXFLAGS will be updated with appropriate C++11 flag,
+        accordingly.
+        """
+
+        return self._check_flags(self._cxx11_flags(),
+                                 self._cxx11_test_program(),
+                                 '.cpp',
+                                 'CXXFLAGS')
+
+    def has_pthreads_support(self):
+        """
+        Check if PThreads are supported by this system
+
+        Returns 1 if this system DOES support pthreads, 0
+        otherwise
+        """
+
+        return self._context.TryCompile(self._pthreads_test_program(), '.c')
+
+    # --------------------------------------------------------------
+    # Check if flag is required to build the given test program.
+    #
+    # Arguments:
+    # test_flags     -- list of flags that may be needed to build
+    #                   test_program
+    # test_program   -- program used used to determine if one of the
+    #                   given flags is required to for a successful
+    #                   build
+    # test_extension -- file extension associated with the test
+    #                   program, e.g. '.cpp' for C++ and '.c' for C
+    # flags_key      -- key used to retrieve compiler flags that may
+    #                   be updated by this check from the SCons
+    #                   environment
+    # --------------------------------------------------------------
+    def _check_flags(self,
+                     test_flags,
+                     test_program,
+                     test_extension,
+                     flags_key):
+        # Check if no additional flags are required.
+        ret = self._context.TryCompile(test_program,
+                                       test_extension)
+
+        if ret is 0:
+            # Try flags known to enable compiler features needed by
+            # the test program.
+
+            last_flags = self._env[flags_key]
+            for flag in test_flags:
+                self._env.Append(**{flags_key : flag})
+                ret = self._context.TryCompile(test_program,
+                                               test_extension)
+
+                if ret:
+                    # Found a flag!
+                    return flag
+                else:
+                    # Restore original compiler flags for next flag
+                    # test.
+                    self._env.Replace(**{flags_key : last_flags})
+
+        return ret
+
+    # ------------------------------------------------------------
+    # Return test program to be used when checking for basic C99
+    # support.
+    #
+    # Subclasses should implement this template method or use the
+    # default test program found in the DefaultConfiguration class
+    # through composition.
+    # ------------------------------------------------------------
+    def _c99_test_program(self):
+        raise NotImplementedError('unimplemented method')
+
+    # --------------------------------------------------------------
+    # Get list of flags that could potentially enable C99 support.
+    #
+    # Subclasses should implement this template method if flags are
+    # needed to enable C99 support.
+    # --------------------------------------------------------------
+    def _c99_flags(self):
+        raise NotImplementedError('unimplemented method')
+
+    # ------------------------------------------------------------
+    # Return test program to be used when checking for basic C++11
+    # support.
+    #
+    # Subclasses should implement this template method or use the
+    # default test program found in the DefaultConfiguration class
+    # through composition.
+    # ------------------------------------------------------------
+    def _cxx11_test_program(self):
+        raise NotImplementedError('unimplemented method')
+
+    # --------------------------------------------------------------
+    # Get list of flags that could potentially enable C++11 support.
+    #
+    # Subclasses should implement this template method if flags are
+    # needed to enable C++11 support.
+    # --------------------------------------------------------------
+    def _cxx11_flags(self):
+        raise NotImplementedError('unimplemented method')
+
+    # --------------------------------------------------------------
+    # Return a test program to be used when checking for PThreads
+    # support
+    #
+    # --------------------------------------------------------------
+    def _pthreads_test_program(self):
+        return """
+#include <unistd.h>
+#include <pthread.h>
+int main()
+{
+    #ifndef _POSIX_THREADS
+    # error POSIX Threads support not available
+    #endif
+    return 0;
+}
+"""
diff --git a/build_common/iotivityconfig/compiler/default_configuration.py b/build_common/iotivityconfig/compiler/default_configuration.py
new file mode 100644 (file)
index 0000000..ed90f40
--- /dev/null
@@ -0,0 +1,84 @@
+# ------------------------------------------------------------------------
+# Copyright 2015 Intel Corporation
+#
+# 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.
+# ------------------------------------------------------------------------
+
+from configuration import Configuration
+
+# Default (very simple) compiler configuration
+class DefaultConfiguration(Configuration):
+    def __init__(self, context):
+        Configuration.__init__(self, context)
+
+    # ------------------------------------------------------------
+    # Return test program to be used when checking for basic C++11
+    # support.
+    # ------------------------------------------------------------
+    def _c99_test_program(self):
+        return """
+// Some headers found in C99.
+#include <stdbool.h>
+#include <stdint.h>
+
+int main()
+{
+    struct foo
+    {
+        bool b;      // C99 type
+        int i;
+        uint64_t q;  // C99 type
+    };
+
+    // Designated initializer.
+    struct foo bar = { .b = false, .q = UINT64_MAX };
+
+    // Implicitly initialized field.
+    return bar.i != 0;
+}
+"""
+
+    # --------------------------------------------------------------
+    # Get list of flags that could potentially enable C99 support.
+    #
+    # The default configuration assumes that no flag is needed to
+    # enable C99 support.
+    # --------------------------------------------------------------
+    def _c99_flags(self):
+        return []
+
+    # ------------------------------------------------------------
+    # Return test program to be used when checking for basic C++11
+    # support.
+    # ------------------------------------------------------------
+    def _cxx11_test_program(self):
+        return """
+int main()
+{
+    int x = 3210;
+    auto f = [x](){
+        return x;
+    };
+
+    return f() != x;
+}
+"""
+
+    # --------------------------------------------------------------
+    # Get list of flags that could potentially enable C++11 support.
+    #
+    # The default configuration assumes that no flag is needed to
+    # enable C++11 support.
+    # --------------------------------------------------------------
+    def _cxx11_flags(self):
+        return []
diff --git a/build_common/iotivityconfig/compiler/factory.py b/build_common/iotivityconfig/compiler/factory.py
new file mode 100644 (file)
index 0000000..7b0bee7
--- /dev/null
@@ -0,0 +1,126 @@
+# ------------------------------------------------------------------------
+# Copyright 2015 Intel Corporation
+#
+# 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.
+# ------------------------------------------------------------------------
+
+from default_configuration import *
+from gcc_configuration import *
+
+# Canonicalize the C or C++ compiler name to "gcc" if gcc is being
+# used to simplify mapping to the GCC compiler configuration since GCC
+# may be installed under a different name.  This will be used when
+# mapping compiler name to configuration in the factory submodule.
+_GCC = 'gcc'
+
+# Update this dictionary with new compiler configurations as needed.
+_CONFIG_MAP = { _GCC : GccConfiguration }
+
+_c_compiler_config = None
+_cxx_compiler_config = None
+
+def check_for_gcc_c(context):
+    """
+    Check if the C compiler is GCC
+
+    Returns 1 if gcc, 0 otherwise
+    """
+
+    test_program = """
+#if !defined(__GNUC__)
+#  error "Not the GCC C compiler."
+#endif
+
+int foo(void)
+{
+    return 0;
+}
+"""
+
+    return context.TryCompile(test_program, '.c')
+
+def check_for_gcc_cxx(context):
+    """
+    Check if the C++ compiler is GCC
+
+    Returns 1 if gcc, 0 otherwise
+    """
+
+    test_program = """
+#if !defined(__GNUC__) || !defined(__cplusplus)
+#  error "Not the GCC C++ compiler."
+#endif
+
+class foo
+{
+public:
+    foo() : x_() {}
+    int x() const { return x_; }
+private:
+    int x_;
+};
+"""
+
+    return context.TryCompile(test_program, '.cpp')
+
+def make_c_compiler_config(context):
+    """
+    Create C compiler-specific configuration object.
+
+    Arguments:
+    context -- the scons configure context
+
+    The 'CC' key in the SCons environment will be mapped to the
+    appropriate supported compiler configuration.  If no match is
+    found compiler configuration operations will simply be no-ops.
+    """
+
+    global _c_compiler_config
+
+    if _c_compiler_config is None:
+        cc = context.env['CC']
+
+        if check_for_gcc_c(context):
+            cc = _GCC
+
+        config = _CONFIG_MAP.get(cc, DefaultConfiguration)
+
+        _c_compiler_config = config(context)
+
+    return _c_compiler_config
+
+def make_cxx_compiler_config(context):
+    """
+    Create C++ compiler-specific configuration object.
+
+    Arguments:
+    context -- the scons configure context
+
+    The 'CXX' key in the SCons environment will be mapped to the
+    appropriate supported compiler configuration.  If no match is
+    found compiler configuration operations will simply be no-ops.
+    """
+
+    global _cxx_compiler_config
+
+    if _cxx_compiler_config is None:
+        cxx = context.env['CXX']
+
+        if check_for_gcc_cxx(context):
+            cxx = _GCC
+
+        config = _CONFIG_MAP.get(cxx, DefaultConfiguration)
+
+        _cxx_compiler_config = config(context)
+
+    return _cxx_compiler_config
diff --git a/build_common/iotivityconfig/compiler/gcc_configuration.py b/build_common/iotivityconfig/compiler/gcc_configuration.py
new file mode 100644 (file)
index 0000000..fbc8f38
--- /dev/null
@@ -0,0 +1,109 @@
+# ------------------------------------------------------------------------
+# Copyright 2015 Intel Corporation
+#
+# 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.
+# ------------------------------------------------------------------------
+
+from configuration import Configuration
+
+# GCC compiler-specific configuration
+class GccConfiguration(Configuration):
+    def __init__(self, context):
+        Configuration.__init__(self, context)
+
+    # ------------------------------------------------------------
+    # Return test program to be used when checking for basic C99
+    # support in GCC.
+    # ------------------------------------------------------------
+    def _c99_test_program(self):
+        # Use the default C99 test program but enable pedantic
+        # diagnostics specific to GCC to force errors to occur if a
+        # flag is required to compile C99 code without warning or
+        # error.
+
+        from default_configuration import DefaultConfiguration
+        def_config = DefaultConfiguration(self._context)
+
+        return """
+#ifndef __clang__
+#pragma GCC diagnostic error "-Wall"
+#pragma GCC diagnostic error "-Werror"
+#pragma GCC diagnostic error "-pedantic"
+#endif
+""" + def_config._c99_test_program()
+
+    # -------------------------------------------------------------
+    # Get flags known to enable C99 support for GCC C compiler.
+    # -------------------------------------------------------------
+    def _c99_flags(self):
+        # Favor flags that do not enable GNU extensions by default,
+        # e.g. '-std=c99'.
+        return [ '-std=c99',
+                 '-std=iso9899:1999',
+                 '-std=gnu99',
+                 '-std=c9x',
+                 '-std=iso9899:199x',
+                 '-std=gnu9x' ]
+
+    # ------------------------------------------------------------
+    # Return test program to be used when checking for basic C++11
+    # support in GCC.
+    # ------------------------------------------------------------
+    def _cxx11_test_program(self):
+        # Besides checking for a basic C++11 feature, this contrived
+        # test program is designed to trigger an issue in some older
+        # (pre-C++11) C library headers that causes functions like
+        # snprintf() to remain undeclared when -std=c++0x or -ansi,
+        # for example, is added to the g++ command line flags, and
+        # despite the fact the appropriate feature test macro to make
+        # the prototypes visible is defined.
+        #
+        # The recommended workaround is to instead of -std=c++0x use
+        # -std=gnu++0x to explicitly enable GNU extensions.  Failure
+        # will force the configuration test to attempt the build with
+        # -std=gnu++0x, for example.
+        #
+        # For a more complete description of this issue, see:
+        #     https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34032
+        #
+        # Other compilers should be able to compile this code without
+        # issue.
+        return """
+#define _POSIX_C_SOURCE 200112L
+#include <stdio.h>
+
+int main()
+{
+    int x = 3210;
+    auto f = [x](){
+        char buf[15] = { 0 };
+        snprintf(buf, sizeof(buf) / sizeof(buf[0]), "%d", x);
+        return buf[0];
+    };
+
+    return f() != '3';
+}
+"""
+
+    # -------------------------------------------------------------
+    # Get flags known to enable C++11 support for GCC C++ compiler.
+    # -------------------------------------------------------------
+    def _cxx11_flags(self):
+        # Favor command line flags from more recent versions of the
+        # compiler over older/deprecated flags.  Also, favor flags
+        # that do not enable GNU extensions by default,
+        # e.g. '-std=c++..'.
+        return [ '-std=c++11',
+                 '-std=gnu++11',
+                 '-std=c++0x',
+                 '-std=gnu++0x' ]
index bb939be..b1640e1 100644 (file)
@@ -4,14 +4,24 @@
 ##
 Import('env')
 
+print "Reading linux configuration script"
+
 # Set release/debug flags
 if env.get('RELEASE'):
        env.AppendUnique(CCFLAGS = ['-Os'])
        env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-       env.AppendUnique(LINKFLAGS = ['-s'])
 else:
        env.AppendUnique(CCFLAGS = ['-g'])
 
+if env.get('LOGGING'):
+       env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__'])
+env.AppendUnique(CFLAGS = ['-std=gnu99'])
+env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+env.AppendUnique(LIBS = ['uuid'])
+env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
+
 # Set arch flags
 target_arch = env.get('TARGET_ARCH')
 if target_arch in ['x86']:
@@ -27,7 +37,7 @@ elif target_arch.find('v7a-hard') > 0:
        env.AppendUnique(LINKFLAGS = ['-mfloat-abi=hard'])
 elif target_arch.find('v7a') > 0:
        env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
-elif target_arch.find('arm64') > 0:
+elif target_arch.find('arm64') >= 0:
        env.AppendUnique(CPPFLAGS = ['-march=armv8-a'])
 else:
        env.AppendUnique(CPPFLAGS = ['-march=armv5te'])
diff --git a/build_common/tizen/SConscript b/build_common/tizen/SConscript
new file mode 100644 (file)
index 0000000..81be23a
--- /dev/null
@@ -0,0 +1,46 @@
+##
+# This script set linux specific flags (GNU GCC)
+#
+##
+Import('env')
+
+print "Reading linux configuration script"
+
+# Set release/debug flags
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+    env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__'])
+env.AppendUnique(CFLAGS = ['-std=gnu99'])
+env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
+
+if env.get('TARGET_OS') == 'tizen':
+    env.AppendUnique(CCFLAGS = ['-D__TIZEN__', '-DSLP_SDK_LOG', '-D_GNU_SOURCE', '-DTIZEN_DEBUG_ENABLE'])
+    env.ParseConfig("pkg-config dlog --cflags --libs")
+
+# Set arch flags
+target_arch = env.get('TARGET_ARCH')
+if target_arch in ['x86']:
+    env.AppendUnique(CCFLAGS = ['-m32'])
+    env.AppendUnique(LINKFLAGS = ['-m32'])
+elif target_arch in ['x86_64']:
+    env.AppendUnique(CCFLAGS = ['-m64'])
+    env.AppendUnique(LINKFLAGS = ['-m64'])
+elif target_arch.find('v7a-hard') > 0:
+    env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
+    env.AppendUnique(CPPFLAGS = ['-mfloat-abi=hard'])
+    env.AppendUnique(CCFLAGS = ['-mfloat-abi=hard'])
+    env.AppendUnique(LINKFLAGS = ['-mfloat-abi=hard'])
+elif target_arch.find('v7a') > 0:
+    env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
+elif target_arch.find('arm64') >= 0:
+    env.AppendUnique(CPPFLAGS = ['-march=armv8-a'])
+else:
+    env.AppendUnique(CPPFLAGS = ['-march=armv5te'])
diff --git a/build_common/tools/UnpackAll.py b/build_common/tools/UnpackAll.py
new file mode 100644 (file)
index 0000000..0df17e4
--- /dev/null
@@ -0,0 +1,414 @@
+# -*- coding: utf-8 -*-
+
+############################################################################
+# GPL License                                                              #
+#                                                                          #
+# This file is a SCons (http://www.scons.org/) builder                     #
+# Copyright (c) 2012-14, Philipp Kraus, <philipp.kraus@flashpixx.de>       #
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.     #
+# This program is free software: you can redistribute it and/or modify     #
+# it under the terms of the GNU General Public License as                  #
+# published by the Free Software Foundation, either version 3 of the       #
+# License, or (at your option) any later version.                          #
+#                                                                          #
+# This program is distributed in the hope that it will be useful,          #
+# but WITHOUT ANY WARRANTY; without even the implied warranty of           #
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
+# GNU General Public License for more details.                             #
+#                                                                          #
+# You should have received a copy of the GNU General Public License        #
+# along with this program. If not, see <http://www.gnu.org/licenses/>.     #
+############################################################################
+
+# This builder originated from work by Philipp Kraus and flashpixx project
+# (see https://github.com/flashpixx). Based on the Unpack.py, it only
+# contains changes to allow a complete unpacking of the archive.
+# It is assumed that the target represents a file in the archive after it
+# is unpacked.
+
+# The Unpack Builder can be used for unpacking archives (eg Zip, TGZ, BZ, ... ).
+# The emitter of the Builder reads the archive data and creates a returning
+# file list the builder extract the archive. The environment variable
+# stores a dictionary "UNPACK" for set different extractions (subdict "EXTRACTOR"):
+# {
+#   PRIORITY         => a value for setting the extractor order (lower numbers = extractor is used earlier)
+#   SUFFIX           => defines a list with file suffixes, which should be handled with this extractor
+#   EXTRACTSUFFIX    => suffix of the extract command
+#   EXTRACTFLAGS     => a string parameter for the RUN command for extracting the data
+#   EXTRACTCMD       => full extract command of the builder
+#   RUN              => the main program which will be started (if the parameter is empty, the extractor will be ignored)
+#   LISTCMD          => the listing command for the emitter
+#   LISTFLAGS        => the string options for the RUN command for showing a list of files
+#   LISTSUFFIX       => suffix of the list command
+#   LISTEXTRACTOR    => a optional Python function, that is called on each output line of the
+#                       LISTCMD for extracting file & dir names, the function need two parameters (first line number,
+#                       second line content) and must return a string with the file / dir path (other value types
+#                       will be ignored)
+# }
+# Other options in the UNPACK dictionary are:
+#   STOPONEMPTYFILE  => bool variable for stoping if the file has empty size (default True)
+#   VIWEXTRACTOUTPUT => shows the output messages of the extraction command (default False)
+#   EXTRACTDIR       => path in that the data will be extracted (default #)
+#
+# The file which is handled by the first suffix match of the extractor, the extractor list can be append for other files.
+# The order of the extractor dictionary creates the listing & extractor command eg file extension .tar.gz should be
+# before .gz, because the tar.gz is extract in one shoot.
+#
+# Under *nix system these tools are supported: tar, bzip2, gzip, unzip
+# Under Windows only 7-Zip (http://www.7-zip.org/) is supported
+
+
+import subprocess, os
+import SCons.Errors, SCons.Warnings, SCons.Util
+
+# enables Scons warning for this builder
+class UnpackWarning(SCons.Warnings.Warning) :
+    pass
+
+SCons.Warnings.enableWarningClass(UnpackWarning)
+
+# extractor function for Tar output
+# @param env environment object
+# @param count number of returning lines
+# @param no number of the output line
+# @param i line content
+def __fileextractor_nix_tar( env, count, no, i ) :
+    return i.split()[-1]
+
+# extractor function for GZip output,
+# ignore the first line
+# @param env environment object
+# @param count number of returning lines
+# @param no number of the output line
+# @param i line content
+def __fileextractor_nix_gzip( env, count, no, i ) :
+    if no == 0 :
+        return None
+    return i.split()[-1]
+
+# extractor function for Unzip output,
+# ignore the first & last two lines
+# @param env environment object
+# @param count number of returning lines
+# @param no number of the output line
+# @param i line content
+def __fileextractor_nix_unzip( env, count, no, i ) :
+    if no < 3 or no >= count - 2 :
+        return None
+    return i.split()[-1]
+
+# extractor function for 7-Zip
+# @param env environment object
+# @param count number of returning lines
+# @param no number of the output line
+# @param i line content
+def __fileextractor_win_7zip( env, count, no, i ) :
+    item = i.split()
+    if no > 8 and no < count - 2 :
+        return item[-1]
+    return None
+
+
+
+# returns the extractor item for handling the source file
+# @param source input source file
+# @param env environment object
+# @return extractor entry or None on non existing
+def __getExtractor( source, env ) :
+    # we check each unpacker and get the correct list command first, run the command and
+    # replace the target filelist with the list values, we sorte the extractors by their priority
+    for unpackername, extractor in sorted(env["UNPACK"]["EXTRACTOR"].iteritems(), key = lambda (k,v) : (v["PRIORITY"],k)):
+
+        if not SCons.Util.is_String(extractor["RUN"]) :
+            raise SCons.Errors.StopError("list command of the unpack builder for [%s] archives is not a string" % (unpackername))
+        if not len(extractor["RUN"]) :
+            raise SCons.Errors.StopError("run command of the unpack builder for [%s] archives is not set - can not extract files" % (unpackername))
+
+
+        if not SCons.Util.is_String(extractor["LISTFLAGS"]) :
+            raise SCons.Errors.StopError("list flags of the unpack builder for [%s] archives is not a string" % (unpackername))
+        if not SCons.Util.is_String(extractor["LISTCMD"]) :
+            raise SCons.Errors.StopError("list command of the unpack builder for [%s] archives is not a string" % (unpackername))
+
+        if not SCons.Util.is_String(extractor["EXTRACTFLAGS"]) :
+            raise SCons.Errors.StopError("extract flags of the unpack builder for [%s] archives is not a string" % (unpackername))
+        if not SCons.Util.is_String(extractor["EXTRACTCMD"]) :
+            raise SCons.Errors.StopError("extract command of the unpack builder for [%s] archives is not a string" % (unpackername))
+
+
+        # check the source file suffix and if the first is found, run the list command
+        if not SCons.Util.is_List(extractor["SUFFIX"]) :
+            raise SCons.Errors.StopError("suffix list of the unpack builder for [%s] archives is not a list" % (unpackername))
+
+        for suffix in extractor["SUFFIX"] :
+            if str(source[0]).lower()[-len(suffix):] == suffix.lower() :
+                return extractor
+
+    return None
+
+
+# creates the extracter output message
+# @param s original message
+# @param target target name
+# @param source source name
+# @param env environment object
+def __message( s, target, source, env ) :
+    print "extract [%s] ..." % (source[0])
+
+
+# action function for extracting of the data
+# @param target target packed file
+# @param source extracted files
+# @param env environment object
+def __action( target, source, env ) :
+    cwd = os.path.realpath('.')
+    extractor = __getExtractor([File(source)], env)
+    if not extractor :
+        print '''******************************* Error *****************************************
+*
+* Doesn't support auto extracting [%s], please extract it to [%s].
+*                                                                             *
+*******************************************************************************
+''' % (source, cwd)
+        raise SCons.Errors.StopError( "can not find any extractor value for the source file [%s]" % (source) )
+
+    extractor_cmd = extractor["EXTRACTCMD"]
+
+    # if the extract command is empty, we create an error
+    if len(extractor_cmd) == 0 :
+        raise SCons.Errors.StopError( "the extractor command for the source file [%s] is empty" % (source) )
+
+    # build it now (we need the shell, because some programs need it)
+    handle = None
+
+    cmd = env.subst(extractor_cmd, source=source, target=target)
+
+    if env["UNPACK"]["VIWEXTRACTOUTPUT"] :
+        handle  = subprocess.Popen( cmd, shell=True )
+    else :
+        devnull = open(os.devnull, "wb")
+        handle  = subprocess.Popen(cmd, shell=True, stdout=devnull, cwd = cwd)
+
+    if handle.wait() <> 0 :
+        print '''******************************* Error *****************************************
+*
+* Fail to unpack [%s]. It should be due to it isn't downloaded completely.
+* Please download it manually or delete it and let the script auto download it*
+* again.                                                                      *
+*                                                                             *
+*******************************************************************************
+''' % (source)
+        raise SCons.Errors.BuildError( "error running extractor [%s] on the source [%s]" % (cmd, source) )
+
+# emitter function for getting the files
+# within the archive
+# @param target target packed file
+# @param source extracted files
+# @param env environment object
+def __emitter( target, source, env ) :
+    return target, source
+
+def __unpack_all(env, target, source) :
+       if os.path.exists(target):
+               return
+
+       print "Unpacking %s ..." % source
+       __action(target, source, env)
+
+# generate function, that adds the builder to the environment
+# @param env environment object
+def generate( env ) :
+    # setup environment variable
+    toolset = {
+        "STOPONEMPTYFILE"  : True,
+        "VIWEXTRACTOUTPUT" : False,
+        "EXTRACTDIR"       : os.curdir,
+        "EXTRACTOR" : {
+            "TARGZ" : {
+                "PRIORITY"       : 0,
+                "SUFFIX"         : [".tar.gz", ".tgz", ".tar.gzip"],
+                "EXTRACTSUFFIX"  : "",
+                "EXTRACTFLAGS"   : "",
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['TARGZ']['RUN']} ${UNPACK['EXTRACTOR']['TARGZ']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARGZ']['EXTRACTSUFFIX']}",
+                "RUN"            : "",
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['TARGZ']['RUN']} ${UNPACK['EXTRACTOR']['TARGZ']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARGZ']['LISTSUFFIX']}",
+                "LISTSUFFIX"     : "",
+                "LISTFLAGS"      : "",
+                "LISTEXTRACTOR"  : None
+            },
+
+            "TARBZ" : {
+                "PRIORITY"       : 0,
+                "SUFFIX"         : [".tar.bz", ".tbz", ".tar.bz2", ".tar.bzip2", ".tar.bzip"],
+                "EXTRACTSUFFIX"  : "",
+                "EXTRACTFLAGS"   : "",
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['TARBZ']['RUN']} ${UNPACK['EXTRACTOR']['TARBZ']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARBZ']['EXTRACTSUFFIX']}",
+                "RUN"            : "",
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['TARBZ']['RUN']} ${UNPACK['EXTRACTOR']['TARBZ']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARBZ']['LISTSUFFIX']}",
+                "LISTSUFFIX"     : "",
+                "LISTFLAGS"      : "",
+                "LISTEXTRACTOR"  : None
+            },
+
+            "BZIP" : {
+                "PRIORITY"       : 1,
+                "SUFFIX"         : [".bz", "bzip", ".bz2", ".bzip2"],
+                "EXTRACTSUFFIX"  : "",
+                "EXTRACTFLAGS"   : "",
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['BZIP']['RUN']} ${UNPACK['EXTRACTOR']['BZIP']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['BZIP']['EXTRACTSUFFIX']}",
+                "RUN"            : "",
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['BZIP']['RUN']} ${UNPACK['EXTRACTOR']['BZIP']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['BZIP']['LISTSUFFIX']}",
+                "LISTSUFFIX"     : "",
+                "LISTFLAGS"      : "",
+                "LISTEXTRACTOR"  : None
+            },
+
+            "GZIP" : {
+                "PRIORITY"       : 1,
+                "SUFFIX"         : [".gz", ".gzip"],
+                "EXTRACTSUFFIX"  : "",
+                "EXTRACTFLAGS"   : "",
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['GZIP']['RUN']} ${UNPACK['EXTRACTOR']['GZIP']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['GZIP']['EXTRACTSUFFIX']}",
+                "RUN"            : "",
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['GZIP']['RUN']} ${UNPACK['EXTRACTOR']['GZIP']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['GZIP']['LISTSUFFIX']}",
+                "LISTSUFFIX"     : "",
+                "LISTFLAGS"      : "",
+                "LISTEXTRACTOR"  : None
+            },
+
+            "TAR" : {
+                "PRIORITY"       : 1,
+                "SUFFIX"         : [".tar"],
+                "EXTRACTSUFFIX"  : "",
+                "EXTRACTFLAGS"   : "",
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['TAR']['RUN']} ${UNPACK['EXTRACTOR']['TAR']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TAR']['EXTRACTSUFFIX']}",
+                "RUN"            : "",
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['TAR']['RUN']} ${UNPACK['EXTRACTOR']['TAR']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TAR']['LISTSUFFIX']}",
+                "LISTSUFFIX"     : "",
+                "LISTFLAGS"      : "",
+                "LISTEXTRACTOR"  : None
+            },
+
+            "ZIP" : {
+                "PRIORITY"       : 1,
+                "SUFFIX"         : [".zip"],
+                "EXTRACTSUFFIX"  : "",
+                "EXTRACTFLAGS"   : "",
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['ZIP']['RUN']} ${UNPACK['EXTRACTOR']['ZIP']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['ZIP']['EXTRACTSUFFIX']}",
+                "RUN"            : "",
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['ZIP']['RUN']} ${UNPACK['EXTRACTOR']['ZIP']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['ZIP']['LISTSUFFIX']}",
+                "LISTSUFFIX"     : "",
+                "LISTFLAGS"      : "",
+                "LISTEXTRACTOR"  : None
+            }
+        }
+    }
+
+    # read tools for Windows system
+    if env["PLATFORM"] <> "darwin" and "win" in env["PLATFORM"] :
+
+        if env.WhereIs("7z") :
+            toolset["EXTRACTOR"]["TARGZ"]["RUN"]           = "7z"
+            toolset["EXTRACTOR"]["TARGZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
+            toolset["EXTRACTOR"]["TARGZ"]["LISTFLAGS"]     = "x"
+            toolset["EXTRACTOR"]["TARGZ"]["LISTSUFFIX"]    = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTFLAGS"]  = "x"
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+
+            toolset["EXTRACTOR"]["TARBZ"]["RUN"]           = "7z"
+            toolset["EXTRACTOR"]["TARBZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
+            toolset["EXTRACTOR"]["TARBZ"]["LISTFLAGS"]     = "x"
+            toolset["EXTRACTOR"]["TARBZ"]["LISTSUFFIX"]    = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTFLAGS"]  = "x"
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+
+            toolset["EXTRACTOR"]["BZIP"]["RUN"]            = "7z"
+            toolset["EXTRACTOR"]["BZIP"]["LISTEXTRACTOR"]  = __fileextractor_win_7zip
+            toolset["EXTRACTOR"]["BZIP"]["LISTFLAGS"]      = "l"
+            toolset["EXTRACTOR"]["BZIP"]["LISTSUFFIX"]     = "-y -so"
+            toolset["EXTRACTOR"]["BZIP"]["EXTRACTFLAGS"]   = "x"
+            toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"]  = "-y -oc:${UNPACK['EXTRACTDIR']}"
+
+            toolset["EXTRACTOR"]["GZIP"]["RUN"]            = "7z"
+            toolset["EXTRACTOR"]["GZIP"]["LISTEXTRACTOR"]  = __fileextractor_win_7zip
+            toolset["EXTRACTOR"]["GZIP"]["LISTFLAGS"]      = "l"
+            toolset["EXTRACTOR"]["GZIP"]["LISTSUFFIX"]     = "-y -so"
+            toolset["EXTRACTOR"]["GZIP"]["EXTRACTFLAGS"]   = "x"
+            toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"]  = "-y -oc:${UNPACK['EXTRACTDIR']}"
+
+            toolset["EXTRACTOR"]["ZIP"]["RUN"]             = "7z"
+            toolset["EXTRACTOR"]["ZIP"]["LISTEXTRACTOR"]   = __fileextractor_win_7zip
+            toolset["EXTRACTOR"]["ZIP"]["LISTFLAGS"]       = "l"
+            toolset["EXTRACTOR"]["ZIP"]["LISTSUFFIX"]      = "-y -so"
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTFLAGS"]    = "x"
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"]   = "-y -oc:${UNPACK['EXTRACTDIR']}"
+
+            toolset["EXTRACTOR"]["TAR"]["RUN"]             = "7z"
+            toolset["EXTRACTOR"]["TAR"]["LISTEXTRACTOR"]   = __fileextractor_win_7zip
+            toolset["EXTRACTOR"]["TAR"]["LISTFLAGS"]       = "l"
+            toolset["EXTRACTOR"]["TAR"]["LISTSUFFIX"]      = "-y -ttar -so"
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTFLAGS"]    = "x"
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"]   = "-y -ttar -oc:${UNPACK['EXTRACTDIR']}"
+
+        # here can add some other Windows tools, that can handle the archive files
+        # but I don't know which ones can handle all file types
+
+
+
+    # read the tools on *nix systems and sets the default parameters
+    elif env["PLATFORM"] in ["darwin", "linux", "posix"] :
+
+        if env.WhereIs("unzip") :
+            toolset["EXTRACTOR"]["ZIP"]["RUN"]             = "unzip"
+            toolset["EXTRACTOR"]["ZIP"]["LISTEXTRACTOR"]   = __fileextractor_nix_unzip
+            toolset["EXTRACTOR"]["ZIP"]["LISTFLAGS"]       = "-l"
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTFLAGS"]    = "-oqq"
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"]   = "-d ${UNPACK['EXTRACTDIR']}"
+
+        if env.WhereIs("tar") :
+            toolset["EXTRACTOR"]["TAR"]["RUN"]             = "tar"
+            toolset["EXTRACTOR"]["TAR"]["LISTEXTRACTOR"]   = __fileextractor_nix_tar
+            toolset["EXTRACTOR"]["TAR"]["LISTFLAGS"]       = "tvf"
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTFLAGS"]    = "xf"
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"]   = "-C ${UNPACK['EXTRACTDIR']}"
+
+            toolset["EXTRACTOR"]["TARGZ"]["RUN"]           = "tar"
+            toolset["EXTRACTOR"]["TARGZ"]["LISTEXTRACTOR"] = __fileextractor_nix_tar
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTFLAGS"]  = "xfz"
+            toolset["EXTRACTOR"]["TARGZ"]["LISTFLAGS"]     = "tvfz"
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-C ${UNPACK['EXTRACTDIR']}"
+
+            toolset["EXTRACTOR"]["TARBZ"]["RUN"]           = "tar"
+            toolset["EXTRACTOR"]["TARBZ"]["LISTEXTRACTOR"] = __fileextractor_nix_tar
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTFLAGS"]  = "xfj"
+            toolset["EXTRACTOR"]["TARBZ"]["LISTFLAGS"]     = "tvfj"
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-C ${UNPACK['EXTRACTDIR']}"
+
+        if env.WhereIs("bzip2") :
+            toolset["EXTRACTOR"]["BZIP"]["RUN"]            = "bzip2"
+            toolset["EXTRACTOR"]["BZIP"]["EXTRACTFLAGS"]   = "-df"
+
+        if env.WhereIs("gzip") :
+            toolset["EXTRACTOR"]["GZIP"]["RUN"]            = "gzip"
+            toolset["EXTRACTOR"]["GZIP"]["LISTEXTRACTOR"]  = __fileextractor_nix_gzip
+            toolset["EXTRACTOR"]["GZIP"]["LISTFLAGS"]      = "-l"
+            toolset["EXTRACTOR"]["GZIP"]["EXTRACTFLAGS"]   = "-df"
+
+    else :
+        raise SCons.Errors.StopError("Unpack tool detection on this platform [%s] unkown" % (env["PLATFORM"]))
+
+    # the target_factory must be a "Entry", because the target list can be files and dirs, so we can not specified the targetfactory explicite
+    env.Replace(UNPACK = toolset)
+    env.AddMethod(__unpack_all, 'UnpackAll')
+
+#    env["BUILDERS"]["UnpackAll"] = SCons.Builder.Builder( action = __action,  emitter = __emitter,  target_factory = SCons.Node.FS.Entry,  source_factory = SCons.Node.FS.File,  single_source = True,  PRINT_CMD_LINE_FUNC = __message )
+
+
+# existing function of the builder
+# @param env environment object
+# @return true
+def exists(env) :
+    return 1
+
+Import('env')
+generate(env)
index 8d6e7d1..b753b94 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"
@@ -38,7 +39,7 @@ void MiddleClient::findResources()
 {
     m_resourceMap.clear();
 
-    OC::OCPlatform::findResource("", OC_WELL_KNOWN_QUERY, m_findCB);
+    OC::OCPlatform::findResource("", OC_WELL_KNOWN_QUERY, OC_ALL, m_findCB);
 }
 
 void MiddleClient::foundOCResource(shared_ptr<OCResource> resource)
@@ -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];
index 52a8528..685d33a 100644 (file)
@@ -52,9 +52,8 @@ int LineInput::run()
     while (true) {
         fputs(">", stdout);
         len = 0;
-        getline(&line, &len, stdin);
-        int n = strlen(line);
-        if (!n)
+        const ssize_t n = getline(&line, &len, stdin);
+        if (n <= 0)
             continue;
         if (m_observer) {
             m_observer->cancelObserve();
@@ -382,7 +381,7 @@ ParseState LineInput::putCharInElem(char c, char *& e, ParseState newState)
 LineResult LineInput::parseLine(string lineIn, elements_t& elems)
 {
     const char *d;
-    char c, *e, delim;
+    char c, *e, delim = 0;
     bool isSep1, isSep2;
     size_t len = lineIn.size();
     ParseState state = PS_Between;
diff --git a/examples/OICMiddle/SConscript b/examples/OICMiddle/SConscript
new file mode 100644 (file)
index 0000000..6748493
--- /dev/null
@@ -0,0 +1,76 @@
+#******************************************************************
+#
+# 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
+##
+Import('env')
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
+
+examples_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+examples_env.AppendUnique(CPPPATH = [
+               '../../resource/include/',
+               '../../resource/csdk/stack/include',
+               '../../resource/csdk/ocrandom/include',
+               '../../resource/csdk/logger/include',
+               '../../resource/oc_logger/include'
+               ])
+
+target_os = env.get('TARGET_OS')
+if target_os not in ['windows', 'winrt']:
+       examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+
+       # Note: 'pthread' is in libc for android. On other platform, if use
+       # new gcc(>4.9?) it isn't required, otherwise, it's required
+       if target_os != 'android':
+               examples_env.AppendUnique(LIBS = ['-lpthread'])
+
+examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction',
+        'coap', 'rt'])
+if env.get('SECURED') == '1':
+    examples_env.AppendUnique(LIBS = ['tinydtls'])
+
+if target_os == 'android':
+       examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+       examples_env.AppendUnique(LIBS = ['gnustl_static'])
+
+       if not env.get('RELEASE'):
+               examples_env.AppendUnique(LIBS = ['log'])
+
+if target_os in ['darwin', 'ios']:
+       examples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+OICMiddle = examples_env.Program('OICMiddle', ['OICMiddle.cpp', 'Client.cpp', 'LineInput.cpp', 'RestInput.cpp', 'Server.cpp', 'WrapResource.cpp'])
+
+Alias("examples", [OICMiddle])
+env.AppendTarget('examples')
+
+
+
index b55e715..b729a48 100644 (file)
@@ -45,10 +45,6 @@ OCEntityHandlerResult MiddleServer::entityHandler(const std::shared_ptr<OCResour
     int requestFlag = request->getRequestHandlerFlag();
     bool responseNeeded = false;
 
-    if (requestFlag && RequestHandlerFlag::InitFlag) {
-        return OC_EH_OK;
-    }
-
     if (requestFlag && RequestHandlerFlag::RequestFlag) {
         if (requestType == "PUT") {
             responseNeeded = true;
diff --git a/examples/OICMiddle/makefile b/examples/OICMiddle/makefile
deleted file mode 100644 (file)
index 5279218..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-#//******************************************************************
-#//
-#// Copyright 2014 Intel Corporation.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#//
-#// 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-# override with `make BUILD=release`
-# default to release build
-BUILD    := debug
-PLATFORM  := linux
-CXX      := g++
-#CXX     := clang
-OUT_DIR          := $(BUILD)
-OIC       := ../..
-OIC_RES   := $(OIC)/resource
-OIC_LIB   := $(OIC)/out/linux/x86_64/release
-OBJS     := OICMiddle.o \
-                               Client.o \
-                               Server.o \
-                               WrapResource.o \
-                               LineInput.o \
-                               RestInput.o
-                               
-CXX_FLAGS.debug     := -O0 -g3 -std=c++0x -Wall -pthread
-
-CXX_FLAGS.release   := -O3 -std=c++0x -Wall -pthread
-
-CXX_INC          := -I$(OIC_RES)/include/
-CXX_INC   += -I$(OIC_RES)/oc_logger/include
-CXX_INC          += -I$(OIC_RES)/csdk/stack/include
-CXX_INC          += -I$(OIC_RES)/csdk/ocsocket/include
-CXX_INC          += -I$(OIC_RES)/csdk/ocrandom/include
-CXX_INC          += -I$(OIC_RES)/csdk/logger/include
-CXX_INC          += -I$(OIC_RES)/csdk/libcoap
-CXX_INC   += -I$(OIC_RES)/../extlibs/cereal/include
-
-CXX_LIBS  := $(OIC_LIB)/liboc.so
-CXX_LIBS  += $(OIC_LIB)/liboctbstack.so
-CXX_LIBS  += $(OIC_LIB)/liboc_logger.so
-CXX_LIBS  += $(OIC_LIB)/liboc_logger_core.so
-CXX_LIBS  += $(OIC_LIB)/libcoap.so
-
-all: prep_dirs OICMiddle
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-       
-OICMiddle: $(OBJS)
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ $(OBJS) $(CXX_LIBS)
-
-OICMiddle.o: OICMiddle.cpp OICMiddle.h
-       $(CXX) -c $(CXX_FLAGS.$(BUILD)) OICMiddle.cpp $(CXX_INC)
-
-Client.o: Client.cpp Client.h OICMiddle.h
-       $(CXX) -c $(CXX_FLAGS.$(BUILD)) Client.cpp $(CXX_INC)
-
-Server.o: Server.cpp Server.h OICMiddle.h
-       $(CXX) -c $(CXX_FLAGS.$(BUILD)) Server.cpp $(CXX_INC)
-
-WrapResource.o: WrapResource.cpp WrapResource.h OICMiddle.h
-       $(CXX) -c $(CXX_FLAGS.$(BUILD)) WrapResource.cpp $(CXX_INC)
-       
-LineInput.o: LineInput.cpp LineInput.h OICMiddle.h
-       $(CXX) -c $(CXX_FLAGS.$(BUILD)) LineInput.cpp $(CXX_INC)
-       
-RestInput.o: RestInput.cpp RestInput.h OICMiddle.h
-       $(CXX) -c $(CXX_FLAGS.$(BUILD)) RestInput.cpp $(CXX_INC)
-       
-clean:
-       rm $(OBJS)
-       rm -rf debug
-       rm -rf release
-
index e9acb2d..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,9 +33,8 @@ 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/csdk/ocsocket/include',
                 IOTIVITY_ROOT + '/resource/oc_logger/include',
                 ])
 envClient.AppendUnique(LIBPATH = [IOTIVITY_LIBS_PATH])
@@ -58,8 +77,8 @@ try:
     envServer.AppendUnique(CPPPATH = [
                 sdk_root + '/usr/include/iotivity/',
                 sdk_root + '/usr/include/iotivity/stack/',
-                sdk_root + '/usr/include/iotivity/ocsocket/',
                 sdk_root + '/usr/include/iotivity/oc_logger/',
-                ])                     
+                ])
 except:
     print "ERROR configuring Yocto cross-toolchain environment. This is required for building the server"
+
diff --git a/extlibs/android/gradle/SConscript b/extlibs/android/gradle/SConscript
new file mode 100644 (file)
index 0000000..9cece4b
--- /dev/null
@@ -0,0 +1,29 @@
+import os, sys, platform, subprocess
+
+Import('env')
+
+env = env.Clone()
+ndk_env = env.Clone()
+SConscript('../../../build_common/external_libs.scons')
+
+target_os = env.get('TARGET_OS')
+host_os = sys.platform
+print host_os
+SConscript('../../../build_common/external_libs.scons')
+######################################################################
+# Build flags
+######################################################################
+src_dir = env.get('SRC_DIR')
+
+path = os.path.join(src_dir, 'extlibs', 'android', 'gradle', 'gradle-2.2.1')
+
+# check 'gradle' library, if it doesn't exits, ask user to download it
+if not os.path.exists(path):
+       gradle_zip = env.Download('gradle2.2.1.zip', 'https://services.gradle.org/distributions/gradle-2.2.1-all.zip')
+       gradle_dir = env.UnpackAll('gradle-2.2.1', gradle_zip)
+       print '''
+***********************************************************************
+* Downloading gradle:                    *
+*******************************************************************************
+'''
+
diff --git a/extlibs/android/ndk/SConscript b/extlibs/android/ndk/SConscript
new file mode 100644 (file)
index 0000000..cc36c4e
--- /dev/null
@@ -0,0 +1,37 @@
+import os, string, sys, subprocess, struct
+
+Import('env')
+
+env = env.Clone()
+ndk_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+target_arch = env.get('TARGET_ARCH')
+
+host_os = sys.platform
+
+######################################################################
+# Build flags
+######################################################################
+src_dir = env.get('SRC_DIR')
+path = os.path.join(src_dir, 'extlibs', 'android', 'ndk', 'android-ndk-r10d')
+
+# check 'ndk' library, if it doesn't exits, ask user to download it
+if not os.path.exists(path):
+       ndk_env = Environment(ENV = os.environ)
+       if host_os == 'linux2' :
+               archType = 8 * struct.calcsize("P")
+               if archType == 64:
+                       env.Download('android-ndk-r10d.bin', 'http://dl.google.com/android/ndk/android-ndk-r10d-linux-x86_64.bin')
+               else:
+                       env.Download('android-ndk-r10d.bin', 'http://dl.google.com/android/ndk/android-ndk-r10d-linux-x86.bin')
+
+               os.system("chmod a+x android-ndk-r10d.bin")
+               os.system("./android-ndk-r10d.bin")
+       else:
+               if target_arch in ['x86_64']:
+                       env.Download('android-ndk-r10d', 'http://dl.google.com/android/ndk/android-ndk-r10d-windows-x86_64.exe')
+               if target_arch in ['x86']:
+                       env.Download('android-ndk-r10d', 'http://dl.google.com/android/ndk/android-ndk-r10d-windows-x86.exe')
+
+
diff --git a/extlibs/android/sdk/SConscript b/extlibs/android/sdk/SConscript
new file mode 100644 (file)
index 0000000..aa268e6
--- /dev/null
@@ -0,0 +1,58 @@
+##
+# Script to install (if they do not exist) the Android SDK library (ie. Android JDK)
+##
+
+import os, subprocess, struct
+import urllib2, urlparse
+import SCons.Errors
+import shutil
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
+SConscript(src_dir + '/build_common/tools/UnpackAll.py')
+SConscript(src_dir + '/build_common/external_libs.scons')
+
+# Download
+if target_os == 'android':
+       android_home = env.get('ANDROID_HOME')
+       if not android_home:
+               print 'Creating ANDROID_HOME for Android SDK'
+
+               androidlib_dir      = src_dir + '/extlibs/android/sdk/android-sdk_r24.2'
+
+               if not os.path.exists(androidlib_dir):
+                       from sys import platform as _platform
+                       if _platform == "linux" or _platform == "linux2":
+                               androidlib_zip_file = src_dir + '/extlibs/android/android-sdk_r24.2-linux.tgz'
+                               androidlib_url      = 'http://dl.google.com/android/android-sdk_r24.2-linux.tgz'
+                       elif _platform == "darwin":
+                               androidlib_zip_file = src_dir + '/extlibs/android/android-sdk_r24.2-macosx.zip'
+                               androidlib_url      = 'http://dl.google.com/android/android-sdk_r24.2-macosx.zip'
+                       elif _platform == "win32":
+                               androidlib_zip_file = src_dir + '/extlibs/android/android-sdk_r24.2-windows.zip'
+                               androidlib_url      = 'http://dl.google.com/android/android-sdk_r24.2-windows.zip'
+
+                       # If the zip file is not already present, download it
+                       if not os.path.exists(androidlib_zip_file):
+                               androidlib_zip = env.Download(androidlib_zip_file, androidlib_url)
+                       else:
+                               androidlib_zip = androidlib_zip_file
+
+                       # Unzip the lib
+                       print 'Unzipping android lib...'
+                       env.UnpackAll(androidlib_dir, androidlib_zip)
+                       print 'Unzipping android lib complete'
+    
+                       # Remove downloaded file
+#                      os.remove(androidlib_zip_file)
+       else:
+               androidlib_dir = env.get('ANDROID_HOME')
+
+# Set the ANDROID_HOME
+env.Replace(ANDROID_HOME = androidlib_dir)
+print 'ANDROID_HOME = ' + env.get('ANDROID_HOME')
+
+
diff --git a/extlibs/arduino/SConscript b/extlibs/arduino/SConscript
new file mode 100644 (file)
index 0000000..268c061
--- /dev/null
@@ -0,0 +1,154 @@
+##
+# Script to install (if they do not exist) the Arduino library, Time library,
+# Red Bear Library, and Nordic library.
+##
+
+import os, subprocess, struct
+import urllib2, urlparse
+import SCons.Errors
+import shutil
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
+SConscript(src_dir + '/build_common/tools/UnpackAll.py')
+SConscript(src_dir + '/build_common/external_libs.scons')
+
+# Download
+if target_os == 'arduino':
+       arduino_home = env.get('ARDUINO_HOME')
+       if not arduino_home:
+               print 'Creating ARDUINO_HOME for Arduino lib'
+               print '''
+        *******************************************************************************
+        *   Arduino root directory isn't set, you can set enviornment variable        *
+        *   ARDUINO_HOME or add it in command line as follows (Only set if your       *
+        *   version has fixes applied as depicted below. Press ctrl+c now if you      *
+        *   wish to manually set ARDUINO_HOME.):                                      *
+        *      # scons ARDUINO_HOME=<path to arduino root directory> ...              *
+        *******************************************************************************
+        '''
+               arduinolib_dir      = src_dir + '/extlibs/arduino/arduino-1.5.8'
+
+               if not os.path.exists(arduinolib_dir):
+                       from sys import platform as _platform
+                       if _platform == "linux" or _platform == "linux2":
+                               archType = 8 * struct.calcsize("P")
+                               print 'On %s-bit machine.' % (archType)
+                               if archType == 32:
+                                       arduinolib_zip_file = src_dir + '/extlibs/arduino/arduino-1.5.8-linux32.tgz'
+                                       arduinolib_url      = 'http://arduino.cc/download.php?f=/arduino-1.5.8-linux32.tgz'
+                               else:
+                                       arduinolib_zip_file = src_dir + '/extlibs/arduino/arduino-1.5.8-linux64.tgz'
+                                       arduinolib_url      = 'http://arduino.cc/download.php?f=/arduino-1.5.8-linux64.tgz'
+                       elif _platform == "darwin":
+                               arduinolib_zip_file = src_dir + '/extlibs/arduino/arduino-1.5.8-macosx.zip'
+                               arduinolib_url      = 'http://arduino.cc/download.php?f=/arduino-1.5.8-macosx.zip'
+                       elif _platform == "win32":
+                               arduinolib_zip_file = src_dir + '/extlibs/arduino/arduino-1.5.8-windows.zip'
+                               arduinolib_url      = src_dir + 'http://arduino.cc/download.php?f=/arduino-1.5.8-windows.zip'
+
+                       # If the zip file is not already present, download it
+                       if not os.path.exists(arduinolib_zip_file):
+                               arduinolib_zip = env.Download(arduinolib_zip_file, arduinolib_url)
+                       else:
+                               arduinolib_zip = arduinolib_zip_file
+
+                       # Unzip the lib
+                       print 'Unzipping arduino lib...'
+                       env.UnpackAll(arduinolib_dir, arduinolib_zip)
+                       print 'Unzipping arduino lib complete'
+
+                       # Remove downloaded file
+                       os.remove(arduinolib_zip_file)
+       else:
+               arduinolib_dir = env.get('ARDUINO_HOME')
+
+       timelib_dir         = arduinolib_dir + '/libraries/Time'
+
+       if not os.path.exists(timelib_dir):
+               timelib_zip_file    = src_dir + '/extlibs/arduino/Time.zip'
+               timelib_url         = 'http://playground.arduino.cc/uploads/Code/Time.zip'
+               # Install Arduino Time library
+               # If the zip file is not already present, download it
+               os.mkdir(timelib_dir)
+               os.chdir(timelib_dir)
+               if not os.path.exists(timelib_zip_file):
+                       timelib_zip = env.Download(timelib_zip_file, timelib_url)
+               else:
+                       timelib_zip = timelib_zip_file
+
+               # Unzip the lib
+               print 'Unzipping Arduino Time lib...'
+               env.UnpackAll(timelib_dir + '/Time', timelib_zip)
+
+               # Apply patches to ARDUINO_HOME directory.
+               os.chdir(arduinolib_dir)
+               print 'Patching Arduino libraries...'
+               os.system("find ./libraries/Time/Time/DateStrings.cpp -type f -exec dos2unix {} \;")
+               os.system("patch -p1 < " + src_dir + "/resource/csdk/connectivity/lib/arduino/arduino_libraries.patch --directory=" + arduinolib_dir)
+
+               # Remove downloaded file
+               os.remove(timelib_zip_file)
+
+       redbearlib_dir         = arduinolib_dir + '/libraries/RBL_nRF8001'
+
+       if not os.path.exists(redbearlib_dir):
+               redbearlib_zip_file    = src_dir + '/extlibs/arduino/25643e7b1b7da3740406325a471e3faa4b948747.zip'
+               redbearlib_url         = 'https://github.com/RedBearLab/nRF8001/archive/25643e7b1b7da3740406325a471e3faa4b948747.zip'
+               if not os.path.exists(redbearlib_zip_file):
+                       redbearlib_zip = env.Download(redbearlib_zip_file, redbearlib_url)
+               else:
+                       redbearlib_zip = redbearlib_zip_file
+
+               # Unzip the lib
+               print 'Unzipping Red Bear lib...'
+               os.chdir(arduinolib_dir + '/libraries')
+               env.UnpackAll(redbearlib_dir, redbearlib_zip)
+
+               # Because the way Red Bear lib is distributed... All Red Bear source files must be moved up a few directories.
+               shutil.move('nRF8001-25643e7b1b7da3740406325a471e3faa4b948747/Arduino/libraries/RBL_nRF8001/', '.')
+               shutil.rmtree('nRF8001-25643e7b1b7da3740406325a471e3faa4b948747')
+
+               # Apply Red Bear patches
+               print 'Patching Red Bear library...'
+               os.chdir(arduinolib_dir + '/libraries/RBL_nRF8001/')
+               os.system("find . -type f -exec dos2unix {} \;")
+               os.system("patch -p1 < " + src_dir + "/resource/csdk/connectivity/lib/arduino/RBL_nRF8001.patch")
+
+               # Remove downloaded file
+               os.remove(redbearlib_zip_file)
+
+       nordiclib_dir           = arduinolib_dir + '/libraries/BLE'
+
+       if not os.path.exists(nordiclib_dir):
+               nordiclib_zip_file    = src_dir + '/extlibs/arduino/ble-sdk-arduino-0.9.5.beta.zip'
+                nordiclib_url         = 'https://github.com/NordicSemiconductor/ble-sdk-arduino/archive/0.9.5.beta.zip'
+               if not os.path.exists(nordiclib_zip_file):
+                       nordiclib_zip = env.Download(nordiclib_zip_file, nordiclib_url)
+               else:
+                       nordiclib_zip = nordiclib_zip_file
+
+               # Unzip the lib
+               print 'Unzipping Nordic lib...'
+               os.chdir(arduinolib_dir + '/libraries')
+               env.UnpackAll(nordiclib_dir, nordiclib_zip)
+
+               # Because the way Nordic lib is distributed... All Nordic source files must be moved up a few directories.
+               shutil.move('ble-sdk-arduino-0.9.5.beta/libraries/BLE/', '.')
+               shutil.rmtree('ble-sdk-arduino-0.9.5.beta')
+
+               # Apply Nordic lib patches
+               print 'Patching Nordic library...'
+               os.chdir(arduinolib_dir + '/libraries/BLE/')
+               os.system("find . -type f -exec dos2unix {} \;")
+               os.system("patch -p1 < " + src_dir + "/resource/csdk/connectivity/lib/arduino/arduino_due_ble.patch")
+               
+               # Remove downloaded file
+               os.remove(nordiclib_zip_file)
+
+# Set the ARDUINO_HOME
+env.Replace(ARDUINO_HOME = arduinolib_dir)
+print 'ARDUINO_HOME = ' + env.get('ARDUINO_HOME')
diff --git a/extlibs/boost/SConscript b/extlibs/boost/SConscript
new file mode 100644 (file)
index 0000000..0fe0662
--- /dev/null
@@ -0,0 +1,56 @@
+import os, string, sys, subprocess
+
+Import('env')
+
+boost_env = env.Clone()
+
+modules = ['thread','program_options']
+
+target_os = env.get('TARGET_OS')
+target_arch = env.get('TARGET_ARCH')
+
+if 'linux' == target_os :
+    # Check for Boost libraries in /usr/boost
+    print 'TODO: Perform platform check for linux'
+    raise SCons.Errors.EnvironmentError('Unsupported platform')
+
+if 'android' == target_os :
+    env.Tool('URLDownload',    toolpath=['../../tools/scons'])
+    env.Tool('UnpackAll',      toolpath=['../../tools/scons'])
+    env.Tool('BoostBootstrap', toolpath=['../../tools/scons'])
+    env.Tool('BoostBuild',     toolpath=['../../tools/scons'])
+
+    boost_version   = '1.58.0'
+    boost_base_name  = 'boost_'+string.replace(boost_version,'.','_')
+    boost_arch_name  = boost_base_name+'.zip'
+    boost_url       = 'http://downloads.sourceforge.net/project/boost/boost/'+boost_version+'/'+boost_arch_name+'?r=&ts=1421801329&use_mirror=iweb'
+
+    host_os = sys.platform
+
+    if host_os == 'linux2' :
+        boost_bootstrap = boost_base_name+os.sep+'bootstrap.sh'
+        boost_b2_name    = boost_base_name+os.sep+'b2'
+    else :
+        msg="Host platform (%s) is currently not supported for boost builds" % host_os
+        raise SCons.Errors.EnvironmentError(msg)
+
+    boost_zip = env.URLDownload(boost_arch_name, boost_url)
+    boost_dir = env.UnpackAll(boost_bootstrap, boost_zip)
+    boost_b2  = env.BoostBootstrap(boost_b2_name, boost_dir)
+
+    dep_sys_root = env['DEP_SYS_ROOT']
+    dep_src_dir =  dep_sys_root + os.sep + 'include'
+    dep_lib_dir =  dep_sys_root + os.sep + 'lib'
+
+    boost_targets = [
+        os.path.join(dep_src_dir, 'boost', 'config.hpp'),
+        os.path.join(dep_src_dir, 'boost', 'variant.hpp'),
+        os.path.join(dep_src_dir, 'boost', 'program_options.hpp'),
+        os.path.join(dep_src_dir, 'libboost_thread.a'),
+        os.path.join(dep_src_dir, 'libboost_atomic.a'),
+        os.path.join(dep_src_dir, 'libboost_system.a'),
+        os.path.join(dep_src_dir, 'libboost_program_options.a')
+        ]
+
+    boost_build = env.BoostBuild(boost_targets, boost_b2, PREFIX=dep_sys_root, MODULES=modules)
+
diff --git a/extlibs/cereal/SConscript b/extlibs/cereal/SConscript
new file mode 100644 (file)
index 0000000..946a483
--- /dev/null
@@ -0,0 +1,41 @@
+######################################################################
+# Cereal library build script
+#
+# Only 'hpp' is used by Iotivity, it's unnecessary to build it
+######################################################################
+import os
+
+Import('env')
+
+src_dir = env.get('SRC_DIR')
+
+# In the pass, cereal library is in extlibs/cereal, according to external
+# library management rule, cereal should be put in extlibs/cereal/cereal.
+# jenkins of gerrit server, still follow the old, to avoid jenkins fail
+# both places are handled.
+old = os.path.join(src_dir, 'extlibs', 'cereal', 'include')
+cur = os.path.join(src_dir, 'extlibs', 'cereal', 'cereal', 'include')
+
+# check 'cereal' library, if it doesn't exits, ask user to download it
+if not os.path.exists(old) and not os.path.exists(cur):
+       cereal_env = Environment(ENV = os.environ)
+       c = cereal_env.Action(['git clone https://github.com/USCiLab/cereal.git cereal',
+               'cd cereal && git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245 && git apply ../../../resource/patches/cereal_gcc46.patch',
+               ])
+
+       print 'Downloading cereal library ...'
+       if cereal_env.Execute(c):
+               print '''
+*********************************** Error: ************************************
+* Please download cereal and apply the patch as following:                    *
+*     $ git clone https://github.com/USCiLab/cereal.git extlibs/cereal/cereal *
+*     $ cd  extlibs/cereal/cereal                                             *
+*     $ git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245             *
+*     $ git apply ../../../resource/patches/cereal_gcc46.patch                *
+*******************************************************************************
+'''
+               Exit(1)
+       else:
+               print 'Download cereal library complete'
+
+env.AppendUnique(CPPPATH = [old, cur])
diff --git a/extlibs/expat/SConscript b/extlibs/expat/SConscript
new file mode 100644 (file)
index 0000000..e6b929c
--- /dev/null
@@ -0,0 +1,55 @@
+##
+# build script for expat library
+#
+# Note:
+#   1) Only a part of source code are required to be built.
+#   2) Download code from https://android.googlesource.com/platform/external/expat.git
+# otherwise, after code is downloaded, it's required to execute './configure' to
+# generate expat_config.h
+#
+##
+
+import os
+
+Import('env')
+
+expat_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/build_common/tools/UnpackAll.py')
+######################################################################
+# Build flags
+######################################################################
+src_dir = 'expat-2.1.0/'
+
+if not os.path.exists(src_dir):
+       # Prepare source code (download / unpack / run configure)
+       env.Download('expat.tar.gz', 'http://sourceforge.net/projects/expat/files/expat/2.1.0/expat-2.1.0.tar.gz/download')
+       expat_src = env.UnpackAll(src_dir + '/Makefile', 'expat.tar.gz')
+       env.Configure(src_dir, './configure')
+
+expat_env.AppendUnique(CPPPATH = [src_dir, src_dir + 'lib', src_dir + 'vms'])
+
+target_os = env.get('TARGET_OS')
+if target_os not in ['windows', 'winrt']:
+       expat_env.AppendUnique(CCFLAGS = ['-g', '-O2', '-Wall',
+                       '-Wmissing-prototypes', '-Wstrict-prototypes',
+                       '-fexceptions', '-fno-common'])
+       expat_env.AppendUnique(CPPDEFINES = ['HAVE_EXPAT_CONFIG_H'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+expat_src = [
+       src_dir + 'lib/xmlparse.c',
+       src_dir + 'lib/xmltok.c',
+       src_dir + 'lib/xmlrole.c',
+       ]
+
+libexpat = expat_env.SharedLibrary('expat', expat_src)
+
+######################################################################
+# Install header files and library binary
+######################################################################
+h = expat_env.InstallHeadFile([src_dir + 'lib/expat.h', src_dir + 'lib/expat_external.h'])
+lib = expat_env.InstallLib(libexpat)
+
+expat_env.AppendTarget('libexpat', [h, lib])
diff --git a/extlibs/gtest/SConscript b/extlibs/gtest/SConscript
new file mode 100644 (file)
index 0000000..396e4f3
--- /dev/null
@@ -0,0 +1,80 @@
+##
+# 'googletest' script to check if Google Unit Test library is installed.  If not,
+# get it and install it
+#
+##
+
+import os
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
+targets_need_gtest = ['darwin','linux']
+gtest_dir      = src_dir + '/extlibs/gtest/gtest-1.7.0'
+gtest_zip_file = src_dir + '/extlibs/gtest/gtest-1.7.0.zip'
+gtest_url      = 'https://googletest.googlecode.com/files/gtest-1.7.0.zip'
+
+if target_os in targets_need_gtest:
+       print '*** Checking for installation of google unit test 1.7.0 ***'
+
+       if not os.path.exists(gtest_dir):
+               # If the gtest zip file is not already present, download it
+               if not os.path.exists(gtest_zip_file):
+                       gtest_zip = env.Download(gtest_zip_file, gtest_url)
+               else:
+                       gtest_zip = gtest_zip_file
+
+               # Unzip gtest
+               print 'Unzipping google unit test'
+               env.UnpackAll(gtest_dir, gtest_zip)
+
+
+if target_os == 'darwin':
+       if os.path.exists(gtest_dir):
+               # Build gtest and store it at a temporary directory
+               gtest_lib_dir = gtest_dir + '/lib'
+               gtest_dotlib_dir = gtest_lib_dir + '/.libs'
+
+               if not os.path.exists(gtest_lib_dir):
+                       print 'Create a directory'
+                       os.mkdir(gtest_lib_dir)
+
+                       print 'Change to a directory'
+                       os.chdir(gtest_lib_dir)
+
+                       print 'Invoke cmake command to generate appropriate make files'
+                       env.Configure(gtest_lib_dir, 'cmake -G"Unix Makefiles" ..')
+
+                       # Run make on gtest
+                       print 'Making google unit test'
+                       env.Configure(gtest_lib_dir, 'make')
+
+                       print 'Create a directory'
+                       os.mkdir(gtest_dotlib_dir)
+
+                       print 'Change to a directory'
+                       os.chdir(gtest_dotlib_dir)
+
+                       print 'Create hard links pointing to gtest libraries'
+                       os.link('../' + 'libgtest.a', 'libgtest.a')
+                       os.link('../' + 'libgtest_main.a', 'libgtest_main.a')
+                       print 'Create hard links pointing to gtest libraries - DONE'
+
+
+elif target_os == 'linux':
+       if os.path.exists(gtest_dir):
+               if not os.path.exists(gtest_dir + "/lib"):
+                       # Run configure on gtest
+                       print 'Configuring google unit test'
+                       if env.get('CROSS_COMPILE'): 
+                               env.Configure(gtest_dir, './configure --host=' + env['CROSS_COMPILE'])
+                       else:
+                               env.Configure(gtest_dir, './configure')
+
+                       # Run make on gtest
+                       print 'Making google unit test'
+                       env.Configure(gtest_dir, 'make')
+
+
diff --git a/extlibs/hippomocks.scons b/extlibs/hippomocks.scons
new file mode 100644 (file)
index 0000000..6d5b5a4
--- /dev/null
@@ -0,0 +1,58 @@
+#******************************************************************
+#
+# 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
+#
+##
+
+import os, sys
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
+# Only verify/install on linux
+if target_os == 'linux':
+       print '*** Checking for installation of hippomocks ***'
+
+       hippomocks_sha      = '2f40aa11e31499432283b67f9d3449a3cd7b9c4d'
+       hippomocks_dir_src  = src_dir + '/extlibs/hippomocks-' + hippomocks_sha
+       hippomocks_dir_dest = src_dir + '/extlibs/hippomocks-master'
+       hippomocks_zip_file = src_dir + '/extlibs/hippomocks-' + hippomocks_sha + '.zip'
+       hippomocks_url      = 'https://github.com/dascandy/hippomocks/archive/' + hippomocks_sha + '.zip'
+
+       if not os.path.exists(hippomocks_dir_dest):
+               # If the hippomocks zip file is not already present, download it
+               if not os.path.exists(hippomocks_zip_file):
+                       hippomocks_zip = env.Download(hippomocks_zip_file, hippomocks_url)
+               else:
+                       hippomocks_zip = hippomocks_zip_file
+
+               # Unzip hippomocks
+               print 'Unzipping hippomocks'
+               env.UnpackAll(hippomocks_dir_src, hippomocks_zip)
+               print 'Renaming hippomocks directory'
+               os.rename(hippomocks_dir_src, hippomocks_dir_dest)
+
+
+
diff --git a/extlibs/rapidxml/rapidxml.hpp b/extlibs/rapidxml/rapidxml.hpp
new file mode 100644 (file)
index 0000000..0845cfb
--- /dev/null
@@ -0,0 +1,2638 @@
+#ifndef RAPIDXML_HPP_INCLUDED
+#define RAPIDXML_HPP_INCLUDED
+
+// Copyright (C) 2006, 2009 Marcin Kalicinski
+// Version 1.13
+// Revision $DateTime: 2009/05/13 01:46:17 $
+//! \file rapidxml.hpp This file contains rapidxml parser and DOM implementation
+
+// If standard library is disabled, user must provide implementations of required functions and typedefs
+#if !defined(RAPIDXML_NO_STDLIB)
+#include <cstdlib>      // For std::size_t
+#include <cassert>      // For assert
+#include <new>          // For placement new
+#endif
+
+// On MSVC, disable "conditional expression is constant" warning (level 4).
+// This warning is almost impossible to avoid with certain types of templated code
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4127)   // Conditional expression is constant
+#endif
+
+///////////////////////////////////////////////////////////////////////////
+// RAPIDXML_PARSE_ERROR
+
+#if defined(RAPIDXML_NO_EXCEPTIONS)
+
+#define RAPIDXML_PARSE_ERROR(what, where) { parse_error_handler(what, where); assert(0); }
+
+namespace rapidxml
+{
+    //! When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS,
+    //! this function is called to notify user about the error.
+    //! It must be defined by the user.
+    //! <br><br>
+    //! This function cannot return. If it does, the results are undefined.
+    //! <br><br>
+    //! A very simple definition might look like that:
+    //! <pre>
+    //! void %rapidxml::%parse_error_handler(const char *what, void *where)
+    //! {
+    //!     std::cout << "Parse error: " << what << "\n";
+    //!     std::abort();
+    //! }
+    //! </pre>
+    //! \param what Human readable description of the error.
+    //! \param where Pointer to character data where error was detected.
+    void parse_error_handler(const char *what, void *where);
+}
+
+#else
+
+#include <exception>    // For std::exception
+
+#define RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where)
+
+namespace rapidxml
+{
+
+    //! Parse error exception.
+    //! This exception is thrown by the parser when an error occurs.
+    //! Use what() function to get human-readable error message.
+    //! Use where() function to get a pointer to position within source text where error was detected.
+    //! <br><br>
+    //! If throwing exceptions by the parser is undesirable,
+    //! it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included.
+    //! This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception.
+    //! This function must be defined by the user.
+    //! <br><br>
+    //! This class derives from <code>std::exception</code> class.
+    class parse_error: public std::exception
+    {
+
+        public:
+
+            //! Constructs parse error
+            parse_error(const char *what, void *where)
+                : m_what(what)
+                , m_where(where)
+            {
+            }
+
+            //! Gets human readable description of error.
+            //! \return Pointer to null terminated description of the error.
+            virtual const char *what() const throw()
+            {
+                return m_what;
+            }
+
+            //! Gets pointer to character data where error happened.
+            //! Ch should be the same as char type of xml_document that produced the error.
+            //! \return Pointer to location within the parsed string where error occured.
+            template<class Ch>
+            Ch *where() const
+            {
+                return reinterpret_cast<Ch *>(m_where);
+            }
+
+        private:
+
+            const char *m_what;
+            void *m_where;
+
+    };
+}
+
+#endif
+
+///////////////////////////////////////////////////////////////////////////
+// Pool sizes
+
+#ifndef RAPIDXML_STATIC_POOL_SIZE
+// Size of static memory block of memory_pool.
+// Define RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value.
+// No dynamic memory allocations are performed by memory_pool until static memory is exhausted.
+#define RAPIDXML_STATIC_POOL_SIZE (64 * 1024)
+#endif
+
+#ifndef RAPIDXML_DYNAMIC_POOL_SIZE
+// Size of dynamic memory block of memory_pool.
+// Define RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value.
+// After the static block is exhausted, dynamic blocks with approximately this size are allocated by memory_pool.
+#define RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024)
+#endif
+
+#ifndef RAPIDXML_ALIGNMENT
+// Memory allocation alignment.
+// Define RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to override the default value, which is the size of pointer.
+// All memory allocations for nodes, attributes and strings will be aligned to this value.
+// This must be a power of 2 and at least 1, otherwise memory_pool will not work.
+#define RAPIDXML_ALIGNMENT sizeof(void *)
+#endif
+
+namespace rapidxml
+{
+    // Forward declarations
+    template<class Ch> class xml_node;
+    template<class Ch> class xml_attribute;
+    template<class Ch> class xml_document;
+
+    //! Enumeration listing all node types produced by the parser.
+    //! Use xml_node::type() function to query node type.
+    enum node_type
+    {
+        node_document,      //!< A document node. Name and value are empty.
+        node_element,       //!< An element node. Name contains element name. Value contains text of first data node.
+        node_data,          //!< A data node. Name is empty. Value contains data text.
+        node_cdata,         //!< A CDATA node. Name is empty. Value contains data text.
+        node_comment,       //!< A comment node. Name is empty. Value contains comment text.
+        node_declaration,   //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.
+        node_doctype,       //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text.
+        node_pi             //!< A PI node. Name contains target. Value contains instructions.
+    };
+
+    ///////////////////////////////////////////////////////////////////////
+    // Parsing flags
+
+    //! Parse flag instructing the parser to not create data nodes.
+    //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_no_data_nodes = 0x1;
+
+    //! Parse flag instructing the parser to not use text of first data node as a value of parent element.
+    //! Can be combined with other flags by use of | operator.
+    //! Note that child data nodes of element node take precendence over its value when printing.
+    //! That is, if element has one or more child data nodes <em>and</em> a value, the value will be ignored.
+    //! Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_no_element_values = 0x2;
+
+    //! Parse flag instructing the parser to not place zero terminators after strings in the source text.
+    //! By default zero terminators are placed, modifying source text.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_no_string_terminators = 0x4;
+
+    //! Parse flag instructing the parser to not translate entities in the source text.
+    //! By default entities are translated, modifying source text.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_no_entity_translation = 0x8;
+
+    //! Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters.
+    //! By default, UTF-8 handling is enabled.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_no_utf8 = 0x10;
+
+    //! Parse flag instructing the parser to create XML declaration node.
+    //! By default, declaration node is not created.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_declaration_node = 0x20;
+
+    //! Parse flag instructing the parser to create comments nodes.
+    //! By default, comment nodes are not created.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_comment_nodes = 0x40;
+
+    //! Parse flag instructing the parser to create DOCTYPE node.
+    //! By default, doctype node is not created.
+    //! Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_doctype_node = 0x80;
+
+    //! Parse flag instructing the parser to create PI nodes.
+    //! By default, PI nodes are not created.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_pi_nodes = 0x100;
+
+    //! Parse flag instructing the parser to validate closing tag names.
+    //! If not set, name inside closing tag is irrelevant to the parser.
+    //! By default, closing tags are not validated.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_validate_closing_tags = 0x200;
+
+    //! Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes.
+    //! By default, whitespace is not trimmed.
+    //! This flag does not cause the parser to modify source text.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_trim_whitespace = 0x400;
+
+    //! Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character.
+    //! Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag.
+    //! By default, whitespace is not normalized.
+    //! If this flag is specified, source text will be modified.
+    //! Can be combined with other flags by use of | operator.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_normalize_whitespace = 0x800;
+
+    // Compound flags
+
+    //! Parse flags which represent default behaviour of the parser.
+    //! This is always equal to 0, so that all other flags can be simply ored together.
+    //! Normally there is no need to inconveniently disable flags by anding with their negated (~) values.
+    //! This also means that meaning of each flag is a <i>negation</i> of the default setting.
+    //! For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is <i>enabled</i> by default,
+    //! and using the flag will disable it.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_default = 0;
+
+    //! A combination of parse flags that forbids any modifications of the source text.
+    //! This also results in faster parsing. However, note that the following will occur:
+    //! <ul>
+    //! <li>names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends</li>
+    //! <li>entities will not be translated</li>
+    //! <li>whitespace will not be normalized</li>
+    //! </ul>
+    //! See xml_document::parse() function.
+    const int parse_non_destructive = parse_no_string_terminators | parse_no_entity_translation;
+
+    //! A combination of parse flags resulting in fastest possible parsing, without sacrificing important data.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_fastest = parse_non_destructive | parse_no_data_nodes;
+
+    //! A combination of parse flags resulting in largest amount of data being extracted.
+    //! This usually results in slowest parsing.
+    //! <br><br>
+    //! See xml_document::parse() function.
+    const int parse_full = parse_declaration_node | parse_comment_nodes | parse_doctype_node |
+                           parse_pi_nodes | parse_validate_closing_tags;
+
+    ///////////////////////////////////////////////////////////////////////
+    // Internals
+
+    //! \cond internal
+    namespace internal
+    {
+
+        // Struct that contains lookup tables for the parser
+        // It must be a template to allow correct linking (because it has static data members, which are defined in a header file).
+        template<int Dummy>
+        struct lookup_tables
+        {
+            static const unsigned char lookup_whitespace[256];              // Whitespace table
+            static const unsigned char lookup_node_name[256];               // Node name table
+            static const unsigned char lookup_text[256];                    // Text table
+            static const unsigned char lookup_text_pure_no_ws[256];         // Text table
+            static const unsigned char lookup_text_pure_with_ws[256];       // Text table
+            static const unsigned char lookup_attribute_name[256];          // Attribute name table
+            static const unsigned char
+            lookup_attribute_data_1[256];        // Attribute data table with single quote
+            static const unsigned char
+            lookup_attribute_data_1_pure[256];   // Attribute data table with single quote
+            static const unsigned char
+            lookup_attribute_data_2[256];        // Attribute data table with double quotes
+            static const unsigned char
+            lookup_attribute_data_2_pure[256];   // Attribute data table with double quotes
+            static const unsigned char lookup_digits[256];                  // Digits
+            static const unsigned char
+            lookup_upcase[256];                  // To uppercase conversion table for ASCII characters
+        };
+
+        // Find length of the string
+        template<class Ch>
+        inline std::size_t measure(const Ch *p)
+        {
+            const Ch *tmp = p;
+            while (*tmp)
+                ++tmp;
+            return tmp - p;
+        }
+
+        // Compare strings for equality
+        template<class Ch>
+        inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2,
+                            bool case_sensitive)
+        {
+            if (size1 != size2)
+                return false;
+            if (case_sensitive)
+            {
+                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
+                    if (*p1 != *p2)
+                        return false;
+            }
+            else
+            {
+                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
+                    if (lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p1)] !=
+                        lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p2)])
+                        return false;
+            }
+            return true;
+        }
+    }
+    //! \endcond
+
+    ///////////////////////////////////////////////////////////////////////
+    // Memory pool
+
+    //! This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation.
+    //! In most cases, you will not need to use this class directly.
+    //! However, if you need to create nodes manually or modify names/values of nodes,
+    //! you are encouraged to use memory_pool of relevant xml_document to allocate the memory.
+    //! Not only is this faster than allocating them by using <code>new</code> operator,
+    //! but also their lifetime will be tied to the lifetime of document,
+    //! possibly simplyfing memory management.
+    //! <br><br>
+    //! Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool.
+    //! You can also call allocate_string() function to allocate strings.
+    //! Such strings can then be used as names or values of nodes without worrying about their lifetime.
+    //! Note that there is no <code>free()</code> function -- all allocations are freed at once when clear() function is called,
+    //! or when the pool is destroyed.
+    //! <br><br>
+    //! It is also possible to create a standalone memory_pool, and use it
+    //! to allocate nodes, whose lifetime will not be tied to any document.
+    //! <br><br>
+    //! Pool maintains <code>RAPIDXML_STATIC_POOL_SIZE</code> bytes of statically allocated memory.
+    //! Until static memory is exhausted, no dynamic memory allocations are done.
+    //! When static memory is exhausted, pool allocates additional blocks of memory of size <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> each,
+    //! by using global <code>new[]</code> and <code>delete[]</code> operators.
+    //! This behaviour can be changed by setting custom allocation routines.
+    //! Use set_allocator() function to set them.
+    //! <br><br>
+    //! Allocations for nodes, attributes and strings are aligned at <code>RAPIDXML_ALIGNMENT</code> bytes.
+    //! This value defaults to the size of pointer on target architecture.
+    //! <br><br>
+    //! To obtain absolutely top performance from the parser,
+    //! it is important that all nodes are allocated from a single, contiguous block of memory.
+    //! Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably.
+    //! If required, you can tweak <code>RAPIDXML_STATIC_POOL_SIZE</code>, <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>RAPIDXML_ALIGNMENT</code>
+    //! to obtain best wasted memory to performance compromise.
+    //! To do it, define their values before rapidxml.hpp file is included.
+    //! \param Ch Character type of created nodes.
+    template<class Ch = char>
+    class memory_pool
+    {
+
+        public:
+
+            //! \cond internal
+            typedef void *(alloc_func)(
+                std::size_t);       // Type of user-defined function used to allocate memory
+            typedef void (free_func)(void *);              // Type of user-defined function used to free memory
+            //! \endcond
+
+            //! Constructs empty pool with default allocator functions.
+            memory_pool()
+                : m_alloc_func(0)
+                , m_free_func(0)
+            {
+                init();
+            }
+
+            //! Destroys pool and frees all the memory.
+            //! This causes memory occupied by nodes allocated by the pool to be freed.
+            //! Nodes allocated from the pool are no longer valid.
+            ~memory_pool()
+            {
+                clear();
+            }
+
+            //! Allocates a new node from the pool, and optionally assigns name and value to it.
+            //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
+            //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
+            //! will call rapidxml::parse_error_handler() function.
+            //! \param type Type of node to create.
+            //! \param name Name to assign to the node, or 0 to assign no name.
+            //! \param value Value to assign to the node, or 0 to assign no value.
+            //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
+            //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
+            //! \return Pointer to allocated node. This pointer will never be NULL.
+            xml_node<Ch> *allocate_node(node_type type,
+                                        const Ch *name = 0, const Ch *value = 0,
+                                        std::size_t name_size = 0, std::size_t value_size = 0)
+            {
+                void *memory = allocate_aligned(sizeof(xml_node<Ch>));
+                xml_node<Ch> *node = new(memory) xml_node<Ch>(type);
+                if (name)
+                {
+                    if (name_size > 0)
+                        node->name(name, name_size);
+                    else
+                        node->name(name);
+                }
+                if (value)
+                {
+                    if (value_size > 0)
+                        node->value(value, value_size);
+                    else
+                        node->value(value);
+                }
+                return node;
+            }
+
+            //! Allocates a new attribute from the pool, and optionally assigns name and value to it.
+            //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
+            //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
+            //! will call rapidxml::parse_error_handler() function.
+            //! \param name Name to assign to the attribute, or 0 to assign no name.
+            //! \param value Value to assign to the attribute, or 0 to assign no value.
+            //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
+            //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
+            //! \return Pointer to allocated attribute. This pointer will never be NULL.
+            xml_attribute<Ch> *allocate_attribute(const Ch *name = 0, const Ch *value = 0,
+                                                  std::size_t name_size = 0, std::size_t value_size = 0)
+            {
+                void *memory = allocate_aligned(sizeof(xml_attribute<Ch>));
+                xml_attribute<Ch> *attribute = new(memory) xml_attribute<Ch>;
+                if (name)
+                {
+                    if (name_size > 0)
+                        attribute->name(name, name_size);
+                    else
+                        attribute->name(name);
+                }
+                if (value)
+                {
+                    if (value_size > 0)
+                        attribute->value(value, value_size);
+                    else
+                        attribute->value(value);
+                }
+                return attribute;
+            }
+
+            //! Allocates a char array of given size from the pool, and optionally copies a given string to it.
+            //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
+            //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
+            //! will call rapidxml::parse_error_handler() function.
+            //! \param source String to initialize the allocated memory with, or 0 to not initialize it.
+            //! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated.
+            //! \return Pointer to allocated char array. This pointer will never be NULL.
+            Ch *allocate_string(const Ch *source = 0, std::size_t size = 0)
+            {
+                assert(source || size);     // Either source or size (or both) must be specified
+                if (size == 0)
+                    size = internal::measure(source) + 1;
+                Ch *result = static_cast<Ch *>(allocate_aligned(size * sizeof(Ch)));
+                if (source)
+                    for (std::size_t i = 0; i < size; ++i)
+                        result[i] = source[i];
+                return result;
+            }
+
+            //! Clones an xml_node and its hierarchy of child nodes and attributes.
+            //! Nodes and attributes are allocated from this memory pool.
+            //! Names and values are not cloned, they are shared between the clone and the source.
+            //! Result node can be optionally specified as a second parameter,
+            //! in which case its contents will be replaced with cloned source node.
+            //! This is useful when you want to clone entire document.
+            //! \param source Node to clone.
+            //! \param result Node to put results in, or 0 to automatically allocate result node
+            //! \return Pointer to cloned node. This pointer will never be NULL.
+            xml_node<Ch> *clone_node(const xml_node<Ch> *source, xml_node<Ch> *result = 0)
+            {
+                // Prepare result node
+                if (result)
+                {
+                    result->remove_all_attributes();
+                    result->remove_all_nodes();
+                    result->type(source->type());
+                }
+                else
+                    result = allocate_node(source->type());
+
+                // Clone name and value
+                result->name(source->name(), source->name_size());
+                result->value(source->value(), source->value_size());
+
+                // Clone child nodes and attributes
+                for (xml_node<Ch> *child = source->first_node(); child; child = child->next_sibling())
+                    result->append_node(clone_node(child));
+                for (xml_attribute<Ch> *attr = source->first_attribute(); attr; attr = attr->next_attribute())
+                    result->append_attribute(allocate_attribute(attr->name(), attr->value(), attr->name_size(),
+                                             attr->value_size()));
+
+                return result;
+            }
+
+            //! Clears the pool.
+            //! This causes memory occupied by nodes allocated by the pool to be freed.
+            //! Any nodes or strings allocated from the pool will no longer be valid.
+            void clear()
+            {
+                while (m_begin != m_static_memory)
+                {
+                    char *previous_begin = reinterpret_cast<header *>(align(m_begin))->previous_begin;
+                    if (m_free_func)
+                        m_free_func(m_begin);
+                    else
+                        delete[] m_begin;
+                    m_begin = previous_begin;
+                }
+                init();
+            }
+
+            //! Sets or resets the user-defined memory allocation functions for the pool.
+            //! This can only be called when no memory is allocated from the pool yet, otherwise results are undefined.
+            //! Allocation function must not return invalid pointer on failure. It should either throw,
+            //! stop the program, or use <code>longjmp()</code> function to pass control to other place of program.
+            //! If it returns invalid pointer, results are undefined.
+            //! <br><br>
+            //! User defined allocation functions must have the following forms:
+            //! <br><code>
+            //! <br>void *allocate(std::size_t size);
+            //! <br>void free(void *pointer);
+            //! </code><br>
+            //! \param af Allocation function, or 0 to restore default function
+            //! \param ff Free function, or 0 to restore default function
+            void set_allocator(alloc_func *af, free_func *ff)
+            {
+                assert(m_begin == m_static_memory
+                       && m_ptr == align(m_begin));    // Verify that no memory is allocated yet
+                m_alloc_func = af;
+                m_free_func = ff;
+            }
+
+        private:
+
+            struct header
+            {
+                char *previous_begin;
+            };
+
+            void init()
+            {
+                m_begin = m_static_memory;
+                m_ptr = align(m_begin);
+                m_end = m_static_memory + sizeof(m_static_memory);
+            }
+
+            char *align(char *ptr)
+            {
+                std::size_t alignment = ((RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (RAPIDXML_ALIGNMENT - 1))) &
+                                         (RAPIDXML_ALIGNMENT - 1));
+                return ptr + alignment;
+            }
+
+            char *allocate_raw(std::size_t size)
+            {
+                // Allocate
+                void *memory;
+                if (m_alloc_func)   // Allocate memory using either user-specified allocation function or global operator new[]
+                {
+                    memory = m_alloc_func(size);
+                    assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp
+                }
+                else
+                {
+                    memory = new char[size];
+#ifdef RAPIDXML_NO_EXCEPTIONS
+                    if (!memory)            // If exceptions are disabled, verify memory allocation, because new will not be able to throw bad_alloc
+                        RAPIDXML_PARSE_ERROR("out of memory", 0);
+#endif
+                }
+                return static_cast<char *>(memory);
+            }
+
+            void *allocate_aligned(std::size_t size)
+            {
+                // Calculate aligned pointer
+                char *result = align(m_ptr);
+
+                // If not enough memory left in current pool, allocate a new pool
+                if (result + size > m_end)
+                {
+                    // Calculate required pool size (may be bigger than RAPIDXML_DYNAMIC_POOL_SIZE)
+                    std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE;
+                    if (pool_size < size)
+                        pool_size = size;
+
+                    // Allocate
+                    std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) +
+                                             pool_size;     // 2 alignments required in worst case: one for header, one for actual allocation
+                    char *raw_memory = allocate_raw(alloc_size);
+
+                    // Setup new pool in allocated memory
+                    char *pool = align(raw_memory);
+                    header *new_header = reinterpret_cast<header *>(pool);
+                    new_header->previous_begin = m_begin;
+                    m_begin = raw_memory;
+                    m_ptr = pool + sizeof(header);
+                    m_end = raw_memory + alloc_size;
+
+                    // Calculate aligned pointer again using new pool
+                    result = align(m_ptr);
+                }
+
+                // Update pool and return aligned pointer
+                m_ptr = result + size;
+                return result;
+            }
+
+            char *m_begin;                                      // Start of raw memory making up current pool
+            char *m_ptr;                                        // First free byte in current pool
+            char *m_end;                                        // One past last available byte in current pool
+            char m_static_memory[RAPIDXML_STATIC_POOL_SIZE];    // Static raw memory
+            alloc_func
+            *m_alloc_func;                           // Allocator function, or 0 if default is to be used
+            free_func *m_free_func;                             // Free function, or 0 if default is to be used
+    };
+
+    ///////////////////////////////////////////////////////////////////////////
+    // XML base
+
+    //! Base class for xml_node and xml_attribute implementing common functions:
+    //! name(), name_size(), value(), value_size() and parent().
+    //! \param Ch Character type to use
+    template<class Ch = char>
+    class xml_base
+    {
+
+        public:
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Construction & destruction
+
+            // Construct a base with empty name, value and parent
+            xml_base()
+                : m_name(0)
+                , m_value(0)
+                , m_parent(0)
+            {
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Node data access
+
+            //! Gets name of the node.
+            //! Interpretation of name depends on type of node.
+            //! Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.
+            //! <br><br>
+            //! Use name_size() function to determine length of the name.
+            //! \return Name of node, or empty string if node has no name.
+            Ch *name() const
+            {
+                return m_name ? m_name : nullstr();
+            }
+
+            //! Gets size of node name, not including terminator character.
+            //! This function works correctly irrespective of whether name is or is not zero terminated.
+            //! \return Size of node name, in characters.
+            std::size_t name_size() const
+            {
+                return m_name ? m_name_size : 0;
+            }
+
+            //! Gets value of node.
+            //! Interpretation of value depends on type of node.
+            //! Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.
+            //! <br><br>
+            //! Use value_size() function to determine length of the value.
+            //! \return Value of node, or empty string if node has no value.
+            Ch *value() const
+            {
+                return m_value ? m_value : nullstr();
+            }
+
+            //! Gets size of node value, not including terminator character.
+            //! This function works correctly irrespective of whether value is or is not zero terminated.
+            //! \return Size of node value, in characters.
+            std::size_t value_size() const
+            {
+                return m_value ? m_value_size : 0;
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Node modification
+
+            //! Sets name of node to a non zero-terminated string.
+            //! See \ref ownership_of_strings.
+            //! <br><br>
+            //! Note that node does not own its name or value, it only stores a pointer to it.
+            //! It will not delete or otherwise free the pointer on destruction.
+            //! It is reponsibility of the user to properly manage lifetime of the string.
+            //! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
+            //! on destruction of the document the string will be automatically freed.
+            //! <br><br>
+            //! Size of name must be specified separately, because name does not have to be zero terminated.
+            //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated).
+            //! \param name Name of node to set. Does not have to be zero terminated.
+            //! \param size Size of name, in characters. This does not include zero terminator, if one is present.
+            void name(const Ch *name, std::size_t size)
+            {
+                m_name = const_cast<Ch *>(name);
+                m_name_size = size;
+            }
+
+            //! Sets name of node to a zero-terminated string.
+            //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t).
+            //! \param name Name of node to set. Must be zero terminated.
+            void name(const Ch *name)
+            {
+                this->name(name, internal::measure(name));
+            }
+
+            //! Sets value of node to a non zero-terminated string.
+            //! See \ref ownership_of_strings.
+            //! <br><br>
+            //! Note that node does not own its name or value, it only stores a pointer to it.
+            //! It will not delete or otherwise free the pointer on destruction.
+            //! It is reponsibility of the user to properly manage lifetime of the string.
+            //! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
+            //! on destruction of the document the string will be automatically freed.
+            //! <br><br>
+            //! Size of value must be specified separately, because it does not have to be zero terminated.
+            //! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated).
+            //! <br><br>
+            //! If an element has a child node of type node_data, it will take precedence over element value when printing.
+            //! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser.
+            //! \param value value of node to set. Does not have to be zero terminated.
+            //! \param size Size of value, in characters. This does not include zero terminator, if one is present.
+            void value(const Ch *value, std::size_t size)
+            {
+                m_value = const_cast<Ch *>(value);
+                m_value_size = size;
+            }
+
+            //! Sets value of node to a zero-terminated string.
+            //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t).
+            //! \param value Vame of node to set. Must be zero terminated.
+            void value(const Ch *value)
+            {
+                this->value(value, internal::measure(value));
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Related nodes access
+
+            //! Gets node parent.
+            //! \return Pointer to parent node, or 0 if there is no parent.
+            xml_node<Ch> *parent() const
+            {
+                return m_parent;
+            }
+
+        protected:
+
+            // Return empty string
+            static Ch *nullstr()
+            {
+                static Ch zero = Ch('\0');
+                return &zero;
+            }
+
+            Ch *m_name;                         // Name of node, or 0 if no name
+            Ch *m_value;                        // Value of node, or 0 if no value
+            std::size_t m_name_size;            // Length of node name, or undefined of no name
+            std::size_t m_value_size;           // Length of node value, or undefined if no value
+            xml_node<Ch> *m_parent;             // Pointer to parent node, or 0 if none
+
+    };
+
+    //! Class representing attribute node of XML document.
+    //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base).
+    //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing.
+    //! Thus, this text must persist in memory for the lifetime of attribute.
+    //! \param Ch Character type to use.
+    template<class Ch = char>
+    class xml_attribute: public xml_base<Ch>
+    {
+
+            friend class xml_node<Ch>;
+
+        public:
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Construction & destruction
+
+            //! Constructs an empty attribute with the specified type.
+            //! Consider using memory_pool of appropriate xml_document if allocating attributes manually.
+            xml_attribute()
+            {
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Related nodes access
+
+            //! Gets document of which attribute is a child.
+            //! \return Pointer to document that contains this attribute, or 0 if there is no parent document.
+            xml_document<Ch> *document() const
+            {
+                if (xml_node<Ch> *node = this->parent())
+                {
+                    while (node->parent())
+                        node = node->parent();
+                    return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0;
+                }
+                else
+                    return 0;
+            }
+
+            //! Gets previous attribute, optionally matching attribute name.
+            //! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found attribute, or 0 if not found.
+            xml_attribute<Ch> *previous_attribute(const Ch *name = 0, std::size_t name_size = 0,
+                                                  bool case_sensitive = true) const
+            {
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_attribute<Ch> *attribute = m_prev_attribute; attribute;
+                         attribute = attribute->m_prev_attribute)
+                        if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
+                            return attribute;
+                    return 0;
+                }
+                else
+                    return this->m_parent ? m_prev_attribute : 0;
+            }
+
+            //! Gets next attribute, optionally matching attribute name.
+            //! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found attribute, or 0 if not found.
+            xml_attribute<Ch> *next_attribute(const Ch *name = 0, std::size_t name_size = 0,
+                                              bool case_sensitive = true) const
+            {
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_attribute<Ch> *attribute = m_next_attribute; attribute;
+                         attribute = attribute->m_next_attribute)
+                        if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
+                            return attribute;
+                    return 0;
+                }
+                else
+                    return this->m_parent ? m_next_attribute : 0;
+            }
+
+        private:
+
+            xml_attribute<Ch>
+            *m_prev_attribute;        // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero
+            xml_attribute<Ch>
+            *m_next_attribute;        // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero
+
+    };
+
+    ///////////////////////////////////////////////////////////////////////////
+    // XML node
+
+    //! Class representing a node of XML document.
+    //! Each node may have associated name and value strings, which are available through name() and value() functions.
+    //! Interpretation of name and value depends on type of the node.
+    //! Type of node can be determined by using type() function.
+    //! <br><br>
+    //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing.
+    //! Thus, this text must persist in the memory for the lifetime of node.
+    //! \param Ch Character type to use.
+    template<class Ch = char>
+    class xml_node: public xml_base<Ch>
+    {
+
+        public:
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Construction & destruction
+
+            //! Constructs an empty node with the specified type.
+            //! Consider using memory_pool of appropriate document to allocate nodes manually.
+            //! \param type Type of node to construct.
+            xml_node(node_type type)
+                : m_type(type)
+                , m_first_node(0)
+                , m_first_attribute(0)
+            {
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Node data access
+
+            //! Gets type of node.
+            //! \return Type of node.
+            node_type type() const
+            {
+                return m_type;
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Related nodes access
+
+            //! Gets document of which node is a child.
+            //! \return Pointer to document that contains this node, or 0 if there is no parent document.
+            xml_document<Ch> *document() const
+            {
+                xml_node<Ch> *node = const_cast<xml_node<Ch> *>(this);
+                while (node->parent())
+                    node = node->parent();
+                return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0;
+            }
+
+            //! Gets first child node, optionally matching node name.
+            //! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found child, or 0 if not found.
+            xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0,
+                                     bool case_sensitive = true) const
+            {
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling())
+                        if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
+                            return child;
+                    return 0;
+                }
+                else
+                    return m_first_node;
+            }
+
+            //! Gets last child node, optionally matching node name.
+            //! Behaviour is undefined if node has no children.
+            //! Use first_node() to test if node has children.
+            //! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found child, or 0 if not found.
+            xml_node<Ch> *last_node(const Ch *name = 0, std::size_t name_size = 0,
+                                    bool case_sensitive = true) const
+            {
+                assert(m_first_node);  // Cannot query for last child if node has no children
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_node<Ch> *child = m_last_node; child; child = child->previous_sibling())
+                        if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
+                            return child;
+                    return 0;
+                }
+                else
+                    return m_last_node;
+            }
+
+            //! Gets previous sibling node, optionally matching node name.
+            //! Behaviour is undefined if node has no parent.
+            //! Use parent() to test if node has a parent.
+            //! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found sibling, or 0 if not found.
+            xml_node<Ch> *previous_sibling(const Ch *name = 0, std::size_t name_size = 0,
+                                           bool case_sensitive = true) const
+            {
+                assert(this->m_parent);     // Cannot query for siblings if node has no parent
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_node<Ch> *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling)
+                        if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive))
+                            return sibling;
+                    return 0;
+                }
+                else
+                    return m_prev_sibling;
+            }
+
+            //! Gets next sibling node, optionally matching node name.
+            //! Behaviour is undefined if node has no parent.
+            //! Use parent() to test if node has a parent.
+            //! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found sibling, or 0 if not found.
+            xml_node<Ch> *next_sibling(const Ch *name = 0, std::size_t name_size = 0,
+                                       bool case_sensitive = true) const
+            {
+                assert(this->m_parent);     // Cannot query for siblings if node has no parent
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_node<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling)
+                        if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive))
+                            return sibling;
+                    return 0;
+                }
+                else
+                    return m_next_sibling;
+            }
+
+            //! Gets first attribute of node, optionally matching attribute name.
+            //! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found attribute, or 0 if not found.
+            xml_attribute<Ch> *first_attribute(const Ch *name = 0, std::size_t name_size = 0,
+                                               bool case_sensitive = true) const
+            {
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_attribute<Ch> *attribute = m_first_attribute; attribute;
+                         attribute = attribute->m_next_attribute)
+                        if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
+                            return attribute;
+                    return 0;
+                }
+                else
+                    return m_first_attribute;
+            }
+
+            //! Gets last attribute of node, optionally matching attribute name.
+            //! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
+            //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
+            //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
+            //! \return Pointer to found attribute, or 0 if not found.
+            xml_attribute<Ch> *last_attribute(const Ch *name = 0, std::size_t name_size = 0,
+                                              bool case_sensitive = true) const
+            {
+                if (name)
+                {
+                    if (name_size == 0)
+                        name_size = internal::measure(name);
+                    for (xml_attribute<Ch> *attribute = m_last_attribute; attribute;
+                         attribute = attribute->m_prev_attribute)
+                        if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
+                            return attribute;
+                    return 0;
+                }
+                else
+                    return m_first_attribute ? m_last_attribute : 0;
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Node modification
+
+            //! Sets type of node.
+            //! \param type Type of node to set.
+            void type(node_type type)
+            {
+                m_type = type;
+            }
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Node manipulation
+
+            //! Prepends a new child node.
+            //! The prepended child becomes the first child, and all existing children are moved one position back.
+            //! \param child Node to prepend.
+            void prepend_node(xml_node<Ch> *child)
+            {
+                assert(child && !child->parent() && child->type() != node_document);
+                if (first_node())
+                {
+                    child->m_next_sibling = m_first_node;
+                    m_first_node->m_prev_sibling = child;
+                }
+                else
+                {
+                    child->m_next_sibling = 0;
+                    m_last_node = child;
+                }
+                m_first_node = child;
+                child->m_parent = this;
+                child->m_prev_sibling = 0;
+            }
+
+            //! Appends a new child node.
+            //! The appended child becomes the last child.
+            //! \param child Node to append.
+            void append_node(xml_node<Ch> *child)
+            {
+                assert(child && !child->parent() && child->type() != node_document);
+                if (first_node())
+                {
+                    child->m_prev_sibling = m_last_node;
+                    m_last_node->m_next_sibling = child;
+                }
+                else
+                {
+                    child->m_prev_sibling = 0;
+                    m_first_node = child;
+                }
+                m_last_node = child;
+                child->m_parent = this;
+                child->m_next_sibling = 0;
+            }
+
+            //! Inserts a new child node at specified place inside the node.
+            //! All children after and including the specified node are moved one position back.
+            //! \param where Place where to insert the child, or 0 to insert at the back.
+            //! \param child Node to insert.
+            void insert_node(xml_node<Ch> *where, xml_node<Ch> *child)
+            {
+                assert(!where || where->parent() == this);
+                assert(child && !child->parent() && child->type() != node_document);
+                if (where == m_first_node)
+                    prepend_node(child);
+                else if (where == 0)
+                    append_node(child);
+                else
+                {
+                    child->m_prev_sibling = where->m_prev_sibling;
+                    child->m_next_sibling = where;
+                    where->m_prev_sibling->m_next_sibling = child;
+                    where->m_prev_sibling = child;
+                    child->m_parent = this;
+                }
+            }
+
+            //! Removes first child node.
+            //! If node has no children, behaviour is undefined.
+            //! Use first_node() to test if node has children.
+            void remove_first_node()
+            {
+                assert(first_node());
+                xml_node<Ch> *child = m_first_node;
+                m_first_node = child->m_next_sibling;
+                if (child->m_next_sibling)
+                    child->m_next_sibling->m_prev_sibling = 0;
+                else
+                    m_last_node = 0;
+                child->m_parent = 0;
+            }
+
+            //! Removes last child of the node.
+            //! If node has no children, behaviour is undefined.
+            //! Use first_node() to test if node has children.
+            void remove_last_node()
+            {
+                assert(first_node());
+                xml_node<Ch> *child = m_last_node;
+                if (child->m_prev_sibling)
+                {
+                    m_last_node = child->m_prev_sibling;
+                    child->m_prev_sibling->m_next_sibling = 0;
+                }
+                else
+                    m_first_node = 0;
+                child->m_parent = 0;
+            }
+
+            //! Removes specified child from the node
+            // \param where Pointer to child to be removed.
+            void remove_node(xml_node<Ch> *where)
+            {
+                assert(where && where->parent() == this);
+                assert(first_node());
+                if (where == m_first_node)
+                    remove_first_node();
+                else if (where == m_last_node)
+                    remove_last_node();
+                else
+                {
+                    where->m_prev_sibling->m_next_sibling = where->m_next_sibling;
+                    where->m_next_sibling->m_prev_sibling = where->m_prev_sibling;
+                    where->m_parent = 0;
+                }
+            }
+
+            //! Removes all child nodes (but not attributes).
+            void remove_all_nodes()
+            {
+                for (xml_node<Ch> *node = first_node(); node; node = node->m_next_sibling)
+                    node->m_parent = 0;
+                m_first_node = 0;
+            }
+
+            //! Prepends a new attribute to the node.
+            //! \param attribute Attribute to prepend.
+            void prepend_attribute(xml_attribute<Ch> *attribute)
+            {
+                assert(attribute && !attribute->parent());
+                if (first_attribute())
+                {
+                    attribute->m_next_attribute = m_first_attribute;
+                    m_first_attribute->m_prev_attribute = attribute;
+                }
+                else
+                {
+                    attribute->m_next_attribute = 0;
+                    m_last_attribute = attribute;
+                }
+                m_first_attribute = attribute;
+                attribute->m_parent = this;
+                attribute->m_prev_attribute = 0;
+            }
+
+            //! Appends a new attribute to the node.
+            //! \param attribute Attribute to append.
+            void append_attribute(xml_attribute<Ch> *attribute)
+            {
+                assert(attribute && !attribute->parent());
+                if (first_attribute())
+                {
+                    attribute->m_prev_attribute = m_last_attribute;
+                    m_last_attribute->m_next_attribute = attribute;
+                }
+                else
+                {
+                    attribute->m_prev_attribute = 0;
+                    m_first_attribute = attribute;
+                }
+                m_last_attribute = attribute;
+                attribute->m_parent = this;
+                attribute->m_next_attribute = 0;
+            }
+
+            //! Inserts a new attribute at specified place inside the node.
+            //! All attributes after and including the specified attribute are moved one position back.
+            //! \param where Place where to insert the attribute, or 0 to insert at the back.
+            //! \param attribute Attribute to insert.
+            void insert_attribute(xml_attribute<Ch> *where, xml_attribute<Ch> *attribute)
+            {
+                assert(!where || where->parent() == this);
+                assert(attribute && !attribute->parent());
+                if (where == m_first_attribute)
+                    prepend_attribute(attribute);
+                else if (where == 0)
+                    append_attribute(attribute);
+                else
+                {
+                    attribute->m_prev_attribute = where->m_prev_attribute;
+                    attribute->m_next_attribute = where;
+                    where->m_prev_attribute->m_next_attribute = attribute;
+                    where->m_prev_attribute = attribute;
+                    attribute->m_parent = this;
+                }
+            }
+
+            //! Removes first attribute of the node.
+            //! If node has no attributes, behaviour is undefined.
+            //! Use first_attribute() to test if node has attributes.
+            void remove_first_attribute()
+            {
+                assert(first_attribute());
+                xml_attribute<Ch> *attribute = m_first_attribute;
+                if (attribute->m_next_attribute)
+                {
+                    attribute->m_next_attribute->m_prev_attribute = 0;
+                }
+                else
+                    m_last_attribute = 0;
+                attribute->m_parent = 0;
+                m_first_attribute = attribute->m_next_attribute;
+            }
+
+            //! Removes last attribute of the node.
+            //! If node has no attributes, behaviour is undefined.
+            //! Use first_attribute() to test if node has attributes.
+            void remove_last_attribute()
+            {
+                assert(first_attribute());
+                xml_attribute<Ch> *attribute = m_last_attribute;
+                if (attribute->m_prev_attribute)
+                {
+                    attribute->m_prev_attribute->m_next_attribute = 0;
+                    m_last_attribute = attribute->m_prev_attribute;
+                }
+                else
+                    m_first_attribute = 0;
+                attribute->m_parent = 0;
+            }
+
+            //! Removes specified attribute from node.
+            //! \param where Pointer to attribute to be removed.
+            void remove_attribute(xml_attribute<Ch> *where)
+            {
+                assert(first_attribute() && where->parent() == this);
+                if (where == m_first_attribute)
+                    remove_first_attribute();
+                else if (where == m_last_attribute)
+                    remove_last_attribute();
+                else
+                {
+                    where->m_prev_attribute->m_next_attribute = where->m_next_attribute;
+                    where->m_next_attribute->m_prev_attribute = where->m_prev_attribute;
+                    where->m_parent = 0;
+                }
+            }
+
+            //! Removes all attributes of node.
+            void remove_all_attributes()
+            {
+                for (xml_attribute<Ch> *attribute = first_attribute(); attribute;
+                     attribute = attribute->m_next_attribute)
+                    attribute->m_parent = 0;
+                m_first_attribute = 0;
+            }
+
+        private:
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Restrictions
+
+            // No copying
+            xml_node(const xml_node &);
+            void operator =(const xml_node &);
+
+            ///////////////////////////////////////////////////////////////////////////
+            // Data members
+
+            // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0.
+            // This is required for maximum performance, as it allows the parser to omit initialization of
+            // unneded/redundant values.
+            //
+            // The rules are as follows:
+            // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively
+            // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage
+            // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage
+
+            node_type m_type;                       // Type of node; always valid
+            xml_node<Ch> *m_first_node;             // Pointer to first child node, or 0 if none; always valid
+            xml_node<Ch>
+            *m_last_node;              // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero
+            xml_attribute<Ch>
+            *m_first_attribute;   // Pointer to first attribute of node, or 0 if none; always valid
+            xml_attribute<Ch>
+            *m_last_attribute;    // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero
+            xml_node<Ch>
+            *m_prev_sibling;           // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero
+            xml_node<Ch>
+            *m_next_sibling;           // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero
+
+    };
+
+    ///////////////////////////////////////////////////////////////////////////
+    // XML document
+
+    //! This class represents root of the DOM hierarchy.
+    //! It is also an xml_node and a memory_pool through public inheritance.
+    //! Use parse() function to build a DOM tree from a zero-terminated XML text string.
+    //! parse() function allocates memory for nodes and attributes by using functions of xml_document,
+    //! which are inherited from memory_pool.
+    //! To access root node of the document, use the document itself, as if it was an xml_node.
+    //! \param Ch Character type to use.
+    template<class Ch = char>
+    class xml_document: public xml_node<Ch>, public memory_pool<Ch>
+    {
+
+        public:
+
+            //! Constructs empty XML document
+            xml_document()
+                : xml_node<Ch>(node_document)
+            {
+            }
+
+            //! Parses zero-terminated XML string according to given flags.
+            //! Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used.
+            //! The string must persist for the lifetime of the document.
+            //! In case of error, rapidxml::parse_error exception will be thrown.
+            //! <br><br>
+            //! If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning.
+            //! Make sure that data is zero-terminated.
+            //! <br><br>
+            //! Document can be parsed into multiple times.
+            //! Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool.
+            //! \param text XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser.
+            template<int Flags>
+            void parse(Ch *text)
+            {
+                assert(text);
+
+                // Remove current contents
+                this->remove_all_nodes();
+                this->remove_all_attributes();
+
+                // Parse BOM, if any
+                parse_bom<Flags>(text);
+
+                // Parse children
+                while (1)
+                {
+                    // Skip whitespace before node
+                    skip<whitespace_pred, Flags>(text);
+                    if (*text == 0)
+                        break;
+
+                    // Parse and append new child
+                    if (*text == Ch('<'))
+                    {
+                        ++text;     // Skip '<'
+                        if (xml_node<Ch> *node = parse_node<Flags>(text))
+                            this->append_node(node);
+                    }
+                    else
+                        RAPIDXML_PARSE_ERROR("expected <", text);
+                }
+
+            }
+
+            //! Clears the document by deleting all nodes and clearing the memory pool.
+            //! All nodes owned by document pool are destroyed.
+            void clear()
+            {
+                this->remove_all_nodes();
+                this->remove_all_attributes();
+                memory_pool<Ch>::clear();
+            }
+
+        private:
+
+            ///////////////////////////////////////////////////////////////////////
+            // Internal character utility functions
+
+            // Detect whitespace character
+            struct whitespace_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    return internal::lookup_tables<0>::lookup_whitespace[static_cast<unsigned char>(ch)];
+                }
+            };
+
+            // Detect node name character
+            struct node_name_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    return internal::lookup_tables<0>::lookup_node_name[static_cast<unsigned char>(ch)];
+                }
+            };
+
+            // Detect attribute name character
+            struct attribute_name_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    return internal::lookup_tables<0>::lookup_attribute_name[static_cast<unsigned char>(ch)];
+                }
+            };
+
+            // Detect text character (PCDATA)
+            struct text_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    return internal::lookup_tables<0>::lookup_text[static_cast<unsigned char>(ch)];
+                }
+            };
+
+            // Detect text character (PCDATA) that does not require processing
+            struct text_pure_no_ws_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    return internal::lookup_tables<0>::lookup_text_pure_no_ws[static_cast<unsigned char>(ch)];
+                }
+            };
+
+            // Detect text character (PCDATA) that does not require processing
+            struct text_pure_with_ws_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    return internal::lookup_tables<0>::lookup_text_pure_with_ws[static_cast<unsigned char>(ch)];
+                }
+            };
+
+            // Detect attribute value character
+            template<Ch Quote>
+            struct attribute_value_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    if (Quote == Ch('\''))
+                        return internal::lookup_tables<0>::lookup_attribute_data_1[static_cast<unsigned char>(ch)];
+                    if (Quote == Ch('\"'))
+                        return internal::lookup_tables<0>::lookup_attribute_data_2[static_cast<unsigned char>(ch)];
+                    return 0;       // Should never be executed, to avoid warnings on Comeau
+                }
+            };
+
+            // Detect attribute value character
+            template<Ch Quote>
+            struct attribute_value_pure_pred
+            {
+                static unsigned char test(Ch ch)
+                {
+                    if (Quote == Ch('\''))
+                        return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast<unsigned char>(ch)];
+                    if (Quote == Ch('\"'))
+                        return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast<unsigned char>(ch)];
+                    return 0;       // Should never be executed, to avoid warnings on Comeau
+                }
+            };
+
+            // Insert coded character, using UTF8 or 8-bit ASCII
+            template<int Flags>
+            static void insert_coded_character(Ch *&text, unsigned long code)
+            {
+                if (Flags & parse_no_utf8)
+                {
+                    // Insert 8-bit ASCII character
+                    // Todo: possibly verify that code is less than 256 and use replacement char otherwise?
+                    text[0] = static_cast<unsigned char>(code);
+                    text += 1;
+                }
+                else
+                {
+                    // Insert UTF8 sequence
+                    if (code < 0x80)    // 1 byte sequence
+                    {
+                        text[0] = static_cast<unsigned char>(code);
+                        text += 1;
+                    }
+                    else if (code < 0x800)  // 2 byte sequence
+                    {
+                        text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
+                        text[0] = static_cast<unsigned char>(code | 0xC0);
+                        text += 2;
+                    }
+                    else if (code < 0x10000)    // 3 byte sequence
+                    {
+                        text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
+                        text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
+                        text[0] = static_cast<unsigned char>(code | 0xE0);
+                        text += 3;
+                    }
+                    else if (code < 0x110000)   // 4 byte sequence
+                    {
+                        text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
+                        text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
+                        text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
+                        text[0] = static_cast<unsigned char>(code | 0xF0);
+                        text += 4;
+                    }
+                    else    // Invalid, only codes up to 0x10FFFF are allowed in Unicode
+                    {
+                        RAPIDXML_PARSE_ERROR("invalid numeric character entity", text);
+                    }
+                }
+            }
+
+            // Skip characters until predicate evaluates to true
+            template<class StopPred, int Flags>
+            static void skip(Ch *&text)
+            {
+                Ch *tmp = text;
+                while (StopPred::test(*tmp))
+                    ++tmp;
+                text = tmp;
+            }
+
+            // Skip characters until predicate evaluates to true while doing the following:
+            // - replacing XML character entity references with proper characters (&apos; &amp; &quot; &lt; &gt; &#...;)
+            // - condensing whitespace sequences to single space character
+            template<class StopPred, class StopPredPure, int Flags>
+            static Ch *skip_and_expand_character_refs(Ch *&text)
+            {
+                // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip
+                if (Flags & parse_no_entity_translation &&
+                    !(Flags & parse_normalize_whitespace) &&
+                    !(Flags & parse_trim_whitespace))
+                {
+                    skip<StopPred, Flags>(text);
+                    return text;
+                }
+
+                // Use simple skip until first modification is detected
+                skip<StopPredPure, Flags>(text);
+
+                // Use translation skip
+                Ch *src = text;
+                Ch *dest = src;
+                while (StopPred::test(*src))
+                {
+                    // If entity translation is enabled
+                    if (!(Flags & parse_no_entity_translation))
+                    {
+                        // Test if replacement is needed
+                        if (src[0] == Ch('&'))
+                        {
+                            switch (src[1])
+                            {
+
+                                // &amp; &apos;
+                                case Ch('a'):
+                                    if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';'))
+                                    {
+                                        *dest = Ch('&');
+                                        ++dest;
+                                        src += 5;
+                                        continue;
+                                    }
+                                    if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';'))
+                                    {
+                                        *dest = Ch('\'');
+                                        ++dest;
+                                        src += 6;
+                                        continue;
+                                    }
+                                    break;
+
+                                // &quot;
+                                case Ch('q'):
+                                    if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';'))
+                                    {
+                                        *dest = Ch('"');
+                                        ++dest;
+                                        src += 6;
+                                        continue;
+                                    }
+                                    break;
+
+                                // &gt;
+                                case Ch('g'):
+                                    if (src[2] == Ch('t') && src[3] == Ch(';'))
+                                    {
+                                        *dest = Ch('>');
+                                        ++dest;
+                                        src += 4;
+                                        continue;
+                                    }
+                                    break;
+
+                                // &lt;
+                                case Ch('l'):
+                                    if (src[2] == Ch('t') && src[3] == Ch(';'))
+                                    {
+                                        *dest = Ch('<');
+                                        ++dest;
+                                        src += 4;
+                                        continue;
+                                    }
+                                    break;
+
+                                // &#...; - assumes ASCII
+                                case Ch('#'):
+                                    if (src[2] == Ch('x'))
+                                    {
+                                        unsigned long code = 0;
+                                        src += 3;   // Skip &#x
+                                        while (1)
+                                        {
+                                            unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)];
+                                            if (digit == 0xFF)
+                                                break;
+                                            code = code * 16 + digit;
+                                            ++src;
+                                        }
+                                        insert_coded_character<Flags>(dest, code);    // Put character in output
+                                    }
+                                    else
+                                    {
+                                        unsigned long code = 0;
+                                        src += 2;   // Skip &#
+                                        while (1)
+                                        {
+                                            unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)];
+                                            if (digit == 0xFF)
+                                                break;
+                                            code = code * 10 + digit;
+                                            ++src;
+                                        }
+                                        insert_coded_character<Flags>(dest, code);    // Put character in output
+                                    }
+                                    if (*src == Ch(';'))
+                                        ++src;
+                                    else
+                                        RAPIDXML_PARSE_ERROR("expected ;", src);
+                                    continue;
+
+                                // Something else
+                                default:
+                                    // Ignore, just copy '&' verbatim
+                                    break;
+
+                            }
+                        }
+                    }
+
+                    // If whitespace condensing is enabled
+                    if (Flags & parse_normalize_whitespace)
+                    {
+                        // Test if condensing is needed
+                        if (whitespace_pred::test(*src))
+                        {
+                            *dest = Ch(' '); ++dest;    // Put single space in dest
+                            ++src;                      // Skip first whitespace char
+                            // Skip remaining whitespace chars
+                            while (whitespace_pred::test(*src))
+                                ++src;
+                            continue;
+                        }
+                    }
+
+                    // No replacement, only copy character
+                    *dest++ = *src++;
+
+                }
+
+                // Return new end
+                text = src;
+                return dest;
+
+            }
+
+            ///////////////////////////////////////////////////////////////////////
+            // Internal parsing functions
+
+            // Parse BOM, if any
+            template<int Flags>
+            void parse_bom(Ch *&text)
+            {
+                // UTF-8?
+                if (static_cast<unsigned char>(text[0]) == 0xEF &&
+                    static_cast<unsigned char>(text[1]) == 0xBB &&
+                    static_cast<unsigned char>(text[2]) == 0xBF)
+                {
+                    text += 3;      // Skup utf-8 bom
+                }
+            }
+
+            // Parse XML declaration (<?xml...)
+            template<int Flags>
+            xml_node<Ch> *parse_xml_declaration(Ch *&text)
+            {
+                // If parsing of declaration is disabled
+                if (!(Flags & parse_declaration_node))
+                {
+                    // Skip until end of declaration
+                    while (text[0] != Ch('?') || text[1] != Ch('>'))
+                    {
+                        if (!text[0])
+                            RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                        ++text;
+                    }
+                    text += 2;    // Skip '?>'
+                    return 0;
+                }
+
+                // Create declaration
+                xml_node<Ch> *declaration = this->allocate_node(node_declaration);
+
+                // Skip whitespace before attributes or ?>
+                skip<whitespace_pred, Flags>(text);
+
+                // Parse declaration attributes
+                parse_node_attributes<Flags>(text, declaration);
+
+                // Skip ?>
+                if (text[0] != Ch('?') || text[1] != Ch('>'))
+                    RAPIDXML_PARSE_ERROR("expected ?>", text);
+                text += 2;
+
+                return declaration;
+            }
+
+            // Parse XML comment (<!--...)
+            template<int Flags>
+            xml_node<Ch> *parse_comment(Ch *&text)
+            {
+                // If parsing of comments is disabled
+                if (!(Flags & parse_comment_nodes))
+                {
+                    // Skip until end of comment
+                    while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
+                    {
+                        if (!text[0])
+                            RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                        ++text;
+                    }
+                    text += 3;     // Skip '-->'
+                    return 0;      // Do not produce comment node
+                }
+
+                // Remember value start
+                Ch *value = text;
+
+                // Skip until end of comment
+                while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
+                {
+                    if (!text[0])
+                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                    ++text;
+                }
+
+                // Create comment node
+                xml_node<Ch> *comment = this->allocate_node(node_comment);
+                comment->value(value, text - value);
+
+                // Place zero terminator after comment value
+                if (!(Flags & parse_no_string_terminators))
+                    *text = Ch('\0');
+
+                text += 3;     // Skip '-->'
+                return comment;
+            }
+
+            // Parse DOCTYPE
+            template<int Flags>
+            xml_node<Ch> *parse_doctype(Ch *&text)
+            {
+                // Remember value start
+                Ch *value = text;
+
+                // Skip to >
+                while (*text != Ch('>'))
+                {
+                    // Determine character type
+                    switch (*text)
+                    {
+
+                        // If '[' encountered, scan for matching ending ']' using naive algorithm with depth
+                        // This works for all W3C test files except for 2 most wicked
+                        case Ch('['):
+                            {
+                                ++text;     // Skip '['
+                                int depth = 1;
+                                while (depth > 0)
+                                {
+                                    switch (*text)
+                                    {
+                                        case Ch('['): ++depth; break;
+                                        case Ch(']'): --depth; break;
+                                        case 0: RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                                        default: break;
+                                    }
+                                    ++text;
+                                }
+                                break;
+                            }
+
+                        // Error on end of text
+                        case Ch('\0'):
+                            RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+
+                        // Other character, skip it
+                        default:
+                            ++text;
+
+                    }
+                }
+
+                // If DOCTYPE nodes enabled
+                if (Flags & parse_doctype_node)
+                {
+                    // Create a new doctype node
+                    xml_node<Ch> *doctype = this->allocate_node(node_doctype);
+                    doctype->value(value, text - value);
+
+                    // Place zero terminator after value
+                    if (!(Flags & parse_no_string_terminators))
+                        *text = Ch('\0');
+
+                    text += 1;      // skip '>'
+                    return doctype;
+                }
+                else
+                {
+                    text += 1;      // skip '>'
+                    return 0;
+                }
+
+            }
+
+            // Parse PI
+            template<int Flags>
+            xml_node<Ch> *parse_pi(Ch *&text)
+            {
+                // If creation of PI nodes is enabled
+                if (Flags & parse_pi_nodes)
+                {
+                    // Create pi node
+                    xml_node<Ch> *pi = this->allocate_node(node_pi);
+
+                    // Extract PI target name
+                    Ch *name = text;
+                    skip<node_name_pred, Flags>(text);
+                    if (text == name)
+                        RAPIDXML_PARSE_ERROR("expected PI target", text);
+                    pi->name(name, text - name);
+
+                    // Skip whitespace between pi target and pi
+                    skip<whitespace_pred, Flags>(text);
+
+                    // Remember start of pi
+                    Ch *value = text;
+
+                    // Skip to '?>'
+                    while (text[0] != Ch('?') || text[1] != Ch('>'))
+                    {
+                        if (*text == Ch('\0'))
+                            RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                        ++text;
+                    }
+
+                    // Set pi value (verbatim, no entity expansion or whitespace normalization)
+                    pi->value(value, text - value);
+
+                    // Place zero terminator after name and value
+                    if (!(Flags & parse_no_string_terminators))
+                    {
+                        pi->name()[pi->name_size()] = Ch('\0');
+                        pi->value()[pi->value_size()] = Ch('\0');
+                    }
+
+                    text += 2;                          // Skip '?>'
+                    return pi;
+                }
+                else
+                {
+                    // Skip to '?>'
+                    while (text[0] != Ch('?') || text[1] != Ch('>'))
+                    {
+                        if (*text == Ch('\0'))
+                            RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                        ++text;
+                    }
+                    text += 2;    // Skip '?>'
+                    return 0;
+                }
+            }
+
+            // Parse and append data
+            // Return character that ends data.
+            // This is necessary because this character might have been overwritten by a terminating 0
+            template<int Flags>
+            Ch parse_and_append_data(xml_node<Ch> *node, Ch *&text, Ch *contents_start)
+            {
+                // Backup to contents start if whitespace trimming is disabled
+                if (!(Flags & parse_trim_whitespace))
+                    text = contents_start;
+
+                // Skip until end of data
+                Ch *value = text, *end;
+                if (Flags & parse_normalize_whitespace)
+                    end = skip_and_expand_character_refs<text_pred, text_pure_with_ws_pred, Flags>(text);
+                else
+                    end = skip_and_expand_character_refs<text_pred, text_pure_no_ws_pred, Flags>(text);
+
+                // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after >
+                if (Flags & parse_trim_whitespace)
+                {
+                    if (Flags & parse_normalize_whitespace)
+                    {
+                        // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end
+                        if (*(end - 1) == Ch(' '))
+                            --end;
+                    }
+                    else
+                    {
+                        // Backup until non-whitespace character is found
+                        while (whitespace_pred::test(*(end - 1)))
+                            --end;
+                    }
+                }
+
+                // If characters are still left between end and value (this test is only necessary if normalization is enabled)
+                // Create new data node
+                if (!(Flags & parse_no_data_nodes))
+                {
+                    xml_node<Ch> *data = this->allocate_node(node_data);
+                    data->value(value, end - value);
+                    node->append_node(data);
+                }
+
+                // Add data to parent node if no data exists yet
+                if (!(Flags & parse_no_element_values))
+                    if (*node->value() == Ch('\0'))
+                        node->value(value, end - value);
+
+                // Place zero terminator after value
+                if (!(Flags & parse_no_string_terminators))
+                {
+                    Ch ch = *text;
+                    *end = Ch('\0');
+                    return ch;      // Return character that ends data; this is required because zero terminator overwritten it
+                }
+
+                // Return character that ends data
+                return *text;
+            }
+
+            // Parse CDATA
+            template<int Flags>
+            xml_node<Ch> *parse_cdata(Ch *&text)
+            {
+                // If CDATA is disabled
+                if (Flags & parse_no_data_nodes)
+                {
+                    // Skip until end of cdata
+                    while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
+                    {
+                        if (!text[0])
+                            RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                        ++text;
+                    }
+                    text += 3;      // Skip ]]>
+                    return 0;       // Do not produce CDATA node
+                }
+
+                // Skip until end of cdata
+                Ch *value = text;
+                while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
+                {
+                    if (!text[0])
+                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                    ++text;
+                }
+
+                // Create new cdata node
+                xml_node<Ch> *cdata = this->allocate_node(node_cdata);
+                cdata->value(value, text - value);
+
+                // Place zero terminator after value
+                if (!(Flags & parse_no_string_terminators))
+                    *text = Ch('\0');
+
+                text += 3;      // Skip ]]>
+                return cdata;
+            }
+
+            // Parse element node
+            template<int Flags>
+            xml_node<Ch> *parse_element(Ch *&text)
+            {
+                // Create element node
+                xml_node<Ch> *element = this->allocate_node(node_element);
+
+                // Extract element name
+                Ch *name = text;
+                skip<node_name_pred, Flags>(text);
+                if (text == name)
+                    RAPIDXML_PARSE_ERROR("expected element name", text);
+                element->name(name, text - name);
+
+                // Skip whitespace between element name and attributes or >
+                skip<whitespace_pred, Flags>(text);
+
+                // Parse attributes, if any
+                parse_node_attributes<Flags>(text, element);
+
+                // Determine ending type
+                if (*text == Ch('>'))
+                {
+                    ++text;
+                    parse_node_contents<Flags>(text, element);
+                }
+                else if (*text == Ch('/'))
+                {
+                    ++text;
+                    if (*text != Ch('>'))
+                        RAPIDXML_PARSE_ERROR("expected >", text);
+                    ++text;
+                }
+                else
+                    RAPIDXML_PARSE_ERROR("expected >", text);
+
+                // Place zero terminator after name
+                if (!(Flags & parse_no_string_terminators))
+                    element->name()[element->name_size()] = Ch('\0');
+
+                // Return parsed element
+                return element;
+            }
+
+            // Determine node type, and parse it
+            template<int Flags>
+            xml_node<Ch> *parse_node(Ch *&text)
+            {
+                // Parse proper node type
+                switch (text[0])
+                {
+
+                    // <...
+                    default:
+                        // Parse and append element node
+                        return parse_element<Flags>(text);
+
+                    // <?...
+                    case Ch('?'):
+                        ++text;     // Skip ?
+                        if ((text[0] == Ch('x') || text[0] == Ch('X')) &&
+                            (text[1] == Ch('m') || text[1] == Ch('M')) &&
+                            (text[2] == Ch('l') || text[2] == Ch('L')) &&
+                            whitespace_pred::test(text[3]))
+                        {
+                            // '<?xml ' - xml declaration
+                            text += 4;      // Skip 'xml '
+                            return parse_xml_declaration<Flags>(text);
+                        }
+                        else
+                        {
+                            // Parse PI
+                            return parse_pi<Flags>(text);
+                        }
+
+                    // <!...
+                    case Ch('!'):
+
+                        // Parse proper subset of <! node
+                        switch (text[1])
+                        {
+
+                            // <!-
+                            case Ch('-'):
+                                if (text[2] == Ch('-'))
+                                {
+                                    // '<!--' - xml comment
+                                    text += 3;     // Skip '!--'
+                                    return parse_comment<Flags>(text);
+                                }
+                                break;
+
+                            // <![
+                            case Ch('['):
+                                if (text[2] == Ch('C') && text[3] == Ch('D') && text[4] == Ch('A') &&
+                                    text[5] == Ch('T') && text[6] == Ch('A') && text[7] == Ch('['))
+                                {
+                                    // '<![CDATA[' - cdata
+                                    text += 8;     // Skip '![CDATA['
+                                    return parse_cdata<Flags>(text);
+                                }
+                                break;
+
+                            // <!D
+                            case Ch('D'):
+                                if (text[2] == Ch('O') && text[3] == Ch('C') && text[4] == Ch('T') &&
+                                    text[5] == Ch('Y') && text[6] == Ch('P') && text[7] == Ch('E') &&
+                                    whitespace_pred::test(text[8]))
+                                {
+                                    // '<!DOCTYPE ' - doctype
+                                    text += 9;      // skip '!DOCTYPE '
+                                    return parse_doctype<Flags>(text);
+                                }
+                                break;
+
+                            default:
+                                break;
+
+                        }   // switch
+
+                        // Attempt to skip other, unrecognized node types starting with <!
+                        ++text;     // Skip !
+                        while (*text != Ch('>'))
+                        {
+                            if (*text == 0)
+                                RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+                            ++text;
+                        }
+                        ++text;     // Skip '>'
+                        return 0;   // No node recognized
+
+                }
+            }
+
+            // Parse contents of the node - children, data etc.
+            template<int Flags>
+            void parse_node_contents(Ch *&text, xml_node<Ch> *node)
+            {
+                // For all children and text
+                while (1)
+                {
+                    // Skip whitespace between > and node contents
+                    Ch *contents_start = text;      // Store start of node contents before whitespace is skipped
+                    skip<whitespace_pred, Flags>(text);
+                    Ch next_char = *text;
+
+                    // After data nodes, instead of continuing the loop, control jumps here.
+                    // This is because zero termination inside parse_and_append_data() function
+                    // would wreak havoc with the above code.
+                    // Also, skipping whitespace after data nodes is unnecessary.
+after_data_node:
+
+                    // Determine what comes next: node closing, child node, data node, or 0?
+                    switch (next_char)
+                    {
+
+                        // Node closing or child node
+                        case Ch('<'):
+                            if (text[1] == Ch('/'))
+                            {
+                                // Node closing
+                                text += 2;      // Skip '</'
+                                if (Flags & parse_validate_closing_tags)
+                                {
+                                    // Skip and validate closing tag name
+                                    Ch *closing_name = text;
+                                    skip<node_name_pred, Flags>(text);
+                                    if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true))
+                                        RAPIDXML_PARSE_ERROR("invalid closing tag name", text);
+                                }
+                                else
+                                {
+                                    // No validation, just skip name
+                                    skip<node_name_pred, Flags>(text);
+                                }
+                                // Skip remaining whitespace after node name
+                                skip<whitespace_pred, Flags>(text);
+                                if (*text != Ch('>'))
+                                    RAPIDXML_PARSE_ERROR("expected >", text);
+                                ++text;     // Skip '>'
+                                return;     // Node closed, finished parsing contents
+                            }
+                            else
+                            {
+                                // Child node
+                                ++text;     // Skip '<'
+                                if (xml_node<Ch> *child = parse_node<Flags>(text))
+                                    node->append_node(child);
+                            }
+                            break;
+
+                        // End of data - error
+                        case Ch('\0'):
+                            RAPIDXML_PARSE_ERROR("unexpected end of data", text);
+
+                        // Data node
+                        default:
+                            next_char = parse_and_append_data<Flags>(node, text, contents_start);
+                            goto after_data_node;   // Bypass regular processing after data nodes
+
+                    }
+                }
+            }
+
+            // Parse XML attributes of the node
+            template<int Flags>
+            void parse_node_attributes(Ch *&text, xml_node<Ch> *node)
+            {
+                // For all attributes
+                while (attribute_name_pred::test(*text))
+                {
+                    // Extract attribute name
+                    Ch *name = text;
+                    ++text;     // Skip first character of attribute name
+                    skip<attribute_name_pred, Flags>(text);
+                    if (text == name)
+                        RAPIDXML_PARSE_ERROR("expected attribute name", name);
+
+                    // Create new attribute
+                    xml_attribute<Ch> *attribute = this->allocate_attribute();
+                    attribute->name(name, text - name);
+                    node->append_attribute(attribute);
+
+                    // Skip whitespace after attribute name
+                    skip<whitespace_pred, Flags>(text);
+
+                    // Skip =
+                    if (*text != Ch('='))
+                        RAPIDXML_PARSE_ERROR("expected =", text);
+                    ++text;
+
+                    // Add terminating zero after name
+                    if (!(Flags & parse_no_string_terminators))
+                        attribute->name()[attribute->name_size()] = 0;
+
+                    // Skip whitespace after =
+                    skip<whitespace_pred, Flags>(text);
+
+                    // Skip quote and remember if it was ' or "
+                    Ch quote = *text;
+                    if (quote != Ch('\'') && quote != Ch('"'))
+                        RAPIDXML_PARSE_ERROR("expected ' or \"", text);
+                    ++text;
+
+                    // Extract attribute value and expand char refs in it
+                    Ch *value = text, *end;
+                    const int AttFlags = Flags &
+                                         ~parse_normalize_whitespace;   // No whitespace normalization in attributes
+                    if (quote == Ch('\''))
+                        end = skip_and_expand_character_refs<attribute_value_pred<Ch('\'')>, attribute_value_pure_pred<Ch('\'')>, AttFlags>
+                              (text);
+                    else
+                        end = skip_and_expand_character_refs<attribute_value_pred<Ch('"')>, attribute_value_pure_pred<Ch('"')>, AttFlags>
+                              (text);
+
+                    // Set attribute value
+                    attribute->value(value, end - value);
+
+                    // Make sure that end quote is present
+                    if (*text != quote)
+                        RAPIDXML_PARSE_ERROR("expected ' or \"", text);
+                    ++text;     // Skip quote
+
+                    // Add terminating zero after value
+                    if (!(Flags & parse_no_string_terminators))
+                        attribute->value()[attribute->value_size()] = 0;
+
+                    // Skip whitespace after attribute value
+                    skip<whitespace_pred, Flags>(text);
+                }
+            }
+
+    };
+
+    //! \cond internal
+    namespace internal
+    {
+
+        // Whitespace (space \n \r \t)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_whitespace[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  0,  1,  0,  0,  // 0
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 1
+            1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 2
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 3
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 4
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 5
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 6
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 7
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 8
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 9
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // A
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // B
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // C
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // D
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // E
+            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0   // F
+        };
+
+        // Node name (anything but space \n \r \t / > ? \0)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_node_name[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Text (i.e. PCDATA) (anything but < \0)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_text[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled
+        // (anything but < \0 &)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_text_pure_no_ws[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled
+        // (anything but < \0 & space \n \r \t)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_text_pure_with_ws[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            0,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Attribute name (anything but space \n \r \t / < > = ? ! \0)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_attribute_name[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Attribute data with single quote (anything but ' \0)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Attribute data with single quote that does not require processing (anything but ' \0 &)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1_pure[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Attribute data with double quote (anything but " \0)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Attribute data with double quote that does not require processing (anything but " \0 &)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2_pure[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
+            1,  1,  0,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
+            1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
+        };
+
+        // Digits (dec and hex, 255 denotes end of numeric character reference)
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_digits[256] =
+        {
+            // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 0
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 1
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 2
+            0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 255, 255, 255, 255, 255, 255, // 3
+            255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 4
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 5
+            255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 6
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 7
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 8
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 9
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // A
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // B
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // C
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // D
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // E
+            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 // F
+        };
+
+        // Upper case conversion
+        template<int Dummy>
+        const unsigned char lookup_tables<Dummy>::lookup_upcase[256] =
+        {
+            // 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  A   B   C   D   E   F
+            0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15,   // 0
+            16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,   // 1
+            32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,   // 2
+            48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,   // 3
+            64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 4
+            80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,   // 5
+            96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 6
+            80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, // 7
+            128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, // 8
+            144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, // 9
+            160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, // A
+            176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, // B
+            192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, // C
+            208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, // D
+            224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, // E
+            240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 // F
+        };
+    }
+    //! \endcond
+
+}
+
+// Undefine internal macros
+#undef RAPIDXML_PARSE_ERROR
+
+// On MSVC, restore warnings state
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+#endif
diff --git a/extlibs/rapidxml/rapidxml_iterators.hpp b/extlibs/rapidxml/rapidxml_iterators.hpp
new file mode 100644 (file)
index 0000000..2960a39
--- /dev/null
@@ -0,0 +1,174 @@
+#ifndef RAPIDXML_ITERATORS_HPP_INCLUDED
+#define RAPIDXML_ITERATORS_HPP_INCLUDED
+
+// Copyright (C) 2006, 2009 Marcin Kalicinski
+// Version 1.13
+// Revision $DateTime: 2009/05/13 01:46:17 $
+//! \file rapidxml_iterators.hpp This file contains rapidxml iterators
+
+#include "rapidxml.hpp"
+
+namespace rapidxml
+{
+
+    //! Iterator of child nodes of xml_node
+    template<class Ch>
+    class node_iterator
+    {
+
+        public:
+
+            typedef typename xml_node<Ch> value_type;
+            typedef typename xml_node<Ch> &reference;
+            typedef typename xml_node<Ch> *pointer;
+            typedef std::ptrdiff_t difference_type;
+            typedef std::bidirectional_iterator_tag iterator_category;
+
+            node_iterator()
+                : m_node(0)
+            {
+            }
+
+            node_iterator(xml_node<Ch> *node)
+                : m_node(node->first_node())
+            {
+            }
+
+            reference operator *() const
+            {
+                assert(m_node);
+                return *m_node;
+            }
+
+            pointer operator->() const
+            {
+                assert(m_node);
+                return m_node;
+            }
+
+            node_iterator &operator++()
+            {
+                assert(m_node);
+                m_node = m_node->next_sibling();
+                return *this;
+            }
+
+            node_iterator operator++(int)
+            {
+                node_iterator tmp = *this;
+                ++this;
+                return tmp;
+            }
+
+            node_iterator &operator--()
+            {
+                assert(m_node && m_node->previous_sibling());
+                m_node = m_node->previous_sibling();
+                return *this;
+            }
+
+            node_iterator operator--(int)
+            {
+                node_iterator tmp = *this;
+                ++this;
+                return tmp;
+            }
+
+            bool operator ==(const node_iterator<Ch> &rhs)
+            {
+                return m_node == rhs.m_node;
+            }
+
+            bool operator !=(const node_iterator<Ch> &rhs)
+            {
+                return m_node != rhs.m_node;
+            }
+
+        private:
+
+            xml_node<Ch> *m_node;
+
+    };
+
+    //! Iterator of child attributes of xml_node
+    template<class Ch>
+    class attribute_iterator
+    {
+
+        public:
+
+            typedef typename xml_attribute<Ch> value_type;
+            typedef typename xml_attribute<Ch> &reference;
+            typedef typename xml_attribute<Ch> *pointer;
+            typedef std::ptrdiff_t difference_type;
+            typedef std::bidirectional_iterator_tag iterator_category;
+
+            attribute_iterator()
+                : m_attribute(0)
+            {
+            }
+
+            attribute_iterator(xml_node<Ch> *node)
+                : m_attribute(node->first_attribute())
+            {
+            }
+
+            reference operator *() const
+            {
+                assert(m_attribute);
+                return *m_attribute;
+            }
+
+            pointer operator->() const
+            {
+                assert(m_attribute);
+                return m_attribute;
+            }
+
+            attribute_iterator &operator++()
+            {
+                assert(m_attribute);
+                m_attribute = m_attribute->next_attribute();
+                return *this;
+            }
+
+            attribute_iterator operator++(int)
+            {
+                attribute_iterator tmp = *this;
+                ++this;
+                return tmp;
+            }
+
+            attribute_iterator &operator--()
+            {
+                assert(m_attribute && m_attribute->previous_attribute());
+                m_attribute = m_attribute->previous_attribute();
+                return *this;
+            }
+
+            attribute_iterator operator--(int)
+            {
+                attribute_iterator tmp = *this;
+                ++this;
+                return tmp;
+            }
+
+            bool operator ==(const attribute_iterator<Ch> &rhs)
+            {
+                return m_attribute == rhs.m_attribute;
+            }
+
+            bool operator !=(const attribute_iterator<Ch> &rhs)
+            {
+                return m_attribute != rhs.m_attribute;
+            }
+
+        private:
+
+            xml_attribute<Ch> *m_attribute;
+
+    };
+
+}
+
+#endif
diff --git a/extlibs/rapidxml/rapidxml_print.hpp b/extlibs/rapidxml/rapidxml_print.hpp
new file mode 100644 (file)
index 0000000..422c3e7
--- /dev/null
@@ -0,0 +1,429 @@
+#ifndef RAPIDXML_PRINT_HPP_INCLUDED
+#define RAPIDXML_PRINT_HPP_INCLUDED
+
+// Copyright (C) 2006, 2009 Marcin Kalicinski
+// Version 1.13
+// Revision $DateTime: 2009/05/13 01:46:17 $
+//! \file rapidxml_print.hpp This file contains rapidxml printer implementation
+
+#include "rapidxml.hpp"
+
+// Only include streams if not disabled
+#ifndef RAPIDXML_NO_STREAMS
+#include <ostream>
+#include <iterator>
+#endif
+
+namespace rapidxml
+{
+
+    ///////////////////////////////////////////////////////////////////////
+    // Printing flags
+
+    const int print_no_indenting =
+        0x1;   //!< Printer flag instructing the printer to suppress indenting of XML. See print() function.
+
+    ///////////////////////////////////////////////////////////////////////
+    // Internal
+
+    //! \cond internal
+    namespace internal
+    {
+
+        ///////////////////////////////////////////////////////////////////////////
+        // Internal character operations
+
+        // Copy characters from given range to given output iterator
+        template<class OutIt, class Ch>
+        inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out)
+        {
+            while (begin != end)
+                *out++ = *begin++;
+            return out;
+        }
+
+        // Copy characters from given range to given output iterator and expand
+        // characters into references (&lt; &gt; &apos; &quot; &amp;)
+        template<class OutIt, class Ch>
+        inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out)
+        {
+            while (begin != end)
+            {
+                if (*begin == noexpand)
+                {
+                    *out++ = *begin;    // No expansion, copy character
+                }
+                else
+                {
+                    switch (*begin)
+                    {
+                        case Ch('<'):
+                            *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';');
+                            break;
+                        case Ch('>'):
+                            *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';');
+                            break;
+                        case Ch('\''):
+                            *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s');
+                            *out++ = Ch(';');
+                            break;
+                        case Ch('"'):
+                            *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t');
+                            *out++ = Ch(';');
+                            break;
+                        case Ch('&'):
+                            *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';');
+                            break;
+                        default:
+                            *out++ = *begin;    // No expansion, copy character
+                    }
+                }
+                ++begin;    // Step to next character
+            }
+            return out;
+        }
+
+        // Fill given output iterator with repetitions of the same character
+        template<class OutIt, class Ch>
+        inline OutIt fill_chars(OutIt out, int n, Ch ch)
+        {
+            for (int i = 0; i < n; ++i)
+                *out++ = ch;
+            return out;
+        }
+
+        // Find character
+        template<class Ch, Ch ch>
+        inline bool find_char(const Ch *begin, const Ch *end)
+        {
+            while (begin != end)
+                if (*begin++ == ch)
+                    return true;
+            return false;
+        }
+
+        template<class OutIt, class Ch>
+        inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);
+
+        // Print children of the node
+        template<class OutIt, class Ch>
+        inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling())
+                out = print_node(out, child, flags, indent);
+            return out;
+        }
+
+        // Print attributes of the node
+        template<class OutIt, class Ch>
+        inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags)
+        {
+            for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute;
+                 attribute = attribute->next_attribute())
+            {
+                if (attribute->name() && attribute->value())
+                {
+                    // Print attribute name
+                    *out = Ch(' '), ++out;
+                    out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out);
+                    *out = Ch('='), ++out;
+                    // Print attribute value using appropriate quote type
+                    if (find_char<Ch, Ch('"')>(attribute->value(), attribute->value() + attribute->value_size()))
+                    {
+                        *out = Ch('\''), ++out;
+                        out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(),
+                                                    Ch('"'), out);
+                        *out = Ch('\''), ++out;
+                    }
+                    else
+                    {
+                        *out = Ch('"'), ++out;
+                        out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(),
+                                                    Ch('\''), out);
+                        *out = Ch('"'), ++out;
+                    }
+                }
+            }
+            return out;
+        }
+
+        // Print data node
+        template<class OutIt, class Ch>
+        inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            assert(node->type() == node_data);
+            if (!(flags & print_no_indenting))
+                out = fill_chars(out, indent, Ch('\t'));
+            out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
+            return out;
+        }
+
+        // Print data node
+        template<class OutIt, class Ch>
+        inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            assert(node->type() == node_cdata);
+            if (!(flags & print_no_indenting))
+                out = fill_chars(out, indent, Ch('\t'));
+            *out = Ch('<'); ++out;
+            *out = Ch('!'); ++out;
+            *out = Ch('['); ++out;
+            *out = Ch('C'); ++out;
+            *out = Ch('D'); ++out;
+            *out = Ch('A'); ++out;
+            *out = Ch('T'); ++out;
+            *out = Ch('A'); ++out;
+            *out = Ch('['); ++out;
+            out = copy_chars(node->value(), node->value() + node->value_size(), out);
+            *out = Ch(']'); ++out;
+            *out = Ch(']'); ++out;
+            *out = Ch('>'); ++out;
+            return out;
+        }
+
+        // Print element node
+        template<class OutIt, class Ch>
+        inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            assert(node->type() == node_element);
+
+            // Print element name and attributes, if any
+            if (!(flags & print_no_indenting))
+                out = fill_chars(out, indent, Ch('\t'));
+            *out = Ch('<'), ++out;
+            out = copy_chars(node->name(), node->name() + node->name_size(), out);
+            out = print_attributes(out, node, flags);
+
+            // If node is childless
+            if (node->value_size() == 0 && !node->first_node())
+            {
+                // Print childless node tag ending
+                *out = Ch('/'), ++out;
+                *out = Ch('>'), ++out;
+            }
+            else
+            {
+                // Print normal node tag ending
+                *out = Ch('>'), ++out;
+
+                // Test if node contains a single data node only (and no other nodes)
+                xml_node<Ch> *child = node->first_node();
+                if (!child)
+                {
+                    // If node has no children, only print its value without indenting
+                    out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
+                }
+                else if (child->next_sibling() == 0 && child->type() == node_data)
+                {
+                    // If node has a sole data child, only print its value without indenting
+                    out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out);
+                }
+                else
+                {
+                    // Print all children with full indenting
+                    if (!(flags & print_no_indenting))
+                        *out = Ch('\n'), ++out;
+                    out = print_children(out, node, flags, indent + 1);
+                    if (!(flags & print_no_indenting))
+                        out = fill_chars(out, indent, Ch('\t'));
+                }
+
+                // Print node end
+                *out = Ch('<'), ++out;
+                *out = Ch('/'), ++out;
+                out = copy_chars(node->name(), node->name() + node->name_size(), out);
+                *out = Ch('>'), ++out;
+            }
+            return out;
+        }
+
+        // Print declaration node
+        template<class OutIt, class Ch>
+        inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            // Print declaration start
+            if (!(flags & print_no_indenting))
+                out = fill_chars(out, indent, Ch('\t'));
+            *out = Ch('<'), ++out;
+            *out = Ch('?'), ++out;
+            *out = Ch('x'), ++out;
+            *out = Ch('m'), ++out;
+            *out = Ch('l'), ++out;
+
+            // Print attributes
+            out = print_attributes(out, node, flags);
+
+            // Print declaration end
+            *out = Ch('?'), ++out;
+            *out = Ch('>'), ++out;
+
+            return out;
+        }
+
+        // Print comment node
+        template<class OutIt, class Ch>
+        inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            assert(node->type() == node_comment);
+            if (!(flags & print_no_indenting))
+                out = fill_chars(out, indent, Ch('\t'));
+            *out = Ch('<'), ++out;
+            *out = Ch('!'), ++out;
+            *out = Ch('-'), ++out;
+            *out = Ch('-'), ++out;
+            out = copy_chars(node->value(), node->value() + node->value_size(), out);
+            *out = Ch('-'), ++out;
+            *out = Ch('-'), ++out;
+            *out = Ch('>'), ++out;
+            return out;
+        }
+
+        // Print doctype node
+        template<class OutIt, class Ch>
+        inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            assert(node->type() == node_doctype);
+            if (!(flags & print_no_indenting))
+                out = fill_chars(out, indent, Ch('\t'));
+            *out = Ch('<'), ++out;
+            *out = Ch('!'), ++out;
+            *out = Ch('D'), ++out;
+            *out = Ch('O'), ++out;
+            *out = Ch('C'), ++out;
+            *out = Ch('T'), ++out;
+            *out = Ch('Y'), ++out;
+            *out = Ch('P'), ++out;
+            *out = Ch('E'), ++out;
+            *out = Ch(' '), ++out;
+            out = copy_chars(node->value(), node->value() + node->value_size(), out);
+            *out = Ch('>'), ++out;
+            return out;
+        }
+
+        // Print pi node
+        template<class OutIt, class Ch>
+        inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            assert(node->type() == node_pi);
+            if (!(flags & print_no_indenting))
+                out = fill_chars(out, indent, Ch('\t'));
+            *out = Ch('<'), ++out;
+            *out = Ch('?'), ++out;
+            out = copy_chars(node->name(), node->name() + node->name_size(), out);
+            *out = Ch(' '), ++out;
+            out = copy_chars(node->value(), node->value() + node->value_size(), out);
+            *out = Ch('?'), ++out;
+            *out = Ch('>'), ++out;
+            return out;
+        }
+        ///////////////////////////////////////////////////////////////////////////
+        // Internal printing operations
+
+        // Print node
+        template<class OutIt, class Ch>
+        inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            // Print proper node type
+            switch (node->type())
+            {
+
+                // Document
+                case node_document:
+                    out = print_children(out, node, flags, indent);
+                    break;
+
+                // Element
+                case node_element:
+                    out = print_element_node(out, node, flags, indent);
+                    break;
+
+                // Data
+                case node_data:
+                    out = print_data_node(out, node, flags, indent);
+                    break;
+
+                // CDATA
+                case node_cdata:
+                    out = print_cdata_node(out, node, flags, indent);
+                    break;
+
+                // Declaration
+                case node_declaration:
+                    out = print_declaration_node(out, node, flags, indent);
+                    break;
+
+                // Comment
+                case node_comment:
+                    out = print_comment_node(out, node, flags, indent);
+                    break;
+
+                // Doctype
+                case node_doctype:
+                    out = print_doctype_node(out, node, flags, indent);
+                    break;
+
+                // Pi
+                case node_pi:
+                    out = print_pi_node(out, node, flags, indent);
+                    break;
+
+                // Unknown
+                default:
+                    assert(0);
+                    break;
+            }
+
+            // If indenting not disabled, add line break after node
+            if (!(flags & print_no_indenting))
+                *out = Ch('\n'), ++out;
+
+            // Return modified iterator
+            return out;
+        }
+    }
+    //! \endcond
+
+    ///////////////////////////////////////////////////////////////////////////
+    // Printing
+
+    //! Prints XML to given output iterator.
+    //! \param out Output iterator to print to.
+    //! \param node Node to be printed. Pass xml_document to print entire document.
+    //! \param flags Flags controlling how XML is printed.
+    //! \return Output iterator pointing to position immediately after last character of printed text.
+    template<class OutIt, class Ch>
+    inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0)
+    {
+        return internal::print_node(out, &node, flags, 0);
+    }
+
+#ifndef RAPIDXML_NO_STREAMS
+
+    //! Prints XML to given output stream.
+    //! \param out Output stream to print to.
+    //! \param node Node to be printed. Pass xml_document to print entire document.
+    //! \param flags Flags controlling how XML is printed.
+    //! \return Output stream.
+    template<class Ch>
+    inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node,
+                                         int flags = 0)
+    {
+        print(std::ostream_iterator<Ch>(out), node, flags);
+        return out;
+    }
+
+    //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.
+    //! \param out Output stream to print to.
+    //! \param node Node to be printed.
+    //! \return Output stream.
+    template<class Ch>
+    inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node)
+    {
+        return print(out, node);
+    }
+
+#endif
+
+}
+
+#endif
diff --git a/extlibs/rapidxml/rapidxml_utils.hpp b/extlibs/rapidxml/rapidxml_utils.hpp
new file mode 100644 (file)
index 0000000..30e7369
--- /dev/null
@@ -0,0 +1,122 @@
+#ifndef RAPIDXML_UTILS_HPP_INCLUDED
+#define RAPIDXML_UTILS_HPP_INCLUDED
+
+// Copyright (C) 2006, 2009 Marcin Kalicinski
+// Version 1.13
+// Revision $DateTime: 2009/05/13 01:46:17 $
+//! \file rapidxml_utils.hpp This file contains high-level rapidxml utilities that can be useful
+//! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective.
+
+#include "rapidxml.hpp"
+#include <vector>
+#include <string>
+#include <fstream>
+#include <stdexcept>
+
+namespace rapidxml
+{
+
+    //! Represents data loaded from a file
+    template<class Ch = char>
+    class file
+    {
+
+        public:
+
+            //! Loads file into the memory. Data will be automatically destroyed by the destructor.
+            //! \param filename Filename to load.
+            file(const char *filename)
+            {
+                using namespace std;
+
+                // Open stream
+                basic_ifstream<Ch> stream(filename, ios::binary);
+                if (!stream)
+                    throw runtime_error(string("cannot open file ") + filename);
+                stream.unsetf(ios::skipws);
+
+                // Determine stream size
+                stream.seekg(0, ios::end);
+                size_t size = stream.tellg();
+                stream.seekg(0);
+
+                // Load data and add terminating 0
+                m_data.resize(size + 1);
+                stream.read(&m_data.front(), static_cast<streamsize>(size));
+                m_data[size] = 0;
+            }
+
+            //! Loads file into the memory. Data will be automatically destroyed by the destructor
+            //! \param stream Stream to load from
+            file(std::basic_istream<Ch> &stream)
+            {
+                using namespace std;
+
+                // Load data and add terminating 0
+                stream.unsetf(ios::skipws);
+                m_data.assign(istreambuf_iterator<Ch>(stream), istreambuf_iterator<Ch>());
+                if (stream.fail() || stream.bad())
+                    throw runtime_error("error reading stream");
+                m_data.push_back(0);
+            }
+
+            //! Gets file data.
+            //! \return Pointer to data of file.
+            Ch *data()
+            {
+                return &m_data.front();
+            }
+
+            //! Gets file data.
+            //! \return Pointer to data of file.
+            const Ch *data() const
+            {
+                return &m_data.front();
+            }
+
+            //! Gets file data size.
+            //! \return Size of file data, in characters.
+            std::size_t size() const
+            {
+                return m_data.size();
+            }
+
+        private:
+
+            std::vector<Ch> m_data;   // File data
+
+    };
+
+    //! Counts children of node. Time complexity is O(n).
+    //! \return Number of children of node
+    template<class Ch>
+    inline std::size_t count_children(xml_node<Ch> *node)
+    {
+        xml_node<Ch> *child = node->first_node();
+        std::size_t count = 0;
+        while (child)
+        {
+            ++count;
+            child = child->next_sibling();
+        }
+        return count;
+    }
+
+    //! Counts attributes of node. Time complexity is O(n).
+    //! \return Number of attributes of node
+    template<class Ch>
+    inline std::size_t count_attributes(xml_node<Ch> *node)
+    {
+        xml_attribute<Ch> *attr = node->first_attribute();
+        std::size_t count = 0;
+        while (attr)
+        {
+            ++count;
+            attr = attr->next_attribute();
+        }
+        return count;
+    }
+
+}
+
+#endif
diff --git a/extlibs/timer/timer.c b/extlibs/timer/timer.c
new file mode 100644 (file)
index 0000000..0dccd4e
--- /dev/null
@@ -0,0 +1,354 @@
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+
+#define _BSD_SOURCE
+
+#ifndef WITH_ARDUINO
+#include <pthread.h>
+#include <unistd.h>
+#include <memory.h>
+#include <stdlib.h>
+#endif
+
+#include <string.h>
+#include <stdio.h>
+
+#include "timer.h"
+
+#define SECOND (1)
+
+#define TIMEOUTS 10
+
+#define TIMEOUT_USED   1
+#define TIMEOUT_UNUSED  2
+
+#ifndef WITH_ARDUINO
+pthread_t thread_id = 0; // 0: initial thread id (meaningless)
+#endif
+
+struct timelist_t
+{
+    int timeout_state;
+    time_t timeout_seconds;
+    time_t timeout_time;
+    void (*cb)();
+} timeout_list[TIMEOUTS];
+
+/*
+ * Return the number of seconds between before and after, (after - before).
+ * This must be async-signal safe, so it cannot use difftime().
+ */
+time_t timespec_diff(const time_t after, const time_t before)
+{
+    return after - before;
+}
+
+/*
+ * Add positive seconds to a timespec, nothing if seconds is negative.
+ */
+void timespec_add(time_t * to, const time_t seconds)
+{
+    if (to && seconds > 0)
+    {
+        (*to) += seconds;
+    }
+}
+
+#ifndef WITH_ARDUINO
+
+long int getSeconds(struct tm* tp)
+{
+    long int nInterval = 0;
+
+    nInterval = (tp->tm_hour * SECS_PER_HOUR);
+    nInterval += (tp->tm_min * SECS_PER_MIN);
+    nInterval += (tp->tm_sec * SECOND);
+
+    printf("%ld", nInterval);
+
+    return nInterval;
+}
+
+long int getRelativeSecondsOfDayofweek(int ia, int ib)
+{
+    if( ia > ib )
+        return (((long int)(7 - (ib - ia))) * SECS_PER_DAY);
+
+    return (((long int)((ib - ia))) * SECS_PER_DAY);
+}
+
+long int getRelativeIntervalOfWeek(struct tm* tp)
+{
+    time_t current_time;
+    struct tm* current, *midnight;
+    time_t delayed_time = 0;
+
+    time(&current_time);
+    current = localtime(&current_time);
+    midnight = (struct tm* )malloc(sizeof(struct tm));
+    memcpy(midnight, current, sizeof(struct tm));
+
+    midnight->tm_hour = 0;
+    midnight->tm_min = 0;
+    midnight->tm_sec = 0;
+
+    // Seconds.
+    // Seconds from midnight.
+    delayed_time = current_time - mktime(midnight);
+    delayed_time = getRelativeSecondsOfDayofweek(current->tm_wday, tp->tm_wday) - delayed_time;
+    delayed_time = delayed_time + getSeconds(tp);
+
+    return delayed_time;
+}
+
+long int getSecondsFromAbsTime(struct tm* tp)
+{
+   time_t current_time;
+   time_t delayed_time = 0;
+
+   time(&current_time);
+   localtime(&current_time);
+
+   delayed_time = mktime(tp) - current_time;
+
+   return delayed_time;
+}
+
+time_t registerTimer(const time_t seconds, int *id, void *cb)
+{
+    time_t now, then;
+    time_t next;
+    int i, idx;
+
+    if (0 == thread_id)
+    {
+        initThread();
+    }
+
+    if (seconds <= 0)
+        return -1 ;
+
+    // get the current time
+    time(&now);
+
+    for (idx = 0; idx < TIMEOUTS; ++idx)
+        if (!((timeout_list[idx].timeout_state & TIMEOUT_USED) & TIMEOUT_USED))
+            break;
+
+    if (TIMEOUTS == idx) // reach to end of timer list
+        return -1;
+
+    // idx th timeout will be used.
+    // Reset and set state of the timer
+    timeout_list[idx].timeout_state = 0;
+    timeout_list[idx].timeout_state |= TIMEOUT_USED;
+
+    // calculate when the timeout should fire
+    then = now;
+    timespec_add(&then, seconds);
+
+    timeout_list[idx].timeout_time = then;
+    timeout_list[idx].timeout_seconds = seconds;
+
+    // printf( "\nbefore timeout_list[idx].cb = %X\n", timeout_list[idx].cb);
+    timeout_list[idx].cb = cb;
+    // printf( " after timeout_list[idx].cb = %X\n", timeout_list[idx].cb);
+
+    // How long till the next timeout?
+    next = seconds;
+    for (i = 0; i < TIMEOUTS; i++)
+    {
+        if ((timeout_list[i].timeout_state & (TIMEOUT_USED | TIMEOUT_UNUSED)) == TIMEOUT_USED)
+        {
+            const time_t secs = timespec_diff(timeout_list[i].timeout_time, now);
+
+            if (secs >= 0 && secs < next)
+                next = secs;
+        }
+    }
+
+    *id = idx;
+    /* Return the timeout number. */
+    return timeout_list[idx].timeout_time;
+}
+
+void unregisterTimer(int idx)
+{
+    if( 0 <= idx && idx <= TIMEOUTS)
+        timeout_list[idx].timeout_state = TIMEOUT_UNUSED;
+}
+
+void checkTimeout()
+{
+    time_t now;
+    int i;
+
+    time(&now);
+
+    /* Check all timeouts that are used and armed, but not passed yet. */
+    for (i = 0; i < TIMEOUTS; i++)
+    {
+        if ((timeout_list[i].timeout_state & (TIMEOUT_USED | TIMEOUT_UNUSED)) == TIMEOUT_USED)
+        {
+            const time_t seconds = timespec_diff(timeout_list[i].timeout_time, now);
+
+            if (seconds <= 0)
+            {
+                /* timeout [i] fires! */
+                timeout_list[i].timeout_state = TIMEOUT_UNUSED;
+                if (timeout_list[i].cb)
+                {
+                    timeout_list[i].cb();
+                }
+            }
+        }
+    }
+}
+
+void *loop(void *threadid)
+{
+    while (1)
+    {
+        sleep(SECOND);
+        checkTimeout();
+    }
+
+    return NULL ;
+}
+
+int initThread()
+{
+    int res;
+    long t = 0;
+
+    res = pthread_create(&thread_id, NULL, loop, (void *) t);
+
+    if (res)
+    {
+        printf("ERROR; return code from pthread_create() is %d\n", res);
+        return -1;
+    }
+
+    return 0;
+}
+#else   // WITH_ARDUINO
+time_t timeToSecondsFromNow(tmElements_t *t_then)
+{
+    time_t t, then;
+
+    t = now();
+    then = makeTime((*t_then));
+
+    return (time_t) (then - t);
+}
+
+time_t registerTimer(const time_t seconds, int *id,  void (*cb)())
+{
+    time_t t, then;
+    time_t next;
+    int i, idx;
+
+    if (seconds <= 0)
+    return -1;
+
+    // get the current time
+    t = now();
+
+    for (idx = 0; idx < TIMEOUTS; ++idx)
+    if (!((timeout_list[idx].timeout_state & TIMEOUT_USED) & TIMEOUT_USED))
+    break;
+
+    if (TIMEOUTS == idx)// reach to end of timer list
+    return -1;
+
+    // idx th timeout will be used.
+    // Reset and set state of the timer
+    timeout_list[idx].timeout_state = 0;
+    timeout_list[idx].timeout_state |= TIMEOUT_USED;
+
+    // calculate when the timeout should fire
+    then = t;
+    timespec_add(&then, seconds);
+
+    timeout_list[idx].timeout_time = then;
+    timeout_list[idx].timeout_seconds = seconds;
+
+    // printf( "\nbefore timeout_list[idx].cb = %X\n", timeout_list[idx].cb);
+    timeout_list[idx].cb = cb;
+    // printf( " after timeout_list[idx].cb = %X\n", timeout_list[idx].cb);
+
+    // How long till the next timeout?
+    next = seconds;
+    for (i = 0; i < TIMEOUTS; i++)
+    {
+        if ((timeout_list[i].timeout_state & (TIMEOUT_USED | TIMEOUT_UNUSED))
+                == TIMEOUT_USED)
+        {
+            const time_t secs = timespec_diff(timeout_list[i].timeout_time,
+                    t);
+
+            if (secs >= 0 && secs < next)
+            next = secs;
+        }
+    }
+
+    *id = idx;
+    /* Return the timeout number. */
+    return timeout_list[idx].timeout_time;
+}
+
+void unregisterTimer(int idx)
+{
+    if( 0 <= idx && idx <= TIMEOUTS)
+        timeout_list[idx].timeout_state = TIMEOUT_UNUSED;
+}
+
+void checkTimeout()
+{
+    time_t t;
+    int i;
+
+    t = now();
+
+    /* Check all timeouts that are used and armed, but not passed yet. */
+    for (i = 0; i < TIMEOUTS; i++)
+    {
+        if ((timeout_list[i].timeout_state & (TIMEOUT_USED | TIMEOUT_UNUSED))
+                == TIMEOUT_USED)
+        {
+            const time_t seconds = timespec_diff(timeout_list[i].timeout_time,
+                    t);
+
+            if (seconds <= 0)
+            {
+                /* timeout [i] fires! */
+                timeout_list[i].timeout_state = TIMEOUT_UNUSED;
+                if (timeout_list[i].cb)
+                {
+                    timeout_list[i].cb();
+                }
+            }
+        }
+    }
+}
+
+#endif
diff --git a/extlibs/timer/timer.h b/extlibs/timer/timer.h
new file mode 100644 (file)
index 0000000..3ecff36
--- /dev/null
@@ -0,0 +1,74 @@
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef TIMER_H_
+#define TIMER_H_
+
+#ifndef WITH_ARDUINO
+#include <sys/time.h>
+#else
+#include <Time.h>
+#endif
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include <math.h>
+
+#ifndef WITH_ARDUINO
+#define SECS_PER_MIN  (60L)
+#define SECS_PER_HOUR (SECS_PER_MIN * 60L)
+#define SECS_PER_DAY  (SECS_PER_HOUR * 24L)
+#define DAYS_PER_WEEK (7L)
+#define SECS_PER_WEEK (SECS_PER_DAY * DAYS_PER_WEEK)
+#define SECS_PER_YEAR (SECS_PER_WEEK * 52L)
+#define SECS_YR_2000  (946684800L)
+#endif
+
+time_t timespec_diff(const time_t after, const time_t before);
+void timespec_add(time_t * to, const time_t seconds);
+void checkTimeout();
+
+#ifndef WITH_ARDUINO
+long int getSeconds(struct tm* tp);
+long int getRelativeIntervalOfWeek(struct tm* tp);
+long int getSecondsFromAbsTime(struct tm* tp);
+
+int initThread();
+void *loop(void *threadid);
+time_t registerTimer(const time_t seconds, int *id, void *cb);
+void unregisterTimer(int id);
+
+#else
+
+time_t timeToSecondsFromNow(tmElements_t *t);
+time_t registerTimer(const time_t seconds, int *id,  void (*cb)());
+void unregisterTimer(int id);
+
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* TIMER_H_ */
+
diff --git a/extlibs/tinydtls/0001-Added-support-in-tinyDTLS-to-support-rehandshake.patch b/extlibs/tinydtls/0001-Added-support-in-tinyDTLS-to-support-rehandshake.patch
new file mode 100644 (file)
index 0000000..fb9c71f
--- /dev/null
@@ -0,0 +1,172 @@
+From c78aa91005b7b9542d595dc32d8c8fe020d2257d Mon Sep 17 00:00:00 2001
+From: Sachin Agrawal <sachin.agrawal@intel.com>
+Date: Wed, 21 Jan 2015 08:55:00 -0800
+Subject: [PATCH 1/1] Added support in tinyDTLS to support rehandshake
+
+As per RFC 6347 section 4.2.8, DTLS Server should support requests
+from clients who have silently abandoned the existing association
+and initiated a new handshake request by sending a ClientHello.
+Code is updated to detect this scenario and delete the old
+association when client successfully responds to HelloVerifyRequest.
+
+
+Change-Id: I6e256921215c1a22e9e5013499c4dfd98659f8cc
+Signed-off-by: Sachin Agrawal <sachin.agrawal@intel.com>
+---
+ extlibs/tinydtls/dtls.c |   74 +++++++++++++++++++++++++++++++++++++++++++----
+ 1 file changed, 68 insertions(+), 6 deletions(-)
+
+diff --git a/extlibs/tinydtls/dtls.c b/extlibs/tinydtls/dtls.c
+index 779e701..111a65d 100644
+--- a/extlibs/tinydtls/dtls.c
++++ b/extlibs/tinydtls/dtls.c
+@@ -529,6 +529,37 @@ known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
+        (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
+ }
++/**
++ * This method detects if we already have a established DTLS session with
++ * peer and the peer is attempting to perform a fresh handshake by sending
++ * messages with epoch = 0. This is to handle situations mentioned in
++ * RFC 6347 - section 4.2.8.
++ *
++ * @param msg  The packet received from Client
++ * @param msglen Packet length
++ * @param peer peer who is the sender for this packet
++ * @return @c 1 if this is a rehandshake attempt by
++ * client
++ */
++static int
++hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
++    dtls_peer_t *peer)
++{
++    if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
++      if (msg[0] == DTLS_CT_HANDSHAKE) {
++        uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
++        if (msg_epoch == 0) {
++          dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
++          if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
++              hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
++            return 1;
++          }
++        }
++      }
++    }
++    return 0;
++}
++
+ /** Dump out the cipher keys and IVs used for the symetric cipher. */
+ static void dtls_debug_keyblock(dtls_security_parameters_t *config)
+ {
+@@ -1540,6 +1571,7 @@ static int
+ dtls_verify_peer(dtls_context_t *ctx, 
+                dtls_peer_t *peer, 
+                session_t *session,
++               const dtls_state_t state,
+                uint8 *data, size_t data_length)
+ {
+   uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
+@@ -1595,9 +1627,11 @@ dtls_verify_peer(dtls_context_t *ctx,
+   /* TODO use the same record sequence number as in the ClientHello,
+      see 4.2.1. Denial-of-Service Countermeasures */
+-  err = dtls_send_handshake_msg_hash(ctx, peer, session,
+-                                   DTLS_HT_HELLO_VERIFY_REQUEST,
+-                                   buf, p - buf, 0);
++  err = dtls_send_handshake_msg_hash(ctx,
++                   state == DTLS_STATE_CONNECTED ? peer : NULL,
++                   session,
++                   DTLS_HT_HELLO_VERIFY_REQUEST,
++                   buf, p - buf, 0);
+   if (err < 0) {
+     dtls_warn("cannot send HelloVerify request\n");
+   }
+@@ -3209,7 +3243,7 @@ handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
+   case DTLS_HT_CLIENT_HELLO:
+-    if ((peer && state != DTLS_STATE_CONNECTED) ||
++    if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
+       (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
+       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+     }
+@@ -3223,7 +3257,7 @@ handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
+        Anything else will be rejected. Fragementation is not allowed
+        here as it would require peer state as well.
+     */
+-    err = dtls_verify_peer(ctx, peer, session, data, data_length);
++    err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
+     if (err < 0) {
+       dtls_warn("error in dtls_verify_peer err: %i\n", err);
+       return err;
+@@ -3236,7 +3270,23 @@ handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
+     /* At this point, we have a good relationship with this peer. This
+      * state is left for re-negotiation of key material. */
++     /* As per RFC 6347 - section 4.2.8 if this is an attempt to
++      * rehandshake, we can delete the existing key material
++      * as the client has demonstrated reachibility by completing
++      * the cookie exchange */
++    if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
++       dtls_debug("removing the peer\n");
++#ifndef WITH_CONTIKI
++       HASH_DEL_PEER(ctx->peers, peer);
++#else  /* WITH_CONTIKI */
++       list_remove(ctx->peers, peer);
++#endif /* WITH_CONTIKI */
++
++       dtls_free_peer(peer);
++       peer = NULL;
++    }
+     if (!peer) {
++      dtls_debug("creating new peer\n");
+       dtls_security_parameters_t *security;
+       /* msg contains a Client Hello with a valid cookie, so we can
+@@ -3594,6 +3644,7 @@ dtls_handle_message(dtls_context_t *ctx,
+   int data_length;            /* length of decrypted payload 
+                                  (without MAC and padding) */
+   int err;
++  int bypass_epoch_check = 0;
+   /* check if we have DTLS state for addr/port/ifindex */
+   peer = dtls_get_peer(ctx, session);
+@@ -3613,6 +3664,15 @@ dtls_handle_message(dtls_context_t *ctx,
+     if (peer) {
+       data_length = decrypt_verify(peer, msg, rlen, &data);
+       if (data_length < 0) {
++        if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
++          data = msg + DTLS_RH_LENGTH;
++          data_length = rlen - DTLS_RH_LENGTH;
++          state = DTLS_STATE_WAIT_CLIENTHELLO;
++          role = DTLS_SERVER;
++          /* Bypass epoch check as the epoch for incoming msg is 0
++             and expected epoch MAY be different */
++          bypass_epoch_check = 1;
++        } else {
+       int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
+         dtls_info("decrypt_verify() failed\n");
+       if (peer->state < DTLS_STATE_CONNECTED) {
+@@ -3623,8 +3683,10 @@ dtls_handle_message(dtls_context_t *ctx,
+       }
+         return err;
+       }
++    } else {
+       role = peer->role;
+       state = peer->state;
++      }
+     } else {
+       /* is_record() ensures that msg contains at least a record header */
+       data = msg + DTLS_RH_LENGTH;
+@@ -3677,7 +3739,7 @@ dtls_handle_message(dtls_context_t *ctx,
+       /* Handshake messages other than Finish must use the current
+        * epoch, Finish has epoch + 1. */
+-      if (peer) {
++      if (peer && !bypass_epoch_check) {
+       uint16_t expected_epoch = dtls_security_params(peer)->epoch;
+       uint16_t msg_epoch = 
+         dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
+-- 
+1.7.9.5
+
diff --git a/extlibs/tinydtls/0001-Adding-autoconf-generated-files-in-tinydtls-repo.patch b/extlibs/tinydtls/0001-Adding-autoconf-generated-files-in-tinydtls-repo.patch
new file mode 100644 (file)
index 0000000..263ed58
--- /dev/null
@@ -0,0 +1,256 @@
+From b44aa20e0ff2763468bf82ff4e996dec03e872bd Mon Sep 17 00:00:00 2001
+From: Sachin Agrawal <sachin.agrawal@intel.com>
+Date: Thu, 2 Apr 2015 15:21:40 -0700
+Subject: [PATCH 1/1] Adding autoconf generated files in tinydtls repo
+
+tinydtls build system uses autotools while Iotivity uses
+scons build system. Since tinydtls contains few source files
+and header files, it seems  convenient for Iotivity to use
+scons to build tinydtls library.
+This patch is to add autoconf generated files so that tinydtls
+can be build using scons script.
+
+Note: Since this change is a custom change and specifically
+for Iotivity, I do not intend to submit this patch for
+upstreaming.
+
+Change-Id: I4da593a8abccd731466a88d365dca536f608c94a
+Signed-off-by: Sachin Agrawal <sachin.agrawal@intel.com>
+---
+ extlibs/tinydtls/dtls_config.h |  171 ++++++++++++++++++++++++++++++++++++++++
+ extlibs/tinydtls/tinydtls.h    |   45 +++++++++++
+ 2 files changed, 216 insertions(+)
+ create mode 100644 extlibs/tinydtls/dtls_config.h
+ create mode 100644 extlibs/tinydtls/tinydtls.h
+
+diff --git a/extlibs/tinydtls/dtls_config.h b/extlibs/tinydtls/dtls_config.h
+new file mode 100644
+index 0000000..39df8c9
+--- /dev/null
++++ b/extlibs/tinydtls/dtls_config.h
+@@ -0,0 +1,171 @@
++/* dtls_config.h.  Generated from dtls_config.h.in by configure.  */
++/* tinydtls -- a very basic DTLS implementation
++ *
++ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
++ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
++ *
++ * Permission is hereby granted, free of charge, to any person
++ * obtaining a copy of this software and associated documentation
++ * files (the "Software"), to deal in the Software without
++ * restriction, including without limitation the rights to use, copy,
++ * modify, merge, publish, distribute, sublicense, and/or sell copies
++ * of the Software, and to permit persons to whom the Software is
++ * furnished to do so, subject to the following conditions:
++ *
++ * The above copyright notice and this permission notice shall be
++ * included in all copies or substantial portions of the Software.
++ *
++ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
++ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
++ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
++ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
++ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
++ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
++ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
++ * SOFTWARE.
++ */
++
++/**
++ * @file dtls_config.h
++ * @brief internal configuration for tinydtls library
++ *
++ * This file has been generated by configure from dtls_config.h.in.
++ */
++
++/* dummy definitions for PACKAGE_NAME and PACKAGE_VERSION */
++#define PACKAGE_NAME "tinydtls"
++#define PACKAGE_STRING "tinydtls 0.8.1"
++#define PACKAGE_VERSION "0.8.1"
++
++#ifdef CONTIKI
++#include "contiki.h"
++#include "contiki-lib.h"
++#include "contiki-net.h"
++
++#include "contiki-conf.h"
++
++/* global constants for constrained devices running Contiki */
++#ifndef DTLS_PEER_MAX
++/** The maximum number DTLS peers (i.e. sessions). */
++#  define DTLS_PEER_MAX 1
++#endif
++
++#ifndef DTLS_HANDSHAKE_MAX
++/** The maximum number of concurrent DTLS handshakes. */
++#  define DTLS_HANDSHAKE_MAX 1
++#endif
++
++#ifndef DTLS_SECURITY_MAX
++/** The maximum number of concurrently used cipher keys */
++#  define DTLS_SECURITY_MAX (DTLS_PEER_MAX + DTLS_HANDSHAKE_MAX)
++#endif
++
++#ifndef DTLS_HASH_MAX
++/** The maximum number of hash functions that can be used in parallel. */
++#  define DTLS_HASH_MAX (3 * DTLS_PEER_MAX)
++#endif
++#endif /* CONTIKI */
++
++/* Define to 1 if you have the <assert.h> header file. */
++#define HAVE_ASSERT_H 1
++
++/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
++   to 0 otherwise. */
++#define HAVE_MALLOC 1
++
++/* Define to 1 if you have the <memory.h> header file. */
++#define HAVE_MEMORY_H 1
++
++/* Define to 1 if you have the `memset' function. */
++#define HAVE_MEMSET 1
++
++/* Define to 1 if you have the <stddef.h> header file. */
++#define HAVE_STDDEF_H 1
++
++/* Define to 1 if you have the <stdint.h> header file. */
++#define HAVE_STDINT_H 1
++
++/* Define to 1 if you have the <stdlib.h> header file. */
++#define HAVE_STDLIB_H 1
++
++/* Define to 1 if you have the `strdup' function. */
++#define HAVE_STRDUP 1
++
++/* Define to 1 if you have the `strerror' function. */
++#define HAVE_STRERROR 1
++
++/* Define to 1 if you have the <strings.h> header file. */
++#define HAVE_STRINGS_H 1
++
++/* Define to 1 if you have the <string.h> header file. */
++#define HAVE_STRING_H 1
++
++/* Define to 1 if you have the `strnlen' function. */
++#define HAVE_STRNLEN 1
++
++/* Define to 1 if you have the <time.h> header file. */
++#define HAVE_TIME_H 1
++
++/* Define to 1 if you have the `vprintf' function. */
++#define HAVE_VPRINTF 1
++
++/* Define to the address where bug reports for this package should be sent. */
++#define PACKAGE_BUGREPORT ""
++
++/* Define to the full name of this package. */
++#define PACKAGE_NAME "tinydtls"
++
++/* Define to the full name and version of this package. */
++#define PACKAGE_STRING "tinydtls 0.8.1"
++
++/* Define to the one symbol short name of this package. */
++#define PACKAGE_TARNAME "tinydtls"
++
++/* Define to the home page for this package. */
++#define PACKAGE_URL ""
++
++/* Define to the version of this package. */
++#define PACKAGE_VERSION "0.8.1"
++
++/* Define to 1 if you have the ANSI C header files. */
++#define STDC_HEADERS 1
++
++/* Define to `__inline__' or `__inline' if that's what the C compiler
++   calls it, or to nothing if 'inline' is not supported under any name.  */
++#ifndef __cplusplus
++/* #undef inline */
++#endif
++
++/* Define to rpl_malloc if the replacement function should be used. */
++/* #undef malloc */
++/* Define to `unsigned int' if <sys/types.h> does not define. */
++
++/* #undef size_t */
++
++/************************************************************************/
++/* Specific Contiki platforms                                           */
++/************************************************************************/
++
++#ifdef CONTIKI
++
++#if CONTIKI_TARGET_ECONOTAG
++#  include "platform-specific/config-econotag.h"
++#endif /* CONTIKI_TARGET_ECONOTAG */
++
++#ifdef CONTIKI_TARGET_CC2538DK
++#  include "platform-specific/config-cc2538dk.h"
++#endif /* CONTIKI_TARGET_CC2538DK */
++
++#ifdef CONTIKI_TARGET_WISMOTE
++#  include "platform-specific/config-wismote.h"
++#endif /* CONTIKI_TARGET_WISMOTE */
++
++#ifdef CONTIKI_TARGET_SKY
++#  include "platform-specific/config-sky.h"
++#endif /* CONTIKI_TARGET_SKY */
++
++#ifdef CONTIKI_TARGET_MINIMAL_NET
++#  include "platform-specific/config-minimal-net.h"
++#endif /* CONTIKI_TARGET_MINIMAL_NET */
++
++#endif /* CONTIKI */
+diff --git a/extlibs/tinydtls/tinydtls.h b/extlibs/tinydtls/tinydtls.h
+new file mode 100644
+index 0000000..3fa228a
+--- /dev/null
++++ b/extlibs/tinydtls/tinydtls.h
+@@ -0,0 +1,45 @@
++/* tinydtls.h.  Generated from tinydtls.h.in by configure.  */
++/* tinydtls -- a very basic DTLS implementation
++ *
++ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
++ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
++ *
++ * Permission is hereby granted, free of charge, to any person
++ * obtaining a copy of this software and associated documentation
++ * files (the "Software"), to deal in the Software without
++ * restriction, including without limitation the rights to use, copy,
++ * modify, merge, publish, distribute, sublicense, and/or sell copies
++ * of the Software, and to permit persons to whom the Software is
++ * furnished to do so, subject to the following conditions:
++ *
++ * The above copyright notice and this permission notice shall be
++ * included in all copies or substantial portions of the Software.
++ *
++ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
++ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
++ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
++ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
++ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
++ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
++ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
++ * SOFTWARE.
++ */
++
++/**
++ * @file tinydtls.h
++ * @brief public tinydtls API
++ */
++
++#ifndef _DTLS_TINYDTLS_H_
++#define _DTLS_TINYDTLS_H_
++
++/** Defined to 1 if tinydtls is built with support for ECC */
++/* #undef DTLS_ECC */
++
++/** Defined to 1 if tinydtls is built with support for PSK */
++#define DTLS_PSK 1
++
++/** Defined to 1 if tinydtls is built for Contiki OS */
++/* #undef WITH_CONTIKI */
++
++#endif /* _DTLS_TINYDTLS_H_ */
+-- 
+1.7.9.5
+
diff --git a/extlibs/tinydtls/0001-Bug-Fix-in-earlier-rehandhsake-implementation.patch b/extlibs/tinydtls/0001-Bug-Fix-in-earlier-rehandhsake-implementation.patch
new file mode 100644 (file)
index 0000000..c52b679
--- /dev/null
@@ -0,0 +1,174 @@
+From e25d93dec6d2907430f3680ad5fbdfedc1ee94d8 Mon Sep 17 00:00:00 2001
+From: Sachin Agrawal <sachin.agrawal@intel.com>
+Date: Sun, 15 Feb 2015 22:16:43 -0800
+Subject: [PATCH 1/1] Bug Fix in earlier rehandhsake implementation
+
+Identified a corner case in earlier rehandshake implementation where if
+no data transfer takes place between client and Server before re-handshake
+is issued, re-handshake process was failing. DTLS state machine does not
+update it's state at Server until the first data packet was received from
+client. Updated logic to detect for 're-handshake' situation when epoch
+mis-match happens. Also updated dtls-client test app to conveniently test
+the feature. Use 'client:rehandshake' command for testing.
+
+Change-Id: Idfaad7d477508603c35ad7948ca7c8f05e3228d0
+Signed-off-by: Sachin Agrawal <sachin.agrawal@intel.com>
+---
+ extlibs/tinydtls/dtls.c              |   44 ++++++++++++++++++----------------
+ extlibs/tinydtls/tests/dtls-client.c |   27 +++++++++++++++++++++
+ 2 files changed, 50 insertions(+), 21 deletions(-)
+
+diff --git a/extlibs/tinydtls/dtls.c b/extlibs/tinydtls/dtls.c
+index a87d7f1..a923386 100644
+--- a/extlibs/tinydtls/dtls.c
++++ b/extlibs/tinydtls/dtls.c
+@@ -1562,6 +1562,7 @@ static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink
+  * \param ctx     The DTLS context.
+  * \param peer    The remote party we are talking to, if any.
+  * \param session Transport address of the remote peer.
++ * \param state   Current state of the connection.
+  * \param msg     The received datagram.
+  * \param msglen  Length of \p msg.
+  * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
+@@ -3644,7 +3645,6 @@ dtls_handle_message(dtls_context_t *ctx,
+   int data_length;            /* length of decrypted payload 
+                                  (without MAC and padding) */
+   int err;
+-  int bypass_epoch_check = 0;
+   /* check if we have DTLS state for addr/port/ifindex */
+   peer = dtls_get_peer(ctx, session);
+@@ -3668,24 +3668,21 @@ dtls_handle_message(dtls_context_t *ctx,
+           data = msg + DTLS_RH_LENGTH;
+           data_length = rlen - DTLS_RH_LENGTH;
+           state = DTLS_STATE_WAIT_CLIENTHELLO;
+-          role = DTLS_SERVER;
+-          /* Bypass epoch check as the epoch for incoming msg is 0
+-             and expected epoch MAY be different */
+-          bypass_epoch_check = 1;
++          role = DTLS_SERVER;       
+         } else {
+-      int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
+-        dtls_info("decrypt_verify() failed\n");
+-      if (peer->state < DTLS_STATE_CONNECTED) {
+-        dtls_alert_send_from_err(ctx, peer, &peer->session, err);
+-        peer->state = DTLS_STATE_CLOSED;
+-        /* dtls_stop_retransmission(ctx, peer); */
+-        dtls_destroy_peer(ctx, peer, 1);
+-      }
+-        return err;
+-      }
+-    } else {
+-      role = peer->role;
+-      state = peer->state;
++        int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
++          dtls_info("decrypt_verify() failed\n");
++        if (peer->state < DTLS_STATE_CONNECTED) {
++          dtls_alert_send_from_err(ctx, peer, &peer->session, err);
++          peer->state = DTLS_STATE_CLOSED;
++          /* dtls_stop_retransmission(ctx, peer); */
++          dtls_destroy_peer(ctx, peer, 1);
++        }
++          return err;
++        }
++      } else {
++        role = peer->role;
++        state = peer->state;
+       }
+     } else {
+       /* is_record() ensures that msg contains at least a record header */
+@@ -3739,7 +3736,7 @@ dtls_handle_message(dtls_context_t *ctx,
+       /* Handshake messages other than Finish must use the current
+        * epoch, Finish has epoch + 1. */
+-      if (peer && !bypass_epoch_check) {
++      if (peer) {
+       uint16_t expected_epoch = dtls_security_params(peer)->epoch;
+       uint16_t msg_epoch = 
+         dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
+@@ -3754,9 +3751,14 @@ dtls_handle_message(dtls_context_t *ctx,
+       }
+       if (expected_epoch != msg_epoch) {
+-        dtls_warn("Wrong epoch, expected %i, got: %i\n",
++          if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
++            state = DTLS_STATE_WAIT_CLIENTHELLO;
++            role = DTLS_SERVER;
++          } else {
++          dtls_warn("Wrong epoch, expected %i, got: %i\n",
+                   expected_epoch, msg_epoch);
+-        break;
++          break;
++        }
+       }
+       }
+diff --git a/extlibs/tinydtls/tests/dtls-client.c b/extlibs/tinydtls/tests/dtls-client.c
+index 306a380..05cb98f 100644
+--- a/extlibs/tinydtls/tests/dtls-client.c
++++ b/extlibs/tinydtls/tests/dtls-client.c
+@@ -44,6 +44,7 @@ typedef struct {
+ static dtls_str output_file = { 0, NULL }; /* output file name */
+ static dtls_context_t *dtls_context = NULL;
++static dtls_context_t *orig_dtls_context = NULL;
+ static const unsigned char ecdsa_priv_key[] = {
+@@ -235,6 +236,7 @@ dtls_handle_read(struct dtls_context_t *ctx) {
+ static void dtls_handle_signal(int sig)
+ {
+   dtls_free_context(dtls_context);
++  dtls_free_context(orig_dtls_context);
+   signal(sig, SIG_DFL);
+   kill(getpid(), sig);
+ }
+@@ -324,6 +326,12 @@ static dtls_handler_t cb = {
+ #define DTLS_CLIENT_CMD_CLOSE "client:close"
+ #define DTLS_CLIENT_CMD_RENEGOTIATE "client:renegotiate"
++/* As per RFC 6347 section 4.2.8, DTLS Server should support requests
++ * from clients who have silently abandoned the existing association
++ * and initiated a new handshake request by sending a ClientHello.
++ * Below command tests this feature.
++ */
++#define DTLS_CLIENT_CMD_REHANDSHAKE "client:rehandshake"
+ int 
+ main(int argc, char **argv) {
+   fd_set rfds, wfds;
+@@ -504,6 +512,24 @@ main(int argc, char **argv) {
+       printf("client: renegotiate connection\n");
+       dtls_renegotiate(dtls_context, &dst);
+       len = 0;
++      } else if (len >= strlen(DTLS_CLIENT_CMD_REHANDSHAKE) &&
++               !memcmp(buf, DTLS_CLIENT_CMD_REHANDSHAKE, strlen(DTLS_CLIENT_CMD_REHANDSHAKE))) {
++      printf("client: rehandshake connection\n");
++      if (orig_dtls_context == NULL) {
++        /* Cache the current context. We cannot free the current context as it will notify 
++         * the Server to close the connection (which we do not want).
++         */
++        orig_dtls_context = dtls_context;
++        /* Now, Create a new context and attempt to initiate a handshake. */
++        dtls_context = dtls_new_context(&fd);
++        if (!dtls_context) {
++          dtls_emerg("cannot create context\n");
++          exit(-1);
++          }
++        dtls_set_handler(dtls_context, &cb);
++        dtls_connect(dtls_context, &dst);
++      }
++      len = 0;
+       } else {
+       try_send(dtls_context, &dst);
+       }
+@@ -511,6 +537,7 @@ main(int argc, char **argv) {
+   }
+   
+   dtls_free_context(dtls_context);
++  dtls_free_context(orig_dtls_context);
+   exit(0);
+ }
+-- 
+1.7.9.5
+
diff --git a/extlibs/tinydtls/0001-Fixed-issue-to-pass-PSK-identity-hint-to-application.patch b/extlibs/tinydtls/0001-Fixed-issue-to-pass-PSK-identity-hint-to-application.patch
new file mode 100644 (file)
index 0000000..343c891
--- /dev/null
@@ -0,0 +1,73 @@
+From 116451f8fab0df90e87d394d1fa1ac9e739c7dbe Mon Sep 17 00:00:00 2001
+From: Sachin Agrawal <sachin.agrawal@intel.com>
+Date: Tue, 20 Jan 2015 15:57:40 -0800
+Subject: [PATCH 1/1] Fixed issue to pass PSK identity hint to application in
+ callback
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+In cases (with PSK ciphersuite) where Server is sending
+'PSK Identity Hint’ inside ServerKeyExchange message, DTLS library
+is not passing the ‘identity hint’ inside ‘desc’ argument in
+get_psk_info(DTLS_PSK_KEY, desc) callback. Instead, ‘desc’ contains
+the identity of the client itself. The reason for this is that the
+code inside dtls_send_client_key_exchange() method
+overwrites the ‘identity hint’ received earlier.
+
+Change-Id: Ibf447e3a6b33284118908a52aed4cf636038ab23
+Signed-off-by: Sachin Agrawal <sachin.agrawal@intel.com>
+---
+ extlibs/tinydtls/dtls.c |   17 +++++++----------
+ 1 file changed, 7 insertions(+), 10 deletions(-)
+
+diff --git a/extlibs/tinydtls/dtls.c b/extlibs/tinydtls/dtls.c
+index 92222eb..9090f22 100644
+--- a/extlibs/tinydtls/dtls.c
++++ b/extlibs/tinydtls/dtls.c
+@@ -2164,6 +2164,7 @@ static int
+ dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
+ {
+   uint8 buf[DTLS_CKXEC_LENGTH];
++  uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
+   uint8 *p;
+   dtls_handshake_parameters_t *handshake = peer->handshake_params;
+@@ -2175,28 +2176,24 @@ dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
+     int len;
+     len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
+-             handshake->keyx.psk.identity, handshake->keyx.psk.id_length,
+-             buf + sizeof(uint16),
+-             min(sizeof(buf) - sizeof(uint16),
+-                 sizeof(handshake->keyx.psk.identity)));
++               NULL, 0,
++               client_id,
++               sizeof(client_id));
+     if (len < 0) {
+       dtls_crit("no psk identity set in kx\n");
+       return len;
+     }
+     if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
+-      memset(&handshake->keyx.psk, 0, sizeof(dtls_handshake_parameters_psk_t));
+       dtls_warn("the psk identity is too long\n");
+       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+     }
+-    handshake->keyx.psk.id_length = (unsigned int)len;
+-    memcpy(handshake->keyx.psk.identity, p + sizeof(uint16), len);
+-    dtls_int_to_uint16(p, handshake->keyx.psk.id_length);
++    dtls_int_to_uint16(p, len);
+     p += sizeof(uint16);
+-    memcpy(p, handshake->keyx.psk.identity, handshake->keyx.psk.id_length);
+-    p += handshake->keyx.psk.id_length;
++    memcpy(p, client_id, len);
++    p += len;
+     break;
+   }
+-- 
+1.7.9.5
+
diff --git a/extlibs/tinydtls/0001-Updated-tinyDTLS-test-apps-to-use-identity-hint.patch b/extlibs/tinydtls/0001-Updated-tinyDTLS-test-apps-to-use-identity-hint.patch
new file mode 100644 (file)
index 0000000..4470e1a
--- /dev/null
@@ -0,0 +1,188 @@
+From 6b26519bea04167b9cf68069bf641af4651c87e0 Mon Sep 17 00:00:00 2001
+From: Sachin Agrawal <sachin.agrawal@intel.com>
+Date: Thu, 26 Feb 2015 09:28:06 -0800
+Subject: [PATCH 1/1] Updated tinyDTLS test apps to use identity hint
+
+dtls-server test is updated to pass 'psk hint' to tinyDTLS library so that
+it can send ServerKeyExchange packet. Similarly, dtls-client test
+is updated to retrieve PSK specific for the server whose identity was
+received via 'psk hint' packet.
+
+Change-Id: Ifba720f1505ed6afbf56dfc179d98790176ce0b0
+Signed-off-by: Sachin Agrawal <sachin.agrawal@intel.com>
+---
+ extlibs/tinydtls/tests/dtls-client.c |   45 ++++++++++++++++++++++------------
+ extlibs/tinydtls/tests/dtls-server.c |   43 +++++++++++++++++++++-----------
+ 2 files changed, 59 insertions(+), 29 deletions(-)
+
+diff --git a/extlibs/tinydtls/tests/dtls-client.c b/extlibs/tinydtls/tests/dtls-client.c
+index 96ed0fa..65b0275 100644
+--- a/extlibs/tinydtls/tests/dtls-client.c
++++ b/extlibs/tinydtls/tests/dtls-client.c
+@@ -22,9 +22,10 @@
+ #define DEFAULT_PORT 20220
+-#define PSK_DEFAULT_IDENTITY "Client_identity"
++#define PSK_CLIENT_IDENTITY  "Client_identity"
++#define PSK_SERVER_IDENTITY  "Server_identity"
+ #define PSK_DEFAULT_KEY      "secretPSK"
+-#define PSK_OPTIONS          "i:k:"
++#define PSK_OPTIONS          "i:s:k:"
+ #ifdef __GNUC__
+ #define UNUSED_PARAM __attribute__((unused))
+@@ -93,8 +94,10 @@ read_from_file(char *arg, unsigned char *buf, size_t max_buf_len) {
+ /* The PSK information for DTLS */
+ #define PSK_ID_MAXLEN 256
+ #define PSK_MAXLEN 256
+-static unsigned char psk_id[PSK_ID_MAXLEN];
+-static size_t psk_id_length = 0;
++static unsigned char psk_client_id[PSK_ID_MAXLEN];
++static size_t psk_client_id_length = 0;
++static unsigned char psk_server_id[PSK_ID_MAXLEN];
++static size_t psk_server_id_length = 0;
+ static unsigned char psk_key[PSK_MAXLEN];
+ static size_t psk_key_length = 0;
+@@ -114,15 +117,15 @@ get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
+       dtls_debug("got psk_identity_hint: '%.*s'\n", id_len, id);
+     }
+-    if (result_length < psk_id_length) {
++    if (result_length < psk_client_id_length) {
+       dtls_warn("cannot set psk_identity -- buffer too small\n");
+       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+     }
+-    memcpy(result, psk_id, psk_id_length);
+-    return psk_id_length;
++    memcpy(result, psk_client_id, psk_client_id_length);
++    return psk_client_id_length;
+   case DTLS_PSK_KEY:
+-    if (id_len != psk_id_length || memcmp(psk_id, id, id_len) != 0) {
++    if (id_len != psk_server_id_length || memcmp(psk_server_id, id, id_len) != 0) {
+       dtls_warn("PSK for unknown id requested, exiting\n");
+       return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
+     } else if (result_length < psk_key_length) {
+@@ -291,12 +294,13 @@ usage( const char *program, const char *version) {
+   fprintf(stderr, "%s v%s -- DTLS client implementation\n"
+         "(c) 2011-2014 Olaf Bergmann <bergmann@tzi.org>\n\n"
+ #ifdef DTLS_PSK
+-        "usage: %s [-i file] [-k file] [-o file] [-p port] [-v num] addr [port]\n"
++        "usage: %s [-i file] [-s file] [-k file] [-o file] [-p port] [-v num] addr [port]\n"
+ #else /*  DTLS_PSK */
+         "usage: %s [-o file] [-p port] [-v num] addr [port]\n"
+ #endif /* DTLS_PSK */
+ #ifdef DTLS_PSK
+-        "\t-i file\t\tread PSK identity from file\n"
++        "\t-i file\t\tread PSK Client identity from file\n"
++        "\t-s file\t\tread PSK Server identity from file\n"
+         "\t-k file\t\tread pre-shared key from file\n"
+ #endif /* DTLS_PSK */
+         "\t-o file\t\toutput received data to this file (use '-' for STDOUT)\n"
+@@ -337,9 +341,11 @@ main(int argc, char **argv) {
+   snprintf(port_str, sizeof(port_str), "%d", port);
+ #ifdef DTLS_PSK
+-  psk_id_length = strlen(PSK_DEFAULT_IDENTITY);
++  psk_client_id_length = strlen(PSK_CLIENT_IDENTITY);
++  psk_server_id_length = strlen(PSK_SERVER_IDENTITY);
+   psk_key_length = strlen(PSK_DEFAULT_KEY);
+-  memcpy(psk_id, PSK_DEFAULT_IDENTITY, psk_id_length);
++  memcpy(psk_client_id, PSK_CLIENT_IDENTITY, psk_client_id_length);
++  memcpy(psk_server_id, PSK_SERVER_IDENTITY, psk_server_id_length);
+   memcpy(psk_key, PSK_DEFAULT_KEY, psk_key_length);
+ #endif /* DTLS_PSK */
+@@ -347,11 +353,20 @@ main(int argc, char **argv) {
+     switch (opt) {
+ #ifdef DTLS_PSK
+     case 'i' : {
+-      ssize_t result = read_from_file(optarg, psk_id, PSK_ID_MAXLEN);
++      ssize_t result = read_from_file(optarg, psk_client_id, PSK_ID_MAXLEN);
+       if (result < 0) {
+-      dtls_warn("cannot read PSK identity\n");
++      dtls_warn("cannot read Client PSK identity\n");
+       } else {
+-      psk_id_length = result;
++      psk_client_id_length = result;
++      }
++      break;
++    }
++    case 's' : {
++      ssize_t result = read_from_file(optarg, psk_server_id, PSK_ID_MAXLEN);
++      if (result < 0) {
++      dtls_warn("cannot read Server PSK identity\n");
++      } else {
++      psk_server_id_length = result;
+       }
+       break;
+     }
+diff --git a/extlibs/tinydtls/tests/dtls-server.c b/extlibs/tinydtls/tests/dtls-server.c
+index 3f030b1..ae1283e 100644
+--- a/extlibs/tinydtls/tests/dtls-server.c
++++ b/extlibs/tinydtls/tests/dtls-server.c
+@@ -47,6 +47,9 @@ handle_sigint(int signum) {
+ #endif
+ #ifdef DTLS_PSK
++
++#define PSK_SERVER_HINT  "Server_identity"
++
+ /* This function is the "key store" for tinyDTLS. It is called to
+  * retrieve a key for the given identity within this particular
+  * session. */
+@@ -70,23 +73,35 @@ get_psk_info(struct dtls_context_t *ctx, const session_t *session,
+       (unsigned char *)"", 1 }
+   };
+-  if (type != DTLS_PSK_KEY) {
+-    return 0;
+-  }
++  switch (type) {
++  case DTLS_PSK_HINT:
++    if (result_length < strlen(PSK_SERVER_HINT)) {
++      dtls_warn("cannot set psk_hint -- buffer too small\n");
++      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
++    }
+-  if (id) {
+-    int i;
+-    for (i = 0; i < sizeof(psk)/sizeof(struct keymap_t); i++) {
+-      if (id_len == psk[i].id_length && memcmp(id, psk[i].id, id_len) == 0) {
+-      if (result_length < psk[i].key_length) {
+-        dtls_warn("buffer too small for PSK");
+-        return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+-      }
+-
+-      memcpy(result, psk[i].key, psk[i].key_length);
+-      return psk[i].key_length;
++    memcpy(result, PSK_SERVER_HINT, strlen(PSK_SERVER_HINT));
++    return strlen(PSK_SERVER_HINT);
++
++  case DTLS_PSK_KEY:
++    if (id) {
++      int i;
++      for (i = 0; i < sizeof(psk)/sizeof(struct keymap_t); i++) {
++        if (id_len == psk[i].id_length && memcmp(id, psk[i].id, id_len) == 0) {
++        if (result_length < psk[i].key_length) {
++          dtls_warn("buffer too small for PSK");
++          return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
++        }
++
++        memcpy(result, psk[i].key, psk[i].key_length);
++        return psk[i].key_length;
++        }
+       }
+     }
++    break;
++
++  default:
++    dtls_warn("unsupported request type: %d\n", type);
+   }
+   return dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
+-- 
+1.7.9.5
+
diff --git a/extlibs/tinydtls/Android.mk b/extlibs/tinydtls/Android.mk
new file mode 100644 (file)
index 0000000..d21965c
--- /dev/null
@@ -0,0 +1,17 @@
+APP_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_PATH = $(APP_PATH)
+LOCAL_MODULE := TinyDtls
+LOCAL_SRC_FILES := dtls.c crypto.c ccm.c hmac.c netq.c peer.c dtls_time.c session.c
+#LOCAL_SRC_FILES += debug.c
+LOCAL_SRC_FILES += aes/rijndael.c
+LOCAL_SRC_FILES += ecc/ecc.c
+LOCAL_SRC_FILES += sha2/sha2.c
+
+LOCAL_C_INCLUDES := $(APP_PATH) $(APP_PATH)/aes $(APP_PATH)/ecc $(APP_PATH)/sha2
+
+#LOCAL_CFLAGS := -DWITH_OICSTACK -fPIC
+LOCAL_CFLAGS += -DDTLSv12 -DWITH_SHA256 -DDTLS_CHECK_CONTENTTYPE -DHAVE_SYS_TIME_H
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/extlibs/tinydtls/LICENSE b/extlibs/tinydtls/LICENSE
new file mode 100644 (file)
index 0000000..2588fe2
--- /dev/null
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/extlibs/tinydtls/Makefile.in b/extlibs/tinydtls/Makefile.in
new file mode 100644 (file)
index 0000000..9a52e4c
--- /dev/null
@@ -0,0 +1,142 @@
+# Makefile for tinydtls
+#
+# Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use, copy,
+# modify, merge, publish, distribute, sublicense, and/or sell copies
+# of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+ETAGS = @ETAGS@
+
+prefix = @prefix@
+exec_prefix = @exec_prefix@
+abs_builddir = @abs_builddir@
+top_builddir = @top_builddir@
+libdir = @libdir@
+includedir = @includedir@/@PACKAGE_NAME@
+package = @PACKAGE_TARNAME@-@PACKAGE_VERSION@
+
+install := cp
+
+# files and flags
+SOURCES:= dtls.c crypto.c ccm.c hmac.c netq.c peer.c dtls_time.c session.c
+ifneq ("@NDEBUG@", "1")
+SOURCES += debug.c
+endif
+SUB_OBJECTS:=aes/rijndael.o @OPT_OBJS@
+OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) $(SUB_OBJECTS)
+HEADERS:=dtls.h hmac.h debug.h dtls_config.h uthash.h numeric.h crypto.h global.h ccm.h \
+ netq.h t_list.h alert.h utlist.h prng.h peer.h state.h dtls_time.h session.h \
+ tinydtls.h
+CFLAGS:=-Wall -pedantic -std=c99 @CFLAGS@
+CPPFLAGS:=@CPPFLAGS@ -DDTLS_CHECK_CONTENTTYPE
+SUBDIRS:=tests doc platform-specific sha2 aes ecc
+DISTSUBDIRS:=$(SUBDIRS) examples/contiki
+DISTDIR=$(top_builddir)/$(package)
+FILES:=Makefile.in configure configure.in dtls_config.h.in tinydtls.h.in \
+  Makefile.tinydtls $(SOURCES) $(HEADERS)
+LIB:=libtinydtls.a
+LDFLAGS:=@LIBS@
+ARFLAGS:=cru
+doc:=doc
+
+.PHONY: all dirs clean install dist distclean .gitignore doc TAGS
+
+ifneq ("@WITH_CONTIKI@", "1")
+.SUFFIXES:
+.SUFFIXES:      .c .o
+
+all:   $(LIB) dirs
+
+check: 
+       echo DISTDIR: $(DISTDIR)
+       echo top_builddir: $(top_builddir)
+       $(MAKE) -C tests check
+
+dirs:  $(SUBDIRS)
+       for dir in $^; do \
+               $(MAKE) -C $$dir ; \
+       done
+
+$(SUB_OBJECTS)::
+       $(MAKE) -C $(@D) $(@F)
+
+$(LIB):        $(OBJECTS)
+       $(AR) $(ARFLAGS) $@ $^ 
+       ranlib $@
+
+clean:
+       @rm -f $(PROGRAM) main.o $(LIB) $(OBJECTS)
+       for dir in $(SUBDIRS); do \
+               $(MAKE) -C $$dir clean ; \
+       done
+else  # WITH_CONTIKI
+all:
+       $(MAKE) -C examples/contiki $@
+endif # WITH_CONTIKI
+
+doc:   
+       $(MAKE) -C doc
+
+distclean:     clean
+       @rm -rf $(DISTDIR)
+       @rm -f *~ $(DISTDIR).tar.gz
+
+dist:  $(FILES) $(DISTSUBDIRS)
+       test -d $(DISTDIR) || mkdir $(DISTDIR)
+       cp $(FILES) $(DISTDIR)
+       for dir in $(DISTSUBDIRS); do \
+               $(MAKE) -C $$dir dist; \
+       done
+       tar czf $(package).tar.gz $(DISTDIR)
+
+install:       $(LIB) $(HEADERS) $(SUBDIRS)
+       test -d $(libdir) || mkdir -p $(libdir)
+       test -d $(includedir) || mkdir -p $(includedir)
+       $(install) $(LIB) $(libdir)/
+       $(install) $(HEADERS) $(includedir)/
+       for dir in $(SUBDIRS); do \
+               $(MAKE) -C $$dir install="$(install)" includedir=$(includedir) install; \
+       done
+
+TAGS:  
+       $(ETAGS) -o $@.new $(SOURCES) 
+       $(ETAGS) -a -o $@.new $(HEADERS) 
+       mv $@.new $@
+
+# files that should be ignored by git
+GITIGNOREDS:= core \*~ \*.[oa] \*.gz \*.cap \*.pcap Makefile \
+ autom4te.cache/ config.h config.log config.status configure \
+ doc/Doxyfile doc/doxygen.out doc/html/ $(LIB) tests/ccm-test \
+ tests/dtls-client tests/dtls-server tests/prf-test $(package) \
+ $(DISTDIR)/ TAGS \*.patch .gitignore ecc/testecc ecc/testfield \
+ \*.d \*.hex \*.elf \*.map obj_\* tinydtls.h dtls_config.h \
+ $(addprefix \*., $(notdir $(wildcard ../../platform/*))) \
+ .project
+
+.gitignore:
+       echo $(GITIGNOREDS) | sed 's/ /\n/g' > $@
+
diff --git a/extlibs/tinydtls/Makefile.tinydtls b/extlibs/tinydtls/Makefile.tinydtls
new file mode 100644 (file)
index 0000000..88affc4
--- /dev/null
@@ -0,0 +1,36 @@
+# This is a -*- Makefile -*-
+
+ifeq ($(TARGET), redbee-econotag)
+CFLAGS += -DSHA2_USE_INTTYPES_H=1 -DLITTLE_ENDIAN=3412 -DBYTE_ORDER=LITTLE_ENDIAN
+endif
+
+ifeq ($(TARGET), wismote)
+CFLAGS += -DSHA2_USE_INTTYPES_H=1 -DLITTLE_ENDIAN=3412 -DBYTE_ORDER=LITTLE_ENDIAN
+endif
+
+ifeq ($(TARGET), exp5438)
+CFLAGS += -DSHA2_USE_INTTYPES_H=1 -DLITTLE_ENDIAN=3412 -DBYTE_ORDER=LITTLE_ENDIAN
+endif
+
+ifeq ($(TARGET), native)
+CFLAGS += -DSHA2_USE_INTTYPES_H=1
+endif
+
+ifeq ($(TARGET), minimal-net)
+CFLAGS += -DSHA2_USE_INTTYPES_H=1
+endif
+
+CFLAGS += -DDTLSv12 -DWITH_SHA256 
+tinydtls_src = dtls.c crypto.c hmac.c rijndael.c sha2.c ccm.c netq.c ecc.c dtls_time.c peer.c session.c
+
+# This adds support for TLS_PSK_WITH_AES_128_CCM_8
+CFLAGS += -DDTLS_PSK
+
+# This adds support for TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
+CFLAGS += -DDTLS_ECC
+tinydtls_src += ecc.c
+
+# This activates debugging support
+# CFLAGS += -DNDEBUG
+tinydtls_src += debug.c
+
diff --git a/extlibs/tinydtls/README b/extlibs/tinydtls/README
new file mode 100644 (file)
index 0000000..a7b6093
--- /dev/null
@@ -0,0 +1,26 @@
+CONTENTS 
+
+This library contains functions and structures that can help
+constructing a single-threaded UDP server with DTLS support in
+C99. The following components are available:
+
+* dtls
+  Basic support for DTLS with pre-shared key mode.
+
+* tests
+  The subdirectory tests contains test programs that show how each
+  component is used. 
+
+BUILDING
+
+When using the code from the git repository at sourceforge, invoke
+'autoreconf' to re-create the configure script. To build for Contiki,
+place tinydtls into Contiki's apps directory and call 
+  ./configure --with-contiki.
+
+After configuration, invoke make to build the library and associated
+test programs. To add tinydtls as Contiki application, drop it into
+the apps directory and add the following line to your Makefile:
+
+  APPS += tinydtls/aes tinydtls/sha2 tinydtls/ecc tinydtls
+
diff --git a/extlibs/tinydtls/SConscript b/extlibs/tinydtls/SConscript
new file mode 100644 (file)
index 0000000..e547991
--- /dev/null
@@ -0,0 +1,98 @@
+# *****************************************************************
+#
+#  Copyright 2015 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.
+#
+# *****************************************************************/
+##
+# Tinydtls build script
+##
+
+Import('env')
+
+print "Reading Tinydtls folder script"
+
+target_os = env.get('TARGET_OS')
+
+if(target_os) == 'arduino':
+       env.Replace(CFLAGS = env.get('CXXFLAGS'))
+
+root_dir = './'
+
+tinydtls_src_path = root_dir
+
+env.AppendUnique(CPPPATH = [root_dir])
+env.AppendUnique(CPPPATH = [root_dir+'aes/'])
+env.AppendUnique(CPPPATH = [root_dir+'ecc/'])
+env.AppendUnique(CPPPATH = [root_dir+'sha2/'])
+
+if target_os not in ['arduino', 'windows', 'winrt']:
+       env.AppendUnique(CPPDEFINES = ['HAVE_SYS_TIME_H'])
+
+######################################################################
+# Source files and Target(s)
+######################################################################
+tinydtls_src = [
+                'dtls.c',
+                'crypto.c',
+                'ccm.c',
+                'hmac.c',
+                'netq.c',
+                'peer.c',
+                'dtls_time.c',
+                'session.c',
+                'aes/rijndael.c',
+                'ecc/ecc.c',
+                'sha2/sha2.c',
+        ]
+
+env.AppendUnique(TINYDTLS_SRC = tinydtls_src)
+
+if not env.get('RELEASE'):
+       if(target_os) not in ['android', 'arduino']:
+               env.AppendUnique(TINYDTLS_SRC = ['debug.c'])
+else:
+       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+
+env.AppendUnique(CPPDEFINES = ['DTLSV12',  'WITH_SHA256', 'DTLS_CHECK_CONTENTTYPE'])
+
+libtinydtls = env.StaticLibrary('libtinydtls', env.get('TINYDTLS_SRC'), OBJPREFIX='libtinydtls_')
+
+######################################################################
+# Generate tinydtls samples
+#
+# Note:
+# Currently there is a bug in debug.h/debug.c which fails compilation
+# of tinydtls samples in release mode. This bug is being tracked in 
+# IOT-395
+######################################################################
+if not env.get('RELEASE'):
+       samples_env = env.Clone()
+
+       if target_os not in ['arduino', 'windows', 'winrt']:
+               samples_env.AppendUnique(CPPDEFINES = ['_GNU_SOURCE'])
+
+       dtlsserver = samples_env.Program('dtls-server', ['tests/dtls-server.c'])
+       dtlsclient = samples_env.Program('dtls-client', ['tests/dtls-client.c'])
+
+       samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       samples_env.PrependUnique(LIBS = ['tinydtls'])
+
+       Alias("samples", [dtlsserver, dtlsclient])
+       samples_env.AppendTarget('samples')
+
+env.InstallTarget(libtinydtls, 'libtinydtls');
+
diff --git a/extlibs/tinydtls/aes/Makefile.in b/extlibs/tinydtls/aes/Makefile.in
new file mode 100644 (file)
index 0000000..4cf29d4
--- /dev/null
@@ -0,0 +1,76 @@
+# Makefile for tinydtls
+#
+# Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use, copy,
+# modify, merge, publish, distribute, sublicense, and/or sell copies
+# of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+
+abs_builddir = @abs_builddir@
+top_builddir = @top_builddir@
+top_srcdir:= @top_srcdir@
+
+SOURCES:= rijndael.c
+HEADERS:= rijndael.h
+OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
+CPPFLAGS=@CPPFLAGS@
+CFLAGS=-Wall -std=c99 -pedantic @CFLAGS@
+LDLIBS=@LIBS@
+FILES:=Makefile.in $(SOURCES) $(HEADERS) 
+DISTDIR=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
+
+.PHONY: all dirs clean install dist distclean .gitignore doc
+
+.SUFFIXES:
+.SUFFIXES:      .c .o
+
+all:
+
+check: 
+       echo DISTDIR: $(DISTDIR)
+       echo top_builddir: $(top_builddir)
+
+clean:
+       @rm -f $(PROGRAMS) main.o $(LIB) $(OBJECTS)
+       for dir in $(SUBDIRS); do \
+               $(MAKE) -C $$dir clean ; \
+       done
+
+distclean:     clean
+       @rm -rf $(DISTDIR)
+       @rm -f *~ $(DISTDIR).tar.gz
+
+dist:  $(FILES)
+       test -d $(DISTDIR)/aes || mkdir $(DISTDIR)/aes
+       cp -p $(FILES) $(DISTDIR)/aes
+
+install:       $(HEADERS)
+       test -d $(includedir)/aes || mkdir -p $(includedir)/aes
+       $(install) $(HEADERS) $(includedir)/aes
+
+.gitignore:
+       echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@
diff --git a/extlibs/tinydtls/aes/rijndael.c b/extlibs/tinydtls/aes/rijndael.c
new file mode 100644 (file)
index 0000000..33001a8
--- /dev/null
@@ -0,0 +1,1287 @@
+/*     $OpenBSD: rijndael.c,v 1.19 2008/06/09 07:49:45 djm Exp $ */
+
+/**
+ * rijndael-alg-fst.c
+ *
+ * @version 3.0 (December 2000)
+ *
+ * Optimised ANSI C code for the Rijndael cipher (now AES)
+ *
+ * @author Vincent Rijmen <vincent.rijmen@esat.kuleuven.ac.be>
+ * @author Antoon Bosselaers <antoon.bosselaers@esat.kuleuven.ac.be>
+ * @author Paulo Barreto <paulo.barreto@terra.com.br>
+ *
+ * This code is hereby placed in the public domain.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* #include <sys/param.h> */
+/* #include <sys/systm.h> */
+
+#include "rijndael.h"
+
+#ifdef ARDUINO_AVR_MEGA2560
+       #include <pgmspace.h>
+#else
+       #define PROGMEM
+       #define pgm_read_dword *
+#endif
+
+#undef FULL_UNROLL
+
+/*
+Te0[x] = S [x].[02, 01, 01, 03];
+Te1[x] = S [x].[03, 02, 01, 01];
+Te2[x] = S [x].[01, 03, 02, 01];
+Te3[x] = S [x].[01, 01, 03, 02];
+Te4[x] = S [x].[01, 01, 01, 01];
+
+Td0[x] = Si[x].[0e, 09, 0d, 0b];
+Td1[x] = Si[x].[0b, 0e, 09, 0d];
+Td2[x] = Si[x].[0d, 0b, 0e, 09];
+Td3[x] = Si[x].[09, 0d, 0b, 0e];
+Td4[x] = Si[x].[01, 01, 01, 01];
+*/
+
+PROGMEM static const aes_u32 Te0[256] = {
+    0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,
+    0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,
+    0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,
+    0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,
+    0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,
+    0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,
+    0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,
+    0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,
+    0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,
+    0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,
+    0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,
+    0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,
+    0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,
+    0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,
+    0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,
+    0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,
+    0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,
+    0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,
+    0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,
+    0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,
+    0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,
+    0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,
+    0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,
+    0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,
+    0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,
+    0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,
+    0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,
+    0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,
+    0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,
+    0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,
+    0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,
+    0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,
+    0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,
+    0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,
+    0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,
+    0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,
+    0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,
+    0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,
+    0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,
+    0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,
+    0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,
+    0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,
+    0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,
+    0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,
+    0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,
+    0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,
+    0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,
+    0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,
+    0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,
+    0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,
+    0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,
+    0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,
+    0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,
+    0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,
+    0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,
+    0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,
+    0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,
+    0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,
+    0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,
+    0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,
+    0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,
+    0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,
+    0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,
+    0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,
+};
+PROGMEM static const aes_u32 Te1[256] = {
+    0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,
+    0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,
+    0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,
+    0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,
+    0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,
+    0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,
+    0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,
+    0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,
+    0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,
+    0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,
+    0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,
+    0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,
+    0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,
+    0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,
+    0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,
+    0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,
+    0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,
+    0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,
+    0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,
+    0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,
+    0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,
+    0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,
+    0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,
+    0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,
+    0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,
+    0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,
+    0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,
+    0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,
+    0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,
+    0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,
+    0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,
+    0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,
+    0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,
+    0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,
+    0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,
+    0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,
+    0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,
+    0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,
+    0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,
+    0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,
+    0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,
+    0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,
+    0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,
+    0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,
+    0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,
+    0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,
+    0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,
+    0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,
+    0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,
+    0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,
+    0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,
+    0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,
+    0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,
+    0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,
+    0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,
+    0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,
+    0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,
+    0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,
+    0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,
+    0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,
+    0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,
+    0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,
+    0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,
+    0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,
+};
+PROGMEM static const aes_u32 Te2[256] = {
+    0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,
+    0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,
+    0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,
+    0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,
+    0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,
+    0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,
+    0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,
+    0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,
+    0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,
+    0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,
+    0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,
+    0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,
+    0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,
+    0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,
+    0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,
+    0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,
+    0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,
+    0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,
+    0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,
+    0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,
+    0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,
+    0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,
+    0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,
+    0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,
+    0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,
+    0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,
+    0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,
+    0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,
+    0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,
+    0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,
+    0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,
+    0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,
+    0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,
+    0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,
+    0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,
+    0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,
+    0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,
+    0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,
+    0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,
+    0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,
+    0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,
+    0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,
+    0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,
+    0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,
+    0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,
+    0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,
+    0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,
+    0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,
+    0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,
+    0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,
+    0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,
+    0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,
+    0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,
+    0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,
+    0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,
+    0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,
+    0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,
+    0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,
+    0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,
+    0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,
+    0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,
+    0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,
+    0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,
+    0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,
+};
+PROGMEM static const aes_u32 Te3[256] = {
+    0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,
+    0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,
+    0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,
+    0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,
+    0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,
+    0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,
+    0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,
+    0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,
+    0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,
+    0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,
+    0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,
+    0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,
+    0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,
+    0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,
+    0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,
+    0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,
+    0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,
+    0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,
+    0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,
+    0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,
+    0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,
+    0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,
+    0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,
+    0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,
+    0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,
+    0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,
+    0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,
+    0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,
+    0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,
+    0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,
+    0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,
+    0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,
+    0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,
+    0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,
+    0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,
+    0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,
+    0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,
+    0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,
+    0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,
+    0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,
+    0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,
+    0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,
+    0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,
+    0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,
+    0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,
+    0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,
+    0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,
+    0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,
+    0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,
+    0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,
+    0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,
+    0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,
+    0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,
+    0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,
+    0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,
+    0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,
+    0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,
+    0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,
+    0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,
+    0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,
+    0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,
+    0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,
+    0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,
+    0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,
+};
+PROGMEM static const aes_u32 Te4[256] = {
+    0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU,
+    0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U,
+    0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU,
+    0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U,
+    0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU,
+    0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U,
+    0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU,
+    0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U,
+    0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U,
+    0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU,
+    0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U,
+    0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U,
+    0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U,
+    0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU,
+    0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U,
+    0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U,
+    0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU,
+    0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U,
+    0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U,
+    0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U,
+    0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU,
+    0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU,
+    0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U,
+    0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU,
+    0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU,
+    0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U,
+    0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU,
+    0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U,
+    0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU,
+    0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U,
+    0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U,
+    0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U,
+    0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU,
+    0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U,
+    0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU,
+    0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U,
+    0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU,
+    0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U,
+    0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U,
+    0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU,
+    0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU,
+    0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU,
+    0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U,
+    0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U,
+    0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU,
+    0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U,
+    0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU,
+    0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U,
+    0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU,
+    0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U,
+    0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU,
+    0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU,
+    0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U,
+    0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU,
+    0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U,
+    0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU,
+    0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U,
+    0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U,
+    0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U,
+    0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU,
+    0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU,
+    0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U,
+    0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU,
+    0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U,
+};
+
+#ifdef WITH_AES_DECRYPT
+
+PROGMEM static const aes_u32 Td0[256] = {
+    0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,
+    0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,
+    0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,
+    0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,
+    0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,
+    0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,
+    0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,
+    0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,
+    0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,
+    0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,
+    0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,
+    0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,
+    0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,
+    0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,
+    0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,
+    0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,
+    0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,
+    0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,
+    0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,
+    0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,
+    0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,
+    0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,
+    0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,
+    0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,
+    0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,
+    0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,
+    0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,
+    0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,
+    0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,
+    0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,
+    0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,
+    0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,
+    0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,
+    0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,
+    0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,
+    0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,
+    0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,
+    0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,
+    0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,
+    0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,
+    0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,
+    0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,
+    0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,
+    0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,
+    0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,
+    0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,
+    0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,
+    0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,
+    0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,
+    0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,
+    0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,
+    0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,
+    0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,
+    0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,
+    0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,
+    0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,
+    0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,
+    0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,
+    0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,
+    0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,
+    0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,
+    0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,
+    0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,
+    0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,
+};
+PROGMEM static const aes_u32 Td1[256] = {
+    0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,
+    0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,
+    0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,
+    0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,
+    0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,
+    0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,
+    0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,
+    0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,
+    0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,
+    0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,
+    0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,
+    0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,
+    0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,
+    0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,
+    0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,
+    0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,
+    0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,
+    0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,
+    0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,
+    0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,
+    0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,
+    0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,
+    0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,
+    0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,
+    0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,
+    0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,
+    0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,
+    0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,
+    0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,
+    0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,
+    0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,
+    0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,
+    0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,
+    0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,
+    0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,
+    0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,
+    0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,
+    0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,
+    0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,
+    0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,
+    0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,
+    0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,
+    0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,
+    0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,
+    0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,
+    0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,
+    0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,
+    0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,
+    0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,
+    0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,
+    0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,
+    0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,
+    0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,
+    0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,
+    0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,
+    0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,
+    0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,
+    0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,
+    0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,
+    0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,
+    0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,
+    0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,
+    0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,
+    0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,
+};
+PROGMEM static const aes_u32 Td2[256] = {
+    0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,
+    0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,
+    0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,
+    0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,
+    0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,
+    0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,
+    0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,
+    0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,
+    0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,
+    0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,
+    0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,
+    0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,
+    0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,
+    0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,
+    0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,
+    0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,
+    0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,
+    0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,
+    0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,
+    0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,
+    0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,
+    0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,
+    0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,
+    0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,
+    0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,
+    0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,
+    0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,
+    0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,
+    0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,
+    0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,
+    0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,
+    0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,
+    0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,
+    0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,
+    0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,
+    0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,
+    0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,
+    0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,
+    0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,
+    0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,
+    0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,
+    0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,
+    0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,
+    0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,
+    0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,
+    0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,
+    0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,
+    0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,
+    0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,
+    0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,
+    0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,
+    0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,
+    0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,
+    0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,
+    0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,
+    0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,
+    0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,
+    0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,
+    0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,
+    0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,
+    0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,
+    0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,
+    0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,
+    0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,
+};
+PROGMEM static const aes_u32 Td3[256] = {
+    0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,
+    0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,
+    0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,
+    0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,
+    0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,
+    0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,
+    0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,
+    0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,
+    0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,
+    0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,
+    0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,
+    0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,
+    0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,
+    0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,
+    0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,
+    0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,
+    0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,
+    0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,
+    0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,
+    0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,
+    0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,
+    0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,
+    0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,
+    0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,
+    0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,
+    0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,
+    0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,
+    0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,
+    0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,
+    0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,
+    0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,
+    0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,
+    0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,
+    0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,
+    0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,
+    0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,
+    0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,
+    0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,
+    0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,
+    0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,
+    0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,
+    0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,
+    0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,
+    0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,
+    0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,
+    0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,
+    0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,
+    0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,
+    0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,
+    0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,
+    0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,
+    0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,
+    0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,
+    0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,
+    0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,
+    0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,
+    0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,
+    0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,
+    0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,
+    0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,
+    0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,
+    0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,
+    0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,
+    0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,
+};
+PROGMEM static const aes_u32 Td4[256] = {
+    0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U,
+    0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U,
+    0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU,
+    0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU,
+    0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U,
+    0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U,
+    0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U,
+    0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU,
+    0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U,
+    0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU,
+    0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU,
+    0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU,
+    0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U,
+    0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U,
+    0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U,
+    0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U,
+    0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U,
+    0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U,
+    0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU,
+    0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U,
+    0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U,
+    0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU,
+    0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U,
+    0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U,
+    0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U,
+    0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU,
+    0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U,
+    0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U,
+    0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU,
+    0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U,
+    0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U,
+    0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU,
+    0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U,
+    0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU,
+    0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU,
+    0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U,
+    0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U,
+    0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U,
+    0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U,
+    0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU,
+    0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U,
+    0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U,
+    0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU,
+    0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU,
+    0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU,
+    0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U,
+    0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU,
+    0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U,
+    0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U,
+    0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U,
+    0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U,
+    0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU,
+    0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U,
+    0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU,
+    0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU,
+    0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU,
+    0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU,
+    0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U,
+    0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU,
+    0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U,
+    0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU,
+    0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U,
+    0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U,
+    0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU,
+};
+
+#endif /* WITH_AES_DECRYPT */
+
+PROGMEM static const aes_u32 rcon[] = {
+       0x01000000, 0x02000000, 0x04000000, 0x08000000,
+       0x10000000, 0x20000000, 0x40000000, 0x80000000,
+       0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
+};
+
+#define GETU32(pt) (((aes_u32)(pt)[0] << 24) ^ ((aes_u32)(pt)[1] << 16) ^ ((aes_u32)(pt)[2] <<  8) ^ ((aes_u32)(pt)[3]))
+#define PUTU32(ct, st) { (ct)[0] = (aes_u8)((st) >> 24); (ct)[1] = (aes_u8)((st) >> 16); (ct)[2] = (aes_u8)((st) >>  8); (ct)[3] = (aes_u8)(st); }
+
+/**
+ * Expand the cipher key into the encryption key schedule.
+ *
+ * @return     the number of rounds for the given cipher key size.
+ */
+int
+rijndaelKeySetupEnc(aes_u32 rk[/*4*(Nr + 1)*/], const aes_u8 cipherKey[], int keyBits)
+{
+       int i = 0;
+       aes_u32 temp;
+
+       rk[0] = GETU32(cipherKey     );
+       rk[1] = GETU32(cipherKey +  4);
+       rk[2] = GETU32(cipherKey +  8);
+       rk[3] = GETU32(cipherKey + 12);
+       if (keyBits == 128) {
+               for (;;) {
+                       temp  = rk[3];
+                       rk[4] = rk[0] ^
+                               (pgm_read_dword(&Te4[(temp >> 16) &0xff ]) & 0xff000000) ^
+                               (pgm_read_dword(&Te4[(temp >>  8) & 0xff]) & 0x00ff0000) ^
+                               (pgm_read_dword(&Te4[(temp      ) & 0xff]) & 0x0000ff00) ^
+                               (pgm_read_dword(&Te4[(temp >> 24)       ]) & 0x000000ff) ^
+                               (pgm_read_dword(&rcon[i]));
+                       rk[5] = rk[1] ^ rk[4];
+                       rk[6] = rk[2] ^ rk[5];
+                       rk[7] = rk[3] ^ rk[6];
+                       if (++i == 10) {
+                               return 10;
+                       }
+                       rk += 4;
+               }
+       }
+       rk[4] = GETU32(cipherKey + 16);
+       rk[5] = GETU32(cipherKey + 20);
+       if (keyBits == 192) {
+               for (;;) {
+                       temp = rk[ 5];
+                       rk[ 6] = rk[ 0] ^
+                               (pgm_read_dword(&Te4[(temp >> 16) & 0xff]) & 0xff000000) ^
+                               (pgm_read_dword(&Te4[(temp >>  8) & 0xff]) & 0x00ff0000) ^
+                               (pgm_read_dword(&Te4[(temp      ) & 0xff]) & 0x0000ff00) ^
+                               (pgm_read_dword(&Te4[(temp >> 24)       ]) & 0x000000ff) ^
+                               (pgm_read_dword(&rcon[i]));
+                       rk[ 7] = rk[ 1] ^ rk[ 6];
+                       rk[ 8] = rk[ 2] ^ rk[ 7];
+                       rk[ 9] = rk[ 3] ^ rk[ 8];
+                       if (++i == 8) {
+                               return 12;
+                       }
+                       rk[10] = rk[ 4] ^ rk[ 9];
+                       rk[11] = rk[ 5] ^ rk[10];
+                       rk += 6;
+               }
+       }
+       rk[6] = GETU32(cipherKey + 24);
+       rk[7] = GETU32(cipherKey + 28);
+       if (keyBits == 256) {
+               for (;;) {
+                       temp = rk[ 7];
+                       rk[ 8] = rk[ 0] ^
+                               (pgm_read_dword(&Te4[(temp >> 16) & 0xff]) & 0xff000000) ^
+                               (pgm_read_dword(&Te4[(temp >>  8) & 0xff]) & 0x00ff0000) ^
+                               (pgm_read_dword(&Te4[(temp      ) & 0xff]) & 0x0000ff00) ^
+                               (pgm_read_dword(&Te4[(temp >> 24)       ]) & 0x000000ff) ^
+                               (pgm_read_dword(&rcon[i]));
+                       rk[ 9] = rk[ 1] ^ rk[ 8];
+                       rk[10] = rk[ 2] ^ rk[ 9];
+                       rk[11] = rk[ 3] ^ rk[10];
+                       if (++i == 7) {
+                               return 14;
+                       }
+                       temp = rk[11];
+                       rk[12] = rk[ 4] ^
+                               (pgm_read_dword(&Te4[(temp >> 24)       ]) & 0xff000000) ^
+                               (pgm_read_dword(&Te4[(temp >> 16) & 0xff]) & 0x00ff0000) ^
+                               (pgm_read_dword(&Te4[(temp >>  8) & 0xff]) & 0x0000ff00) ^
+                               (pgm_read_dword(&Te4[(temp      ) & 0xff]) & 0x000000ff);
+                       rk[13] = rk[ 5] ^ rk[12];
+                       rk[14] = rk[ 6] ^ rk[13];
+                       rk[15] = rk[ 7] ^ rk[14];
+                       rk += 8;
+               }
+       }
+       return 0;
+}
+
+#ifdef WITH_AES_DECRYPT
+/**
+ * Expand the cipher key into the decryption key schedule.
+ *
+ * @return     the number of rounds for the given cipher key size.
+ */
+int
+rijndaelKeySetupDec(aes_u32 rk[/*4*(Nr + 1)*/], const aes_u8 cipherKey[], int keyBits)
+{
+       int Nr, i, j;
+       aes_u32 temp;
+
+       /* expand the cipher key: */
+       Nr = rijndaelKeySetupEnc(rk, cipherKey, keyBits);
+
+       /* invert the order of the round keys: */
+       for (i = 0, j = 4*Nr; i < j; i += 4, j -= 4) {
+               temp = rk[i    ]; rk[i    ] = rk[j    ]; rk[j    ] = temp;
+               temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;
+               temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;
+               temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
+       }
+       /* apply the inverse MixColumn transform to all round keys but the first and the last: */
+       for (i = 1; i < Nr; i++) {
+               rk += 4;
+               rk[0] =
+                       pgm_read_dword(&Td0[pgm_read_dword(&Te4[(rk[0] >> 24)       ]) & 0xff]) ^
+                       pgm_read_dword(&Td1[pgm_read_dword(&Te4[(rk[0] >> 16) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td2[pgm_read_dword(&Te4[(rk[0] >>  8) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td3[pgm_read_dword(&Te4[(rk[0]      ) & 0xff]) & 0xff]);
+               rk[1] =
+                       pgm_read_dword(&Td0[pgm_read_dword(&Te4[(rk[1] >> 24)       ]) & 0xff]) ^
+                       pgm_read_dword(&Td1[pgm_read_dword(&Te4[(rk[1] >> 16) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td2[pgm_read_dword(&Te4[(rk[1] >>  8) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td3[pgm_read_dword(&Te4[(rk[1]      ) & 0xff]) & 0xff]);
+               rk[2] =
+                       pgm_read_dword(&Td0[pgm_read_dword(&Te4[(rk[2] >> 24)       ]) & 0xff]) ^
+                       pgm_read_dword(&Td1[pgm_read_dword(&Te4[(rk[2] >> 16) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td2[pgm_read_dword(&Te4[(rk[2] >>  8) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td3[pgm_read_dword(&Te4[(rk[2]      ) & 0xff]) & 0xff]);
+               rk[3] =
+                       pgm_read_dword(&Td0[pgm_read_dword(&Te4[(rk[3] >> 24)       ]) & 0xff]) ^
+                       pgm_read_dword(&Td1[pgm_read_dword(&Te4[(rk[3] >> 16) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td2[pgm_read_dword(&Te4[(rk[3] >>  8) & 0xff]) & 0xff]) ^
+                       pgm_read_dword(&Td3[pgm_read_dword(&Te4[(rk[3]      ) & 0xff]) & 0xff]);
+       }
+       return Nr;
+}
+#endif
+
+void
+rijndaelEncrypt(const aes_u32 rk[/*4*(Nr + 1)*/], int Nr, const aes_u8 pt[16],
+    aes_u8 ct[16])
+{
+       aes_u32 s0, s1, s2, s3, t0, t1, t2, t3;
+#ifndef FULL_UNROLL
+    int r;
+#endif /* ?FULL_UNROLL */
+
+    /*
+        * map byte array block to cipher state
+        * and add initial round key:
+        */
+       s0 = GETU32(pt     ) ^ rk[0];
+       s1 = GETU32(pt +  4) ^ rk[1];
+       s2 = GETU32(pt +  8) ^ rk[2];
+       s3 = GETU32(pt + 12) ^ rk[3];
+#ifdef FULL_UNROLL
+    /* round 1: */
+       t0 = pgm_read_dword(&Te0[s0 >> 24]) ^ pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s3 & 0xff]) ^ rk[ 4];
+       t1 = pgm_read_dword(&Te0[s1 >> 24]) ^ pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s0 & 0xff]) ^ rk[ 5];
+       t2 = pgm_read_dword(&Te0[s2 >> 24]) ^ pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s1 & 0xff]) ^ rk[ 6];
+       t3 = pgm_read_dword(&Te0[s3 >> 24]) ^ pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s2 & 0xff]) ^ rk[ 7];
+       /* round 2: */
+       s0 = pgm_read_dword(&Te0[t0 >> 24]) ^ pgm_read_dword(&Te1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t3 & 0xff]) ^ rk[ 8];
+       s1 = pgm_read_dword(&Te0[t1 >> 24]) ^ pgm_read_dword(&Te1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t0 & 0xff]) ^ rk[ 9];
+       s2 = pgm_read_dword(&Te0[t2 >> 24]) ^ pgm_read_dword(&Te1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t1 & 0xff]) ^ rk[10];
+       s3 = pgm_read_dword(&Te0[t3 >> 24]) ^ pgm_read_dword(&Te1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t2 & 0xff]) ^ rk[11];
+    /* round 3: */
+       t0 = pgm_read_dword(&Te0[s0 >> 24]) ^ pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s3 & 0xff]) ^ rk[12];
+       t1 = pgm_read_dword(&Te0[s1 >> 24]) ^ pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s0 & 0xff]) ^ rk[13];
+       t2 = pgm_read_dword(&Te0[s2 >> 24]) ^ pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s1 & 0xff]) ^ rk[14];
+       t3 = pgm_read_dword(&Te0[s3 >> 24]) ^ pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s2 & 0xff]) ^ rk[15];
+       /* round 4: */
+       s0 = pgm_read_dword(&Te0[t0 >> 24]) ^ pgm_read_dword(&Te1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t3 & 0xff]) ^ rk[16];
+       s1 = pgm_read_dword(&Te0[t1 >> 24]) ^ pgm_read_dword(&Te1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t0 & 0xff]) ^ rk[17];
+       s2 = pgm_read_dword(&Te0[t2 >> 24]) ^ pgm_read_dword(&Te1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t1 & 0xff]) ^ rk[18];
+       s3 = pgm_read_dword(&Te0[t3 >> 24]) ^ pgm_read_dword(&Te1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t2 & 0xff]) ^ rk[19];
+    /* round 5: */
+       t0 = pgm_read_dword(&Te0[s0 >> 24]) ^ pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s3 & 0xff]) ^ rk[20];
+       t1 = pgm_read_dword(&Te0[s1 >> 24]) ^ pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s0 & 0xff]) ^ rk[21];
+       t2 = pgm_read_dword(&Te0[s2 >> 24]) ^ pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s1 & 0xff]) ^ rk[22];
+       t3 = pgm_read_dword(&Te0[s3 >> 24]) ^ pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s2 & 0xff]) ^ rk[23];
+       /* round 6: */
+       s0 = pgm_read_dword(&Te0[t0 >> 24]) ^ pgm_read_dword(&Te1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t3 & 0xff]) ^ rk[24];
+       s1 = pgm_read_dword(&Te0[t1 >> 24]) ^ pgm_read_dword(&Te1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t0 & 0xff]) ^ rk[25];
+       s2 = pgm_read_dword(&Te0[t2 >> 24]) ^ pgm_read_dword(&Te1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t1 & 0xff]) ^ rk[26];
+       s3 = pgm_read_dword(&Te0[t3 >> 24]) ^ pgm_read_dword(&Te1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t2 & 0xff]) ^ rk[27];
+    /* round 7: */
+       t0 = pgm_read_dword(&Te0[s0 >> 24]) ^ pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s3 & 0xff]) ^ rk[28];
+       t1 = pgm_read_dword(&Te0[s1 >> 24]) ^ pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s0 & 0xff]) ^ rk[29];
+       t2 = pgm_read_dword(&Te0[s2 >> 24]) ^ pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s1 & 0xff]) ^ rk[30];
+       t3 = pgm_read_dword(&Te0[s3 >> 24]) ^ pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s2 & 0xff]) ^ rk[31];
+       /* round 8: */
+       s0 = pgm_read_dword(&Te0[t0 >> 24]) ^ pgm_read_dword(&Te1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t3 & 0xff]) ^ rk[32];
+       s1 = pgm_read_dword(&Te0[t1 >> 24]) ^ pgm_read_dword(&Te1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t0 & 0xff]) ^ rk[33];
+       s2 = pgm_read_dword(&Te0[t2 >> 24]) ^ pgm_read_dword(&Te1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t1 & 0xff]) ^ rk[34];
+       s3 = pgm_read_dword(&Te0[t3 >> 24]) ^ pgm_read_dword(&Te1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t2 & 0xff]) ^ rk[35];
+    /* round 9: */
+       t0 = pgm_read_dword(&Te0[s0 >> 24]) ^ pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s3 & 0xff]) ^ rk[36];
+       t1 = pgm_read_dword(&Te0[s1 >> 24]) ^ pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s0 & 0xff]) ^ rk[37];
+       t2 = pgm_read_dword(&Te0[s2 >> 24]) ^ pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s1 & 0xff]) ^ rk[38];
+       t3 = pgm_read_dword(&Te0[s3 >> 24]) ^ pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s2 & 0xff]) ^ rk[39];
+    if (Nr > 10) {
+       /* round 10: */
+       s0 = pgm_read_dword(&Te0[t0 >> 24]) ^ pgm_read_dword(&Te1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t3 & 0xff]) ^ rk[40];
+       s1 = pgm_read_dword(&Te0[t1 >> 24]) ^ pgm_read_dword(&Te1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t0 & 0xff]) ^ rk[41];
+       s2 = pgm_read_dword(&Te0[t2 >> 24]) ^ pgm_read_dword(&Te1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t1 & 0xff]) ^ rk[42];
+       s3 = pgm_read_dword(&Te0[t3 >> 24]) ^ pgm_read_dword(&Te1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t2 & 0xff]) ^ rk[43];
+       /* round 11: */
+       t0 = pgm_read_dword(&Te0[s0 >> 24]) ^ pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s3 & 0xff]) ^ rk[44];
+       t1 = pgm_read_dword(&Te0[s1 >> 24]) ^ pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s0 & 0xff]) ^ rk[45];
+       t2 = pgm_read_dword(&Te0[s2 >> 24]) ^ pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s1 & 0xff]) ^ rk[46];
+       t3 = pgm_read_dword(&Te0[s3 >> 24]) ^ pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s2 & 0xff]) ^ rk[47];
+       if (Nr > 12) {
+           /* round 12: */
+           s0 = pgm_read_dword(&Te0[t0 >> 24]) ^ pgm_read_dword(&Te1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t3 & 0xff]) ^ rk[48];
+           s1 = pgm_read_dword(&Te0[t1 >> 24]) ^ pgm_read_dword(&Te1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t0 & 0xff]) ^ rk[49];
+           s2 = pgm_read_dword(&Te0[t2 >> 24]) ^ pgm_read_dword(&Te1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t1 & 0xff]) ^ rk[50];
+           s3 = pgm_read_dword(&Te0[t3 >> 24]) ^ pgm_read_dword(&Te1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[t2 & 0xff]) ^ rk[51];
+           /* round 13: */
+           t0 = pgm_read_dword(&Te0[s0 >> 24]) ^ pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s3 & 0xff]) ^ rk[52];
+           t1 = pgm_read_dword(&Te0[s1 >> 24]) ^ pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s0 & 0xff]) ^ rk[53];
+           t2 = pgm_read_dword(&Te0[s2 >> 24]) ^ pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s1 & 0xff]) ^ rk[54];
+           t3 = pgm_read_dword(&Te0[s3 >> 24]) ^ pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Te3[s2 & 0xff]) ^ rk[55];
+       }
+    }
+    rk += Nr << 2;
+#else  /* !FULL_UNROLL */
+    /*
+        * Nr - 1 full rounds:
+        */
+    r = Nr >> 1;
+    for (;;) {
+       t0 =
+           pgm_read_dword(&Te0[(s0 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(s1 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(s2 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(s3      ) & 0xff]) ^
+           rk[4];
+       t1 =
+           pgm_read_dword(&Te0[(s1 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(s2 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(s3 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(s0      ) & 0xff]) ^
+           rk[5];
+       t2 =
+           pgm_read_dword(&Te0[(s2 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(s3 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(s0 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(s1      ) & 0xff]) ^
+           rk[6];
+       t3 =
+           pgm_read_dword(&Te0[(s3 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(s0 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(s1 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(s2      ) & 0xff]) ^
+           rk[7];
+
+       rk += 8;
+       if (--r == 0) {
+           break;
+       }
+
+       s0 =
+           pgm_read_dword(&Te0[(t0 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(t1 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(t2 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(t3      ) & 0xff]) ^
+           rk[0];
+       s1 =
+           pgm_read_dword(&Te0[(t1 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(t2 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(t3 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(t0      ) & 0xff]) ^
+           rk[1];
+       s2 =
+           pgm_read_dword(&Te0[(t2 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(t3 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(t0 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(t1      ) & 0xff]) ^
+           rk[2];
+       s3 =
+           pgm_read_dword(&Te0[(t3 >> 24)       ]) ^
+           pgm_read_dword(&Te1[(t0 >> 16) & 0xff]) ^
+           pgm_read_dword(&Te2[(t1 >>  8) & 0xff]) ^
+           pgm_read_dword(&Te3[(t2      ) & 0xff]) ^
+           rk[3];
+    }
+#endif /* ?FULL_UNROLL */
+    /*
+        * apply last round and
+        * map cipher state to byte array block:
+        */
+       s0 =
+               (pgm_read_dword(&Te4[(t0 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Te4[(t1 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Te4[(t2 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Te4[(t3      ) & 0xff]) & 0x000000ff) ^
+               rk[0];
+       PUTU32(ct     , s0);
+       s1 =
+               (pgm_read_dword(&Te4[(t1 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Te4[(t2 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Te4[(t3 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Te4[(t0      ) & 0xff]) & 0x000000ff) ^
+               rk[1];
+       PUTU32(ct +  4, s1);
+       s2 =
+               (pgm_read_dword(&Te4[(t2 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Te4[(t3 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Te4[(t0 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Te4[(t1      ) & 0xff]) & 0x000000ff) ^
+               rk[2];
+       PUTU32(ct +  8, s2);
+       s3 =
+               (pgm_read_dword(&Te4[(t3 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Te4[(t0 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Te4[(t1 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Te4[(t2      ) & 0xff]) & 0x000000ff) ^
+               rk[3];
+       PUTU32(ct + 12, s3);
+}
+
+#ifdef WITH_AES_DECRYPT
+static void
+rijndaelDecrypt(const aes_u32 rk[/*4*(Nr + 1)*/], int Nr, const aes_u8 ct[16],
+    aes_u8 pt[16])
+{
+       aes_u32 s0, s1, s2, s3, t0, t1, t2, t3;
+#ifndef FULL_UNROLL
+    int r;
+#endif /* ?FULL_UNROLL */
+
+    /*
+        * map byte array block to cipher state
+        * and add initial round key:
+        */
+    s0 = GETU32(ct     ) ^ rk[0];
+    s1 = GETU32(ct +  4) ^ rk[1];
+    s2 = GETU32(ct +  8) ^ rk[2];
+    s3 = GETU32(ct + 12) ^ rk[3];
+#ifdef FULL_UNROLL
+    /* round 1: */
+    t0 = pgm_read_dword(&Td0[s0 >> 24]) ^ pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s1 & 0xff]) ^ rk[ 4];
+    t1 = pgm_read_dword(&Td0[s1 >> 24]) ^ pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s2 & 0xff]) ^ rk[ 5];
+    t2 = pgm_read_dword(&Td0[s2 >> 24]) ^ pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s3 & 0xff]) ^ rk[ 6];
+    t3 = pgm_read_dword(&Td0[s3 >> 24]) ^ pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s0 & 0xff]) ^ rk[ 7];
+    /* round 2: */
+    s0 = pgm_read_dword(&Td0[t0 >> 24]) ^ pgm_read_dword(&Td1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t1 & 0xff]) ^ rk[ 8];
+    s1 = pgm_read_dword(&Td0[t1 >> 24]) ^ pgm_read_dword(&Td1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t2 & 0xff]) ^ rk[ 9];
+    s2 = pgm_read_dword(&Td0[t2 >> 24]) ^ pgm_read_dword(&Td1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t3 & 0xff]) ^ rk[10];
+    s3 = pgm_read_dword(&Td0[t3 >> 24]) ^ pgm_read_dword(&Td1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t0 & 0xff]) ^ rk[11];
+    /* round 3: */
+    t0 = pgm_read_dword(&Td0[s0 >> 24]) ^ pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s1 & 0xff]) ^ rk[12];
+    t1 = pgm_read_dword(&Td0[s1 >> 24]) ^ pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s2 & 0xff]) ^ rk[13];
+    t2 = pgm_read_dword(&Td0[s2 >> 24]) ^ pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s3 & 0xff]) ^ rk[14];
+    t3 = pgm_read_dword(&Td0[s3 >> 24]) ^ pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s0 & 0xff]) ^ rk[15];
+    /* round 4: */
+    s0 = pgm_read_dword(&Td0[t0 >> 24]) ^ pgm_read_dword(&Td1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t1 & 0xff]) ^ rk[16];
+    s1 = pgm_read_dword(&Td0[t1 >> 24]) ^ pgm_read_dword(&Td1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t2 & 0xff]) ^ rk[17];
+    s2 = pgm_read_dword(&Td0[t2 >> 24]) ^ pgm_read_dword(&Td1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t3 & 0xff]) ^ rk[18];
+    s3 = pgm_read_dword(&Td0[t3 >> 24]) ^ pgm_read_dword(&Td1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t0 & 0xff]) ^ rk[19];
+    /* round 5: */
+    t0 = pgm_read_dword(&Td0[s0 >> 24]) ^ pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s1 & 0xff]) ^ rk[20];
+    t1 = pgm_read_dword(&Td0[s1 >> 24]) ^ pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s2 & 0xff]) ^ rk[21];
+    t2 = pgm_read_dword(&Td0[s2 >> 24]) ^ pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s3 & 0xff]) ^ rk[22];
+    t3 = pgm_read_dword(&Td0[s3 >> 24]) ^ pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s0 & 0xff]) ^ rk[23];
+    /* round 6: */
+    s0 = pgm_read_dword(&Td0[t0 >> 24]) ^ pgm_read_dword(&Td1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t1 & 0xff]) ^ rk[24];
+    s1 = pgm_read_dword(&Td0[t1 >> 24]) ^ pgm_read_dword(&Td1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t2 & 0xff]) ^ rk[25];
+    s2 = pgm_read_dword(&Td0[t2 >> 24]) ^ pgm_read_dword(&Td1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t3 & 0xff]) ^ rk[26];
+    s3 = pgm_read_dword(&Td0[t3 >> 24]) ^ pgm_read_dword(&Td1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t0 & 0xff]) ^ rk[27];
+    /* round 7: */
+    t0 = pgm_read_dword(&Td0[s0 >> 24]) ^ pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s1 & 0xff]) ^ rk[28];
+    t1 = pgm_read_dword(&Td0[s1 >> 24]) ^ pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s2 & 0xff]) ^ rk[29];
+    t2 = pgm_read_dword(&Td0[s2 >> 24]) ^ pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s3 & 0xff]) ^ rk[30];
+    t3 = pgm_read_dword(&Td0[s3 >> 24]) ^ pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s0 & 0xff]) ^ rk[31];
+    /* round 8: */
+    s0 = pgm_read_dword(&Td0[t0 >> 24]) ^ pgm_read_dword(&Td1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t1 & 0xff]) ^ rk[32];
+    s1 = pgm_read_dword(&Td0[t1 >> 24]) ^ pgm_read_dword(&Td1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t2 & 0xff]) ^ rk[33];
+    s2 = pgm_read_dword(&Td0[t2 >> 24]) ^ pgm_read_dword(&Td1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t3 & 0xff]) ^ rk[34];
+    s3 = pgm_read_dword(&Td0[t3 >> 24]) ^ pgm_read_dword(&Td1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t0 & 0xff]) ^ rk[35];
+    /* round 9: */
+    t0 = pgm_read_dword(&Td0[s0 >> 24]) ^ pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s1 & 0xff]) ^ rk[36];
+    t1 = pgm_read_dword(&Td0[s1 >> 24]) ^ pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s2 & 0xff]) ^ rk[37];
+    t2 = pgm_read_dword(&Td0[s2 >> 24]) ^ pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s3 & 0xff]) ^ rk[38];
+    t3 = pgm_read_dword(&Td0[s3 >> 24]) ^ pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s0 & 0xff]) ^ rk[39];
+    if (Nr > 10) {
+       /* round 10: */
+       s0 = pgm_read_dword(&Td0[t0 >> 24]) ^ pgm_read_dword(&Td1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t1 & 0xff]) ^ rk[40];
+       s1 = pgm_read_dword(&Td0[t1 >> 24]) ^ pgm_read_dword(&Td1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t2 & 0xff]) ^ rk[41];
+       s2 = pgm_read_dword(&Td0[t2 >> 24]) ^ pgm_read_dword(&Td1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t3 & 0xff]) ^ rk[42];
+       s3 = pgm_read_dword(&Td0[t3 >> 24]) ^ pgm_read_dword(&Td1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t0 & 0xff]) ^ rk[43];
+       /* round 11: */
+       t0 = pgm_read_dword(&Td0[s0 >> 24]) ^ pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s1 & 0xff]) ^ rk[44];
+       t1 = pgm_read_dword(&Td0[s1 >> 24]) ^ pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s2 & 0xff]) ^ rk[45];
+       t2 = pgm_read_dword(&Td0[s2 >> 24]) ^ pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s3 & 0xff]) ^ rk[46];
+       t3 = pgm_read_dword(&Td0[s3 >> 24]) ^ pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s0 & 0xff]) ^ rk[47];
+       if (Nr > 12) {
+           /* round 12: */
+           s0 = pgm_read_dword(&Td0[t0 >> 24]) ^ pgm_read_dword(&Td1[(t3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t1 & 0xff]) ^ rk[48];
+           s1 = pgm_read_dword(&Td0[t1 >> 24]) ^ pgm_read_dword(&Td1[(t0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t2 & 0xff]) ^ rk[49];
+           s2 = pgm_read_dword(&Td0[t2 >> 24]) ^ pgm_read_dword(&Td1[(t1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t3 & 0xff]) ^ rk[50];
+           s3 = pgm_read_dword(&Td0[t3 >> 24]) ^ pgm_read_dword(&Td1[(t2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(t1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[t0 & 0xff]) ^ rk[51];
+           /* round 13: */
+           t0 = pgm_read_dword(&Td0[s0 >> 24]) ^ pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s1 & 0xff]) ^ rk[52];
+           t1 = pgm_read_dword(&Td0[s1 >> 24]) ^ pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s2 & 0xff]) ^ rk[53];
+           t2 = pgm_read_dword(&Td0[s2 >> 24]) ^ pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s3 & 0xff]) ^ rk[54];
+           t3 = pgm_read_dword(&Td0[s3 >> 24]) ^ pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^ pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^ pgm_read_dword(&Td3[s0 & 0xff]) ^ rk[55];
+       }
+    }
+       rk += Nr << 2;
+#else  /* !FULL_UNROLL */
+    /*
+     * Nr - 1 full rounds:
+     */
+    r = Nr >> 1;
+    for (;;) {
+       t0 =
+           pgm_read_dword(&Td0[(s0 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(s3 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(s2 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(s1      ) & 0xff]) ^
+           rk[4];
+       t1 =
+           pgm_read_dword(&Td0[(s1 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(s0 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(s3 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(s2      ) & 0xff]) ^
+           rk[5];
+       t2 =
+           pgm_read_dword(&Td0[(s2 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(s1 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(s0 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(s3      ) & 0xff]) ^
+           rk[6];
+       t3 =
+           pgm_read_dword(&Td0[(s3 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(s2 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(s1 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(s0      ) & 0xff]) ^
+           rk[7];
+
+       rk += 8;
+       if (--r == 0) {
+           break;
+       }
+
+       s0 =
+           pgm_read_dword(&Td0[(t0 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(t3 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(t2 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(t1      ) & 0xff]) ^
+           rk[0];
+       s1 =
+           pgm_read_dword(&Td0[(t1 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(t0 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(t3 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(t2      ) & 0xff]) ^
+           rk[1];
+       s2 =
+           pgm_read_dword(&Td0[(t2 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(t1 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(t0 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(t3      ) & 0xff]) ^
+           rk[2];
+       s3 =
+           pgm_read_dword(&Td0[(t3 >> 24)       ]) ^
+           pgm_read_dword(&Td1[(t2 >> 16) & 0xff]) ^
+           pgm_read_dword(&Td2[(t1 >>  8) & 0xff]) ^
+           pgm_read_dword(&Td3[(t0      ) & 0xff]) ^
+           rk[3];
+    }
+#endif /* ?FULL_UNROLL */
+    /*
+        * apply last round and
+        * map cipher state to byte array block:
+        */
+       s0 =
+               (pgm_read_dword(&Td4[(t0 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Td4[(t3 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Td4[(t2 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Td4[(t1      ) & 0xff]) & 0x000000ff) ^
+               rk[0];
+       PUTU32(pt     , s0);
+       s1 =
+               (pgm_read_dword(&Td4[(t1 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Td4[(t0 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Td4[(t3 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Td4[(t2      ) & 0xff]) & 0x000000ff) ^
+               rk[1];
+       PUTU32(pt +  4, s1);
+       s2 =
+               (pgm_read_dword(&Td4[(t2 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Td4[(t1 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Td4[(t0 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Td4[(t3      ) & 0xff]) & 0x000000ff) ^
+               rk[2];
+       PUTU32(pt +  8, s2);
+       s3 =
+               (pgm_read_dword(&Td4[(t3 >> 24)       ]) & 0xff000000) ^
+               (pgm_read_dword(&Td4[(t2 >> 16) & 0xff]) & 0x00ff0000) ^
+               (pgm_read_dword(&Td4[(t1 >>  8) & 0xff]) & 0x0000ff00) ^
+               (pgm_read_dword(&Td4[(t0      ) & 0xff]) & 0x000000ff) ^
+               rk[3];
+       PUTU32(pt + 12, s3);
+}
+#endif
+
+/* setup key context for encryption only */
+int
+rijndael_set_key_enc_only(rijndael_ctx *ctx, const u_char *key, int bits)
+{
+       int rounds;
+
+       rounds = rijndaelKeySetupEnc(ctx->ek, key, bits);
+       if (rounds == 0)
+               return -1;
+
+       ctx->Nr = rounds;
+#ifdef WITH_AES_DECRYPT
+       ctx->enc_only = 1;
+#endif
+
+       return 0;
+}
+
+#ifdef WITH_AES_DECRYPT
+/* setup key context for both encryption and decryption */
+int
+rijndael_set_key(rijndael_ctx *ctx, const u_char *key, int bits)
+{
+       int rounds;
+
+       rounds = rijndaelKeySetupEnc(ctx->ek, key, bits);
+       if (rounds == 0)
+               return -1;
+       if (rijndaelKeySetupDec(ctx->dk, key, bits) != rounds)
+               return -1;
+
+       ctx->Nr = rounds;
+       ctx->enc_only = 0;
+
+       return 0;
+}
+
+void
+rijndael_decrypt(rijndael_ctx *ctx, const u_char *src, u_char *dst)
+{
+       rijndaelDecrypt(ctx->dk, ctx->Nr, src, dst);
+}
+#endif
+
+void
+rijndael_encrypt(rijndael_ctx *ctx, const u_char *src, u_char *dst)
+{
+       rijndaelEncrypt(ctx->ek, ctx->Nr, src, dst);
+}
diff --git a/extlibs/tinydtls/aes/rijndael.h b/extlibs/tinydtls/aes/rijndael.h
new file mode 100644 (file)
index 0000000..60e9bef
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $OpenBSD: rijndael.h,v 1.13 2008/06/09 07:49:45 djm Exp $ */
+
+/**
+ * rijndael-alg-fst.h
+ *
+ * @version 3.0 (December 2000)
+ *
+ * Optimised ANSI C code for the Rijndael cipher (now AES)
+ *
+ * @author Vincent Rijmen <vincent.rijmen@esat.kuleuven.ac.be>
+ * @author Antoon Bosselaers <antoon.bosselaers@esat.kuleuven.ac.be>
+ * @author Paulo Barreto <paulo.barreto@terra.com.br>
+ *
+ * This code is hereby placed in the public domain.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __RIJNDAEL_H
+#define __RIJNDAEL_H
+
+#include <stdint.h>
+
+#define AES_MAXKEYBITS (256)
+#define AES_MAXKEYBYTES        (AES_MAXKEYBITS>>3)
+/* for 256-bit keys we need 14 rounds for a 128 we only need 10 round */
+#define AES_MAXROUNDS  14
+
+/* bergmann: to avoid conflicts with typedefs from certain Contiki platforms,
+ * the following type names have been prefixed with "aes_": */
+typedef unsigned char  u_char;
+typedef uint8_t                aes_u8;
+typedef uint16_t       aes_u16;
+typedef uint32_t       aes_u32;
+
+/*  The structure for key information */
+typedef struct {
+#ifdef WITH_AES_DECRYPT
+       int     enc_only;               /* context contains only encrypt schedule */
+#endif
+       int     Nr;                     /* key-length-dependent number of rounds */
+       aes_u32 ek[4*(AES_MAXROUNDS + 1)];      /* encrypt key schedule */
+#ifdef WITH_AES_DECRYPT
+       aes_u32 dk[4*(AES_MAXROUNDS + 1)];      /* decrypt key schedule */
+#endif
+} rijndael_ctx;
+
+int     rijndael_set_key(rijndael_ctx *, const u_char *, int);
+int     rijndael_set_key_enc_only(rijndael_ctx *, const u_char *, int);
+void    rijndael_decrypt(rijndael_ctx *, const u_char *, u_char *);
+void    rijndael_encrypt(rijndael_ctx *, const u_char *, u_char *);
+
+int    rijndaelKeySetupEnc(aes_u32 rk[/*4*(Nr + 1)*/], const aes_u8 cipherKey[], int keyBits);
+int    rijndaelKeySetupDec(aes_u32 rk[/*4*(Nr + 1)*/], const aes_u8 cipherKey[], int keyBits);
+void   rijndaelEncrypt(const aes_u32 rk[/*4*(Nr + 1)*/], int Nr, const aes_u8 pt[16], aes_u8 ct[16]);
+
+#endif /* __RIJNDAEL_H */
diff --git a/extlibs/tinydtls/alert.h b/extlibs/tinydtls/alert.h
new file mode 100644 (file)
index 0000000..5a27faa
--- /dev/null
@@ -0,0 +1,81 @@
+/* alert.h -- DTLS alert protocol
+ *
+ * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file alert.h
+ * @brief DTLS alert protocol
+ */
+
+#ifndef _DTLS_ALERT_H_
+#define _DTLS_ALERT_H_
+
+typedef enum {
+  DTLS_ALERT_LEVEL_WARNING=1,
+  DTLS_ALERT_LEVEL_FATAL=2
+} dtls_alert_level_t;
+
+typedef enum {
+  DTLS_ALERT_CLOSE_NOTIFY = 0,                 /* close_notify */
+  DTLS_ALERT_UNEXPECTED_MESSAGE = 10,          /* unexpected_message */
+  DTLS_ALERT_BAD_RECORD_MAC = 20,              /* bad_record_mac */
+  DTLS_ALERT_RECORD_OVERFLOW = 22,             /* record_overflow */
+  DTLS_ALERT_DECOMPRESSION_FAILURE = 30,       /* decompression_failure */
+  DTLS_ALERT_HANDSHAKE_FAILURE = 40,           /* handshake_failure */
+  DTLS_ALERT_BAD_CERTIFICATE = 42,             /* bad_certificate */
+  DTLS_ALERT_UNSUPPORTED_CERTIFICATE = 43,     /* unsupported_certificate */
+  DTLS_ALERT_CERTIFICATE_REVOKED = 44,         /* certificate_revoked */
+  DTLS_ALERT_CERTIFICATE_EXPIRED = 45,         /* certificate_expired */
+  DTLS_ALERT_CERTIFICATE_UNKNOWN = 46,         /* certificate_unknown */
+  DTLS_ALERT_ILLEGAL_PARAMETER = 47,           /* illegal_parameter */
+  DTLS_ALERT_UNKNOWN_CA = 48,                  /* unknown_ca */
+  DTLS_ALERT_ACCESS_DENIED = 49,               /* access_denied */
+  DTLS_ALERT_DECODE_ERROR = 50,                        /* decode_error */
+  DTLS_ALERT_DECRYPT_ERROR = 51,               /* decrypt_error */
+  DTLS_ALERT_PROTOCOL_VERSION = 70,            /* protocol_version */
+  DTLS_ALERT_INSUFFICIENT_SECURITY = 71,       /* insufficient_security */
+  DTLS_ALERT_INTERNAL_ERROR = 80,              /* internal_error */
+  DTLS_ALERT_USER_CANCELED = 90,               /* user_canceled */
+  DTLS_ALERT_NO_RENEGOTIATION = 100,           /* no_renegotiation */
+  DTLS_ALERT_UNSUPPORTED_EXTENSION = 110       /* unsupported_extension */
+} dtls_alert_t;
+
+#define DTLS_EVENT_CONNECT        0x01DC /**< initiated handshake */
+#define DTLS_EVENT_CONNECTED      0x01DE /**< handshake or re-negotiation
+                                         * has finished */
+#define DTLS_EVENT_RENEGOTIATE    0x01DF /**< re-negotiation has started */
+
+static inline int
+dtls_alert_create(dtls_alert_level_t level, dtls_alert_t desc)
+{
+  return -((level << 8) | desc);
+}
+
+static inline int
+dtls_alert_fatal_create(dtls_alert_t desc)
+{
+  return dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, desc);
+}
+
+#endif /* _DTLS_ALERT_H_ */
diff --git a/extlibs/tinydtls/ccm.c b/extlibs/tinydtls/ccm.c
new file mode 100644 (file)
index 0000000..7563db8
--- /dev/null
@@ -0,0 +1,311 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include <string.h>
+
+#include "dtls_config.h"
+#include "global.h"
+#include "numeric.h"
+#include "ccm.h"
+
+#ifdef HAVE_ASSERT_H
+# include <assert.h>
+#endif
+
+#define CCM_FLAGS(A,M,L) (((A > 0) << 6) | (((M - 2)/2) << 3) | (L - 1))
+
+#define MASK_L(_L) ((1 << 8 * _L) - 1)
+
+#define SET_COUNTER(A,L,cnt,C) {                                       \
+    int i;                                                             \
+    memset((A) + DTLS_CCM_BLOCKSIZE - (L), 0, (L));                    \
+    (C) = (cnt) & MASK_L(L);                                           \
+    for (i = DTLS_CCM_BLOCKSIZE - 1; (C) && (i > (L)); --i, (C) >>= 8) \
+      (A)[i] |= (C) & 0xFF;                                            \
+  }
+
+static inline void 
+block0(size_t M,       /* number of auth bytes */
+       size_t L,       /* number of bytes to encode message length */
+       size_t la,      /* l(a) octets additional authenticated data */
+       size_t lm,      /* l(m) message length */
+       unsigned char nonce[DTLS_CCM_BLOCKSIZE],
+       unsigned char *result) {
+  int i;
+
+  result[0] = CCM_FLAGS(la, M, L);
+
+  /* copy the nonce */
+  memcpy(result + 1, nonce, DTLS_CCM_BLOCKSIZE - L);
+  
+  for (i=0; i < L; i++) {
+    result[15-i] = lm & 0xff;
+    lm >>= 8;
+  }
+}
+
+/** 
+ * Creates the CBC-MAC for the additional authentication data that
+ * is sent in cleartext. 
+ *
+ * \param ctx  The crypto context for the AES encryption.
+ * \param msg  The message starting with the additional authentication data.
+ * \param la   The number of additional authentication bytes in \p msg.
+ * \param B    The input buffer for crypto operations. When this function
+ *             is called, \p B must be initialized with \c B0 (the first
+ *             authentication block.
+ * \param X    The output buffer where the result of the CBC calculation
+ *             is placed.
+ * \return     The result is written to \p X.
+ */
+static void
+add_auth_data(rijndael_ctx *ctx, const unsigned char *msg, size_t la,
+             unsigned char B[DTLS_CCM_BLOCKSIZE], 
+             unsigned char X[DTLS_CCM_BLOCKSIZE]) {
+  size_t i,j; 
+
+  rijndael_encrypt(ctx, B, X);
+
+  memset(B, 0, DTLS_CCM_BLOCKSIZE);
+
+  if (!la)
+    return;
+
+#ifndef WITH_CONTIKI
+    if (la < 0xFF00) {         /* 2^16 - 2^8 */
+      j = 2;
+      dtls_int_to_uint16(B, la);
+  } else if (la <= UINT32_MAX) {
+      j = 6;
+      dtls_int_to_uint16(B, 0xFFFE);
+      dtls_int_to_uint32(B+2, la);
+    } else {
+      j = 10;
+      dtls_int_to_uint16(B, 0xFFFF);
+      dtls_int_to_uint64(B+2, la);
+    }
+#else /* WITH_CONTIKI */
+  /* With Contiki, we are building for small devices and thus
+   * anticipate that the number of additional authentication bytes
+   * will not exceed 65280 bytes (0xFF00) and we can skip the
+   * workarounds required for j=6 and j=10 on devices with a word size
+   * of 32 bits or 64 bits, respectively.
+   */
+
+  assert(la < 0xFF00);
+  j = 2;
+  dtls_int_to_uint16(B, la);
+#endif /* WITH_CONTIKI */
+
+    i = min(DTLS_CCM_BLOCKSIZE - j, la);
+    memcpy(B + j, msg, i);
+    la -= i;
+    msg += i;
+    
+    memxor(B, X, DTLS_CCM_BLOCKSIZE);
+  
+  rijndael_encrypt(ctx, B, X);
+  
+  while (la > DTLS_CCM_BLOCKSIZE) {
+    for (i = 0; i < DTLS_CCM_BLOCKSIZE; ++i)
+      B[i] = X[i] ^ *msg++;
+    la -= DTLS_CCM_BLOCKSIZE;
+
+    rijndael_encrypt(ctx, B, X);
+  }
+  
+  if (la) {
+    memset(B, 0, DTLS_CCM_BLOCKSIZE);
+    memcpy(B, msg, la);
+    memxor(B, X, DTLS_CCM_BLOCKSIZE);
+
+    rijndael_encrypt(ctx, B, X);  
+  } 
+}
+
+static inline void
+encrypt(rijndael_ctx *ctx, size_t L, unsigned long counter,
+       unsigned char *msg, size_t len,
+       unsigned char A[DTLS_CCM_BLOCKSIZE],
+       unsigned char S[DTLS_CCM_BLOCKSIZE]) {
+
+  static unsigned long counter_tmp;
+
+  SET_COUNTER(A, L, counter, counter_tmp);    
+  rijndael_encrypt(ctx, A, S);
+  memxor(msg, S, len);
+}
+
+static inline void
+mac(rijndael_ctx *ctx, 
+    unsigned char *msg, size_t len,
+    unsigned char B[DTLS_CCM_BLOCKSIZE],
+    unsigned char X[DTLS_CCM_BLOCKSIZE]) {
+  size_t i;
+
+  for (i = 0; i < len; ++i)
+    B[i] = X[i] ^ msg[i];
+
+  rijndael_encrypt(ctx, B, X);
+
+}
+
+long int
+dtls_ccm_encrypt_message(rijndael_ctx *ctx, size_t M, size_t L, 
+                        unsigned char nonce[DTLS_CCM_BLOCKSIZE], 
+                        unsigned char *msg, size_t lm, 
+                        const unsigned char *aad, size_t la) {
+  size_t i, len;
+  unsigned long counter_tmp;
+  unsigned long counter = 1; /* \bug does not work correctly on ia32 when
+                                    lm >= 2^16 */
+  unsigned char A[DTLS_CCM_BLOCKSIZE]; /* A_i blocks for encryption input */
+  unsigned char B[DTLS_CCM_BLOCKSIZE]; /* B_i blocks for CBC-MAC input */
+  unsigned char S[DTLS_CCM_BLOCKSIZE]; /* S_i = encrypted A_i blocks */
+  unsigned char X[DTLS_CCM_BLOCKSIZE]; /* X_i = encrypted B_i blocks */
+
+  len = lm;                    /* save original length */
+  /* create the initial authentication block B0 */
+  block0(M, L, la, lm, nonce, B);
+  add_auth_data(ctx, aad, la, B, X);
+
+  /* initialize block template */
+  A[0] = L-1;
+
+  /* copy the nonce */
+  memcpy(A + 1, nonce, DTLS_CCM_BLOCKSIZE - L);
+  
+  while (lm >= DTLS_CCM_BLOCKSIZE) {
+    /* calculate MAC */
+    mac(ctx, msg, DTLS_CCM_BLOCKSIZE, B, X);
+
+    /* encrypt */
+    encrypt(ctx, L, counter, msg, DTLS_CCM_BLOCKSIZE, A, S);
+
+    /* update local pointers */
+    lm -= DTLS_CCM_BLOCKSIZE;
+    msg += DTLS_CCM_BLOCKSIZE;
+    counter++;
+  }
+
+  if (lm) {
+    /* Calculate MAC. The remainder of B must be padded with zeroes, so
+     * B is constructed to contain X ^ msg for the first lm bytes (done in
+     * mac() and X ^ 0 for the remaining DTLS_CCM_BLOCKSIZE - lm bytes
+     * (i.e., we can use memcpy() here).
+     */
+    memcpy(B + lm, X + lm, DTLS_CCM_BLOCKSIZE - lm);
+    mac(ctx, msg, lm, B, X);
+
+    /* encrypt */
+    encrypt(ctx, L, counter, msg, lm, A, S);
+
+    /* update local pointers */
+    msg += lm;
+  }
+  
+  /* calculate S_0 */  
+  SET_COUNTER(A, L, 0, counter_tmp);
+  rijndael_encrypt(ctx, A, S);
+
+  for (i = 0; i < M; ++i)
+    *msg++ = X[i] ^ S[i];
+
+  return len + M;
+}
+
+long int
+dtls_ccm_decrypt_message(rijndael_ctx *ctx, size_t M, size_t L,
+                        unsigned char nonce[DTLS_CCM_BLOCKSIZE], 
+                        unsigned char *msg, size_t lm, 
+                        const unsigned char *aad, size_t la) {
+  
+  size_t len;
+  unsigned long counter_tmp;
+  unsigned long counter = 1; /* \bug does not work correctly on ia32 when
+                                    lm >= 2^16 */
+  unsigned char A[DTLS_CCM_BLOCKSIZE]; /* A_i blocks for encryption input */
+  unsigned char B[DTLS_CCM_BLOCKSIZE]; /* B_i blocks for CBC-MAC input */
+  unsigned char S[DTLS_CCM_BLOCKSIZE]; /* S_i = encrypted A_i blocks */
+  unsigned char X[DTLS_CCM_BLOCKSIZE]; /* X_i = encrypted B_i blocks */
+
+  if (lm < M)
+    goto error;
+
+  len = lm;          /* save original length */
+  lm -= M;           /* detract MAC size*/
+
+  /* create the initial authentication block B0 */
+  block0(M, L, la, lm, nonce, B);
+  add_auth_data(ctx, aad, la, B, X);
+
+  /* initialize block template */
+  A[0] = L-1;
+
+  /* copy the nonce */
+  memcpy(A + 1, nonce, DTLS_CCM_BLOCKSIZE - L);
+  
+  while (lm >= DTLS_CCM_BLOCKSIZE) {
+    /* decrypt */
+    encrypt(ctx, L, counter, msg, DTLS_CCM_BLOCKSIZE, A, S);
+    
+    /* calculate MAC */
+    mac(ctx, msg, DTLS_CCM_BLOCKSIZE, B, X);
+
+    /* update local pointers */
+    lm -= DTLS_CCM_BLOCKSIZE;
+    msg += DTLS_CCM_BLOCKSIZE;
+    counter++;
+  }
+
+  if (lm) {
+    /* decrypt */
+    encrypt(ctx, L, counter, msg, lm, A, S);
+
+    /* Calculate MAC. Note that msg ends in the MAC so we must
+     * construct B to contain X ^ msg for the first lm bytes (done in
+     * mac() and X ^ 0 for the remaining DTLS_CCM_BLOCKSIZE - lm bytes
+     * (i.e., we can use memcpy() here).
+     */
+    memcpy(B + lm, X + lm, DTLS_CCM_BLOCKSIZE - lm);
+    mac(ctx, msg, lm, B, X); 
+
+    /* update local pointers */
+    msg += lm;
+  }
+  
+  /* calculate S_0 */  
+  SET_COUNTER(A, L, 0, counter_tmp);
+  rijndael_encrypt(ctx, A, S);
+
+  memxor(msg, S, M);
+
+  /* return length if MAC is valid, otherwise continue with error handling */
+  if (equals(X, msg, M))
+    return len - M;
+  
+ error:
+  return -1;
+}
diff --git a/extlibs/tinydtls/ccm.h b/extlibs/tinydtls/ccm.h
new file mode 100644 (file)
index 0000000..c3949d2
--- /dev/null
@@ -0,0 +1,69 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef _DTLS_CCM_H_
+#define _DTLS_CCM_H_
+
+#include "aes/rijndael.h"
+
+/* implementation of Counter Mode CBC-MAC, RFC 3610 */
+
+#define DTLS_CCM_BLOCKSIZE  16 /**< size of hmac blocks */
+#define DTLS_CCM_MAX        16 /**< max number of bytes in digest */
+#define DTLS_CCM_NONCE_SIZE 12 /**< size of nonce */
+
+/** 
+ * Authenticates and encrypts a message using AES in CCM mode. Please
+ * see also RFC 3610 for the meaning of \p M, \p L, \p lm and \p la.
+ * 
+ * \param ctx The initialized rijndael_ctx object to be used for AES operations.
+ * \param M   The number of authentication octets.
+ * \param L   The number of bytes used to encode the message length.
+ * \param N   The nonce value to use. You must provide \c DTLS_CCM_BLOCKSIZE 
+ *            nonce octets, although only the first \c 16 - \p L are used.
+ * \param msg The message to encrypt. The first \p la octets are additional
+ *            authentication data that will be cleartext. Note that the 
+ *            encryption operation modifies the contents of \p msg and adds 
+ *            \p M bytes MAC. Therefore, the buffer must be at least
+ *            \p lm + \p M bytes large.
+ * \param lm  The actual length of \p msg.
+ * \param aad A pointer to the additional authentication data (can be \c NULL if
+ *            \p la is zero).
+ * \param la  The number of additional authentication octets (may be zero).
+ * \return FIXME
+ */
+long int
+dtls_ccm_encrypt_message(rijndael_ctx *ctx, size_t M, size_t L, 
+                        unsigned char nonce[DTLS_CCM_BLOCKSIZE], 
+                        unsigned char *msg, size_t lm, 
+                        const unsigned char *aad, size_t la);
+
+long int
+dtls_ccm_decrypt_message(rijndael_ctx *ctx, size_t M, size_t L, 
+                        unsigned char nonce[DTLS_CCM_BLOCKSIZE], 
+                        unsigned char *msg, size_t lm, 
+                        const unsigned char *aad, size_t la);
+
+#endif /* _DTLS_CCM_H_ */
diff --git a/extlibs/tinydtls/configure.in b/extlibs/tinydtls/configure.in
new file mode 100644 (file)
index 0000000..70b9a54
--- /dev/null
@@ -0,0 +1,115 @@
+#                                               -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+#
+# Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use, copy,
+# modify, merge, publish, distribute, sublicense, and/or sell copies
+# of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+AC_PREREQ([2.65])
+AC_INIT([tinydtls], [0.8.1])
+AC_CONFIG_SRCDIR([dtls.c])
+dnl AC_CONFIG_HEADERS([config.h])
+
+AC_ARG_WITH(contiki,
+  [AS_HELP_STRING([--with-contiki],[build libtinydtls for the Contiki OS])],
+  [AC_DEFINE(WITH_CONTIKI,1,[Define to 1 if building for Contiki.])
+   WITH_CONTIKI=1],
+  [])
+
+AC_PATH_PROG(DOXYGEN, doxygen, [:])
+AC_PATH_PROG(ETAGS, etags, [/bin/false])
+
+if test "${with_contiki}" != "yes" ; then
+# Checks for programs.
+AC_PROG_MAKE_SET
+AC_PROG_CC
+AC_PROG_RANLIB
+
+AC_C_BIGENDIAN
+
+# Checks for libraries.
+AC_SEARCH_LIBS([gethostbyname], [nsl])
+AC_SEARCH_LIBS([socket], [socket])
+fi
+
+AC_ARG_WITH(debug,
+  [AS_HELP_STRING([--without-debug],[disable all debug output and assertions])],
+  [CPPFLAGS="${CPPFLAGS} -DNDEBUG"
+   NDEBUG=1], 
+  [])
+
+AC_ARG_WITH(ecc,
+  [AS_HELP_STRING([--without-ecc],[disable support for TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8])],
+  [],
+  [AC_DEFINE(DTLS_ECC, 1, [Define to 1 if building with ECC support.])
+   OPT_OBJS="${OPT_OBJS} ecc/ecc.o"
+   DTLS_ECC=1])
+
+AC_ARG_WITH(psk,
+  [AS_HELP_STRING([--without-psk],[disable support for TLS_PSK_WITH_AES_128_CCM_8])],
+  [],
+  [AC_DEFINE(DTLS_PSK, 1, [Define to 1 if building with PSK support])
+   DTLS_PSK=1])
+
+CPPFLAGS="${CPPFLAGS} -DDTLSv12 -DWITH_SHA256"
+OPT_OBJS="${OPT_OBJS} sha2/sha2.o"
+
+AC_SUBST(OPT_OBJS)
+AC_SUBST(NDEBUG)
+AC_SUBST(WITH_CONTIKI)
+AC_SUBST(DTLS_ECC)
+AC_SUBST(DTLS_PSK)
+
+if test "${with_contiki}" = "yes" ; then
+  AC_MSG_NOTICE([skipping header checks for Contiki])
+else
+  # Checks for header files.
+  AC_CHECK_HEADERS([assert.h arpa/inet.h fcntl.h inttypes.h netdb.h netinet/in.h stddef.h stdint.h stdlib.h string.h strings.h sys/param.h sys/socket.h unistd.h])
+
+  AC_CHECK_HEADERS([sys/time.h time.h])
+  AC_CHECK_HEADERS([sys/types.h sys/stat.h])
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_C_INLINE
+AC_TYPE_SIZE_T
+
+AC_CHECK_MEMBER([struct sockaddr_in6.sin6_len],
+               [AC_DEFINE(HAVE_SOCKADDR_IN6_SIN6_LEN, [1], 
+                  [Define to 1 if struct sockaddr_in6 has a member sin6_len.])], [], 
+               [#include <netinet/in.h>])
+
+# Checks for library functions.
+AC_FUNC_MALLOC
+AC_CHECK_FUNCS([memset select socket strdup strerror strnlen fls vprintf])
+fi
+
+AC_CONFIG_HEADERS([dtls_config.h tinydtls.h])
+
+AC_CONFIG_FILES([Makefile
+                 doc/Makefile
+                 doc/Doxyfile
+                 tests/Makefile
+                 examples/contiki/Makefile
+                 platform-specific/Makefile
+                sha2/Makefile
+                aes/Makefile
+                ecc/Makefile])
+AC_OUTPUT
diff --git a/extlibs/tinydtls/crypto.c b/extlibs/tinydtls/crypto.c
new file mode 100644 (file)
index 0000000..0113342
--- /dev/null
@@ -0,0 +1,554 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ *
+ * Modified source code for micro-ecc porting,
+ *
+ * Following functions are removed:
+ *   - dtls_ec_key_to_uint32
+ *   - dtls_ec_key_from_uint32
+ * Following functions are modified:
+ *   - dtls_ecdh_pre_master_secret
+ *   - dtls_ecdsa_generate_key
+ *   - dtls_ecdsa_create_sig_hash
+ *   - dtls_ecdsa_verify_sig_hash
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include <stdio.h>
+
+#include "tinydtls.h"
+#include "dtls_config.h"
+
+#ifdef HAVE_ASSERT_H
+#include <assert.h>
+#else
+#define assert(x)
+#endif
+
+#include "global.h"
+#include "debug.h"
+#include "numeric.h"
+#include "dtls.h"
+#include "crypto.h"
+#include "ccm.h"
+#include "ecc/ecc.h"
+#include "prng.h"
+#include "netq.h"
+
+#ifndef WITH_CONTIKI
+#include <pthread.h>
+#endif
+
+#define HMAC_UPDATE_SEED(Context,Seed,Length)          \
+  if (Seed) dtls_hmac_update(Context, (Seed), (Length))
+
+static struct dtls_cipher_context_t cipher_context;
+#ifndef WITH_CONTIKI
+static pthread_mutex_t cipher_context_mutex = PTHREAD_MUTEX_INITIALIZER;
+#endif
+
+static struct dtls_cipher_context_t *dtls_cipher_context_get(void)
+{
+#ifndef WITH_CONTIKI
+  pthread_mutex_lock(&cipher_context_mutex);
+#endif
+  return &cipher_context;
+}
+
+static void dtls_cipher_context_release(void)
+{
+#ifndef WITH_CONTIKI
+  pthread_mutex_unlock(&cipher_context_mutex);
+#endif
+}
+
+#ifndef WITH_CONTIKI
+void crypto_init()
+{
+}
+
+static dtls_handshake_parameters_t *dtls_handshake_malloc() {
+  return malloc(sizeof(dtls_handshake_parameters_t));
+}
+
+static void dtls_handshake_dealloc(dtls_handshake_parameters_t *handshake) {
+  free(handshake);
+}
+
+static dtls_security_parameters_t *dtls_security_malloc() {
+  return malloc(sizeof(dtls_security_parameters_t));
+}
+
+static void dtls_security_dealloc(dtls_security_parameters_t *security) {
+  free(security);
+}
+#else /* WITH_CONTIKI */
+
+#include "memb.h"
+MEMB(handshake_storage, dtls_handshake_parameters_t, DTLS_HANDSHAKE_MAX);
+MEMB(security_storage, dtls_security_parameters_t, DTLS_SECURITY_MAX);
+
+void crypto_init() {
+  memb_init(&handshake_storage);
+  memb_init(&security_storage);
+}
+
+static dtls_handshake_parameters_t *dtls_handshake_malloc() {
+  return memb_alloc(&handshake_storage);
+}
+
+static void dtls_handshake_dealloc(dtls_handshake_parameters_t *handshake) {
+  memb_free(&handshake_storage, handshake);
+}
+
+static dtls_security_parameters_t *dtls_security_malloc() {
+  return memb_alloc(&security_storage);
+}
+
+static void dtls_security_dealloc(dtls_security_parameters_t *security) {
+  memb_free(&security_storage, security);
+}
+#endif /* WITH_CONTIKI */
+
+dtls_handshake_parameters_t *dtls_handshake_new()
+{
+  dtls_handshake_parameters_t *handshake;
+
+  handshake = dtls_handshake_malloc();
+  if (!handshake) {
+    dtls_crit("can not allocate a handshake struct\n");
+    return NULL;
+  }
+
+  memset(handshake, 0, sizeof(*handshake));
+
+  if (handshake) {
+    /* initialize the handshake hash wrt. the hard-coded DTLS version */
+    dtls_debug("DTLSv12: initialize HASH_SHA256\n");
+    /* TLS 1.2:  PRF(secret, label, seed) = P_<hash>(secret, label + seed) */
+    /* FIXME: we use the default SHA256 here, might need to support other
+              hash functions as well */
+    dtls_hash_init(&handshake->hs_state.hs_hash);
+  }
+  return handshake;
+}
+
+void dtls_handshake_free(dtls_handshake_parameters_t *handshake)
+{
+  if (!handshake)
+    return;
+
+  netq_delete_all(handshake->reorder_queue);
+  dtls_handshake_dealloc(handshake);
+}
+
+dtls_security_parameters_t *dtls_security_new()
+{
+  dtls_security_parameters_t *security;
+
+  security = dtls_security_malloc();
+  if (!security) {
+    dtls_crit("can not allocate a security struct\n");
+    return NULL;
+  }
+
+  memset(security, 0, sizeof(*security));
+
+  if (security) {
+    security->cipher = TLS_NULL_WITH_NULL_NULL;
+    security->compression = TLS_COMPRESSION_NULL;
+  }
+  return security;
+}
+
+void dtls_security_free(dtls_security_parameters_t *security)
+{
+  if (!security)
+    return;
+
+  dtls_security_dealloc(security);
+}
+
+size_t
+dtls_p_hash(dtls_hashfunc_t h,
+           const unsigned char *key, size_t keylen,
+           const unsigned char *label, size_t labellen,
+           const unsigned char *random1, size_t random1len,
+           const unsigned char *random2, size_t random2len,
+           unsigned char *buf, size_t buflen) {
+  dtls_hmac_context_t *hmac_a, *hmac_p;
+
+  unsigned char A[DTLS_HMAC_DIGEST_SIZE];
+  unsigned char tmp[DTLS_HMAC_DIGEST_SIZE];
+  size_t dlen;                 /* digest length */
+  size_t len = 0;                      /* result length */
+
+  hmac_a = dtls_hmac_new(key, keylen);
+  if (!hmac_a)
+    return 0;
+
+  /* calculate A(1) from A(0) == seed */
+  HMAC_UPDATE_SEED(hmac_a, label, labellen);
+  HMAC_UPDATE_SEED(hmac_a, random1, random1len);
+  HMAC_UPDATE_SEED(hmac_a, random2, random2len);
+
+  dlen = dtls_hmac_finalize(hmac_a, A);
+
+  hmac_p = dtls_hmac_new(key, keylen);
+  if (!hmac_p)
+    goto error;
+
+  while (len + dlen < buflen) {
+
+    /* FIXME: rewrite loop to avoid superflous call to dtls_hmac_init() */
+    dtls_hmac_init(hmac_p, key, keylen);
+    dtls_hmac_update(hmac_p, A, dlen);
+
+    HMAC_UPDATE_SEED(hmac_p, label, labellen);
+    HMAC_UPDATE_SEED(hmac_p, random1, random1len);
+    HMAC_UPDATE_SEED(hmac_p, random2, random2len);
+
+    len += dtls_hmac_finalize(hmac_p, tmp);
+    memcpy(buf, tmp, dlen);
+    buf += dlen;
+
+    /* calculate A(i+1) */
+    dtls_hmac_init(hmac_a, key, keylen);
+    dtls_hmac_update(hmac_a, A, dlen);
+    dtls_hmac_finalize(hmac_a, A);
+  }
+
+  dtls_hmac_init(hmac_p, key, keylen);
+  dtls_hmac_update(hmac_p, A, dlen);
+
+  HMAC_UPDATE_SEED(hmac_p, label, labellen);
+  HMAC_UPDATE_SEED(hmac_p, random1, random1len);
+  HMAC_UPDATE_SEED(hmac_p, random2, random2len);
+
+  dtls_hmac_finalize(hmac_p, tmp);
+  memcpy(buf, tmp, buflen - len);
+
+ error:
+  dtls_hmac_free(hmac_a);
+  dtls_hmac_free(hmac_p);
+
+  return buflen;
+}
+
+size_t
+dtls_prf(const unsigned char *key, size_t keylen,
+        const unsigned char *label, size_t labellen,
+        const unsigned char *random1, size_t random1len,
+        const unsigned char *random2, size_t random2len,
+        unsigned char *buf, size_t buflen) {
+
+  /* Clear the result buffer */
+  memset(buf, 0, buflen);
+  return dtls_p_hash(HASH_SHA256,
+                    key, keylen,
+                    label, labellen,
+                    random1, random1len,
+                    random2, random2len,
+                    buf, buflen);
+}
+
+void
+dtls_mac(dtls_hmac_context_t *hmac_ctx,
+        const unsigned char *record,
+        const unsigned char *packet, size_t length,
+        unsigned char *buf) {
+  uint16 L;
+  dtls_int_to_uint16(L, length);
+
+  assert(hmac_ctx);
+  dtls_hmac_update(hmac_ctx, record +3, sizeof(uint16) + sizeof(uint48));
+  dtls_hmac_update(hmac_ctx, record, sizeof(uint8) + sizeof(uint16));
+  dtls_hmac_update(hmac_ctx, L, sizeof(uint16));
+  dtls_hmac_update(hmac_ctx, packet, length);
+
+  dtls_hmac_finalize(hmac_ctx, buf);
+}
+
+static size_t
+dtls_ccm_encrypt(aes128_ccm_t *ccm_ctx, const unsigned char *src, size_t srclen,
+                unsigned char *buf,
+                unsigned char *nounce,
+                const unsigned char *aad, size_t la) {
+  long int len;
+
+  assert(ccm_ctx);
+
+  len = dtls_ccm_encrypt_message(&ccm_ctx->ctx, 8 /* M */,
+                                max(2, 15 - DTLS_CCM_NONCE_SIZE),
+                                nounce,
+                                buf, srclen,
+                                aad, la);
+  return len;
+}
+
+static size_t
+dtls_ccm_decrypt(aes128_ccm_t *ccm_ctx, const unsigned char *src,
+                size_t srclen, unsigned char *buf,
+                unsigned char *nounce,
+                const unsigned char *aad, size_t la) {
+  long int len;
+
+  assert(ccm_ctx);
+
+  len = dtls_ccm_decrypt_message(&ccm_ctx->ctx, 8 /* M */,
+                                max(2, 15 - DTLS_CCM_NONCE_SIZE),
+                                nounce,
+                                buf, srclen,
+                                aad, la);
+  return len;
+}
+
+#ifdef DTLS_PSK
+int
+dtls_psk_pre_master_secret(unsigned char *key, size_t keylen,
+                          unsigned char *result, size_t result_len) {
+  unsigned char *p = result;
+
+  if (result_len < (2 * (sizeof(uint16) + keylen))) {
+    return -1;
+  }
+
+  dtls_int_to_uint16(p, keylen);
+  p += sizeof(uint16);
+
+  memset(p, 0, keylen);
+  p += keylen;
+
+  memcpy(p, result, sizeof(uint16));
+  p += sizeof(uint16);
+
+  memcpy(p, key, keylen);
+
+  return 2 * (sizeof(uint16) + keylen);
+}
+#endif /* DTLS_PSK */
+
+#ifdef DTLS_ECC
+
+int dtls_ec_key_from_uint32_asn1(const uint32_t *key, size_t key_size,
+                                unsigned char *buf) {
+  int i;
+  unsigned char *buf_orig = buf;
+  int first = 1;
+
+  for (i = (key_size / sizeof(uint32_t)) - 1; i >= 0 ; i--) {
+    if (key[i] == 0)
+      continue;
+    /* the first bit has to be set to zero, to indicate a poritive integer */
+    if (first && key[i] & 0x80000000) {
+      *buf = 0;
+      buf++;
+      dtls_int_to_uint32(buf, key[i]);
+      buf += 4;
+    } else if (first && !(key[i] & 0xFF800000)) {
+      buf[0] = (key[i] >> 16) & 0xff;
+      buf[1] = (key[i] >> 8) & 0xff;
+      buf[2] = key[i] & 0xff;
+      buf += 3;
+    } else if (first && !(key[i] & 0xFFFF8000)) {
+      buf[0] = (key[i] >> 8) & 0xff;
+      buf[1] = key[i] & 0xff;
+      buf += 2;
+    } else if (first && !(key[i] & 0xFFFFFF80)) {
+      buf[0] = key[i] & 0xff;
+      buf += 1;
+    } else {
+      dtls_int_to_uint32(buf, key[i]);
+      buf += 4;
+    }
+    first = 0;
+  }
+  return buf - buf_orig;
+}
+
+int dtls_ecdh_pre_master_secret(unsigned char *priv_key,
+                                  unsigned char *pub_key_x,
+                                   unsigned char *pub_key_y,
+                                   size_t key_size,
+                                   unsigned char *result,
+                                   size_t result_len) {
+
+  uint8_t publicKey[64];
+  uint8_t privateKey[32];
+
+  if (result_len < key_size) {
+    return -1;
+  }
+
+
+  memcpy(publicKey, pub_key_x, 32);
+  memcpy(publicKey + 32, pub_key_y, 32);
+  memcpy(privateKey, priv_key, 32);
+  uECC_shared_secret(publicKey, privateKey, result);
+
+  return key_size;
+}
+
+void
+dtls_ecdsa_generate_key(unsigned char *priv_key,
+                       unsigned char *pub_key_x,
+                       unsigned char *pub_key_y,
+                       size_t key_size) {
+
+  uint8_t publicKey[64];
+  uint8_t privateKey[32];
+
+  uECC_make_key(publicKey, privateKey);
+  memcpy(pub_key_x, publicKey, 32);
+  memcpy(pub_key_y, publicKey + 32, 32);
+  memcpy(priv_key, privateKey, 32);
+
+}
+
+/* rfc4492#section-5.4 */
+void
+dtls_ecdsa_create_sig_hash(const unsigned char *priv_key, size_t key_size,
+                          const unsigned char *sign_hash, size_t sign_hash_size,
+                          uint32_t point_r[9], uint32_t point_s[9]) {
+  int ret;
+
+  uint8_t privateKey[32];
+  uint8_t hashValue[32];
+  uint8_t sign[64];
+
+
+  uECC_sign(privateKey, hashValue, sign);
+  memcpy(point_r, sign, 32);
+  memcpy(point_s, sign + 32, 32);
+}
+
+void
+dtls_ecdsa_create_sig(const unsigned char *priv_key, size_t key_size,
+                     const unsigned char *client_random, size_t client_random_size,
+                     const unsigned char *server_random, size_t server_random_size,
+                     const unsigned char *keyx_params, size_t keyx_params_size,
+                     uint32_t point_r[9], uint32_t point_s[9]) {
+  dtls_hash_ctx data;
+  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
+
+  dtls_hash_init(&data);
+  dtls_hash_update(&data, client_random, client_random_size);
+  dtls_hash_update(&data, server_random, server_random_size);
+  dtls_hash_update(&data, keyx_params, keyx_params_size);
+  dtls_hash_finalize(sha256hash, &data);
+
+  dtls_ecdsa_create_sig_hash(priv_key, key_size, sha256hash,
+                            sizeof(sha256hash), point_r, point_s);
+}
+
+/* rfc4492#section-5.4 */
+int
+dtls_ecdsa_verify_sig_hash(const unsigned char *pub_key_x,
+                          const unsigned char *pub_key_y, size_t key_size,
+                          const unsigned char *sign_hash, size_t sign_hash_size,
+                          unsigned char *result_r, unsigned char *result_s) {
+
+  uint8_t publicKey[64];
+  uint8_t hashValue[32];
+  uint8_t sign[64];
+
+  memcpy(publicKey, pub_key_x, 32);
+  memcpy(publicKey + 32, pub_key_y, 32);
+  return uECC_verify(publicKey, hashValue, sign);
+}
+
+int
+dtls_ecdsa_verify_sig(const unsigned char *pub_key_x,
+                     const unsigned char *pub_key_y, size_t key_size,
+                     const unsigned char *client_random, size_t client_random_size,
+                     const unsigned char *server_random, size_t server_random_size,
+                     const unsigned char *keyx_params, size_t keyx_params_size,
+                     unsigned char *result_r, unsigned char *result_s) {
+  dtls_hash_ctx data;
+  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
+
+  dtls_hash_init(&data);
+  dtls_hash_update(&data, client_random, client_random_size);
+  dtls_hash_update(&data, server_random, server_random_size);
+  dtls_hash_update(&data, keyx_params, keyx_params_size);
+  dtls_hash_finalize(sha256hash, &data);
+
+  return dtls_ecdsa_verify_sig_hash(pub_key_x, pub_key_y, key_size, sha256hash,
+                                   sizeof(sha256hash), result_r, result_s);
+}
+#endif /* DTLS_ECC */
+
+int
+dtls_encrypt(const unsigned char *src, size_t length,
+            unsigned char *buf,
+            unsigned char *nounce,
+            unsigned char *key, size_t keylen,
+            const unsigned char *aad, size_t la)
+{
+  int ret;
+  struct dtls_cipher_context_t *ctx = dtls_cipher_context_get();
+
+  ret = rijndael_set_key_enc_only(&ctx->data.ctx, key, 8 * keylen);
+  if (ret < 0) {
+    /* cleanup everything in case the key has the wrong size */
+    dtls_warn("cannot set rijndael key\n");
+    goto error;
+  }
+
+  if (src != buf)
+    memmove(buf, src, length);
+  ret = dtls_ccm_encrypt(&ctx->data, src, length, buf, nounce, aad, la);
+
+error:
+  dtls_cipher_context_release();
+  return ret;
+}
+
+int
+dtls_decrypt(const unsigned char *src, size_t length,
+            unsigned char *buf,
+            unsigned char *nounce,
+            unsigned char *key, size_t keylen,
+            const unsigned char *aad, size_t la)
+{
+  int ret;
+  struct dtls_cipher_context_t *ctx = dtls_cipher_context_get();
+
+  ret = rijndael_set_key_enc_only(&ctx->data.ctx, key, 8 * keylen);
+  if (ret < 0) {
+    /* cleanup everything in case the key has the wrong size */
+    dtls_warn("cannot set rijndael key\n");
+    goto error;
+  }
+
+  if (src != buf)
+    memmove(buf, src, length);
+  ret = dtls_ccm_decrypt(&ctx->data, src, length, buf, nounce, aad, la);
+
+error:
+  dtls_cipher_context_release();
+  return ret;
+}
+
diff --git a/extlibs/tinydtls/crypto.h b/extlibs/tinydtls/crypto.h
new file mode 100644 (file)
index 0000000..972a174
--- /dev/null
@@ -0,0 +1,359 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef _DTLS_CRYPTO_H_
+#define _DTLS_CRYPTO_H_
+
+#include <stdlib.h>            /* for rand() and srand() */
+#include <stdint.h>
+
+#include "t_list.h"
+
+#include "aes/rijndael.h"
+
+#include "global.h"
+#include "state.h"
+#include "numeric.h"
+#include "hmac.h"
+#include "ccm.h"
+
+/* TLS_PSK_WITH_AES_128_CCM_8 */
+#define DTLS_MAC_KEY_LENGTH    0
+#define DTLS_KEY_LENGTH        16 /* AES-128 */
+#define DTLS_BLK_LENGTH        16 /* AES-128 */
+#define DTLS_MAC_LENGTH        DTLS_HMAC_DIGEST_SIZE
+#define DTLS_IV_LENGTH         4  /* length of nonce_explicit */
+
+/** 
+ * Maximum size of the generated keyblock. Note that MAX_KEYBLOCK_LENGTH must 
+ * be large enough to hold the pre_master_secret, i.e. twice the length of the 
+ * pre-shared key + 1.
+ */
+#define MAX_KEYBLOCK_LENGTH  \
+  (2 * DTLS_MAC_KEY_LENGTH + 2 * DTLS_KEY_LENGTH + 2 * DTLS_IV_LENGTH)
+
+/** Length of DTLS master_secret */
+#define DTLS_MASTER_SECRET_LENGTH 48
+#define DTLS_RANDOM_LENGTH 32
+
+typedef enum { AES128=0 
+} dtls_crypto_alg;
+
+typedef enum {
+  DTLS_ECDH_CURVE_SECP256R1
+} dtls_ecdh_curve;
+
+/** Crypto context for TLS_PSK_WITH_AES_128_CCM_8 cipher suite. */
+typedef struct {
+  rijndael_ctx ctx;                   /**< AES-128 encryption context */
+} aes128_ccm_t;
+
+typedef struct dtls_cipher_context_t {
+  /** numeric identifier of this cipher suite in host byte order. */
+  aes128_ccm_t data;           /**< The crypto context */
+} dtls_cipher_context_t;
+
+typedef struct {
+  uint8 own_eph_priv[32];
+  uint8 other_eph_pub_x[32];
+  uint8 other_eph_pub_y[32];
+  uint8 other_pub_x[32];
+  uint8 other_pub_y[32];
+} dtls_handshake_parameters_ecdsa_t;
+
+/* This is the maximal supported length of the psk client identity and psk
+ * server identity hint */
+#define DTLS_PSK_MAX_CLIENT_IDENTITY_LEN   32
+
+/* This is the maximal supported length of the pre-shared key. */
+#define DTLS_PSK_MAX_KEY_LEN 32
+
+typedef struct {
+  uint16_t id_length;
+  unsigned char identity[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
+} dtls_handshake_parameters_psk_t;
+
+typedef struct {
+  dtls_compression_t compression;      /**< compression method */
+
+  dtls_cipher_t cipher;                /**< cipher type */
+  uint16_t epoch;           /**< counter for cipher state changes*/
+  uint64_t rseq;            /**< sequence number of last record sent */
+
+  /** 
+   * The key block generated from PRF applied to client and server
+   * random bytes. The actual size is given by the selected cipher and
+   * can be calculated using dtls_kb_size(). Use \c dtls_kb_ macros to
+   * access the components of the key block.
+   */
+  uint8 key_block[MAX_KEYBLOCK_LENGTH];
+} dtls_security_parameters_t;
+
+typedef struct {
+  union {
+    struct random_t {
+      uint8 client[DTLS_RANDOM_LENGTH];        /**< client random gmt and bytes */
+      uint8 server[DTLS_RANDOM_LENGTH];        /**< server random gmt and bytes */
+    } random;
+    /** the session's master secret */
+    uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
+  } tmp;
+  LIST_STRUCT(reorder_queue);  /**< the packets to reorder */
+  dtls_hs_state_t hs_state;  /**< handshake protocol status */
+
+  dtls_compression_t compression;              /**< compression method */
+  dtls_cipher_t cipher;                /**< cipher type */
+  unsigned int do_client_auth:1;
+  union {
+#ifdef DTLS_ECC
+    dtls_handshake_parameters_ecdsa_t ecdsa;
+#endif /* DTLS_ECC */
+#ifdef DTLS_PSK
+    dtls_handshake_parameters_psk_t psk;
+#endif /* DTLS_PSK */
+  } keyx;
+} dtls_handshake_parameters_t;
+
+/* The following macros provide access to the components of the
+ * key_block in the security parameters. */
+
+#define dtls_kb_client_mac_secret(Param, Role) ((Param)->key_block)
+#define dtls_kb_server_mac_secret(Param, Role)                         \
+  (dtls_kb_client_mac_secret(Param, Role) + DTLS_MAC_KEY_LENGTH)
+#define dtls_kb_remote_mac_secret(Param, Role)                         \
+  ((Role) == DTLS_SERVER                                               \
+   ? dtls_kb_client_mac_secret(Param, Role)                            \
+   : dtls_kb_server_mac_secret(Param, Role))
+#define dtls_kb_local_mac_secret(Param, Role)                          \
+  ((Role) == DTLS_CLIENT                                               \
+   ? dtls_kb_client_mac_secret(Param, Role)                            \
+   : dtls_kb_server_mac_secret(Param, Role))
+#define dtls_kb_mac_secret_size(Param, Role) DTLS_MAC_KEY_LENGTH
+#define dtls_kb_client_write_key(Param, Role)                          \
+  (dtls_kb_server_mac_secret(Param, Role) + DTLS_MAC_KEY_LENGTH)
+#define dtls_kb_server_write_key(Param, Role)                          \
+  (dtls_kb_client_write_key(Param, Role) + DTLS_KEY_LENGTH)
+#define dtls_kb_remote_write_key(Param, Role)                          \
+  ((Role) == DTLS_SERVER                                               \
+   ? dtls_kb_client_write_key(Param, Role)                             \
+   : dtls_kb_server_write_key(Param, Role))
+#define dtls_kb_local_write_key(Param, Role)                           \
+  ((Role) == DTLS_CLIENT                                               \
+   ? dtls_kb_client_write_key(Param, Role)                             \
+   : dtls_kb_server_write_key(Param, Role))
+#define dtls_kb_key_size(Param, Role) DTLS_KEY_LENGTH
+#define dtls_kb_client_iv(Param, Role)                                 \
+  (dtls_kb_server_write_key(Param, Role) + DTLS_KEY_LENGTH)
+#define dtls_kb_server_iv(Param, Role)                                 \
+  (dtls_kb_client_iv(Param, Role) + DTLS_IV_LENGTH)
+#define dtls_kb_remote_iv(Param, Role)                                 \
+  ((Role) == DTLS_SERVER                                               \
+   ? dtls_kb_client_iv(Param, Role)                                    \
+   : dtls_kb_server_iv(Param, Role))
+#define dtls_kb_local_iv(Param, Role)                                  \
+  ((Role) == DTLS_CLIENT                                               \
+   ? dtls_kb_client_iv(Param, Role)                                    \
+   : dtls_kb_server_iv(Param, Role))
+#define dtls_kb_iv_size(Param, Role) DTLS_IV_LENGTH
+
+#define dtls_kb_size(Param, Role)                                      \
+  (2 * (dtls_kb_mac_secret_size(Param, Role) +                         \
+       dtls_kb_key_size(Param, Role) + dtls_kb_iv_size(Param, Role)))
+
+/* just for consistency */
+#define dtls_kb_digest_size(Param, Role) DTLS_MAC_LENGTH
+
+/** 
+ * Expands the secret and key to a block of DTLS_HMAC_MAX 
+ * size according to the algorithm specified in section 5 of
+ * RFC 4346.
+ *
+ * \param h       Identifier of the hash function to use.
+ * \param key     The secret.
+ * \param keylen  Length of \p key.
+ * \param seed    The seed. 
+ * \param seedlen Length of \p seed.
+ * \param buf     Output buffer where the result is XORed into
+ *                The buffe must be capable to hold at least
+ *                \p buflen bytes.
+ * \return The actual number of bytes written to \p buf or 0
+ * on error.
+ */
+size_t dtls_p_hash(dtls_hashfunc_t h, 
+                  const unsigned char *key, size_t keylen,
+                  const unsigned char *label, size_t labellen,
+                  const unsigned char *random1, size_t random1len,
+                  const unsigned char *random2, size_t random2len,
+                  unsigned char *buf, size_t buflen);
+
+/**
+ * This function implements the TLS PRF for DTLS_VERSION. For version
+ * 1.0, the PRF is P_MD5 ^ P_SHA1 while version 1.2 uses
+ * P_SHA256. Currently, the actual PRF is selected at compile time.
+ */
+size_t dtls_prf(const unsigned char *key, size_t keylen,
+               const unsigned char *label, size_t labellen,
+               const unsigned char *random1, size_t random1len,
+               const unsigned char *random2, size_t random2len,
+               unsigned char *buf, size_t buflen);
+
+/**
+ * Calculates MAC for record + cleartext packet and places the result
+ * in \p buf. The given \p hmac_ctx must be initialized with the HMAC
+ * function to use and the proper secret. As the DTLS mac calculation
+ * requires data from the record header, \p record must point to a
+ * buffer of at least \c sizeof(dtls_record_header_t) bytes. Usually,
+ * the remaining packet will be encrypted, therefore, the cleartext
+ * is passed separately in \p packet.
+ * 
+ * \param hmac_ctx  The HMAC context to use for MAC calculation.
+ * \param record    The record header.
+ * \param packet    Cleartext payload to apply the MAC to.
+ * \param length    Size of \p packet.
+ * \param buf       A result buffer that is large enough to hold
+ *                  the generated digest.
+ */
+void dtls_mac(dtls_hmac_context_t *hmac_ctx, 
+             const unsigned char *record,
+             const unsigned char *packet, size_t length,
+             unsigned char *buf);
+
+/** 
+ * Encrypts the specified \p src of given \p length, writing the
+ * result to \p buf. The cipher implementation may add more data to
+ * the result buffer such as an initialization vector or padding
+ * (e.g. for block cipers in CBC mode). The caller therefore must
+ * ensure that \p buf provides sufficient storage to hold the result.
+ * Usually this means ( 2 + \p length / blocksize ) * blocksize.  The
+ * function returns a value less than zero on error or otherwise the
+ * number of bytes written.
+ *
+ * \param ctx    The cipher context to use.
+ * \param src    The data to encrypt.
+ * \param length The actual size of of \p src.
+ * \param buf    The result buffer. \p src and \p buf must not 
+ *               overlap.
+ * \param aad    additional data for AEAD ciphers
+ * \param aad_length actual size of @p aad
+ * \return The number of encrypted bytes on success, less than zero
+ *         otherwise. 
+ */
+int dtls_encrypt(const unsigned char *src, size_t length,
+                unsigned char *buf,
+                unsigned char *nounce,
+                unsigned char *key, size_t keylen,
+                const unsigned char *aad, size_t aad_length);
+
+/** 
+ * Decrypts the given buffer \p src of given \p length, writing the
+ * result to \p buf. The function returns \c -1 in case of an error,
+ * or the number of bytes written. Note that for block ciphers, \p
+ * length must be a multiple of the cipher's block size. A return
+ * value between \c 0 and the actual length indicates that only \c n-1
+ * block have been processed. Unlike dtls_encrypt(), the source
+ * and destination of dtls_decrypt() may overlap. 
+ * 
+ * \param ctx     The cipher context to use.
+ * \param src     The buffer to decrypt.
+ * \param length  The length of the input buffer. 
+ * \param buf     The result buffer.
+ * \param aad     additional authentication data for AEAD ciphers
+ * \param aad_length actual size of @p aad
+ * \return Less than zero on error, the number of decrypted bytes 
+ *         otherwise.
+ */
+int dtls_decrypt(const unsigned char *src, size_t length,
+                unsigned char *buf,
+                unsigned char *nounce,
+                unsigned char *key, size_t keylen,
+                const unsigned char *a_data, size_t a_data_length);
+
+/* helper functions */
+
+/** 
+ * Generates pre_master_sercet from given PSK and fills the result
+ * according to the "plain PSK" case in section 2 of RFC 4279.
+ * Diffie-Hellman and RSA key exchange are currently not supported.
+ *
+ * @param key    The shared key.
+ * @param keylen Length of @p key in bytes.
+ * @param result The derived pre master secret.
+ * @return The actual length of @p result.
+ */
+int dtls_psk_pre_master_secret(unsigned char *key, size_t keylen,
+                              unsigned char *result, size_t result_len);
+
+#define DTLS_EC_KEY_SIZE 32
+
+int dtls_ecdh_pre_master_secret(unsigned char *priv_key,
+                               unsigned char *pub_key_x,
+                                unsigned char *pub_key_y,
+                                size_t key_size,
+                                unsigned char *result,
+                                size_t result_len);
+
+void dtls_ecdsa_generate_key(unsigned char *priv_key,
+                            unsigned char *pub_key_x,
+                            unsigned char *pub_key_y,
+                            size_t key_size);
+
+void dtls_ecdsa_create_sig_hash(const unsigned char *priv_key, size_t key_size,
+                               const unsigned char *sign_hash, size_t sign_hash_size,
+                               uint32_t point_r[9], uint32_t point_s[9]);
+
+void dtls_ecdsa_create_sig(const unsigned char *priv_key, size_t key_size,
+                          const unsigned char *client_random, size_t client_random_size,
+                          const unsigned char *server_random, size_t server_random_size,
+                          const unsigned char *keyx_params, size_t keyx_params_size,
+                          uint32_t point_r[9], uint32_t point_s[9]);
+
+int dtls_ecdsa_verify_sig_hash(const unsigned char *pub_key_x,
+                              const unsigned char *pub_key_y, size_t key_size,
+                              const unsigned char *sign_hash, size_t sign_hash_size,
+                              unsigned char *result_r, unsigned char *result_s);
+
+int dtls_ecdsa_verify_sig(const unsigned char *pub_key_x,
+                         const unsigned char *pub_key_y, size_t key_size,
+                         const unsigned char *client_random, size_t client_random_size,
+                         const unsigned char *server_random, size_t server_random_size,
+                         const unsigned char *keyx_params, size_t keyx_params_size,
+                         unsigned char *result_r, unsigned char *result_s);
+
+int dtls_ec_key_from_uint32_asn1(const uint32_t *key, size_t key_size,
+                                unsigned char *buf);
+
+
+dtls_handshake_parameters_t *dtls_handshake_new();
+
+void dtls_handshake_free(dtls_handshake_parameters_t *handshake);
+
+dtls_security_parameters_t *dtls_security_new();
+
+void dtls_security_free(dtls_security_parameters_t *security);
+void crypto_init();
+
+#endif /* _DTLS_CRYPTO_H_ */
+
diff --git a/extlibs/tinydtls/debug.c b/extlibs/tinydtls/debug.c
new file mode 100644 (file)
index 0000000..49a93eb
--- /dev/null
@@ -0,0 +1,373 @@
+/* debug.c -- debug utilities
+ *
+ * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "tinydtls.h"
+#include "dtls_config.h"
+
+#if defined(HAVE_ASSERT_H) && !defined(assert)
+#include <assert.h>
+#endif
+
+#include <stdarg.h>
+#include <stdio.h>
+
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
+
+#include "global.h"
+#include "debug.h"
+
+static int maxlog = DTLS_LOG_WARN;     /* default maximum log level */
+
+const char *dtls_package_name() {
+  return PACKAGE_NAME;
+}
+
+const char *dtls_package_version() {
+  return PACKAGE_VERSION;
+}
+
+log_t 
+dtls_get_log_level() {
+  return maxlog;
+}
+
+void
+dtls_set_log_level(log_t level) {
+  maxlog = level;
+}
+
+/* this array has the same order as the type log_t */
+static char *loglevels[] = {
+  "EMRG", "ALRT", "CRIT", "WARN", "NOTE", "INFO", "DEBG" 
+};
+
+#ifdef HAVE_TIME_H
+
+static inline size_t
+print_timestamp(char *s, size_t len, time_t t) {
+  struct tm *tmp;
+  tmp = localtime(&t);
+  return strftime(s, len, "%b %d %H:%M:%S", tmp);
+}
+
+#else /* alternative implementation: just print the timestamp */
+
+static inline size_t
+print_timestamp(char *s, size_t len, clock_time_t t) {
+#ifdef HAVE_SNPRINTF
+  return snprintf(s, len, "%u.%03u", 
+                 (unsigned int)(t / CLOCK_SECOND), 
+                 (unsigned int)(t % CLOCK_SECOND));
+#else /* HAVE_SNPRINTF */
+  /* @todo do manual conversion of timestamp */
+  return 0;
+#endif /* HAVE_SNPRINTF */
+}
+
+#endif /* HAVE_TIME_H */
+
+/** 
+ * A length-safe strlen() fake. 
+ * 
+ * @param s      The string to count characters != 0.
+ * @param maxlen The maximum length of @p s.
+ * 
+ * @return The length of @p s.
+ */
+static inline size_t
+dtls_strnlen(const char *s, size_t maxlen) {
+  size_t n = 0;
+  while(*s++ && n < maxlen)
+    ++n;
+  return n;
+}
+
+#ifndef min
+#define min(a,b) ((a) < (b) ? (a) : (b))
+#endif
+
+static size_t
+dsrv_print_addr(const session_t *addr, char *buf, size_t len) {
+#ifdef HAVE_ARPA_INET_H
+  const void *addrptr = NULL;
+  in_port_t port;
+  char *p = buf;
+
+  switch (addr->addr.sa.sa_family) {
+  case AF_INET: 
+    if (len < INET_ADDRSTRLEN)
+      return 0;
+  
+    addrptr = &addr->addr.sin.sin_addr;
+    port = ntohs(addr->addr.sin.sin_port);
+    break;
+  case AF_INET6:
+    if (len < INET6_ADDRSTRLEN + 2)
+      return 0;
+
+    *p++ = '[';
+
+    addrptr = &addr->addr.sin6.sin6_addr;
+    port = ntohs(addr->addr.sin6.sin6_port);
+
+    break;
+  default:
+    memcpy(buf, "(unknown address type)", min(22, len));
+    return min(22, len);
+  }
+
+  if (inet_ntop(addr->addr.sa.sa_family, addrptr, p, len) == 0) {
+    perror("dsrv_print_addr");
+    return 0;
+  }
+
+  p += dtls_strnlen(p, len);
+
+  if (addr->addr.sa.sa_family == AF_INET6) {
+    if (p < buf + len) {
+      *p++ = ']';
+    } else 
+      return 0;
+  }
+
+  p += snprintf(p, buf + len - p + 1, ":%d", port);
+
+  return p - buf;
+#else /* HAVE_ARPA_INET_H */
+# if WITH_CONTIKI
+  char *p = buf;
+#  ifdef UIP_CONF_IPV6
+  uint8_t i;
+  const char hex[] = "0123456789ABCDEF";
+
+  if (len < 41)
+    return 0;
+
+  *p++ = '[';
+
+  for (i=0; i < 16; i += 2) {
+    if (i) {
+      *p++ = ':';
+    }
+    *p++ = hex[(addr->addr.u8[i] & 0xf0) >> 4];
+    *p++ = hex[(addr->addr.u8[i] & 0x0f)];
+    *p++ = hex[(addr->addr.u8[i+1] & 0xf0) >> 4];
+    *p++ = hex[(addr->addr.u8[i+1] & 0x0f)];
+  }
+  *p++ = ']';
+#  else /* UIP_CONF_IPV6 */
+#   warning "IPv4 network addresses will not be included in debug output"
+
+  if (len < 21)
+    return 0;
+#  endif /* UIP_CONF_IPV6 */
+  if (buf + len - p < 6)
+    return 0;
+
+  p += sprintf(p, ":%d", uip_htons(addr->port));
+
+  return p - buf;
+# else /* WITH_CONTIKI */
+  /* TODO: output addresses manually */
+#   warning "inet_ntop() not available, network addresses will not be included in debug output"
+# endif /* WITH_CONTIKI */
+  return 0;
+#endif
+}
+
+#ifndef WITH_CONTIKI
+void 
+dsrv_log(log_t level, char *format, ...) {
+  static char timebuf[32];
+  va_list ap;
+  FILE *log_fd;
+
+  if (maxlog < level)
+    return;
+
+  log_fd = level <= DTLS_LOG_CRIT ? stderr : stdout;
+
+  if (print_timestamp(timebuf,sizeof(timebuf), time(NULL)))
+    fprintf(log_fd, "%s ", timebuf);
+
+  if (level <= DTLS_LOG_DEBUG) 
+    fprintf(log_fd, "%s ", loglevels[level]);
+
+  va_start(ap, format);
+  vfprintf(log_fd, format, ap);
+  va_end(ap);
+  fflush(log_fd);
+}
+#elif defined (HAVE_VPRINTF) /* WITH_CONTIKI */
+void 
+dsrv_log(log_t level, char *format, ...) {
+  static char timebuf[32];
+  va_list ap;
+
+  if (maxlog < level)
+    return;
+
+  if (print_timestamp(timebuf,sizeof(timebuf), clock_time()))
+    PRINTF("%s ", timebuf);
+
+  if (level <= DTLS_LOG_DEBUG) 
+    PRINTF("%s ", loglevels[level]);
+
+  va_start(ap, format);
+  vprintf(format, ap);
+  va_end(ap);
+}
+#endif /* WITH_CONTIKI */
+
+#ifndef NDEBUG
+/** dumps packets in usual hexdump format */
+void hexdump(const unsigned char *packet, int length) {
+  int n = 0;
+
+  while (length--) { 
+    if (n % 16 == 0)
+      printf("%08X ",n);
+
+    printf("%02X ", *packet++);
+    
+    n++;
+    if (n % 8 == 0) {
+      if (n % 16 == 0)
+       printf("\n");
+      else
+       printf(" ");
+    }
+  }
+}
+
+/** dump as narrow string of hex digits */
+void dump(unsigned char *buf, size_t len) {
+  while (len--) 
+    printf("%02x", *buf++);
+}
+
+void dtls_dsrv_log_addr(log_t level, const char *name, const session_t *addr)
+{
+  char addrbuf[73];
+  int len;
+
+  len = dsrv_print_addr(addr, addrbuf, sizeof(addrbuf));
+  if (!len)
+    return;
+  dsrv_log(level, "%s: %s\n", name, addrbuf);
+}
+
+#ifndef WITH_CONTIKI
+void 
+dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend) {
+  static char timebuf[32];
+  FILE *log_fd;
+  int n = 0;
+
+  if (maxlog < level)
+    return;
+
+  log_fd = level <= DTLS_LOG_CRIT ? stderr : stdout;
+
+  if (print_timestamp(timebuf, sizeof(timebuf), time(NULL)))
+    fprintf(log_fd, "%s ", timebuf);
+
+  if (level <= DTLS_LOG_DEBUG) 
+    fprintf(log_fd, "%s ", loglevels[level]);
+
+  if (extend) {
+    fprintf(log_fd, "%s: (%zu bytes):\n", name, length);
+
+    while (length--) {
+      if (n % 16 == 0)
+       fprintf(log_fd, "%08X ", n);
+
+      fprintf(log_fd, "%02X ", *buf++);
+
+      n++;
+      if (n % 8 == 0) {
+       if (n % 16 == 0)
+         fprintf(log_fd, "\n");
+       else
+         fprintf(log_fd, " ");
+      }
+    }
+  } else {
+    fprintf(log_fd, "%s: (%zu bytes): ", name, length);
+    while (length--) 
+      fprintf(log_fd, "%02X", *buf++);
+  }
+  fprintf(log_fd, "\n");
+
+  fflush(log_fd);
+}
+#else /* WITH_CONTIKI */
+void 
+dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend) {
+  static char timebuf[32];
+  int n = 0;
+
+  if (maxlog < level)
+    return;
+
+  if (print_timestamp(timebuf,sizeof(timebuf), clock_time()))
+    PRINTF("%s ", timebuf);
+
+  if (level >= 0 && level <= DTLS_LOG_DEBUG) 
+    PRINTF("%s ", loglevels[level]);
+
+  if (extend) {
+    PRINTF("%s: (%zu bytes):\n", name, length);
+
+    while (length--) {
+      if (n % 16 == 0)
+       PRINTF("%08X ", n);
+
+      PRINTF("%02X ", *buf++);
+
+      n++;
+      if (n % 8 == 0) {
+       if (n % 16 == 0)
+         PRINTF("\n");
+       else
+         PRINTF(" ");
+      }
+    }
+  } else {
+    PRINTF("%s: (%zu bytes): ", name, length);
+    while (length--) 
+      PRINTF("%02X", *buf++);
+  }
+  PRINTF("\n");
+}
+#endif /* WITH_CONTIKI */
+
+#endif /* NDEBUG */
diff --git a/extlibs/tinydtls/debug.h b/extlibs/tinydtls/debug.h
new file mode 100644 (file)
index 0000000..95286f8
--- /dev/null
@@ -0,0 +1,143 @@
+/* debug.h -- debug utilities
+ *
+ * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef _DTLS_DEBUG_H_
+#define _DTLS_DEBUG_H_
+
+#include <stdlib.h>
+
+#include "dtls_config.h"
+#include "global.h"
+#include "session.h"
+
+#ifdef WITH_CONTIKI
+# ifndef DEBUG
+#  define DEBUG DEBUG_PRINT
+# endif /* DEBUG */
+#include "net/ip/uip-debug.h"
+
+#ifdef CONTIKI_TARGET_MBXXX
+extern char __Stack_Init, _estack;
+
+static inline void check_stack() {
+  const char *p = &__Stack_Init;
+  while (p < &_estack && *p == 0x38) {
+    p++;
+  }
+
+  PRINTF("Stack: %d bytes used (%d free)\n", &_estack - p, p - &__Stack_Init);
+}
+#else /* CONTIKI_TARGET_MBXXX */
+static inline void check_stack() {
+}
+#endif /* CONTIKI_TARGET_MBXXX */
+#else /* WITH_CONTKI */
+#define PRINTF(...)
+
+static inline void check_stack() {
+}
+#endif
+
+struct __session_t;
+
+/** Pre-defined log levels akin to what is used in \b syslog. */
+typedef enum { DTLS_LOG_EMERG=0, DTLS_LOG_ALERT, DTLS_LOG_CRIT, DTLS_LOG_WARN, 
+       DTLS_LOG_NOTICE, DTLS_LOG_INFO, DTLS_LOG_DEBUG
+} log_t;
+
+/** Returns a zero-terminated string with the name of this library. */
+const char *dtls_package_name();
+
+/** Returns a zero-terminated string with the library version. */
+const char *dtls_package_version();
+
+#ifndef NDEBUG
+/** Returns the current log level. */
+log_t dtls_get_log_level();
+
+/** Sets the log level to the specified value. */
+void dtls_set_log_level(log_t level);
+
+/** 
+ * Writes the given text to \c stdout. The text is output only when \p
+ * level is below or equal to the log level that set by
+ * set_log_level(). */
+#ifdef HAVE_VPRINTF
+void dsrv_log(log_t level, char *format, ...);
+#else
+#define dsrv_log(level, format, ...) PRINTF(format, ##__VA_ARGS__)
+#endif
+
+/** dumps packets in usual hexdump format */
+void hexdump(const unsigned char *packet, int length);
+
+/** dump as narrow string of hex digits */
+void dump(unsigned char *buf, size_t len);
+
+void dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend);
+
+void dtls_dsrv_log_addr(log_t level, const char *name, const session_t *addr);
+
+#else /* NDEBUG */
+
+static inline log_t dtls_get_log_level()
+{
+  return DTLS_LOG_EMERG;
+}
+
+static inline void dtls_set_log_level(log_t level)
+{}
+
+static inline void dsrv_log(log_t level, char *format, ...)
+{}
+
+static inline void hexdump(const unsigned char *packet, int length)
+{}
+
+static inline void dump(unsigned char *buf, size_t len)
+{}
+
+static inline void
+dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend)
+{}
+
+static inline void
+dtls_dsrv_log_addr(log_t level, const char *name, const struct __session_t *addr)
+{}
+
+#endif /* NDEBUG */
+
+/* A set of convenience macros for common log levels. */
+#define dtls_emerg(...) dsrv_log(DTLS_LOG_EMERG, __VA_ARGS__)
+#define dtls_alert(...) dsrv_log(DTLS_LOG_ALERT, __VA_ARGS__)
+#define dtls_crit(...) dsrv_log(DTLS_LOG_CRIT, __VA_ARGS__)
+#define dtls_warn(...) dsrv_log(DTLS_LOG_WARN, __VA_ARGS__)
+#define dtls_notice(...) dsrv_log(DTLS_LOG_NOTICE, __VA_ARGS__)
+#define dtls_info(...) dsrv_log(DTLS_LOG_INFO, __VA_ARGS__)
+#define dtls_debug(...) dsrv_log(DTLS_LOG_DEBUG, __VA_ARGS__)
+#define dtls_debug_hexdump(name, buf, length) dtls_dsrv_hexdump_log(DTLS_LOG_DEBUG, name, buf, length, 1)
+#define dtls_debug_dump(name, buf, length) dtls_dsrv_hexdump_log(DTLS_LOG_DEBUG, name, buf, length, 0)
+
+#endif /* _DTLS_DEBUG_H_ */
diff --git a/extlibs/tinydtls/doc/Doxyfile.in b/extlibs/tinydtls/doc/Doxyfile.in
new file mode 100644 (file)
index 0000000..9f7ffdf
--- /dev/null
@@ -0,0 +1,1551 @@
+# Doxyfile 1.6.3
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+#       TAG = value [value, ...]
+# For lists items can also be appended using:
+#       TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
+# by quotes) that should identify the project.
+
+PROJECT_NAME           = @PACKAGE_NAME@
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER         = @PACKAGE_VERSION@
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       =
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF       =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES        = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful is your file systems
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF      = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE               = 4
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES                =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = YES
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it parses.
+# With this tag you can assign which parser to use for a given extension.
+# Doxygen has a built-in mapping, but you can override or extend it using this tag.
+# The format is ext=language, where ext is a file extension, and language is one of
+# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP,
+# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat
+# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran),
+# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen to replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING            = YES
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penality.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will rougly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols
+
+SYMBOL_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC         = YES
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespace are hidden.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES       = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or define consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and defines in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES        = YES
+
+# If the sources in your project are distributed over multiple directories
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES       = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.
+# This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by
+# doxygen. The layout file controls the global structure of the generated output files
+# in an output format independent way. The create the layout file that represents
+# doxygen's defaults, run doxygen with the -l option. You can optionally specify a
+# file name after the option, if omitted DoxygenLayout.xml will be used as the name
+# of the layout file.
+
+LAYOUT_FILE            =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS               = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT                  = ..
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
+
+FILE_PATTERNS          =
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE              = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
+# directories that are symbolic links (a Unix filesystem feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS       =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH             =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.
+# If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.
+# Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.
+# The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
+# is applied to all files.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER         = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C and C++ comments will always remain visible.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.
+# Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX     = NO
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER            =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If the tag is left blank doxygen
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# stylesheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET        =
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
+# files or namespaces will be aligned in HTML using tables. If set to
+# NO a bullet list will be used.
+
+HTML_ALIGN_MEMBERS     = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded. For this to work a browser that supports
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.
+
+GENERATE_DOCSET        = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP      = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE               =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION           =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI           = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING     =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER
+# are set, an additional index file will be generated that can be used as input for
+# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated
+# HTML documentation.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add.
+# For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+#  will be generated, which together with the HTML files, form an Eclipse help
+#  plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
+# top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it.
+
+DISABLE_INDEX          = NO
+
+# This tag can be used to set the number of enum values (range [1..20])
+# that doxygen will group on one line in the generated HTML documentation.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+
+GENERATE_TREEVIEW      = NO
+
+# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
+# and Class Hierarchy pages using a tree view instead of an ordered list.
+
+USE_INLINE_TREES       = NO
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH         = 250
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE       = 10
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, a4wide, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER           =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE        = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE      = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE    =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT             = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA             =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD                =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.
+# This is useful
+# if you want to understand what is going on.
+# On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED             = DSRV_NO_DTLS DSRV_NO_PROTOCOL_DEMUX
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all function-like macros that are alone
+# on a line, have an all uppercase name, and do not end with a semicolon. Such
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles.
+# Optionally an initial location of the external documentation
+# can be added for each tagfile. The format of a tag file without
+# this location is as follows:
+#
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths or
+# URLs. If a location is present for each tag, the installdox tool
+# does not have to be run to correct the links.
+# Note that each tag file must have a unique name
+# (where the name does NOT include the path)
+# If a tag file is not located in the directory in which doxygen
+# is run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS        = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option is superseded by the HAVE_DOT option below. This is only a
+# fallback. It is recommended to install and use dot, since it yields more
+# powerful graphs.
+
+CLASS_DIAGRAMS         = NO
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT               = NO
+
+# By default doxygen will write a font called FreeSans.ttf to the output
+# directory and reference it in all dot files that doxygen generates. This
+# font does not include all possible unicode characters however, so when you need
+# these (or just want a differently looking font) you can specify the font name
+# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
+# which can be done by putting it in a standard location or by setting the
+# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
+# containing the font.
+
+DOT_FONTNAME           = FreeSans
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the output directory to look for the
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a
+# different font using DOT_FONTNAME you can set the path where dot
+# can find it using this tag.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# the CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK               = NO
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH          = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are png, jpg, or gif
+# If left blank png will be used.
+
+DOT_IMAGE_FORMAT       = png
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS           =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = YES
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP            = YES
diff --git a/extlibs/tinydtls/doc/DoxygenLayout.xml b/extlibs/tinydtls/doc/DoxygenLayout.xml
new file mode 100644 (file)
index 0000000..1c8525c
--- /dev/null
@@ -0,0 +1,184 @@
+<doxygenlayout version="1.0">
+  <!-- Navigation index tabs for HTML output -->
+  <navindex>
+    <tab type="mainpage" visible="yes" title=""/>
+    <tab type="pages" visible="yes" title=""/>
+    <tab type="modules" visible="yes" title=""/>
+    <tab type="namespaces" visible="yes" title="">
+      <tab type="namespaces" visible="yes" title=""/>
+      <tab type="namespacemembers" visible="yes" title=""/>
+    </tab>
+    <tab type="classes" visible="yes" title="">
+      <tab type="classes" visible="yes" title=""/>
+      <tab type="classindex" visible="$ALPHABETICAL_INDEX" title=""/> 
+      <tab type="hierarchy" visible="yes" title=""/>
+      <tab type="classmembers" visible="yes" title=""/>
+    </tab>
+    <tab type="files" visible="yes" title="">
+      <tab type="files" visible="yes" title=""/>
+      <tab type="globals" visible="yes" title=""/>
+    </tab>
+    <tab type="dirs" visible="yes" title=""/>
+    <tab type="examples" visible="yes" title=""/>  
+  </navindex>
+
+  <!-- Layout definition for a class page -->
+  <class>
+    <briefdescription visible="yes"/>
+    <includes visible="$SHOW_INCLUDE_FILES"/>
+    <inheritancegraph visible="$CLASS_GRAPH"/>
+    <collaborationgraph visible="$COLLABORATION_GRAPH"/>
+    <allmemberslink visible="yes"/>
+    <memberdecl>
+      <nestedclasses visible="yes" title=""/>
+      <publictypes title=""/>
+      <publicslots title=""/>
+      <signals title=""/>
+      <publicmethods title=""/>
+      <publicstaticmethods title=""/>
+      <publicattributes title=""/>
+      <publicstaticattributes title=""/>
+      <protectedtypes title=""/>
+      <protectedslots title=""/>
+      <protectedmethods title=""/>
+      <protectedstaticmethods title=""/>
+      <protectedattributes title=""/>
+      <protectedstaticattributes title=""/>
+      <packagetypes title=""/>
+      <packagemethods title=""/>
+      <packagestaticmethods title=""/>
+      <packageattributes title=""/>
+      <packagestaticattributes title=""/>
+      <properties title=""/>
+      <events title=""/>
+      <privatetypes title=""/>
+      <privateslots title=""/>
+      <privatemethods title=""/>
+      <privatestaticmethods title=""/>
+      <privateattributes title=""/>
+      <privatestaticattributes title=""/>
+      <friends title=""/>
+      <related title="" subtitle=""/>
+      <membergroups visible="yes"/>
+    </memberdecl>
+    <detaileddescription title=""/>
+    <memberdef>
+      <typedefs title=""/>
+      <enums title=""/>
+      <constructors title=""/>
+      <functions title=""/>
+      <related title=""/>
+      <variables title=""/>
+      <properties title=""/>
+      <events title=""/>
+    </memberdef>
+    <usedfiles visible="$SHOW_USED_FILES"/>
+    <authorsection visible="yes"/>
+  </class>
+
+  <!-- Layout definition for a namespace page -->
+  <namespace>
+    <briefdescription visible="yes"/>
+    <memberdecl>
+      <nestednamespaces visible="yes" title=""/>
+      <classes visible="yes" title=""/>
+      <typedefs title=""/>
+      <enums title=""/>
+      <functions title=""/>
+      <variables title=""/>
+      <membergroups visible="yes"/>
+    </memberdecl>
+    <detaileddescription title=""/>
+    <memberdef>
+      <typedefs title=""/>
+      <enums title=""/>
+      <functions title=""/>
+      <variables title=""/>
+    </memberdef>
+    <authorsection visible="yes"/>
+  </namespace>
+
+  <!-- Layout definition for a file page -->
+  <file>
+    <briefdescription visible="yes"/>
+    <includes visible="$SHOW_INCLUDE_FILES"/>
+    <includegraph visible="$INCLUDE_GRAPH"/>
+    <includedbygraph visible="$INCLUDED_BY_GRAPH"/>
+    <sourcelink visible="yes"/>
+    <memberdecl>
+      <classes visible="yes" title=""/>
+      <namespaces visible="yes" title=""/>
+      <defines title=""/>
+      <typedefs title=""/>
+      <enums title=""/>
+      <functions title=""/>
+      <variables title=""/>
+      <membergroups visible="yes"/>
+    </memberdecl>
+    <detaileddescription title=""/>
+    <memberdef>
+      <defines title=""/>
+      <typedefs title=""/>
+      <enums title=""/>
+      <functions title=""/>
+      <variables title=""/>
+    </memberdef>
+    <authorsection/>
+  </file>
+
+  <!-- Layout definition for a group page -->
+  <group>
+    <briefdescription visible="yes"/>
+    <groupgraph visible="$GROUP_GRAPHS"/>
+    <memberdecl>
+      <classes visible="yes" title=""/>
+      <namespaces visible="yes" title=""/>
+      <dirs visible="yes" title=""/>
+      <nestedgroups visible="yes" title=""/>
+      <files visible="yes" title=""/>
+      <defines title=""/>
+      <typedefs title=""/>
+      <enums title=""/>
+      <enumvalues title=""/>
+      <functions title=""/>
+      <variables title=""/>
+      <signals title=""/>
+      <publicslots title=""/>
+      <protectedslots title=""/>
+      <privateslots title=""/>
+      <events title=""/>
+      <properties title=""/>
+      <friends title=""/>
+      <membergroups visible="yes"/>
+    </memberdecl>
+    <detaileddescription title=""/>
+    <memberdef>
+      <pagedocs/>
+      <defines title=""/>
+      <typedefs title=""/>
+      <enums title=""/>
+      <enumvalues title=""/>
+      <functions title=""/>
+      <variables title=""/>
+      <signals title=""/>
+      <publicslots title=""/>
+      <protectedslots title=""/>
+      <privateslots title=""/>
+      <events title=""/>
+      <properties title=""/>
+      <friends title=""/>
+    </memberdef>
+    <authorsection visible="yes"/>
+  </group>
+
+  <!-- Layout definition for a directory page -->
+  <directory>
+    <briefdescription visible="yes"/>
+    <directorygraph visible="yes"/>
+    <memberdecl>
+      <dirs visible="yes"/>
+      <files visible="yes"/>
+    </memberdecl>
+    <detaileddescription title=""/>
+  </directory>
+</doxygenlayout>
diff --git a/extlibs/tinydtls/doc/Makefile.in b/extlibs/tinydtls/doc/Makefile.in
new file mode 100644 (file)
index 0000000..a07101e
--- /dev/null
@@ -0,0 +1,36 @@
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+PACKAGE_TARNAME:=@PACKAGE_TARNAME@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+DOXYGEN= @DOXYGEN@
+
+top_builddir = @top_builddir@
+prefix = @prefix@
+datarootdir = @datarootdir@
+docdir = @docdir@
+htmldir = @htmldir@
+
+DISTDIR?=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
+FILES:=Makefile.in Doxyfile.in html
+
+doc:   Doxyfile
+       $(DOXYGEN) $< >./doxygen.out 2>&1 
+
+clean:
+       @rm -rf html
+
+distclean:     clean
+       @rm -rf $(DISTDIR)
+       @rm -f *~ 
+
+dist:  doc
+       test -d $(DISTDIR)/doc || mkdir $(DISTDIR)/doc
+       cp -r $(FILES) $(DISTDIR)/doc
+
+install:       $(doc) html
+       test -d $(htmldir) || mkdir -p $(htmldir)
+       cp -r html/* $(htmldir)
diff --git a/extlibs/tinydtls/dtls.c b/extlibs/tinydtls/dtls.c
new file mode 100644 (file)
index 0000000..a923386
--- /dev/null
@@ -0,0 +1,4072 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2012,2014 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "tinydtls.h"
+#include "dtls_config.h"
+#include "dtls_time.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef HAVE_ASSERT_H
+#include <assert.h>
+#endif
+#ifndef WITH_CONTIKI
+#include <stdlib.h>
+#include "uthash.h"
+#endif /* WITH_CONTIKI */
+
+#include "debug.h"
+#include "numeric.h"
+#include "netq.h"
+#include "dtls.h"
+
+#include "alert.h"
+#include "session.h"
+#include "prng.h"
+
+#ifdef WITH_SHA256
+#  include "sha2/sha2.h"
+#endif
+
+#define dtls_set_version(H,V) dtls_int_to_uint16((H)->version, (V))
+#define dtls_set_content_type(H,V) ((H)->content_type = (V) & 0xff)
+#define dtls_set_length(H,V)  ((H)->length = (V))
+
+#define dtls_get_content_type(H) ((H)->content_type & 0xff)
+#define dtls_get_version(H) dtls_uint16_to_int((H)->version)
+#define dtls_get_epoch(H) dtls_uint16_to_int((H)->epoch)
+#define dtls_get_sequence_number(H) dtls_uint48_to_ulong((H)->sequence_number)
+#define dtls_get_fragment_length(H) dtls_uint24_to_int((H)->fragment_length)
+
+#ifndef WITH_CONTIKI
+#define HASH_FIND_PEER(head,sess,out)          \
+  HASH_FIND(hh,head,sess,sizeof(session_t),out)
+#define HASH_ADD_PEER(head,sess,add)           \
+  HASH_ADD(hh,head,sess,sizeof(session_t),add)
+#define HASH_DEL_PEER(head,delptr)             \
+  HASH_DELETE(hh,head,delptr)
+#endif /* WITH_CONTIKI */
+
+#define DTLS_RH_LENGTH sizeof(dtls_record_header_t)
+#define DTLS_HS_LENGTH sizeof(dtls_handshake_header_t)
+#define DTLS_CH_LENGTH sizeof(dtls_client_hello_t) /* no variable length fields! */
+#define DTLS_COOKIE_LENGTH_MAX 32
+#define DTLS_CH_LENGTH_MAX sizeof(dtls_client_hello_t) + DTLS_COOKIE_LENGTH_MAX + 12 + 26
+#define DTLS_HV_LENGTH sizeof(dtls_hello_verify_t)
+#define DTLS_SH_LENGTH (2 + DTLS_RANDOM_LENGTH + 1 + 2 + 1)
+#define DTLS_CE_LENGTH (3 + 3 + 27 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
+#define DTLS_SKEXEC_LENGTH (1 + 2 + 1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE + 1 + 1 + 2 + 70)
+#define DTLS_SKEXECPSK_LENGTH_MIN 2
+#define DTLS_SKEXECPSK_LENGTH_MAX 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
+#define DTLS_CKXPSK_LENGTH_MIN 2
+#define DTLS_CKXEC_LENGTH (1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
+#define DTLS_CV_LENGTH (1 + 1 + 2 + 1 + 1 + 1 + 1 + DTLS_EC_KEY_SIZE + 1 + 1 + DTLS_EC_KEY_SIZE)
+#define DTLS_FIN_LENGTH 12
+
+#define HS_HDR_LENGTH  DTLS_RH_LENGTH + DTLS_HS_LENGTH
+#define HV_HDR_LENGTH  HS_HDR_LENGTH + DTLS_HV_LENGTH
+
+#define HIGH(V) (((V) >> 8) & 0xff)
+#define LOW(V)  ((V) & 0xff)
+
+#define DTLS_RECORD_HEADER(M) ((dtls_record_header_t *)(M))
+#define DTLS_HANDSHAKE_HEADER(M) ((dtls_handshake_header_t *)(M))
+
+#define HANDSHAKE(M) ((dtls_handshake_header_t *)((M) + DTLS_RH_LENGTH))
+#define CLIENTHELLO(M) ((dtls_client_hello_t *)((M) + HS_HDR_LENGTH))
+
+/* The length check here should work because dtls_*_to_int() works on
+ * unsigned char. Otherwise, broken messages could cause severe
+ * trouble. Note that this macro jumps out of the current program flow
+ * when the message is too short. Beware!
+ */
+#define SKIP_VAR_FIELD(P,L,T) {                                                \
+    if (L < dtls_ ## T ## _to_int(P) + sizeof(T))                      \
+      goto error;                                                      \
+    L -= dtls_ ## T ## _to_int(P) + sizeof(T);                         \
+    P += dtls_ ## T ## _to_int(P) + sizeof(T);                         \
+  }
+
+/* some constants for the PRF */
+#define PRF_LABEL(Label) prf_label_##Label
+#define PRF_LABEL_SIZE(Label) (sizeof(PRF_LABEL(Label)) - 1)
+
+static const unsigned char prf_label_master[] = "master secret";
+static const unsigned char prf_label_key[] = "key expansion";
+static const unsigned char prf_label_client[] = "client";
+static const unsigned char prf_label_server[] = "server";
+static const unsigned char prf_label_finished[] = " finished";
+
+/* first part of Raw public key, the is the start of the Subject Public Key */
+static const unsigned char cert_asn1_header[] = {
+  0x30, 0x59, /* SEQUENCE, length 89 bytes */
+    0x30, 0x13, /* SEQUENCE, length 19 bytes */
+      0x06, 0x07, /* OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1) */
+        0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01,
+      0x06, 0x08, /* OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7) */
+        0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07,
+      0x03, 0x42, 0x00, /* BIT STRING, length 66 bytes, 0 bits unused */
+         0x04 /* uncompressed, followed by the r und s values of the public key */
+};
+
+#ifdef WITH_CONTIKI
+PROCESS(dtls_retransmit_process, "DTLS retransmit process");
+
+static dtls_context_t the_dtls_context;
+
+static inline dtls_context_t *
+malloc_context() {
+  return &the_dtls_context;
+}
+
+static inline void
+free_context(dtls_context_t *context) {
+}
+
+#else /* WITH_CONTIKI */
+
+static inline dtls_context_t *
+malloc_context() {
+  return (dtls_context_t *)malloc(sizeof(dtls_context_t));
+}
+
+static inline void
+free_context(dtls_context_t *context) {
+  free(context);
+}
+#endif
+
+void
+dtls_init() {
+  dtls_clock_init();
+  crypto_init();
+  netq_init();
+  peer_init();
+}
+
+/* Calls cb_alert() with given arguments if defined, otherwise an
+ * error message is logged and the result is -1. This is just an
+ * internal helper.
+ */
+#define CALL(Context, which, ...)                                      \
+  ((Context)->h && (Context)->h->which                                 \
+   ? (Context)->h->which((Context), ##__VA_ARGS__)                     \
+   : -1)
+
+static int
+dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
+               dtls_security_parameters_t *security , session_t *session,
+               unsigned char type, uint8 *buf_array[],
+               size_t buf_len_array[], size_t buf_array_len);
+
+/** 
+ * Sends the fragment of length \p buflen given in \p buf to the
+ * specified \p peer. The data will be MAC-protected and encrypted
+ * according to the selected cipher and split into one or more DTLS
+ * records of the specified \p type. This function returns the number
+ * of bytes that were sent, or \c -1 if an error occurred.
+ *
+ * \param ctx    The DTLS context to use.
+ * \param peer   The remote peer.
+ * \param type   The content type of the record. 
+ * \param buf    The data to send.
+ * \param buflen The actual length of \p buf.
+ * \return Less than zero on error, the number of bytes written otherwise.
+ */
+static int
+dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
+         uint8 *buf, size_t buflen) {
+  return dtls_send_multi(ctx, peer, dtls_security_params(peer), &peer->session,
+                        type, &buf, &buflen, 1);
+}
+
+/**
+ * Stops ongoing retransmissions of handshake messages for @p peer.
+ */
+static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
+
+dtls_peer_t *
+dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
+  dtls_peer_t *p = NULL;
+
+#ifndef WITH_CONTIKI
+  HASH_FIND_PEER(ctx->peers, session, p);
+#else /* WITH_CONTIKI */
+  for (p = list_head(ctx->peers); p; p = list_item_next(p))
+    if (dtls_session_equals(&p->session, session))
+      return p;
+#endif /* WITH_CONTIKI */
+  
+  return p;
+}
+
+static void
+dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
+#ifndef WITH_CONTIKI
+  HASH_ADD_PEER(ctx->peers, session, peer);
+#else /* WITH_CONTIKI */
+  list_add(ctx->peers, peer);
+#endif /* WITH_CONTIKI */
+}
+
+int
+dtls_write(struct dtls_context_t *ctx, 
+          session_t *dst, uint8 *buf, size_t len) {
+  
+  dtls_peer_t *peer = dtls_get_peer(ctx, dst);
+
+  /* Check if peer connection already exists */
+  if (!peer) { /* no ==> create one */
+    int res;
+
+    /* dtls_connect() returns a value greater than zero if a new
+     * connection attempt is made, 0 for session reuse. */
+    res = dtls_connect(ctx, dst);
+
+    return (res >= 0) ? 0 : res;
+  } else { /* a session exists, check if it is in state connected */
+    
+    if (peer->state != DTLS_STATE_CONNECTED) {
+      return 0;
+    } else {
+      return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
+    }
+  }
+}
+
+static int
+dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie) {
+  /* To access the cookie, we have to determine the session id's
+   * length and skip the whole thing. */
+  if (msglen < DTLS_HS_LENGTH + DTLS_CH_LENGTH + sizeof(uint8))
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+
+  if (dtls_uint16_to_int(msg + DTLS_HS_LENGTH) != DTLS_VERSION)
+    return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
+
+  msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
+  msg += DTLS_HS_LENGTH + DTLS_CH_LENGTH;
+
+  SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
+
+  if (msglen < (*msg & 0xff) + sizeof(uint8))
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  
+  *cookie = msg + sizeof(uint8);
+  return dtls_uint8_to_int(msg);
+
+ error:
+  return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+}
+
+static int
+dtls_create_cookie(dtls_context_t *ctx, 
+                  session_t *session,
+                  uint8 *msg, size_t msglen,
+                  uint8 *cookie, int *clen) {
+  unsigned char buf[DTLS_HMAC_MAX];
+  size_t len, e;
+
+  /* create cookie with HMAC-SHA256 over:
+   * - SECRET
+   * - session parameters (only IP address?)
+   * - client version 
+   * - random gmt and bytes
+   * - session id
+   * - cipher_suites 
+   * - compression method
+   */
+
+  /* We use our own buffer as hmac_context instead of a dynamic buffer
+   * created by dtls_hmac_new() to separate storage space for cookie
+   * creation from storage that is used in real sessions. Note that
+   * the buffer size must fit with the default hash algorithm (see
+   * implementation of dtls_hmac_context_new()). */
+
+  dtls_hmac_context_t hmac_context;
+  dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
+
+  dtls_hmac_update(&hmac_context, 
+                  (unsigned char *)&session->addr, session->size);
+
+  /* feed in the beginning of the Client Hello up to and including the
+     session id */
+  e = sizeof(dtls_client_hello_t);
+  e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
+  if (e + DTLS_HS_LENGTH > msglen)
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+
+  dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
+  
+  /* skip cookie bytes and length byte */
+  e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
+  e += sizeof(uint8);
+  if (e + DTLS_HS_LENGTH > msglen)
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+
+  dtls_hmac_update(&hmac_context, 
+                  msg + DTLS_HS_LENGTH + e,
+                  dtls_get_fragment_length(DTLS_HANDSHAKE_HEADER(msg)) - e);
+
+  len = dtls_hmac_finalize(&hmac_context, buf);
+
+  if (len < *clen) {
+    memset(cookie + len, 0, *clen - len);
+    *clen = len;
+  }
+  
+  memcpy(cookie, buf, *clen);
+  return 0;
+}
+
+#ifdef DTLS_CHECK_CONTENTTYPE
+/* used to check if a received datagram contains a DTLS message */
+static char const content_types[] = { 
+  DTLS_CT_CHANGE_CIPHER_SPEC,
+  DTLS_CT_ALERT,
+  DTLS_CT_HANDSHAKE,
+  DTLS_CT_APPLICATION_DATA,
+  0                            /* end marker */
+};
+#endif
+
+/**
+ * Checks if \p msg points to a valid DTLS record. If
+ * 
+ */
+static unsigned int
+is_record(uint8 *msg, size_t msglen) {
+  unsigned int rlen = 0;
+
+  if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
+#ifdef DTLS_CHECK_CONTENTTYPE
+      && strchr(content_types, msg[0])
+#endif
+      && msg[1] == HIGH(DTLS_VERSION)
+      && msg[2] == LOW(DTLS_VERSION)) 
+    {
+      rlen = DTLS_RH_LENGTH + 
+       dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->length);
+      
+      /* we do not accept wrong length field in record header */
+      if (rlen > msglen)       
+       rlen = 0;
+  } 
+  
+  return rlen;
+}
+
+/**
+ * Initializes \p buf as record header. The caller must ensure that \p
+ * buf is capable of holding at least \c sizeof(dtls_record_header_t)
+ * bytes. Increments sequence number counter of \p security.
+ * \return pointer to the next byte after the written header.
+ * The length will be set to 0 and has to be changed before sending.
+ */ 
+static inline uint8 *
+dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
+                      uint8 *buf) {
+  
+  dtls_int_to_uint8(buf, type);
+  buf += sizeof(uint8);
+
+  dtls_int_to_uint16(buf, DTLS_VERSION);
+  buf += sizeof(uint16);
+
+  if (security) {
+    dtls_int_to_uint16(buf, security->epoch);
+    buf += sizeof(uint16);
+
+    dtls_int_to_uint48(buf, security->rseq);
+    buf += sizeof(uint48);
+
+    /* increment record sequence counter by 1 */
+    security->rseq++;
+  } else {
+    memset(buf, 0, sizeof(uint16) + sizeof(uint48));
+    buf += sizeof(uint16) + sizeof(uint48);
+  }
+
+  memset(buf, 0, sizeof(uint16));
+  return buf + sizeof(uint16);
+}
+
+/**
+ * Initializes \p buf as handshake header. The caller must ensure that \p
+ * buf is capable of holding at least \c sizeof(dtls_handshake_header_t)
+ * bytes. Increments message sequence number counter of \p peer.
+ * \return pointer to the next byte after \p buf
+ */ 
+static inline uint8 *
+dtls_set_handshake_header(uint8 type, dtls_peer_t *peer, 
+                         int length, 
+                         int frag_offset, int frag_length, 
+                         uint8 *buf) {
+  
+  dtls_int_to_uint8(buf, type);
+  buf += sizeof(uint8);
+
+  dtls_int_to_uint24(buf, length);
+  buf += sizeof(uint24);
+
+  if (peer && peer->handshake_params) {
+    /* and copy the result to buf */
+    dtls_int_to_uint16(buf, peer->handshake_params->hs_state.mseq_s);
+
+    /* increment handshake message sequence counter by 1 */
+    peer->handshake_params->hs_state.mseq_s++;
+  } else {
+    memset(buf, 0, sizeof(uint16));    
+  }
+  buf += sizeof(uint16);
+  
+  dtls_int_to_uint24(buf, frag_offset);
+  buf += sizeof(uint24);
+
+  dtls_int_to_uint24(buf, frag_length);
+  buf += sizeof(uint24);
+  
+  return buf;
+}
+
+/** only one compression method is currently defined */
+static uint8 compression_methods[] = {
+  TLS_COMPRESSION_NULL
+};
+
+/** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
+static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
+{
+#ifdef DTLS_ECC
+  return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
+#else
+  return 0;
+#endif /* DTLS_ECC */
+}
+
+/** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
+static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
+{
+#ifdef DTLS_PSK
+  return cipher == TLS_PSK_WITH_AES_128_CCM_8;
+#else
+  return 0;
+#endif /* DTLS_PSK */
+}
+
+/** returns true if the application is configured for psk */
+static inline int is_psk_supported(dtls_context_t *ctx)
+{
+#ifdef DTLS_PSK
+  return ctx && ctx->h && ctx->h->get_psk_info;
+#else
+  return 0;
+#endif /* DTLS_PSK */
+}
+
+/** returns true if the application is configured for ecdhe_ecdsa */
+static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
+{
+#ifdef DTLS_ECC
+  return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) || 
+                          (is_client && ctx->h->verify_ecdsa_key));
+#else
+  return 0;
+#endif /* DTLS_ECC */
+}
+
+/** Returns true if the application is configured for ecdhe_ecdsa with
+  * client authentication */
+static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
+{
+#ifdef DTLS_ECC
+  return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
+#else
+  return 0;
+#endif /* DTLS_ECC */
+}
+
+/**
+ * Returns @c 1 if @p code is a cipher suite other than @c
+ * TLS_NULL_WITH_NULL_NULL that we recognize.
+ *
+ * @param ctx   The current DTLS context
+ * @param code The cipher suite identifier to check
+ * @param is_client 1 for a dtls client, 0 for server
+ * @return @c 1 iff @p code is recognized,
+ */ 
+static int
+known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
+  int psk;
+  int ecdsa;
+
+  psk = is_psk_supported(ctx);
+  ecdsa = is_ecdsa_supported(ctx, is_client);
+  return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
+        (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
+}
+
+/**
+ * This method detects if we already have a established DTLS session with
+ * peer and the peer is attempting to perform a fresh handshake by sending
+ * messages with epoch = 0. This is to handle situations mentioned in
+ * RFC 6347 - section 4.2.8.
+ *
+ * @param msg  The packet received from Client
+ * @param msglen Packet length
+ * @param peer peer who is the sender for this packet
+ * @return @c 1 if this is a rehandshake attempt by
+ * client
+ */
+static int
+hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
+    dtls_peer_t *peer)
+{
+    if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
+      if (msg[0] == DTLS_CT_HANDSHAKE) {
+        uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
+        if (msg_epoch == 0) {
+          dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
+          if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
+              hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
+            return 1;
+          }
+        }
+      }
+    }
+    return 0;
+}
+
+/** Dump out the cipher keys and IVs used for the symetric cipher. */
+static void dtls_debug_keyblock(dtls_security_parameters_t *config)
+{
+  dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
+  dtls_debug_dump("  client_MAC_secret",
+                 dtls_kb_client_mac_secret(config, peer->role),
+                 dtls_kb_mac_secret_size(config, peer->role));
+
+  dtls_debug_dump("  server_MAC_secret",
+                 dtls_kb_server_mac_secret(config, peer->role),
+                 dtls_kb_mac_secret_size(config, peer->role));
+
+  dtls_debug_dump("  client_write_key",
+                 dtls_kb_client_write_key(config, peer->role),
+                 dtls_kb_key_size(config, peer->role));
+
+  dtls_debug_dump("  server_write_key",
+                 dtls_kb_server_write_key(config, peer->role),
+                 dtls_kb_key_size(config, peer->role));
+
+  dtls_debug_dump("  client_IV",
+                 dtls_kb_client_iv(config, peer->role),
+                 dtls_kb_iv_size(config, peer->role));
+
+  dtls_debug_dump("  server_IV",
+                 dtls_kb_server_iv(config, peer->role),
+                 dtls_kb_iv_size(config, peer->role));
+}
+
+/** returns the name of the goven handshake type number.
+  * see IANA for a full list of types:
+  * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
+  */
+static char *dtls_handshake_type_to_name(int type)
+{
+  switch (type) {
+  case DTLS_HT_HELLO_REQUEST:
+    return "hello_request";
+  case DTLS_HT_CLIENT_HELLO:
+    return "client_hello";
+  case DTLS_HT_SERVER_HELLO:
+    return "server_hello";
+  case DTLS_HT_HELLO_VERIFY_REQUEST:
+    return "hello_verify_request";
+  case DTLS_HT_CERTIFICATE:
+    return "certificate";
+  case DTLS_HT_SERVER_KEY_EXCHANGE:
+    return "server_key_exchange";
+  case DTLS_HT_CERTIFICATE_REQUEST:
+    return "certificate_request";
+  case DTLS_HT_SERVER_HELLO_DONE:
+    return "server_hello_done";
+  case DTLS_HT_CERTIFICATE_VERIFY:
+    return "certificate_verify";
+  case DTLS_HT_CLIENT_KEY_EXCHANGE:
+    return "client_key_exchange";
+  case DTLS_HT_FINISHED:
+    return "finished";
+  default:
+    return "unknown";
+  }
+}
+
+/**
+ * Calculate the pre master secret and after that calculate the master-secret.
+ */
+static int
+calculate_key_block(dtls_context_t *ctx, 
+                   dtls_handshake_parameters_t *handshake,
+                   dtls_peer_t *peer,
+                   session_t *session,
+                   dtls_peer_type role) {
+  unsigned char *pre_master_secret;
+  int pre_master_len = 0;
+  dtls_security_parameters_t *security = dtls_security_params_next(peer);
+  uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
+
+  if (!security) {
+    return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+  }
+
+  pre_master_secret = security->key_block;
+
+  switch (handshake->cipher) {
+#ifdef DTLS_PSK
+  case TLS_PSK_WITH_AES_128_CCM_8: {
+    unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
+    int len;
+
+    len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
+              handshake->keyx.psk.identity,
+              handshake->keyx.psk.id_length,
+              psk, DTLS_PSK_MAX_KEY_LEN);
+    if (len < 0) {
+      dtls_crit("no psk key for session available\n");
+      return len;
+    }
+  /* Temporarily use the key_block storage space for the pre master secret. */
+    pre_master_len = dtls_psk_pre_master_secret(psk, len,
+                                               pre_master_secret,
+                                               MAX_KEYBLOCK_LENGTH);
+
+    dtls_debug_hexdump("psk", psk, len);
+
+    memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
+    if (pre_master_len < 0) {
+      dtls_crit("the psk was too long, for the pre master secret\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    break;
+  }
+#endif /* DTLS_PSK */
+#ifdef DTLS_ECC
+  case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: {
+    pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecdsa.own_eph_priv,
+                                                handshake->keyx.ecdsa.other_eph_pub_x,
+                                                handshake->keyx.ecdsa.other_eph_pub_y,
+                                                sizeof(handshake->keyx.ecdsa.own_eph_priv),
+                                                pre_master_secret,
+                                                MAX_KEYBLOCK_LENGTH);
+    if (pre_master_len < 0) {
+      dtls_crit("the curve was too long, for the pre master secret\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+    break;
+  }
+#endif /* DTLS_ECC */
+  default:
+    dtls_crit("calculate_key_block: unknown cipher\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+  }
+
+  dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
+  dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
+  dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
+
+  dtls_prf(pre_master_secret, pre_master_len,
+          PRF_LABEL(master), PRF_LABEL_SIZE(master),
+          handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
+          handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
+          master_secret,
+          DTLS_MASTER_SECRET_LENGTH);
+
+  dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
+
+  /* create key_block from master_secret
+   * key_block = PRF(master_secret,
+                    "key expansion" + tmp.random.server + tmp.random.client) */
+
+  dtls_prf(master_secret,
+          DTLS_MASTER_SECRET_LENGTH,
+          PRF_LABEL(key), PRF_LABEL_SIZE(key),
+          handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
+          handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
+          security->key_block,
+          dtls_kb_size(security, role));
+
+  memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
+  dtls_debug_keyblock(security);
+
+  security->cipher = handshake->cipher;
+  security->compression = handshake->compression;
+  security->rseq = 0;
+
+  return 0;
+}
+
+/* TODO: add a generic method which iterates over a list and searches for a specific key */
+static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
+  int i, curve_name;
+
+  /* length of curve list */
+  i = dtls_uint16_to_int(data);
+  data += sizeof(uint16);
+  if (i + sizeof(uint16) != data_length) {
+    dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+
+  for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
+    /* check if this curve is supported */
+    curve_name = dtls_uint16_to_int(data);
+    data += sizeof(uint16);
+
+    if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
+      return 0;
+  }
+
+  dtls_warn("no supported elliptic curve found\n");
+  return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+}
+
+static int verify_ext_cert_type(uint8 *data, size_t data_length) {
+  int i, cert_type;
+
+  /* length of cert type list */
+  i = dtls_uint8_to_int(data);
+  data += sizeof(uint8);
+  if (i + sizeof(uint8) != data_length) {
+    dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+
+  for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
+    /* check if this cert type is supported */
+    cert_type = dtls_uint8_to_int(data);
+    data += sizeof(uint8);
+
+    if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
+      return 0;
+  }
+
+  dtls_warn("no supported certificate type found\n");
+  return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+}
+
+static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
+  int i, cert_type;
+
+  /* length of ec_point_formats list */
+  i = dtls_uint8_to_int(data);
+  data += sizeof(uint8);
+  if (i + sizeof(uint8) != data_length) {
+    dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+
+  for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
+    /* check if this ec_point_format is supported */
+    cert_type = dtls_uint8_to_int(data);
+    data += sizeof(uint8);
+
+    if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
+      return 0;
+  }
+
+  dtls_warn("no supported ec_point_format found\n");
+  return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+}
+
+/*
+ * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
+ */
+static int
+dtls_check_tls_extension(dtls_peer_t *peer,
+                        uint8 *data, size_t data_length, int client_hello)
+{
+  uint16_t i, j;
+  int ext_elliptic_curve = 0;
+  int ext_client_cert_type = 0;
+  int ext_server_cert_type = 0;
+  int ext_ec_point_formats = 0;
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+
+  if (data_length < sizeof(uint16)) { 
+    /* no tls extensions specified */
+    if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
+      goto error;
+    }
+    return 0;
+  }
+
+  /* get the length of the tls extension list */
+  j = dtls_uint16_to_int(data);
+  data += sizeof(uint16);
+  data_length -= sizeof(uint16);
+
+  if (data_length < j)
+    goto error;
+
+  /* check for TLS extensions needed for this cipher */
+  while (data_length) {
+    if (data_length < sizeof(uint16) * 2)
+      goto error;
+
+    /* get the tls extension type */
+    i = dtls_uint16_to_int(data);
+    data += sizeof(uint16);
+    data_length -= sizeof(uint16);
+
+    /* get the length of the tls extension */
+    j = dtls_uint16_to_int(data);
+    data += sizeof(uint16);
+    data_length -= sizeof(uint16);
+
+    if (data_length < j)
+      goto error;
+
+    switch (i) {
+      case TLS_EXT_ELLIPTIC_CURVES:
+        ext_elliptic_curve = 1;
+        if (verify_ext_eliptic_curves(data, j))
+          goto error;
+        break;
+      case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
+        ext_client_cert_type = 1;
+        if (client_hello) {
+         if (verify_ext_cert_type(data, j))
+            goto error;
+        } else {
+         if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
+           goto error;
+        }
+        break;
+      case TLS_EXT_SERVER_CERTIFICATE_TYPE:
+        ext_server_cert_type = 1;
+        if (client_hello) {
+         if (verify_ext_cert_type(data, j))
+            goto error;
+        } else {
+         if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
+           goto error;
+        }
+        break;
+      case TLS_EXT_EC_POINT_FORMATS:
+        ext_ec_point_formats = 1;
+        if (verify_ext_ec_point_formats(data, j))
+          goto error;
+        break;
+      case TLS_EXT_ENCRYPT_THEN_MAC:
+       /* As only AEAD cipher suites are currently available, this
+        * extension can be skipped. 
+        */
+       dtls_info("skipped encrypt-then-mac extension\n");
+       break;
+      default:
+        dtls_warn("unsupported tls extension: %i\n", i);
+        break;
+    }
+    data += j;
+    data_length -= j;
+  }
+  if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
+    if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
+       || !ext_ec_point_formats) {
+      dtls_warn("not all required tls extensions found in client hello\n");
+      goto error;
+    }
+  } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
+    if (!ext_client_cert_type || !ext_server_cert_type) {
+      dtls_warn("not all required tls extensions found in server hello\n");
+      goto error;
+    }
+  }
+  return 0;
+
+error:
+  if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
+    return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
+  } else {
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+}
+
+/**
+ * Parses the ClientHello from the client and updates the internal handshake
+ * parameters with the new data for the given \p peer. When the ClientHello
+ * handshake message in \p data does not contain a cipher suite or
+ * compression method, it is copied from the the current security parameters.
+ *
+ * \param ctx   The current DTLS context.
+ * \param peer  The remote peer whose security parameters are about to change.
+ * \param data  The handshake message with a ClientHello. 
+ * \param data_length The actual size of \p data.
+ * \return \c -Something if an error occurred, \c 0 on success.
+ */
+static int
+dtls_update_parameters(dtls_context_t *ctx, 
+                      dtls_peer_t *peer,
+                      uint8 *data, size_t data_length) {
+  int i, j;
+  int ok;
+  dtls_handshake_parameters_t *config = peer->handshake_params;
+  dtls_security_parameters_t *security = dtls_security_params(peer);
+
+  assert(config);
+  assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
+
+  /* skip the handshake header and client version information */
+  data += DTLS_HS_LENGTH + sizeof(uint16);
+  data_length -= DTLS_HS_LENGTH + sizeof(uint16);
+
+  /* store client random in config */
+  memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
+  data += DTLS_RANDOM_LENGTH;
+  data_length -= DTLS_RANDOM_LENGTH;
+
+  /* Caution: SKIP_VAR_FIELD may jump to error: */
+  SKIP_VAR_FIELD(data, data_length, uint8);    /* skip session id */
+  SKIP_VAR_FIELD(data, data_length, uint8);    /* skip cookie */
+
+  i = dtls_uint16_to_int(data);
+  if (data_length < i + sizeof(uint16)) {
+    /* Looks like we do not have a cipher nor compression. This is ok
+     * for renegotiation, but not for the initial handshake. */
+
+    if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
+      goto error;
+
+    config->cipher = security->cipher;
+    config->compression = security->compression;
+
+    return 0;
+  }
+
+  data += sizeof(uint16);
+  data_length -= sizeof(uint16) + i;
+
+  ok = 0;
+  while (i && !ok) {
+    config->cipher = dtls_uint16_to_int(data);
+    ok = known_cipher(ctx, config->cipher, 0);
+    i -= sizeof(uint16);
+    data += sizeof(uint16);
+  }
+
+  /* skip remaining ciphers */
+  data += i;
+
+  if (!ok) {
+    /* reset config cipher to a well-defined value */
+    config->cipher = TLS_NULL_WITH_NULL_NULL;
+    dtls_warn("No matching cipher found\n");
+    goto error;
+  }
+
+  if (data_length < sizeof(uint8)) { 
+    /* no compression specified, take the current compression method */
+    if (security)
+      config->compression = security->compression;
+    else
+      config->compression = TLS_COMPRESSION_NULL;
+    return 0;
+  }
+
+  i = dtls_uint8_to_int(data);
+  if (data_length < i + sizeof(uint8))
+    goto error;
+
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8) + i;
+
+  ok = 0;
+  while (i && !ok) {
+    for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
+      if (dtls_uint8_to_int(data) == compression_methods[j]) {
+       config->compression = compression_methods[j];
+       ok = 1;
+      }
+    i -= sizeof(uint8);
+    data += sizeof(uint8);    
+  }
+
+  if (!ok) {
+    /* reset config cipher to a well-defined value */
+    goto error;
+  }
+  
+  return dtls_check_tls_extension(peer, data, data_length, 1);
+error:
+  if (peer->state == DTLS_STATE_CONNECTED) {
+    return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
+  } else {
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+}
+
+/**
+ * Parse the ClientKeyExchange and update the internal handshake state with
+ * the new data.
+ */
+static inline int
+check_client_keyexchange(dtls_context_t *ctx, 
+                        dtls_handshake_parameters_t *handshake,
+                        uint8 *data, size_t length) {
+
+#ifdef DTLS_ECC
+  if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
+
+    if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
+      dtls_debug("The client key exchange is too short\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+    }
+    data += DTLS_HS_LENGTH;
+
+    if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
+      dtls_alert("expected 65 bytes long public point\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+    }
+    data += sizeof(uint8);
+
+    if (dtls_uint8_to_int(data) != 4) {
+      dtls_alert("expected uncompressed public point\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+    }
+    data += sizeof(uint8);
+
+    memcpy(handshake->keyx.ecdsa.other_eph_pub_x, data,
+          sizeof(handshake->keyx.ecdsa.other_eph_pub_x));
+    data += sizeof(handshake->keyx.ecdsa.other_eph_pub_x);
+
+    memcpy(handshake->keyx.ecdsa.other_eph_pub_y, data,
+          sizeof(handshake->keyx.ecdsa.other_eph_pub_y));
+    data += sizeof(handshake->keyx.ecdsa.other_eph_pub_y);
+  }
+#endif /* DTLS_ECC */
+#ifdef DTLS_PSK
+  if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
+    int id_length;
+
+    if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
+      dtls_debug("The client key exchange is too short\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+    }
+    data += DTLS_HS_LENGTH;
+
+    id_length = dtls_uint16_to_int(data);
+    data += sizeof(uint16);
+
+    if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
+      dtls_debug("The identity has a wrong length\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+    }
+
+    if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
+      dtls_warn("please use a smaller client identity\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    handshake->keyx.psk.id_length = id_length;
+    memcpy(handshake->keyx.psk.identity, data, id_length);
+  }
+#endif /* DTLS_PSK */
+  return 0;
+}
+
+static inline void
+update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
+  dtls_debug_dump("add MAC data", data, length);
+  dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
+}
+
+static void
+copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
+  memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
+        sizeof(peer->handshake_params->hs_state.hs_hash));
+}
+
+static inline size_t
+finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
+  return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
+}
+
+static inline void
+clear_hs_hash(dtls_peer_t *peer) {
+  assert(peer);
+  dtls_debug("clear MAC\n");
+  dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
+}
+
+/** 
+ * Checks if \p record + \p data contain a Finished message with valid
+ * verify_data. 
+ *
+ * \param ctx    The current DTLS context.
+ * \param peer   The remote peer of the security association.
+ * \param data   The cleartext payload of the message.
+ * \param data_length Actual length of \p data.
+ * \return \c 0 if the Finished message is valid, \c negative number otherwise.
+ */
+static int
+check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
+              uint8 *data, size_t data_length) {
+  size_t digest_length, label_size;
+  const unsigned char *label;
+  unsigned char buf[DTLS_HMAC_MAX];
+
+  if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+
+  /* Use a union here to ensure that sufficient stack space is
+   * reserved. As statebuf and verify_data are not used at the same
+   * time, we can re-use the storage safely.
+   */
+  union {
+    unsigned char statebuf[DTLS_HASH_CTX_SIZE];
+    unsigned char verify_data[DTLS_FIN_LENGTH];
+  } b;
+
+  /* temporarily store hash status for roll-back after finalize */
+  memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
+
+  digest_length = finalize_hs_hash(peer, buf);
+  /* clear_hash(); */
+
+  /* restore hash status */
+  memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
+
+  if (peer->role == DTLS_CLIENT) {
+    label = PRF_LABEL(server);
+    label_size = PRF_LABEL_SIZE(server);
+  } else { /* server */
+    label = PRF_LABEL(client);
+    label_size = PRF_LABEL_SIZE(client);
+  }
+
+  dtls_prf(peer->handshake_params->tmp.master_secret,
+          DTLS_MASTER_SECRET_LENGTH,
+          label, label_size,
+          PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
+          buf, digest_length,
+          b.verify_data, sizeof(b.verify_data));
+
+  dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
+  dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
+
+  /* compare verify data and create DTLS alert code when they differ */
+  return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
+    ? 0
+    : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
+}
+
+/**
+ * Prepares the payload given in \p data for sending with
+ * dtls_send(). The \p data is encrypted and compressed according to
+ * the current security parameters of \p peer.  The result of this
+ * operation is put into \p sendbuf with a prepended record header of
+ * type \p type ready for sending. As some cipher suites add a MAC
+ * before encryption, \p data must be large enough to hold this data
+ * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
+ *
+ * \param peer    The remote peer the packet will be sent to.
+ * \param security  The encryption paramater used to encrypt
+ * \param type    The content type of this record.
+ * \param data_array Array with payloads in correct order.
+ * \param data_len_array sizes of the payloads in correct order.
+ * \param data_array_len The number of payloads given.
+ * \param sendbuf The output buffer where the encrypted record
+ *                will be placed.
+ * \param rlen    This parameter must be initialized with the 
+ *                maximum size of \p sendbuf and will be updated
+ *                to hold the actual size of the stored packet
+ *                on success. On error, the value of \p rlen is
+ *                undefined. 
+ * \return Less than zero on error, or greater than zero success.
+ */
+static int
+dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
+                   unsigned char type,
+                   uint8 *data_array[], size_t data_len_array[],
+                   size_t data_array_len,
+                   uint8 *sendbuf, size_t *rlen) {
+  uint8 *p, *start;
+  int res;
+  unsigned int i;
+  
+  if (*rlen < DTLS_RH_LENGTH) {
+    dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
+    return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+  }
+
+  p = dtls_set_record_header(type, security, sendbuf);
+  start = p;
+
+  if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
+    /* no cipher suite */
+
+    res = 0;
+    for (i = 0; i < data_array_len; i++) {
+      /* check the minimum that we need for packets that are not encrypted */
+      if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
+        dtls_debug("dtls_prepare_record: send buffer too small\n");
+        return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+      }
+
+      memcpy(p, data_array[i], data_len_array[i]);
+      p += data_len_array[i];
+      res += data_len_array[i];
+    }
+  } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */   
+    /** 
+     * length of additional_data for the AEAD cipher which consists of
+     * seq_num(2+6) + type(1) + version(2) + length(2)
+     */
+#define A_DATA_LEN 13
+    unsigned char nonce[DTLS_CCM_BLOCKSIZE];
+    unsigned char A_DATA[A_DATA_LEN];
+
+    if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
+      dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
+    } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
+      dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
+    } else {
+      dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
+    }
+
+    /* set nonce       
+       from RFC 6655:
+       The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
+       the "nonce" SHALL be 12 bytes long and is constructed as follows:
+       (this is an example of a "partially explicit" nonce; see Section
+       3.2.1 in [RFC5116]).
+
+                       struct {
+             opaque salt[4];
+             opaque nonce_explicit[8];
+                       } CCMNonce;
+
+         [...]
+
+        In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
+        48-bit seq_num.
+
+        When the nonce_explicit is equal to the sequence number, the CCMNonce
+        will have the structure of the CCMNonceExample given below.
+
+                   struct {
+                    uint32 client_write_IV; // low order 32-bits
+                    uint64 seq_num;         // TLS sequence number
+                   } CCMClientNonce.
+
+
+                   struct {
+                    uint32 server_write_IV; // low order 32-bits
+                    uint64 seq_num; // TLS sequence number
+                   } CCMServerNonce.
+
+
+                   struct {
+                    case client:
+                      CCMClientNonce;
+                    case server:
+                      CCMServerNonce:
+                   } CCMNonceExample;
+    */
+
+    memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
+    p += 8;
+    res = 8;
+
+    for (i = 0; i < data_array_len; i++) {
+      /* check the minimum that we need for packets that are not encrypted */
+      if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
+        dtls_debug("dtls_prepare_record: send buffer too small\n");
+        return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+      }
+
+      memcpy(p, data_array[i], data_len_array[i]);
+      p += data_len_array[i];
+      res += data_len_array[i];
+    }
+
+    memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
+    memcpy(nonce, dtls_kb_local_iv(security, peer->role),
+          dtls_kb_iv_size(security, peer->role));
+    memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
+
+    dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
+    dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
+                   dtls_kb_key_size(security, peer->role));
+    
+    /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
+     * 
+     * additional_data = seq_num + TLSCompressed.type +
+     *                   TLSCompressed.version + TLSCompressed.length;
+     */
+    memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
+    memcpy(A_DATA + 8,  &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
+    dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
+    
+    res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
+                      dtls_kb_local_write_key(security, peer->role),
+                      dtls_kb_key_size(security, peer->role),
+                      A_DATA, A_DATA_LEN);
+
+    if (res < 0)
+      return res;
+
+    res += 8;                  /* increment res by size of nonce_explicit */
+    dtls_debug_dump("message:", start, res);
+  }
+
+  /* fix length of fragment in sendbuf */
+  dtls_int_to_uint16(sendbuf + 11, res);
+  
+  *rlen = DTLS_RH_LENGTH + res;
+  return 0;
+}
+
+static int
+dtls_send_handshake_msg_hash(dtls_context_t *ctx,
+                            dtls_peer_t *peer,
+                            session_t *session,
+                            uint8 header_type,
+                            uint8 *data, size_t data_length,
+                            int add_hash)
+{
+  uint8 buf[DTLS_HS_LENGTH];
+  uint8 *data_array[2];
+  size_t data_len_array[2];
+  int i = 0;
+  dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
+
+  dtls_set_handshake_header(header_type, peer, data_length, 0,
+                           data_length, buf);
+
+  if (add_hash) {
+    update_hs_hash(peer, buf, sizeof(buf));
+  }
+  data_array[i] = buf;
+  data_len_array[i] = sizeof(buf);
+  i++;
+
+  if (data != NULL) {
+    if (add_hash) {
+      update_hs_hash(peer, data, data_length);
+    }
+    data_array[i] = data;
+    data_len_array[i] = data_length;
+    i++;
+  }
+  dtls_debug("send handshake packet of type: %s (%i)\n",
+            dtls_handshake_type_to_name(header_type), header_type);
+  return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
+                        data_array, data_len_array, i);
+}
+
+static int
+dtls_send_handshake_msg(dtls_context_t *ctx,
+                       dtls_peer_t *peer,
+                       uint8 header_type,
+                       uint8 *data, size_t data_length)
+{
+  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
+                                     header_type, data, data_length, 1);
+}
+
+/** 
+ * Returns true if the message @p Data is a handshake message that
+ * must be included in the calculation of verify_data in the Finished
+ * message.
+ * 
+ * @param Type The message type. Only handshake messages but the initial 
+ * Client Hello and Hello Verify Request are included in the hash,
+ * @param Data The PDU to examine.
+ * @param Length The length of @p Data.
+ * 
+ * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
+ *
+ * @hideinitializer
+ */
+#define MUST_HASH(Type, Data, Length)                                  \
+  ((Type) == DTLS_CT_HANDSHAKE &&                                      \
+   ((Data) != NULL) && ((Length) > 0)  &&                              \
+   ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) &&                      \
+   ((Data)[0] != DTLS_HT_CLIENT_HELLO ||                               \
+    ((Length) >= HS_HDR_LENGTH &&                                      \
+     (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) ||       \
+      (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
+
+/**
+ * Sends the data passed in @p buf as a DTLS record of type @p type to
+ * the given peer. The data will be encrypted and compressed according
+ * to the security parameters for @p peer.
+ *
+ * @param ctx    The DTLS context in effect.
+ * @param peer   The remote party where the packet is sent.
+ * @param type   The content type of this record.
+ * @param buf    The data to send.
+ * @param buflen The number of bytes to send from @p buf.
+ * @return Less than zero in case of an error or the number of
+ *   bytes that have been sent otherwise.
+ */
+static int
+dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
+               dtls_security_parameters_t *security , session_t *session,
+               unsigned char type, uint8 *buf_array[],
+               size_t buf_len_array[], size_t buf_array_len)
+{
+  /* We cannot use ctx->sendbuf here as it is reserved for collecting
+   * the input for this function, i.e. buf == ctx->sendbuf.
+   *
+   * TODO: check if we can use the receive buf here. This would mean
+   * that we might not be able to handle multiple records stuffed in
+   * one UDP datagram */
+  unsigned char sendbuf[DTLS_MAX_BUF];
+  size_t len = sizeof(sendbuf);
+  int res;
+  unsigned int i;
+  size_t overall_len = 0;
+
+  res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
+
+  if (res < 0)
+    return res;
+
+  /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
+  /*   update_hs_hash(peer, buf, buflen); */
+
+  dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
+  for (i = 0; i < buf_array_len; i++) {
+    dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
+    overall_len += buf_len_array[i];
+  }
+
+  if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
+      type == DTLS_CT_CHANGE_CIPHER_SPEC) {
+    /* copy handshake messages other than HelloVerify into retransmit buffer */
+    netq_t *n = netq_node_new(overall_len);
+    if (n) {
+      dtls_tick_t now;
+      dtls_ticks(&now);
+      n->t = now + 2 * CLOCK_SECOND;
+      n->retransmit_cnt = 0;
+      n->timeout = 2 * CLOCK_SECOND;
+      n->peer = peer;
+      n->epoch = (security) ? security->epoch : 0;
+      n->type = type;
+      n->length = 0;
+      for (i = 0; i < buf_array_len; i++) {
+        memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
+        n->length += buf_len_array[i];
+      }
+
+      if (!netq_insert_node(ctx->sendqueue, n)) {
+       dtls_warn("cannot add packet to retransmit buffer\n");
+       netq_node_free(n);
+#ifdef WITH_CONTIKI
+      } else {
+       /* must set timer within the context of the retransmit process */
+       PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
+       etimer_set(&ctx->retransmit_timer, n->timeout);
+       PROCESS_CONTEXT_END(&dtls_retransmit_process);
+#else /* WITH_CONTIKI */
+       dtls_debug("copied to sendqueue\n");
+#endif /* WITH_CONTIKI */
+      }
+    } else 
+      dtls_warn("retransmit buffer full\n");
+  }
+
+  /* FIXME: copy to peer's sendqueue (after fragmentation if
+   * necessary) and initialize retransmit timer */
+  res = CALL(ctx, write, session, sendbuf, len);
+
+  /* Guess number of bytes application data actually sent:
+   * dtls_prepare_record() tells us in len the number of bytes to
+   * send, res will contain the bytes actually sent. */
+  return res <= 0 ? res : overall_len - (len - res);
+}
+
+static inline int
+dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
+               dtls_alert_t description) {
+  uint8_t msg[] = { level, description };
+
+  dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
+  return 0;
+}
+
+int 
+dtls_close(dtls_context_t *ctx, const session_t *remote) {
+  int res = -1;
+  dtls_peer_t *peer;
+
+  peer = dtls_get_peer(ctx, remote);
+
+  if (peer) {
+    res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
+    /* indicate tear down */
+    peer->state = DTLS_STATE_CLOSING;
+  }
+  return res;
+}
+
+static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
+{
+  if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
+    dtls_close(ctx, &peer->session);
+  if (unlink) {
+#ifndef WITH_CONTIKI
+    HASH_DEL_PEER(ctx->peers, peer);
+#else /* WITH_CONTIKI */
+    list_remove(ctx->peers, peer);
+#endif /* WITH_CONTIKI */
+
+    dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
+  }
+  dtls_free_peer(peer);
+}
+
+/**
+ * Checks a received Client Hello message for a valid cookie. When the
+ * Client Hello contains no cookie, the function fails and a Hello
+ * Verify Request is sent to the peer (using the write callback function
+ * registered with \p ctx). The return value is \c -1 on error, \c 0 when
+ * undecided, and \c 1 if the Client Hello was good. 
+ * 
+ * \param ctx     The DTLS context.
+ * \param peer    The remote party we are talking to, if any.
+ * \param session Transport address of the remote peer.
+ * \param state   Current state of the connection.
+ * \param msg     The received datagram.
+ * \param msglen  Length of \p msg.
+ * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
+ * \c -1 otherwise.
+ */
+static int
+dtls_verify_peer(dtls_context_t *ctx, 
+                dtls_peer_t *peer, 
+                session_t *session,
+                const dtls_state_t state,
+                uint8 *data, size_t data_length)
+{
+  uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
+  uint8 *p = buf;
+  int len = DTLS_COOKIE_LENGTH;
+  uint8 *cookie = NULL;
+  int err;
+#undef mycookie
+#define mycookie (buf + DTLS_HV_LENGTH)
+
+  /* Store cookie where we can reuse it for the HelloVerify request. */
+  err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
+  if (err < 0)
+    return err;
+
+  dtls_debug_dump("create cookie", mycookie, len);
+
+  assert(len == DTLS_COOKIE_LENGTH);
+    
+  /* Perform cookie check. */
+  len = dtls_get_cookie(data, data_length, &cookie);
+  if (len < 0) {
+    dtls_warn("error while fetching the cookie, err: %i\n", err);
+    return err;
+  }
+
+  dtls_debug_dump("compare with cookie", cookie, len);
+
+  /* check if cookies match */
+  if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
+    dtls_debug("found matching cookie\n");
+    return 0;
+  }
+
+  if (len > 0) {
+    dtls_debug_dump("invalid cookie", cookie, len);
+  } else {
+    dtls_debug("cookie len is 0!\n");
+  }
+
+  /* ClientHello did not contain any valid cookie, hence we send a
+   * HelloVerify request. */
+
+  dtls_int_to_uint16(p, DTLS_VERSION);
+  p += sizeof(uint16);
+
+  dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
+  p += sizeof(uint8);
+
+  assert(p == mycookie);
+
+  p += DTLS_COOKIE_LENGTH;
+
+  /* TODO use the same record sequence number as in the ClientHello,
+     see 4.2.1. Denial-of-Service Countermeasures */
+  err = dtls_send_handshake_msg_hash(ctx,
+                    state == DTLS_STATE_CONNECTED ? peer : NULL,
+                    session,
+                    DTLS_HT_HELLO_VERIFY_REQUEST,
+                    buf, p - buf, 0);
+  if (err < 0) {
+    dtls_warn("cannot send HelloVerify request\n");
+  }
+  return err; /* HelloVerify is sent, now we cannot do anything but wait */
+
+#undef mycookie
+}
+
+#ifdef DTLS_ECC
+static int
+dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
+                               unsigned char **result_r,
+                               unsigned char **result_s)
+{
+  int i;
+  uint8 *data_orig = data;
+
+  if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
+    dtls_alert("only sha256 is supported in certificate verify\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
+    dtls_alert("only ecdsa signature is supported in client verify\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  if (data_length < dtls_uint16_to_int(data)) {
+    dtls_alert("signature length wrong\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint16);
+  data_length -= sizeof(uint16);
+
+  if (dtls_uint8_to_int(data) != 0x30) {
+    dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  if (data_length < dtls_uint8_to_int(data)) {
+    dtls_alert("signature length wrong\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  if (dtls_uint8_to_int(data) != 0x02) {
+    dtls_alert("wrong ASN.1 struct, expected Integer\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  i = dtls_uint8_to_int(data);
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  /* Sometimes these values have a leeding 0 byte */
+  *result_r = data + i - DTLS_EC_KEY_SIZE;
+
+  data += i;
+  data_length -= i;
+
+  if (dtls_uint8_to_int(data) != 0x02) {
+    dtls_alert("wrong ASN.1 struct, expected Integer\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  i = dtls_uint8_to_int(data);
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  /* Sometimes these values have a leeding 0 byte */
+  *result_s = data + i - DTLS_EC_KEY_SIZE;
+
+  data += i;
+  data_length -= i;
+
+  return data - data_orig;
+}
+
+static int
+check_client_certificate_verify(dtls_context_t *ctx, 
+                               dtls_peer_t *peer,
+                               uint8 *data, size_t data_length)
+{
+  dtls_handshake_parameters_t *config = peer->handshake_params;
+  int ret;
+  unsigned char *result_r;
+  unsigned char *result_s;
+  dtls_hash_ctx hs_hash;
+  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
+
+  assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
+
+  data += DTLS_HS_LENGTH;
+
+  if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
+    dtls_alert("the packet length does not match the expected\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+
+  ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
+  if (ret < 0) {
+    return ret;
+  }
+  data += ret;
+  data_length -= ret;
+
+  copy_hs_hash(peer, &hs_hash);
+
+  dtls_hash_finalize(sha256hash, &hs_hash);
+
+  ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecdsa.other_pub_x, config->keyx.ecdsa.other_pub_y,
+                           sizeof(config->keyx.ecdsa.other_pub_x),
+                           sha256hash, sizeof(sha256hash),
+                           result_r, result_s);
+
+  if (ret < 0) {
+    dtls_alert("wrong signature err: %i\n", ret);
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+  return 0;
+}
+#endif /* DTLS_ECC */
+
+static int
+dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
+{
+  /* Ensure that the largest message to create fits in our source
+   * buffer. (The size of the destination buffer is checked by the
+   * encoding function, so we do not need to guess.) */
+  uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
+  uint8 *p;
+  int ecdsa;
+  uint8 extension_size;
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+  dtls_tick_t now;
+
+  ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
+
+  extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
+
+  /* Handshake header */
+  p = buf;
+
+  /* ServerHello */
+  dtls_int_to_uint16(p, DTLS_VERSION);
+  p += sizeof(uint16);
+
+  /* Set server random: First 4 bytes are the server's Unix timestamp,
+   * followed by 28 bytes of generate random data. */
+  dtls_ticks(&now);
+  dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
+  dtls_prng(handshake->tmp.random.server + 4, 28);
+
+  memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
+  p += DTLS_RANDOM_LENGTH;
+
+  *p++ = 0;                    /* no session id */
+
+  if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
+    /* selected cipher suite */
+    dtls_int_to_uint16(p, handshake->cipher);
+    p += sizeof(uint16);
+
+    /* selected compression method */
+    *p++ = compression_methods[handshake->compression];
+  }
+
+  if (extension_size) {
+    /* length of the extensions */
+    dtls_int_to_uint16(p, extension_size - 2);
+    p += sizeof(uint16);
+  }
+
+  if (ecdsa) {
+    /* client certificate type extension */
+    dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
+    p += sizeof(uint16);
+
+    /* length of this extension type */
+    dtls_int_to_uint16(p, 1);
+    p += sizeof(uint16);
+
+    dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
+    p += sizeof(uint8);
+
+    /* client certificate type extension */
+    dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
+    p += sizeof(uint16);
+
+    /* length of this extension type */
+    dtls_int_to_uint16(p, 1);
+    p += sizeof(uint16);
+
+    dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
+    p += sizeof(uint8);
+
+    /* ec_point_formats */
+    dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
+    p += sizeof(uint16);
+
+    /* length of this extension type */
+    dtls_int_to_uint16(p, 2);
+    p += sizeof(uint16);
+
+    /* number of supported formats */
+    dtls_int_to_uint8(p, 1);
+    p += sizeof(uint8);
+
+    dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
+    p += sizeof(uint8);
+  }
+
+  assert(p - buf <= sizeof(buf));
+
+  /* TODO use the same record sequence number as in the ClientHello,
+     see 4.2.1. Denial-of-Service Countermeasures */
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
+                                buf, p - buf);
+}
+
+#ifdef DTLS_ECC
+static int
+dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
+                           const dtls_ecdsa_key_t *key)
+{
+  uint8 buf[DTLS_CE_LENGTH];
+  uint8 *p;
+
+  /* Certificate 
+   *
+   * Start message construction at beginning of buffer. */
+  p = buf;
+
+  dtls_int_to_uint24(p, 94);   /* certificates length */
+  p += sizeof(uint24);
+
+  dtls_int_to_uint24(p, 91);   /* length of this certificate */
+  p += sizeof(uint24);
+  
+  memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
+  p += sizeof(cert_asn1_header);
+
+  memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
+  p += DTLS_EC_KEY_SIZE;
+
+  memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
+  p += DTLS_EC_KEY_SIZE;
+
+  assert(p - buf <= sizeof(buf));
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
+                                buf, p - buf);
+}
+
+static uint8 *
+dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
+{
+  int len_r;
+  int len_s;
+
+#define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
+#define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
+  /* store the pointer to the r component of the signature and make space */
+  len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
+  len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
+
+#undef R_KEY_OFFSET
+#undef S_KEY_OFFSET
+
+  /* sha256 */
+  dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
+  p += sizeof(uint8);
+
+  /* ecdsa */
+  dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
+  p += sizeof(uint8);
+
+  /* length of signature */
+  dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
+  p += sizeof(uint16);
+
+  /* ASN.1 SEQUENCE */
+  dtls_int_to_uint8(p, 0x30);
+  p += sizeof(uint8);
+
+  dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
+  p += sizeof(uint8);
+
+  /* ASN.1 Integer r */
+  dtls_int_to_uint8(p, 0x02);
+  p += sizeof(uint8);
+
+  dtls_int_to_uint8(p, len_r);
+  p += sizeof(uint8);
+
+  /* the pint r was added here */
+  p += len_r;
+
+  /* ASN.1 Integer s */
+  dtls_int_to_uint8(p, 0x02);
+  p += sizeof(uint8);
+
+  dtls_int_to_uint8(p, len_s);
+  p += sizeof(uint8);
+
+  /* the pint s was added here */
+  p += len_s;
+
+  return p;
+}
+
+static int
+dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
+                                  const dtls_ecdsa_key_t *key)
+{
+  /* The ASN.1 Integer representation of an 32 byte unsigned int could be
+   * 33 bytes long add space for that */
+  uint8 buf[DTLS_SKEXEC_LENGTH + 2];
+  uint8 *p;
+  uint8 *key_params;
+  uint8 *ephemeral_pub_x;
+  uint8 *ephemeral_pub_y;
+  uint32_t point_r[9];
+  uint32_t point_s[9];
+  dtls_handshake_parameters_t *config = peer->handshake_params;
+
+  /* ServerKeyExchange 
+   *
+   * Start message construction at beginning of buffer. */
+  p = buf;
+
+  key_params = p;
+  /* ECCurveType curve_type: named_curve */
+  dtls_int_to_uint8(p, 3);
+  p += sizeof(uint8);
+
+  /* NamedCurve namedcurve: secp256r1 */
+  dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
+  p += sizeof(uint16);
+
+  dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
+  p += sizeof(uint8);
+
+  /* This should be an uncompressed point, but I do not have access to the spec. */
+  dtls_int_to_uint8(p, 4);
+  p += sizeof(uint8);
+
+  /* store the pointer to the x component of the pub key and make space */
+  ephemeral_pub_x = p;
+  p += DTLS_EC_KEY_SIZE;
+
+  /* store the pointer to the y component of the pub key and make space */
+  ephemeral_pub_y = p;
+  p += DTLS_EC_KEY_SIZE;
+
+  dtls_ecdsa_generate_key(config->keyx.ecdsa.own_eph_priv,
+                         ephemeral_pub_x, ephemeral_pub_y,
+                         DTLS_EC_KEY_SIZE);
+
+  /* sign the ephemeral and its paramaters */
+  dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
+                      config->tmp.random.client, DTLS_RANDOM_LENGTH,
+                      config->tmp.random.server, DTLS_RANDOM_LENGTH,
+                      key_params, p - key_params,
+                      point_r, point_s);
+
+  p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
+
+  assert(p - buf <= sizeof(buf));
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
+                                buf, p - buf);
+}
+#endif /* DTLS_ECC */
+
+#ifdef DTLS_PSK
+static int
+dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
+                                 const unsigned char *psk_hint, size_t len)
+{
+  uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
+  uint8 *p;
+
+  p = buf;
+
+  assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
+  if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
+    /* should never happen */
+    dtls_warn("psk identity hint is too long\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+  }
+
+  dtls_int_to_uint16(p, len);
+  p += sizeof(uint16);
+
+  memcpy(p, psk_hint, len);
+  p += len;
+
+  assert(p - buf <= sizeof(buf));
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
+                                buf, p - buf);
+}
+#endif /* DTLS_PSK */
+
+#ifdef DTLS_ECC
+static int
+dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
+{
+  uint8 buf[8];
+  uint8 *p;
+
+  /* ServerHelloDone 
+   *
+   * Start message construction at beginning of buffer. */
+  p = buf;
+
+  /* certificate_types */
+  dtls_int_to_uint8(p, 1);
+  p += sizeof(uint8);
+
+  /* ecdsa_sign */
+  dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
+  p += sizeof(uint8);
+
+  /* supported_signature_algorithms */
+  dtls_int_to_uint16(p, 2);
+  p += sizeof(uint16);
+
+  /* sha256 */
+  dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
+  p += sizeof(uint8);
+
+  /* ecdsa */
+  dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
+  p += sizeof(uint8);
+
+  /* certificate_authoritiess */
+  dtls_int_to_uint16(p, 0);
+  p += sizeof(uint16);
+
+  assert(p - buf <= sizeof(buf));
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
+                                buf, p - buf);
+}
+#endif /* DTLS_ECC */
+
+static int
+dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
+{
+
+  /* ServerHelloDone 
+   *
+   * Start message construction at beginning of buffer. */
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
+                                NULL, 0);
+}
+
+static int
+dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
+{
+  int res;
+
+  res = dtls_send_server_hello(ctx, peer);
+
+  if (res < 0) {
+    dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
+    return res;
+  }
+
+#ifdef DTLS_ECC
+  if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
+    const dtls_ecdsa_key_t *ecdsa_key;
+
+    res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
+    if (res < 0) {
+      dtls_crit("no ecdsa certificate to send in certificate\n");
+      return res;
+    }
+
+    res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
+
+    if (res < 0) {
+      dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
+      return res;
+    }
+
+    res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
+
+    if (res < 0) {
+      dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
+      return res;
+    }
+
+    if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
+       is_ecdsa_client_auth_supported(ctx)) {
+      res = dtls_send_server_certificate_request(ctx, peer);
+
+      if (res < 0) {
+        dtls_debug("dtls_server_hello: cannot prepare certificate Request record\n");
+        return res;
+      }
+    }
+  }
+#endif /* DTLS_ECC */
+
+#ifdef DTLS_PSK
+  if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
+    unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
+    int len;
+
+    /* The identity hint is optional, therefore we ignore the result
+     * and check psk only. */
+    len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
+              NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
+
+    if (len < 0) {
+      dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
+      return len;
+    }
+
+    if (len > 0) {
+      res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
+
+      if (res < 0) {
+       dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
+       return res;
+      }
+    }
+  }
+#endif /* DTLS_PSK */
+
+  res = dtls_send_server_hello_done(ctx, peer);
+
+  if (res < 0) {
+    dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
+    return res;
+  }
+  return 0;
+}
+
+static inline int 
+dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
+  uint8 buf[1] = {1};
+
+  return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
+}
+
+    
+static int
+dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
+{
+  uint8 buf[DTLS_CKXEC_LENGTH];
+  uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
+  uint8 *p;
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+
+  p = buf;
+
+  switch (handshake->cipher) {
+#ifdef DTLS_PSK
+  case TLS_PSK_WITH_AES_128_CCM_8: {
+    int len;
+
+    len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
+               NULL, 0,
+               client_id,
+               sizeof(client_id));
+    if (len < 0) {
+      dtls_crit("no psk identity set in kx\n");
+      return len;
+    }
+
+    if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
+      dtls_warn("the psk identity is too long\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    dtls_int_to_uint16(p, len);
+    p += sizeof(uint16);
+
+    memcpy(p, client_id, len);
+    p += len;
+
+    break;
+  }
+#endif /* DTLS_PSK */
+#ifdef DTLS_ECC
+  case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: {
+    uint8 *ephemeral_pub_x;
+    uint8 *ephemeral_pub_y;
+
+    dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
+    p += sizeof(uint8);
+
+    /* This should be an uncompressed point, but I do not have access to the spec. */
+    dtls_int_to_uint8(p, 4);
+    p += sizeof(uint8);
+
+    ephemeral_pub_x = p;
+    p += DTLS_EC_KEY_SIZE;
+    ephemeral_pub_y = p;
+    p += DTLS_EC_KEY_SIZE;
+
+    dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecdsa.own_eph_priv,
+                           ephemeral_pub_x, ephemeral_pub_y,
+                           DTLS_EC_KEY_SIZE);
+
+    break;
+  }
+#endif /* DTLS_ECC */
+  default:
+    dtls_crit("cipher not supported\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+  }
+
+  assert(p - buf <= sizeof(buf));
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
+                                buf, p - buf);
+}
+
+#ifdef DTLS_ECC
+static int
+dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
+                                  const dtls_ecdsa_key_t *key)
+{
+  /* The ASN.1 Integer representation of an 32 byte unsigned int could be
+   * 33 bytes long add space for that */
+  uint8 buf[DTLS_CV_LENGTH + 2];
+  uint8 *p;
+  uint32_t point_r[9];
+  uint32_t point_s[9];
+  dtls_hash_ctx hs_hash;
+  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
+
+  /* ServerKeyExchange 
+   *
+   * Start message construction at beginning of buffer. */
+  p = buf;
+
+  copy_hs_hash(peer, &hs_hash);
+
+  dtls_hash_finalize(sha256hash, &hs_hash);
+
+  /* sign the ephemeral and its paramaters */
+  dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
+                            sha256hash, sizeof(sha256hash),
+                            point_r, point_s);
+
+  p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
+
+  assert(p - buf <= sizeof(buf));
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
+                                buf, p - buf);
+}
+#endif /* DTLS_ECC */
+
+static int
+dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
+                  const unsigned char *label, size_t labellen)
+{
+  int length;
+  uint8 hash[DTLS_HMAC_MAX];
+  uint8 buf[DTLS_FIN_LENGTH];
+  dtls_hash_ctx hs_hash;
+  uint8 *p = buf;
+
+  copy_hs_hash(peer, &hs_hash);
+
+  length = dtls_hash_finalize(hash, &hs_hash);
+
+  dtls_prf(peer->handshake_params->tmp.master_secret,
+          DTLS_MASTER_SECRET_LENGTH,
+          label, labellen,
+          PRF_LABEL(finished), PRF_LABEL_SIZE(finished), 
+          hash, length,
+          p, DTLS_FIN_LENGTH);
+
+  dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
+
+  p += DTLS_FIN_LENGTH;
+
+  assert(p - buf <= sizeof(buf));
+
+  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
+                                buf, p - buf);
+}
+
+static int
+dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
+                       uint8 cookie[], size_t cookie_length) {
+  uint8 buf[DTLS_CH_LENGTH_MAX];
+  uint8 *p = buf;
+  uint8_t cipher_size;
+  uint8_t extension_size;
+  int psk;
+  int ecdsa;
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+  dtls_tick_t now;
+
+  psk = is_psk_supported(ctx);
+  ecdsa = is_ecdsa_supported(ctx, 1);
+
+  cipher_size = 2 + ((ecdsa) ? 2 : 0) + ((psk) ? 2 : 0);
+  extension_size = (ecdsa) ? 2 + 6 + 6 + 8 + 6: 0;
+
+  if (cipher_size == 0) {
+    dtls_crit("no cipher callbacks implemented\n");
+  }
+
+  dtls_int_to_uint16(p, DTLS_VERSION);
+  p += sizeof(uint16);
+
+  if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
+    dtls_warn("the cookie is too long\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+
+  if (cookie_length == 0) {
+    /* Set client random: First 4 bytes are the client's Unix timestamp,
+     * followed by 28 bytes of generate random data. */
+    dtls_ticks(&now);
+    dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
+    dtls_prng(handshake->tmp.random.client + sizeof(uint32),
+         DTLS_RANDOM_LENGTH - sizeof(uint32));
+  }
+  /* we must use the same Client Random as for the previous request */
+  memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
+  p += DTLS_RANDOM_LENGTH;
+
+  /* session id (length 0) */
+  dtls_int_to_uint8(p, 0);
+  p += sizeof(uint8);
+
+  /* cookie */
+  dtls_int_to_uint8(p, cookie_length);
+  p += sizeof(uint8);
+  if (cookie_length != 0) {
+    memcpy(p, cookie, cookie_length);
+    p += cookie_length;
+  }
+
+  /* add known cipher(s) */
+  dtls_int_to_uint16(p, cipher_size - 2);
+  p += sizeof(uint16);
+
+  if (ecdsa) {
+    dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
+    p += sizeof(uint16);
+  }
+  if (psk) {
+    dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
+    p += sizeof(uint16);
+  }
+
+  /* compression method */
+  dtls_int_to_uint8(p, 1);
+  p += sizeof(uint8);
+
+  dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
+  p += sizeof(uint8);
+
+  if (extension_size) {
+    /* length of the extensions */
+    dtls_int_to_uint16(p, extension_size - 2);
+    p += sizeof(uint16);
+  }
+
+  if (ecdsa) {
+    /* client certificate type extension */
+    dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
+    p += sizeof(uint16);
+
+    /* length of this extension type */
+    dtls_int_to_uint16(p, 2);
+    p += sizeof(uint16);
+
+    /* length of the list */
+    dtls_int_to_uint8(p, 1);
+    p += sizeof(uint8);
+
+    dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
+    p += sizeof(uint8);
+
+    /* client certificate type extension */
+    dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
+    p += sizeof(uint16);
+
+    /* length of this extension type */
+    dtls_int_to_uint16(p, 2);
+    p += sizeof(uint16);
+
+    /* length of the list */
+    dtls_int_to_uint8(p, 1);
+    p += sizeof(uint8);
+
+    dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
+    p += sizeof(uint8);
+
+    /* elliptic_curves */
+    dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
+    p += sizeof(uint16);
+
+    /* length of this extension type */
+    dtls_int_to_uint16(p, 4);
+    p += sizeof(uint16);
+
+    /* length of the list */
+    dtls_int_to_uint16(p, 2);
+    p += sizeof(uint16);
+
+    dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
+    p += sizeof(uint16);
+
+    /* ec_point_formats */
+    dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
+    p += sizeof(uint16);
+
+    /* length of this extension type */
+    dtls_int_to_uint16(p, 2);
+    p += sizeof(uint16);
+
+    /* number of supported formats */
+    dtls_int_to_uint8(p, 1);
+    p += sizeof(uint8);
+
+    dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
+    p += sizeof(uint8);
+  }
+
+  assert(p - buf <= sizeof(buf));
+
+  if (cookie_length != 0)
+    clear_hs_hash(peer);
+
+  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
+                                     DTLS_HT_CLIENT_HELLO,
+                                     buf, p - buf, cookie_length != 0);
+}
+
+static int
+check_server_hello(dtls_context_t *ctx, 
+                     dtls_peer_t *peer,
+                     uint8 *data, size_t data_length)
+{
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+
+  /* This function is called when we expect a ServerHello (i.e. we
+   * have sent a ClientHello).  We might instead receive a HelloVerify
+   * request containing a cookie. If so, we must repeat the
+   * ClientHello with the given Cookie.
+   */
+  if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+
+  update_hs_hash(peer, data, data_length);
+
+  /* FIXME: check data_length before accessing fields */
+
+  /* Get the server's random data and store selected cipher suite
+   * and compression method (like dtls_update_parameters().
+   * Then calculate master secret and wait for ServerHelloDone. When received,
+   * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
+    
+  /* check server version */
+  data += DTLS_HS_LENGTH;
+  data_length -= DTLS_HS_LENGTH;
+    
+  if (dtls_uint16_to_int(data) != DTLS_VERSION) {
+    dtls_alert("unknown DTLS version\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
+  }
+
+  data += sizeof(uint16);            /* skip version field */
+  data_length -= sizeof(uint16);
+
+  /* store server random data */
+  memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
+  /* skip server random */
+  data += DTLS_RANDOM_LENGTH;
+  data_length -= DTLS_RANDOM_LENGTH;
+
+  SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
+    
+  /* Check cipher suite. As we offer all we have, it is sufficient
+   * to check if the cipher suite selected by the server is in our
+   * list of known cipher suites. Subsets are not supported. */
+  handshake->cipher = dtls_uint16_to_int(data);
+  if (!known_cipher(ctx, handshake->cipher, 1)) {
+    dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
+            data[0], data[1]);
+    return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
+  }
+  data += sizeof(uint16);
+  data_length -= sizeof(uint16);
+
+  /* Check if NULL compression was selected. We do not know any other. */
+  if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
+    dtls_alert("unsupported compression method 0x%02x\n", data[0]);
+    return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  return dtls_check_tls_extension(peer, data, data_length, 0);
+
+error:
+  return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+}
+
+static int
+check_server_hello_verify_request(dtls_context_t *ctx,
+                                 dtls_peer_t *peer,
+                                 uint8 *data, size_t data_length)
+{
+  dtls_hello_verify_t *hv;
+  int res;
+
+  if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+
+  hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
+
+  res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
+
+  if (res < 0)
+    dtls_warn("cannot send ClientHello\n");
+
+  return res;
+}
+
+#ifdef DTLS_ECC
+static int
+check_server_certificate(dtls_context_t *ctx, 
+                        dtls_peer_t *peer,
+                        uint8 *data, size_t data_length)
+{
+  int err;
+  dtls_handshake_parameters_t *config = peer->handshake_params;
+
+  update_hs_hash(peer, data, data_length);
+
+  assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
+
+  data += DTLS_HS_LENGTH;
+
+  if (dtls_uint24_to_int(data) != 94) {
+    dtls_alert("expect length of 94 bytes for server certificate message\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint24);
+
+  if (dtls_uint24_to_int(data) != 91) {
+    dtls_alert("expect length of 91 bytes for certificate\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint24);
+
+  if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
+    dtls_alert("got an unexpected Subject public key format\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(cert_asn1_header);
+
+  memcpy(config->keyx.ecdsa.other_pub_x, data,
+        sizeof(config->keyx.ecdsa.other_pub_x));
+  data += sizeof(config->keyx.ecdsa.other_pub_x);
+
+  memcpy(config->keyx.ecdsa.other_pub_y, data,
+        sizeof(config->keyx.ecdsa.other_pub_y));
+  data += sizeof(config->keyx.ecdsa.other_pub_y);
+
+  err = CALL(ctx, verify_ecdsa_key, &peer->session,
+            config->keyx.ecdsa.other_pub_x,
+            config->keyx.ecdsa.other_pub_y,
+            sizeof(config->keyx.ecdsa.other_pub_x));
+  if (err < 0) {
+    dtls_warn("The certificate was not accepted\n");
+    return err;
+  }
+
+  return 0;
+}
+
+static int
+check_server_key_exchange_ecdsa(dtls_context_t *ctx,
+                               dtls_peer_t *peer,
+                               uint8 *data, size_t data_length)
+{
+  dtls_handshake_parameters_t *config = peer->handshake_params;
+  int ret;
+  unsigned char *result_r;
+  unsigned char *result_s;
+  unsigned char *key_params;
+
+  update_hs_hash(peer, data, data_length);
+
+  assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
+
+  data += DTLS_HS_LENGTH;
+
+  if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
+    dtls_alert("the packet length does not match the expected\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  key_params = data;
+
+  if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
+    dtls_alert("Only named curves supported\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
+    dtls_alert("secp256r1 supported\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+  data += sizeof(uint16);
+  data_length -= sizeof(uint16);
+
+  if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
+    dtls_alert("expected 65 bytes long public point\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  if (dtls_uint8_to_int(data) != 4) {
+    dtls_alert("expected uncompressed public point\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  data += sizeof(uint8);
+  data_length -= sizeof(uint8);
+
+  memcpy(config->keyx.ecdsa.other_eph_pub_x, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
+  data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
+  data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
+
+  memcpy(config->keyx.ecdsa.other_eph_pub_y, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
+  data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
+  data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
+
+  ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
+  if (ret < 0) {
+    return ret;
+  }
+  data += ret;
+  data_length -= ret;
+
+  ret = dtls_ecdsa_verify_sig(config->keyx.ecdsa.other_pub_x, config->keyx.ecdsa.other_pub_y,
+                           sizeof(config->keyx.ecdsa.other_pub_x),
+                           config->tmp.random.client, DTLS_RANDOM_LENGTH,
+                           config->tmp.random.server, DTLS_RANDOM_LENGTH,
+                           key_params,
+                           1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
+                           result_r, result_s);
+
+  if (ret < 0) {
+    dtls_alert("wrong signature\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+  return 0;
+}
+#endif /* DTLS_ECC */
+
+#ifdef DTLS_PSK
+static int
+check_server_key_exchange_psk(dtls_context_t *ctx,
+                             dtls_peer_t *peer,
+                             uint8 *data, size_t data_length)
+{
+  dtls_handshake_parameters_t *config = peer->handshake_params;
+  uint16_t len;
+
+  update_hs_hash(peer, data, data_length);
+
+  assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
+
+  data += DTLS_HS_LENGTH;
+
+  if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
+    dtls_alert("the packet length does not match the expected\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+
+  len = dtls_uint16_to_int(data);
+  data += sizeof(uint16);
+
+  if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
+    dtls_warn("the length of the server identity hint is worng\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+
+  if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
+    dtls_warn("please use a smaller server identity hint\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+  }
+
+  /* store the psk_identity_hint in config->keyx.psk for later use */
+  config->keyx.psk.id_length = len;
+  memcpy(config->keyx.psk.identity, data, len);
+  return 0;
+}
+#endif /* DTLS_PSK */
+
+static int
+check_certificate_request(dtls_context_t *ctx, 
+                         dtls_peer_t *peer,
+                         uint8 *data, size_t data_length)
+{
+  unsigned int i;
+  int auth_alg;
+  int sig_alg;
+  int hash_alg;
+
+  update_hs_hash(peer, data, data_length);
+
+  assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
+
+  data += DTLS_HS_LENGTH;
+
+  if (data_length < DTLS_HS_LENGTH + 5) {
+    dtls_alert("the packet length does not match the expected\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+
+  i = dtls_uint8_to_int(data);
+  data += sizeof(uint8);
+  if (i + 1 > data_length) {
+    dtls_alert("the cerfificate types are too long\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+
+  auth_alg = 0;
+  for (; i > 0 ; i -= sizeof(uint8)) {
+    if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
+       && auth_alg == 0)
+      auth_alg = dtls_uint8_to_int(data);
+    data += sizeof(uint8);
+  }
+
+  if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
+    dtls_alert("the request authentication algorithm is not supproted\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+
+  i = dtls_uint16_to_int(data);
+  data += sizeof(uint16);
+  if (i + 1 > data_length) {
+    dtls_alert("the signature and hash algorithm list is too long\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+
+  hash_alg = 0;
+  sig_alg = 0;
+  for (; i > 0 ; i -= sizeof(uint16)) {
+    int current_hash_alg;
+    int current_sig_alg;
+
+    current_hash_alg = dtls_uint8_to_int(data);
+    data += sizeof(uint8);
+    current_sig_alg = dtls_uint8_to_int(data);
+    data += sizeof(uint8);
+
+    if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 && 
+        current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
+      hash_alg = current_hash_alg;
+      sig_alg = current_sig_alg;
+    }
+  }
+
+  if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
+      sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
+    dtls_alert("no supported hash and signature algorithem\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+  }
+
+  /* common names are ignored */
+
+  peer->handshake_params->do_client_auth = 1;
+  return 0;
+}
+
+static int
+check_server_hellodone(dtls_context_t *ctx, 
+                     dtls_peer_t *peer,
+                     uint8 *data, size_t data_length)
+{
+  int res;
+#ifdef DTLS_ECC
+  const dtls_ecdsa_key_t *ecdsa_key;
+#endif /* DTLS_ECC */
+
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+
+  /* calculate master key, send CCS */
+
+  update_hs_hash(peer, data, data_length);
+
+#ifdef DTLS_ECC
+  if (handshake->do_client_auth) {
+
+    res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
+    if (res < 0) {
+      dtls_crit("no ecdsa certificate to send in certificate\n");
+      return res;
+    }
+
+    res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
+
+    if (res < 0) {
+      dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
+      return res;
+    }
+  }
+#endif /* DTLS_ECC */
+
+  /* send ClientKeyExchange */
+  res = dtls_send_client_key_exchange(ctx, peer);
+
+  if (res < 0) {
+    dtls_debug("cannot send KeyExchange message\n");
+    return res;
+  }
+
+#ifdef DTLS_ECC
+  if (handshake->do_client_auth) {
+
+    res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
+
+    if (res < 0) {
+      dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
+      return res;
+    }
+  }
+#endif /* DTLS_ECC */
+
+  res = calculate_key_block(ctx, handshake, peer,
+                           &peer->session, peer->role);
+  if (res < 0) {
+    return res;
+  }
+
+  res = dtls_send_ccs(ctx, peer);
+  if (res < 0) {
+    dtls_debug("cannot send CCS message\n");
+    return res;
+  }
+
+  /* and switch cipher suite */
+  dtls_security_params_switch(peer);
+
+  /* Client Finished */
+  return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
+}
+
+static int
+decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
+              uint8 **cleartext)
+{
+  dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
+  dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
+  int clen;
+  
+  *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
+  clen = length - sizeof(dtls_record_header_t);
+
+  if (!security) {
+    dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
+    return -1;
+  }
+
+  if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
+    /* no cipher suite selected */
+    return clen;
+  } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
+    /** 
+     * length of additional_data for the AEAD cipher which consists of
+     * seq_num(2+6) + type(1) + version(2) + length(2)
+     */
+#define A_DATA_LEN 13
+    unsigned char nonce[DTLS_CCM_BLOCKSIZE];
+    unsigned char A_DATA[A_DATA_LEN];
+
+    if (clen < 16)             /* need at least IV and MAC */
+      return -1;
+
+    memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
+    memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
+          dtls_kb_iv_size(security, peer->role));
+
+    /* read epoch and seq_num from message */
+    memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
+    *cleartext += 8;
+    clen -= 8;
+
+    dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
+    dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
+                   dtls_kb_key_size(security, peer->role));
+    dtls_debug_dump("ciphertext", *cleartext, clen);
+
+    /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
+     * 
+     * additional_data = seq_num + TLSCompressed.type +
+     *                   TLSCompressed.version + TLSCompressed.length;
+     */
+    memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
+    memcpy(A_DATA + 8,  &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
+    dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
+
+    clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
+                      dtls_kb_remote_write_key(security, peer->role),
+                      dtls_kb_key_size(security, peer->role),
+                      A_DATA, A_DATA_LEN);
+    if (clen < 0)
+      dtls_warn("decryption failed\n");
+    else {
+#ifndef NDEBUG
+      printf("decrypt_verify(): found %i bytes cleartext\n", clen);
+#endif
+      dtls_security_params_free_other(peer);
+      dtls_debug_dump("cleartext", *cleartext, clen);
+    }
+  }
+  return clen;
+}
+
+static int
+dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
+{
+  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
+                                     DTLS_HT_HELLO_REQUEST,
+                                     NULL, 0, 0);
+}
+
+int
+dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
+{
+  dtls_peer_t *peer = NULL;
+  int err;
+
+  peer = dtls_get_peer(ctx, dst);
+
+  if (!peer) {
+    return -1;
+  }
+  if (peer->state != DTLS_STATE_CONNECTED)
+    return -1;
+
+  peer->handshake_params = dtls_handshake_new();
+  if (!peer->handshake_params)
+    return -1;
+
+  peer->handshake_params->hs_state.mseq_r = 0;
+  peer->handshake_params->hs_state.mseq_s = 0;
+
+  if (peer->role == DTLS_CLIENT) {
+    /* send ClientHello with empty Cookie */
+    err = dtls_send_client_hello(ctx, peer, NULL, 0);
+    if (err < 0)
+      dtls_warn("cannot send ClientHello\n");
+    else
+      peer->state = DTLS_STATE_CLIENTHELLO;
+    return err;
+  } else if (peer->role == DTLS_SERVER) {
+    return dtls_send_hello_request(ctx, peer);
+  }
+
+  return -1;
+}
+
+static int
+handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
+                const dtls_peer_type role, const dtls_state_t state,
+                uint8 *data, size_t data_length) {
+
+  int err = 0;
+
+  /* This will clear the retransmission buffer if we get an expected
+   * handshake message. We have to make sure that no handshake message
+   * should get expected when we still should retransmit something, when
+   * we do everything accordingly to the DTLS 1.2 standard this should
+   * not be a problem. */
+  if (peer) {
+    dtls_stop_retransmission(ctx, peer);
+  }
+
+  /* The following switch construct handles the given message with
+   * respect to the current internal state for this peer. In case of
+   * error, it is left with return 0. */
+
+  dtls_debug("handle handshake packet of type: %s (%i)\n",
+            dtls_handshake_type_to_name(data[0]), data[0]);
+  switch (data[0]) {
+
+  /************************************************************************
+   * Client states
+   ************************************************************************/
+  case DTLS_HT_HELLO_VERIFY_REQUEST:
+
+    if (state != DTLS_STATE_CLIENTHELLO) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    err = check_server_hello_verify_request(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
+      return err;
+    }
+
+    break;
+  case DTLS_HT_SERVER_HELLO:
+
+    if (state != DTLS_STATE_CLIENTHELLO) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    err = check_server_hello(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_server_hello err: %i\n", err);
+      return err;
+    }
+    if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
+      peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE;
+    else
+      peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
+    /* update_hs_hash(peer, data, data_length); */
+
+    break;
+
+#ifdef DTLS_ECC
+  case DTLS_HT_CERTIFICATE:
+
+    if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
+        (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+    err = check_server_certificate(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_server_certificate err: %i\n", err);
+      return err;
+    }
+    if (role == DTLS_CLIENT) {
+      peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
+    } else if (role == DTLS_SERVER){
+      peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
+    }
+    /* update_hs_hash(peer, data, data_length); */
+
+    break;
+#endif /* DTLS_ECC */
+
+  case DTLS_HT_SERVER_KEY_EXCHANGE:
+
+#ifdef DTLS_ECC
+    if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
+      if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
+        return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+      }
+      err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
+    }
+#endif /* DTLS_ECC */
+#ifdef DTLS_PSK
+    if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
+      if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
+        return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+      }
+      err = check_server_key_exchange_psk(ctx, peer, data, data_length);
+    }
+#endif /* DTLS_PSK */
+
+    if (err < 0) {
+      dtls_warn("error in check_server_key_exchange err: %i\n", err);
+      return err;
+    }
+    peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
+    /* update_hs_hash(peer, data, data_length); */
+
+    break;
+
+  case DTLS_HT_SERVER_HELLO_DONE:
+
+    if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    err = check_server_hellodone(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_server_hellodone err: %i\n", err);
+      return err;
+    }
+    peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
+    /* update_hs_hash(peer, data, data_length); */
+
+    break;
+
+  case DTLS_HT_CERTIFICATE_REQUEST:
+
+    if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    err = check_certificate_request(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_certificate_request err: %i\n", err);
+      return err;
+    }
+
+    break;
+
+  case DTLS_HT_FINISHED:
+    /* expect a Finished message from server */
+
+    if (state != DTLS_STATE_WAIT_FINISHED) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    err = check_finished(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_finished err: %i\n", err);
+      return err;
+    }
+    if (role == DTLS_SERVER) {
+      /* send ServerFinished */
+      update_hs_hash(peer, data, data_length);
+
+      /* send change cipher spec message and switch to new configuration */
+      err = dtls_send_ccs(ctx, peer);
+      if (err < 0) {
+        dtls_warn("cannot send CCS message\n");
+        return err;
+      }
+
+      dtls_security_params_switch(peer);
+
+      err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
+      if (err < 0) {
+        dtls_warn("sending server Finished failed\n");
+        return err;
+      }
+    }
+    dtls_handshake_free(peer->handshake_params);
+    peer->handshake_params = NULL;
+    dtls_debug("Handshake complete\n");
+    check_stack();
+    peer->state = DTLS_STATE_CONNECTED;
+
+    /* return here to not increase the message receive counter */
+    return err;
+
+  /************************************************************************
+   * Server states
+   ************************************************************************/
+
+  case DTLS_HT_CLIENT_KEY_EXCHANGE:
+    /* handle ClientHello, update msg and msglen and goto next if not finished */
+
+    if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_client_keyexchange err: %i\n", err);
+      return err;
+    }
+    update_hs_hash(peer, data, data_length);
+
+    if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
+       is_ecdsa_client_auth_supported(ctx))
+      peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY;
+    else
+      peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
+    break;
+
+#ifdef DTLS_ECC
+  case DTLS_HT_CERTIFICATE_VERIFY:
+
+    if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    err = check_client_certificate_verify(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in check_client_certificate_verify err: %i\n", err);
+      return err;
+    }
+
+    update_hs_hash(peer, data, data_length);
+    peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
+    break;
+#endif /* DTLS_ECC */
+
+  case DTLS_HT_CLIENT_HELLO:
+
+    if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
+       (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
+      return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+    }
+
+    /* When no DTLS state exists for this peer, we only allow a
+       Client Hello message with
+
+       a) a valid cookie, or
+       b) no cookie.
+
+       Anything else will be rejected. Fragementation is not allowed
+       here as it would require peer state as well.
+    */
+    err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
+    if (err < 0) {
+      dtls_warn("error in dtls_verify_peer err: %i\n", err);
+      return err;
+    }
+
+    if (err > 0) {
+      dtls_debug("server hello verify was sent\n");
+      break;
+    }
+
+    /* At this point, we have a good relationship with this peer. This
+     * state is left for re-negotiation of key material. */
+     /* As per RFC 6347 - section 4.2.8 if this is an attempt to
+      * rehandshake, we can delete the existing key material
+      * as the client has demonstrated reachibility by completing
+      * the cookie exchange */
+    if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
+       dtls_debug("removing the peer\n");
+#ifndef WITH_CONTIKI
+       HASH_DEL_PEER(ctx->peers, peer);
+#else  /* WITH_CONTIKI */
+       list_remove(ctx->peers, peer);
+#endif /* WITH_CONTIKI */
+
+       dtls_free_peer(peer);
+       peer = NULL;
+    }
+    if (!peer) {
+      dtls_debug("creating new peer\n");
+      dtls_security_parameters_t *security;
+
+      /* msg contains a Client Hello with a valid cookie, so we can
+       * safely create the server state machine and continue with
+       * the handshake. */
+      peer = dtls_new_peer(session);
+      if (!peer) {
+        dtls_alert("cannot create peer\n");
+        return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+      }
+      peer->role = DTLS_SERVER;
+
+      /* Initialize record sequence number to 1 for new peers. The first
+       * record with sequence number 0 is a stateless Hello Verify Request.
+       */
+      security = dtls_security_params(peer);
+      security->rseq = 1;
+      dtls_add_peer(ctx, peer);
+    }
+    if (peer && !peer->handshake_params) {
+      dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
+
+      peer->handshake_params = dtls_handshake_new();
+      if (!peer->handshake_params)
+        return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+
+      LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
+      peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
+      peer->handshake_params->hs_state.mseq_s = 1;
+    }
+
+    clear_hs_hash(peer);
+
+    /* First negotiation step: check for PSK
+     *
+     * Note that we already have checked that msg is a Handshake
+     * message containing a ClientHello. dtls_get_cipher() therefore
+     * does not check again.
+     */
+    err = dtls_update_parameters(ctx, peer, data, data_length);
+    if (err < 0) {
+      dtls_warn("error updating security parameters\n");
+      return err;
+    }
+
+    /* update finish MAC */
+    update_hs_hash(peer, data, data_length);
+
+    err = dtls_send_server_hello_msgs(ctx, peer);
+    if (err < 0) {
+      return err;
+    }
+    if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
+       is_ecdsa_client_auth_supported(ctx))
+      peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE;
+    else
+      peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
+
+    /* after sending the ServerHelloDone, we expect the
+     * ClientKeyExchange (possibly containing the PSK id),
+     * followed by a ChangeCipherSpec and an encrypted Finished.
+     */
+
+    break;
+
+  case DTLS_HT_HELLO_REQUEST:
+
+    if (state != DTLS_STATE_CONNECTED) {
+      /* we should just ignore such packets when in handshake */
+      return 0;
+    }
+
+    if (peer && !peer->handshake_params) {
+      peer->handshake_params = dtls_handshake_new();
+      if (!peer->handshake_params)
+        return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+
+      LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
+      peer->handshake_params->hs_state.mseq_r = 0;
+      peer->handshake_params->hs_state.mseq_s = 0;
+    }
+
+    /* send ClientHello with empty Cookie */
+    err = dtls_send_client_hello(ctx, peer, NULL, 0);
+    if (err < 0) {
+      dtls_warn("cannot send ClientHello\n");
+      return err;
+    }
+    peer->state = DTLS_STATE_CLIENTHELLO;
+    break;
+
+  default:
+    dtls_crit("unhandled message %d\n", data[0]);
+    return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
+  }
+
+  if (peer && peer->handshake_params && err >= 0) {
+    peer->handshake_params->hs_state.mseq_r++;
+  }
+
+  return err;
+}
+      
+static int
+handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
+                const dtls_peer_type role, const dtls_state_t state,
+                uint8 *data, size_t data_length)
+{
+  dtls_handshake_header_t *hs_header;
+  int res;
+
+  if (data_length < DTLS_HS_LENGTH) {
+    dtls_warn("handshake message too short\n");
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+  }
+  hs_header = DTLS_HANDSHAKE_HEADER(data);
+
+  dtls_debug("received handshake packet of type: %s (%i)\n",
+            dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
+
+  if (!peer || !peer->handshake_params) {
+    /* This is the initial ClientHello */
+    if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
+      dtls_warn("If there is no peer only ClientHello is allowed\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
+    }
+
+    /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
+    if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
+       hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
+      return handle_handshake_msg(ctx, peer, session, role, state, data,
+                                 data_length);
+    } else {
+      dtls_warn("ignore unexpected handshake message\n");
+      return 0;
+    }
+  }
+
+  if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
+    dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
+             peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
+    return 0;
+  } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
+    /* A packet in between is missing, buffer this packet. */
+    netq_t *n;
+
+    /* TODO: only add packet that are not too new. */
+    if (data_length > DTLS_MAX_BUF) {
+      dtls_warn("the packet is too big to buffer for reoder\n");
+      return 0;
+    }
+
+    netq_t *node = netq_head(peer->handshake_params->reorder_queue);
+    while (node) {
+      dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
+      if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
+        dtls_warn("a packet with this sequence number is already stored\n");
+        return 0;
+      }
+      node = netq_next(node);
+    }
+
+    n = netq_node_new(data_length);
+    if (!n) {
+      dtls_warn("no space in reoder buffer\n");
+      return 0;
+    }
+
+    n->peer = peer;
+    n->length = data_length;
+    memcpy(n->data, data, data_length);
+
+    if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
+      dtls_warn("cannot add packet to reoder buffer\n");
+      netq_node_free(n);
+    }
+    dtls_info("Added packet for reordering\n");
+    return 0;
+  } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
+    /* Found the expected packet, use this and all the buffered packet */
+    int next = 1;
+
+    res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
+    if (res < 0)
+      return res;
+
+    /* We do not know in which order the packet are in the list just search the list for every packet. */
+    while (next && peer->handshake_params) {
+      next = 0;
+      netq_t *node = netq_head(peer->handshake_params->reorder_queue);
+      while (node) {
+        dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
+
+        if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
+          netq_remove(peer->handshake_params->reorder_queue, node);
+          next = 1;
+          res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
+          if (res < 0) {
+            return res;
+          }
+
+          break;
+        } else {
+          node = netq_next(node);
+        }
+      }
+    }
+    return res;
+  }
+  assert(0);
+  return 0;
+}
+
+static int
+handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer, 
+          uint8 *record_header, uint8 *data, size_t data_length)
+{
+  int err;
+  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+
+  /* A CCS message is handled after a KeyExchange message was
+   * received from the client. When security parameters have been
+   * updated successfully and a ChangeCipherSpec message was sent
+   * by ourself, the security context is switched and the record
+   * sequence number is reset. */
+  
+  if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
+    dtls_warn("expected ChangeCipherSpec during handshake\n");
+    return 0;
+  }
+
+  if (data_length < 1 || data[0] != 1)
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+
+  /* Just change the cipher when we are on the same epoch */
+  if (peer->role == DTLS_SERVER) {
+    err = calculate_key_block(ctx, handshake, peer,
+                             &peer->session, peer->role);
+    if (err < 0) {
+      return err;
+    }
+  }
+  
+  peer->state = DTLS_STATE_WAIT_FINISHED;
+
+  return 0;
+}  
+
+/** 
+ * Handles incoming Alert messages. This function returns \c 1 if the
+ * connection should be closed and the peer is to be invalidated.
+ */
+static int
+handle_alert(dtls_context_t *ctx, dtls_peer_t *peer, 
+            uint8 *record_header, uint8 *data, size_t data_length) {
+  int free_peer = 0;           /* indicates whether to free peer */
+
+  if (data_length < 2)
+    return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
+
+  dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
+
+  if (!peer) {
+    dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
+    return 0;
+  }
+
+  /* The peer object is invalidated for FATAL alerts and close
+   * notifies. This is done in two steps.: First, remove the object
+   * from our list of peers. After that, the event handler callback is
+   * invoked with the still existing peer object. Finally, the storage
+   * used by peer is released.
+   */
+  if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
+    dtls_alert("%d invalidate peer\n", data[1]);
+    
+#ifndef WITH_CONTIKI
+    HASH_DEL_PEER(ctx->peers, peer);
+#else /* WITH_CONTIKI */
+    list_remove(ctx->peers, peer);
+
+#ifndef NDEBUG
+    PRINTF("removed peer [");
+    PRINT6ADDR(&peer->session.addr);
+    PRINTF("]:%d\n", uip_ntohs(peer->session.port));
+#endif
+#endif /* WITH_CONTIKI */
+
+    free_peer = 1;
+
+  }
+
+  (void)CALL(ctx, event, &peer->session, 
+            (dtls_alert_level_t)data[0], (unsigned short)data[1]);
+  switch (data[1]) {
+  case DTLS_ALERT_CLOSE_NOTIFY:
+    /* If state is DTLS_STATE_CLOSING, we have already sent a
+     * close_notify so, do not send that again. */
+    if (peer->state != DTLS_STATE_CLOSING) {
+      peer->state = DTLS_STATE_CLOSING;
+      dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
+    } else
+      peer->state = DTLS_STATE_CLOSED;
+    break;
+  default:
+    ;
+  }
+  
+  if (free_peer) {
+    dtls_stop_retransmission(ctx, peer);
+    dtls_destroy_peer(ctx, peer, 0);
+  }
+
+  return free_peer;
+}
+
+static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
+                                   session_t *session, int err)
+{
+  int level;
+  int desc;
+
+  if (err < -(1 << 8) && err > -(3 << 8)) {
+    level = ((-err) & 0xff00) >> 8;
+    desc = (-err) & 0xff;
+    if (!peer) {
+      peer = dtls_get_peer(ctx, session);
+    }
+    if (peer) {
+      peer->state = DTLS_STATE_CLOSING;
+      return dtls_send_alert(ctx, peer, level, desc);
+    }
+  } else if (err == -1) {
+    if (!peer) {
+      peer = dtls_get_peer(ctx, session);
+    }
+    if (peer) {
+      peer->state = DTLS_STATE_CLOSING;
+      return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
+    }
+  }
+  return -1;
+}
+
+/** 
+ * Handles incoming data as DTLS message from given peer.
+ */
+int
+dtls_handle_message(dtls_context_t *ctx, 
+                   session_t *session,
+                   uint8 *msg, int msglen) {
+  dtls_peer_t *peer = NULL;
+  unsigned int rlen;           /* record length */
+  uint8 *data;                         /* (decrypted) payload */
+  int data_length;             /* length of decrypted payload 
+                                  (without MAC and padding) */
+  int err;
+
+  /* check if we have DTLS state for addr/port/ifindex */
+  peer = dtls_get_peer(ctx, session);
+
+  if (!peer) {
+    dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
+    dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
+  } else {
+    dtls_debug("dtls_handle_message: FOUND PEER\n");
+  }
+
+  while ((rlen = is_record(msg,msglen))) {
+    dtls_peer_type role;
+    dtls_state_t state;
+
+    dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
+    if (peer) {
+      data_length = decrypt_verify(peer, msg, rlen, &data);
+      if (data_length < 0) {
+        if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
+          data = msg + DTLS_RH_LENGTH;
+          data_length = rlen - DTLS_RH_LENGTH;
+          state = DTLS_STATE_WAIT_CLIENTHELLO;
+          role = DTLS_SERVER;       
+        } else {
+         int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
+          dtls_info("decrypt_verify() failed\n");
+         if (peer->state < DTLS_STATE_CONNECTED) {
+           dtls_alert_send_from_err(ctx, peer, &peer->session, err);
+           peer->state = DTLS_STATE_CLOSED;
+           /* dtls_stop_retransmission(ctx, peer); */
+           dtls_destroy_peer(ctx, peer, 1);
+         }
+          return err;
+        }
+      } else {
+        role = peer->role;
+        state = peer->state;
+      }
+    } else {
+      /* is_record() ensures that msg contains at least a record header */
+      data = msg + DTLS_RH_LENGTH;
+      data_length = rlen - DTLS_RH_LENGTH;
+      state = DTLS_STATE_WAIT_CLIENTHELLO;
+      role = DTLS_SERVER;
+    }
+
+    dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
+    dtls_debug_hexdump("receive unencrypted", data, data_length);
+
+    /* Handle received record according to the first byte of the
+     * message, i.e. the subprotocol. We currently do not support
+     * combining multiple fragments of one type into a single
+     * record. */
+
+    switch (msg[0]) {
+
+    case DTLS_CT_CHANGE_CIPHER_SPEC:
+      if (peer) {
+        dtls_stop_retransmission(ctx, peer);
+      }
+      err = handle_ccs(ctx, peer, msg, data, data_length);
+      if (err < 0) {
+       dtls_warn("error while handling ChangeCipherSpec message\n");
+       dtls_alert_send_from_err(ctx, peer, session, err);
+
+       /* invalidate peer */
+       dtls_destroy_peer(ctx, peer, 1);
+       peer = NULL;
+
+       return err;
+      }
+      break;
+
+    case DTLS_CT_ALERT:
+      if (peer) {
+        dtls_stop_retransmission(ctx, peer);
+      }
+      err = handle_alert(ctx, peer, msg, data, data_length);
+      if (err < 0 || err == 1) {
+         dtls_warn("received alert, peer has been invalidated\n");
+         /* handle alert has invalidated peer */
+         peer = NULL;
+         return err < 0 ?err:-1;
+      }
+      break;
+
+    case DTLS_CT_HANDSHAKE:
+      /* Handshake messages other than Finish must use the current
+       * epoch, Finish has epoch + 1. */
+
+      if (peer) {
+       uint16_t expected_epoch = dtls_security_params(peer)->epoch;
+       uint16_t msg_epoch = 
+         dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
+
+       /* The new security parameters must be used for all messages
+        * that are sent after the ChangeCipherSpec message. This
+        * means that the client's Finished message uses epoch + 1
+        * while the server is still in the old epoch.
+        */
+       if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
+         expected_epoch++;
+       }
+
+       if (expected_epoch != msg_epoch) {
+          if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
+            state = DTLS_STATE_WAIT_CLIENTHELLO;
+            role = DTLS_SERVER;
+          } else {
+           dtls_warn("Wrong epoch, expected %i, got: %i\n",
+                   expected_epoch, msg_epoch);
+           break;
+         }
+       }
+      }
+
+      err = handle_handshake(ctx, peer, session, role, state, data, data_length);
+      if (err < 0) {
+       dtls_warn("error while handling handshake packet\n");
+       dtls_alert_send_from_err(ctx, peer, session, err);
+       return err;
+      }
+      if (peer && peer->state == DTLS_STATE_CONNECTED) {
+       /* stop retransmissions */
+       dtls_stop_retransmission(ctx, peer);
+       CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
+      }
+      break;
+
+    case DTLS_CT_APPLICATION_DATA:
+      dtls_info("** application data:\n");
+      if (!peer) {
+        dtls_warn("no peer available, send an alert\n");
+        // TODO: should we send a alert here?
+        return -1;
+      }
+      dtls_stop_retransmission(ctx, peer);
+      CALL(ctx, read, &peer->session, data, data_length);
+      break;
+    default:
+      dtls_info("dropped unknown message of type %d\n",msg[0]);
+    }
+
+    /* advance msg by length of ciphertext */
+    msg += rlen;
+    msglen -= rlen;
+  }
+
+  return 0;
+}
+
+dtls_context_t *
+dtls_new_context(void *app_data) {
+  dtls_context_t *c;
+  dtls_tick_t now;
+#ifndef WITH_CONTIKI
+  FILE *urandom = fopen("/dev/urandom", "r");
+  unsigned char buf[sizeof(unsigned long)];
+#endif /* WITH_CONTIKI */
+
+  dtls_ticks(&now);
+#ifdef WITH_CONTIKI
+  /* FIXME: need something better to init PRNG here */
+  dtls_prng_init(now);
+#else /* WITH_CONTIKI */
+  if (!urandom) {
+    dtls_emerg("cannot initialize PRNG\n");
+    return NULL;
+  }
+
+  if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
+    dtls_emerg("cannot initialize PRNG\n");
+    return NULL;
+  }
+
+  fclose(urandom);
+  dtls_prng_init((unsigned long)*buf);
+#endif /* WITH_CONTIKI */
+
+  c = malloc_context();
+  if (!c)
+    goto error;
+
+  memset(c, 0, sizeof(dtls_context_t));
+  c->app = app_data;
+  
+  LIST_STRUCT_INIT(c, sendqueue);
+
+#ifdef WITH_CONTIKI
+  LIST_STRUCT_INIT(c, peers);
+  /* LIST_STRUCT_INIT(c, key_store); */
+  
+  process_start(&dtls_retransmit_process, (char *)c);
+  PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
+  /* the retransmit timer must be initialized to some large value */
+  etimer_set(&c->retransmit_timer, 0xFFFF);
+  PROCESS_CONTEXT_END(&coap_retransmit_process);
+#endif /* WITH_CONTIKI */
+
+  if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
+    c->cookie_secret_age = now;
+  else 
+    goto error;
+  
+  return c;
+
+ error:
+  dtls_alert("cannot create DTLS context\n");
+  if (c)
+    dtls_free_context(c);
+  return NULL;
+}
+
+void
+dtls_free_context(dtls_context_t *ctx) {
+  dtls_peer_t *p;
+
+  if (!ctx) {
+    return;
+  }
+
+#ifndef WITH_CONTIKI
+  dtls_peer_t *tmp;
+
+  if (ctx->peers) {
+    HASH_ITER(hh, ctx->peers, p, tmp) {
+      dtls_destroy_peer(ctx, p, 1);
+    }
+  }
+#else /* WITH_CONTIKI */
+  for (p = list_head(ctx->peers); p; p = list_item_next(p))
+    dtls_destroy_peer(ctx, p, 1);
+#endif /* WITH_CONTIKI */
+
+  free_context(ctx);
+}
+
+int
+dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
+  int res;
+
+  assert(peer);
+  if (!peer)
+    return -1;
+
+  /* check if the same peer is already in our list */
+  if (peer == dtls_get_peer(ctx, &peer->session)) {
+    dtls_debug("found peer, try to re-connect\n");
+    return dtls_renegotiate(ctx, &peer->session);
+  }
+    
+  /* set local peer role to client, remote is server */
+  peer->role = DTLS_CLIENT;
+
+  dtls_add_peer(ctx, peer);
+
+  /* send ClientHello with empty Cookie */
+  peer->handshake_params = dtls_handshake_new();
+      if (!peer->handshake_params)
+        return -1;
+
+  peer->handshake_params->hs_state.mseq_r = 0;
+  peer->handshake_params->hs_state.mseq_s = 0;
+  LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
+  res = dtls_send_client_hello(ctx, peer, NULL, 0);
+  if (res < 0)
+    dtls_warn("cannot send ClientHello\n");
+  else 
+    peer->state = DTLS_STATE_CLIENTHELLO;
+
+  return res;
+}
+
+int
+dtls_connect(dtls_context_t *ctx, const session_t *dst) {
+  dtls_peer_t *peer;
+  int res;
+
+  peer = dtls_get_peer(ctx, dst);
+  
+  if (!peer)
+    peer = dtls_new_peer(dst);
+
+  if (!peer) {
+    dtls_crit("cannot create new peer\n");
+    return -1;
+  }
+
+  res = dtls_connect_peer(ctx, peer);
+
+  /* Invoke event callback to indicate connection attempt or
+   * re-negotiation. */
+  if (res > 0) {
+    CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
+  } else if (res == 0) {
+    CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
+  }
+  
+  return res;
+}
+
+static void
+dtls_retransmit(dtls_context_t *context, netq_t *node) {
+  if (!context || !node)
+    return;
+
+  /* re-initialize timeout when maximum number of retransmissions are not reached yet */
+  if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
+      unsigned char sendbuf[DTLS_MAX_BUF];
+      size_t len = sizeof(sendbuf);
+      int err;
+      unsigned char *data = node->data;
+      size_t length = node->length;
+      dtls_tick_t now;
+      dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
+
+      dtls_ticks(&now);
+      node->retransmit_cnt++;
+      node->t = now + (node->timeout << node->retransmit_cnt);
+      netq_insert_node(context->sendqueue, node);
+      
+      if (node->type == DTLS_CT_HANDSHAKE) {
+       dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
+
+       dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
+                  dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
+      } else {
+       dtls_debug("** retransmit packet\n");
+      }
+      
+      err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
+                               1, sendbuf, &len);
+      if (err < 0) {
+       dtls_warn("can not retransmit packet, err: %i\n", err);
+       return;
+      }
+      dtls_debug_hexdump("retransmit header", sendbuf,
+                        sizeof(dtls_record_header_t));
+      dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
+
+      (void)CALL(context, write, &node->peer->session, sendbuf, len);
+      return;
+  }
+
+  /* no more retransmissions, remove node from system */
+  
+  dtls_debug("** removed transaction\n");
+
+  /* And finally delete the node */
+  netq_node_free(node);
+}
+
+static void
+dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
+  netq_t *node;
+  node = list_head(context->sendqueue); 
+
+  while (node) {
+    if (dtls_session_equals(&node->peer->session, &peer->session)) {
+      netq_t *tmp = node;
+      node = list_item_next(node);
+      list_remove(context->sendqueue, tmp);
+      netq_node_free(tmp);
+    } else
+      node = list_item_next(node);    
+  }
+}
+
+void
+dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
+  dtls_tick_t now;
+  netq_t *node = netq_head(context->sendqueue);
+
+  dtls_ticks(&now);
+  while (node && node->t <= now) {
+    netq_pop_first(context->sendqueue);
+    dtls_retransmit(context, node);
+    node = netq_head(context->sendqueue);
+  }
+
+  if (next && node)
+    *next = node->t;
+}
+
+#ifdef WITH_CONTIKI
+/*---------------------------------------------------------------------------*/
+/* message retransmission */
+/*---------------------------------------------------------------------------*/
+PROCESS_THREAD(dtls_retransmit_process, ev, data)
+{
+  clock_time_t now;
+  netq_t *node;
+
+  PROCESS_BEGIN();
+
+  dtls_debug("Started DTLS retransmit process\r\n");
+
+  while(1) {
+    PROCESS_YIELD();
+    if (ev == PROCESS_EVENT_TIMER) {
+      if (etimer_expired(&the_dtls_context.retransmit_timer)) {
+       
+       node = list_head(the_dtls_context.sendqueue);
+       
+       now = clock_time();
+       if (node && node->t <= now) {
+         dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
+         node = list_head(the_dtls_context.sendqueue);
+       }
+
+       /* need to set timer to some value even if no nextpdu is available */
+       if (node) {
+         etimer_set(&the_dtls_context.retransmit_timer, 
+                    node->t <= now ? 1 : node->t - now);
+       } else {
+         etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
+       }
+      } 
+    }
+  }
+  
+  PROCESS_END();
+}
+#endif /* WITH_CONTIKI */
diff --git a/extlibs/tinydtls/dtls.h b/extlibs/tinydtls/dtls.h
new file mode 100644 (file)
index 0000000..7ebde6b
--- /dev/null
@@ -0,0 +1,746 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file dtls.h
+ * @brief High level DTLS API and visible structures. 
+ */
+
+#ifndef _DTLS_DTLS_H_
+#define _DTLS_DTLS_H_
+
+#include <stdint.h>
+
+#include "t_list.h"
+#include "state.h"
+#include "peer.h"
+
+#ifndef WITH_CONTIKI
+#include "uthash.h"
+#include "t_list.h"
+#endif /* WITH_CONTIKI */
+
+#include "alert.h"
+#include "crypto.h"
+#include "hmac.h"
+
+#include "global.h"
+#include "dtls_time.h"
+
+#ifndef DTLSv12
+#define DTLS_VERSION 0xfeff    /* DTLS v1.1 */
+#else
+#define DTLS_VERSION 0xfefd    /* DTLS v1.2 */
+#endif
+
+typedef enum dtls_credentials_type_t {
+  DTLS_PSK_HINT, DTLS_PSK_IDENTITY, DTLS_PSK_KEY
+} dtls_credentials_type_t;
+
+typedef struct dtls_ecdsa_key_t {
+  dtls_ecdh_curve curve;
+  const unsigned char *priv_key;       /** < private key as bytes > */
+  const unsigned char *pub_key_x;      /** < x part of the public key for the given private key > */
+  const unsigned char *pub_key_y;      /** < y part of the public key for the given private key > */
+} dtls_ecdsa_key_t;
+
+/** Length of the secret that is used for generating Hello Verify cookies. */
+#define DTLS_COOKIE_SECRET_LENGTH 12
+
+struct dtls_context_t;
+
+/**
+ * This structure contains callback functions used by tinydtls to
+ * communicate with the application. At least the write function must
+ * be provided. It is called by the DTLS state machine to send packets
+ * over the network. The read function is invoked to deliver decrypted
+ * and verfified application data. The third callback is an event
+ * handler function that is called when alert messages are encountered
+ * or events generated by the library have occured.
+ */ 
+typedef struct {
+  /** 
+   * Called from dtls_handle_message() to send DTLS packets over the
+   * network. The callback function must use the network interface
+   * denoted by session->ifindex to send the data.
+   *
+   * @param ctx  The current DTLS context.
+   * @param session The session object, including the address of the
+   *              remote peer where the data shall be sent.
+   * @param buf  The data to send.
+   * @param len  The actual length of @p buf.
+   * @return The callback function must return the number of bytes 
+   *         that were sent, or a value less than zero to indicate an 
+   *         error.
+   */
+  int (*write)(struct dtls_context_t *ctx, 
+              session_t *session, uint8 *buf, size_t len);
+
+  /** 
+   * Called from dtls_handle_message() deliver application data that was 
+   * received on the given session. The data is delivered only after
+   * decryption and verification have succeeded. 
+   *
+   * @param ctx  The current DTLS context.
+   * @param session The session object, including the address of the
+   *              data's origin. 
+   * @param buf  The received data packet.
+   * @param len  The actual length of @p buf.
+   * @return ignored
+   */
+  int (*read)(struct dtls_context_t *ctx, 
+              session_t *session, uint8 *buf, size_t len);
+
+  /**
+   * The event handler is called when a message from the alert
+   * protocol is received or the state of the DTLS session changes.
+   *
+   * @param ctx     The current dtls context.
+   * @param session The session object that was affected.
+   * @param level   The alert level or @c 0 when an event ocurred that 
+   *                is not an alert. 
+   * @param code    Values less than @c 256 indicate alerts, while
+   *                @c 256 or greater indicate internal DTLS session changes.
+   * @return ignored
+   */
+  int (*event)(struct dtls_context_t *ctx, session_t *session, 
+               dtls_alert_level_t level, unsigned short code);
+
+#ifdef DTLS_PSK
+  /**
+   * Called during handshake to get information related to the
+   * psk key exchange. The type of information requested is
+   * indicated by @p type which will be one of DTLS_PSK_HINT,
+   * DTLS_PSK_IDENTITY, or DTLS_PSK_KEY. The called function
+   * must store the requested item in the buffer @p result of
+   * size @p result_length. On success, the function must return
+   * the actual number of bytes written to @p result, of a
+   * value less than zero on error. The parameter @p desc may
+   * contain additional request information (e.g. the psk_identity
+   * for which a key is requested when @p type == @c DTLS_PSK_KEY.
+   *
+   * @param ctx     The current dtls context.
+   * @param session The session where the key will be used.
+   * @param type    The type of the requested information.
+   * @param desc    Additional request information
+   * @param desc_len The actual length of desc.
+   * @param result  Must be filled with the requested information.
+   * @param result_length  Maximum size of @p result.
+   * @return The number of bytes written to @p result or a value
+   *         less than zero on error.
+   */
+  int (*get_psk_info)(struct dtls_context_t *ctx,
+                     const session_t *session,
+                     dtls_credentials_type_t type,
+                     const unsigned char *desc, size_t desc_len,
+                     unsigned char *result, size_t result_length);
+
+#endif /* DTLS_PSK */
+
+#ifdef DTLS_ECC
+  /**
+   * Called during handshake to get the server's or client's ecdsa
+   * key used to authenticate this server or client in this 
+   * session. If found, the key must be stored in @p result and 
+   * the return value must be @c 0. If not found, @p result is 
+   * undefined and the return value must be less than zero.
+   *
+   * If ECDSA should not be supported, set this pointer to NULL.
+   *
+   * Implement this if you want to provide your own certificate to 
+   * the other peer. This is mandatory for a server providing ECDSA
+   * support and optional for a client. A client doing DTLS client
+   * authentication has to implementing this callback.
+   *
+   * @param ctx     The current dtls context.
+   * @param session The session where the key will be used.
+   * @param result  Must be set to the key object to used for the given
+   *                session.
+   * @return @c 0 if result is set, or less than zero on error.
+   */
+  int (*get_ecdsa_key)(struct dtls_context_t *ctx, 
+                      const session_t *session,
+                      const dtls_ecdsa_key_t **result);
+
+  /**
+   * Called during handshake to check the peer's pubic key in this
+   * session. If the public key matches the session and should be
+   * considerated valid the return value must be @c 0. If not valid,
+   * the return value must be less than zero.
+   *
+   * If ECDSA should not be supported, set this pointer to NULL.
+   *
+   * Implement this if you want to verify the other peers public key.
+   * This is mandatory for a DTLS client doing based ECDSA
+   * authentication. A server implementing this will request the
+   * client to do DTLS client authentication.
+   *
+   * @param ctx          The current dtls context.
+   * @param session      The session where the key will be used.
+   * @param other_pub_x  x component of the public key.
+   * @param other_pub_y  y component of the public key.
+   * @return @c 0 if public key matches, or less than zero on error.
+   * error codes:
+   *   return dtls_alert_fatal_create(DTLS_ALERT_BAD_CERTIFICATE);
+   *   return dtls_alert_fatal_create(DTLS_ALERT_UNSUPPORTED_CERTIFICATE);
+   *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_REVOKED);
+   *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_EXPIRED);
+   *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_UNKNOWN);
+   *   return dtls_alert_fatal_create(DTLS_ALERT_UNKNOWN_CA);
+   */
+  int (*verify_ecdsa_key)(struct dtls_context_t *ctx, 
+                         const session_t *session,
+                         const unsigned char *other_pub_x,
+                         const unsigned char *other_pub_y,
+                         size_t key_size);
+#endif /* DTLS_ECC */
+} dtls_handler_t;
+
+/** Holds global information of the DTLS engine. */
+typedef struct dtls_context_t {
+  unsigned char cookie_secret[DTLS_COOKIE_SECRET_LENGTH];
+  clock_time_t cookie_secret_age; /**< the time the secret has been generated */
+
+#ifndef WITH_CONTIKI
+  dtls_peer_t *peers;          /**< peer hash map */
+#else /* WITH_CONTIKI */
+  LIST_STRUCT(peers);
+
+  struct etimer retransmit_timer; /**< fires when the next packet must be sent */
+#endif /* WITH_CONTIKI */
+
+  LIST_STRUCT(sendqueue);      /**< the packets to send */
+
+  void *app;                   /**< application-specific data */
+
+  dtls_handler_t *h;           /**< callback handlers */
+
+  unsigned char readbuf[DTLS_MAX_BUF];
+} dtls_context_t;
+
+/** 
+ * This function initializes the tinyDTLS memory management and must
+ * be called first.
+ */
+void dtls_init();
+
+/** 
+ * Creates a new context object. The storage allocated for the new
+ * object must be released with dtls_free_context(). */
+dtls_context_t *dtls_new_context(void *app_data);
+
+/** Releases any storage that has been allocated for \p ctx. */
+void dtls_free_context(dtls_context_t *ctx);
+
+#define dtls_set_app_data(CTX,DATA) ((CTX)->app = (DATA))
+#define dtls_get_app_data(CTX) ((CTX)->app)
+
+/** Sets the callback handler object for @p ctx to @p h. */
+static inline void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
+  ctx->h = h;
+}
+
+/**
+ * Establishes a DTLS channel with the specified remote peer @p dst.
+ * This function returns @c 0 if that channel already exists, a value
+ * greater than zero when a new ClientHello message was sent, and
+ * a value less than zero on error.
+ *
+ * @param ctx    The DTLS context to use.
+ * @param dst    The remote party to connect to.
+ * @return A value less than zero on error, greater or equal otherwise.
+ */
+int dtls_connect(dtls_context_t *ctx, const session_t *dst);
+
+/**
+ * Establishes a DTLS channel with the specified remote peer.
+ * This function returns @c 0 if that channel already exists, a value
+ * greater than zero when a new ClientHello message was sent, and
+ * a value less than zero on error.
+ *
+ * @param ctx    The DTLS context to use.
+ * @param peer   The peer object that describes the session.
+ * @return A value less than zero on error, greater or equal otherwise.
+ */
+int dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer);
+
+/**
+ * Closes the DTLS connection associated with @p remote. This function
+ * returns zero on success, and a value less than zero on error.
+ */
+int dtls_close(dtls_context_t *ctx, const session_t *remote);
+
+int dtls_renegotiate(dtls_context_t *ctx, const session_t *dst);
+
+/** 
+ * Writes the application data given in @p buf to the peer specified
+ * by @p session. 
+ * 
+ * @param ctx      The DTLS context to use.
+ * @param session  The remote transport address and local interface.
+ * @param buf      The data to write.
+ * @param len      The actual length of @p data.
+ * 
+ * @return The number of bytes written or @c -1 on error.
+ */
+int dtls_write(struct dtls_context_t *ctx, session_t *session, 
+              uint8 *buf, size_t len);
+
+/**
+ * Checks sendqueue of given DTLS context object for any outstanding
+ * packets to be transmitted. 
+ *
+ * @param context The DTLS context object to use.
+ * @param next    If not NULL, @p next is filled with the timestamp
+ *  of the next scheduled retransmission, or @c 0 when no packets are
+ *  waiting.
+ */
+void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next);
+
+#define DTLS_COOKIE_LENGTH 16
+
+#define DTLS_CT_CHANGE_CIPHER_SPEC 20
+#define DTLS_CT_ALERT              21
+#define DTLS_CT_HANDSHAKE          22
+#define DTLS_CT_APPLICATION_DATA   23
+
+/** Generic header structure of the DTLS record layer. */
+typedef struct __attribute__((__packed__)) {
+  uint8 content_type;          /**< content type of the included message */
+  uint16 version;              /**< Protocol version */
+  uint16 epoch;                        /**< counter for cipher state changes */
+  uint48 sequence_number;       /**< sequence number */
+  uint16 length;               /**< length of the following fragment */
+  /* fragment */
+} dtls_record_header_t;
+
+/* Handshake types */
+
+#define DTLS_HT_HELLO_REQUEST        0
+#define DTLS_HT_CLIENT_HELLO         1
+#define DTLS_HT_SERVER_HELLO         2
+#define DTLS_HT_HELLO_VERIFY_REQUEST 3
+#define DTLS_HT_CERTIFICATE         11
+#define DTLS_HT_SERVER_KEY_EXCHANGE 12
+#define DTLS_HT_CERTIFICATE_REQUEST 13
+#define DTLS_HT_SERVER_HELLO_DONE   14
+#define DTLS_HT_CERTIFICATE_VERIFY  15
+#define DTLS_HT_CLIENT_KEY_EXCHANGE 16
+#define DTLS_HT_FINISHED            20
+
+/** Header structure for the DTLS handshake protocol. */
+typedef struct __attribute__((__packed__)) {
+  uint8 msg_type; /**< Type of handshake message  (one of DTLS_HT_) */
+  uint24 length;  /**< length of this message */
+  uint16 message_seq;  /**< Message sequence number */
+  uint24 fragment_offset;      /**< Fragment offset. */
+  uint24 fragment_length;      /**< Fragment length. */
+  /* body */
+} dtls_handshake_header_t;
+
+/** Structure of the Client Hello message. */
+typedef struct __attribute__((__packed__)) {
+  uint16 version;        /**< Client version */
+  uint32 gmt_random;     /**< GMT time of the random byte creation */
+  unsigned char random[28];    /**< Client random bytes */
+  /* session id (up to 32 bytes) */
+  /* cookie (up to 32 bytes) */
+  /* cipher suite (2 to 2^16 -1 bytes) */
+  /* compression method */
+} dtls_client_hello_t;
+
+/** Structure of the Hello Verify Request. */
+typedef struct __attribute__((__packed__)) {
+  uint16 version;              /**< Server version */
+  uint8 cookie_length; /**< Length of the included cookie */
+  uint8 cookie[];              /**< up to 32 bytes making up the cookie */
+} dtls_hello_verify_t;  
+
+#if 0
+/** 
+ * Checks a received DTLS record for consistency and eventually decrypt,
+ * verify, decompress and reassemble the contained fragment for 
+ * delivery to high-lever clients. 
+ * 
+ * \param state The DTLS record state for the current session. 
+ * \param 
+ */
+int dtls_record_read(dtls_state_t *state, uint8 *msg, int msglen);
+#endif
+
+/** 
+ * Handles incoming data as DTLS message from given peer.
+ *
+ * @param ctx     The dtls context to use.
+ * @param session The current session
+ * @param msg     The received data
+ * @param msglen  The actual length of @p msg.
+ * @return A value less than zero on error, zero on success.
+ */
+int dtls_handle_message(dtls_context_t *ctx, session_t *session,
+                       uint8 *msg, int msglen);
+
+/**
+ * Check if @p session is associated with a peer object in @p context.
+ * This function returns a pointer to the peer if found, NULL otherwise.
+ *
+ * @param context  The DTLS context to search.
+ * @param session  The remote address and local interface
+ * @return A pointer to the peer associated with @p session or NULL if
+ *  none exists.
+ */
+dtls_peer_t *dtls_get_peer(const dtls_context_t *context,
+                          const session_t *session);
+
+
+#endif /* _DTLS_DTLS_H_ */
+
+/**
+ * @mainpage 
+ *
+ * @author Olaf Bergmann, TZI Uni Bremen
+ *
+ * This library provides a very simple datagram server with DTLS
+ * support. It is designed to support session multiplexing in
+ * single-threaded applications and thus targets specifically on
+ * embedded systems.
+ *
+ * @section license License
+ *
+ * This software is under the <a 
+ * href="http://www.opensource.org/licenses/mit-license.php">MIT License</a>.
+ * 
+ * @subsection uthash UTHash
+ *
+ * This library uses <a href="http://uthash.sourceforge.net/">uthash</a> to manage
+ * its peers (not used for Contiki). @b uthash uses the <b>BSD revised license</b>, see
+ * <a href="http://uthash.sourceforge.net/license.html">http://uthash.sourceforge.net/license.html</a>.
+ *
+ * @subsection sha256 Aaron D. Gifford's SHA256 Implementation
+ *
+ * tinyDTLS provides HMAC-SHA256 with BSD-licensed code from Aaron D. Gifford, 
+ * see <a href="http://www.aarongifford.com/">www.aarongifford.com</a>.
+ *
+ * @subsection aes Rijndael Implementation From OpenBSD
+ *
+ * The AES implementation is taken from rijndael.{c,h} contained in the crypto 
+ * sub-system of the OpenBSD operating system. It is copyright by Vincent Rijmen, *
+ * Antoon Bosselaers and Paulo Barreto. See <a 
+ * href="http://www.openbsd.org/cgi-bin/cvsweb/src/sys/crypto/rijndael.c">rijndael.c</a> 
+ * for License info.
+ *
+ * @section download Getting the Files
+ *
+ * You can get the sources either from the <a 
+ * href="http://sourceforge.net/projects/tinydtls/files">downloads</a> section or 
+ * through git from the <a 
+ * href="http://sourceforge.net/projects/tinydtls/develop">project develop page</a>.
+ *
+ * @section config Configuration
+ *
+ * Use @c configure to set up everything for a successful build. For Contiki, use the
+ * option @c --with-contiki.
+ *
+ * @section build Building
+ *
+ * After configuration, just type 
+ * @code
+make
+ * @endcode
+ * optionally followed by
+ * @code
+make install
+ * @endcode
+ * The Contiki version is integrated with the Contiki build system, hence you do not
+ * need to invoke @c make explicitely. Just add @c tinydtls to the variable @c APPS
+ * in your @c Makefile.
+ *
+ * @addtogroup dtls_usage DTLS Usage
+ *
+ * @section dtls_server_example DTLS Server Example
+ *
+ * This section shows how to use the DTLS library functions to setup a 
+ * simple secure UDP echo server. The application is responsible for the
+ * entire network communication and thus will look like a usual UDP
+ * server with socket creation and binding and a typical select-loop as
+ * shown below. The minimum configuration required for DTLS is the 
+ * creation of the dtls_context_t using dtls_new_context(), and a callback
+ * for sending data. Received packets are read by the application and
+ * passed to dtls_handle_message() as shown in @ref dtls_read_cb. 
+ * For any useful communication to happen, read and write call backs 
+ * and a key management function should be registered as well. 
+ * 
+ * @code 
+ dtls_context_t *the_context = NULL;
+ int fd, result;
+
+ static dtls_handler_t cb = {
+   .write = send_to_peer,
+   .read  = read_from_peer,
+   .event = NULL,
+   .get_psk_key = get_psk_key
+ };
+
+ fd = socket(...);
+ if (fd < 0 || bind(fd, ...) < 0)
+   exit(-1);
+
+ the_context = dtls_new_context(&fd);
+ dtls_set_handler(the_context, &cb);
+
+ while (1) {
+   ...initialize fd_set rfds and timeout ...
+   result = select(fd+1, &rfds, NULL, 0, NULL);
+    
+   if (FD_ISSET(fd, &rfds))
+     dtls_handle_read(the_context);
+ }
+
+ dtls_free_context(the_context);
+ * @endcode
+ * 
+ * @subsection dtls_read_cb The Read Callback
+ *
+ * The DTLS library expects received raw data to be passed to
+ * dtls_handle_message(). The application is responsible for
+ * filling a session_t structure with the address data of the
+ * remote peer as illustrated by the following example:
+ * 
+ * @code
+int dtls_handle_read(struct dtls_context_t *ctx) {
+  int *fd;
+  session_t session;
+  static uint8 buf[DTLS_MAX_BUF];
+  int len;
+
+  fd = dtls_get_app_data(ctx);
+
+  assert(fd);
+
+  session.size = sizeof(session.addr);
+  len = recvfrom(*fd, buf, sizeof(buf), 0, &session.addr.sa, &session.size);
+  
+  return len < 0 ? len : dtls_handle_message(ctx, &session, buf, len);
+}    
+ * @endcode 
+ * 
+ * Once a new DTLS session was established and DTLS ApplicationData has been
+ * received, the DTLS server invokes the read callback with the MAC-verified 
+ * cleartext data as its argument. A read callback for a simple echo server
+ * could look like this:
+ * @code
+int read_from_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
+  return dtls_write(ctx, session, data, len);
+}
+ * @endcode 
+ * 
+ * @subsection dtls_send_cb The Send Callback
+ * 
+ * The callback function send_to_peer() is called whenever data must be
+ * sent over the network. Here, the sendto() system call is used to
+ * transmit data within the given session. The socket descriptor required
+ * by sendto() has been registered as application data when the DTLS context
+ * was created with dtls_new_context().
+ * Note that it is on the application to buffer the data when it cannot be
+ * sent at the time this callback is invoked. The following example thus
+ * is incomplete as it would have to deal with EAGAIN somehow.
+ * @code
+int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
+  int fd = *(int *)dtls_get_app_data(ctx);
+  return sendto(fd, data, len, MSG_DONTWAIT, &session->addr.sa, session->size);
+}
+ * @endcode
+ * 
+ * @subsection dtls_get_psk_info The Key Storage
+ *
+ * When a new DTLS session is created, the library must ask the application
+ * for keying material. To do so, it invokes the registered call-back function
+ * get_psk_info() with the current context and session information as parameter.
+ * When the call-back function is invoked with the parameter @p type set to 
+ * @c DTLS_PSK_IDENTITY, the result parameter @p result must be filled with
+ * the psk_identity_hint in case of a server, or the actual psk_identity in 
+ * case of a client. When @p type is @c DTLS_PSK_KEY, the result parameter
+ * must be filled with a key for the given identity @p id. The function must
+ * return the number of bytes written to @p result which must not exceed
+ * @p result_length.
+ * In case of an error, the function must return a negative value that 
+ * corresponds to a valid error code defined in alert.h.
+ * 
+ * @code
+int get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
+           const session_t *session UNUSED_PARAM,
+           dtls_credentials_type_t type,
+           const unsigned char *id, size_t id_len,
+           unsigned char *result, size_t result_length) {
+
+  switch (type) {
+  case DTLS_PSK_IDENTITY:
+    if (result_length < psk_id_length) {
+      dtls_warn("cannot set psk_identity -- buffer too small\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    memcpy(result, psk_id, psk_id_length);
+    return psk_id_length;
+  case DTLS_PSK_KEY:
+    if (id_len != psk_id_length || memcmp(psk_id, id, id_len) != 0) {
+      dtls_warn("PSK for unknown id requested, exiting\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
+    } else if (result_length < psk_key_length) {
+      dtls_warn("cannot set psk -- buffer too small\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    memcpy(result, psk_key, psk_key_length);
+    return psk_key_length;
+  default:
+    dtls_warn("unsupported request type: %d\n", type);
+  }
+
+  return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+}
+ * @endcode
+ * 
+ * @subsection dtls_events The Event Notifier
+ *
+ * Applications that want to be notified whenever the status of a DTLS session
+ * has changed can register an event handling function with the field @c event
+ * in the dtls_handler_t structure (see \ref dtls_server_example). The call-back
+ * function is called for alert messages and internal state changes. For alert
+ * messages, the argument @p level will be set to a value greater than zero, and
+ * @p code will indicate the notification code. For internal events, @p level
+ * is @c 0, and @p code a value greater than @c 255. 
+ *
+ * Internal events are DTLS_EVENT_CONNECTED, @c DTLS_EVENT_CONNECT, and
+ * @c DTLS_EVENT_RENEGOTIATE.
+ *
+ * @code
+int handle_event(struct dtls_context_t *ctx, session_t *session, 
+                 dtls_alert_level_t level, unsigned short code) {
+  ... do something with event ...
+  return 0;
+}
+ * @endcode
+ *
+ * @section dtls_client_example DTLS Client Example
+ *
+ * A DTLS client is constructed like a server but needs to actively setup
+ * a new session by calling dtls_connect() at some point. As this function
+ * usually returns before the new DTLS channel is established, the application
+ * must register an event handler and wait for @c DTLS_EVENT_CONNECT before
+ * it can send data over the DTLS channel.
+ *
+ */
+
+/**
+ * @addtogroup contiki Contiki
+ *
+ * To use tinyDTLS as Contiki application, place the source code in the directory 
+ * @c apps/tinydtls in the Contiki source tree and invoke configure with the option
+ * @c --with-contiki. This will define WITH_CONTIKI in tinydtls.h and include 
+ * @c Makefile.contiki in the main Makefile. To cross-compile for another platform
+ * you will need to set your host and build system accordingly. For example,
+ * when configuring for ARM, you would invoke
+ * @code
+./configure --with-contiki --build=x86_64-linux-gnu --host=arm-none-eabi 
+ * @endcode
+ * on an x86_64 linux host.
+ *
+ * Then, create a Contiki project with @c APPS += tinydtls in its Makefile. A sample
+ * server could look like this (with read_from_peer() and get_psk_key() as shown above).
+ *
+ * @code
+#include "contiki.h"
+
+#include "tinydtls.h"
+#include "dtls.h"
+
+#define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
+#define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
+
+int send_to_peer(struct dtls_context_t *, session_t *, uint8 *, size_t);
+
+static struct uip_udp_conn *server_conn;
+static dtls_context_t *dtls_context;
+
+static dtls_handler_t cb = {
+  .write = send_to_peer,
+  .read  = read_from_peer,
+  .event = NULL,
+  .get_psk_key = get_psk_key
+};
+
+PROCESS(server_process, "DTLS server process");
+AUTOSTART_PROCESSES(&server_process);
+
+PROCESS_THREAD(server_process, ev, data)
+{
+  PROCESS_BEGIN();
+
+  dtls_init();
+
+  server_conn = udp_new(NULL, 0, NULL);
+  udp_bind(server_conn, UIP_HTONS(5684));
+
+  dtls_context = dtls_new_context(server_conn);
+  if (!dtls_context) {
+    dtls_emerg("cannot create context\n");
+    PROCESS_EXIT();
+  }
+
+  dtls_set_handler(dtls_context, &cb);
+
+  while(1) {
+    PROCESS_WAIT_EVENT();
+    if(ev == tcpip_event && uip_newdata()) {
+      session_t session;
+
+      uip_ipaddr_copy(&session.addr, &UIP_IP_BUF->srcipaddr);
+      session.port = UIP_UDP_BUF->srcport;
+      session.size = sizeof(session.addr) + sizeof(session.port);
+    
+      dtls_handle_message(ctx, &session, uip_appdata, uip_datalen());
+    }
+  }
+
+  PROCESS_END();
+}
+
+int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
+  struct uip_udp_conn *conn = (struct uip_udp_conn *)dtls_get_app_data(ctx);
+
+  uip_ipaddr_copy(&conn->ripaddr, &session->addr);
+  conn->rport = session->port;
+
+  uip_udp_packet_send(conn, data, len);
+
+  memset(&conn->ripaddr, 0, sizeof(server_conn->ripaddr));
+  memset(&conn->rport, 0, sizeof(conn->rport));
+
+  return len;
+}
+ * @endcode
+ */
diff --git a/extlibs/tinydtls/dtls_config.h b/extlibs/tinydtls/dtls_config.h
new file mode 100644 (file)
index 0000000..39df8c9
--- /dev/null
@@ -0,0 +1,171 @@
+/* dtls_config.h.  Generated from dtls_config.h.in by configure.  */
+/* tinydtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file dtls_config.h
+ * @brief internal configuration for tinydtls library
+ *
+ * This file has been generated by configure from dtls_config.h.in.
+ */
+
+/* dummy definitions for PACKAGE_NAME and PACKAGE_VERSION */
+#define PACKAGE_NAME "tinydtls"
+#define PACKAGE_STRING "tinydtls 0.8.1"
+#define PACKAGE_VERSION "0.8.1"
+
+#ifdef CONTIKI
+#include "contiki.h"
+#include "contiki-lib.h"
+#include "contiki-net.h"
+
+#include "contiki-conf.h"
+
+/* global constants for constrained devices running Contiki */
+#ifndef DTLS_PEER_MAX
+/** The maximum number DTLS peers (i.e. sessions). */
+#  define DTLS_PEER_MAX 1
+#endif
+
+#ifndef DTLS_HANDSHAKE_MAX
+/** The maximum number of concurrent DTLS handshakes. */
+#  define DTLS_HANDSHAKE_MAX 1
+#endif
+
+#ifndef DTLS_SECURITY_MAX
+/** The maximum number of concurrently used cipher keys */
+#  define DTLS_SECURITY_MAX (DTLS_PEER_MAX + DTLS_HANDSHAKE_MAX)
+#endif
+
+#ifndef DTLS_HASH_MAX
+/** The maximum number of hash functions that can be used in parallel. */
+#  define DTLS_HASH_MAX (3 * DTLS_PEER_MAX)
+#endif
+#endif /* CONTIKI */
+
+/* Define to 1 if you have the <assert.h> header file. */
+#define HAVE_ASSERT_H 1
+
+/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
+   to 0 otherwise. */
+#define HAVE_MALLOC 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `memset' function. */
+#define HAVE_MEMSET 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the `strdup' function. */
+#define HAVE_STRDUP 1
+
+/* Define to 1 if you have the `strerror' function. */
+#define HAVE_STRERROR 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strnlen' function. */
+#define HAVE_STRNLEN 1
+
+/* Define to 1 if you have the <time.h> header file. */
+#define HAVE_TIME_H 1
+
+/* Define to 1 if you have the `vprintf' function. */
+#define HAVE_VPRINTF 1
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "tinydtls"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "tinydtls 0.8.1"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "tinydtls"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "0.8.1"
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+   calls it, or to nothing if 'inline' is not supported under any name.  */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define to rpl_malloc if the replacement function should be used. */
+/* #undef malloc */
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+
+/* #undef size_t */
+
+/************************************************************************/
+/* Specific Contiki platforms                                           */
+/************************************************************************/
+
+#ifdef CONTIKI
+
+#if CONTIKI_TARGET_ECONOTAG
+#  include "platform-specific/config-econotag.h"
+#endif /* CONTIKI_TARGET_ECONOTAG */
+
+#ifdef CONTIKI_TARGET_CC2538DK
+#  include "platform-specific/config-cc2538dk.h"
+#endif /* CONTIKI_TARGET_CC2538DK */
+
+#ifdef CONTIKI_TARGET_WISMOTE
+#  include "platform-specific/config-wismote.h"
+#endif /* CONTIKI_TARGET_WISMOTE */
+
+#ifdef CONTIKI_TARGET_SKY
+#  include "platform-specific/config-sky.h"
+#endif /* CONTIKI_TARGET_SKY */
+
+#ifdef CONTIKI_TARGET_MINIMAL_NET
+#  include "platform-specific/config-minimal-net.h"
+#endif /* CONTIKI_TARGET_MINIMAL_NET */
+
+#endif /* CONTIKI */
diff --git a/extlibs/tinydtls/dtls_config.h.in b/extlibs/tinydtls/dtls_config.h.in
new file mode 100644 (file)
index 0000000..a29077c
--- /dev/null
@@ -0,0 +1,218 @@
+/* tinydtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file dtls_config.h
+ * @brief internal configuration for tinydtls library
+ *
+ * This file has been generated by configure from dtls_config.h.in.
+ */
+
+/* dummy definitions for PACKAGE_NAME and PACKAGE_VERSION */
+#define PACKAGE_NAME "tinydtls"
+#define PACKAGE_STRING PACKAGE_NAME
+#define PACKAGE_VERSION PACKAGE_VERSION
+
+#ifdef CONTIKI
+#include "contiki.h"
+#include "contiki-lib.h"
+#include "contiki-net.h"
+
+#include "contiki-conf.h"
+
+/* global constants for constrained devices running Contiki */
+#ifndef DTLS_PEER_MAX
+/** The maximum number DTLS peers (i.e. sessions). */
+#  define DTLS_PEER_MAX 1
+#endif
+
+#ifndef DTLS_HANDSHAKE_MAX
+/** The maximum number of concurrent DTLS handshakes. */
+#  define DTLS_HANDSHAKE_MAX 1
+#endif
+
+#ifndef DTLS_SECURITY_MAX
+/** The maximum number of concurrently used cipher keys */
+#  define DTLS_SECURITY_MAX (DTLS_PEER_MAX + DTLS_HANDSHAKE_MAX)
+#endif
+
+#ifndef DTLS_HASH_MAX
+/** The maximum number of hash functions that can be used in parallel. */
+#  define DTLS_HASH_MAX (3 * DTLS_PEER_MAX)
+#endif
+#endif /* CONTIKI */
+
+/* Define if building universal (internal helper macro) */
+#undef AC_APPLE_UNIVERSAL_BUILD
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#undef HAVE_ARPA_INET_H
+
+/* Define to 1 if you have the <assert.h> header file. */
+#undef HAVE_ASSERT_H
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#undef HAVE_FCNTL_H
+
+/* Define to 1 if you have the `fls' function. */
+#undef HAVE_FLS
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#undef HAVE_INTTYPES_H
+
+/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
+   to 0 otherwise. */
+#undef HAVE_MALLOC
+
+/* Define to 1 if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define to 1 if you have the `memset' function. */
+#undef HAVE_MEMSET
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#undef HAVE_NETDB_H
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#undef HAVE_NETINET_IN_H
+
+/* Define to 1 if you have the `select' function. */
+#undef HAVE_SELECT
+
+/* Define to 1 if struct sockaddr_in6 has a member sin6_len. */
+#undef HAVE_SOCKADDR_IN6_SIN6_LEN
+
+/* Define to 1 if you have the `socket' function. */
+#undef HAVE_SOCKET
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#undef HAVE_STDDEF_H
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#undef HAVE_STDLIB_H
+
+/* Define to 1 if you have the `strdup' function. */
+#undef HAVE_STRDUP
+
+/* Define to 1 if you have the `strerror' function. */
+#undef HAVE_STRERROR
+
+/* Define to 1 if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#undef HAVE_STRING_H
+
+/* Define to 1 if you have the `strnlen' function. */
+#undef HAVE_STRNLEN
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#undef HAVE_SYS_PARAM_H
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#undef HAVE_SYS_SOCKET_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#undef HAVE_SYS_TIME_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#undef HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have the <time.h> header file. */
+#undef HAVE_TIME_H
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#undef HAVE_UNISTD_H
+
+/* Define to 1 if you have the `vprintf' function. */
+#undef HAVE_VPRINTF
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+   calls it, or to nothing if 'inline' is not supported under any name.  */
+#ifndef __cplusplus
+#undef inline
+#endif
+
+/* Define to rpl_malloc if the replacement function should be used. */
+#undef malloc
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+
+#undef size_t
+
+/************************************************************************/
+/* Specific Contiki platforms                                           */
+/************************************************************************/
+
+#ifdef CONTIKI
+
+#if CONTIKI_TARGET_ECONOTAG
+#  include "platform-specific/config-econotag.h"
+#endif /* CONTIKI_TARGET_ECONOTAG */
+
+#ifdef CONTIKI_TARGET_CC2538DK
+#  include "platform-specific/config-cc2538dk.h"
+#endif /* CONTIKI_TARGET_CC2538DK */
+
+#ifdef CONTIKI_TARGET_WISMOTE
+#  include "platform-specific/config-wismote.h"
+#endif /* CONTIKI_TARGET_WISMOTE */
+
+#ifdef CONTIKI_TARGET_SKY
+#  include "platform-specific/config-sky.h"
+#endif /* CONTIKI_TARGET_SKY */
+
+#ifdef CONTIKI_TARGET_MINIMAL_NET
+#  include "platform-specific/config-minimal-net.h"
+#endif /* CONTIKI_TARGET_MINIMAL_NET */
+
+#endif /* CONTIKI */
diff --git a/extlibs/tinydtls/dtls_time.c b/extlibs/tinydtls/dtls_time.c
new file mode 100644 (file)
index 0000000..88c292a
--- /dev/null
@@ -0,0 +1,80 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file dtls_time.c
+ * @brief Clock Handling
+ */
+
+#include "tinydtls.h"
+#include "dtls_config.h"
+#include "dtls_time.h"
+
+#ifdef WITH_CONTIKI
+clock_time_t dtls_clock_offset;
+
+void
+dtls_clock_init(void) {
+  clock_init();
+  dtls_clock_offset = clock_time();
+}
+
+void
+dtls_ticks(dtls_tick_t *t) {
+  *t = clock_time();
+}
+
+#else /* WITH_CONTIKI */
+
+time_t dtls_clock_offset;
+
+void
+dtls_clock_init(void) {
+#ifdef HAVE_TIME_H
+  dtls_clock_offset = time(NULL);
+#else
+#  ifdef __GNUC__
+  /* Issue a warning when using gcc. Other prepropressors do 
+   *  not seem to have a similar feature. */ 
+#   warning "cannot initialize clock"
+#  endif
+  dtls_clock_offset = 0;
+#endif
+}
+
+void dtls_ticks(dtls_tick_t *t) {
+#ifdef HAVE_SYS_TIME_H
+  struct timeval tv;
+  gettimeofday(&tv, NULL);
+  *t = (tv.tv_sec - dtls_clock_offset) * DTLS_TICKS_PER_SECOND 
+    + (tv.tv_usec * DTLS_TICKS_PER_SECOND / 1000000);
+#else
+#error "clock not implemented"
+#endif
+}
+
+#endif /* WITH_CONTIKI */
+
+
diff --git a/extlibs/tinydtls/dtls_time.h b/extlibs/tinydtls/dtls_time.h
new file mode 100644 (file)
index 0000000..82ff062
--- /dev/null
@@ -0,0 +1,69 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file dtls_time.h
+ * @brief Clock Handling
+ */
+
+#ifndef _DTLS_DTLS_TIME_H_
+#define _DTLS_DTLS_TIME_H_
+
+#include <stdint.h>
+#include <sys/time.h>
+
+#include "tinydtls.h"
+
+/**
+ * @defgroup clock Clock Handling
+ * Default implementation of internal clock. You should redefine this if
+ * you do not have time() and gettimeofday().
+ * @{
+ */
+
+#ifdef WITH_CONTIKI
+#include "clock.h"
+#else /* WITH_CONTIKI */
+#include <time.h>
+
+#ifndef CLOCK_SECOND
+# define CLOCK_SECOND 1000
+#endif
+
+typedef uint32_t clock_time_t;
+#endif /* WITH_CONTIKI */
+
+typedef clock_time_t dtls_tick_t;
+
+#ifndef DTLS_TICKS_PER_SECOND
+#define DTLS_TICKS_PER_SECOND CLOCK_SECOND
+#endif /* DTLS_TICKS_PER_SECOND */
+
+void dtls_clock_init(void);
+void dtls_ticks(dtls_tick_t *t);
+
+/** @} */
+
+#endif /* _DTLS_DTLS_TIME_H_ */
diff --git a/extlibs/tinydtls/ecc/LICENSE.txt b/extlibs/tinydtls/ecc/LICENSE.txt
new file mode 100644 (file)
index 0000000..ab099ae
--- /dev/null
@@ -0,0 +1,21 @@
+Copyright (c) 2014, Kenneth MacKay
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright notice, this
+   list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/extlibs/tinydtls/ecc/Makefile.contiki b/extlibs/tinydtls/ecc/Makefile.contiki
new file mode 100644 (file)
index 0000000..7787d2d
--- /dev/null
@@ -0,0 +1,7 @@
+CONTIKI=../../..
+
+APPS += ecc
+
+CFLAGS += -DTEST_INCLUDE
+
+include $(CONTIKI)/Makefile.include
diff --git a/extlibs/tinydtls/ecc/Makefile.ecc b/extlibs/tinydtls/ecc/Makefile.ecc
new file mode 100644 (file)
index 0000000..382e48f
--- /dev/null
@@ -0,0 +1,3 @@
+# This is a -*- Makefile -*-
+
+ecc_src = ecc.c test_helper.c
diff --git a/extlibs/tinydtls/ecc/Makefile.in b/extlibs/tinydtls/ecc/Makefile.in
new file mode 100644 (file)
index 0000000..2a38603
--- /dev/null
@@ -0,0 +1,93 @@
+# Makefile for tinydtls
+#
+# Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+# Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use, copy,
+# modify, merge, publish, distribute, sublicense, and/or sell copies
+# of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+
+abs_builddir = @abs_builddir@
+top_builddir = @top_builddir@
+top_srcdir:= @top_srcdir@
+
+
+ECC_SOURCES:= ecc.c test/test_ecdh.c test/test_ecdsa.c
+ECC_HEADERS:= ecc.h
+FILES:=Makefile.in Makefile.contiki $(ECC_SOURCES) $(ECC_HEADERS)
+DISTDIR=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
+
+ifeq ("@WITH_CONTIKI@", "1")
+include Makefile.contiki
+else
+ECC_OBJECTS:= $(patsubst %.c, %.o, $(ECC_SOURCES)) ecc_test.o
+PROGRAMS:= test_ecdh test_ecdsa
+CPPFLAGS=@CPPFLAGS@
+CFLAGS=-Wall -std=c99 @CFLAGS@ -DTEST_INCLUDE
+LDLIBS=@LIBS@
+
+.PHONY: all dirs clean install distclean .gitignore doc
+
+.SUFFIXES:
+.SUFFIXES:      .c .o
+
+all: $(PROGRAMS)
+
+ecc_test.o:    ecc.c ecc.h
+       $(CC) $(CFLAGS) $(CPPFLAGS)  -c -o $@ $<
+
+test_ecdh: ecc.c test/test_ecdh.c
+       $(CC) $(CFLAGS) $(CPPFLAGS) -o test_ecdh ecc.c test/test_ecdh.c
+
+test_ecdsa:ecc.c test/test_ecdsa.c
+       $(CC) $(CFLAGS) $(CPPFLAGS) -o test_ecdsa ecc.c test/test_ecdsa.c
+
+check:
+       echo DISTDIR: $(DISTDIR)
+       echo top_builddir: $(top_builddir)
+
+clean:
+       @rm -f $(PROGRAMS) main.o $(LIB) $(OBJECTS)
+       for dir in $(SUBDIRS); do \
+               $(MAKE) -C $$dir clean ; \
+       done
+
+distclean:     clean
+       @rm -rf $(DISTDIR)
+       @rm -f *~ $(DISTDIR).tar.gz
+endif # WITH_CONTIKI
+
+dist:  $(FILES)
+       test -d $(DISTDIR)/ecc || mkdir $(DISTDIR)/ecc
+       cp -p $(FILES) $(DISTDIR)/ecc
+
+install:       $(HEADERS)
+       test -d $(includedir)/ecc || mkdir -p $(includedir)/ecc
+       $(install) $(HEADERS) $(includedir)/ecc
+
+.gitignore:
+       echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@
diff --git a/extlibs/tinydtls/ecc/README.md b/extlibs/tinydtls/ecc/README.md
new file mode 100644 (file)
index 0000000..24f1231
--- /dev/null
@@ -0,0 +1,208 @@
+micro-ecc
+==========
+
+A small and fast ECDH and ECDSA implementation for 8-bit, 32-bit, and 64-bit processors.
+
+The old version of micro-ecc can be found in the "old" branch.
+
+Features
+--------
+
+ * Resistant to known side-channel attacks.
+ * Written in C, with optional GCC inline assembly for AVR, ARM and Thumb platforms.
+ * Supports 8, 32, and 64-bit architectures.
+ * Small code size.
+ * No dynamic memory allocation.
+ * Support for 4 standard curves: secp160r1, secp192r1, secp256r1, and secp256k1.
+ * BSD 2-clause license.
+
+Usage Notes
+-----------
+### Point Representation ###
+Compressed points are represented in the standard format as defined in http://www.secg.org/collateral/sec1_final.pdf; uncompressed points are represented in standard format, but without the `0x04` prefix. `uECC_make_key()`, `uECC_shared_secret()`, `uECC_sign()`, and `uECC_verify()` only handle uncompressed points; you can use `uECC_compress()` and `uECC_decompress()` to convert between compressed and uncompressed point representations.
+
+Private keys are represented in the standard format.
+
+### Using the Code ###
+
+I recommend just copying (or symlink) uECC.h, uECC.c, and the appropriate asm\_&lt;arch&gt;\_.inc (if any) into your project. Then just `#include "uECC.h"` to use the micro-ecc functions.
+
+For use with Arduino, you can just create a symlink to the `uECC` directory in your Arduino `libraries` directory. You can then use uECC just like any other Arduino library (uECC should show up in the **Sketch**=>**Import Library** submenu).
+
+See uECC.h for documentation for each function.
+
+### Compilation Notes ###
+
+ * Should compile with any C/C++ compiler that supports stdint.h (this includes Visual Studio 2013).
+ * If you want to change the defaults for `uECC_CURVE` and `uECC_ASM`, you must change them in your Makefile or similar so that uECC.c is compiled with the desired values (ie, compile uECC.c with `-DuECC_CURVE=uECC_secp256r1` or whatever).
+ * When compiling for a Thumb-1 platform with inline assembly enabled (ie, `uECC_ASM` is defined to `uECC_asm_small` or `uECC_asm_fast`), you must use the `-fomit-frame-pointer` GCC option (this is enabled by default when compiling with `-O1` or higher).
+ * When compiling for an ARM/Thumb-2 platform with fast inline assembly enabled (ie, `uECC_ASM` is defined to `uECC_asm_fast`), you must use the `-fomit-frame-pointer` GCC option (this is enabled by default when compiling with `-O1` or higher).
+ * When compiling for AVR with inline assembly enabled, you must have optimizations enabled (compile with `-O1` or higher).
+ * When building for Windows, you will need to link in the `advapi32.lib` system library.
+
+ARM Performance
+---------------
+
+All tests were built using gcc 4.8.2 with `-O3`, and were run on a Raspberry Pi B+. `uECC_ASM` was defined to `uECC_asm_fast` and `ECC_SQUARE_FUNC` was defined to `1` in all cases. All times are in milliseconds.
+
+<table>
+       <tr>
+               <th></th>
+               <th>secp160r1</th>
+               <th>secp192r1</th>
+               <th>secp256r1</th>
+               <th>secp256k1</th>
+       </tr>
+       <tr>
+               <td><em>ECDH:</em></td>
+               <td>2.3</td>
+               <td>2.7</td>
+               <td>7.9</td>
+               <td>6.5</td>
+       </tr>
+       <tr>
+               <td><em>ECDSA sign:</em></td>
+               <td>2.8</td>
+               <td>3.1</td>
+               <td>8.6</td>
+               <td>7.2</td>
+       </tr>
+       <tr>
+               <td><em>ECDSA verify:</em></td>
+               <td>2.7</td>
+               <td>3.2</td>
+               <td>9.2</td>
+               <td>7.0</td>
+       </tr>
+</table>
+
+AVR Performance
+---------------
+
+All tests were built using avr-gcc 4.8.1 with `-Os`, and were run on a 16 MHz ATmega256RFR2. Code size refers to the space used by micro-ecc code and data.
+
+#### ECDH (fast) ####
+
+In these tests, `uECC_ASM` was defined to `uECC_asm_fast` and `ECC_SQUARE_FUNC` was defined to `1` in all cases.
+
+<table>
+       <tr>
+               <th></th>
+               <th>secp160r1</th>
+               <th>secp192r1</th>
+               <th>secp256r1</th>
+               <th>secp256k1</th>
+       </tr>
+       <tr>
+               <td><em>ECDH time (ms):</em></td>
+               <td>470</td>
+               <td>810</td>
+               <td>2220</td>
+               <td>1615</td>
+       </tr>
+       <tr>
+               <td><em>Code size (bytes):</em></td>
+               <td>10768</td>
+               <td>13112</td>
+               <td>20886</td>
+               <td>21126</td>
+       </tr>
+</table>
+
+#### ECDH (small) ####
+
+In these tests, `uECC_ASM` was defined to `uECC_asm_small` and `ECC_SQUARE_FUNC` was defined to `0` in all cases.
+
+<table>
+       <tr>
+               <th></th>
+               <th>secp160r1</th>
+               <th>secp192r1</th>
+               <th>secp256r1</th>
+               <th>secp256k1</th>
+       </tr>
+       <tr>
+               <td><em>ECDH time (ms):</em></td>
+               <td>1250</td>
+               <td>1810</td>
+               <td>4790</td>
+               <td>4700</td>
+       </tr>
+       <tr>
+               <td><em>Code size (bytes):</em></td>
+               <td>3244</td>
+               <td>3400</td>
+               <td>5274</td>
+               <td>3426</td>
+       </tr>
+</table>
+
+#### ECDSA (fast) ####
+
+In these tests, `uECC_ASM` was defined to `uECC_asm_fast` and `ECC_SQUARE_FUNC` was defined to `1` in all cases.
+
+<table>
+       <tr>
+               <th></th>
+               <th>secp160r1</th>
+               <th>secp192r1</th>
+               <th>secp256r1</th>
+               <th>secp256k1</th>
+       </tr>
+       <tr>
+               <td><em>ECDSA sign time (ms):</em></td>
+               <td>555</td>
+               <td>902</td>
+               <td>2386</td>
+               <td>1773</td>
+       </tr>
+       <tr>
+               <td><em>ECDSA verify time (ms):</em></td>
+               <td>590</td>
+               <td>990</td>
+               <td>2650</td>
+               <td>1800</td>
+       </tr>
+       <tr>
+               <td><em>Code size (bytes):</em></td>
+               <td>13246</td>
+               <td>14798</td>
+               <td>22594</td>
+               <td>22826</td>
+       </tr>
+</table>
+
+#### ECDSA (small) ####
+
+In these tests, `uECC_ASM` was defined to `uECC_asm_small` and `ECC_SQUARE_FUNC` was defined to `0` in all cases.
+
+<table>
+       <tr>
+               <th></th>
+               <th>secp160r1</th>
+               <th>secp192r1</th>
+               <th>secp256r1</th>
+               <th>secp256k1</th>
+       </tr>
+       <tr>
+               <td><em>ECDSA sign time (ms):</em></td>
+               <td>1359</td>
+               <td>1931</td>
+               <td>4998</td>
+               <td>4904</td>
+       </tr>
+       <tr>
+               <td><em>ECDSA verify time (ms):</em></td>
+               <td>1515</td>
+               <td>2160</td>
+               <td>5700</td>
+               <td>5220</td>
+       </tr>
+       <tr>
+               <td><em>Code size (bytes):</em></td>
+               <td>5690</td>
+               <td>5054</td>
+               <td>6980</td>
+               <td>5080</td>
+       </tr>
+</table>
diff --git a/extlibs/tinydtls/ecc/asm_arm.inc b/extlibs/tinydtls/ecc/asm_arm.inc
new file mode 100755 (executable)
index 0000000..f181b17
--- /dev/null
@@ -0,0 +1,1905 @@
+#define DEC_5 4
+#define DEC_6 5
+#define DEC_8 7
+
+#define DEC(N) uECC_CONCAT(DEC_, N)
+
+#define REPEAT_1(stuff) stuff
+#define REPEAT_2(stuff) REPEAT_1(stuff) stuff
+#define REPEAT_3(stuff) REPEAT_2(stuff) stuff
+#define REPEAT_4(stuff) REPEAT_3(stuff) stuff
+#define REPEAT_5(stuff) REPEAT_4(stuff) stuff
+#define REPEAT_6(stuff) REPEAT_5(stuff) stuff
+#define REPEAT_7(stuff) REPEAT_6(stuff) stuff
+#define REPEAT_8(stuff) REPEAT_7(stuff) stuff
+
+#define REPEAT(N, stuff) uECC_CONCAT(REPEAT_, N)(stuff)
+
+#define STR2(thing) #thing
+#define STR(thing) STR2(thing)
+
+#if (uECC_ASM == uECC_asm_fast)
+
+static uint32_t vli_add(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+    uint32_t l_carry = 0;
+    uint32_t l_left;
+    uint32_t l_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "ldmia %[lptr]!, {%[left]} \n\t"  /* Load left word. */
+        "ldmia %[rptr]!, {%[right]} \n\t" /* Load right word. */
+        "adds %[left], %[right] \n\t"     /* Add first word. */
+        "stmia %[dptr]!, {%[left]} \n\t"  /* Store result word. */
+        
+        /* Now we just do the remaining words with the carry bit (using ADC) */
+        REPEAT(DEC(uECC_WORDS), "ldmia %[lptr]!, {%[left]} \n\t"
+            "ldmia %[rptr]!, {%[right]} \n\t"
+            "adcs %[left], %[right] \n\t"
+            "stmia %[dptr]!, {%[left]} \n\t")
+        
+        "adcs %[carry], %[carry] \n\t" /* Store carry bit in l_carry. */
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+    #if (uECC_PLATFORM == uECC_arm_thumb)
+        : [dptr] "+l" (p_result), [lptr] "+l" (p_left), [rptr] "+l" (p_right),
+          [carry] "+l" (l_carry), [left] "=l" (l_left), [right] "=l" (l_right)
+    #else
+        : [dptr] "+r" (p_result), [lptr] "+r" (p_left), [rptr] "+r" (p_right),
+          [carry] "+r" (l_carry), [left] "=r" (l_left), [right] "=r" (l_right)
+    #endif
+        :
+        : "cc", "memory"
+    );
+    return l_carry;
+}
+#define asm_add 1
+
+static uint32_t vli_sub(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+    uint32_t l_carry = 0;
+    uint32_t l_left;
+    uint32_t l_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "ldmia %[lptr]!, {%[left]} \n\t"  /* Load left word. */
+        "ldmia %[rptr]!, {%[right]} \n\t" /* Load right word. */
+        "subs %[left], %[right] \n\t"     /* Subtract. */
+        "stmia %[dptr]!, {%[left]} \n\t"  /* Store result word. */
+        
+        /* Now we just do the remaining words with the carry bit (using SBC) */
+        REPEAT(DEC(uECC_WORDS), "ldmia %[lptr]!, {%[left]} \n\t"
+            "ldmia %[rptr]!, {%[right]} \n\t"
+            "sbcs %[left], %[right] \n\t"
+            "stmia %[dptr]!, {%[left]} \n\t")
+            
+        "adcs %[carry], %[carry] \n\t" /* Store carry bit in l_carry. */
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+    #if (uECC_PLATFORM == uECC_arm_thumb)
+        : [dptr] "+l" (p_result), [lptr] "+l" (p_left), [rptr] "+l" (p_right),
+          [carry] "+l" (l_carry), [left] "=l" (l_left), [right] "=l" (l_right)
+    #else
+        : [dptr] "+r" (p_result), [lptr] "+r" (p_left), [rptr] "+r" (p_right),
+          [carry] "+r" (l_carry), [left] "=r" (l_left), [right] "=r" (l_right)
+    #endif
+        :
+        : "cc", "memory"
+    );
+    return !l_carry; // note that on ARM, carry flag set means "no borrow" when subtracting (for some reason...)
+}
+#define asm_sub 1
+
+#if (uECC_PLATFORM != uECC_arm_thumb)
+#if (uECC_WORDS == 5)
+static void vli_mult(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    register uint32_t *r2 __asm__("r2") = p_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "add r0, 12 \n\t"
+        "add r2, 12 \n\t"
+        "ldmia r1!, {r3,r4} \n\t"
+        "ldmia r2!, {r6,r7} \n\t"
+
+        "umull r11, r12, r3, r6 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r9, r3, r7 \n\t"
+        "adds r12, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r11, r14, r4, r6 \n\t"
+        "adds r12, r11 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "umull r12, r14, r4, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adc r10, r14 \n\t"
+        "stmia r0!, {r9, r10} \n\t"
+
+        "sub r0, 28 \n\t"
+        "sub r2, 20 \n\t"
+        "ldmia r2!, {r6,r7,r8} \n\t"
+        "ldmia r1!, {r5} \n\t"
+
+        "umull r11, r12, r3, r6 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r9, r3, r7 \n\t"
+        "adds r12, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r11, r14, r4, r6 \n\t"
+        "adds r12, r11 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r5, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "ldmia r1!, {r3} \n\t"
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r4, r8 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r5, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r3, r6 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "ldmia r1!, {r4} \n\t"
+        "mov r14, #0 \n\t"
+        "umull r9, r10, r5, r8 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r3, r7 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r4, r6 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "ldr r9, [r0] \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, #0 \n\t"
+        "adc r14, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "ldmia r2!, {r6} \n\t"
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r5, r6 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r3, r8 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r4, r7 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "ldr r10, [r0] \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "ldmia r2!, {r7} \n\t"
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r5, r7 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r3, r6 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r4, r8 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "ldr r11, [r0] \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, #0 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r14} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "umull r14, r9, r4, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adc r11, r9 \n\t"
+        "stmia r0!, {r10, r11} \n\t"
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : "+r" (r0), "+r" (r1), "+r" (r2)
+        :
+        : "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r14", "cc", "memory"
+    );
+}
+#define asm_mult 1
+#endif /* (uECC_WORDS == 5) */
+
+#if (uECC_WORDS == 6)
+static void vli_mult(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    register uint32_t *r2 __asm__("r2") = p_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "add r0, 12 \n\t"
+        "add r2, 12 \n\t"
+        "ldmia r1!, {r3,r4,r5} \n\t"
+        "ldmia r2!, {r6,r7,r8} \n\t"
+
+        "umull r11, r12, r3, r6 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r9, r3, r7 \n\t"
+        "adds r12, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r11, r14, r4, r6 \n\t"
+        "adds r12, r11 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r5, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r4, r8 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r5, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "umull r9, r10, r5, r8 \n\t"
+        "adds r11, r9 \n\t"
+        "adc r12, r10 \n\t"
+        "stmia r0!, {r11, r12} \n\t"
+
+        "sub r0, 36 \n\t"
+        "sub r2, 24 \n\t"
+        "ldmia r2!, {r6,r7,r8} \n\t"
+
+        "umull r11, r12, r3, r6 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r9, r3, r7 \n\t"
+        "adds r12, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r11, r14, r4, r6 \n\t"
+        "adds r12, r11 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r5, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "ldmia r1!, {r3} \n\t"
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r4, r8 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r5, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r3, r6 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "ldmia r1!, {r4} \n\t"
+        "mov r14, #0 \n\t"
+        "umull r9, r10, r5, r8 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r3, r7 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r4, r6 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "ldr r9, [r0] \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, #0 \n\t"
+        "adc r14, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "ldmia r1!, {r5} \n\t"
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r3, r8 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r4, r7 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r5, r6 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "ldr r10, [r0] \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "ldmia r2!, {r6} \n\t"
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r3, r6 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r4, r8 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r5, r7 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "ldr r11, [r0] \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, #0 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r14} \n\t"
+
+        "ldmia r2!, {r7} \n\t"
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r5, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "ldr r12, [r0] \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, #0 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "ldmia r2!, {r8} \n\t"
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r3, r8 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r4, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r5, r6 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "mov r14, #0 \n\t"
+        "umull r9, r10, r4, r8 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r5, r7 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "umull r10, r11, r5, r8 \n\t"
+        "adds r12, r10 \n\t"
+        "adc r14, r11 \n\t"
+        "stmia r0!, {r12, r14} \n\t"
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : "+r" (r0), "+r" (r1), "+r" (r2)
+        :
+        : "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r14", "cc", "memory"
+    );
+}
+#define asm_mult 1
+#endif /* (uECC_WORDS == 6) */
+
+#if (uECC_WORDS == 8)
+static void vli_mult(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    register uint32_t *r2 __asm__("r2") = p_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "add r0, 24 \n\t"
+        "add r2, 24 \n\t"
+        "ldmia r1!, {r3,r4} \n\t"
+        "ldmia r2!, {r6,r7} \n\t"
+
+        "umull r11, r12, r3, r6 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r9, r3, r7 \n\t"
+        "adds r12, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r11, r14, r4, r6 \n\t"
+        "adds r12, r11 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "umull r12, r14, r4, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adc r10, r14 \n\t"
+        "stmia r0!, {r9, r10} \n\t"
+
+        "sub r0, 28 \n\t"
+        "sub r2, 20 \n\t"
+        "ldmia r2!, {r6,r7,r8} \n\t"
+        "ldmia r1!, {r5} \n\t"
+
+        "umull r11, r12, r3, r6 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r9, r3, r7 \n\t"
+        "adds r12, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r11, r14, r4, r6 \n\t"
+        "adds r12, r11 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r5, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "ldmia r1!, {r3} \n\t"
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r4, r8 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r5, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r3, r6 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "ldmia r1!, {r4} \n\t"
+        "mov r14, #0 \n\t"
+        "umull r9, r10, r5, r8 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r3, r7 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r4, r6 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "ldr r9, [r0] \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, #0 \n\t"
+        "adc r14, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "ldmia r2!, {r6} \n\t"
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r5, r6 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r3, r8 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r4, r7 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "ldr r10, [r0] \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "ldmia r2!, {r7} \n\t"
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r5, r7 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r3, r6 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r4, r8 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "ldr r11, [r0] \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, #0 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r14} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "umull r14, r9, r4, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adc r11, r9 \n\t"
+        "stmia r0!, {r10, r11} \n\t"
+
+        "sub r0, 52 \n\t"
+        "sub r1, 20 \n\t"
+        "sub r2, 32 \n\t"
+        "ldmia r1!, {r3,r4,r5} \n\t"
+        "ldmia r2!, {r6,r7,r8} \n\t"
+
+        "umull r11, r12, r3, r6 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r9, r3, r7 \n\t"
+        "adds r12, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r11, r14, r4, r6 \n\t"
+        "adds r12, r11 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r3, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r5, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "ldmia r1!, {r3} \n\t"
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r4, r8 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r5, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r3, r6 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "ldmia r1!, {r4} \n\t"
+        "mov r14, #0 \n\t"
+        "umull r9, r10, r5, r8 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r3, r7 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r4, r6 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "ldr r9, [r0] \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, #0 \n\t"
+        "adc r14, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "ldmia r1!, {r5} \n\t"
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r3, r8 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r4, r7 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r5, r6 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "ldr r10, [r0] \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "ldmia r1!, {r3} \n\t"
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r4, r8 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r5, r7 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r3, r6 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "ldr r11, [r0] \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, #0 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r14} \n\t"
+
+        "ldmia r1!, {r4} \n\t"
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r5, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r3, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "ldr r12, [r0] \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, #0 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "ldmia r2!, {r6} \n\t"
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r5, r6 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r3, r8 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r4, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "ldmia r2!, {r7} \n\t"
+        "mov r14, #0 \n\t"
+        "umull r9, r10, r5, r7 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r3, r6 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "umull r9, r10, r4, r8 \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r14, #0 \n\t"
+        "ldr r9, [r0] \n\t"
+        "adds r11, r9 \n\t"
+        "adcs r12, #0 \n\t"
+        "adc r14, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "ldmia r2!, {r8} \n\t"
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r5, r8 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r3, r7 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "umull r10, r11, r4, r6 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "ldr r10, [r0] \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r14, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "ldmia r2!, {r6} \n\t"
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r5, r6 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r3, r8 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r4, r7 \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "ldr r11, [r0] \n\t"
+        "adds r14, r11 \n\t"
+        "adcs r9, #0 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r14} \n\t"
+
+        "ldmia r2!, {r7} \n\t"
+        "mov r11, #0 \n\t"
+        "umull r12, r14, r5, r7 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r3, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "umull r12, r14, r4, r8 \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, r14 \n\t"
+        "adc r11, #0 \n\t"
+        "ldr r12, [r0] \n\t"
+        "adds r9, r12 \n\t"
+        "adcs r10, #0 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r14, r9, r3, r7 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r14, r9, r4, r6 \n\t"
+        "adds r10, r14 \n\t"
+        "adcs r11, r9 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r10} \n\t"
+
+        "umull r9, r10, r4, r7 \n\t"
+        "adds r11, r9 \n\t"
+        "adc r12, r10 \n\t"
+        "stmia r0!, {r11, r12} \n\t"
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : "+r" (r0), "+r" (r1), "+r" (r2)
+        :
+        : "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r14", "cc", "memory"
+    );
+}
+#define asm_mult 1
+#endif /* (uECC_WORDS == 8) */
+
+#if (uECC_WORDS == 5)
+static void vli_square(uint32_t *p_result, uint32_t *p_left)
+{
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "ldmia r1!, {r2,r3,r4,r5,r6} \n\t"
+
+        "umull r11, r12, r2, r2 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r2, r3 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r8, r11, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r8, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r2, r4 \n\t"
+        "adds r11, r11 \n\t"
+        "adcs r12, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r3, r3 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r2, r5 \n\t"
+        "umull r1, r14, r3, r4 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r14 \n\t"
+        "adc r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r8, r9, r2, r6 \n\t"
+        "umull r1, r14, r3, r5 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r9, r9 \n\t"
+        "adc r10, r10 \n\t"
+        "umull r1, r14, r4, r4 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r3, r6 \n\t"
+        "umull r1, r14, r4, r5 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r14 \n\t"
+        "adc r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r8, #0 \n\t"
+        "umull r1, r10, r4, r6 \n\t"
+        "adds r1, r1 \n\t"
+        "adcs r10, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "adds r11, r1 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "umull r1, r10, r5, r5 \n\t"
+        "adds r11, r1 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r1, r10, r5, r6 \n\t"
+        "adds r1, r1 \n\t"
+        "adcs r10, r10 \n\t"
+        "adc r11, #0 \n\t"
+        "adds r12, r1 \n\t"
+        "adcs r8, r10 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "umull r1, r10, r6, r6 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r10 \n\t"
+        "stmia r0!, {r8, r11} \n\t"
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : "+r" (r0), "+r" (r1)
+        :
+        : "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r14", "cc", "memory"
+    );
+}
+#define asm_square 1
+#endif /* (uECC_WORDS == 5) */
+
+#if (uECC_WORDS == 6)
+static void vli_square(uint32_t *p_result, uint32_t *p_left)
+{
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "ldmia r1!, {r2,r3,r4,r5,r6,r7} \n\t"
+
+        "umull r11, r12, r2, r2 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r2, r3 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r8, r11, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r8, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r2, r4 \n\t"
+        "adds r11, r11 \n\t"
+        "adcs r12, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r3, r3 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r2, r5 \n\t"
+        "umull r1, r14, r3, r4 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r14 \n\t"
+        "adc r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r8, r9, r2, r6 \n\t"
+        "umull r1, r14, r3, r5 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r9, r9 \n\t"
+        "adc r10, r10 \n\t"
+        "umull r1, r14, r4, r4 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r2, r7 \n\t"
+        "umull r1, r14, r3, r6 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r14 \n\t"
+        "adc r12, #0 \n\t"
+        "umull r1, r14, r4, r5 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r14 \n\t"
+        "adc r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r8, r9, r3, r7 \n\t"
+        "umull r1, r14, r4, r6 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r9, r9 \n\t"
+        "adc r10, r10 \n\t"
+        "umull r1, r14, r5, r5 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r9, r14 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r4, r7 \n\t"
+        "umull r1, r14, r5, r6 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r14 \n\t"
+        "adc r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r8, #0 \n\t"
+        "umull r1, r10, r5, r7 \n\t"
+        "adds r1, r1 \n\t"
+        "adcs r10, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "adds r11, r1 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "umull r1, r10, r6, r6 \n\t"
+        "adds r11, r1 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r1, r10, r6, r7 \n\t"
+        "adds r1, r1 \n\t"
+        "adcs r10, r10 \n\t"
+        "adc r11, #0 \n\t"
+        "adds r12, r1 \n\t"
+        "adcs r8, r10 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "umull r1, r10, r7, r7 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r10 \n\t"
+        "stmia r0!, {r8, r11} \n\t"
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : "+r" (r0), "+r" (r1)
+        :
+        : "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r14", "cc", "memory"
+    );
+}
+#define asm_square 1
+#endif /* (uECC_WORDS == 6) */
+
+#if (uECC_WORDS == 8)
+static void vli_square(uint32_t *p_result, uint32_t *p_left)
+{
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "ldmia r1!, {r2, r3} \n\t"
+        "add r1, 16 \n\t"
+        "ldmia r1!, {r5, r6} \n\t"
+        "add r0, 24 \n\t"
+
+        "umull r8, r9, r2, r5 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "umull r12, r10, r2, r6 \n\t"
+        "adds r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r9} \n\t"
+
+        "umull r8, r9, r3, r6 \n\t"
+        "adds r10, r8 \n\t"
+        "adc r11, r9, #0 \n\t"
+        "stmia r0!, {r10, r11} \n\t"
+
+        "sub r0, 40 \n\t"
+        "sub r1, 32 \n\t"
+        "ldmia r1!, {r2,r3,r4,r5,r6,r7} \n\t"
+
+        "umull r11, r12, r2, r2 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r9, #0 \n\t"
+        "umull r10, r11, r2, r3 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r8, r11, #0 \n\t"
+        "adc r9, #0 \n\t"
+        "adds r12, r10 \n\t"
+        "adcs r8, r11 \n\t"
+        "adc r9, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r11, r12, r2, r4 \n\t"
+        "adds r11, r11 \n\t"
+        "adcs r12, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "umull r11, r12, r3, r3 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r2, r5 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r3, r4 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r8, r9, r2, r6 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r3, r5 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r9, r9 \n\t"
+        "adc r10, r10 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r4, r4 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r2, r7 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r3, r6 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r4, r5 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "ldmia r1!, {r2} \n\t"
+        "mov r10, #0 \n\t"
+        "umull r8, r9, r3, r7 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r4, r6 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r8, r14 \n\t"
+        "adcs r9, #0 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r9, r9 \n\t"
+        "adc r10, r10 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r5, r5 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r3, r2 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r4, r7 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r5, r6 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r8, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "ldmia r1!, {r3} \n\t"
+        "mov r10, #0 \n\t"
+        "umull r8, r9, r4, r2 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r5, r7 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r8, r14 \n\t"
+        "adcs r9, #0 \n\t"
+        "adc r10, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r9, r9 \n\t"
+        "adc r10, r10 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r6, r6 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r4, r3 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r5, r2 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r6, r7 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "ldr r14, [r0] \n\t"
+        "adds r8, r14 \n\t"
+        "adcs r11, #0 \n\t"
+        "adc r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r10, #0 \n\t"
+        "umull r8, r9, r5, r3 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r6, r2 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r9, r9 \n\t"
+        "adc r10, r10 \n\t"
+        "mov r14, r9 \n\t"
+        "umlal r8, r9, r7, r7 \n\t"
+        "cmp r14, r9 \n\t"
+        "it hi \n\t"
+        "adchi r10, #0 \n\t"
+        "adds r8, r11 \n\t"
+        "adcs r9, r12 \n\t"
+        "adc r10, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r12, #0 \n\t"
+        "umull r8, r11, r6, r3 \n\t"
+        "mov r14, r11 \n\t"
+        "umlal r8, r11, r7, r2 \n\t"
+        "cmp r14, r11 \n\t"
+        "it hi \n\t"
+        "adchi r12, #0 \n\t"
+        "adds r8, r8 \n\t"
+        "adcs r11, r11 \n\t"
+        "adc r12, r12 \n\t"
+        "adds r8, r9 \n\t"
+        "adcs r11, r10 \n\t"
+        "adc r12, #0 \n\t"
+        "stmia r0!, {r8} \n\t"
+
+        "mov r8, #0 \n\t"
+        "umull r1, r10, r7, r3 \n\t"
+        "adds r1, r1 \n\t"
+        "adcs r10, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "adds r11, r1 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "umull r1, r10, r2, r2 \n\t"
+        "adds r11, r1 \n\t"
+        "adcs r12, r10 \n\t"
+        "adc r8, #0 \n\t"
+        "stmia r0!, {r11} \n\t"
+
+        "mov r11, #0 \n\t"
+        "umull r1, r10, r2, r3 \n\t"
+        "adds r1, r1 \n\t"
+        "adcs r10, r10 \n\t"
+        "adc r11, #0 \n\t"
+        "adds r12, r1 \n\t"
+        "adcs r8, r10 \n\t"
+        "adc r11, #0 \n\t"
+        "stmia r0!, {r12} \n\t"
+
+        "umull r1, r10, r3, r3 \n\t"
+        "adds r8, r1 \n\t"
+        "adcs r11, r10 \n\t"
+        "stmia r0!, {r8, r11} \n\t"
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : "+r" (r0), "+r" (r1)
+        :
+        : "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r14", "cc", "memory"
+    );
+}
+#define asm_square 1
+#endif /* (uECC_WORDS == 8) */
+
+#endif /* (uECC_PLATFORM != uECC_arm_thumb) */
+
+#endif /* (uECC_ASM == uECC_asm_fast) */
+
+#if !asm_add
+static uint32_t vli_add(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+    uint32_t l_counter = uECC_WORDS;
+    uint32_t l_carry = 0; /* carry = 0 initially */
+    uint32_t l_left;
+    uint32_t l_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "1: \n\t"
+        "ldmia %[lptr]!, {%[left]} \n\t"  /* Load left word. */
+        "ldmia %[rptr]!, {%[right]} \n\t" /* Load right word. */
+        "lsrs %[carry], #1 \n\t"          /* Set up carry flag (l_carry = 0 after this). */
+        "adcs %[left], %[right] \n\t"     /* Add with carry. */
+        "adcs %[carry], %[carry] \n\t"    /* Store carry bit in l_carry. */
+        "stmia %[dptr]!, {%[left]} \n\t"  /* Store result word. */
+        "subs %[ctr], #1 \n\t"            /* Decrement index. */
+        "bne 1b \n\t"                     /* Loop until index == 0. */
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+    #if (uECC_PLATFORM == uECC_arm_thumb)
+        : [dptr] "+l" (p_result), [lptr] "+l" (p_left), [rptr] "+l" (p_right),
+          [ctr] "+l" (l_counter), [carry] "+l" (l_carry), [left] "=l" (l_left), [right] "=l" (l_right)
+    #else
+        : [dptr] "+r" (p_result), [lptr] "+r" (p_left), [rptr] "+r" (p_right),
+          [ctr] "+r" (l_counter), [carry] "+r" (l_carry), [left] "=r" (l_left), [right] "=r" (l_right)
+    #endif
+        :
+        : "cc", "memory"
+    );
+    return l_carry;
+}
+#define asm_add 1
+#endif
+
+#if !asm_sub
+static uint32_t vli_sub(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+    uint32_t l_counter = uECC_WORDS;
+    uint32_t l_carry = 1; /* carry = 1 initially (means don't borrow) */
+    uint32_t l_left;
+    uint32_t l_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "1: \n\t"
+        "ldmia %[lptr]!, {%[left]} \n\t"  /* Load left word. */
+        "ldmia %[rptr]!, {%[right]} \n\t" /* Load right word. */
+        "lsrs %[carry], #1 \n\t"          /* Set up carry flag (l_carry = 0 after this). */
+        "sbcs %[left], %[right] \n\t"     /* Subtract with borrow. */
+        "adcs %[carry], %[carry] \n\t"    /* Store carry bit in l_carry. */
+        "stmia %[dptr]!, {%[left]} \n\t"  /* Store result word. */
+        "subs %[ctr], #1 \n\t"            /* Decrement index. */
+        "bne 1b \n\t"                     /* Loop until index == 0. */
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+    #if (uECC_PLATFORM == uECC_arm_thumb)
+        : [dptr] "+l" (p_result), [lptr] "+l" (p_left), [rptr] "+l" (p_right),
+          [ctr] "+l" (l_counter), [carry] "+l" (l_carry), [left] "=l" (l_left), [right] "=l" (l_right)
+    #else
+        : [dptr] "+r" (p_result), [lptr] "+r" (p_left), [rptr] "+r" (p_right),
+          [ctr] "+r" (l_counter), [carry] "+r" (l_carry), [left] "=r" (l_left), [right] "=r" (l_right)
+    #endif
+        :
+        : "cc", "memory"
+    );
+    return !l_carry;
+}
+#define asm_sub 1
+#endif
+
+#if !asm_mult
+static void vli_mult(uint32_t *p_result, uint32_t *p_left, uint32_t *p_right)
+{
+#if (uECC_PLATFORM != uECC_arm_thumb)
+    uint32_t c0 = 0;
+    uint32_t c1 = 0;
+    uint32_t c2 = 0;
+    uint32_t k = 0;
+    uint32_t i;
+    uint32_t t0, t1;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        
+        "1: \n\t" /* outer loop (k < uECC_WORDS) */
+        "movs %[i], #0 \n\t" /* i = 0 */
+        "b 3f \n\t"
+        
+        "2: \n\t" /* outer loop (k >= uECC_WORDS) */
+        "movs %[i], %[k] \n\t"      /* i = k */
+        "subs %[i], %[eccdm1] \n\t" /* i = k - (uECC_WORDS - 1) (times 4) */
+        
+        "3: \n\t" /* inner loop */
+        "subs %[t0], %[k], %[i] \n\t" /* t0 = k-i */
+        
+        "ldr %[t1], [%[right], %[t0]] \n\t" /* t1 = p_right[k-i] */
+        "ldr %[t0], [%[left], %[i]] \n\t"   /* t0 = p_left[i] */
+        
+        "umull %[t0], %[t1], %[t0], %[t1] \n\t" /* (t0, t1) = p_left[i] * p_right[k-i] */
+        
+        "adds %[c0], %[t0] \n\t" /* add low word to c0 */
+        "adcs %[c1], %[t1] \n\t" /* add high word to c1, including carry */
+        "adcs %[c2], #0 \n\t"    /* add carry to c2 */
+
+        "adds %[i], #4 \n\t"     /* i += 4 */
+        "cmp %[i], %[eccd] \n\t" /* i < uECC_WORDS (times 4)? */
+        "bge 4f \n\t" /* if not, exit the loop */
+        "cmp %[i], %[k] \n\t"    /* i <= k? */
+        "ble 3b \n\t" /* if so, continue looping */
+        
+        "4: \n\t" /* end inner loop */
+        
+        "str %[c0], [%[result], %[k]] \n\t" /* p_result[k] = c0 */
+        "mov %[c0], %[c1] \n\t"     /* c0 = c1 */
+        "mov %[c1], %[c2] \n\t"     /* c1 = c2 */
+        "movs %[c2], #0 \n\t"       /* c2 = 0 */
+        "adds %[k], #4 \n\t"        /* k += 4 */
+        "cmp %[k], %[eccd] \n\t"    /* k < uECC_WORDS (times 4) ? */
+        "blt 1b \n\t" /* if not, loop back, start with i = 0 */
+        "cmp %[k], %[eccd2m1] \n\t" /* k < uECC_WORDS * 2 - 1 (times 4) ? */
+        "blt 2b \n\t" /* if not, loop back, start with i = (k+1) - uECC_WORDS */
+        /* end outer loop */
+        
+        "str %[c0], [%[result], %[k]] \n\t" /* p_result[uECC_WORDS * 2 - 1] = c0 */
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : [c0] "+r" (c0), [c1] "+r" (c1), [c2] "+r" (c2), [k] "+r" (k), [i] "=&r" (i), [t0] "=&r" (t0), [t1] "=&r" (t1)
+        : [result] "r" (p_result), [left] "r" (p_left), [right] "r" (p_right),
+          [eccd] "I" (uECC_WORDS * 4), [eccdm1] "I" ((uECC_WORDS-1) * 4), [eccd2m1] "I" ((uECC_WORDS * 2 - 1) * 4)
+        : "cc", "memory"
+    );
+    
+#else /* Thumb-1 */
+
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    register uint32_t *r2 __asm__("r2") = p_right;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "movs r3, #0 \n\t" /* c0 = 0 */
+        "movs r4, #0 \n\t" /* c1 = 0 */
+        "movs r5, #0 \n\t" /* c2 = 0 */
+        "movs r6, #0 \n\t" /* k = 0 */
+        
+        "push {r0} \n\t" /* keep p_result on the stack */
+        
+        "1: \n\t" /* outer loop (k < uECC_WORDS) */
+        "movs r7, #0 \n\t" /* r7 = i = 0 */
+        "b 3f \n\t"
+        
+        "2: \n\t" /* outer loop (k >= uECC_WORDS) */
+        "movs r7, r6 \n\t"        /* r7 = k */
+        "subs r7, %[eccdm1] \n\t" /* r7 = i = k - (uECC_WORDS - 1) (times 4) */
+        
+        "3: \n\t" /* inner loop */
+        "push {r3, r4, r5, r6} \n\t" /* push things, r3 (c0) is at the top of stack. */
+        "subs r0, r6, r7 \n\t"       /* r0 = k-i */
+        
+        "ldr r4, [r2, r0] \n\t" /* r4 = p_right[k-i] */
+        "ldr r0, [r1, r7] \n\t" /* r0 = p_left[i] */
+        
+        "lsrs r3, r0, #16 \n\t" /* r3 = a1 */
+        "uxth r0, r0 \n\t"      /* r0 = a0 */
+        
+        "lsrs r5, r4, #16 \n\t" /* r5 = b1 */
+        "uxth r4, r4 \n\t"      /* r4 = b0 */
+        
+        "movs r6, r3 \n\t"     /* r6 = a1 */
+        "muls r6, r5, r6 \n\t" /* r6 = a1*b1 */
+        "muls r3, r4, r3 \n\t" /* r3 = b0*a1 */
+        "muls r5, r0, r5 \n\t" /* r5 = a0*b1 */
+        "muls r0, r4, r0 \n\t" /* r0 = a0*b0 */
+        
+        "movs r4, #0 \n\t"  /* r4 = 0 */
+        "adds r3, r5 \n\t"  /* r3 = b0*a1 + a0*b1 */
+        "adcs r4, r4 \n\t"  /* r4 = carry */
+        "lsls r4, #16 \n\t" /* r4 = carry << 16 */
+        "adds r6, r4 \n\t"  /* r6 = a1*b1 + carry */
+        
+        "lsls r4, r3, #16 \n\t" /* r4 = (b0*a1 + a0*b1) << 16 */
+        "lsrs r3, #16 \n\t"     /* r3 = (b0*a1 + a0*b1) >> 16 */
+        "adds r0, r4 \n\t"      /* r0 = low word = a0*b0 + ((b0*a1 + a0*b1) << 16) */
+        "adcs r6, r3 \n\t"      /* r6 = high word = a1*b1 + carry + ((b0*a1 + a0*b1) >> 16) */
+        
+        "pop {r3, r4, r5} \n\t" /* r3 = c0, r4 = c1, r5 = c2 */
+        "adds r3, r0 \n\t"      /* add low word to c0 */
+        "adcs r4, r6 \n\t"      /* add high word to c1, including carry */
+        "movs r0, #0 \n\t"      /* r0 = 0 (does not affect carry bit) */
+        "adcs r5, r0 \n\t"      /* add carry to c2 */
+        
+        "pop {r6} \n\t" /* r6 = k */
+
+        "adds r7, #4 \n\t"     /* i += 4 */
+        "cmp r7, %[eccd] \n\t" /* i < uECC_WORDS (times 4)? */
+        "bge 4f \n\t" /* if not, exit the loop */
+        "cmp r7, r6 \n\t"      /* i <= k? */
+        "ble 3b \n\t" /* if so, continue looping */
+        
+        "4: \n\t" /* end inner loop */
+        
+        "ldr r0, [sp, #0] \n\t" /* r0 = p_result */
+        
+        "str r3, [r0, r6] \n\t"   /* p_result[k] = c0 */
+        "mov r3, r4 \n\t"         /* c0 = c1 */
+        "mov r4, r5 \n\t"         /* c1 = c2 */
+        "movs r5, #0 \n\t"        /* c2 = 0 */
+        "adds r6, #4 \n\t"        /* k += 4 */
+        "cmp r6, %[eccd] \n\t"    /* k < uECC_WORDS (times 4) ? */
+        "blt 1b \n\t" /* if not, loop back, start with i = 0 */
+        "cmp r6, %[eccd2m1] \n\t" /* k < uECC_WORDS * 2 - 1 (times 4) ? */
+        "blt 2b \n\t" /* if not, loop back, start with i = (k+1) - uECC_WORDS */
+        /* end outer loop */
+        
+        "str r3, [r0, r6] \n\t" /* p_result[uECC_WORDS * 2 - 1] = c0 */
+        "pop {r0} \n\t"         /* pop p_result off the stack */
+        
+        ".syntax divided \n\t"
+        : 
+        : [r0] "l" (r0), [r1] "l" (r1), [r2] "l" (r2), [eccd] "I" (uECC_WORDS * 4), [eccdm1] "I" ((uECC_WORDS-1) * 4), [eccd2m1] "I" ((uECC_WORDS * 2 - 1) * 4)
+        : "r3", "r4", "r5", "r6", "r7", "cc", "memory"
+    );
+#endif
+}
+#define asm_mult 1
+#endif /* !asm_mult */
+
+#if uECC_SQUARE_FUNC
+#if !asm_square
+static void vli_square(uint32_t *p_result, uint32_t *p_left)
+{
+#if (uECC_PLATFORM != uECC_arm_thumb)
+    uint32_t c0 = 0;
+    uint32_t c1 = 0;
+    uint32_t c2 = 0;
+    uint32_t k = 0;
+    uint32_t i, tt;
+    uint32_t t0, t1;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        
+        "1: \n\t" /* outer loop (k < uECC_WORDS) */
+        "movs %[i], #0 \n\t" /* i = 0 */
+        "b 3f \n\t"
+        
+        "2: \n\t" /* outer loop (k >= uECC_WORDS) */
+        "movs %[i], %[k] \n\t"      /* i = k */
+        "subs %[i], %[eccdm1] \n\t" /* i = k - (uECC_WORDS - 1) (times 4) */
+        
+        "3: \n\t" /* inner loop */
+        "subs %[tt], %[k], %[i] \n\t" /* tt = k-i */
+        
+        "ldr %[t1], [%[left], %[tt]] \n\t" /* t1 = p_left[k-i] */
+        "ldr %[t0], [%[left], %[i]] \n\t"  /* t0 = p_left[i] */
+        
+        "umull %[t0], %[t1], %[t0], %[t1] \n\t" /* (t0, t1) = p_left[i] * p_right[k-i] */
+        
+        "cmp %[i], %[tt] \n\t"   /* (i < k-i) ? */
+        "bge 4f \n\t" /* if i >= k-i, skip */
+        "lsls %[t1], #1 \n\t"    /* high word << 1 */
+        "adc %[c2], #0 \n\t"     /* add carry bit to c2 */
+        "lsls %[t0], #1 \n\t"       /* low word << 1 */
+        "adc %[t1], #0 \n\t"     /* add carry bit to high word */
+        
+        "4: \n\t"
+
+        "adds %[c0], %[t0] \n\t" /* add low word to c0 */
+        "adcs %[c1], %[t1] \n\t" /* add high word to c1, including carry */
+        "adc %[c2], #0 \n\t"     /* add carry to c2 */
+        
+        "adds %[i], #4 \n\t"          /* i += 4 */
+        "cmp %[i], %[k] \n\t"         /* i <= k? */
+        "bge 5f \n\t" /* if not, exit the loop */
+        "subs %[tt], %[k], %[i] \n\t" /* tt = k-i */
+        "cmp %[i], %[tt] \n\t"        /* i <= k-i? */
+        "ble 3b \n\t" /* if so, continue looping */
+        
+        "5: \n\t" /* end inner loop */
+        
+        "str %[c0], [%[result], %[k]] \n\t" /* p_result[k] = c0 */
+        "mov %[c0], %[c1] \n\t"     /* c0 = c1 */
+        "mov %[c1], %[c2] \n\t"     /* c1 = c2 */
+        "movs %[c2], #0 \n\t"       /* c2 = 0 */
+        "adds %[k], #4 \n\t"        /* k += 4 */
+        "cmp %[k], %[eccd] \n\t"    /* k < uECC_WORDS (times 4) ? */
+        "blt 1b \n\t" /* if not, loop back, start with i = 0 */
+        "cmp %[k], %[eccd2m1] \n\t" /* k < uECC_WORDS * 2 - 1 (times 4) ? */
+        "blt 2b \n\t" /* if not, loop back, start with i = (k+1) - uECC_WORDS */
+        /* end outer loop */
+        
+        "str %[c0], [%[result], %[k]] \n\t" /* p_result[uECC_WORDS * 2 - 1] = c0 */
+    #if (uECC_PLATFORM != uECC_arm_thumb2)
+        ".syntax divided \n\t"
+    #endif
+        : [c0] "+r" (c0), [c1] "+r" (c1), [c2] "+r" (c2), [k] "+r" (k), [i] "=&r" (i), [tt] "=&r" (tt), [t0] "=&r" (t0), [t1] "=&r" (t1)
+        : [result] "r" (p_result), [left] "r" (p_left),
+          [eccd] "I" (uECC_WORDS * 4), [eccdm1] "I" ((uECC_WORDS-1) * 4), [eccd2m1] "I" ((uECC_WORDS * 2 - 1) * 4)
+        : "cc", "memory"
+    );
+    
+#else
+
+    register uint32_t *r0 __asm__("r0") = p_result;
+    register uint32_t *r1 __asm__("r1") = p_left;
+    
+    __asm__ volatile (
+        ".syntax unified \n\t"
+        "movs r2, #0 \n\t" /* c0 = 0 */
+        "movs r3, #0 \n\t" /* c1 = 0 */
+        "movs r4, #0 \n\t" /* c2 = 0 */
+        "movs r5, #0 \n\t" /* k = 0 */
+        
+        "push {r0} \n\t" /* keep p_result on the stack */
+        
+        "1: \n\t" /* outer loop (k < uECC_WORDS) */
+        "movs r6, #0 \n\t" /* r6 = i = 0 */
+        "b 3f \n\t"
+        
+        "2: \n\t" /* outer loop (k >= uECC_WORDS) */
+        "movs r6, r5 \n\t"        /* r6 = k */
+        "subs r6, %[eccdm1] \n\t" /* r6 = i = k - (uECC_WORDS - 1) (times 4) */
+        
+        "3: \n\t" /* inner loop */
+        "push {r2, r3, r4, r5} \n\t" /* push things, r2 (c0) is at the top of stack. */
+        "subs r7, r5, r6 \n\t"       /* r7 = k-i */
+        
+        "ldr r3, [r1, r7] \n\t" /* r3 = p_left[k-i] */
+        "ldr r0, [r1, r6] \n\t" /* r0 = p_left[i] */
+        
+        "lsrs r2, r0, #16 \n\t" /* r2 = a1 */
+        "uxth r0, r0 \n\t"      /* r0 = a0 */
+        
+        "lsrs r4, r3, #16 \n\t" /* r4 = b1 */
+        "uxth r3, r3 \n\t"      /* r3 = b0 */
+        
+        "movs r5, r2 \n\t"     /* r5 = a1 */
+        "muls r5, r4, r5 \n\t" /* r5 = a1*b1 */
+        "muls r2, r3, r2 \n\t" /* r2 = b0*a1 */
+        "muls r4, r0, r4 \n\t" /* r4 = a0*b1 */
+        "muls r0, r3, r0 \n\t" /* r0 = a0*b0 */
+        
+        "movs r3, #0 \n\t"  /* r3 = 0 */
+        "adds r2, r4 \n\t"  /* r2 = b0*a1 + a0*b1 */
+        "adcs r3, r3 \n\t"  /* r3 = carry */
+        "lsls r3, #16 \n\t" /* r3 = carry << 16 */
+        "adds r5, r3 \n\t"  /* r5 = a1*b1 + carry */
+        
+        "lsls r3, r2, #16 \n\t" /* r3 = (b0*a1 + a0*b1) << 16 */
+        "lsrs r2, #16 \n\t"     /* r2 = (b0*a1 + a0*b1) >> 16 */
+        "adds r0, r3 \n\t"      /* r0 = low word = a0*b0 + ((b0*a1 + a0*b1) << 16) */
+        "adcs r5, r2 \n\t"      /* r5 = high word = a1*b1 + carry + ((b0*a1 + a0*b1) >> 16) */
+    
+        "movs r3, #0 \n\t"  /* r3 = 0 */
+        "cmp r6, r7 \n\t"   /* (i < k-i) ? */
+        "mov r7, r3 \n\t"   /* r7 = 0 (does not affect condition)*/
+        "bge 4f \n\t" /* if i >= k-i, skip */
+        "lsls r5, #1 \n\t"  /* high word << 1 */
+        "adcs r7, r3 \n\t"  /* r7 = carry bit for c2 */
+        "lsls r0, #1 \n\t"  /* low word << 1 */
+        "adcs r5, r3 \n\t"  /* add carry from shift to high word */
+        
+        "4: \n\t"
+        "pop {r2, r3, r4} \n\t" /* r2 = c0, r3 = c1, r4 = c2 */
+        "adds r2, r0 \n\t"      /* add low word to c0 */
+        "adcs r3, r5 \n\t"      /* add high word to c1, including carry */
+        "movs r0, #0 \n\t"      /* r0 = 0 (does not affect carry bit) */
+        "adcs r4, r0 \n\t"      /* add carry to c2 */
+        "adds r4, r7 \n\t"      /* add carry from doubling (if any) */
+        
+        "pop {r5} \n\t" /* r5 = k */
+        
+        "adds r6, #4 \n\t"     /* i += 4 */
+        "cmp r6, r5 \n\t"      /* i <= k? */
+        "bge 5f \n\t" /* if not, exit the loop */
+        "subs r7, r5, r6 \n\t" /* r7 = k-i */
+        "cmp r6, r7 \n\t"      /* i <= k-i? */
+        "ble 3b \n\t" /* if so, continue looping */
+        
+        "5: \n\t" /* end inner loop */
+        
+        "ldr r0, [sp, #0] \n\t" /* r0 = p_result */
+        
+        "str r2, [r0, r5] \n\t"   /* p_result[k] = c0 */
+        "mov r2, r3 \n\t"         /* c0 = c1 */
+        "mov r3, r4 \n\t"         /* c1 = c2 */
+        "movs r4, #0 \n\t"        /* c2 = 0 */
+        "adds r5, #4 \n\t"        /* k += 4 */
+        "cmp r5, %[eccd] \n\t"    /* k < uECC_WORDS (times 4) ? */
+        "blt 1b \n\t" /* if not, loop back, start with i = 0 */
+        "cmp r5, %[eccd2m1] \n\t" /* k < uECC_WORDS * 2 - 1 (times 4) ? */
+        "blt 2b \n\t" /* if not, loop back, start with i = (k+1) - uECC_WORDS */
+        /* end outer loop */
+        
+        "str r2, [r0, r5] \n\t" /* p_result[uECC_WORDS * 2 - 1] = c0 */
+        "pop {r0} \n\t"         /* pop p_result off the stack */
+
+        ".syntax divided \n\t"
+        : [r0] "+l" (r0), [r1] "+l" (r1)
+        : [eccd] "I" (uECC_WORDS * 4), [eccdm1] "I" ((uECC_WORDS-1) * 4), [eccd2m1] "I" ((uECC_WORDS * 2 - 1) * 4)
+        : "r2", "r3", "r4", "r5", "r6", "r7", "cc", "memory"
+    );
+#endif
+}
+#define asm_square 1
+#endif /* !asm_square */
+#endif /* uECC_SQUARE_FUNC */
diff --git a/extlibs/tinydtls/ecc/asm_avr.inc b/extlibs/tinydtls/ecc/asm_avr.inc
new file mode 100755 (executable)
index 0000000..a945e52
--- /dev/null
@@ -0,0 +1,16276 @@
+#define DEC_20 19
+#define DEC_24 23
+#define DEC_32 31
+
+#define DEC(N) uECC_CONCAT(DEC_, N)
+
+#define REPEAT_1(stuff) stuff
+#define REPEAT_2(stuff) REPEAT_1(stuff) stuff
+#define REPEAT_3(stuff) REPEAT_2(stuff) stuff
+#define REPEAT_4(stuff) REPEAT_3(stuff) stuff
+#define REPEAT_5(stuff) REPEAT_4(stuff) stuff
+#define REPEAT_6(stuff) REPEAT_5(stuff) stuff
+#define REPEAT_7(stuff) REPEAT_6(stuff) stuff
+#define REPEAT_8(stuff) REPEAT_7(stuff) stuff
+#define REPEAT_9(stuff) REPEAT_8(stuff) stuff
+#define REPEAT_10(stuff) REPEAT_9(stuff) stuff
+#define REPEAT_11(stuff) REPEAT_10(stuff) stuff
+#define REPEAT_12(stuff) REPEAT_11(stuff) stuff
+#define REPEAT_13(stuff) REPEAT_12(stuff) stuff
+#define REPEAT_14(stuff) REPEAT_13(stuff) stuff
+#define REPEAT_15(stuff) REPEAT_14(stuff) stuff
+#define REPEAT_16(stuff) REPEAT_15(stuff) stuff
+#define REPEAT_17(stuff) REPEAT_16(stuff) stuff
+#define REPEAT_18(stuff) REPEAT_17(stuff) stuff
+#define REPEAT_19(stuff) REPEAT_18(stuff) stuff
+#define REPEAT_20(stuff) REPEAT_19(stuff) stuff
+#define REPEAT_21(stuff) REPEAT_20(stuff) stuff
+#define REPEAT_22(stuff) REPEAT_21(stuff) stuff
+#define REPEAT_23(stuff) REPEAT_22(stuff) stuff
+#define REPEAT_24(stuff) REPEAT_23(stuff) stuff
+#define REPEAT_25(stuff) REPEAT_24(stuff) stuff
+#define REPEAT_26(stuff) REPEAT_25(stuff) stuff
+#define REPEAT_27(stuff) REPEAT_26(stuff) stuff
+#define REPEAT_28(stuff) REPEAT_27(stuff) stuff
+#define REPEAT_29(stuff) REPEAT_28(stuff) stuff
+#define REPEAT_30(stuff) REPEAT_29(stuff) stuff
+#define REPEAT_31(stuff) REPEAT_30(stuff) stuff
+#define REPEAT_32(stuff) REPEAT_31(stuff) stuff
+
+#define REPEAT(N, stuff) uECC_CONCAT(REPEAT_, N)(stuff)
+
+#define STR2(thing) #thing
+#define STR(thing) STR2(thing)
+
+#if (uECC_ASM == uECC_asm_fast)
+
+static void vli_clear(uint8_t *p_vli)
+{
+    __asm__ volatile (
+        REPEAT(uECC_BYTES, "st %a[ptr]+, r1 \n\t")
+
+        : [ptr] "+e" (p_vli)
+        :
+        : "r0", "cc", "memory"
+    );
+}
+#define asm_clear 1
+
+static void vli_set(uint8_t *p_dest, const uint8_t *p_src)
+{
+    __asm__ volatile (
+        REPEAT(uECC_BYTES, "ld r0, %a[sptr]+ \n\t"
+            "st %a[dptr]+, r0 \n\t")
+        : [dptr] "+e" (p_dest), [sptr] "+e" (p_src)
+        :
+        : "r0", "cc", "memory"
+    );
+}
+#define asm_set 1
+
+static void vli_rshift1(uint8_t *p_vli)
+{
+    __asm__ volatile (
+        "adiw r30, " STR(uECC_BYTES) " \n\t"
+        "ld r0, -z \n\t"  /* Load byte. */
+        "lsr r0 \n\t" /* Shift. */
+        "st z, r0 \n\t"  /* Store the first result byte. */
+
+        /* Now we just do the remaining bytes with the carry bit (using ROR) */
+        REPEAT(DEC(uECC_BYTES), "ld r0, -z \n\t"
+            "ror r0 \n\t"
+            "st z, r0 \n\t")
+
+        : "+z" (p_vli)
+        :
+        : "r0", "cc", "memory"
+    );
+}
+#define asm_rshift1 1
+
+/* Computes p_result = p_left + p_right, returning carry. Can modify in place. */
+static uint8_t vli_add(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    uint8_t l_carry = 0;
+    uint8_t l_left;
+    uint8_t l_right;
+
+    __asm__ volatile (
+        "ld %[left], x+ \n\t"  /* Load left byte. */
+        "ld %[right], y+ \n\t" /* Load right byte. */
+        "add %[left], %[right] \n\t" /* Add the first byte. */
+        "st z+, %[left] \n\t"  /* Store the first result byte. */
+        
+        /* Now we just do the remaining bytes with the carry bit (using ADC) */
+        REPEAT(DEC(uECC_BYTES), "ld %[left], x+ \n\t"
+            "ld %[right], y+ \n\t"
+            "adc %[left], %[right] \n\t"
+            "st z+, %[left] \n\t")
+        
+        "adc %[carry], %[carry] \n\t"    /* Store carry bit in l_carry. */
+        
+        "sbiw r28, " STR(uECC_BYTES) " \n\t" /* Restore Y */
+
+        : "+z" (p_result), "+x" (p_left),
+            [carry] "+r" (l_carry), [left] "=&r" (l_left), [right] "=&r" (l_right)
+        : "y" (p_right)
+        : "cc", "memory"
+    );
+    return l_carry;
+}
+#define asm_add 1
+
+/* Computes p_result = p_left - p_right, returning borrow. Can modify in place. */
+static uint8_t vli_sub(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    uint8_t l_borrow = 0;
+    uint8_t l_left;
+    uint8_t l_right;
+
+    __asm__ volatile (
+        "ld %[left], x+ \n\t"  /* Load left byte. */
+        "ld %[right], y+ \n\t" /* Load right byte. */
+        "sub %[left], %[right] \n\t" /* Subtract the first byte. */
+        "st z+, %[left] \n\t"  /* Store the first result byte. */
+        
+        /* Now we just do the remaining bytes with the carry bit (using SBC) */
+        REPEAT(DEC(uECC_BYTES), "ld %[left], x+ \n\t"
+            "ld %[right], y+ \n\t"
+            "sbc %[left], %[right] \n\t"
+            "st z+, %[left] \n\t")
+        
+        "adc %[borrow], %[borrow] \n\t"    /* Store carry bit in l_borrow. */
+        
+        "sbiw r28, " STR(uECC_BYTES) " \n\t" /* Restore Y */
+
+        : "+z" (p_result), "+x" (p_left),
+            [borrow] "+r" (l_borrow), [left] "=&r" (l_left), [right] "=&r" (l_right)
+        : "y" (p_right)
+        : "cc", "memory"
+    );
+    return l_borrow;
+}
+#define asm_sub 1
+
+#if (uECC_BYTES == 20)
+__attribute((noinline))
+static void vli_mult(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    __asm__ volatile (
+        "adiw r30, 10 \n\t"
+        "adiw r28, 10 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r11, x+ \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r17, y+ \n\t"
+        "ld r18, y+ \n\t"
+        "ld r19, y+ \n\t"
+        "ld r20, y+ \n\t"
+        "ld r21, y+ \n\t"
+        "ldi r25, 0 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r24 \n\t"
+        "st z+, r22 \n\t"
+
+        "sbiw r30, 30 \n\t"
+        "sbiw r28, 20 \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r17, y+ \n\t"
+        "ld r18, y+ \n\t"
+        "ld r19, y+ \n\t"
+        "ld r20, y+ \n\t"
+        "ld r21, y+ \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r6, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r7, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r8, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r9, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r10, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r11, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r16, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r17, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r18, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r19, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r20, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r21, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "mul r11, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "st z+, r23 \n\t"
+        "st z+, r24 \n\t"
+        "eor r1, r1 \n\t"
+        : "+x" (p_left), "+y" (p_right), "+z" (p_result)
+        :
+        : "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
+          "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "cc", "memory"
+    );
+}
+#define asm_mult 1
+#elif (uECC_BYTES == 24)
+__attribute((noinline))
+static void vli_mult(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    __asm__ volatile (
+        "adiw r30, 20 \n\t"
+        "adiw r28, 20 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r15, y+ \n\t"
+        "ldi r25, 0 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r24 \n\t"
+        "st z+, r22 \n\t"
+
+        "sbiw r30, 18 \n\t"
+        "sbiw r28, 14 \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r17, y+ \n\t"
+        "ld r18, y+ \n\t"
+        "ld r19, y+ \n\t"
+        "ld r20, y+ \n\t"
+        "ld r21, y+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r11, x+ \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r6, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r7, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r8, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r10, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r11, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r3, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r4, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "st z+, r23 \n\t"
+        "st z+, r24 \n\t"
+
+        "sbiw r30, 38 \n\t"
+        "sbiw r28, 24 \n\t"
+        "sbiw r26, 14 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r12, y+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r17, y+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r18, y+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r19, y+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r20, y+ \n\t"
+        "ld r11, x+ \n\t"
+        "ld r21, y+ \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r6, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r7, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r8, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r9, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r10, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r11, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r6, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r6, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r16, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r17, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r18, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r6, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r19, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r20, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r21, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r4, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "mul r5, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st z+, r22 \n\t"
+        "st z+, r23 \n\t"
+
+        "eor r1, r1 \n\t"
+        : "+x" (p_left), "+y" (p_right), "+z" (p_result)
+        :
+        : "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
+          "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "cc", "memory"
+    );
+}
+#define asm_mult 1
+#elif (uECC_BYTES == 32)
+__attribute((noinline))
+static void vli_mult(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    __asm__ volatile (
+        "adiw r30, 30 \n\t"
+        "adiw r28, 30 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "ldi r25, 0 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "st z+, r23 \n\t"
+        "st z+, r24 \n\t"
+
+        "sbiw r30, 14 \n\t"
+        "sbiw r28, 12 \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r17, y+ \n\t"
+        "ld r18, y+ \n\t"
+        "ld r19, y+ \n\t"
+        "ld r20, y+ \n\t"
+        "ld r21, y+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r11, x+ \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r6, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r7, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r9, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r10, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st z+, r22 \n\t"
+        "st z+, r23 \n\t"
+
+        "sbiw r30, 34 \n\t"
+        "sbiw r28, 22 \n\t"
+        "sbiw r26, 12 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r12, y+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r17, y+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r18, y+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r19, y+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r20, y+ \n\t"
+        "ld r11, x+ \n\t"
+        "ld r21, y+ \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r6, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r7, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r8, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r9, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r10, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r11, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r16, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r17, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r18, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r19, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r20, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r21, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r24 \n\t"
+        "st z+, r22 \n\t"
+
+        "sbiw r30, 54 \n\t"
+        "sbiw r28, 32 \n\t"
+        "sbiw r26, 22 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r12, y+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r17, y+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r18, y+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r19, y+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r20, y+ \n\t"
+        "ld r11, x+ \n\t"
+        "ld r21, y+ \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r6, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r7, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r8, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r9, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r10, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r11, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r6, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r7, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r8, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r9, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r10, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r11, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r11, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r16, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r17, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r18, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r19, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r20, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r21, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r16, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r17, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r18, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r19, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r20, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r21, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r25 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r25 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r5, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r6, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r8, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r19 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r18 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r9, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r11, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r21 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "st z+, r23 \n\t"
+        "st z+, r24 \n\t"
+
+        "eor r1, r1 \n\t"
+        : "+x" (p_left), "+y" (p_right), "+z" (p_result)
+        :
+        : "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
+          "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "cc", "memory"
+    );
+}
+#define asm_mult 1
+#endif /* uECC_BYTES == 32 */
+
+#if uECC_SQUARE_FUNC
+
+#if (uECC_BYTES == 20)
+static void vli_square(uint8_t *p_result, uint8_t *p_left)
+{
+    __asm__ volatile (
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r11, x+ \n\t"
+        "ld r12, x+ \n\t"
+        "ld r13, x+ \n\t"
+        "ld r14, x+ \n\t"
+        "ld r15, x+ \n\t"
+        "ld r16, x+ \n\t"
+        "ld r17, x+ \n\t"
+        "ld r18, x+ \n\t"
+        "ld r19, x+ \n\t"
+        "ld r20, x+ \n\t"
+        "ld r21, x+ \n\t"
+        "ldi r27, 0 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r2 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r3 \n\t"
+        "lsl r0 \n\t"
+        "rol r1 \n\t"
+        "adc r24, r27 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r27 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r4 \n\t"
+        "lsl r0 \n\t"
+        "rol r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r3, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r6 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r4, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r7 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r8 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r4, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r5, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r9 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r5, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r10 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r4, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r5, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r6, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r11 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r5, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r6, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r4, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r5, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r6, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r7, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r5, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r6, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r7, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r5, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r6, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r7, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r8, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r6, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r7, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r8, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r7, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r8, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r9, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r8, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r9, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r4, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r6, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r9, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r10, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r10, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r11, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r4, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r5, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r6, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r7, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r8, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r9, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r12, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r4, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r12, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r5, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r6, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r7, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r8, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r9, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r10, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r11, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r12, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r13, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r6, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r12, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r13, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r7, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r12, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r13, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r14, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r8, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r9, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r10, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r11, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r12, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r13, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r14, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r9, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r12, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r13, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r14, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r15, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r10, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r12, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r13, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r14, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r15, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r11, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r12, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r13, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r14, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r15, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r16, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r12, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r13, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r14, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r15, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r16, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r13, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r14, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r15, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r16, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r17, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r14, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r15, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r16, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r17, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r15, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r16, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "mul r17, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r18, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r16, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r17, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "mul r18, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r17, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r18, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r19, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r27 \n\t"
+        "add r23, r25 \n\t"
+        "adc r24, r26 \n\t"
+        "adc r22, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r26, 0 \n\t"
+        "mul r18, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r25, r1 \n\t"
+        "mul r19, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "adc r26, r27 \n\t"
+        "lsl r23 \n\t"
+        "rol r25 \n\t"
+        "rol r26 \n\t"
+        "add r23, r24 \n\t"
+        "adc r25, r22 \n\t"
+        "adc r26, r27 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r19, r21 \n\t"
+        "lsl r0 \n\t"
+        "rol r1 \n\t"
+        "adc r23, r27 \n\t"
+        "add r25, r0 \n\t"
+        "adc r26, r1 \n\t"
+        "adc r23, r27 \n\t"
+        "mul r20, r20 \n\t"
+        "add r25, r0 \n\t"
+        "adc r26, r1 \n\t"
+        "adc r23, r27 \n\t"
+        "st z+, r25 \n\t"
+
+        "ldi r25, 0 \n\t"
+        "mul r20, r21 \n\t"
+        "lsl r0 \n\t"
+        "rol r1 \n\t"
+        "adc r25, r27 \n\t"
+        "add r26, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r25, r27 \n\t"
+        "st z+, r26 \n\t"
+
+        "mul r21, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r25, r1 \n\t"
+        "st z+, r23 \n\t"
+        "st z+, r25 \n\t"
+        "eor r1, r1 \n\t"
+        : "+x" (p_left), "+z" (p_result)
+        :
+        : "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
+          "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "cc", "memory"
+    );
+}
+#define asm_square 1
+
+#elif (uECC_BYTES == 24)
+
+__attribute((noinline))
+static void vli_square(uint8_t *p_result, uint8_t *p_left)
+{
+    __asm__ volatile (
+        "ldi r25, 0 \n\t"
+        "movw r28, r26 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "adiw r28, 20 \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "adiw r30, 20 \n\t"
+        
+        "ldi r23, 0 \n\t"
+        "mul 2, 12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+        
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+        
+        "ld r12, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ld r13, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+        
+        "ld r2, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r3, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+        
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "mul r3, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r24 \n\t"
+        "st z+, r22 \n\t"
+        
+        "sbiw r26, 4 \n\t"
+        "sbiw r30, 28 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r11, x+ \n\t"
+        "ld r12, x+ \n\t"
+        "ld r13, x+ \n\t"
+        "ld r14, x+ \n\t"
+        "ld r15, x+ \n\t"
+        "ld r16, x+ \n\t"
+        "ld r17, x+ \n\t"
+        "ld r18, x+ \n\t"
+        "ld r19, x+ \n\t"
+        "ld r20, x+ \n\t"
+        "ld r21, x+ \n\t"
+        
+        "ldi r23, 0 \n\t"
+        "mul r2, r2 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+        
+        "ldi r24, 0 \n\t"
+        "mul r2, r3 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r6 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r4, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r7 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r8 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r5, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r9 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r10 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r6, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r11 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r7, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r8, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r9, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r10, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r11, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ld r2, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r12, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r3, r2 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r2 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r5, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r13, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r4, r3 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r5, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ld r4, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r5, r3 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r6, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r14, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r5, r4 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r6, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ld r5, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r4 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r7, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r15, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r6, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r7, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r7, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r8, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r16, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r8, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r9, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r9, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r10, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r17, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r10, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r11, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r11, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r12, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r18, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r12, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r13, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r13, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r14, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r19, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r14, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r15, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r15, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r16, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r20, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r16, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r17, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r17, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r18, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r20, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r21, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r18, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r19, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r21, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r19, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r20, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r21, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r2, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r20, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r21, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r2, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r22, 0 \n\t"
+        "mul r21, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r2, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r3, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r29, 0 \n\t"
+        "mul r2, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+        
+        "ldi r23, 0 \n\t"
+        "mul r3, r5 \n\t"
+        "add r28, r0 \n\t"
+        "adc r29, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "add r28, r0 \n\t"
+        "adc r29, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r4 \n\t"
+        "add r28, r0 \n\t"
+        "adc r29, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r28 \n\t"
+        
+        "ldi r28, 0 \n\t"
+        "mul r4, r5 \n\t"
+        "add r29, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r28, r25 \n\t"
+        "add r29, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r28, r25 \n\t"
+        "st z+, r29 \n\t"
+        
+        "mul r5, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "st z+, r23 \n\t"
+        "st z+, r28 \n\t"
+        "eor r1, r1 \n\t"
+        : "+x" (p_left), "+z" (p_result)
+        :
+        : "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
+          "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r28", "r29", "cc", "memory"
+    );
+}
+#define asm_square 1
+
+#elif (uECC_BYTES == 32)
+
+__attribute((noinline))
+static void vli_square(uint8_t *p_result, uint8_t *p_left)
+{
+    __asm__ volatile (
+        "ldi r25, 0 \n\t"
+        "movw r28, r26 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r7, x+ \n\t"
+        "adiw r28, 20 \n\t"
+        "ld r12, y+ \n\t"
+        "ld r13, y+ \n\t"
+        "ld r14, y+ \n\t"
+        "ld r15, y+ \n\t"
+        "ld r16, y+ \n\t"
+        "ld r17, y+ \n\t"
+        "adiw r30, 20 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul 2, 12 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r12, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r13, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r14, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r15, y+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r16, y+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r17, y+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r12 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r13 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r23, 0 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r2, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r3, r14 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ld r6, x+ \n\t"
+        "ldi r24, 0 \n\t"
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r2, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r3, r15 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ld r7, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r3, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r4, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r6, r17 \n\t"
+        "add r24, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r24 \n\t"
+
+        "mul r7, r17 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st z+, r22 \n\t"
+        "st z+, r23 \n\t"
+
+        "sbiw r26, 12 \n\t"
+        "sbiw r30, 44 \n\t"
+        "ld r2, x+ \n\t"
+        "ld r3, x+ \n\t"
+        "ld r4, x+ \n\t"
+        "ld r5, x+ \n\t"
+        "ld r6, x+ \n\t"
+        "ld r7, x+ \n\t"
+        "ld r8, x+ \n\t"
+        "ld r9, x+ \n\t"
+        "ld r10, x+ \n\t"
+        "ld r11, x+ \n\t"
+        "ld r12, x+ \n\t"
+        "ld r13, x+ \n\t"
+        "ld r14, x+ \n\t"
+        "ld r15, x+ \n\t"
+        "ld r16, x+ \n\t"
+        "ld r17, x+ \n\t"
+        "ld r18, x+ \n\t"
+        "ld r19, x+ \n\t"
+        "ld r20, x+ \n\t"
+        "ld r21, x+ \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r2, r2 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+
+        "ldi r24, 0 \n\t"
+        "mul r2, r3 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r24, r25 \n\t"
+        "st z+, r22 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r6 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r4, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r7 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r8 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r5, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r9 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r10 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r6, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r11 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r12 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r7, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r14 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r8, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r15 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r16 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r9, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r17 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r18 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r10, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r19 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r2, r20 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r3, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r11, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r2, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r3, r21 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r4, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r12, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r3, r2 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r4, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r3, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r4, r2 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r5, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r13, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r4, r3 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r5, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r4, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r5, r3 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r6, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r14, r14 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r5, r4 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r6, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r5, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r6, r4 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r7, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r15, r15 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r6, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r7, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r6, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r7, r5 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r8, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r16, r16 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r7, r6 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r8, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r7, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r8, r6 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r9, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r10, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r17, r17 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r8, r7 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r9, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r8, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r9, r7 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r10, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r11, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r18, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r9, r8 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r10, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r11, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r9, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r10, r8 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r11, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r12, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r19, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r10, r9 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r11, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r12, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r10, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r11, r9 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r12, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r13, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r20, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r11, r10 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r12, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r13, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r11, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r12, r10 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r13, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r14, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r20, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r21, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r12, r11 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r13, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r14, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r21, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r12, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r13, r11 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r14, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r15, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r20, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r21, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r2, r2 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r13, r12 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r14, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r15, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r21, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r2, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ld r13, x+ \n\t"
+        "ldi r22, 0 \n\t"
+        "mul r14, r12 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r15, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r16, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r20, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r21, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r25 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r3, r3 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r14, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r15, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r16, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r17, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r21, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r2, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r3, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "ld r0, z \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r25 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r15, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r16, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r17, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r18, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r20, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r21, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r4, r4 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r16, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r17, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r18, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r19, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r21, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r2, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r3, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r17, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r18, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r19, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r20, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r21, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r5, r5 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r18, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r19, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r20, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r21, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r2, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r3, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r19, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r20, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r21, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r2, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r6, r6 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r20, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r21, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r2, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r3, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r21, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r2, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r3, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r4, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r7, r7 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r2, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r3, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r4, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r5, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r3, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r4, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r5, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r6, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r8, r8 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r4, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r5, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r6, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r7, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r5, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r6, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r7, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r8, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r9, r9 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r6, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r7, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r8, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r9, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r7, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r8, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "mul r9, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r10, r10 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r8, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r9, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "mul r10, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r22, 0 \n\t"
+        "mul r9, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r24, r1 \n\t"
+        "mul r10, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r24 \n\t"
+        "rol r22 \n\t"
+        "mul r11, r11 \n\t"
+        "add r23, r0 \n\t"
+        "adc r24, r1 \n\t"
+        "adc r22, r25 \n\t"
+        "add r23, r28 \n\t"
+        "adc r24, r29 \n\t"
+        "adc r22, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r29, 0 \n\t"
+        "mul r10, r13 \n\t"
+        "mov r23, r0 \n\t"
+        "mov r28, r1 \n\t"
+        "mul r11, r12 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "adc r29, r25 \n\t"
+        "lsl r23 \n\t"
+        "rol r28 \n\t"
+        "rol r29 \n\t"
+        "add r23, r24 \n\t"
+        "adc r28, r22 \n\t"
+        "adc r29, r25 \n\t"
+        "st z+, r23 \n\t"
+
+        "ldi r23, 0 \n\t"
+        "mul r11, r13 \n\t"
+        "add r28, r0 \n\t"
+        "adc r29, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "add r28, r0 \n\t"
+        "adc r29, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "mul r12, r12 \n\t"
+        "add r28, r0 \n\t"
+        "adc r29, r1 \n\t"
+        "adc r23, r25 \n\t"
+        "st z+, r28 \n\t"
+
+        "ldi r28, 0 \n\t"
+        "mul r12, r13 \n\t"
+        "add r29, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r28, r25 \n\t"
+        "add r29, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "adc r28, r25 \n\t"
+        "st z+, r29 \n\t"
+
+        "mul r13, r13 \n\t"
+        "add r23, r0 \n\t"
+        "adc r28, r1 \n\t"
+        "st z+, r23 \n\t"
+        "st z+, r28 \n\t"
+        "eor r1, r1 \n\t"
+        : "+x" (p_left), "+z" (p_result)
+        :
+        : "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12",
+          "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r28", "r29", "cc", "memory"
+    );
+}
+#define asm_square 1
+
+#endif /* uECC_BYTES == xx */
+#endif /* uECC_SQUARE_FUNC */
+
+static void vli_modSub_fast(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    uint8_t t1, t2;
+    __asm__ volatile (
+        "push r28 \n\t" /* Save Y */
+        "push r29 \n\t"
+        
+        "ld %[t1], x+ \n\t"  /* Load left word. */
+        "ld %[t2], y+ \n\t" /* Load right word. */
+        "sub %[t1], %[t2] \n\t" /* Subtract the first word. */
+        "st z+, %[t1] \n\t"  /* Store the first result word. */
+        
+        /* Now we just do the remaining words with the carry bit (using SBC) */
+        REPEAT(DEC(uECC_BYTES), "ld %[t1], x+ \n\t"
+            "ld %[t2], y+ \n\t"
+            "sbc %[t1], %[t2] \n\t"
+            "st z+, %[t1] \n\t")
+        
+        "brcs 1f \n\t" /* If borrow is set, then we need to add */
+        "rjmp done \n\t" /* otherwise we are done */
+        "1: \n\t"
+        
+        "sbiw r30, " STR(uECC_BYTES) " \n\t" /* make z point at p_result again */
+        "ldi r28, lo8(curve_p) \n\t" /* make y point at curve_p */
+       "ldi r29, hi8(curve_p) \n\t"
+       
+       /* do the addition */
+       "ld %[t1], z \n\t"
+        "ld %[t2], y+ \n\t"
+        "add %[t1], %[t2] \n\t"
+        "st z+, %[t1] \n\t"
+        REPEAT(DEC(uECC_BYTES), "ld %[t1], z \n\t"
+            "ld %[t2], y+ \n\t"
+            "adc %[t1], %[t2] \n\t"
+            "st z+, %[t1] \n\t")
+        
+        "done: \n\t"
+        "pop r29 \n\t" /* Restore Y */
+        "pop r28 \n\t"
+
+        : "+z" (p_result), "+x" (p_left),
+          [t1] "=&r" (t1), [t2] "=&r" (t2)
+        : "y" (p_right)
+        : "cc", "memory"
+    );
+}
+#define asm_modSub_fast 1
+
+#if uECC_CURVE == uECC_secp160r1
+static void vli_mmod_fast(uint8_t *RESTRICT p_result, uint8_t *RESTRICT p_product)
+{
+    uint8_t l_carry = 0;
+    __asm__ volatile (
+        "in r30, __SP_L__ \n\t"
+       "in r31, __SP_H__ \n\t"
+       "sbiw r30, 24 \n\t"
+       "in r0, __SREG__ \n\t"
+       "cli \n\t"
+       "out __SP_H__, r31 \n\t"
+       "out __SREG__, r0 \n\t"
+       "out __SP_L__, r30 \n\t"
+       
+       "adiw r30, 25 \n\t" /* we are shifting by 31 bits, so shift over 4 bytes (+ 1 since z initially points below the stack) */
+        "adiw r26, 40 \n\t" /* end of p_product */
+        "ld r18, -x \n\t"  /* Load word. */
+        "lsr r18 \n\t" /* Shift. */
+        "st -z, r18 \n\t"  /* Store the first result word. */
+
+        /* Now we just do the remaining words with the carry bit (using ROR) */
+        REPEAT(19, "ld r18, -x \n\t"
+            "ror r18 \n\t"
+            "st -z, r18 \n\t")
+
+        "eor r18, r18 \n\t" /* r18 = 0 */
+        "ror r18 \n\t" /* get last bit */
+        "st -z, r18 \n\t" /* store it */
+
+        "sbiw r30, 3 \n\t" /* move z back to point at tmp */
+        /* now we add p_right */
+        "ld r18, x+ \n\t"
+        "st z+, r18 \n\t" /* the first 3 bytes do not need to be added */
+        "ld r18, x+ \n\t"
+        "st z+, r18 \n\t"
+        "ld r18, x+ \n\t"
+        "st z+, r18 \n\t"
+
+        "ld r18, x+ \n\t"
+        "ld r19, z \n\t"
+        "add r18, r19 \n\t"
+        "st z+, r18 \n\t"
+
+        /* Now we just do the remaining words with the carry bit (using ADC) */
+        REPEAT(16, "ld r18, x+ \n\t"
+            "ld r19, z \n\t"
+            "adc r18, r19 \n\t"
+            "st z+, r18 \n\t")
+
+        /* Propagate over the remaining bytes of p_result */
+        "ld r18, z \n\t"
+        "adc r18, r1 \n\t"
+        "st z+, r18 \n\t"
+
+        "ld r18, z \n\t"
+        "adc r18, r1 \n\t"
+        "st z+, r18 \n\t"
+
+        "ld r18, z \n\t"
+        "adc r18, r1 \n\t"
+        "st z+, r18 \n\t"
+
+        "ld r18, z \n\t"
+        "adc r18, r1 \n\t"
+        "st z+, r18 \n\t"
+        
+        "sbiw r30, 24 \n\t" /* move z back to point at tmp */
+        "sbiw r26, 40 \n\t" /* move x back to point at p_product */
+        
+        /* add low bytes of tmp to p_product, storing in p_result */
+        "ld r18, z+ \n\t"
+        "ld r19, x+ \n\t"
+        "add r18, r19 \n\t"
+        "st y+, r18 \n\t"
+        REPEAT(19, "ld r18, z+ \n\t"
+            "ld r19, x+ \n\t"
+            "adc r18, r19 \n\t"
+            "st y+, r18 \n\t")
+        "adc %[carry], __zero_reg__ \n\t"    /* Store carry bit (carry flag is cleared). */
+        /* at this point x is at the end of p_product, y is at the end of p_result, z is 20 bytes into tmp */
+        "sbiw r28, 20 \n\t" /* move y back to point at p_result */
+        "adiw r30, 4 \n\t" /* move z to point to the end of tmp */
+        
+        /* do omega_mult again with the 4 relevant bytes */
+        /* z points to the end of tmp, x points to the end of p_product */
+        "ld r18, -z \n\t"  /* Load word. */
+        "lsr r18 \n\t" /* Shift. */
+        "st -x, r18 \n\t"  /* Store the first result word. */
+        
+        "ld r18, -z \n\t"
+        "ror r18 \n\t"
+        "st -x, r18 \n\t"
+        "ld r18, -z \n\t"
+        "ror r18 \n\t"
+        "st -x, r18 \n\t"
+        "ld r18, -z \n\t"
+        "ror r18 \n\t"
+        "st -x, r18 \n\t"
+        
+        "eor r18, r18 \n\t" /* r18 = 0 */
+        "ror r18 \n\t" /* get last bit */
+        "st -x, r18 \n\t" /* store it */
+        
+        "sbiw r26, 3 \n\t" /* move x back to point at beginning */
+        /* now we add a copy of the 4 bytes */
+        "ld r18, z+ \n\t"
+        "st x+, r18 \n\t" /* the first 3 bytes do not need to be added */
+        "ld r18, z+ \n\t"
+        "st x+, r18 \n\t"
+        "ld r18, z+ \n\t"
+        "st x+, r18 \n\t"
+        
+        "ld r18, z+ \n\t"
+        "ld r19, x \n\t"
+        "add r18, r19 \n\t"
+        "st x+, r18 \n\t"
+        
+        /* Propagate over the remaining bytes */
+        "ld r18, x \n\t"
+        "adc r18, r1 \n\t"
+        "st x+, r18 \n\t"
+        
+        "ld r18, x \n\t"
+        "adc r18, r1 \n\t"
+        "st x+, r18 \n\t"
+        
+        "ld r18, x \n\t"
+        "adc r18, r1 \n\t"
+        "st x+, r18 \n\t"
+        
+        "ld r18, x \n\t"
+        "adc r18, r1 \n\t"
+        "st x+, r18 \n\t"
+        
+        /* now z points to the end of tmp, x points to the end of p_product (y still points at p_result) */
+        "sbiw r26, 8 \n\t" /* move x back to point at beginning of actual data */
+        /* add into p_result */
+        "ld r18, x+ \n\t"
+        "ld r19, y \n\t"
+        "add r18, r19 \n\t"
+        "st y+, r18 \n\t"
+        REPEAT(7, "ld r18, x+ \n\t"
+            "ld r19, y \n\t"
+            "adc r18, r19 \n\t"
+            "st y+, r18 \n\t")
+        
+        /* Done adding, now propagate carry bit */
+        REPEAT(12, "ld r18, y \n\t"
+            "adc r18, __zero_reg__ \n\t"
+            "st y+, r18 \n\t")
+        
+        "adc %[carry], __zero_reg__ \n\t"    /* Store carry bit (carry flag is cleared). */
+        "sbiw r28, 20 \n\t" /* move y back to point at p_result */
+        
+        "sbiw r30, 1 \n\t" /* fix stack pointer */
+       "in r0, __SREG__ \n\t"
+       "cli \n\t"
+       "out __SP_H__, r31 \n\t"
+       "out __SREG__, r0 \n\t"
+       "out __SP_L__, r30 \n\t"
+        
+        : "+x" (p_product), [carry] "+r" (l_carry)
+        : "y" (p_result)
+        : "r0", "r18", "r19", "r30", "r31", "cc", "memory"
+    );
+    
+    if(l_carry > 0)
+    {
+        --l_carry;
+        vli_sub(p_result, p_result, curve_p);
+    }
+    if(l_carry > 0)
+    {
+        vli_sub(p_result, p_result, curve_p);
+    }
+    
+    if(vli_cmp(p_result, curve_p) > 0)
+    {
+        vli_sub(p_result, p_result, curve_p);
+    }
+}
+#define asm_mmod_fast 1
+
+#elif (uECC_CURVE == uECC_secp256k1)
+static void vli_mmod_fast(uint8_t *RESTRICT p_result, uint8_t *RESTRICT p_product)
+{
+    uint8_t l_carry = 0;
+    __asm__ volatile (
+        "in r30, __SP_L__ \n\t"
+       "in r31, __SP_H__ \n\t"
+       "sbiw r30, 37 \n\t"
+       "in r0, __SREG__ \n\t"
+       "cli \n\t"
+       "out __SP_H__, r31 \n\t"
+       "out __SREG__, r0 \n\t"
+       "out __SP_L__, r30 \n\t"
+       
+       "adiw r30, 1 \n\t" /* add 1 since z initially points below the stack */
+        "adiw r26, 32 \n\t" /* p_product + uECC_WORDS */
+        "ldi r25, 0x03 \n\t"
+        "ldi r24, 0xD1 \n\t"
+        "ld r18, x+ \n\t"
+        "ld r19, x+ \n\t"
+        "ld r20, x+ \n\t"
+        "ld r21, x+ \n\t"
+        
+        "mul r24, r18 \n\t"
+        "st z+, r0 \n\t"
+        "mov r22, r1 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "mul r24, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t" /* can't overflow */
+        "mul r25, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t" /* can't overflow */
+        "st z+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        "mul r24, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "mul r25, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "mul r24, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r25, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st z+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        /* now we start adding the 2^32 part as well */
+        "add r23, r18 \n\t" // 28
+        "adc r22, r22 \n\t"
+        "ld r18, x+ \n\t"
+        "mul r24, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "mul r25, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "add r22, r19 \n\t" // 27
+        "adc r23, r23 \n\t"
+        "ld r19, x+ \n\t"
+        "mul r24, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r25, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st z+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        REPEAT(6, // 26 - 3
+            "add r23, r20 \n\t"
+            "adc r22, r22 \n\t"
+            "ld r20, x+ \n\t"
+            "mul r24, r20 \n\t"
+            "add r23, r0 \n\t"
+            "adc r22, r1 \n\t"
+            "mul r25, r19 \n\t"
+            "add r23, r0 \n\t"
+            "adc r22, r1 \n\t"
+            "st z+, r23 \n\t"
+            "ldi r23, 0 \n\t"
+            
+            "add r22, r21 \n\t"
+            "adc r23, r23 \n\t"
+            "ld r21, x+ \n\t"
+            "mul r24, r21 \n\t"
+            "add r22, r0 \n\t"
+            "adc r23, r1 \n\t"
+            "mul r25, r20 \n\t"
+            "add r22, r0 \n\t"
+            "adc r23, r1 \n\t"
+            "st z+, r22 \n\t"
+            "ldi r22, 0 \n\t"
+            
+            "add r23, r18 \n\t"
+            "adc r22, r22 \n\t"
+            "ld r18, x+ \n\t"
+            "mul r24, r18 \n\t"
+            "add r23, r0 \n\t"
+            "adc r22, r1 \n\t"
+            "mul r25, r21 \n\t"
+            "add r23, r0 \n\t"
+            "adc r22, r1 \n\t"
+            "st z+, r23 \n\t"
+            "ldi r23, 0 \n\t"
+            
+            "add r22, r19 \n\t"
+            "adc r23, r23 \n\t"
+            "ld r19, x+ \n\t"
+            "mul r24, r19 \n\t"
+            "add r22, r0 \n\t"
+            "adc r23, r1 \n\t"
+            "mul r25, r18 \n\t"
+            "add r22, r0 \n\t"
+            "adc r23, r1 \n\t"
+            "st z+, r22 \n\t"
+            "ldi r22, 0 \n\t")
+
+        "add r23, r20 \n\t" // 2
+        "adc r22, r22 \n\t"
+        "ld r20, x+ \n\t"
+        "mul r24, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "mul r25, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "add r22, r21 \n\t" // 1
+        "adc r23, r23 \n\t"
+        "ld r21, x+ \n\t"
+        "mul r24, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r25, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st z+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        /* Now finish the carries etc */
+        "add r23, r18 \n\t"
+        "adc r22, r22 \n\t"
+        "mul r25, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st z+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "add r22, r19 \n\t"
+        "adc r23, r23 \n\t"
+        "st z+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        "add r23, r20 \n\t"
+        "adc r22, r22 \n\t"
+        "st z+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "add r22, r21 \n\t"
+        "adc r23, r23 \n\t"
+        "st z+, r22 \n\t"
+        "st z+, r23 \n\t"
+        "eor r1, r1 \n\t" /* make r1 be 0 again */
+        
+        "sbiw r30, 37 \n\t" /* move z back to point at tmp */
+        "subi r26, 64 \n\t" /* move x back to point at p_product */
+        "sbc r27, __zero_reg__ \n\t"
+        
+        /* add low bytes of tmp to p_product, storing in p_result */
+        "ld r18, z+ \n\t"
+        "ld r19, x+ \n\t"
+        "add r18, r19 \n\t"
+        "st y+, r18 \n\t"
+        REPEAT(31, "ld r18, z+ \n\t"
+            "ld r19, x+ \n\t"
+            "adc r18, r19 \n\t"
+            "st y+, r18 \n\t")
+        
+        "adc %[carry], __zero_reg__ \n\t"    /* Store carry bit (carry flag is cleared). */
+        /* at this point x is at the end of p_product, y is at the end of p_result, z is 32 bytes into tmp */
+        "sbiw r28, 32 \n\t" /* move y back to point at p_result */
+
+        /* do omega_mult again with the 5 relevant bytes */
+        /* z points to l_tmp + uECC_WORDS, x points to the end of p_product */
+        "sbiw r26, 32 \n\t" /* shift x back to point into the p_product buffer (we can overwrite it now) */
+        
+        "ld r18, z+ \n\t"
+        "ld r19, z+ \n\t"
+        "ld r20, z+ \n\t"
+        "ld r21, z+ \n\t"
+        
+        "mul r24, r18 \n\t"
+        "st x+, r0 \n\t"
+        "mov r22, r1 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "mul r24, r19 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t" /* can't overflow */
+        "mul r25, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t" /* can't overflow */
+        "st x+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        "mul r24, r20 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "mul r25, r19 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st x+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "mul r24, r21 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "mul r25, r20 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st x+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        "add r23, r18 \n\t"
+        "adc r22, r22 \n\t"
+        "ld r18, z+ \n\t"
+        "mul r24, r18 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "mul r25, r21 \n\t"
+        "add r23, r0 \n\t"
+        "adc r22, r1 \n\t"
+        "st x+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        /* Now finish the carries etc */
+        "add r22, r19 \n\t"
+        "adc r23, r23 \n\t"
+        "mul r25, r18 \n\t"
+        "add r22, r0 \n\t"
+        "adc r23, r1 \n\t"
+        "st x+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        "add r23, r20 \n\t"
+        "adc r22, r22 \n\t"
+        "st x+, r23 \n\t"
+        "ldi r23, 0 \n\t"
+        
+        "add r22, r21 \n\t"
+        "adc r23, r23 \n\t"
+        "st x+, r22 \n\t"
+        "ldi r22, 0 \n\t"
+        
+        "add r23, r18 \n\t"
+        "adc r22, r22 \n\t"
+        "st x+, r23 \n\t"
+        "st x+, r22 \n\t"
+        "eor r1, r1 \n\t" /* make r1 be 0 again */
+        
+        /* now z points to the end of tmp, x points to the end of p_product (y still points at p_result) */
+        "sbiw r26, 10 \n\t" /* move x back to point at beginning of actual data */
+        /* add into p_result */
+        "ld r18, x+ \n\t"
+        "ld r19, y \n\t"
+        "add r18, r19 \n\t"
+        "st y+, r18 \n\t"
+        REPEAT(9, "ld r18, x+ \n\t"
+            "ld r19, y \n\t"
+            "adc r18, r19 \n\t"
+            "st y+, r18 \n\t")
+        
+        /* Done adding, now propagate carry bit */
+        REPEAT(22, "ld r18, y \n\t"
+            "adc r18, __zero_reg__ \n\t"
+            "st y+, r18 \n\t")
+        
+        "adc %[carry], __zero_reg__ \n\t"    /* Store carry bit (carry flag is cleared). */
+        "sbiw r28, 32 \n\t" /* move y back to point at p_result */
+        
+        "sbiw r30, 1 \n\t" /* fix stack pointer */
+       "in r0, __SREG__ \n\t"
+       "cli \n\t"
+       "out __SP_H__, r31 \n\t"
+       "out __SREG__, r0 \n\t"
+       "out __SP_L__, r30 \n\t"
+        
+        : "+x" (p_product), [carry] "+r" (l_carry)
+        : "y" (p_result)
+        : "r0", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r30", "r31", "cc", "memory"
+    );
+    
+    if(l_carry > 0)
+    {
+        --l_carry;
+        vli_sub(p_result, p_result, curve_p);
+    }
+    if(l_carry > 0)
+    {
+        vli_sub(p_result, p_result, curve_p);
+    }
+    
+    if(vli_cmp(p_result, curve_p) > 0)
+    {
+        vli_sub(p_result, p_result, curve_p);
+    }
+}
+#define asm_mmod_fast 1
+
+#endif /* (uECC_CURVE == uECC_secp256k1) */
+
+#endif /* (uECC_ASM == uECC_asm_fast) */
+
+#if !asm_rshift1
+static void vli_rshift1(uint8_t *p_vli)
+{
+    uint8_t i = uECC_BYTES;
+    __asm__ volatile (
+        "adiw r30, " STR(uECC_BYTES) " \n\t"
+        "clc \n\t"
+        
+        "1: \n\t"
+        "ld r0, -z \n\t"
+        "ror r0 \n\t"
+        "st z, r0 \n\t"
+        "dec %[i] \n\t"
+        "brne 1b \n\t"
+
+        : "+z" (p_vli), [i] "+r" (i)
+        : 
+        : "r0", "cc", "memory"
+    );
+}
+#define asm_rshift1 1
+#endif
+
+#if !asm_add
+static uint8_t vli_add(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    uint8_t i = uECC_BYTES;
+    uint8_t l_carry = 0;
+    uint8_t l_left;
+    uint8_t l_right;
+
+    __asm__ volatile (
+        "clc \n\t"
+        
+        "1: \n\t"
+        "ld %[left], x+ \n\t"  /* Load left byte. */
+        "ld %[right], y+ \n\t" /* Load right byte. */
+        "adc %[left], %[right] \n\t" /* Add. */
+        "st z+, %[left] \n\t"  /* Store the result. */
+        "dec %[i] \n\t"
+        "brne 1b \n\t"
+        
+        "adc %[carry], %[carry] \n\t"    /* Store carry bit in l_carry. */
+        
+        "sbiw r28, " STR(uECC_BYTES) " \n\t" /* Restore Y */
+
+        : "+z" (p_result), "+x" (p_left), [i] "+r" (i),
+            [carry] "+r" (l_carry), [left] "=&r" (l_left), [right] "=&r" (l_right)
+        : "y" (p_right)
+        : "cc", "memory"
+    );
+    return l_carry;
+}
+#define asm_add 1
+#endif
+
+#if !asm_sub
+static uint8_t vli_sub(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    uint8_t i = uECC_BYTES;
+    uint8_t l_borrow = 0;
+    uint8_t l_left;
+    uint8_t l_right;
+
+    __asm__ volatile (
+        "clc \n\t"
+        
+        "1: \n\t"
+        "ld %[left], x+ \n\t"  /* Load left byte. */
+        "ld %[right], y+ \n\t" /* Load right byte. */
+        "sbc %[left], %[right] \n\t" /* Subtract. */
+        "st z+, %[left] \n\t"  /* Store the result. */
+        "dec %[i] \n\t"
+        "brne 1b \n\t"
+        
+        "adc %[borrow], %[borrow] \n\t"    /* Store carry bit in l_borrow. */
+        
+        "sbiw r28, " STR(uECC_BYTES) " \n\t" /* Restore Y */
+
+        : "+z" (p_result), "+x" (p_left), [i] "+r" (i),
+            [borrow] "+r" (l_borrow), [left] "=&r" (l_left), [right] "=&r" (l_right)
+        : "y" (p_right)
+        : "cc", "memory"
+    );
+    return l_borrow;
+}
+#define asm_sub 1
+#endif
+
+#if !asm_mult
+__attribute((noinline))
+static void vli_mult(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
+{
+    uint8_t r0 = 0;
+    uint8_t r1 = 0;
+    uint8_t r2 = 0;
+    
+    uint8_t l_zero = 0;
+    
+    uint8_t k, i;
+    
+    __asm__ volatile (
+        "ldi %[k], 1 \n\t" /* k = 1; k < uECC_BYTES; ++k */
+        
+        "1: \n\t"
+        "ldi %[i], 0 \n\t"  /* i=0; i < k; ++i */
+        
+        "add r28, %[k] \n\t" /* pre-add right ptr */
+        "adc r29, %[zero] \n\t"
+        
+        "2: \n\t"
+        "ld r0, x+ \n\t"
+        "ld r1, -y \n\t"
+        "mul r0, r1 \n\t"
+        
+        "add %[r0], r0 \n\t"
+        "adc %[r1], r1 \n\t"
+        "adc %[r2], %[zero] \n\t"
+        
+        "inc %[i] \n\t"
+        "cp %[i], %[k] \n\t"
+        "brlo 2b \n\t" /* loop if i < k */
+        
+        "sub r26, %[k] \n\t" /* fix up left ptr */
+        "sbc r27, %[zero] \n\t"
+        
+        "st z+, %[r0] \n\t"  /* Store the result. */
+        "mov %[r0], %[r1] \n\t"
+        "mov %[r1], %[r2] \n\t"
+        "mov %[r2], %[zero] \n\t"
+        
+        "inc %[k] \n\t"
+        "cpi %[k], " STR(uECC_BYTES) " \n\t"
+        "brlo 1b \n\t" /* loop if k < uECC_BYTES */
+        
+        /* second half */
+        "ldi %[k], " STR(uECC_BYTES) " \n\t" /* k = uECC_BYTES; k > 0; --k */
+        "adiw r28, " STR(uECC_BYTES) " \n\t" /* move right ptr to point at the end of p_right */
+        
+        "1: \n\t"
+        "ldi %[i], 0 \n\t" /* i=0; i < k; ++i */
+        
+        "2: \n\t"
+        "ld r0, x+ \n\t"
+        "ld r1, -y \n\t"
+        "mul r0, r1 \n\t"
+        
+        "add %[r0], r0 \n\t"
+        "adc %[r1], r1 \n\t"
+        "adc %[r2], %[zero] \n\t"
+        
+        "inc %[i] \n\t"
+        "cp %[i], %[k] \n\t"
+        "brlo 2b \n\t" /* loop if i < k */
+        
+        "add r28, %[k] \n\t" /* fix up right ptr */
+        "adc r29, %[zero] \n\t"
+        
+        "st z+, %[r0] \n\t"  /* Store the result. */
+        "mov %[r0], %[r1] \n\t"
+        "mov %[r1], %[r2] \n\t"
+        "mov %[r2], %[zero] \n\t"
+        
+        "dec %[k] \n\t"
+        "sub r26, %[k] \n\t" /* fix up left ptr (after k is decremented, so next time we start 1 higher) */
+        "sbc r27, %[zero] \n\t"
+        
+        "cpi %[k], 0 \n\t"
+        "brne 1b \n\t" /* loop if k > 0 */
+        
+        "st z+, %[r0] \n\t"  /* Store last result byte. */
+        
+        "eor r1, r1 \n\t" /* fix r1 to be 0 again */
+        
+        "sbiw r28, " STR(uECC_BYTES) " \n\t" /* Restore Y */
+    
+        : "+z" (p_result), "+x" (p_left),
+          [r0] "+r" (r0), [r1] "+r" (r1), [r2] "+r" (r2), [zero] "+r" (l_zero),
+          [k] "=&a" (k), [i] "=&a" (i)
+        : "y" (p_right)
+        : "r0", "cc", "memory"
+    );
+}
+#define asm_mult 1
+#endif
+
+#if uECC_SQUARE_FUNC
+#if !asm_square
+static void vli_square(uint8_t *p_result, uint8_t *p_left)
+{
+    uint8_t r0 = 0;
+    uint8_t r1 = 0;
+    uint8_t r2 = 0;
+    
+    uint8_t l_zero = 0;
+    
+    uint8_t k;
+    
+    __asm__ volatile (
+        "ldi %[k], 1 \n\t" /* k = 1; k < uECC_BYTES*2; ++k */
+        
+        "1: \n\t"
+        
+        "movw r26, %[orig] \n\t"  /* copy orig ptr to 'left' ptr */
+        "movw r30, %[orig] \n\t"  /* copy orig ptr to 'right' ptr */
+        "cpi %[k], " STR(uECC_BYTES) " \n\t"
+        "brlo 2f \n\t"
+        "breq 2f \n\t"
+        
+        /* when k > uECC_BYTES, we start from (k - uECC_BYTES) on the 'left' ptr */
+        "add r26, %[k] \n\t"
+        "adc r27, %[zero] \n\t"
+        "subi r26, " STR(uECC_BYTES) " \n\t"
+        "sbc r27, %[zero] \n\t"
+        "adiw r30, " STR(uECC_BYTES) " \n\t" /* move right ptr to point at the end */
+        "rjmp 3f \n\t"
+        
+        "2: \n\t" /* when k <= uECC_BYTES, we add k to the 'right' ptr */
+        "add r30, %[k] \n\t" /* pre-add 'right' ptr */
+        "adc r31, %[zero] \n\t"
+        
+        "3: \n\t"
+        "ld r0, x+ \n\t"
+        "cp r26, r30 \n\t" /* if left == right here, then we are done after this mult (and we don't need to double) */
+        "breq 4f \n\t"
+        "ld r1, -z \n\t"
+        "mul r0, r1 \n\t"
+        
+        /* add twice since it costs the same as doubling */
+        "add %[r0], r0 \n\t"
+        "adc %[r1], r1 \n\t"
+        "adc %[r2], %[zero] \n\t"
+        "add %[r0], r0 \n\t"
+        "adc %[r1], r1 \n\t"
+        "adc %[r2], %[zero] \n\t"
+        
+        "cpse r26, r30 \n\t" /* if left == right here, then we are done */
+        "rjmp 3b \n\t"
+        "rjmp 5f \n\t" /* skip code for non-doubled mult */
+        
+        "4: \n\t"
+        "ld r1, -z \n\t"
+        "mul r0, r1 \n\t"
+        "add %[r0], r0 \n\t"
+        "adc %[r1], r1 \n\t"
+        "adc %[r2], %[zero] \n\t"
+        
+        "5: \n\t"
+        "movw r30, %[result] \n\t"  /* make z point to result */
+        "st z+, %[r0] \n\t"  /* Store the result. */
+        "movw %[result], r30 \n\t"  /* update result ptr*/
+        "mov %[r0], %[r1] \n\t"
+        "mov %[r1], %[r2] \n\t"
+        "mov %[r2], %[zero] \n\t"
+        
+        "inc %[k] \n\t"
+        "cpi %[k], %[max] \n\t"
+        "brlo 1b \n\t" /* loop if k < uECC_BYTES */
+        
+        "movw r30, %[result] \n\t"  /* make z point to result */
+        "st z+, %[r0] \n\t"  /* Store last result byte. */
+        
+        "eor r1, r1 \n\t" /* fix r1 to be 0 again */
+    
+        : [result] "+r" (p_result),
+          [r0] "+r" (r0), [r1] "+r" (r1), [r2] "+r" (r2), [zero] "+r" (l_zero),
+          [k] "=&a" (k)
+        : [orig] "r" (p_left), [max] "M" (2*uECC_BYTES)
+        : "r0", "r26", "r27", "r30", "r31", "cc", "memory"
+    );
+}
+#define asm_square 1
+#endif
+#endif /* uECC_SQUARE_FUNC */
diff --git a/extlibs/tinydtls/ecc/ecc.c b/extlibs/tinydtls/ecc/ecc.c
new file mode 100644 (file)
index 0000000..c9bd8c5
--- /dev/null
@@ -0,0 +1,2335 @@
+/* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
+
+#include "ecc.h"
+
+#ifndef uECC_PLATFORM
+    #if __AVR__
+        #define uECC_PLATFORM uECC_avr
+    #elif defined(__thumb2__) || defined(_M_ARMT) /* I think MSVC only supports Thumb-2 targets */
+        #define uECC_PLATFORM uECC_arm_thumb2
+    #elif defined(__thumb__)
+        #define uECC_PLATFORM uECC_arm_thumb
+    #elif defined(__arm__) || defined(_M_ARM)
+        #define uECC_PLATFORM uECC_arm
+    #elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) || defined(__I86__)
+        #define uECC_PLATFORM uECC_x86
+    #elif defined(__amd64__) || defined(_M_X64)
+        #define uECC_PLATFORM uECC_x86_64
+    #else
+        #define uECC_PLATFORM uECC_arch_other
+    #endif
+#endif
+
+#ifndef uECC_WORD_SIZE
+    #if uECC_PLATFORM == uECC_avr
+        #define uECC_WORD_SIZE 1
+    #elif (uECC_PLATFORM == uECC_x86_64)
+        #define uECC_WORD_SIZE 8
+    #else
+        #define uECC_WORD_SIZE 4
+    #endif
+#endif
+
+#if (uECC_CURVE == uECC_secp160r1) && (uECC_WORD_SIZE == 8)
+    #undef uECC_WORD_SIZE
+    #define uECC_WORD_SIZE 4
+    #if (uECC_PLATFORM == uECC_x86_64)
+        #undef uECC_PLATFORM
+        #define uECC_PLATFORM uECC_x86
+    #endif
+#endif
+
+#if (uECC_WORD_SIZE != 1) && (uECC_WORD_SIZE != 4) && (uECC_WORD_SIZE != 8)
+    #error "Unsupported value for uECC_WORD_SIZE"
+#endif
+
+#if (uECC_ASM && (uECC_PLATFORM == uECC_avr) && (uECC_WORD_SIZE != 1))
+    #pragma message ("uECC_WORD_SIZE must be 1 when using AVR asm")
+    #undef uECC_WORD_SIZE
+    #define uECC_WORD_SIZE 1
+#endif
+
+#if (uECC_ASM && (uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb) && (uECC_WORD_SIZE != 4))
+    #pragma message ("uECC_WORD_SIZE must be 4 when using ARM asm")
+    #undef uECC_WORD_SIZE
+    #define uECC_WORD_SIZE 4
+#endif
+
+#if __STDC_VERSION__ >= 199901L
+    #define RESTRICT restrict
+#else
+    #define RESTRICT
+#endif
+
+#if defined(__SIZEOF_INT128__) || ((__clang_major__ * 100 + __clang_minor__) >= 302)
+    #define SUPPORTS_INT128 1
+#else
+    #define SUPPORTS_INT128 0
+#endif
+
+#define MAX_TRIES 16
+
+#if (uECC_WORD_SIZE == 1)
+
+typedef uint8_t uECC_word_t;
+typedef uint16_t uECC_dword_t;
+typedef uint8_t wordcount_t;
+typedef int8_t swordcount_t;
+typedef int16_t bitcount_t;
+typedef int8_t cmpresult_t;
+
+#define HIGH_BIT_SET 0x80
+#define uECC_WORD_BITS 8
+#define uECC_WORD_BITS_SHIFT 3
+#define uECC_WORD_BITS_MASK 0x07
+
+#define uECC_WORDS_1 20
+#define uECC_WORDS_2 24
+#define uECC_WORDS_3 32
+#define uECC_WORDS_4 32
+
+#define uECC_N_WORDS_1 21
+#define uECC_N_WORDS_2 24
+#define uECC_N_WORDS_3 32
+#define uECC_N_WORDS_4 32
+
+#define Curve_P_1 {0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF}
+#define Curve_P_2 {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
+#define Curve_P_3 {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, \
+                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+                   0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF}
+#define Curve_P_4 {0x2F, 0xFC, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
+
+#define Curve_B_1 {0x45, 0xFA, 0x65, 0xC5, 0xAD, 0xD4, 0xD4, 0x81, \
+                   0x9F, 0xF8, 0xAC, 0x65, 0x8B, 0x7A, 0xBD, 0x54, \
+                   0xFC, 0xBE, 0x97, 0x1C}
+#define Curve_B_2 {0xB1, 0xB9, 0x46, 0xC1, 0xEC, 0xDE, 0xB8, 0xFE, \
+                   0x49, 0x30, 0x24, 0x72, 0xAB, 0xE9, 0xA7, 0x0F, \
+                   0xE7, 0x80, 0x9C, 0xE5, 0x19, 0x05, 0x21, 0x64}
+#define Curve_B_3 {0x4B, 0x60, 0xD2, 0x27, 0x3E, 0x3C, 0xCE, 0x3B, \
+                   0xF6, 0xB0, 0x53, 0xCC, 0xB0, 0x06, 0x1D, 0x65, \
+                   0xBC, 0x86, 0x98, 0x76, 0x55, 0xBD, 0xEB, 0xB3, \
+                   0xE7, 0x93, 0x3A, 0xAA, 0xD8, 0x35, 0xC6, 0x5A}
+#define Curve_B_4 {0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
+
+#define Curve_G_1 { \
+    {0x82, 0xFC, 0xCB, 0x13, 0xB9, 0x8B, 0xC3, 0x68, \
+        0x89, 0x69, 0x64, 0x46, 0x28, 0x73, 0xF5, 0x8E, \
+        0x68, 0xB5, 0x96, 0x4A}, \
+    {0x32, 0xFB, 0xC5, 0x7A, 0x37, 0x51, 0x23, 0x04, \
+        0x12, 0xC9, 0xDC, 0x59, 0x7D, 0x94, 0x68, 0x31, \
+        0x55, 0x28, 0xA6, 0x23}}
+
+#define Curve_G_2 { \
+    {0x12, 0x10, 0xFF, 0x82, 0xFD, 0x0A, 0xFF, 0xF4, \
+        0x00, 0x88, 0xA1, 0x43, 0xEB, 0x20, 0xBF, 0x7C, \
+        0xF6, 0x90, 0x30, 0xB0, 0x0E, 0xA8, 0x8D, 0x18}, \
+    {0x11, 0x48, 0x79, 0x1E, 0xA1, 0x77, 0xF9, 0x73, \
+        0xD5, 0xCD, 0x24, 0x6B, 0xED, 0x11, 0x10, 0x63, \
+        0x78, 0xDA, 0xC8, 0xFF, 0x95, 0x2B, 0x19, 0x07}}
+
+#define Curve_G_3 { \
+    {0x96, 0xC2, 0x98, 0xD8, 0x45, 0x39, 0xA1, 0xF4, \
+        0xA0, 0x33, 0xEB, 0x2D, 0x81, 0x7D, 0x03, 0x77, \
+        0xF2, 0x40, 0xA4, 0x63, 0xE5, 0xE6, 0xBC, 0xF8, \
+        0x47, 0x42, 0x2C, 0xE1, 0xF2, 0xD1, 0x17, 0x6B}, \
+    {0xF5, 0x51, 0xBF, 0x37, 0x68, 0x40, 0xB6, 0xCB, \
+        0xCE, 0x5E, 0x31, 0x6B, 0x57, 0x33, 0xCE, 0x2B, \
+        0x16, 0x9E, 0x0F, 0x7C, 0x4A, 0xEB, 0xE7, 0x8E, \
+        0x9B, 0x7F, 0x1A, 0xFE, 0xE2, 0x42, 0xE3, 0x4F}}
+
+#define Curve_G_4 { \
+    {0x98, 0x17, 0xF8, 0x16, 0x5B, 0x81, 0xF2, 0x59, \
+        0xD9, 0x28, 0xCE, 0x2D, 0xDB, 0xFC, 0x9B, 0x02, \
+        0x07, 0x0B, 0x87, 0xCE, 0x95, 0x62, 0xA0, 0x55, \
+        0xAC, 0xBB, 0xDC, 0xF9, 0x7E, 0x66, 0xBE, 0x79}, \
+    {0xB8, 0xD4, 0x10, 0xFB, 0x8F, 0xD0, 0x47, 0x9C, \
+        0x19, 0x54, 0x85, 0xA6, 0x48, 0xB4, 0x17, 0xFD, \
+        0xA8, 0x08, 0x11, 0x0E, 0xFC, 0xFB, 0xA4, 0x5D, \
+        0x65, 0xC4, 0xA3, 0x26, 0x77, 0xDA, 0x3A, 0x48}}
+
+#define Curve_N_1 {0x57, 0x22, 0x75, 0xCA, 0xD3, 0xAE, 0x27, 0xF9, \
+                   0xC8, 0xF4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, \
+                   0x00, 0x00, 0x00, 0x00, 0x01}
+#define Curve_N_2 {0x31, 0x28, 0xD2, 0xB4, 0xB1, 0xC9, 0x6B, 0x14, \
+                   0x36, 0xF8, 0xDE, 0x99, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
+#define Curve_N_3 {0x51, 0x25, 0x63, 0xFC, 0xC2, 0xCA, 0xB9, 0xF3, \
+                   0x84, 0x9E, 0x17, 0xA7, 0xAD, 0xFA, 0xE6, 0xBC, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF}
+#define Curve_N_4 {0x41, 0x41, 0x36, 0xD0, 0x8C, 0x5E, 0xD2, 0xBF, \
+                   0x3B, 0xA0, 0x48, 0xAF, 0xE6, 0xDC, 0xAE, 0xBA, \
+                   0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+                   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
+
+#elif (uECC_WORD_SIZE == 4)
+
+typedef uint32_t uECC_word_t;
+typedef uint64_t uECC_dword_t;
+typedef unsigned wordcount_t;
+typedef int swordcount_t;
+typedef int bitcount_t;
+typedef int cmpresult_t;
+
+#define HIGH_BIT_SET 0x80000000
+#define uECC_WORD_BITS 32
+#define uECC_WORD_BITS_SHIFT 5
+#define uECC_WORD_BITS_MASK 0x01F
+
+#define uECC_WORDS_1 5
+#define uECC_WORDS_2 6
+#define uECC_WORDS_3 8
+#define uECC_WORDS_4 8
+
+#define uECC_N_WORDS_1 6
+#define uECC_N_WORDS_2 6
+#define uECC_N_WORDS_3 8
+#define uECC_N_WORDS_4 8
+
+#define Curve_P_1 {0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}
+#define Curve_P_2 {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}
+#define Curve_P_3 {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}
+#define Curve_P_4 {0xFFFFFC2F, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}
+
+#define Curve_B_1 {0xC565FA45, 0x81D4D4AD, 0x65ACF89F, 0x54BD7A8B, 0x1C97BEFC}
+#define Curve_B_2 {0xC146B9B1, 0xFEB8DEEC, 0x72243049, 0x0FA7E9AB, 0xE59C80E7, 0x64210519}
+#define Curve_B_3 {0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8}
+#define Curve_B_4 {0x00000007, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}
+
+#define Curve_G_1 { \
+    {0x13CBFC82, 0x68C38BB9, 0x46646989, 0x8EF57328, 0x4A96B568}, \
+    {0x7AC5FB32, 0x04235137, 0x59DCC912, 0x3168947D, 0x23A62855}}
+
+#define Curve_G_2 { \
+    {0x82FF1012, 0xF4FF0AFD, 0x43A18800, 0x7CBF20EB, 0xB03090F6, 0x188DA80E}, \
+    {0x1E794811, 0x73F977A1, 0x6B24CDD5, 0x631011ED, 0xFFC8DA78, 0x07192B95}}
+
+#define Curve_G_3 { \
+    {0xD898C296, 0xF4A13945, 0x2DEB33A0, 0x77037D81, 0x63A440F2, 0xF8BCE6E5, 0xE12C4247, 0x6B17D1F2}, \
+    {0x37BF51F5, 0xCBB64068, 0x6B315ECE, 0x2BCE3357, 0x7C0F9E16, 0x8EE7EB4A, 0xFE1A7F9B, 0x4FE342E2}}
+
+#define Curve_G_4 { \
+    {0x16F81798, 0x59F2815B, 0x2DCE28D9, 0x029BFCDB, 0xCE870B07, 0x55A06295, 0xF9DCBBAC, 0x79BE667E}, \
+    {0xFB10D4B8, 0x9C47D08F, 0xA6855419, 0xFD17B448, 0x0E1108A8, 0x5DA4FBFC, 0x26A3C465, 0x483ADA77}}
+
+#define Curve_N_1 {0xCA752257, 0xF927AED3, 0x0001F4C8, 0x00000000, 0x00000000, 0x00000001}
+#define Curve_N_2 {0xB4D22831, 0x146BC9B1, 0x99DEF836, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}
+#define Curve_N_3 {0xFC632551, 0xF3B9CAC2, 0xA7179E84, 0xBCE6FAAD, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF}
+#define Curve_N_4 {0xD0364141, 0xBFD25E8C, 0xAF48A03B, 0xBAAEDCE6, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}
+
+#elif (uECC_WORD_SIZE == 8)
+
+typedef uint64_t uECC_word_t;
+#if SUPPORTS_INT128
+typedef unsigned __int128 uECC_dword_t;
+#endif
+typedef unsigned wordcount_t;
+typedef int swordcount_t;
+typedef int bitcount_t;
+typedef int cmpresult_t;
+
+#define HIGH_BIT_SET 0x8000000000000000ull
+#define uECC_WORD_BITS 64
+#define uECC_WORD_BITS_SHIFT 6
+#define uECC_WORD_BITS_MASK 0x03F
+
+#define uECC_WORDS_1 3
+#define uECC_WORDS_2 3
+#define uECC_WORDS_3 4
+#define uECC_WORDS_4 4
+
+#define uECC_N_WORDS_1 3
+#define uECC_N_WORDS_2 3
+#define uECC_N_WORDS_3 4
+#define uECC_N_WORDS_4 4
+
+#define Curve_P_1 {0xFFFFFFFF7FFFFFFFull, 0xFFFFFFFFFFFFFFFFull, 0x00000000FFFFFFFFull}
+#define Curve_P_2 {0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFFFFFFFFFEull, 0xFFFFFFFFFFFFFFFFull}
+#define Curve_P_3 {0xFFFFFFFFFFFFFFFFull, 0x00000000FFFFFFFFull, 0x0000000000000000ull, 0xFFFFFFFF00000001ull}
+#define Curve_P_4 {0xFFFFFFFEFFFFFC2Full, 0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFFFFFFFFFFull}
+
+#define Curve_B_1 {0x81D4D4ADC565FA45ull, 0x54BD7A8B65ACF89Full, 0x000000001C97BEFCull}
+#define Curve_B_2 {0xFEB8DEECC146B9B1ull, 0x0FA7E9AB72243049ull, 0x64210519E59C80E7ull}
+#define Curve_B_3 {0x3BCE3C3E27D2604Bull, 0x651D06B0CC53B0F6ull, 0xB3EBBD55769886BCull, 0x5AC635D8AA3A93E7ull}
+#define Curve_B_4 {0x0000000000000007ull, 0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull}
+
+#define Curve_G_1 { \
+    {0x68C38BB913CBFC82ull, 0x8EF5732846646989ull, 0x000000004A96B568ull}, \
+    {0x042351377AC5FB32ull, 0x3168947D59DCC912ull, 0x0000000023A62855ull}}
+
+#define Curve_G_2 { \
+    {0xF4FF0AFD82FF1012ull, 0x7CBF20EB43A18800ull, 0x188DA80EB03090F6ull}, \
+    {0x73F977A11E794811ull, 0x631011ED6B24CDD5ull, 0x07192B95FFC8DA78ull}}
+
+#define Curve_G_3 { \
+    {0xF4A13945D898C296ull, 0x77037D812DEB33A0ull, 0xF8BCE6E563A440F2ull, 0x6B17D1F2E12C4247ull}, \
+    {0xCBB6406837BF51F5ull, 0x2BCE33576B315ECEull, 0x8EE7EB4A7C0F9E16ull, 0x4FE342E2FE1A7F9Bull}}
+
+#define Curve_G_4 { \
+    {0x59F2815B16F81798, 0x029BFCDB2DCE28D9, 0x55A06295CE870B07, 0x79BE667EF9DCBBAC}, \
+    {0x9C47D08FFB10D4B8, 0xFD17B448A6855419, 0x5DA4FBFC0E1108A8, 0x483ADA7726A3C465}}
+
+#define Curve_N_1 {0xF927AED3CA752257ull, 0x000000000001F4C8ull, 0x0000000100000000ull}
+#define Curve_N_2 {0x146BC9B1B4D22831ull, 0xFFFFFFFF99DEF836ull, 0xFFFFFFFFFFFFFFFFull}
+#define Curve_N_3 {0xF3B9CAC2FC632551ull, 0xBCE6FAADA7179E84ull, 0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFF00000000ull}
+#define Curve_N_4 {0xBFD25E8CD0364141, 0xBAAEDCE6AF48A03B, 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF}
+
+#endif /* (uECC_WORD_SIZE == 8) */
+
+#define uECC_WORDS uECC_CONCAT(uECC_WORDS_, uECC_CURVE)
+#define uECC_N_WORDS uECC_CONCAT(uECC_N_WORDS_, uECC_CURVE)
+
+typedef struct EccPoint
+{
+    uECC_word_t x[uECC_WORDS];
+    uECC_word_t y[uECC_WORDS];
+} EccPoint;
+
+static uECC_word_t curve_p[uECC_WORDS] = uECC_CONCAT(Curve_P_, uECC_CURVE);
+static uECC_word_t curve_b[uECC_WORDS] = uECC_CONCAT(Curve_B_, uECC_CURVE);
+static EccPoint curve_G = uECC_CONCAT(Curve_G_, uECC_CURVE);
+static uECC_word_t curve_n[uECC_N_WORDS] = uECC_CONCAT(Curve_N_, uECC_CURVE);
+
+static void vli_clear(uECC_word_t *p_vli);
+static uECC_word_t vli_isZero(const uECC_word_t *p_vli);
+static uECC_word_t vli_testBit(const uECC_word_t *p_vli, bitcount_t p_bit);
+static bitcount_t vli_numBits(const uECC_word_t *p_vli, wordcount_t p_maxWords);
+static void vli_set(uECC_word_t *p_dest, const uECC_word_t *p_src);
+static cmpresult_t vli_cmp(uECC_word_t *p_left, uECC_word_t *p_right);
+static void vli_rshift1(uECC_word_t *p_vli);
+static uECC_word_t vli_add(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right);
+static uECC_word_t vli_sub(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right);
+static void vli_mult(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right);
+static void vli_modAdd(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right, uECC_word_t *p_mod);
+static void vli_modSub(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right, uECC_word_t *p_mod);
+static void vli_mmod_fast(uECC_word_t *RESTRICT p_result, uECC_word_t *RESTRICT p_product);
+static void vli_modMult_fast(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right);
+static void vli_modInv(uECC_word_t *p_result, uECC_word_t *p_input, uECC_word_t *p_mod);
+#if uECC_SQUARE_FUNC
+static void vli_square(uECC_word_t *p_result, uECC_word_t *p_left);
+static void vli_modSquare_fast(uECC_word_t *p_result, uECC_word_t *p_left);
+#endif
+
+#if (defined(_WIN32) || defined(_WIN64))
+/* Windows */
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <wincrypt.h>
+
+static int default_RNG(uint8_t *p_dest, unsigned p_size)
+{
+    HCRYPTPROV l_prov;
+    if(!CryptAcquireContext(&l_prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
+    {
+        return 0;
+    }
+
+    CryptGenRandom(l_prov, p_size, (BYTE *)p_dest);
+    CryptReleaseContext(l_prov, 0);
+
+    return 1;
+}
+
+#elif defined(unix) || defined(__linux__) || defined(__unix__) || defined(__unix) || \
+    (defined(__APPLE__) && defined(__MACH__)) || defined(uECC_POSIX)
+
+/* Some POSIX-like system with /dev/urandom or /dev/random. */
+#include <sys/types.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#ifndef O_CLOEXEC
+    #define O_CLOEXEC 0
+#endif
+
+static int default_RNG(uint8_t *p_dest, unsigned p_size)
+{
+    int l_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
+    if(l_fd == -1)
+    {
+        l_fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
+        if(l_fd == -1)
+        {
+            return 0;
+        }
+    }
+
+    char *l_ptr = (char *)p_dest;
+    size_t l_left = p_size;
+    while(l_left > 0)
+    {
+        int l_read = read(l_fd, l_ptr, l_left);
+        if(l_read <= 0)
+        { // read failed
+            close(l_fd);
+            return 0;
+        }
+        l_left -= l_read;
+        l_ptr += l_read;
+    }
+
+    close(l_fd);
+    return 1;
+}
+
+#else /* Some other platform */
+
+static int default_RNG(uint8_t *p_dest, unsigned p_size)
+{
+    return 0;
+}
+
+#endif
+
+static uECC_RNG_Function g_rng = &default_RNG;
+
+void uECC_set_rng(uECC_RNG_Function p_rng)
+{
+    g_rng = p_rng;
+}
+
+#ifdef __GNUC__ /* Only support GCC inline asm for now */
+    #if (uECC_ASM && (uECC_PLATFORM == uECC_avr))
+        #include "asm_avr.inc"
+    #endif
+
+    #if (uECC_ASM && (uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb || uECC_PLATFORM == uECC_arm_thumb2))
+        #include "asm_arm.inc"
+    #endif
+#endif
+
+#if !asm_clear
+static void vli_clear(uECC_word_t *p_vli)
+{
+    wordcount_t i;
+    for(i = 0; i < uECC_WORDS; ++i)
+    {
+        p_vli[i] = 0;
+    }
+}
+#endif
+
+/* Returns 1 if p_vli == 0, 0 otherwise. */
+#if !asm_isZero
+static uECC_word_t vli_isZero(const uECC_word_t *p_vli)
+{
+    wordcount_t i;
+    for(i = 0; i < uECC_WORDS; ++i)
+    {
+        if(p_vli[i])
+        {
+            return 0;
+        }
+    }
+    return 1;
+}
+#endif
+
+/* Returns nonzero if bit p_bit of p_vli is set. */
+#if !asm_testBit
+static uECC_word_t vli_testBit(const uECC_word_t *p_vli, bitcount_t p_bit)
+{
+    return (p_vli[p_bit >> uECC_WORD_BITS_SHIFT] & ((uECC_word_t)1 << (p_bit & uECC_WORD_BITS_MASK)));
+}
+#endif
+
+/* Counts the number of words in p_vli. */
+#if !asm_numBits
+static wordcount_t vli_numDigits(const uECC_word_t *p_vli, wordcount_t p_maxWords)
+{
+    swordcount_t i;
+    /* Search from the end until we find a non-zero digit.
+       We do it in reverse because we expect that most digits will be nonzero. */
+    for(i = p_maxWords-1; i >= 0 && p_vli[i] == 0; --i)
+    {
+    }
+
+    return (i + 1);
+}
+
+/* Counts the number of bits required to represent p_vli. */
+static bitcount_t vli_numBits(const uECC_word_t *p_vli, wordcount_t p_maxWords)
+{
+    uECC_word_t i;
+    uECC_word_t l_digit;
+
+    wordcount_t l_numDigits = vli_numDigits(p_vli, p_maxWords);
+    if(l_numDigits == 0)
+    {
+        return 0;
+    }
+
+    l_digit = p_vli[l_numDigits - 1];
+    for(i = 0; l_digit; ++i)
+    {
+        l_digit >>= 1;
+    }
+
+    return (((bitcount_t)(l_numDigits - 1) << uECC_WORD_BITS_SHIFT) + i);
+}
+#endif /* !asm_numBits */
+
+/* Sets p_dest = p_src. */
+#if !asm_set
+static void vli_set(uECC_word_t *p_dest, const uECC_word_t *p_src)
+{
+    wordcount_t i;
+    for(i=0; i<uECC_WORDS; ++i)
+    {
+        p_dest[i] = p_src[i];
+    }
+}
+#endif
+
+/* Returns sign of p_left - p_right. */
+#if !asm_cmp
+static cmpresult_t vli_cmp(uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    swordcount_t i;
+    for(i = uECC_WORDS-1; i >= 0; --i)
+    {
+        if(p_left[i] > p_right[i])
+        {
+            return 1;
+        }
+        else if(p_left[i] < p_right[i])
+        {
+            return -1;
+        }
+    }
+    return 0;
+}
+#endif
+
+/* Computes p_vli = p_vli >> 1. */
+#if !asm_rshift1
+static void vli_rshift1(uECC_word_t *p_vli)
+{
+    uECC_word_t *l_end = p_vli;
+    uECC_word_t l_carry = 0;
+
+    p_vli += uECC_WORDS;
+    while(p_vli-- > l_end)
+    {
+        uECC_word_t l_temp = *p_vli;
+        *p_vli = (l_temp >> 1) | l_carry;
+        l_carry = l_temp << (uECC_WORD_BITS - 1);
+    }
+}
+#endif
+
+/* Computes p_result = p_left + p_right, returning carry. Can modify in place. */
+#if !asm_add
+static uECC_word_t vli_add(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_carry = 0;
+    wordcount_t i;
+    for(i = 0; i < uECC_WORDS; ++i)
+    {
+        uECC_word_t l_sum = p_left[i] + p_right[i] + l_carry;
+        if(l_sum != p_left[i])
+        {
+            l_carry = (l_sum < p_left[i]);
+        }
+        p_result[i] = l_sum;
+    }
+    return l_carry;
+}
+#endif
+
+/* Computes p_result = p_left - p_right, returning borrow. Can modify in place. */
+#if !asm_sub
+static uECC_word_t vli_sub(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_borrow = 0;
+    wordcount_t i;
+    for(i = 0; i < uECC_WORDS; ++i)
+    {
+        uECC_word_t l_diff = p_left[i] - p_right[i] - l_borrow;
+        if(l_diff != p_left[i])
+        {
+            l_borrow = (l_diff > p_left[i]);
+        }
+        p_result[i] = l_diff;
+    }
+    return l_borrow;
+}
+#endif
+
+#if (!asm_mult || !asm_square || uECC_CURVE == uECC_secp256k1)
+static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0, uECC_word_t *r1, uECC_word_t *r2)
+{
+#if uECC_WORD_SIZE == 8 && !SUPPORTS_INT128
+    uint64_t a0 = a & 0xffffffffull;
+    uint64_t a1 = a >> 32;
+    uint64_t b0 = b & 0xffffffffull;
+    uint64_t b1 = b >> 32;
+
+    uint64_t i0 = a0 * b0;
+    uint64_t i1 = a0 * b1;
+    uint64_t i2 = a1 * b0;
+    uint64_t i3 = a1 * b1;
+
+    uint64_t p0, p1;
+
+    i2 += (i0 >> 32);
+    i2 += i1;
+    if(i2 < i1)
+    { // overflow
+        i3 += 0x100000000ull;
+    }
+
+    p0 = (i0 & 0xffffffffull) | (i2 << 32);
+    p1 = i3 + (i2 >> 32);
+
+    *r0 += p0;
+    *r1 += (p1 + (*r0 < p0));
+    *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
+#else
+    uECC_dword_t p = (uECC_dword_t)a * b;
+    uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
+    r01 += p;
+    *r2 += (r01 < p);
+    *r1 = r01 >> uECC_WORD_BITS;
+    *r0 = (uECC_word_t)r01;
+#endif
+}
+#define muladd_exists 1
+#endif
+
+#if !asm_mult
+static void vli_mult(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t r0 = 0;
+    uECC_word_t r1 = 0;
+    uECC_word_t r2 = 0;
+
+    wordcount_t i, k;
+
+    /* Compute each digit of p_result in sequence, maintaining the carries. */
+    for(k = 0; k < uECC_WORDS; ++k)
+    {
+        for(i = 0; i <= k; ++i)
+        {
+            muladd(p_left[i], p_right[k-i], &r0, &r1, &r2);
+        }
+        p_result[k] = r0;
+        r0 = r1;
+        r1 = r2;
+        r2 = 0;
+    }
+    for(k = uECC_WORDS; k < uECC_WORDS*2 - 1; ++k)
+    {
+        for(i = (k + 1) - uECC_WORDS; i<uECC_WORDS; ++i)
+        {
+            muladd(p_left[i], p_right[k-i], &r0, &r1, &r2);
+        }
+        p_result[k] = r0;
+        r0 = r1;
+        r1 = r2;
+        r2 = 0;
+    }
+
+    p_result[uECC_WORDS*2 - 1] = r0;
+}
+#endif
+
+#if uECC_SQUARE_FUNC
+
+#if !asm_square
+static void mul2add(uECC_word_t a, uECC_word_t b, uECC_word_t *r0, uECC_word_t *r1, uECC_word_t *r2)
+{
+#if uECC_WORD_SIZE == 8 && !SUPPORTS_INT128
+    uint64_t a0 = a & 0xffffffffull;
+    uint64_t a1 = a >> 32;
+    uint64_t b0 = b & 0xffffffffull;
+    uint64_t b1 = b >> 32;
+
+    uint64_t i0 = a0 * b0;
+    uint64_t i1 = a0 * b1;
+    uint64_t i2 = a1 * b0;
+    uint64_t i3 = a1 * b1;
+
+    uint64_t p0, p1;
+
+    i2 += (i0 >> 32);
+    i2 += i1;
+    if(i2 < i1)
+    { // overflow
+        i3 += 0x100000000ull;
+    }
+
+    p0 = (i0 & 0xffffffffull) | (i2 << 32);
+    p1 = i3 + (i2 >> 32);
+
+    *r2 += (p1 >> 63);
+    p1 = (p1 << 1) | (p0 >> 63);
+    p0 <<= 1;
+
+    *r0 += p0;
+    *r1 += (p1 + (*r0 < p0));
+    *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
+#else
+    uECC_dword_t p = (uECC_dword_t)a * b;
+    uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
+    *r2 += (p >> (uECC_WORD_BITS * 2 - 1));
+    p *= 2;
+    r01 += p;
+    *r2 += (r01 < p);
+    *r1 = r01 >> uECC_WORD_BITS;
+    *r0 = (uECC_word_t)r01;
+#endif
+}
+
+static void vli_square(uECC_word_t *p_result, uECC_word_t *p_left)
+{
+    uECC_word_t r0 = 0;
+    uECC_word_t r1 = 0;
+    uECC_word_t r2 = 0;
+
+    wordcount_t i, k;
+
+    for(k = 0; k < uECC_WORDS*2 - 1; ++k)
+    {
+        uECC_word_t l_min = (k < uECC_WORDS ? 0 : (k + 1) - uECC_WORDS);
+        for(i = l_min; i<=k && i<=k-i; ++i)
+        {
+            if(i < k-i)
+            {
+                mul2add(p_left[i], p_left[k-i], &r0, &r1, &r2);
+            }
+            else
+            {
+                muladd(p_left[i], p_left[k-i], &r0, &r1, &r2);
+            }
+        }
+        p_result[k] = r0;
+        r0 = r1;
+        r1 = r2;
+        r2 = 0;
+    }
+
+    p_result[uECC_WORDS*2 - 1] = r0;
+}
+#endif
+
+#else /* uECC_SQUARE_FUNC */
+
+#define vli_square(result, left, size) vli_mult((result), (left), (left), (size))
+
+#endif /* uECC_SQUARE_FUNC */
+
+
+/* Computes p_result = (p_left + p_right) % p_mod.
+   Assumes that p_left < p_mod and p_right < p_mod, p_result != p_mod. */
+#if !asm_modAdd
+static void vli_modAdd(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right, uECC_word_t *p_mod)
+{
+    uECC_word_t l_carry = vli_add(p_result, p_left, p_right);
+    if(l_carry || vli_cmp(p_result, p_mod) >= 0)
+    { /* p_result > p_mod (p_result = p_mod + remainder), so subtract p_mod to get remainder. */
+        vli_sub(p_result, p_result, p_mod);
+    }
+}
+#endif
+
+/* Computes p_result = (p_left - p_right) % p_mod.
+   Assumes that p_left < p_mod and p_right < p_mod, p_result != p_mod. */
+#if !asm_modSub
+static void vli_modSub(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right, uECC_word_t *p_mod)
+{
+    uECC_word_t l_borrow = vli_sub(p_result, p_left, p_right);
+    if(l_borrow)
+    { /* In this case, p_result == -diff == (max int) - diff.
+         Since -x % d == d - x, we can get the correct result from p_result + p_mod (with overflow). */
+        vli_add(p_result, p_result, p_mod);
+    }
+}
+#endif
+
+#if !asm_modSub_fast
+    #define vli_modSub_fast(result, left, right) vli_modSub((result), (left), (right), curve_p)
+#endif
+
+#if !asm_mmod_fast
+
+#if (uECC_CURVE == uECC_secp160r1 || uECC_CURVE == uECC_secp256k1)
+/* omega_mult() is defined farther below for the different curves / word sizes */
+static void omega_mult(uECC_word_t * RESTRICT p_result, uECC_word_t * RESTRICT p_right);
+
+/* Computes p_result = p_product % curve_p
+    see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
+
+    Note that this only works if log2(omega) < log2(p)/2 */
+static void vli_mmod_fast(uECC_word_t *RESTRICT p_result, uECC_word_t *RESTRICT p_product)
+{
+    uECC_word_t l_tmp[2*uECC_WORDS];
+    uECC_word_t l_carry;
+
+    vli_clear(l_tmp);
+    vli_clear(l_tmp + uECC_WORDS);
+
+    omega_mult(l_tmp, p_product + uECC_WORDS); /* (Rq, q) = q * c */
+
+    l_carry = vli_add(p_result, p_product, l_tmp); /* (C, r) = r + q       */
+    vli_clear(p_product);
+    omega_mult(p_product, l_tmp + uECC_WORDS); /* Rq*c */
+    l_carry += vli_add(p_result, p_result, p_product); /* (C1, r) = r + Rq*c */
+
+    while(l_carry > 0)
+    {
+        --l_carry;
+        vli_sub(p_result, p_result, curve_p);
+    }
+
+    if(vli_cmp(p_result, curve_p) > 0)
+    {
+        vli_sub(p_result, p_result, curve_p);
+    }
+}
+
+#endif
+
+#if uECC_CURVE == uECC_secp160r1
+
+#if uECC_WORD_SIZE == 1
+static void omega_mult(uint8_t * RESTRICT p_result, uint8_t * RESTRICT p_right)
+{
+    uint8_t l_carry;
+    uint8_t i;
+
+    /* Multiply by (2^31 + 1). */
+    vli_set(p_result + 4, p_right); /* 2^32 */
+    vli_rshift1(p_result + 4); /* 2^31 */
+    p_result[3] = p_right[0] << 7; /* get last bit from shift */
+
+    l_carry = vli_add(p_result, p_result, p_right); /* 2^31 + 1 */
+    for(i = uECC_WORDS; l_carry; ++i)
+    {
+        uint16_t l_sum = (uint16_t)p_result[i] + l_carry;
+        p_result[i] = (uint8_t)l_sum;
+        l_carry = l_sum >> 8;
+    }
+}
+#elif uECC_WORD_SIZE == 4
+static void omega_mult(uint32_t * RESTRICT p_result, uint32_t * RESTRICT p_right)
+{
+    uint32_t l_carry;
+    unsigned i;
+
+    /* Multiply by (2^31 + 1). */
+    vli_set(p_result + 1, p_right); /* 2^32 */
+    vli_rshift1(p_result + 1); /* 2^31 */
+    p_result[0] = p_right[0] << 31; /* get last bit from shift */
+
+    l_carry = vli_add(p_result, p_result, p_right); /* 2^31 + 1 */
+    for(i = uECC_WORDS; l_carry; ++i)
+    {
+        uint64_t l_sum = (uint64_t)p_result[i] + l_carry;
+        p_result[i] = (uint32_t)l_sum;
+        l_carry = l_sum >> 32;
+    }
+}
+#endif /* uECC_WORD_SIZE */
+
+#elif uECC_CURVE == uECC_secp192r1
+
+/* Computes p_result = p_product % curve_p.
+   See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf */
+#if uECC_WORD_SIZE == 1
+static void vli_mmod_fast(uint8_t *RESTRICT p_result, uint8_t *RESTRICT p_product)
+{
+    uint8_t l_tmp[uECC_WORDS];
+    uint8_t l_carry;
+
+    vli_set(p_result, p_product);
+
+    vli_set(l_tmp, &p_product[24]);
+    l_carry = vli_add(p_result, p_result, l_tmp);
+
+    l_tmp[0] = l_tmp[1] = l_tmp[2] = l_tmp[3] = l_tmp[4] = l_tmp[5] = l_tmp[6] = l_tmp[7] = 0;
+    l_tmp[8] = p_product[24]; l_tmp[9] = p_product[25]; l_tmp[10] = p_product[26]; l_tmp[11] = p_product[27];
+    l_tmp[12] = p_product[28]; l_tmp[13] = p_product[29]; l_tmp[14] = p_product[30]; l_tmp[15] = p_product[31];
+    l_tmp[16] = p_product[32]; l_tmp[17] = p_product[33]; l_tmp[18] = p_product[34]; l_tmp[19] = p_product[35];
+    l_tmp[20] = p_product[36]; l_tmp[21] = p_product[37]; l_tmp[22] = p_product[38]; l_tmp[23] = p_product[39];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    l_tmp[0] = l_tmp[8] = p_product[40];
+    l_tmp[1] = l_tmp[9] = p_product[41];
+    l_tmp[2] = l_tmp[10] = p_product[42];
+    l_tmp[3] = l_tmp[11] = p_product[43];
+    l_tmp[4] = l_tmp[12] = p_product[44];
+    l_tmp[5] = l_tmp[13] = p_product[45];
+    l_tmp[6] = l_tmp[14] = p_product[46];
+    l_tmp[7] = l_tmp[15] = p_product[47];
+    l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    while(l_carry || vli_cmp(curve_p, p_result) != 1)
+    {
+        l_carry -= vli_sub(p_result, p_result, curve_p);
+    }
+}
+#elif uECC_WORD_SIZE == 4
+static void vli_mmod_fast(uint32_t *RESTRICT p_result, uint32_t *RESTRICT p_product)
+{
+    uint32_t l_tmp[uECC_WORDS];
+    int l_carry;
+
+    vli_set(p_result, p_product);
+
+    vli_set(l_tmp, &p_product[6]);
+    l_carry = vli_add(p_result, p_result, l_tmp);
+
+    l_tmp[0] = l_tmp[1] = 0;
+    l_tmp[2] = p_product[6];
+    l_tmp[3] = p_product[7];
+    l_tmp[4] = p_product[8];
+    l_tmp[5] = p_product[9];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    l_tmp[0] = l_tmp[2] = p_product[10];
+    l_tmp[1] = l_tmp[3] = p_product[11];
+    l_tmp[4] = l_tmp[5] = 0;
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    while(l_carry || vli_cmp(curve_p, p_result) != 1)
+    {
+        l_carry -= vli_sub(p_result, p_result, curve_p);
+    }
+}
+#else
+static void vli_mmod_fast(uint64_t *RESTRICT p_result, uint64_t *RESTRICT p_product)
+{
+    uint64_t l_tmp[uECC_WORDS];
+    int l_carry;
+
+    vli_set(p_result, p_product);
+
+    vli_set(l_tmp, &p_product[3]);
+    l_carry = vli_add(p_result, p_result, l_tmp);
+
+    l_tmp[0] = 0;
+    l_tmp[1] = p_product[3];
+    l_tmp[2] = p_product[4];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    l_tmp[0] = l_tmp[1] = p_product[5];
+    l_tmp[2] = 0;
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    while(l_carry || vli_cmp(curve_p, p_result) != 1)
+    {
+        l_carry -= vli_sub(p_result, p_result, curve_p);
+    }
+}
+#endif /* uECC_WORD_SIZE */
+
+#elif uECC_CURVE == uECC_secp256r1
+
+/* Computes p_result = p_product % curve_p
+   from http://www.nsa.gov/ia/_files/nist-routines.pdf */
+#if uECC_WORD_SIZE == 1
+static void vli_mmod_fast(uint8_t *RESTRICT p_result, uint8_t *RESTRICT p_product)
+{
+    uint8_t l_tmp[uECC_BYTES];
+    int8_t l_carry;
+
+    /* t */
+    vli_set(p_result, p_product);
+
+    /* s1 */
+    l_tmp[0] = l_tmp[1] = l_tmp[2] = l_tmp[3] = 0;
+    l_tmp[4] = l_tmp[5] = l_tmp[6] = l_tmp[7] = 0;
+    l_tmp[8] = l_tmp[9] = l_tmp[10] = l_tmp[11] = 0;
+    l_tmp[12] = p_product[44]; l_tmp[13] = p_product[45]; l_tmp[14] = p_product[46]; l_tmp[15] = p_product[47];
+    l_tmp[16] = p_product[48]; l_tmp[17] = p_product[49]; l_tmp[18] = p_product[50]; l_tmp[19] = p_product[51];
+    l_tmp[20] = p_product[52]; l_tmp[21] = p_product[53]; l_tmp[22] = p_product[54]; l_tmp[23] = p_product[55];
+    l_tmp[24] = p_product[56]; l_tmp[25] = p_product[57]; l_tmp[26] = p_product[58]; l_tmp[27] = p_product[59];
+    l_tmp[28] = p_product[60]; l_tmp[29] = p_product[61]; l_tmp[30] = p_product[62]; l_tmp[31] = p_product[63];
+    l_carry = vli_add(l_tmp, l_tmp, l_tmp);
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s2 */
+    l_tmp[12] = p_product[48]; l_tmp[13] = p_product[49]; l_tmp[14] = p_product[50]; l_tmp[15] = p_product[51];
+    l_tmp[16] = p_product[52]; l_tmp[17] = p_product[53]; l_tmp[18] = p_product[54]; l_tmp[19] = p_product[55];
+    l_tmp[20] = p_product[56]; l_tmp[21] = p_product[57]; l_tmp[22] = p_product[58]; l_tmp[23] = p_product[59];
+    l_tmp[24] = p_product[60]; l_tmp[25] = p_product[61]; l_tmp[26] = p_product[62]; l_tmp[27] = p_product[63];
+    l_tmp[28] = l_tmp[29] = l_tmp[30] = l_tmp[31] = 0;
+    l_carry += vli_add(l_tmp, l_tmp, l_tmp);
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s3 */
+    l_tmp[0] = p_product[32]; l_tmp[1] = p_product[33]; l_tmp[2] = p_product[34]; l_tmp[3] = p_product[35];
+    l_tmp[4] = p_product[36]; l_tmp[5] = p_product[37]; l_tmp[6] = p_product[38]; l_tmp[7] = p_product[39];
+    l_tmp[8] = p_product[40]; l_tmp[9] = p_product[41]; l_tmp[10] = p_product[42]; l_tmp[11] = p_product[43];
+    l_tmp[12] = l_tmp[13] = l_tmp[14] = l_tmp[15] = 0;
+    l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = 0;
+    l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
+    l_tmp[24] = p_product[56]; l_tmp[25] = p_product[57]; l_tmp[26] = p_product[58]; l_tmp[27] = p_product[59];
+    l_tmp[28] = p_product[60]; l_tmp[29] = p_product[61]; l_tmp[30] = p_product[62]; l_tmp[31] = p_product[63];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s4 */
+    l_tmp[0] = p_product[36]; l_tmp[1] = p_product[37]; l_tmp[2] = p_product[38]; l_tmp[3] = p_product[39];
+    l_tmp[4] = p_product[40]; l_tmp[5] = p_product[41]; l_tmp[6] = p_product[42]; l_tmp[7] = p_product[43];
+    l_tmp[8] = p_product[44]; l_tmp[9] = p_product[45]; l_tmp[10] = p_product[46]; l_tmp[11] = p_product[47];
+    l_tmp[12] = p_product[52]; l_tmp[13] = p_product[53]; l_tmp[14] = p_product[54]; l_tmp[15] = p_product[55];
+    l_tmp[16] = p_product[56]; l_tmp[17] = p_product[57]; l_tmp[18] = p_product[58]; l_tmp[19] = p_product[59];
+    l_tmp[20] = p_product[60]; l_tmp[21] = p_product[61]; l_tmp[22] = p_product[62]; l_tmp[23] = p_product[63];
+    l_tmp[24] = p_product[52]; l_tmp[25] = p_product[53]; l_tmp[26] = p_product[54]; l_tmp[27] = p_product[55];
+    l_tmp[28] = p_product[32]; l_tmp[29] = p_product[33]; l_tmp[30] = p_product[34]; l_tmp[31] = p_product[35];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* d1 */
+    l_tmp[0] = p_product[44]; l_tmp[1] = p_product[45]; l_tmp[2] = p_product[46]; l_tmp[3] = p_product[47];
+    l_tmp[4] = p_product[48]; l_tmp[5] = p_product[49]; l_tmp[6] = p_product[50]; l_tmp[7] = p_product[51];
+    l_tmp[8] = p_product[52]; l_tmp[9] = p_product[53]; l_tmp[10] = p_product[54]; l_tmp[11] = p_product[55];
+    l_tmp[12] = l_tmp[13] = l_tmp[14] = l_tmp[15] = 0;
+    l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = 0;
+    l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
+    l_tmp[24] = p_product[32]; l_tmp[25] = p_product[33]; l_tmp[26] = p_product[34]; l_tmp[27] = p_product[35];
+    l_tmp[28] = p_product[40]; l_tmp[29] = p_product[41]; l_tmp[30] = p_product[42]; l_tmp[31] = p_product[43];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d2 */
+    l_tmp[0] = p_product[48]; l_tmp[1] = p_product[49]; l_tmp[2] = p_product[50]; l_tmp[3] = p_product[51];
+    l_tmp[4] = p_product[52]; l_tmp[5] = p_product[53]; l_tmp[6] = p_product[54]; l_tmp[7] = p_product[55];
+    l_tmp[8] = p_product[56]; l_tmp[9] = p_product[57]; l_tmp[10] = p_product[58]; l_tmp[11] = p_product[59];
+    l_tmp[12] = p_product[60]; l_tmp[13] = p_product[61]; l_tmp[14] = p_product[62]; l_tmp[15] = p_product[63];
+    l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = 0;
+    l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
+    l_tmp[24] = p_product[36]; l_tmp[25] = p_product[37]; l_tmp[26] = p_product[38]; l_tmp[27] = p_product[39];
+    l_tmp[28] = p_product[44]; l_tmp[29] = p_product[45]; l_tmp[30] = p_product[46]; l_tmp[31] = p_product[47];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d3 */
+    l_tmp[0] = p_product[52]; l_tmp[1] = p_product[53]; l_tmp[2] = p_product[54]; l_tmp[3] = p_product[55];
+    l_tmp[4] = p_product[56]; l_tmp[5] = p_product[57]; l_tmp[6] = p_product[58]; l_tmp[7] = p_product[59];
+    l_tmp[8] = p_product[60]; l_tmp[9] = p_product[61]; l_tmp[10] = p_product[62]; l_tmp[11] = p_product[63];
+    l_tmp[12] = p_product[32]; l_tmp[13] = p_product[33]; l_tmp[14] = p_product[34]; l_tmp[15] = p_product[35];
+    l_tmp[16] = p_product[36]; l_tmp[17] = p_product[37]; l_tmp[18] = p_product[38]; l_tmp[19] = p_product[39];
+    l_tmp[20] = p_product[40]; l_tmp[21] = p_product[41]; l_tmp[22] = p_product[42]; l_tmp[23] = p_product[43];
+    l_tmp[24] = l_tmp[25] = l_tmp[26] = l_tmp[27] = 0;
+    l_tmp[28] = p_product[48]; l_tmp[29] = p_product[49]; l_tmp[30] = p_product[50]; l_tmp[31] = p_product[51];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d4 */
+    l_tmp[0] = p_product[56]; l_tmp[1] = p_product[57]; l_tmp[2] = p_product[58]; l_tmp[3] = p_product[59];
+    l_tmp[4] = p_product[60]; l_tmp[5] = p_product[61]; l_tmp[6] = p_product[62]; l_tmp[7] = p_product[63];
+    l_tmp[8] = l_tmp[9] = l_tmp[10] = l_tmp[11] = 0;
+    l_tmp[12] = p_product[36]; l_tmp[13] = p_product[37]; l_tmp[14] = p_product[38]; l_tmp[15] = p_product[39];
+    l_tmp[16] = p_product[40]; l_tmp[17] = p_product[41]; l_tmp[18] = p_product[42]; l_tmp[19] = p_product[43];
+    l_tmp[20] = p_product[44]; l_tmp[21] = p_product[45]; l_tmp[22] = p_product[46]; l_tmp[23] = p_product[47];
+    l_tmp[24] = l_tmp[25] = l_tmp[26] = l_tmp[27] = 0;
+    l_tmp[28] = p_product[52]; l_tmp[29] = p_product[53]; l_tmp[30] = p_product[54]; l_tmp[31] = p_product[55];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    if(l_carry < 0)
+    {
+        do
+        {
+            l_carry += vli_add(p_result, p_result, curve_p);
+        } while(l_carry < 0);
+    }
+    else
+    {
+        while(l_carry || vli_cmp(curve_p, p_result) != 1)
+        {
+            l_carry -= vli_sub(p_result, p_result, curve_p);
+        }
+    }
+}
+#elif uECC_WORD_SIZE == 4
+static void vli_mmod_fast(uint32_t *RESTRICT p_result, uint32_t *RESTRICT p_product)
+{
+    uint32_t l_tmp[uECC_WORDS];
+    int l_carry;
+
+    /* t */
+    vli_set(p_result, p_product);
+
+    /* s1 */
+    l_tmp[0] = l_tmp[1] = l_tmp[2] = 0;
+    l_tmp[3] = p_product[11];
+    l_tmp[4] = p_product[12];
+    l_tmp[5] = p_product[13];
+    l_tmp[6] = p_product[14];
+    l_tmp[7] = p_product[15];
+    l_carry = vli_add(l_tmp, l_tmp, l_tmp);
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s2 */
+    l_tmp[3] = p_product[12];
+    l_tmp[4] = p_product[13];
+    l_tmp[5] = p_product[14];
+    l_tmp[6] = p_product[15];
+    l_tmp[7] = 0;
+    l_carry += vli_add(l_tmp, l_tmp, l_tmp);
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s3 */
+    l_tmp[0] = p_product[8];
+    l_tmp[1] = p_product[9];
+    l_tmp[2] = p_product[10];
+    l_tmp[3] = l_tmp[4] = l_tmp[5] = 0;
+    l_tmp[6] = p_product[14];
+    l_tmp[7] = p_product[15];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s4 */
+    l_tmp[0] = p_product[9];
+    l_tmp[1] = p_product[10];
+    l_tmp[2] = p_product[11];
+    l_tmp[3] = p_product[13];
+    l_tmp[4] = p_product[14];
+    l_tmp[5] = p_product[15];
+    l_tmp[6] = p_product[13];
+    l_tmp[7] = p_product[8];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* d1 */
+    l_tmp[0] = p_product[11];
+    l_tmp[1] = p_product[12];
+    l_tmp[2] = p_product[13];
+    l_tmp[3] = l_tmp[4] = l_tmp[5] = 0;
+    l_tmp[6] = p_product[8];
+    l_tmp[7] = p_product[10];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d2 */
+    l_tmp[0] = p_product[12];
+    l_tmp[1] = p_product[13];
+    l_tmp[2] = p_product[14];
+    l_tmp[3] = p_product[15];
+    l_tmp[4] = l_tmp[5] = 0;
+    l_tmp[6] = p_product[9];
+    l_tmp[7] = p_product[11];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d3 */
+    l_tmp[0] = p_product[13];
+    l_tmp[1] = p_product[14];
+    l_tmp[2] = p_product[15];
+    l_tmp[3] = p_product[8];
+    l_tmp[4] = p_product[9];
+    l_tmp[5] = p_product[10];
+    l_tmp[6] = 0;
+    l_tmp[7] = p_product[12];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d4 */
+    l_tmp[0] = p_product[14];
+    l_tmp[1] = p_product[15];
+    l_tmp[2] = 0;
+    l_tmp[3] = p_product[9];
+    l_tmp[4] = p_product[10];
+    l_tmp[5] = p_product[11];
+    l_tmp[6] = 0;
+    l_tmp[7] = p_product[13];
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    if(l_carry < 0)
+    {
+        do
+        {
+            l_carry += vli_add(p_result, p_result, curve_p);
+        } while(l_carry < 0);
+    }
+    else
+    {
+        while(l_carry || vli_cmp(curve_p, p_result) != 1)
+        {
+            l_carry -= vli_sub(p_result, p_result, curve_p);
+        }
+    }
+}
+#else
+static void vli_mmod_fast(uint64_t *RESTRICT p_result, uint64_t *RESTRICT p_product)
+{
+    uint64_t l_tmp[uECC_WORDS];
+    int l_carry;
+
+    /* t */
+    vli_set(p_result, p_product);
+
+    /* s1 */
+    l_tmp[0] = 0;
+    l_tmp[1] = p_product[5] & 0xffffffff00000000ull;
+    l_tmp[2] = p_product[6];
+    l_tmp[3] = p_product[7];
+    l_carry = vli_add(l_tmp, l_tmp, l_tmp);
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s2 */
+    l_tmp[1] = p_product[6] << 32;
+    l_tmp[2] = (p_product[6] >> 32) | (p_product[7] << 32);
+    l_tmp[3] = p_product[7] >> 32;
+    l_carry += vli_add(l_tmp, l_tmp, l_tmp);
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s3 */
+    l_tmp[0] = p_product[4];
+    l_tmp[1] = p_product[5] & 0xffffffff;
+    l_tmp[2] = 0;
+    l_tmp[3] = p_product[7];
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* s4 */
+    l_tmp[0] = (p_product[4] >> 32) | (p_product[5] << 32);
+    l_tmp[1] = (p_product[5] >> 32) | (p_product[6] & 0xffffffff00000000ull);
+    l_tmp[2] = p_product[7];
+    l_tmp[3] = (p_product[6] >> 32) | (p_product[4] << 32);
+    l_carry += vli_add(p_result, p_result, l_tmp);
+
+    /* d1 */
+    l_tmp[0] = (p_product[5] >> 32) | (p_product[6] << 32);
+    l_tmp[1] = (p_product[6] >> 32);
+    l_tmp[2] = 0;
+    l_tmp[3] = (p_product[4] & 0xffffffff) | (p_product[5] << 32);
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d2 */
+    l_tmp[0] = p_product[6];
+    l_tmp[1] = p_product[7];
+    l_tmp[2] = 0;
+    l_tmp[3] = (p_product[4] >> 32) | (p_product[5] & 0xffffffff00000000ull);
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d3 */
+    l_tmp[0] = (p_product[6] >> 32) | (p_product[7] << 32);
+    l_tmp[1] = (p_product[7] >> 32) | (p_product[4] << 32);
+    l_tmp[2] = (p_product[4] >> 32) | (p_product[5] << 32);
+    l_tmp[3] = (p_product[6] << 32);
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    /* d4 */
+    l_tmp[0] = p_product[7];
+    l_tmp[1] = p_product[4] & 0xffffffff00000000ull;
+    l_tmp[2] = p_product[5];
+    l_tmp[3] = p_product[6] & 0xffffffff00000000ull;
+    l_carry -= vli_sub(p_result, p_result, l_tmp);
+
+    if(l_carry < 0)
+    {
+        do
+        {
+            l_carry += vli_add(p_result, p_result, curve_p);
+        } while(l_carry < 0);
+    }
+    else
+    {
+        while(l_carry || vli_cmp(curve_p, p_result) != 1)
+        {
+            l_carry -= vli_sub(p_result, p_result, curve_p);
+        }
+    }
+}
+#endif /* uECC_WORD_SIZE */
+
+#elif uECC_CURVE == uECC_secp256k1
+
+#if uECC_WORD_SIZE == 1
+static void omega_mult(uint8_t * RESTRICT p_result, uint8_t * RESTRICT p_right)
+{
+    /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
+    uECC_word_t r0 = 0;
+    uECC_word_t r1 = 0;
+    uECC_word_t r2 = 0;
+
+    wordcount_t k;
+
+    /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
+    muladd(0xD1, p_right[0], &r0, &r1, &r2);
+    p_result[0] = r0;
+    r0 = r1;
+    r1 = r2;
+    /* r2 is still 0 */
+
+    for(k = 1; k < uECC_WORDS; ++k)
+    {
+        muladd(0x03, p_right[k-1], &r0, &r1, &r2);
+        muladd(0xD1, p_right[k], &r0, &r1, &r2);
+        p_result[k] = r0;
+        r0 = r1;
+        r1 = r2;
+        r2 = 0;
+    }
+
+    muladd(0x03, p_right[uECC_WORDS-1], &r0, &r1, &r2);
+    p_result[uECC_WORDS] = r0;
+    p_result[uECC_WORDS + 1] = r1;
+
+    p_result[4 + uECC_WORDS] = vli_add(p_result + 4, p_result + 4, p_right); /* add the 2^32 multiple */
+}
+#elif uECC_WORD_SIZE == 4
+static void omega_mult(uint32_t * RESTRICT p_result, uint32_t * RESTRICT p_right)
+{
+    /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
+    uint32_t l_carry = 0;
+    wordcount_t k;
+
+    for(k = 0; k < uECC_WORDS; ++k)
+    {
+        uint64_t p = (uint64_t)0x3D1 * p_right[k] + l_carry;
+        p_result[k] = (p & 0xffffffff);
+        l_carry = p >> 32;
+    }
+    p_result[uECC_WORDS] = l_carry;
+
+    p_result[1 + uECC_WORDS] = vli_add(p_result + 1, p_result + 1, p_right); /* add the 2^32 multiple */
+}
+#else
+static void omega_mult(uint64_t * RESTRICT p_result, uint64_t * RESTRICT p_right)
+{
+    uECC_word_t r0 = 0;
+    uECC_word_t r1 = 0;
+    uECC_word_t r2 = 0;
+
+    wordcount_t k;
+
+    /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
+    for(k = 0; k < uECC_WORDS; ++k)
+    {
+        muladd(0x1000003D1ull, p_right[k], &r0, &r1, &r2);
+        p_result[k] = r0;
+        r0 = r1;
+        r1 = r2;
+        r2 = 0;
+    }
+
+    p_result[uECC_WORDS] = r0;
+}
+#endif /* uECC_WORD_SIZE */
+
+#endif /* uECC_CURVE */
+#endif /* !asm_mmod_fast */
+
+/* Computes p_result = (p_left * p_right) % curve_p. */
+static void vli_modMult_fast(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_product[2 * uECC_WORDS];
+    vli_mult(l_product, p_left, p_right);
+    vli_mmod_fast(p_result, l_product);
+}
+
+#if uECC_SQUARE_FUNC
+
+/* Computes p_result = p_left^2 % curve_p. */
+static void vli_modSquare_fast(uECC_word_t *p_result, uECC_word_t *p_left)
+{
+    uECC_word_t l_product[2 * uECC_WORDS];
+    vli_square(l_product, p_left);
+    vli_mmod_fast(p_result, l_product);
+}
+
+#else /* uECC_SQUARE_FUNC */
+
+#define vli_modSquare_fast(result, left) vli_modMult_fast((result), (left), (left))
+
+#endif /* uECC_SQUARE_FUNC */
+
+
+#define EVEN(vli) (!(vli[0] & 1))
+/* Computes p_result = (1 / p_input) % p_mod. All VLIs are the same size.
+   See "From Euclid's GCD to Montgomery Multiplication to the Great Divide"
+   https://labs.oracle.com/techrep/2001/smli_tr-2001-95.pdf */
+#if !asm_modInv
+static void vli_modInv(uECC_word_t *p_result, uECC_word_t *p_input, uECC_word_t *p_mod)
+{
+    uECC_word_t a[uECC_WORDS], b[uECC_WORDS], u[uECC_WORDS], v[uECC_WORDS];
+    uECC_word_t l_carry;
+    cmpresult_t l_cmpResult;
+
+    if(vli_isZero(p_input))
+    {
+        vli_clear(p_result);
+        return;
+    }
+
+    vli_set(a, p_input);
+    vli_set(b, p_mod);
+    vli_clear(u);
+    u[0] = 1;
+    vli_clear(v);
+    while((l_cmpResult = vli_cmp(a, b)) != 0)
+    {
+        l_carry = 0;
+        if(EVEN(a))
+        {
+            vli_rshift1(a);
+            if(!EVEN(u))
+            {
+                l_carry = vli_add(u, u, p_mod);
+            }
+            vli_rshift1(u);
+            if(l_carry)
+            {
+                u[uECC_WORDS-1] |= HIGH_BIT_SET;
+            }
+        }
+        else if(EVEN(b))
+        {
+            vli_rshift1(b);
+            if(!EVEN(v))
+            {
+                l_carry = vli_add(v, v, p_mod);
+            }
+            vli_rshift1(v);
+            if(l_carry)
+            {
+                v[uECC_WORDS-1] |= HIGH_BIT_SET;
+            }
+        }
+        else if(l_cmpResult > 0)
+        {
+            vli_sub(a, a, b);
+            vli_rshift1(a);
+            if(vli_cmp(u, v) < 0)
+            {
+                vli_add(u, u, p_mod);
+            }
+            vli_sub(u, u, v);
+            if(!EVEN(u))
+            {
+                l_carry = vli_add(u, u, p_mod);
+            }
+            vli_rshift1(u);
+            if(l_carry)
+            {
+                u[uECC_WORDS-1] |= HIGH_BIT_SET;
+            }
+        }
+        else
+        {
+            vli_sub(b, b, a);
+            vli_rshift1(b);
+            if(vli_cmp(v, u) < 0)
+            {
+                vli_add(v, v, p_mod);
+            }
+            vli_sub(v, v, u);
+            if(!EVEN(v))
+            {
+                l_carry = vli_add(v, v, p_mod);
+            }
+            vli_rshift1(v);
+            if(l_carry)
+            {
+                v[uECC_WORDS-1] |= HIGH_BIT_SET;
+            }
+        }
+    }
+
+    vli_set(p_result, u);
+}
+#endif /* !asm_modInv */
+
+/* ------ Point operations ------ */
+
+/* Returns 1 if p_point is the point at infinity, 0 otherwise. */
+static cmpresult_t EccPoint_isZero(EccPoint *p_point)
+{
+    return (vli_isZero(p_point->x) && vli_isZero(p_point->y));
+}
+
+/* Point multiplication algorithm using Montgomery's ladder with co-Z coordinates.
+From http://eprint.iacr.org/2011/338.pdf
+*/
+
+/* Double in place */
+#if (uECC_CURVE == uECC_secp256k1)
+static void EccPoint_double_jacobian(uECC_word_t * RESTRICT X1, uECC_word_t * RESTRICT Y1, uECC_word_t * RESTRICT Z1)
+{
+    /* t1 = X, t2 = Y, t3 = Z */
+    uECC_word_t t4[uECC_WORDS];
+    uECC_word_t t5[uECC_WORDS];
+
+    if(vli_isZero(Z1))
+    {
+        return;
+    }
+
+    vli_modSquare_fast(t5, Y1);   /* t5 = y1^2 */
+    vli_modMult_fast(t4, X1, t5); /* t4 = x1*y1^2 = A */
+    vli_modSquare_fast(X1, X1);   /* t1 = x1^2 */
+    vli_modSquare_fast(t5, t5);   /* t5 = y1^4 */
+    vli_modMult_fast(Z1, Y1, Z1); /* t3 = y1*z1 = z3 */
+
+    vli_modAdd(Y1, X1, X1, curve_p); /* t2 = 2*x1^2 */
+    vli_modAdd(Y1, Y1, X1, curve_p); /* t2 = 3*x1^2 */
+    if(vli_testBit(Y1, 0))
+    {
+        uECC_word_t l_carry = vli_add(Y1, Y1, curve_p);
+        vli_rshift1(Y1);
+        Y1[uECC_WORDS-1] |= l_carry << (uECC_WORD_BITS - 1);
+    }
+    else
+    {
+        vli_rshift1(Y1);
+    }
+    /* t2 = 3/2*(x1^2) = B */
+
+    vli_modSquare_fast(X1, Y1);   /* t1 = B^2 */
+    vli_modSub(X1, X1, t4, curve_p); /* t1 = B^2 - A */
+    vli_modSub(X1, X1, t4, curve_p); /* t1 = B^2 - 2A = x3 */
+
+    vli_modSub(t4, t4, X1, curve_p); /* t4 = A - x3 */
+    vli_modMult_fast(Y1, Y1, t4);    /* t2 = B * (A - x3) */
+    vli_modSub(Y1, Y1, t5, curve_p); /* t2 = B * (A - x3) - y1^4 = y3 */
+}
+#else
+static void EccPoint_double_jacobian(uECC_word_t * RESTRICT X1, uECC_word_t * RESTRICT Y1, uECC_word_t * RESTRICT Z1)
+{
+    /* t1 = X, t2 = Y, t3 = Z */
+    uECC_word_t t4[uECC_WORDS];
+    uECC_word_t t5[uECC_WORDS];
+
+    if(vli_isZero(Z1))
+    {
+        return;
+    }
+
+    vli_modSquare_fast(t4, Y1);   /* t4 = y1^2 */
+    vli_modMult_fast(t5, X1, t4); /* t5 = x1*y1^2 = A */
+    vli_modSquare_fast(t4, t4);   /* t4 = y1^4 */
+    vli_modMult_fast(Y1, Y1, Z1); /* t2 = y1*z1 = z3 */
+    vli_modSquare_fast(Z1, Z1);   /* t3 = z1^2 */
+
+    vli_modAdd(X1, X1, Z1, curve_p); /* t1 = x1 + z1^2 */
+    vli_modAdd(Z1, Z1, Z1, curve_p); /* t3 = 2*z1^2 */
+    vli_modSub_fast(Z1, X1, Z1); /* t3 = x1 - z1^2 */
+    vli_modMult_fast(X1, X1, Z1);    /* t1 = x1^2 - z1^4 */
+
+    vli_modAdd(Z1, X1, X1, curve_p); /* t3 = 2*(x1^2 - z1^4) */
+    vli_modAdd(X1, X1, Z1, curve_p); /* t1 = 3*(x1^2 - z1^4) */
+    if(vli_testBit(X1, 0))
+    {
+        uECC_word_t l_carry = vli_add(X1, X1, curve_p);
+        vli_rshift1(X1);
+        X1[uECC_WORDS-1] |= l_carry << (uECC_WORD_BITS - 1);
+    }
+    else
+    {
+        vli_rshift1(X1);
+    }
+    /* t1 = 3/2*(x1^2 - z1^4) = B */
+
+    vli_modSquare_fast(Z1, X1);      /* t3 = B^2 */
+    vli_modSub_fast(Z1, Z1, t5); /* t3 = B^2 - A */
+    vli_modSub_fast(Z1, Z1, t5); /* t3 = B^2 - 2A = x3 */
+    vli_modSub_fast(t5, t5, Z1); /* t5 = A - x3 */
+    vli_modMult_fast(X1, X1, t5);    /* t1 = B * (A - x3) */
+    vli_modSub_fast(t4, X1, t4); /* t4 = B * (A - x3) - y1^4 = y3 */
+
+    vli_set(X1, Z1);
+    vli_set(Z1, Y1);
+    vli_set(Y1, t4);
+}
+#endif
+
+/* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
+static void apply_z(uECC_word_t * RESTRICT X1, uECC_word_t * RESTRICT Y1, uECC_word_t * RESTRICT Z)
+{
+    uECC_word_t t1[uECC_WORDS];
+
+    vli_modSquare_fast(t1, Z);    /* z^2 */
+    vli_modMult_fast(X1, X1, t1); /* x1 * z^2 */
+    vli_modMult_fast(t1, t1, Z);  /* z^3 */
+    vli_modMult_fast(Y1, Y1, t1); /* y1 * z^3 */
+}
+
+/* P = (x1, y1) => 2P, (x2, y2) => P' */
+static void XYcZ_initial_double(uECC_word_t * RESTRICT X1, uECC_word_t * RESTRICT Y1,
+    uECC_word_t * RESTRICT X2, uECC_word_t * RESTRICT Y2, const uECC_word_t * RESTRICT p_initialZ)
+{
+    uECC_word_t z[uECC_WORDS];
+
+    vli_set(X2, X1);
+    vli_set(Y2, Y1);
+
+    vli_clear(z);
+    z[0] = 1;
+    if(p_initialZ)
+    {
+        vli_set(z, p_initialZ);
+    }
+
+    apply_z(X1, Y1, z);
+
+    EccPoint_double_jacobian(X1, Y1, z);
+
+    apply_z(X2, Y2, z);
+}
+
+/* Input P = (x1, y1, Z), Q = (x2, y2, Z)
+   Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
+   or P => P', Q => P + Q
+*/
+static void XYcZ_add(uECC_word_t * RESTRICT X1, uECC_word_t * RESTRICT Y1, uECC_word_t * RESTRICT X2, uECC_word_t * RESTRICT Y2)
+{
+    /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+    uECC_word_t t5[uECC_WORDS];
+
+    vli_modSub_fast(t5, X2, X1); /* t5 = x2 - x1 */
+    vli_modSquare_fast(t5, t5);      /* t5 = (x2 - x1)^2 = A */
+    vli_modMult_fast(X1, X1, t5);    /* t1 = x1*A = B */
+    vli_modMult_fast(X2, X2, t5);    /* t3 = x2*A = C */
+    vli_modSub_fast(Y2, Y2, Y1); /* t4 = y2 - y1 */
+    vli_modSquare_fast(t5, Y2);      /* t5 = (y2 - y1)^2 = D */
+
+    vli_modSub_fast(t5, t5, X1); /* t5 = D - B */
+    vli_modSub_fast(t5, t5, X2); /* t5 = D - B - C = x3 */
+    vli_modSub_fast(X2, X2, X1); /* t3 = C - B */
+    vli_modMult_fast(Y1, Y1, X2);    /* t2 = y1*(C - B) */
+    vli_modSub_fast(X2, X1, t5); /* t3 = B - x3 */
+    vli_modMult_fast(Y2, Y2, X2);    /* t4 = (y2 - y1)*(B - x3) */
+    vli_modSub_fast(Y2, Y2, Y1); /* t4 = y3 */
+
+    vli_set(X2, t5);
+}
+
+/* Input P = (x1, y1, Z), Q = (x2, y2, Z)
+   Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
+   or P => P - Q, Q => P + Q
+*/
+static void XYcZ_addC(uECC_word_t * RESTRICT X1, uECC_word_t * RESTRICT Y1, uECC_word_t * RESTRICT X2, uECC_word_t * RESTRICT Y2)
+{
+    /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+    uECC_word_t t5[uECC_WORDS];
+    uECC_word_t t6[uECC_WORDS];
+    uECC_word_t t7[uECC_WORDS];
+
+    vli_modSub_fast(t5, X2, X1); /* t5 = x2 - x1 */
+    vli_modSquare_fast(t5, t5);      /* t5 = (x2 - x1)^2 = A */
+    vli_modMult_fast(X1, X1, t5);    /* t1 = x1*A = B */
+    vli_modMult_fast(X2, X2, t5);    /* t3 = x2*A = C */
+    vli_modAdd(t5, Y2, Y1, curve_p); /* t4 = y2 + y1 */
+    vli_modSub_fast(Y2, Y2, Y1); /* t4 = y2 - y1 */
+
+    vli_modSub_fast(t6, X2, X1); /* t6 = C - B */
+    vli_modMult_fast(Y1, Y1, t6);    /* t2 = y1 * (C - B) */
+    vli_modAdd(t6, X1, X2, curve_p); /* t6 = B + C */
+    vli_modSquare_fast(X2, Y2);      /* t3 = (y2 - y1)^2 */
+    vli_modSub_fast(X2, X2, t6); /* t3 = x3 */
+
+    vli_modSub_fast(t7, X1, X2); /* t7 = B - x3 */
+    vli_modMult_fast(Y2, Y2, t7);    /* t4 = (y2 - y1)*(B - x3) */
+    vli_modSub_fast(Y2, Y2, Y1); /* t4 = y3 */
+
+    vli_modSquare_fast(t7, t5);      /* t7 = (y2 + y1)^2 = F */
+    vli_modSub_fast(t7, t7, t6); /* t7 = x3' */
+    vli_modSub_fast(t6, t7, X1); /* t6 = x3' - B */
+    vli_modMult_fast(t6, t6, t5);    /* t6 = (y2 + y1)*(x3' - B) */
+    vli_modSub_fast(Y1, t6, Y1); /* t2 = y3' */
+
+    vli_set(X1, t7);
+}
+
+static void EccPoint_mult(EccPoint * RESTRICT p_result, EccPoint * RESTRICT p_point,
+    const uECC_word_t * RESTRICT p_scalar, const uECC_word_t * RESTRICT p_initialZ, bitcount_t p_numBits)
+{
+    /* R0 and R1 */
+    uECC_word_t Rx[2][uECC_WORDS];
+    uECC_word_t Ry[2][uECC_WORDS];
+    uECC_word_t z[uECC_WORDS];
+
+    bitcount_t i;
+    uECC_word_t nb;
+
+    vli_set(Rx[1], p_point->x);
+    vli_set(Ry[1], p_point->y);
+
+    XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], p_initialZ);
+
+    for(i = p_numBits - 2; i > 0; --i)
+    {
+        nb = !vli_testBit(p_scalar, i);
+        XYcZ_addC(Rx[1-nb], Ry[1-nb], Rx[nb], Ry[nb]);
+        XYcZ_add(Rx[nb], Ry[nb], Rx[1-nb], Ry[1-nb]);
+    }
+
+    nb = !vli_testBit(p_scalar, 0);
+    XYcZ_addC(Rx[1-nb], Ry[1-nb], Rx[nb], Ry[nb]);
+
+    /* Find final 1/Z value. */
+    vli_modSub_fast(z, Rx[1], Rx[0]); /* X1 - X0 */
+    vli_modMult_fast(z, z, Ry[1-nb]);     /* Yb * (X1 - X0) */
+    vli_modMult_fast(z, z, p_point->x);   /* xP * Yb * (X1 - X0) */
+    vli_modInv(z, z, curve_p);            /* 1 / (xP * Yb * (X1 - X0)) */
+    vli_modMult_fast(z, z, p_point->y);   /* yP / (xP * Yb * (X1 - X0)) */
+    vli_modMult_fast(z, z, Rx[1-nb]);     /* Xb * yP / (xP * Yb * (X1 - X0)) */
+    /* End 1/Z calculation */
+
+    XYcZ_add(Rx[nb], Ry[nb], Rx[1-nb], Ry[1-nb]);
+
+    apply_z(Rx[0], Ry[0], z);
+
+    vli_set(p_result->x, Rx[0]);
+    vli_set(p_result->y, Ry[0]);
+}
+
+/* Compute a = sqrt(a) (mod curve_p). */
+static void mod_sqrt(uECC_word_t *a)
+{
+    bitcount_t i;
+    uECC_word_t p1[uECC_WORDS] = {1};
+    uECC_word_t l_result[uECC_WORDS] = {1};
+
+    /* Since curve_p == 3 (mod 4) for all supported curves, we can
+       compute sqrt(a) = a^((curve_p + 1) / 4) (mod curve_p). */
+    vli_add(p1, curve_p, p1); /* p1 = curve_p + 1 */
+    for(i = vli_numBits(p1, uECC_WORDS) - 1; i > 1; --i)
+    {
+        vli_modSquare_fast(l_result, l_result);
+        if(vli_testBit(p1, i))
+        {
+            vli_modMult_fast(l_result, l_result, a);
+        }
+    }
+    vli_set(a, l_result);
+}
+
+#if uECC_WORD_SIZE == 1
+
+static void vli_nativeToBytes(uint8_t * RESTRICT p_dest, const uint8_t * RESTRICT p_src)
+{
+    uint8_t i;
+    for(i=0; i<uECC_BYTES; ++i)
+    {
+        p_dest[i] = p_src[(uECC_BYTES - 1) - i];
+    }
+}
+
+#define vli_bytesToNative(dest, src) vli_nativeToBytes((dest), (src))
+
+#elif uECC_WORD_SIZE == 4
+
+static void vli_nativeToBytes(uint8_t *p_bytes, const uint32_t *p_native)
+{
+    unsigned i;
+    for(i=0; i<uECC_WORDS; ++i)
+    {
+        uint8_t *p_digit = p_bytes + 4 * (uECC_WORDS - 1 - i);
+        p_digit[0] = p_native[i] >> 24;
+        p_digit[1] = p_native[i] >> 16;
+        p_digit[2] = p_native[i] >> 8;
+        p_digit[3] = p_native[i];
+    }
+}
+
+static void vli_bytesToNative(uint32_t *p_native, const uint8_t *p_bytes)
+{
+    unsigned i;
+    for(i=0; i<uECC_WORDS; ++i)
+    {
+        const uint8_t *p_digit = p_bytes + 4 * (uECC_WORDS - 1 - i);
+        p_native[i] = ((uint32_t)p_digit[0] << 24) | ((uint32_t)p_digit[1] << 16) | ((uint32_t)p_digit[2] << 8) | (uint32_t)p_digit[3];
+    }
+}
+
+#else
+
+static void vli_nativeToBytes(uint8_t *p_bytes, const uint64_t *p_native)
+{
+    unsigned i;
+    for(i=0; i<uECC_WORDS; ++i)
+    {
+        uint8_t *p_digit = p_bytes + 8 * (uECC_WORDS - 1 - i);
+        p_digit[0] = p_native[i] >> 56;
+        p_digit[1] = p_native[i] >> 48;
+        p_digit[2] = p_native[i] >> 40;
+        p_digit[3] = p_native[i] >> 32;
+        p_digit[4] = p_native[i] >> 24;
+        p_digit[5] = p_native[i] >> 16;
+        p_digit[6] = p_native[i] >> 8;
+        p_digit[7] = p_native[i];
+    }
+}
+
+static void vli_bytesToNative(uint64_t *p_native, const uint8_t *p_bytes)
+{
+    unsigned i;
+    for(i=0; i<uECC_WORDS; ++i)
+    {
+        const uint8_t *p_digit = p_bytes + 8 * (uECC_WORDS - 1 - i);
+        p_native[i] = ((uint64_t)p_digit[0] << 56) | ((uint64_t)p_digit[1] << 48) | ((uint64_t)p_digit[2] << 40) | ((uint64_t)p_digit[3] << 32) |
+            ((uint64_t)p_digit[4] << 24) | ((uint64_t)p_digit[5] << 16) | ((uint64_t)p_digit[6] << 8) | (uint64_t)p_digit[7];
+    }
+}
+
+#endif /* uECC_WORD_SIZE */
+
+int uECC_make_key(uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_privateKey[uECC_BYTES])
+{
+    EccPoint l_public;
+    uECC_word_t l_private[uECC_WORDS];
+    uECC_word_t l_tries = 0;
+
+    do
+    {
+    repeat:
+        if(!g_rng((uint8_t *)l_private, sizeof(l_private)) || (l_tries++ >= MAX_TRIES))
+        {
+            return 0;
+        }
+        if(vli_isZero(l_private))
+        {
+            goto repeat;
+        }
+
+        /* Make sure the private key is in the range [1, n-1]. */
+    #if uECC_CURVE != uECC_secp160r1
+        if(vli_cmp(curve_n, l_private) != 1)
+        {
+            goto repeat;
+        }
+    #endif
+
+        EccPoint_mult(&l_public, &curve_G, l_private, 0, vli_numBits(l_private, uECC_WORDS));
+    } while(EccPoint_isZero(&l_public));
+
+    vli_nativeToBytes(p_privateKey, l_private);
+    vli_nativeToBytes(p_publicKey, l_public.x);
+    vli_nativeToBytes(p_publicKey + uECC_BYTES, l_public.y);
+    return 1;
+}
+
+int uECC_shared_secret(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_privateKey[uECC_BYTES], uint8_t p_secret[uECC_BYTES])
+{
+    EccPoint l_public;
+    uECC_word_t l_private[uECC_WORDS];
+    uECC_word_t l_random[uECC_WORDS];
+
+    g_rng((uint8_t *)l_random, sizeof(l_random));
+
+    vli_bytesToNative(l_private, p_privateKey);
+    vli_bytesToNative(l_public.x, p_publicKey);
+    vli_bytesToNative(l_public.y, p_publicKey + uECC_BYTES);
+
+    EccPoint l_product;
+    EccPoint_mult(&l_product, &l_public, l_private, (vli_isZero(l_random) ? 0: l_random), vli_numBits(l_private, uECC_WORDS));
+
+    vli_nativeToBytes(p_secret, l_product.x);
+
+    return !EccPoint_isZero(&l_product);
+}
+
+void uECC_compress(const uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_compressed[uECC_BYTES+1])
+{
+    wordcount_t i;
+    for(i=0; i<uECC_BYTES; ++i)
+    {
+        p_compressed[i+1] = p_publicKey[i];
+    }
+    p_compressed[0] = 2 + (p_publicKey[uECC_BYTES * 2 - 1] & 0x01);
+}
+
+void uECC_decompress(const uint8_t p_compressed[uECC_BYTES+1], uint8_t p_publicKey[uECC_BYTES*2])
+{
+    EccPoint l_point;
+    vli_bytesToNative(l_point.x, p_compressed + 1);
+
+#if (uECC_CURVE == uECC_secp256k1)
+    vli_modSquare_fast(l_point.y, l_point.x); /* r = x^2 */
+    vli_modMult_fast(l_point.y, l_point.y, l_point.x); /* r = x^3 */
+    vli_modAdd(l_point.y, l_point.y, curve_b, curve_p); /* r = x^3 + b */
+#else
+    uECC_word_t _3[uECC_WORDS] = {3}; /* -a = 3 */
+
+    vli_modSquare_fast(l_point.y, l_point.x); /* y = x^2 */
+    vli_modSub_fast(l_point.y, l_point.y, _3); /* y = x^2 - 3 */
+    vli_modMult_fast(l_point.y, l_point.y, l_point.x); /* y = x^3 - 3x */
+    vli_modAdd(l_point.y, l_point.y, curve_b, curve_p); /* y = x^3 - 3x + b */
+#endif
+
+    mod_sqrt(l_point.y);
+
+    if((l_point.y[0] & 0x01) != (p_compressed[0] & 0x01))
+    {
+        vli_sub(l_point.y, curve_p, l_point.y);
+    }
+
+    vli_nativeToBytes(p_publicKey, l_point.x);
+    vli_nativeToBytes(p_publicKey + uECC_BYTES, l_point.y);
+}
+
+/* -------- ECDSA code -------- */
+
+#if (uECC_CURVE == uECC_secp160r1)
+static void vli_clear_n(uECC_word_t *p_vli)
+{
+    vli_clear(p_vli);
+    p_vli[uECC_N_WORDS - 1] = 0;
+}
+
+static uECC_word_t vli_isZero_n(const uECC_word_t *p_vli)
+{
+    if(p_vli[uECC_N_WORDS - 1])
+    {
+        return 0;
+    }
+    return vli_isZero(p_vli);
+}
+
+static void vli_set_n(uECC_word_t *p_dest, const uECC_word_t *p_src)
+{
+    vli_set(p_dest, p_src);
+    p_dest[uECC_N_WORDS-1] = p_src[uECC_N_WORDS-1];
+}
+
+static cmpresult_t vli_cmp_n(uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    if(p_left[uECC_N_WORDS-1] > p_right[uECC_N_WORDS-1])
+    {
+        return 1;
+    }
+    else if(p_left[uECC_N_WORDS-1] < p_right[uECC_N_WORDS-1])
+    {
+        return -1;
+    }
+    return vli_cmp(p_left, p_right);
+}
+
+static void vli_rshift1_n(uECC_word_t *p_vli)
+{
+    vli_rshift1(p_vli);
+    p_vli[uECC_N_WORDS-2] |= p_vli[uECC_N_WORDS-1] << (uECC_WORD_BITS - 1);
+    p_vli[uECC_N_WORDS-1] = p_vli[uECC_N_WORDS-1] >> 1;
+}
+
+static uECC_word_t vli_add_n(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_carry = vli_add(p_result, p_left, p_right);
+    uECC_word_t l_sum = p_left[uECC_N_WORDS-1] + p_right[uECC_N_WORDS-1] + l_carry;
+    if(l_sum != p_left[uECC_N_WORDS-1])
+    {
+        l_carry = (l_sum < p_left[uECC_N_WORDS-1]);
+    }
+    p_result[uECC_N_WORDS-1] = l_sum;
+    return l_carry;
+}
+
+static uECC_word_t vli_sub_n(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_borrow = vli_sub(p_result, p_left, p_right);
+    uECC_word_t l_diff = p_left[uECC_N_WORDS-1] - p_right[uECC_N_WORDS-1] - l_borrow;
+    if(l_diff != p_left[uECC_N_WORDS-1])
+    {
+        l_borrow = (l_diff > p_left[uECC_N_WORDS-1]);
+    }
+    p_result[uECC_N_WORDS-1] = l_diff;
+    return l_borrow;
+}
+
+#if !muladd_exists
+static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0, uECC_word_t *r1, uECC_word_t *r2)
+{
+    uECC_dword_t p = (uECC_dword_t)a * b;
+    uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
+    r01 += p;
+    *r2 += (r01 < p);
+    *r1 = r01 >> uECC_WORD_BITS;
+    *r0 = (uECC_word_t)r01;
+}
+#define muladd_exists 1
+#endif
+
+static void vli_mult_n(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t r0 = 0;
+    uECC_word_t r1 = 0;
+    uECC_word_t r2 = 0;
+
+    wordcount_t i, k;
+    for(k = 0; k < uECC_N_WORDS*2 - 1; ++k)
+    {
+        wordcount_t l_min = (k < uECC_N_WORDS ? 0 : (k + 1) - uECC_N_WORDS);
+        wordcount_t l_max = (k < uECC_N_WORDS ? k : uECC_N_WORDS-1);
+        for(i = l_min; i <= l_max; ++i)
+        {
+            muladd(p_left[i], p_right[k-i], &r0, &r1, &r2);
+        }
+        p_result[k] = r0;
+        r0 = r1;
+        r1 = r2;
+        r2 = 0;
+    }
+
+    p_result[uECC_N_WORDS*2 - 1] = r0;
+}
+
+static void vli_modAdd_n(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right, uECC_word_t *p_mod)
+{
+    uECC_word_t l_carry = vli_add_n(p_result, p_left, p_right);
+    if(l_carry || vli_cmp_n(p_result, p_mod) >= 0)
+    {
+        vli_sub_n(p_result, p_result, p_mod);
+    }
+}
+
+static void vli_modInv_n(uECC_word_t *p_result, uECC_word_t *p_input, uECC_word_t *p_mod)
+{
+    uECC_word_t a[uECC_N_WORDS], b[uECC_N_WORDS], u[uECC_N_WORDS], v[uECC_N_WORDS];
+    uECC_word_t l_carry;
+    cmpresult_t l_cmpResult;
+
+    if(vli_isZero_n(p_input))
+    {
+        vli_clear_n(p_result);
+        return;
+    }
+
+    vli_set_n(a, p_input);
+    vli_set_n(b, p_mod);
+    vli_clear_n(u);
+    u[0] = 1;
+    vli_clear_n(v);
+    while((l_cmpResult = vli_cmp_n(a, b)) != 0)
+    {
+        l_carry = 0;
+        if(EVEN(a))
+        {
+            vli_rshift1_n(a);
+            if(!EVEN(u)) l_carry = vli_add_n(u, u, p_mod);
+            vli_rshift1_n(u);
+            if(l_carry) u[uECC_N_WORDS-1] |= HIGH_BIT_SET;
+        }
+        else if(EVEN(b))
+        {
+            vli_rshift1_n(b);
+            if(!EVEN(v)) l_carry = vli_add_n(v, v, p_mod);
+            vli_rshift1_n(v);
+            if(l_carry) v[uECC_N_WORDS-1] |= HIGH_BIT_SET;
+        }
+        else if(l_cmpResult > 0)
+        {
+            vli_sub_n(a, a, b);
+            vli_rshift1_n(a);
+            if(vli_cmp_n(u, v) < 0) vli_add_n(u, u, p_mod);
+            vli_sub_n(u, u, v);
+            if(!EVEN(u)) l_carry = vli_add_n(u, u, p_mod);
+            vli_rshift1_n(u);
+            if(l_carry) u[uECC_N_WORDS-1] |= HIGH_BIT_SET;
+        }
+        else
+        {
+            vli_sub_n(b, b, a);
+            vli_rshift1_n(b);
+            if(vli_cmp_n(v, u) < 0) vli_add_n(v, v, p_mod);
+            vli_sub_n(v, v, u);
+            if(!EVEN(v)) l_carry = vli_add_n(v, v, p_mod);
+            vli_rshift1_n(v);
+            if(l_carry) v[uECC_N_WORDS-1] |= HIGH_BIT_SET;
+        }
+    }
+
+    vli_set_n(p_result, u);
+}
+
+static void vli2_rshift1_n(uECC_word_t *p_vli)
+{
+    vli_rshift1_n(p_vli);
+    p_vli[uECC_N_WORDS-1] |= p_vli[uECC_N_WORDS] << (uECC_WORD_BITS - 1);
+    vli_rshift1_n(p_vli + uECC_N_WORDS);
+}
+
+static uECC_word_t vli2_sub_n(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_borrow = 0;
+    wordcount_t i;
+    for(i=0; i<uECC_N_WORDS*2; ++i)
+    {
+        uECC_word_t l_diff = p_left[i] - p_right[i] - l_borrow;
+        if(l_diff != p_left[i])
+        {
+            l_borrow = (l_diff > p_left[i]);
+        }
+        p_result[i] = l_diff;
+    }
+    return l_borrow;
+}
+
+/* Computes p_result = (p_left * p_right) % curve_n. */
+static void vli_modMult_n(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_product[2 * uECC_N_WORDS];
+    uECC_word_t l_modMultiple[2 * uECC_N_WORDS];
+    uECC_word_t l_tmp[2 * uECC_N_WORDS];
+    uECC_word_t *v[2] = {l_tmp, l_product};
+
+    vli_mult_n(l_product, p_left, p_right);
+    vli_clear_n(l_modMultiple);
+    vli_set(l_modMultiple + uECC_N_WORDS + 1, curve_n);
+    vli_rshift1(l_modMultiple + uECC_N_WORDS + 1);
+    l_modMultiple[2 * uECC_N_WORDS - 1] |= HIGH_BIT_SET;
+    l_modMultiple[uECC_N_WORDS] = HIGH_BIT_SET;
+
+    bitcount_t i;
+    uECC_word_t l_index = 1;
+    for(i=0; i<=((((bitcount_t)uECC_N_WORDS) << uECC_WORD_BITS_SHIFT) + (uECC_WORD_BITS - 1)); ++i)
+    {
+        uECC_word_t l_borrow = vli2_sub_n(v[1-l_index], v[l_index], l_modMultiple);
+        l_index = !(l_index ^ l_borrow); /* Swap the index if there was no borrow */
+        vli2_rshift1_n(l_modMultiple);
+    }
+
+    vli_set_n(p_result, v[l_index]);
+}
+
+#else
+
+#define vli_modInv_n vli_modInv
+#define vli_modAdd_n vli_modAdd
+
+static void vli2_rshift1(uECC_word_t *p_vli)
+{
+    vli_rshift1(p_vli);
+    p_vli[uECC_WORDS-1] |= p_vli[uECC_WORDS] << (uECC_WORD_BITS - 1);
+    vli_rshift1(p_vli + uECC_WORDS);
+}
+
+static uECC_word_t vli2_sub(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_borrow = 0;
+    wordcount_t i;
+    for(i=0; i<uECC_WORDS*2; ++i)
+    {
+        uECC_word_t l_diff = p_left[i] - p_right[i] - l_borrow;
+        if(l_diff != p_left[i])
+        {
+            l_borrow = (l_diff > p_left[i]);
+        }
+        p_result[i] = l_diff;
+    }
+    return l_borrow;
+}
+
+/* Computes p_result = (p_left * p_right) % curve_n. */
+static void vli_modMult_n(uECC_word_t *p_result, uECC_word_t *p_left, uECC_word_t *p_right)
+{
+    uECC_word_t l_product[2 * uECC_WORDS];
+    uECC_word_t l_modMultiple[2 * uECC_WORDS];
+    uECC_word_t l_tmp[2 * uECC_WORDS];
+    uECC_word_t *v[2] = {l_tmp, l_product};
+
+    vli_mult(l_product, p_left, p_right);
+    vli_set(l_modMultiple + uECC_WORDS, curve_n); /* works if curve_n has its highest bit set */
+    vli_clear(l_modMultiple);
+
+    bitcount_t i;
+    uECC_word_t l_index = 1;
+    for(i=0; i<=uECC_BYTES * 8; ++i)
+    {
+        uECC_word_t l_borrow = vli2_sub(v[1-l_index], v[l_index], l_modMultiple);
+        l_index = !(l_index ^ l_borrow); /* Swap the index if there was no borrow */
+        vli2_rshift1(l_modMultiple);
+    }
+
+    vli_set(p_result, v[l_index]);
+}
+#endif /* (uECC_CURVE != uECC_secp160r1) */
+
+int uECC_sign(const uint8_t p_privateKey[uECC_BYTES], const uint8_t p_hash[uECC_BYTES], uint8_t p_signature[uECC_BYTES*2])
+{
+    uECC_word_t k[uECC_N_WORDS];
+    uECC_word_t l_tmp[uECC_N_WORDS];
+    uECC_word_t s[uECC_N_WORDS];
+    uECC_word_t *k2[2] = {l_tmp, s};
+    EccPoint p;
+    uECC_word_t l_tries = 0;
+
+    do
+    {
+    repeat:
+        if(!g_rng((uint8_t *)k, sizeof(k)) || (l_tries++ >= MAX_TRIES))
+        {
+            return 0;
+        }
+
+        if(vli_isZero(k))
+        {
+            goto repeat;
+        }
+
+    #if (uECC_CURVE == uECC_secp160r1)
+        k[uECC_WORDS] &= 0x01;
+        if(vli_cmp_n(curve_n, k) != 1)
+        {
+            goto repeat;
+        }
+
+        /* make sure that we don't leak timing information about k. See http://eprint.iacr.org/2011/232.pdf */
+        vli_add_n(l_tmp, k, curve_n);
+        uECC_word_t l_carry = (l_tmp[uECC_WORDS] & 0x02);
+        vli_add_n(s, l_tmp, curve_n);
+
+        /* p = k * G */
+        EccPoint_mult(&p, &curve_G, k2[!l_carry], 0, (uECC_BYTES * 8) + 2);
+    #else
+        if(vli_cmp(curve_n, k) != 1)
+        {
+            goto repeat;
+        }
+
+        /* make sure that we don't leak timing information about k. See http://eprint.iacr.org/2011/232.pdf */
+        uECC_word_t l_carry = vli_add(l_tmp, k, curve_n);
+        vli_add(s, l_tmp, curve_n);
+
+        /* p = k * G */
+        EccPoint_mult(&p, &curve_G, k2[!l_carry], 0, (uECC_BYTES * 8) + 1);
+
+        /* r = x1 (mod n) */
+        if(vli_cmp(curve_n, p.x) != 1)
+        {
+            vli_sub(p.x, p.x, curve_n);
+        }
+    #endif
+    } while(vli_isZero(p.x));
+
+    l_tries = 0;
+    do
+    {
+        if(!g_rng((uint8_t *)l_tmp, sizeof(l_tmp)) || (l_tries++ >= MAX_TRIES))
+        {
+            return 0;
+        }
+    } while(vli_isZero(l_tmp));
+
+    /* Prevent side channel analysis of vli_modInv() to determine
+       bits of k / the private key by premultiplying by a random number */
+    vli_modMult_n(k, k, l_tmp); /* k' = rand * k */
+    vli_modInv_n(k, k, curve_n); /* k = 1 / k' */
+    vli_modMult_n(k, k, l_tmp); /* k = 1 / k */
+
+    vli_nativeToBytes(p_signature, p.x); /* store r */
+
+    l_tmp[uECC_N_WORDS-1] = 0;
+    vli_bytesToNative(l_tmp, p_privateKey); /* tmp = d */
+    s[uECC_N_WORDS-1] = 0;
+    vli_set(s, p.x);
+    vli_modMult_n(s, l_tmp, s); /* s = r*d */
+
+    vli_bytesToNative(l_tmp, p_hash);
+    vli_modAdd_n(s, l_tmp, s, curve_n); /* s = e + r*d */
+    vli_modMult_n(s, s, k); /* s = (e + r*d) / k */
+#if (uECC_CURVE == uECC_secp160r1)
+    if(s[uECC_N_WORDS-1])
+    {
+        goto repeat;
+    }
+#endif
+    vli_nativeToBytes(p_signature + uECC_BYTES, s);
+
+    return 1;
+}
+
+static bitcount_t smax(bitcount_t a, bitcount_t b)
+{
+    return (a > b ? a : b);
+}
+
+int uECC_verify(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_hash[uECC_BYTES], const uint8_t p_signature[uECC_BYTES*2])
+{
+    uECC_word_t u1[uECC_N_WORDS], u2[uECC_N_WORDS];
+    uECC_word_t z[uECC_N_WORDS];
+    EccPoint l_public, l_sum;
+    uECC_word_t rx[uECC_WORDS];
+    uECC_word_t ry[uECC_WORDS];
+    uECC_word_t tx[uECC_WORDS];
+    uECC_word_t ty[uECC_WORDS];
+    uECC_word_t tz[uECC_WORDS];
+
+    uECC_word_t r[uECC_N_WORDS], s[uECC_N_WORDS];
+    r[uECC_N_WORDS-1] = 0;
+    s[uECC_N_WORDS-1] = 0;
+
+    vli_bytesToNative(l_public.x, p_publicKey);
+    vli_bytesToNative(l_public.y, p_publicKey + uECC_BYTES);
+    vli_bytesToNative(r, p_signature);
+    vli_bytesToNative(s, p_signature + uECC_BYTES);
+
+    if(vli_isZero(r) || vli_isZero(s))
+    { /* r, s must not be 0. */
+        return 0;
+    }
+
+#if (uECC_CURVE != uECC_secp160r1)
+    if(vli_cmp(curve_n, r) != 1 || vli_cmp(curve_n, s) != 1)
+    { /* r, s must be < n. */
+        return 0;
+    }
+#endif
+
+    /* Calculate u1 and u2. */
+    vli_modInv_n(z, s, curve_n); /* Z = s^-1 */
+    u1[uECC_N_WORDS-1] = 0;
+    vli_bytesToNative(u1, p_hash);
+    vli_modMult_n(u1, u1, z); /* u1 = e/s */
+    vli_modMult_n(u2, r, z); /* u2 = r/s */
+
+    /* Calculate l_sum = G + Q. */
+    vli_set(l_sum.x, l_public.x);
+    vli_set(l_sum.y, l_public.y);
+    vli_set(tx, curve_G.x);
+    vli_set(ty, curve_G.y);
+    vli_modSub_fast(z, l_sum.x, tx); /* Z = x2 - x1 */
+    XYcZ_add(tx, ty, l_sum.x, l_sum.y);
+    vli_modInv(z, z, curve_p); /* Z = 1/Z */
+    apply_z(l_sum.x, l_sum.y, z);
+
+    /* Use Shamir's trick to calculate u1*G + u2*Q */
+    EccPoint *l_points[4] = {0, &curve_G, &l_public, &l_sum};
+    bitcount_t l_numBits = smax(vli_numBits(u1, uECC_N_WORDS), vli_numBits(u2, uECC_N_WORDS));
+
+    EccPoint *l_point = l_points[(!!vli_testBit(u1, l_numBits-1)) | ((!!vli_testBit(u2, l_numBits-1)) << 1)];
+    vli_set(rx, l_point->x);
+    vli_set(ry, l_point->y);
+    vli_clear(z);
+    z[0] = 1;
+
+    bitcount_t i;
+    for(i = l_numBits - 2; i >= 0; --i)
+    {
+        EccPoint_double_jacobian(rx, ry, z);
+
+        uECC_word_t l_index = (!!vli_testBit(u1, i)) | ((!!vli_testBit(u2, i)) << 1);
+        l_point = l_points[l_index];
+        if(l_point)
+        {
+            vli_set(tx, l_point->x);
+            vli_set(ty, l_point->y);
+            apply_z(tx, ty, z);
+            vli_modSub_fast(tz, rx, tx); /* Z = x2 - x1 */
+            XYcZ_add(tx, ty, rx, ry);
+            vli_modMult_fast(z, z, tz);
+        }
+    }
+
+    vli_modInv(z, z, curve_p); /* Z = 1/Z */
+    apply_z(rx, ry, z);
+
+    /* v = x1 (mod n) */
+#if (uECC_CURVE != uECC_secp160r1)
+    if(vli_cmp(curve_n, rx) != 1)
+    {
+        vli_sub(rx, rx, curve_n);
+    }
+#endif
+
+    /* Accept only if v == r. */
+    return (vli_cmp(rx, r) == 0);
+}
diff --git a/extlibs/tinydtls/ecc/ecc.h b/extlibs/tinydtls/ecc/ecc.h
new file mode 100644 (file)
index 0000000..92e1313
--- /dev/null
@@ -0,0 +1,171 @@
+/* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
+
+#ifndef _MICRO_ECC_H_
+#define _MICRO_ECC_H_
+
+#include <stdint.h>
+
+/* Platform selection options.
+If uECC_PLATFORM is not defined, the code will try to guess it based on compiler macros.
+Possible values for uECC_PLATFORM are defined below: */
+#define uECC_arch_other 0
+#define uECC_x86        1
+#define uECC_x86_64     2
+#define uECC_arm        3
+#define uECC_arm_thumb  4
+#define uECC_avr        5
+
+/* If desired, you can define uECC_WORD_SIZE as appropriate for your platform (1, 4, or 8 bytes).
+If uECC_WORD_SIZE is not explicitly defined then it will be automatically set based on your platform. */
+
+/* Inline assembly options.
+uECC_asm_none  - Use standard C99 only.
+uECC_asm_small - Use GCC inline assembly for the target platform (if available), optimized for minimum size.
+uECC_asm_fast  - Use GCC inline assembly optimized for maximum speed. */
+#define uECC_asm_none  0
+#define uECC_asm_small 1
+#define uECC_asm_fast  2
+#ifndef uECC_ASM
+    #define uECC_ASM uECC_asm_none//uECC_asm_fast
+#endif
+
+/* Curve selection options. */
+#define uECC_secp160r1 1
+#define uECC_secp192r1 2
+#define uECC_secp256r1 3
+#define uECC_secp256k1 4
+#ifndef uECC_CURVE
+    #define uECC_CURVE uECC_secp256r1
+#endif
+
+/* uECC_SQUARE_FUNC - If enabled (defined as nonzero), this will cause a specific function to be used for (scalar) squaring
+    instead of the generic multiplication function. This will make things faster by about 8% but increases the code size. */
+#define uECC_SQUARE_FUNC 1
+
+#define uECC_CONCAT1(a, b) a##b
+#define uECC_CONCAT(a, b) uECC_CONCAT1(a, b)
+
+#define uECC_size_1 20 /* secp160r1 */
+#define uECC_size_2 24 /* secp192r1 */
+#define uECC_size_3 32 /* secp256r1 */
+#define uECC_size_4 32 /* secp256k1 */
+
+#define uECC_BYTES uECC_CONCAT(uECC_size_, uECC_CURVE)
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* uECC_RNG_Function type
+The RNG function should fill p_size random bytes into p_dest. It should return 1 if
+p_dest was filled with random data, or 0 if the random data could not be generated.
+The filled-in values should be either truly random, or from a cryptographically-secure PRNG.
+
+A correctly functioning RNG function must be set (using uECC_set_rng()) before calling
+uECC_make_key() or uECC_sign().
+
+A correct RNG function is set by default when building for Windows, Linux, or OS X.
+If you are building on another POSIX-compliant system that supports /dev/random or /dev/urandom,
+you can define uECC_POSIX to use the predefined RNG. For embedded platforms there is no predefined
+RNG function; you must provide your own.
+*/
+typedef int (*uECC_RNG_Function)(uint8_t *p_dest, unsigned p_size);
+
+/* uECC_set_rng() function.
+Set the function that will be used to generate random bytes. The RNG function should
+return 1 if the random data was generated, or 0 if the random data could not be generated.
+
+On platforms where there is no predefined RNG function (eg embedded platforms), this must
+be called before uECC_make_key() or uECC_sign() are used.
+
+Inputs:
+    p_rng  - The function that will be used to generate random bytes.
+*/
+void uECC_set_rng(uECC_RNG_Function p_rng);
+
+/* uECC_make_key() function.
+Create a public/private key pair.
+
+Outputs:
+    p_publicKey  - Will be filled in with the public key.
+    p_privateKey - Will be filled in with the private key.
+
+Returns 1 if the key pair was generated successfully, 0 if an error occurred.
+*/
+int uECC_make_key(uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_privateKey[uECC_BYTES]);
+
+/* uECC_shared_secret() function.
+Compute a shared secret given your secret key and someone else's public key.
+Note: It is recommended that you hash the result of uECC_shared_secret() before using it for symmetric encryption or HMAC.
+
+Inputs:
+    p_publicKey  - The public key of the remote party.
+    p_privateKey - Your private key.
+
+Outputs:
+    p_secret - Will be filled in with the shared secret value.
+
+Returns 1 if the shared secret was generated successfully, 0 if an error occurred.
+*/
+int uECC_shared_secret(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_privateKey[uECC_BYTES], uint8_t p_secret[uECC_BYTES]);
+
+/* uECC_compress() function.
+Compress a public key.
+
+Inputs:
+    p_publicKey - The public key to compress.
+
+Outputs:
+    p_compressed - Will be filled in with the compressed public key.
+*/
+void uECC_compress(const uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_compressed[uECC_BYTES+1]);
+
+/* uECC_decompress() function.
+Decompress a compressed public key.
+
+Inputs:
+    p_compressed - The compressed public key.
+
+Outputs:
+    p_publicKey - Will be filled in with the decompressed public key.
+*/
+void uECC_decompress(const uint8_t p_compressed[uECC_BYTES+1], uint8_t p_publicKey[uECC_BYTES*2]);
+
+/* uECC_sign() function.
+Generate an ECDSA signature for a given hash value.
+
+Usage: Compute a hash of the data you wish to sign (SHA-2 is recommended) and pass it in to
+this function along with your private key.
+
+Inputs:
+    p_privateKey - Your private key.
+    p_hash       - The message hash to sign.
+
+Outputs:
+    p_signature  - Will be filled in with the signature value.
+
+Returns 1 if the signature generated successfully, 0 if an error occurred.
+*/
+int uECC_sign(const uint8_t p_privateKey[uECC_BYTES], const uint8_t p_hash[uECC_BYTES], uint8_t p_signature[uECC_BYTES*2]);
+
+/* uECC_verify() function.
+Verify an ECDSA signature.
+
+Usage: Compute the hash of the signed data using the same hash as the signer and
+pass it to this function along with the signer's public key and the signature values (r and s).
+
+Inputs:
+    p_publicKey - The signer's public key
+    p_hash      - The hash of the signed data.
+    p_signature - The signature value.
+
+Returns 1 if the signature is valid, 0 if it is invalid.
+*/
+int uECC_verify(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_hash[uECC_BYTES], const uint8_t p_signature[uECC_BYTES*2]);
+
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+
+#endif /* _MICRO_ECC_H_ */
diff --git a/extlibs/tinydtls/ecc/test/ecc_test/ecc_test.ino b/extlibs/tinydtls/ecc/test/ecc_test/ecc_test.ino
new file mode 100755 (executable)
index 0000000..04c5e4a
--- /dev/null
@@ -0,0 +1,115 @@
+#include <uECC.h>
+
+#include <j0g.h>
+#include <js0n.h>
+
+#include <lwm.h>
+
+#include <bitlash.h>
+
+#include <GS.h>
+
+#include <SPI.h>
+#include <Wire.h>
+#include <Scout.h>
+#include <Shell.h>
+
+
+#include <uECC.h>
+
+extern "C" {
+
+static int RNG(uint8_t *p_dest, unsigned p_size)
+{
+  // Use the least-significant bits from the ADC for an unconnected pin (or connected to a source of random noise)
+  // This can take a long time to generate random data if the result of analogRead(0) doesn't change very frequently.
+  while(p_size) {
+    uint8_t l_val = 0;
+    for(unsigned i=0; i<8; ++i)
+    {
+      int l_init = analogRead(0);
+      int l_count = 0;
+      while(analogRead(0) == l_init)
+      {
+        ++l_count;
+      }
+      
+      if(l_count == 0)
+      {
+         l_val = (l_val << 1) | (l_init & 0x01);
+      }
+      else
+      {
+         l_val = (l_val << 1) | (l_count & 0x01);
+      }
+    }
+    *p_dest = l_val;
+    ++p_dest;
+    --p_size;
+  }
+  
+  // NOTE: it would be a good idea to hash the resulting random data using SHA-256 or similar.
+  return 1;
+}
+
+}
+
+void setup()
+{
+  Scout.setup();
+  
+  Serial.print("Testing ecc\n");
+  
+  uECC_set_rng(&RNG);
+}
+
+void loop() {
+  uint8_t l_private1[uECC_BYTES];
+  uint8_t l_private2[uECC_BYTES];
+  
+  uint8_t l_public1[uECC_BYTES * 2];
+  uint8_t l_public2[uECC_BYTES * 2];
+  
+  uint8_t l_secret1[uECC_BYTES];
+  uint8_t l_secret2[uECC_BYTES];
+  
+  unsigned long a = millis();
+  uECC_make_key(l_public1, l_private1);
+  unsigned long b = millis();
+  
+  Serial.print("Made key 1 in "); Serial.println(b-a);
+  a = millis();
+  uECC_make_key(l_public2, l_private2);
+  b = millis();
+  Serial.print("Made key 2 in "); Serial.println(b-a);
+
+  a = millis();
+  int r = uECC_shared_secret(l_public2, l_private1, l_secret1);
+  b = millis();
+  Serial.print("Shared secret 1 in "); Serial.println(b-a);
+  if(!r)
+  {
+    Serial.print("shared_secret() failed (1)\n");
+    return;
+  }
+
+  a = millis();
+  r = uECC_shared_secret(l_public1, l_private2, l_secret2);
+  b = millis();
+  Serial.print("Shared secret 2 in "); Serial.println(b-a);
+  if(!r)
+  {
+    Serial.print("shared_secret() failed (2)\n");
+    return;
+  }
+    
+  if(memcmp(l_secret1, l_secret2, sizeof(l_secret1)) != 0)
+  {
+    Serial.print("Shared secrets are not identical!\n");
+  }
+  else
+  {
+    Serial.print("Shared secrets are identical\n");
+  }
+}
+
diff --git a/extlibs/tinydtls/ecc/test/emk_rules.py b/extlibs/tinydtls/ecc/test/emk_rules.py
new file mode 100755 (executable)
index 0000000..956ccf5
--- /dev/null
@@ -0,0 +1,4 @@
+c, link = emk.module("c", "link")
+link.depdirs += [
+    "$:proj:$"
+]
diff --git a/extlibs/tinydtls/ecc/test/test_ecdh.c b/extlibs/tinydtls/ecc/test/test_ecdh.c
new file mode 100644 (file)
index 0000000..cef274d
--- /dev/null
@@ -0,0 +1,107 @@
+/* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
+
+#include "../ecc.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#if LPC11XX
+
+#include "/Projects/lpc11xx/peripherals/uart.h"
+#include "/Projects/lpc11xx/peripherals/time.h"
+
+static uint64_t g_rand = 88172645463325252ull;
+int fake_rng(uint8_t *p_dest, unsigned p_size)
+{
+    while(p_size)
+    {
+        g_rand ^= (g_rand << 13);
+        g_rand ^= (g_rand >> 7);
+        g_rand ^= (g_rand << 17);
+
+        unsigned l_amount = (p_size > 8 ? 8 : p_size);
+        memcpy(p_dest, &g_rand, l_amount);
+        p_size -= l_amount;
+    }
+    return 1;
+}
+
+#endif
+
+void vli_print(uint8_t *p_vli, unsigned int p_size)
+{
+    while(p_size)
+    {
+        printf("%02X ", (unsigned)p_vli[p_size - 1]);
+        --p_size;
+    }
+}
+
+int main()
+{
+#if LPC11XX
+    uartInit(BAUD_115200);
+       initTime();
+
+    uECC_set_rng(&fake_rng);
+#endif
+
+    int i;
+
+    uint8_t l_private1[uECC_BYTES];
+    uint8_t l_private2[uECC_BYTES];
+
+    uint8_t l_public1[uECC_BYTES * 2];
+    uint8_t l_public2[uECC_BYTES * 2];
+
+    uint8_t l_secret1[uECC_BYTES];
+    uint8_t l_secret2[uECC_BYTES];
+
+    printf("Testing 256 random private key pairs\n");
+
+    for(i=0; i<256; ++i)
+    {
+        printf(".");
+    #if !LPC11XX
+        fflush(stdout);
+    #endif
+
+        if(!uECC_make_key(l_public1, l_private1) || !uECC_make_key(l_public2, l_private2))
+        {
+            printf("uECC_make_key() failed\n");
+            return 1;
+        }
+
+        if(!uECC_shared_secret(l_public2, l_private1, l_secret1))
+        {
+            printf("shared_secret() failed (1)\n");
+            return 1;
+        }
+
+        if(!uECC_shared_secret(l_public1, l_private2, l_secret2))
+        {
+            printf("shared_secret() failed (2)\n");
+            return 1;
+        }
+
+        if(memcmp(l_secret1, l_secret2, sizeof(l_secret1)) != 0)
+        {
+            printf("Shared secrets are not identical!\n");
+            printf("Shared secret 1 = ");
+            vli_print(l_secret1, uECC_BYTES);
+            printf("\n");
+            printf("Shared secret 2 = ");
+            vli_print(l_secret2, uECC_BYTES);
+            printf("\n");
+            printf("Private key 1 = ");
+            vli_print(l_private1, uECC_BYTES);
+            printf("\n");
+            printf("Private key 2 = ");
+            vli_print(l_private2, uECC_BYTES);
+            printf("\n");
+        }
+    }
+    printf("\n");
+
+    return 0;
+}
diff --git a/extlibs/tinydtls/ecc/test/test_ecdsa.c b/extlibs/tinydtls/ecc/test/test_ecdsa.c
new file mode 100644 (file)
index 0000000..f3983bb
--- /dev/null
@@ -0,0 +1,79 @@
+/* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
+
+#include "../ecc.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#if LPC11XX
+
+#include "/Projects/lpc11xx/peripherals/uart.h"
+#include "/Projects/lpc11xx/peripherals/time.h"
+
+static uint64_t g_rand = 88172645463325252ull;
+int fake_rng(uint8_t *p_dest, unsigned p_size)
+{
+    while(p_size)
+    {
+        g_rand ^= (g_rand << 13);
+        g_rand ^= (g_rand >> 7);
+        g_rand ^= (g_rand << 17);
+
+        unsigned l_amount = (p_size > 8 ? 8 : p_size);
+        memcpy(p_dest, &g_rand, l_amount);
+        p_size -= l_amount;
+    }
+    return 1;
+}
+
+#endif
+
+int main()
+{
+#if LPC11XX
+    uartInit(BAUD_115200);
+       initTime();
+
+    uECC_set_rng(&fake_rng);
+#endif
+
+    uint8_t l_public[uECC_BYTES*2];
+    uint8_t l_private[uECC_BYTES];
+
+    uint8_t l_hash[uECC_BYTES];
+
+    uint8_t l_sig[uECC_BYTES*2];
+
+    int i;
+
+    printf("Testing 256 signatures\n");
+
+    for(i=0; i<256; ++i)
+    {
+        printf(".");
+    #if !LPC11XX
+        fflush(stdout);
+    #endif
+
+        if(!uECC_make_key(l_public, l_private))
+        {
+            printf("uECC_make_key() failed\n");
+            continue;
+        }
+        memcpy(l_hash, l_public, uECC_BYTES);
+
+        if(!uECC_sign(l_private, l_hash, l_sig))
+        {
+            printf("uECC_sign() failed\n");
+            continue;
+        }
+
+        if(!uECC_verify(l_public, l_hash, l_sig))
+        {
+            printf("uECC_verify() failed\n");
+        }
+    }
+    printf("\n");
+
+    return 0;
+}
diff --git a/extlibs/tinydtls/ecc/test_helper.c b/extlibs/tinydtls/ecc/test_helper.c
new file mode 100644 (file)
index 0000000..bda44ba
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2009 Chris K Cockrum <ckc@cockrum.net>
+ *
+ * Copyright (c) 2013 Jens Trillmann <jtrillma@tzi.de>
+ * Copyright (c) 2013 Marc Müller-Weinhardt <muewei@tzi.de>
+ * Copyright (c) 2013 Lars Schmertmann <lars@tzi.de>
+ * Copyright (c) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ *
+ * This implementation is based in part on the paper Implementation of an
+ * Elliptic Curve Cryptosystem on an 8-bit Microcontroller [0] by
+ * Chris K Cockrum <ckc@cockrum.net>.
+ *
+ * [0]: http://cockrum.net/Implementation_of_ECC_on_an_8-bit_microcontroller.pdf
+ *
+ * This is a efficient ECC implementation on the secp256r1 curve for 32 Bit CPU
+ * architectures. It provides basic operations on the secp256r1 curve and support
+ * for ECDH and ECDSA.
+ */
+#include "test_helper.h"
+#include "ecc.h"
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+void ecc_printNumber(const uint32_t *x, int numberLength){ //here the values are turned to MSB!
+       int n;
+
+       for(n = numberLength - 1; n >= 0; n--){
+               printf("%08x", x[n]);
+       }
+       printf("\n");
+}
+
+void ecc_setRandom(uint32_t *secret){
+       int i;
+
+       for (i = 0; i < arrayLength; ++i)
+       {
+               secret[i] = rand();
+       }
+}
+const uint32_t ecc_prime_m[8] = {0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,
+                                0x00000000, 0x00000000, 0x00000001, 0xffffffff};
+
+                                                       
+/* This is added after an static byte addition if the answer has a carry in MSB*/
+const uint32_t ecc_prime_r[8] = {0x00000001, 0x00000000, 0x00000000, 0xffffffff,
+                                0xffffffff, 0xffffffff, 0xfffffffe, 0x00000000};
+
+#ifdef CONTIKI
+void
+test_assert(const char *file, int lineno)
+{
+  printf("Assertion failed: file %s, line %d.\n", file, lineno);
+  /*
+   * loop for a while;
+   * call _reset_vector__();
+   */
+}
+#endif
diff --git a/extlibs/tinydtls/ecc/test_helper.h b/extlibs/tinydtls/ecc/test_helper.h
new file mode 100644 (file)
index 0000000..38a194e
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2009 Chris K Cockrum <ckc@cockrum.net>
+ *
+ * Copyright (c) 2013 Jens Trillmann <jtrillma@tzi.de>
+ * Copyright (c) 2013 Marc Müller-Weinhardt <muewei@tzi.de>
+ * Copyright (c) 2013 Lars Schmertmann <lars@tzi.de>
+ * Copyright (c) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ *
+ * This implementation is based in part on the paper Implementation of an
+ * Elliptic Curve Cryptosystem on an 8-bit Microcontroller [0] by
+ * Chris K Cockrum <ckc@cockrum.net>.
+ *
+ * [0]: http://cockrum.net/Implementation_of_ECC_on_an_8-bit_microcontroller.pdf
+ *
+ * This is a efficient ECC implementation on the secp256r1 curve for 32 Bit CPU
+ * architectures. It provides basic operations on the secp256r1 curve and support
+ * for ECDH and ECDSA.
+ */
+#include <inttypes.h>
+
+extern const uint32_t ecc_prime_m[8];
+extern const uint32_t ecc_prime_r[8];
+
+//debug function to print long numbers
+void ecc_printNumber(const uint32_t *x, int numberLength);
+void ecc_setRandom(uint32_t *secret);
+
+#ifdef CONTIKI
+#undef assert
+#define assert(e) ((e) ? (void)0 : test_assert(__FILE__, __LINE__))
+void test_assert(const char *, int);
+#endif
diff --git a/extlibs/tinydtls/ecc/testecc.c b/extlibs/tinydtls/ecc/testecc.c
new file mode 100644 (file)
index 0000000..b36d46b
--- /dev/null
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2009 Chris K Cockrum <ckc@cockrum.net>
+ *
+ * Copyright (c) 2013 Jens Trillmann <jtrillma@tzi.de>
+ * Copyright (c) 2013 Marc Müller-Weinhardt <muewei@tzi.de>
+ * Copyright (c) 2013 Lars Schmertmann <lars@tzi.de>
+ * Copyright (c) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ *
+ * This implementation is based in part on the paper Implementation of an
+ * Elliptic Curve Cryptosystem on an 8-bit Microcontroller [0] by
+ * Chris K Cockrum <ckc@cockrum.net>.
+ *
+ * [0]: http://cockrum.net/Implementation_of_ECC_on_an_8-bit_microcontroller.pdf
+ *
+ * This is a efficient ECC implementation on the secp256r1 curve for 32 Bit CPU
+ * architectures. It provides basic operations on the secp256r1 curve and support
+ * for ECDH and ECDSA.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "ecc.h"
+#include "test_helper.h"
+
+#ifdef CONTIKI
+#include "contiki.h"
+#else
+#include <time.h>
+#endif /* CONTIKI */
+
+//These are testvalues taken from the NIST P-256 definition
+//6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296
+uint32_t BasePointx[8] = {     0xd898c296, 0xf4a13945, 0x2deb33a0, 0x77037d81,
+                                                       0x63a440f2, 0xf8bce6e5, 0xe12c4247, 0x6b17d1f2};
+
+//4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5
+uint32_t BasePointy[8] = {     0x37bf51f5, 0xcbb64068, 0x6b315ece, 0x2bce3357,
+                                                       0x7c0f9e16, 0x8ee7eb4a, 0xfe1a7f9b, 0x4fe342e2};
+
+//de2444be bc8d36e6 82edd27e 0f271508 617519b3 221a8fa0 b77cab39 89da97c9
+uint32_t Sx[8] = {     0x89da97c9, 0xb77cab39, 0x221a8fa0, 0x617519b3, 
+                                       0x0f271508, 0x82edd27e, 0xbc8d36e6, 0xde2444be};
+
+//c093ae7f f36e5380 fc01a5aa d1e66659 702de80f 53cec576 b6350b24 3042a256
+uint32_t Sy[8] = {     0x3042a256, 0xb6350b24, 0x53cec576, 0x702de80f,
+                                       0xd1e66659, 0xfc01a5aa, 0xf36e5380, 0xc093ae7f};
+
+//55a8b00f 8da1d44e 62f6b3b2 5316212e 39540dc8 61c89575 bb8cf92e 35e0986b
+uint32_t Tx[8] = {     0x35e0986b, 0xbb8cf92e, 0x61c89575, 0x39540dc8,
+                                       0x5316212e, 0x62f6b3b2, 0x8da1d44e, 0x55a8b00f};
+
+//5421c320 9c2d6c70 4835d82a c4c3dd90 f61a8a52 598b9e7a b656e9d8 c8b24316
+uint32_t Ty[8] = {     0xc8b24316, 0xb656e9d8, 0x598b9e7a, 0xf61a8a52,
+                                       0xc4c3dd90, 0x4835d82a, 0x9c2d6c70, 0x5421c320};
+
+//c51e4753 afdec1e6 b6c6a5b9 92f43f8d d0c7a893 3072708b 6522468b 2ffb06fd
+uint32_t secret[8] = { 0x2ffb06fd, 0x6522468b, 0x3072708b, 0xd0c7a893,
+                                               0x92f43f8d, 0xb6c6a5b9, 0xafdec1e6, 0xc51e4753};
+                                                       
+//72b13dd4 354b6b81 745195e9 8cc5ba69 70349191 ac476bd4 553cf35a 545a067e
+uint32_t resultAddx[8] = {     0x545a067e, 0x553cf35a, 0xac476bd4, 0x70349191,
+                                                       0x8cc5ba69, 0x745195e9, 0x354b6b81, 0x72b13dd4};
+
+//8d585cbb 2e1327d7 5241a8a1 22d7620d c33b1331 5aa5c9d4 6d013011 744ac264
+uint32_t resultAddy[8] = {     0x744ac264, 0x6d013011, 0x5aa5c9d4, 0xc33b1331,
+                                                       0x22d7620d, 0x5241a8a1, 0x2e1327d7, 0x8d585cbb};
+
+//7669e690 1606ee3b a1a8eef1 e0024c33 df6c22f3 b17481b8 2a860ffc db6127b0
+uint32_t resultDoublex[8] = {  0xdb6127b0, 0x2a860ffc, 0xb17481b8, 0xdf6c22f3,
+                                                               0xe0024c33, 0xa1a8eef1, 0x1606ee3b, 0x7669e690};
+
+//fa878162 187a54f6 c39f6ee0 072f33de 389ef3ee cd03023d e10ca2c1 db61d0c7
+uint32_t resultDoubley[8] = {  0xdb61d0c7, 0xe10ca2c1, 0xcd03023d, 0x389ef3ee,
+                                                               0x072f33de, 0xc39f6ee0, 0x187a54f6, 0xfa878162};
+
+//51d08d5f 2d427888 2946d88d 83c97d11 e62becc3 cfc18bed acc89ba3 4eeca03f
+uint32_t resultMultx[8] = {    0x4eeca03f, 0xacc89ba3, 0xcfc18bed, 0xe62becc3,
+                                                       0x83c97d11, 0x2946d88d, 0x2d427888, 0x51d08d5f};
+
+//75ee68eb 8bf626aa 5b673ab5 1f6e744e 06f8fcf8 a6c0cf30 35beca95 6a7b41d5
+uint32_t resultMulty[8] = {    0x6a7b41d5, 0x35beca95, 0xa6c0cf30, 0x06f8fcf8,
+                                                       0x1f6e744e, 0x5b673ab5, 0x8bf626aa, 0x75ee68eb};
+
+static const uint32_t ecdsaTestMessage[] = { 0x65637572, 0x20612073, 0x68206F66, 0x20686173, 0x69732061, 0x68697320, 0x6F2C2054, 0x48616C6C};
+
+static const uint32_t ecdsaTestSecret[] = {0x94A949FA, 0x401455A1, 0xAD7294CA, 0x896A33BB, 0x7A80E714, 0x4321435B, 0x51247A14, 0x41C1CB6B};
+
+static const uint32_t ecdsaTestRand1[] = { 0x1D1E1F20, 0x191A1B1C, 0x15161718, 0x11121314, 0x0D0E0F10, 0x090A0B0C, 0x05060708, 0x01020304};
+static const uint32_t ecdsaTestresultR1[] = { 0xC3B4035F, 0x515AD0A6, 0xBF375DCA, 0x0CC1E997, 0x7F54FDCD, 0x04D3FECA, 0xB9E396B9, 0x515C3D6E};
+static const uint32_t ecdsaTestresultS1[] = { 0x5366B1AB, 0x0F1DBF46, 0xB0C8D3C4, 0xDB755B6F, 0xB9BF9243, 0xE644A8BE, 0x55159A59, 0x6F9E52A6};
+
+static const uint32_t ecdsaTestRand2[] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x01FFFFFF};
+static const uint32_t ecdsaTestresultR2[] = { 0x14146C91, 0xE878724D, 0xCD4FF928, 0xCC24BC04, 0xAC403390, 0x650C0060, 0x4A30B3F1, 0x9C69B726};
+static const uint32_t ecdsaTestresultS2[] = { 0x433AAB6F, 0x808250B1, 0xE46F90F4, 0xB342E972, 0x18B2F7E4, 0x2DB981A2, 0x6A288FA4, 0x41CF59DB};
+
+void addTest(){
+       uint32_t tempx[8];
+       uint32_t tempy[8];
+
+       ecc_ec_add(Tx, Ty, Sx, Sy, tempx, tempy);
+       assert(ecc_isSame(tempx, resultAddx, arrayLength));
+       assert(ecc_isSame(tempy, resultAddy, arrayLength));
+}
+
+void doubleTest(){
+       uint32_t tempx[8];
+       uint32_t tempy[8];
+
+       ecc_ec_double(Sx, Sy, tempx, tempy);
+       assert(ecc_isSame(tempx, resultDoublex, arrayLength));
+       assert(ecc_isSame(tempy, resultDoubley, arrayLength));
+}
+
+void multTest(){
+       uint32_t tempx[8];
+       uint32_t tempy[8];
+
+       ecc_ec_mult(Sx, Sy, secret, tempx, tempy);
+       assert(ecc_isSame(tempx, resultMultx, arrayLength));
+       assert(ecc_isSame(tempy, resultMulty, arrayLength));
+}
+
+void eccdhTest(){
+       uint32_t tempx[8];
+       uint32_t tempy[8];
+       uint32_t tempAx2[8];
+       uint32_t tempAy2[8];
+       uint32_t tempBx1[8];
+       uint32_t tempBy1[8];
+       uint32_t tempBx2[8];
+       uint32_t tempBy2[8];    
+       uint32_t secretA[8];
+       uint32_t secretB[8];
+       ecc_setRandom(secretA);
+       ecc_printNumber(secretA, 8);
+       ecc_setRandom(secretB);
+       ecc_printNumber(secretB, 8);
+       ecc_ec_mult(BasePointx, BasePointy, secretA, tempx, tempy);
+       ecc_ec_mult(BasePointx, BasePointy, secretB, tempBx1, tempBy1);
+       //public key exchange
+       ecc_ec_mult(tempBx1, tempBy1, secretA, tempAx2, tempAy2);
+       ecc_ec_mult(tempx, tempy, secretB, tempBx2, tempBy2);
+       assert(ecc_isSame(tempAx2, tempBx2, arrayLength));
+       assert(ecc_isSame(tempAy2, tempBy2, arrayLength));
+
+}
+
+void ecdsaTest() {
+       int ret __attribute__((unused));
+       uint32_t tempx[9];
+       uint32_t tempy[9];
+       uint32_t pub_x[8];
+       uint32_t pub_y[8];
+
+       ecc_ec_mult(BasePointx, BasePointy, ecdsaTestSecret, pub_x, pub_y);
+
+       ret = ecc_ecdsa_sign(ecdsaTestSecret, ecdsaTestMessage, ecdsaTestRand1, tempx, tempy);
+       assert(ecc_isSame(tempx, ecdsaTestresultR1, arrayLength));
+       assert(ecc_isSame(tempy, ecdsaTestresultS1, arrayLength));
+       assert(ret == 0);
+
+       ret = ecc_ecdsa_validate(pub_x, pub_y, ecdsaTestMessage, tempx, tempy);
+       assert(!ret);
+
+
+       ret = ecc_ecdsa_sign(ecdsaTestSecret, ecdsaTestMessage, ecdsaTestRand2, tempx, tempy);
+       assert(ecc_isSame(tempx, ecdsaTestresultR2, arrayLength));
+       assert(ecc_isSame(tempy, ecdsaTestresultS2, arrayLength));
+       assert(ret == 0);
+
+       ret = ecc_ecdsa_validate(pub_x, pub_y, ecdsaTestMessage, tempx, tempy);
+       assert(!ret);
+}
+
+#ifdef CONTIKI
+PROCESS(ecc_filed_test, "ECC test");
+AUTOSTART_PROCESSES(&ecc_filed_test);
+PROCESS_THREAD(ecc_filed_test, ev, d)
+{
+       PROCESS_BEGIN();
+
+       srand(1234);
+       addTest();
+       doubleTest();
+       multTest();
+       eccdhTest();
+       ecdsaTest();
+       printf("%s\n", "All Tests successful.");
+
+       PROCESS_END();
+}
+#else /* CONTIKI */
+int main(int argc, char const *argv[])
+{
+       srand(time(NULL));
+       addTest();
+       doubleTest();
+       multTest();
+       eccdhTest();
+       ecdsaTest();
+       printf("%s\n", "All Tests successful.");
+       return 0;
+}
+#endif /* CONTIKI */
diff --git a/extlibs/tinydtls/ecc/testfield.c b/extlibs/tinydtls/ecc/testfield.c
new file mode 100644 (file)
index 0000000..30a690e
--- /dev/null
@@ -0,0 +1,290 @@
+/*
+ * Copyright (c) 2009 Chris K Cockrum <ckc@cockrum.net>
+ *
+ * Copyright (c) 2013 Jens Trillmann <jtrillma@tzi.de>
+ * Copyright (c) 2013 Marc Müller-Weinhardt <muewei@tzi.de>
+ * Copyright (c) 2013 Lars Schmertmann <lars@tzi.de>
+ * Copyright (c) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ *
+ * This implementation is based in part on the paper Implementation of an
+ * Elliptic Curve Cryptosystem on an 8-bit Microcontroller [0] by
+ * Chris K Cockrum <ckc@cockrum.net>.
+ *
+ * [0]: http://cockrum.net/Implementation_of_ECC_on_an_8-bit_microcontroller.pdf
+ *
+ * This is a efficient ECC implementation on the secp256r1 curve for 32 Bit CPU
+ * architectures. It provides basic operations on the secp256r1 curve and support
+ * for ECDH and ECDSA.
+ */
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+#include "ecc.h"
+#include "test_helper.h"
+
+#ifdef CONTIKI
+#include "contiki.h"
+#endif /* CONTIKI */
+
+//arbitrary test values and results
+uint32_t null[8] = {   0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t null64[16] = {        0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t one[8] = {    0x00000001,0x00000000,0x00000000,0x00000000,
+                                       0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t one64[16] = { 0x00000001,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t two[8] = {    0x00000002,0x00000000,0x00000000,0x00000000,
+                                       0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t two64[16] = { 0x00000002,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t three[8] = {  0x00000003,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t four[8] = {0x00000004,0x00000000,0x00000000,0x00000000,
+                                       0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t four64[16] = {        0x00000004,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t six[8] = {    0x00000006,0x00000000,0x00000000,0x00000000,
+                                       0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t eight[8] = {  0x00000008,0x00000000,0x00000000,0x00000000,
+                                               0x00000000,0x00000000,0x00000000,0x00000000};
+uint32_t full[8] = {   0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
+                                               0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF};
+//00000000fffffffeffffffffffffffffffffffff000000000000000000000001_16
+uint32_t resultFullAdd[8] = {  0x00000001,0x00000000,0x00000000,0xFFFFFFFF,
+                                                               0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFE,0x00000000};
+uint32_t primeMinusOne[8]=     {       0xfffffffe,0xffffffff,0xffffffff,0x00000000,
+                                                               0x00000000,0x00000000,0x00000001,0xffffffff};
+uint32_t resultDoubleMod[8] = { 0xfffffffd,0xffffffff,0xffffffff,0x00000000,
+                                                               0x00000000,0x00000000,0x00000001,0xffffffff};
+//fffffffe00000002fffffffe0000000100000001fffffffe00000001fffffffc00000003fffffffcfffffffffffffffffffffffc000000000000000000000004_16
+uint32_t resultQuadMod[16] = { 0x00000004,0x00000000,0x00000000,0xFFFFFFFC,
+                                                               0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFC,0x00000003,
+                                                               0xFFFFFFFC,0x00000001,0xFFFFFFFE,0x00000001,
+                                                               0x00000001,0xFFFFFFFE,0x00000002,0xFFFFFFFE};
+//00000002fffffffffffffffffffffffefffffffdffffffff0000000000000002_16
+uint32_t resultFullMod[8] = {  0x00000002,0x00000000,0xFFFFFFFF,0xFFFFFFFD,
+                                                               0xFFFFFFFE,0xFFFFFFFF,0xFFFFFFFF,0x00000002};
+
+static const uint32_t orderMinusOne[8] = {0xFC632550, 0xF3B9CAC2, 0xA7179E84, 0xBCE6FAAD,
+                                       0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF};
+static const uint32_t orderResultDoubleMod[8] = {0xFC63254F, 0xF3B9CAC2, 0xA7179E84, 0xBCE6FAAD, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF};
+
+uint32_t temp[8];
+uint32_t temp2[16];
+
+void nullEverything(){
+       memset(temp, 0, sizeof(temp));
+       memset(temp2, 0, sizeof(temp));
+}
+
+void fieldAddTest(){
+       assert(ecc_isSame(one, one, arrayLength));
+       ecc_fieldAdd(one, null, ecc_prime_r, temp);
+       assert(ecc_isSame(temp, one, arrayLength));
+       nullEverything();
+       ecc_fieldAdd(one, one, ecc_prime_r, temp);
+       assert(ecc_isSame(temp, two, arrayLength));
+       nullEverything();
+       ecc_add(full, one, temp, 32);
+       assert(ecc_isSame(null, temp, arrayLength));
+       nullEverything();
+       ecc_fieldAdd(full, one, ecc_prime_r, temp);
+       assert(ecc_isSame(temp, resultFullAdd, arrayLength));
+}
+
+void fieldSubTest(){
+       assert(ecc_isSame(one, one, arrayLength));
+       ecc_fieldSub(one, null, ecc_prime_m, temp);
+       assert(ecc_isSame(one, temp, arrayLength));
+       nullEverything();
+       ecc_fieldSub(one, one, ecc_prime_m, temp);
+       assert(ecc_isSame(null, temp, arrayLength));
+       nullEverything();
+       ecc_fieldSub(null, one, ecc_prime_m, temp);
+       assert(ecc_isSame(primeMinusOne, temp, arrayLength));
+}
+
+void fieldMultTest(){
+       ecc_fieldMult(one, null, temp2, arrayLength);
+       assert(ecc_isSame(temp2, null64, arrayLength * 2));
+       nullEverything();
+       ecc_fieldMult(one, two, temp2, arrayLength);
+       assert(ecc_isSame(temp2, two64, arrayLength * 2));
+       nullEverything();
+       ecc_fieldMult(two, two, temp2, arrayLength);
+       assert(ecc_isSame(temp2, four64, arrayLength * 2));
+       nullEverything();
+       ecc_fieldMult(primeMinusOne, primeMinusOne, temp2, arrayLength);
+       assert(ecc_isSame(temp2, resultQuadMod, arrayLength * 2));
+       nullEverything();
+       ecc_fieldInv(two, ecc_prime_m, ecc_prime_r, temp);
+       ecc_fieldMult(temp, two, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(temp, one, arrayLength));
+}
+
+void fieldModPTest(){
+       ecc_fieldMult(primeMinusOne, primeMinusOne, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(temp, one, arrayLength));
+       nullEverything();
+       ecc_fieldModP(temp, one64);
+       assert(ecc_isSame(temp, one, arrayLength));
+       nullEverything();
+       ecc_fieldMult(two, primeMinusOne, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(temp, resultDoubleMod, arrayLength));
+       nullEverything();
+       /*fieldMult(full, full, temp2, arrayLength); //not working, maybe because of the number bigger than p^2?
+       fieldModP(temp, temp2);
+       assert(ecc_isSame(temp, resultFullMod, arrayLength));*/
+}
+
+void fieldModOTest(){
+       ecc_fieldMult(orderMinusOne, orderMinusOne, temp2, arrayLength);
+       ecc_fieldModO(temp2, temp, arrayLength * 2);
+       assert(ecc_isSame(temp, one, arrayLength));
+       nullEverything();
+       ecc_fieldModO(one64, temp, arrayLength * 2);
+       assert(ecc_isSame(temp, one, arrayLength));
+       nullEverything();
+       ecc_fieldMult(two, orderMinusOne, temp2, arrayLength);
+       ecc_fieldModO(temp2, temp, arrayLength * 2);
+       assert(ecc_isSame(temp, orderResultDoubleMod, arrayLength));
+       nullEverything();
+}
+
+
+// void rShiftTest(){
+//     printNumber(full, 32);
+//     rshift(full);
+//     printNumber(full, 32);
+//     printNumber(two, 32);
+//     rshift(two);
+//     printNumber(two, 32);
+//     printNumber(four, 32);
+//     rshift(four);
+//     printNumber(four, 32);
+// }
+
+// void isOneTest(){
+//     printf("%d\n", isone(one));
+//     printf("%d\n", isone(two));
+//     printf("%d\n", isone(four));
+//     printf("%d\n", isone(full));
+//     printf("%d\n", isone(null));
+// }
+
+void fieldInvTest(){
+       nullEverything();
+       ecc_fieldInv(two, ecc_prime_m, ecc_prime_r, temp);
+       ecc_fieldMult(temp, two, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(one, temp, arrayLength));
+       nullEverything();
+       ecc_fieldInv(eight, ecc_prime_m, ecc_prime_r, temp);
+       ecc_fieldMult(temp, eight, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(one, temp, arrayLength));
+       nullEverything();
+       ecc_fieldInv(three, ecc_prime_m, ecc_prime_r, temp);
+       ecc_fieldMult(temp, three, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(one, temp, arrayLength));
+       nullEverything();
+       ecc_fieldInv(six, ecc_prime_m, ecc_prime_r, temp);
+       ecc_fieldMult(temp, six, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(one, temp, arrayLength));
+       nullEverything();
+       ecc_fieldInv(primeMinusOne, ecc_prime_m, ecc_prime_r, temp);
+       ecc_fieldMult(temp, primeMinusOne, temp2, arrayLength);
+       ecc_fieldModP(temp, temp2);
+       assert(ecc_isSame(one, temp, arrayLength));
+}
+
+// void randomStuff(){
+
+// }
+
+#ifdef CONTIKI
+PROCESS(ecc_filed_test, "ECC field test");
+AUTOSTART_PROCESSES(&ecc_filed_test);
+PROCESS_THREAD(ecc_filed_test, ev, d)
+{
+       PROCESS_BEGIN();
+
+       nullEverything();
+       //randomStuff();
+       nullEverything();
+       fieldAddTest();
+       nullEverything();
+       fieldSubTest();
+       nullEverything();
+       fieldMultTest();
+       nullEverything();
+       fieldModPTest();
+       nullEverything();
+       fieldModOTest();
+       nullEverything();
+       fieldInvTest();
+       nullEverything();
+       //rShiftTest();
+       //isOneTest();
+       printf("%s\n", "All Tests succesfull!");
+
+       PROCESS_END();
+}
+#else /* CONTIKI */
+int main(int argc, char const *argv[])
+{
+       nullEverything();
+       //randomStuff();
+       nullEverything();
+       fieldAddTest();
+       nullEverything();
+       fieldSubTest();
+       nullEverything();
+       fieldMultTest();
+       nullEverything();
+       fieldModPTest();
+       nullEverything();
+       fieldModOTest();
+       nullEverything();
+       fieldInvTest();
+       nullEverything();
+       //rShiftTest();
+       //isOneTest();
+       printf("%s\n", "All Tests succesfull!");
+       return 0;
+}
+#endif /* CONTIKI */
diff --git a/extlibs/tinydtls/examples/contiki/Makefile.in b/extlibs/tinydtls/examples/contiki/Makefile.in
new file mode 100644 (file)
index 0000000..770f220
--- /dev/null
@@ -0,0 +1,61 @@
+########################################################################
+# platform-specific options
+
+ifeq ($(TARGET), econotag)
+CFLAGS += -DUIP_CONF_TCP=0
+endif
+
+ifeq ($(TARGET), minimal-net)
+UIP_CONF_IPV6_RPL=0
+CFLAGS += -DUIP_CONF_IPV6_RPL=0 -DRPL_BORDER_ROUTER=0
+endif
+
+# usually, you should not need changing anything beyond this line
+########################################################################
+
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+
+abs_builddir = @abs_builddir@
+top_builddir = @top_builddir@
+top_srcdir:= @top_srcdir@
+DISTDIR=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
+DTLS_SOURCES:=dtls-server.c dtls-client.c
+FILES:=Makefile.in $(DTLS_SOURCES)
+
+all: dtls-server dtls-client
+       $(MAKE) $(MAKEFLAGS) ROLE=server dtls-server
+       $(MAKE) $(MAKEFLAGS) clean
+       $(MAKE) $(MAKEFLAGS) ROLE=client dtls-client
+
+CONTIKI=$(top_srcdir)/../..
+
+WITH_UIP6=1
+UIP_CONF_IPV6=1
+
+ifneq ($(ROLE),client)
+       CFLAGS+= -DHARD_CODED_ADDRESS=\"aaaa::02:232\"
+else
+       CFLAGS+= -DUDP_CONNECTION_ADDR="fe80::ff:fe02:232" \
+                -DHARD_CODED_ADDRESS=\"aaaa::02:230\"
+endif
+
+CFLAGS += -ffunction-sections
+LDFLAGS += -Wl,--gc-sections,--undefined=_reset_vector__,--undefined=InterruptVectors,--undefined=_copy_data_init__,--undefined=_clear_bss_init__,--undefined=_end_of_init__
+
+CFLAGS += -DSHA2_USE_INTTYPES_H
+
+APPS += tinydtls/aes tinydtls/sha2 tinydtls/ecc tinydtls
+
+ccm-test: tests/ccm-test
+
+dist:  $(FILES)
+       test -d $(DISTDIR)/examples/contiki || $(MKDIR) -p $(DISTDIR)/examples/contiki
+       cp $(FILES) $(DISTDIR)/examples/contiki
+
+include $(CONTIKI)/Makefile.include
diff --git a/extlibs/tinydtls/examples/contiki/dtls-client.c b/extlibs/tinydtls/examples/contiki/dtls-client.c
new file mode 100644 (file)
index 0000000..b1af669
--- /dev/null
@@ -0,0 +1,337 @@
+/*
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the Contiki operating system.
+ *
+ */
+
+#include "contiki.h"
+#include "contiki-lib.h"
+#include "contiki-net.h"
+
+#include "dev/serial-line.h"
+
+#include <string.h>
+
+#include "tinydtls.h"
+
+#ifndef DEBUG
+#define DEBUG DEBUG_PRINT
+#endif
+#include "net/ip/uip-debug.h"
+
+#include "debug.h"
+#include "dtls.h"
+
+#ifdef DTLS_PSK
+/* The PSK information for DTLS */
+/* make sure that default identity and key fit into buffer, i.e.
+ * sizeof(PSK_DEFAULT_IDENTITY) - 1 <= PSK_ID_MAXLEN and
+ * sizeof(PSK_DEFAULT_KEY) - 1 <= PSK_MAXLEN
+*/
+
+#define PSK_ID_MAXLEN 32
+#define PSK_MAXLEN 32
+#define PSK_DEFAULT_IDENTITY "Client_identity"
+#define PSK_DEFAULT_KEY      "secretPSK"
+#endif /* DTLS_PSK */
+
+#define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
+#define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
+
+#define MAX_PAYLOAD_LEN 120
+
+static struct uip_udp_conn *client_conn;
+static dtls_context_t *dtls_context;
+static char buf[200];
+static size_t buflen = 0;
+
+static const unsigned char ecdsa_priv_key[] = {
+                       0x41, 0xC1, 0xCB, 0x6B, 0x51, 0x24, 0x7A, 0x14,
+                       0x43, 0x21, 0x43, 0x5B, 0x7A, 0x80, 0xE7, 0x14,
+                       0x89, 0x6A, 0x33, 0xBB, 0xAD, 0x72, 0x94, 0xCA,
+                       0x40, 0x14, 0x55, 0xA1, 0x94, 0xA9, 0x49, 0xFA};
+
+static const unsigned char ecdsa_pub_key_x[] = {
+                       0x36, 0xDF, 0xE2, 0xC6, 0xF9, 0xF2, 0xED, 0x29,
+                       0xDA, 0x0A, 0x9A, 0x8F, 0x62, 0x68, 0x4E, 0x91,
+                       0x63, 0x75, 0xBA, 0x10, 0x30, 0x0C, 0x28, 0xC5,
+                       0xE4, 0x7C, 0xFB, 0xF2, 0x5F, 0xA5, 0x8F, 0x52};
+
+static const unsigned char ecdsa_pub_key_y[] = {
+                       0x71, 0xA0, 0xD4, 0xFC, 0xDE, 0x1A, 0xB8, 0x78,
+                       0x5A, 0x3C, 0x78, 0x69, 0x35, 0xA7, 0xCF, 0xAB,
+                       0xE9, 0x3F, 0x98, 0x72, 0x09, 0xDA, 0xED, 0x0B,
+                       0x4F, 0xAB, 0xC3, 0x6F, 0xC7, 0x72, 0xF8, 0x29};
+
+static void
+try_send(struct dtls_context_t *ctx, session_t *dst) {
+  int res;
+  res = dtls_write(ctx, dst, (uint8 *)buf, buflen);
+  if (res >= 0) {
+    memmove(buf, buf + res, buflen - res);
+    buflen -= res;
+  }
+}
+
+static int
+read_from_peer(struct dtls_context_t *ctx, 
+              session_t *session, uint8 *data, size_t len) {
+  size_t i;
+  for (i = 0; i < len; i++)
+    PRINTF("%c", data[i]);
+  return 0;
+}
+
+static int
+send_to_peer(struct dtls_context_t *ctx, 
+            session_t *session, uint8 *data, size_t len) {
+
+  struct uip_udp_conn *conn = (struct uip_udp_conn *)dtls_get_app_data(ctx);
+
+  uip_ipaddr_copy(&conn->ripaddr, &session->addr);
+  conn->rport = session->port;
+
+  PRINTF("send to ");
+  PRINT6ADDR(&conn->ripaddr);
+  PRINTF(":%u\n", uip_ntohs(conn->rport));
+
+  uip_udp_packet_send(conn, data, len);
+
+  /* Restore server connection to allow data from any node */
+  /* FIXME: do we want this at all? */
+  memset(&conn->ripaddr, 0, sizeof(conn->ripaddr));
+  memset(&conn->rport, 0, sizeof(conn->rport));
+
+  return len;
+}
+
+#ifdef DTLS_PSK
+static unsigned char psk_id[PSK_ID_MAXLEN] = PSK_DEFAULT_IDENTITY;
+static size_t psk_id_length = sizeof(PSK_DEFAULT_IDENTITY) - 1;
+static unsigned char psk_key[PSK_MAXLEN] = PSK_DEFAULT_KEY;
+static size_t psk_key_length = sizeof(PSK_DEFAULT_KEY) - 1;
+
+#ifdef __GNUC__
+#define UNUSED_PARAM __attribute__((unused))
+#else
+#define UNUSED_PARAM
+#endif /* __GNUC__ */
+
+/* This function is the "key store" for tinyDTLS. It is called to
+ * retrieve a key for the given identity within this particular
+ * session. */
+static int
+get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
+           const session_t *session UNUSED_PARAM,
+           dtls_credentials_type_t type,
+           const unsigned char *id, size_t id_len,
+           unsigned char *result, size_t result_length) {
+
+  switch (type) {
+  case DTLS_PSK_IDENTITY:
+    if (result_length < psk_id_length) {
+      dtls_warn("cannot set psk_identity -- buffer too small\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    memcpy(result, psk_id, psk_id_length);
+    return psk_id_length;
+  case DTLS_PSK_KEY:
+    if (id_len != psk_id_length || memcmp(psk_id, id, id_len) != 0) {
+      dtls_warn("PSK for unknown id requested, exiting\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
+    } else if (result_length < psk_key_length) {
+      dtls_warn("cannot set psk -- buffer too small\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    memcpy(result, psk_key, psk_key_length);
+    return psk_key_length;
+  default:
+    dtls_warn("unsupported request type: %d\n", type);
+  }
+
+  return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+}
+#endif /* DTLS_PSK */
+
+#ifdef DTLS_ECC
+static int
+get_ecdsa_key(struct dtls_context_t *ctx,
+             const session_t *session,
+             const dtls_ecdsa_key_t **result) {
+  static const dtls_ecdsa_key_t ecdsa_key = {
+    .curve = DTLS_ECDH_CURVE_SECP256R1,
+    .priv_key = ecdsa_priv_key,
+    .pub_key_x = ecdsa_pub_key_x,
+    .pub_key_y = ecdsa_pub_key_y
+  };
+
+  *result = &ecdsa_key;
+  return 0;
+}
+
+static int
+verify_ecdsa_key(struct dtls_context_t *ctx,
+                const session_t *session,
+                const unsigned char *other_pub_x,
+                const unsigned char *other_pub_y,
+                size_t key_size) {
+  return 0;
+}
+#endif /* DTLS_ECC */
+
+PROCESS(udp_server_process, "UDP server process");
+AUTOSTART_PROCESSES(&udp_server_process);
+/*---------------------------------------------------------------------------*/
+static void
+dtls_handle_read(dtls_context_t *ctx) {
+  static session_t session;
+
+  if(uip_newdata()) {
+    uip_ipaddr_copy(&session.addr, &UIP_IP_BUF->srcipaddr);
+    session.port = UIP_UDP_BUF->srcport;
+    session.size = sizeof(session.addr) + sizeof(session.port);
+
+    ((char *)uip_appdata)[uip_datalen()] = 0;
+    PRINTF("Client received message from ");
+    PRINT6ADDR(&session.addr);
+    PRINTF(":%d\n", uip_ntohs(session.port));
+
+    dtls_handle_message(ctx, &session, uip_appdata, uip_datalen());
+  }
+}
+/*---------------------------------------------------------------------------*/
+static void
+print_local_addresses(void)
+{
+  int i;
+  uint8_t state;
+
+  PRINTF("Client IPv6 addresses: ");
+  for(i = 0; i < UIP_DS6_ADDR_NB; i++) {
+    state = uip_ds6_if.addr_list[i].state;
+    if(uip_ds6_if.addr_list[i].isused &&
+       (state == ADDR_TENTATIVE || state == ADDR_PREFERRED)) {
+      PRINT6ADDR(&uip_ds6_if.addr_list[i].ipaddr);
+      PRINTF("\n");
+    }
+  }
+}
+
+static void
+set_connection_address(uip_ipaddr_t *ipaddr)
+{
+#define _QUOTEME(x) #x
+#define QUOTEME(x) _QUOTEME(x)
+#ifdef UDP_CONNECTION_ADDR
+  if(uiplib_ipaddrconv(QUOTEME(UDP_CONNECTION_ADDR), ipaddr) == 0) {
+    PRINTF("UDP client failed to parse address '%s'\n", QUOTEME(UDP_CONNECTION_ADDR));
+  }
+#elif UIP_CONF_ROUTER
+  uip_ip6addr(ipaddr,0xaaaa,0,0,0,0x0200,0x0000,0x0000,0x0001);
+#else
+  uip_ip6addr(ipaddr,0xfe80,0,0,0,0x6466,0x6666,0x6666,0x6666);
+#endif /* UDP_CONNECTION_ADDR */
+}
+
+void
+init_dtls(session_t *dst) {
+  static dtls_handler_t cb = {
+    .write = send_to_peer,
+    .read  = read_from_peer,
+    .event = NULL,
+#ifdef DTLS_PSK
+    .get_psk_info = get_psk_info,
+#endif /* DTLS_PSK */
+#ifdef DTLS_ECC
+    .get_ecdsa_key = get_ecdsa_key,
+    .verify_ecdsa_key = verify_ecdsa_key
+#endif /* DTLS_ECC */
+  };
+  PRINTF("DTLS client started\n");
+
+  print_local_addresses();
+
+  dst->size = sizeof(dst->addr) + sizeof(dst->port);
+  dst->port = UIP_HTONS(20220);
+
+  set_connection_address(&dst->addr);
+  client_conn = udp_new(&dst->addr, 0, NULL);
+  udp_bind(client_conn, dst->port);
+
+  PRINTF("set connection address to ");
+  PRINT6ADDR(&dst->addr);
+  PRINTF(":%d\n", uip_ntohs(dst->port));
+
+  dtls_set_log_level(DTLS_LOG_DEBUG);
+
+  dtls_context = dtls_new_context(client_conn);
+  if (dtls_context)
+    dtls_set_handler(dtls_context, &cb);
+}
+
+/*---------------------------------------------------------------------------*/
+PROCESS_THREAD(udp_server_process, ev, data)
+{
+  static int connected = 0;
+  static session_t dst;
+
+  PROCESS_BEGIN();
+
+  dtls_init();
+
+  init_dtls(&dst);
+  serial_line_init();
+
+  if (!dtls_context) {
+    dtls_emerg("cannot create context\n");
+    PROCESS_EXIT();
+  }
+
+  while(1) {
+    PROCESS_YIELD();
+    if(ev == tcpip_event) {
+      dtls_handle_read(dtls_context);
+    } else if (ev == serial_line_event_message) {
+      register size_t len = min(strlen(data), sizeof(buf) - buflen);
+      memcpy(buf + buflen, data, len);
+      buflen += len;
+      if (buflen < sizeof(buf) - 1)
+       buf[buflen++] = '\n';   /* serial event does not contain LF */
+    }
+
+    if (buflen) {
+      if (!connected)
+       connected = dtls_connect(dtls_context, &dst) >= 0;
+      
+      try_send(dtls_context, &dst);
+    }
+  }
+  
+  PROCESS_END();
+}
+/*---------------------------------------------------------------------------*/
diff --git a/extlibs/tinydtls/examples/contiki/dtls-server.c b/extlibs/tinydtls/examples/contiki/dtls-server.c
new file mode 100644 (file)
index 0000000..d9269a8
--- /dev/null
@@ -0,0 +1,332 @@
+/*
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the Contiki operating system.
+ *
+ */
+
+#include "contiki.h"
+#include "contiki-lib.h"
+#include "contiki-net.h"
+
+#if UIP_CONF_IPV6_RPL
+#include "net/rpl/rpl.h"
+#endif /* UIP_CONF_IPV6_RPL */
+
+#include <string.h>
+
+#include "tinydtls.h"
+
+#ifndef DEBUG
+#define DEBUG DEBUG_PRINT
+#endif
+#include "net/ip/uip-debug.h"
+
+#include "debug.h"
+#include "dtls.h"
+
+#ifdef ENABLE_POWERTRACE
+#include "powertrace.h"
+#endif
+
+#define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
+#define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
+
+#define MAX_PAYLOAD_LEN 120
+
+static struct uip_udp_conn *server_conn;
+
+static dtls_context_t *dtls_context;
+
+static const unsigned char ecdsa_priv_key[] = {
+                       0xD9, 0xE2, 0x70, 0x7A, 0x72, 0xDA, 0x6A, 0x05,
+                       0x04, 0x99, 0x5C, 0x86, 0xED, 0xDB, 0xE3, 0xEF,
+                       0xC7, 0xF1, 0xCD, 0x74, 0x83, 0x8F, 0x75, 0x70,
+                       0xC8, 0x07, 0x2D, 0x0A, 0x76, 0x26, 0x1B, 0xD4};
+
+static const unsigned char ecdsa_pub_key_x[] = {
+                       0xD0, 0x55, 0xEE, 0x14, 0x08, 0x4D, 0x6E, 0x06,
+                       0x15, 0x59, 0x9D, 0xB5, 0x83, 0x91, 0x3E, 0x4A,
+                       0x3E, 0x45, 0x26, 0xA2, 0x70, 0x4D, 0x61, 0xF2,
+                       0x7A, 0x4C, 0xCF, 0xBA, 0x97, 0x58, 0xEF, 0x9A};
+
+static const unsigned char ecdsa_pub_key_y[] = {
+                       0xB4, 0x18, 0xB6, 0x4A, 0xFE, 0x80, 0x30, 0xDA,
+                       0x1D, 0xDC, 0xF4, 0xF4, 0x2E, 0x2F, 0x26, 0x31,
+                       0xD0, 0x43, 0xB1, 0xFB, 0x03, 0xE2, 0x2F, 0x4D,
+                       0x17, 0xDE, 0x43, 0xF9, 0xF9, 0xAD, 0xEE, 0x70};
+
+static int
+read_from_peer(struct dtls_context_t *ctx, 
+              session_t *session, uint8 *data, size_t len) {
+  size_t i;
+  for (i = 0; i < len; i++)
+    PRINTF("%c", data[i]);
+
+  /* echo incoming application data */
+  dtls_write(ctx, session, data, len);
+  return 0;
+}
+
+static int
+send_to_peer(struct dtls_context_t *ctx, 
+            session_t *session, uint8 *data, size_t len) {
+
+  struct uip_udp_conn *conn = (struct uip_udp_conn *)dtls_get_app_data(ctx);
+
+  uip_ipaddr_copy(&conn->ripaddr, &session->addr);
+  conn->rport = session->port;
+
+  PRINTF("send to ");
+  PRINT6ADDR(&conn->ripaddr);
+  PRINTF(":%u\n", uip_ntohs(conn->rport));
+
+  uip_udp_packet_send(conn, data, len);
+
+  /* Restore server connection to allow data from any node */
+  memset(&conn->ripaddr, 0, sizeof(conn->ripaddr));
+  memset(&conn->rport, 0, sizeof(conn->rport));
+
+  return len;
+}
+
+#ifdef DTLS_PSK
+/* This function is the "key store" for tinyDTLS. It is called to
+ * retrieve a key for the given identity within this particular
+ * session. */
+static int
+get_psk_info(struct dtls_context_t *ctx, const session_t *session,
+            dtls_credentials_type_t type,
+            const unsigned char *id, size_t id_len,
+            unsigned char *result, size_t result_length) {
+
+  struct keymap_t {
+    unsigned char *id;
+    size_t id_length;
+    unsigned char *key;
+    size_t key_length;
+  } psk[3] = {
+    { (unsigned char *)"Client_identity", 15,
+      (unsigned char *)"secretPSK", 9 },
+    { (unsigned char *)"default identity", 16,
+      (unsigned char *)"\x11\x22\x33", 3 },
+    { (unsigned char *)"\0", 2,
+      (unsigned char *)"", 1 }
+  };
+
+  if (type != DTLS_PSK_KEY) {
+    return 0;
+  }
+
+  if (id) {
+    int i;
+    for (i = 0; i < sizeof(psk)/sizeof(struct keymap_t); i++) {
+      if (id_len == psk[i].id_length && memcmp(id, psk[i].id, id_len) == 0) {
+       if (result_length < psk[i].key_length) {
+         dtls_warn("buffer too small for PSK");
+         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+       }
+
+       memcpy(result, psk[i].key, psk[i].key_length);
+       return psk[i].key_length;
+      }
+    }
+  }
+
+  return dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
+}
+#endif /* DTLS_PSK */
+
+#ifdef DTLS_ECC
+static int
+get_ecdsa_key(struct dtls_context_t *ctx,
+             const session_t *session,
+             const dtls_ecdsa_key_t **result) {
+  static const dtls_ecdsa_key_t ecdsa_key = {
+    .curve = DTLS_ECDH_CURVE_SECP256R1,
+    .priv_key = ecdsa_priv_key,
+    .pub_key_x = ecdsa_pub_key_x,
+    .pub_key_y = ecdsa_pub_key_y
+  };
+
+  *result = &ecdsa_key;
+  return 0;
+}
+
+static int
+verify_ecdsa_key(struct dtls_context_t *ctx,
+                const session_t *session,
+                const unsigned char *other_pub_x,
+                const unsigned char *other_pub_y,
+                size_t key_size) {
+  return 0;
+}
+#endif /* DTLS_ECC */
+
+PROCESS(udp_server_process, "UDP server process");
+AUTOSTART_PROCESSES(&udp_server_process);
+/*---------------------------------------------------------------------------*/
+static void
+dtls_handle_read(dtls_context_t *ctx) {
+  session_t session;
+
+  if(uip_newdata()) {
+    uip_ipaddr_copy(&session.addr, &UIP_IP_BUF->srcipaddr);
+    session.port = UIP_UDP_BUF->srcport;
+    session.size = sizeof(session.addr) + sizeof(session.port);
+    
+    dtls_handle_message(ctx, &session, uip_appdata, uip_datalen());
+  }
+}
+/*---------------------------------------------------------------------------*/
+static void
+print_local_addresses(void)
+{
+  int i;
+  uint8_t state;
+
+  PRINTF("Server IPv6 addresses: \n");
+  for(i = 0; i < UIP_DS6_ADDR_NB; i++) {
+    state = uip_ds6_if.addr_list[i].state;
+    if(uip_ds6_if.addr_list[i].isused &&
+       (state == ADDR_TENTATIVE || state == ADDR_PREFERRED)) {
+      PRINT6ADDR(&uip_ds6_if.addr_list[i].ipaddr);
+      PRINTF("\n");
+    }
+  }
+}
+
+#if 0
+static void
+create_rpl_dag(uip_ipaddr_t *ipaddr)
+{
+  struct uip_ds6_addr *root_if;
+
+  root_if = uip_ds6_addr_lookup(ipaddr);
+  if(root_if != NULL) {
+    rpl_dag_t *dag;
+    uip_ipaddr_t prefix;
+    
+    rpl_set_root(RPL_DEFAULT_INSTANCE, ipaddr);
+    dag = rpl_get_any_dag();
+    uip_ip6addr(&prefix, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
+    rpl_set_prefix(dag, &prefix, 64);
+    PRINTF("created a new RPL dag\n");
+  } else {
+    PRINTF("failed to create a new RPL DAG\n");
+  }
+}
+#endif
+
+void
+init_dtls() {
+  static dtls_handler_t cb = {
+    .write = send_to_peer,
+    .read  = read_from_peer,
+    .event = NULL,
+#ifdef DTLS_PSK
+    .get_psk_info = get_psk_info,
+#endif /* DTLS_PSK */
+#ifdef DTLS_ECC
+    .get_ecdsa_key = get_ecdsa_key,
+    .verify_ecdsa_key = verify_ecdsa_key
+#endif /* DTLS_ECC */
+  };
+#if 0
+  uip_ipaddr_t ipaddr;
+  /* struct uip_ds6_addr *root_if; */
+#endif /* UIP_CONF_ROUTER */
+
+  PRINTF("DTLS server started\n");
+
+#if 0  /* TEST */
+  memset(&tmp_addr, 0, sizeof(rimeaddr_t));
+  if(get_eui64_from_eeprom(tmp_addr.u8));
+#if UIP_CONF_IPV6
+  memcpy(&uip_lladdr.addr, &tmp_addr.u8, 8);
+#endif
+#endif /* TEST */
+
+#if 0
+/*   uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); */
+/*   uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); */
+/*   uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF); */
+
+/*   create_rpl_dag(&ipaddr); */
+/* #else */
+  /* uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF); */
+
+  uip_ip6addr(&ipaddr, 0xaaaa, 0,0,0,0x0200,0,0,0x0003);
+  uip_ds6_addr_add(&ipaddr, 0, ADDR_MANUAL);
+
+  create_rpl_dag(&ipaddr);
+#endif /* UIP_CONF_ROUTER */
+
+  server_conn = udp_new(NULL, 0, NULL);
+  udp_bind(server_conn, UIP_HTONS(20220));
+
+  dtls_set_log_level(DTLS_LOG_DEBUG);
+
+  dtls_context = dtls_new_context(server_conn);
+  if (dtls_context)
+    dtls_set_handler(dtls_context, &cb);
+}
+
+/*---------------------------------------------------------------------------*/
+PROCESS_THREAD(udp_server_process, ev, data)
+{
+  PROCESS_BEGIN();
+
+  dtls_init();
+  init_dtls();
+
+  print_local_addresses();
+
+  if (!dtls_context) {
+    dtls_emerg("cannot create context\n");
+    PROCESS_EXIT();
+  }
+
+#ifdef ENABLE_POWERTRACE
+  powertrace_start(CLOCK_SECOND * 2); 
+#endif
+
+  while(1) {
+    PROCESS_WAIT_EVENT();
+    if(ev == tcpip_event) {
+      dtls_handle_read(dtls_context);
+    }
+#if 0
+    if (bytes_read > 0) {
+      /* dtls_handle_message(dtls_context, &the_session, readbuf, bytes_read); */
+      read_from_peer(dtls_context, &the_session, readbuf, bytes_read);
+    }
+    dtls_handle_message(ctx, &session, uip_appdata, bytes_read);
+#endif
+  }
+
+  PROCESS_END();
+}
+/*---------------------------------------------------------------------------*/
diff --git a/extlibs/tinydtls/global.h b/extlibs/tinydtls/global.h
new file mode 100644 (file)
index 0000000..f0977c8
--- /dev/null
@@ -0,0 +1,147 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef _DTLS_GLOBAL_H_
+#define _DTLS_GLOBAL_H_
+
+#include <stdlib.h>
+#include <sys/types.h>
+
+#include "tinydtls.h"
+
+#ifndef DTLSv12
+/* The current version of tinyDTLS supports DTLSv1.2 only. */
+#define DTLSv12 1
+#endif
+
+#ifndef WITH_SHA256
+/* The current version of tinyDTLS supports DTLSv1.2 with SHA256 PRF
+   only. */
+#define WITH_SHA256 1
+#endif
+
+/* Define our own types as at least uint32_t does not work on my amd64. */
+
+typedef unsigned char uint8;
+typedef unsigned char uint16[2];
+typedef unsigned char uint24[3];
+typedef unsigned char uint32[4];
+typedef unsigned char uint48[6];
+
+#ifndef DTLS_MAX_BUF
+/** Maximum size of DTLS message.
+    When Peers are sending bigger messages this causes problems. Californium
+    with ECDSA needs at least 220 */
+#ifdef WITH_CONTIKI
+#ifdef DTLS_ECC
+#define DTLS_MAX_BUF 200
+#else /* DTLS_ECC */
+#define DTLS_MAX_BUF 100
+#endif /* DTLS_ECC */
+#else /* WITH_CONTIKI */
+#define DTLS_MAX_BUF 1400
+#endif /* WITH_CONTIKI */
+#endif
+
+#ifndef DTLS_DEFAULT_MAX_RETRANSMIT
+/** Number of message retransmissions. */
+#define DTLS_DEFAULT_MAX_RETRANSMIT 7
+#endif
+
+/** Known cipher suites.*/
+typedef enum { 
+  TLS_NULL_WITH_NULL_NULL = 0x0000,   /**< NULL cipher  */
+  TLS_PSK_WITH_AES_128_CCM_8 = 0xC0A8, /**< see RFC 6655 */
+  TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xC0AE /**< see RFC 7251 */
+} dtls_cipher_t;
+
+/** Known compression suites.*/
+typedef enum {
+  TLS_COMPRESSION_NULL = 0x0000                /* NULL compression */
+} dtls_compression_t;
+
+#define TLS_EXT_ELLIPTIC_CURVES                10 /* see RFC 4492 */
+#define TLS_EXT_EC_POINT_FORMATS       11 /* see RFC 4492 */
+#define TLS_EXT_SIG_HASH_ALGO          13 /* see RFC 5246 */
+#define TLS_EXT_CLIENT_CERTIFICATE_TYPE        19 /* see RFC 7250 */
+#define TLS_EXT_SERVER_CERTIFICATE_TYPE        20 /* see RFC 7250 */
+#define TLS_EXT_ENCRYPT_THEN_MAC       22 /* see RFC 7366 */
+
+#define TLS_CERT_TYPE_RAW_PUBLIC_KEY   2 /* see RFC 7250 */
+
+#define TLS_EXT_ELLIPTIC_CURVES_SECP256R1      23 /* see RFC 4492 */
+
+#define TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED  0 /* see RFC 4492 */
+
+#define TLS_EC_CURVE_TYPE_NAMED_CURVE          3 /* see RFC 4492 */
+
+#define TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN 64 /* see RFC 4492 */
+
+#define TLS_EXT_SIG_HASH_ALGO_SHA256           4 /* see RFC 5246 */
+#define TLS_EXT_SIG_HASH_ALGO_ECDSA            3 /* see RFC 5246 */
+
+/** 
+ * XORs \p n bytes byte-by-byte starting at \p y to the memory area
+ * starting at \p x. */
+static inline void
+memxor(unsigned char *x, const unsigned char *y, size_t n) {
+  while(n--) {
+    *x ^= *y;
+    x++; y++;
+  }
+}
+
+/**
+ * Compares \p len bytes from @p a with @p b in constant time. This
+ * functions always traverses the entire length to prevent timing
+ * attacks.
+ *
+ * \param a Byte sequence to compare
+ * \param b Byte sequence to compare
+ * \param len Number of bytes to compare.
+ * \return \c 1 if \p a and \p b are equal, \c 0 otherwise.
+ */
+static inline int
+equals(unsigned char *a, unsigned char *b, size_t len) {
+  int result = 1;
+  while (len--) {
+    result &= (*a++ == *b++);
+  }
+  return result;
+}
+
+#ifdef HAVE_FLS
+#define dtls_fls(i) fls(i)
+#else
+static inline int 
+dtls_fls(unsigned int i) {
+  int n;
+  for (n = 0; i; n++)
+    i >>= 1;
+  return n;
+}
+#endif /* HAVE_FLS */
+
+#endif /* _DTLS_GLOBAL_H_ */
diff --git a/extlibs/tinydtls/hmac.c b/extlibs/tinydtls/hmac.c
new file mode 100644 (file)
index 0000000..0a9b8f7
--- /dev/null
@@ -0,0 +1,173 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "dtls_config.h"
+
+#ifdef HAVE_ASSERT_H
+#include <assert.h>
+#else
+#define assert(x)
+#endif
+
+#include "debug.h"
+#include "hmac.h"
+
+/* use malloc()/free() on platforms other than Contiki */
+#ifndef WITH_CONTIKI
+#include <stdlib.h>
+
+static inline dtls_hmac_context_t *
+dtls_hmac_context_new() {
+  return (dtls_hmac_context_t *)malloc(sizeof(dtls_hmac_context_t));
+}
+
+static inline void
+dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
+  free(ctx);
+}
+
+#else /* WITH_CONTIKI */
+#include "memb.h"
+MEMB(hmac_context_storage, dtls_hmac_context_t, DTLS_HASH_MAX);
+
+static inline dtls_hmac_context_t *
+dtls_hmac_context_new() {
+  return (dtls_hmac_context_t *)memb_alloc(&hmac_context_storage);
+}
+
+static inline void
+dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
+  memb_free(&hmac_context_storage, ctx);
+}
+
+void
+dtls_hmac_storage_init() {
+  memb_init(&hmac_context_storage);
+}
+#endif /* WITH_CONTIKI */
+
+void
+dtls_hmac_update(dtls_hmac_context_t *ctx,
+                const unsigned char *input, size_t ilen) {
+  assert(ctx);
+  dtls_hash_update(&ctx->data, input, ilen);
+}
+
+dtls_hmac_context_t *
+dtls_hmac_new(const unsigned char *key, size_t klen) {
+  dtls_hmac_context_t *ctx;
+
+  ctx = dtls_hmac_context_new();
+  if (ctx) 
+    dtls_hmac_init(ctx, key, klen);
+
+  return ctx;
+}
+
+void
+dtls_hmac_init(dtls_hmac_context_t *ctx, const unsigned char *key, size_t klen) {
+  int i;
+
+  assert(ctx);
+
+  memset(ctx, 0, sizeof(dtls_hmac_context_t));
+
+  if (klen > DTLS_HMAC_BLOCKSIZE) {
+    dtls_hash_init(&ctx->data);
+    dtls_hash_update(&ctx->data, key, klen);
+    dtls_hash_finalize(ctx->pad, &ctx->data);
+  } else
+    memcpy(ctx->pad, key, klen);
+
+  /* create ipad: */
+  for (i=0; i < DTLS_HMAC_BLOCKSIZE; ++i)
+    ctx->pad[i] ^= 0x36;
+
+  dtls_hash_init(&ctx->data);
+  dtls_hmac_update(ctx, ctx->pad, DTLS_HMAC_BLOCKSIZE);
+
+  /* create opad by xor-ing pad[i] with 0x36 ^ 0x5C: */
+  for (i=0; i < DTLS_HMAC_BLOCKSIZE; ++i)
+    ctx->pad[i] ^= 0x6A;
+}
+
+void
+dtls_hmac_free(dtls_hmac_context_t *ctx) {
+  if (ctx)
+    dtls_hmac_context_free(ctx);
+}
+
+int
+dtls_hmac_finalize(dtls_hmac_context_t *ctx, unsigned char *result) {
+  unsigned char buf[DTLS_HMAC_DIGEST_SIZE];
+  size_t len; 
+
+  assert(ctx);
+  assert(result);
+  
+  len = dtls_hash_finalize(buf, &ctx->data);
+
+  dtls_hash_init(&ctx->data);
+  dtls_hash_update(&ctx->data, ctx->pad, DTLS_HMAC_BLOCKSIZE);
+  dtls_hash_update(&ctx->data, buf, len);
+
+  len = dtls_hash_finalize(result, &ctx->data);
+
+  return len;
+}
+
+#ifdef HMAC_TEST
+#include <stdio.h>
+
+int main(int argc, char **argv) {
+  static unsigned char buf[DTLS_HMAC_DIGEST_SIZE];
+  size_t len, i;
+  dtls_hmac_context_t *ctx;
+
+  if (argc < 3) {
+    fprintf(stderr, "usage: %s key text", argv[0]);
+    return -1;
+  }
+
+  dtls_hmac_storage_init();
+  ctx = dtls_hmac_new(argv[1], strlen(argv[1]));
+  assert(ctx);
+  dtls_hmac_update(ctx, argv[2], strlen(argv[2]));
+  
+  len = dtls_hmac_finalize(ctx, buf);
+
+  for(i = 0; i < len; i++) 
+    printf("%02x", buf[i]);
+  printf("\n");
+
+  dtls_hmac_free(ctx);
+
+  return 0;
+}
+#endif
diff --git a/extlibs/tinydtls/hmac.h b/extlibs/tinydtls/hmac.h
new file mode 100644 (file)
index 0000000..d9c5e53
--- /dev/null
@@ -0,0 +1,154 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef _DTLS_HMAC_H_
+#define _DTLS_HMAC_H_
+
+#include <sys/types.h>
+
+#include "global.h"
+
+#ifdef WITH_SHA256
+/** Aaron D. Gifford's implementation of SHA256
+ *  see http://www.aarongifford.com/ */
+#include "sha2/sha2.h"
+
+typedef SHA256_CTX dtls_hash_ctx;
+typedef dtls_hash_ctx *dtls_hash_t;
+#define DTLS_HASH_CTX_SIZE sizeof(SHA256_CTX)
+
+static inline void
+dtls_hash_init(dtls_hash_t ctx) {
+  SHA256_Init((SHA256_CTX *)ctx);
+}
+
+static inline void 
+dtls_hash_update(dtls_hash_t ctx, const unsigned char *input, size_t len) {
+  SHA256_Update((SHA256_CTX *)ctx, input, len);
+}
+
+static inline size_t
+dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx) {
+  SHA256_Final(buf, (SHA256_CTX *)ctx);
+  return SHA256_DIGEST_LENGTH;
+}
+#endif /* WITH_SHA256 */
+
+#ifndef WITH_CONTIKI
+static inline void dtls_hmac_storage_init()
+{ }
+#else
+void dtls_hmac_storage_init();
+#endif
+
+/**
+ * \defgroup HMAC Keyed-Hash Message Authentication Code (HMAC)
+ * NIST Standard FIPS 198 describes the Keyed-Hash Message Authentication 
+ * Code (HMAC) which is used as hash function for the DTLS PRF.
+ * @{
+ */
+
+#define DTLS_HMAC_BLOCKSIZE   64       /**< size of hmac blocks */
+#define DTLS_HMAC_DIGEST_SIZE 32       /**< digest size (for SHA-256) */
+#define DTLS_HMAC_MAX         64       /**< max number of bytes in digest */
+
+/**
+ * List of known hash functions for use in dtls_hmac_init(). The
+ * identifiers are the same as the HashAlgorithm defined in 
+ * <a href="http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1"
+ * >Section 7.4.1.4.1 of RFC 5246</a>.
+ */
+typedef enum { 
+  HASH_NONE=0, HASH_MD5=1, HASH_SHA1=2, HASH_SHA224=3,
+  HASH_SHA256=4, HASH_SHA384=5, HASH_SHA512=6
+} dtls_hashfunc_t;
+
+/**
+ * Context for HMAC generation. This object is initialized with
+ * dtls_hmac_init() and must be passed to dtls_hmac_update() and
+ * dtls_hmac_finalize(). Once, finalized, the component \c H is
+ * invalid and must be initialized again with dtls_hmac_init() before
+ * the structure can be used again. 
+ */
+typedef struct {
+  unsigned char pad[DTLS_HMAC_BLOCKSIZE]; /**< ipad and opad storage */
+  dtls_hash_ctx data;                    /**< context for hash function */
+} dtls_hmac_context_t;
+
+/**
+ * Initializes an existing HMAC context. 
+ *
+ * @param ctx The HMAC context to initialize.
+ * @param key    The secret key.
+ * @param klen   The length of @p key.
+ */
+void dtls_hmac_init(dtls_hmac_context_t *ctx, const unsigned char *key, size_t klen);
+
+/**
+ * Allocates a new HMAC context \p ctx with the given secret key.
+ * This function returns \c 1 if \c ctx has been set correctly, or \c
+ * 0 or \c -1 otherwise. Note that this function allocates new storage
+ * that must be released by dtls_hmac_free().
+ *
+ * \param key    The secret key.
+ * \param klen   The length of \p key.
+ * \return A new dtls_hmac_context_t object or @c NULL on error
+ */
+dtls_hmac_context_t *dtls_hmac_new(const unsigned char *key, size_t klen);
+
+/**
+ * Releases the storage for @p ctx that has been allocated by
+ * dtls_hmac_new().
+ *
+ * @param ctx The dtls_hmac_context_t to free. 
+ */
+void dtls_hmac_free(dtls_hmac_context_t *ctx);
+
+/**
+ * Updates the HMAC context with data from \p input. 
+ * 
+ * \param ctx    The HMAC context.
+ * \param input  The input data.
+ * \param ilen   Size of \p input.
+ */
+void dtls_hmac_update(dtls_hmac_context_t *ctx,
+                     const unsigned char *input, size_t ilen);
+
+/** 
+ * Completes the HMAC generation and writes the result to the given
+ * output parameter \c result. The buffer must be large enough to hold
+ * the message digest created by the actual hash function. If in
+ * doubt, use \c DTLS_HMAC_MAX. The function returns the number of
+ * bytes written to \c result. 
+ *
+ * \param ctx    The HMAC context.
+ * \param result Output parameter where the MAC is written to.
+ * \return Length of the MAC written to \p result.
+ */
+int dtls_hmac_finalize(dtls_hmac_context_t *ctx, unsigned char *result);
+
+/**@}*/
+
+#endif /* _DTLS_HMAC_H_ */
diff --git a/extlibs/tinydtls/netq.c b/extlibs/tinydtls/netq.c
new file mode 100644 (file)
index 0000000..0a10a50
--- /dev/null
@@ -0,0 +1,140 @@
+/* netq.h -- Simple packet queue
+ *
+ * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * This file is part of the library tinyDTLS. Please see the file
+ * LICENSE for terms of use.
+ */
+
+#include "dtls_config.h"
+#include "debug.h"
+#include "netq.h"
+
+#ifdef HAVE_ASSERT_H
+#include <assert.h>
+#else
+#ifndef assert
+#warning "assertions are disabled"
+#  define assert(x)
+#endif
+#endif
+
+#include "t_list.h"
+
+#ifndef WITH_CONTIKI
+#include <stdlib.h>
+
+static inline netq_t *
+netq_malloc_node(size_t size) {
+  return (netq_t *)malloc(sizeof(netq_t) + size);
+}
+
+static inline void
+netq_free_node(netq_t *node) {
+  free(node);
+}
+
+/* FIXME: implement Contiki's list functions using utlist.h */
+
+#else /* WITH_CONTIKI */
+#include "memb.h"
+
+MEMB(netq_storage, netq_t, NETQ_MAXCNT);
+
+static inline netq_t *
+netq_malloc_node(size_t size) {
+  return (netq_t *)memb_alloc(&netq_storage);
+}
+
+static inline void
+netq_free_node(netq_t *node) {
+  memb_free(&netq_storage, node);
+}
+
+void
+netq_init() {
+  memb_init(&netq_storage);
+}
+#endif /* WITH_CONTIKI */
+
+int 
+netq_insert_node(list_t queue, netq_t *node) {
+  netq_t *p;
+
+  assert(queue);
+  assert(node);
+
+  p = (netq_t *)list_head(queue);
+  while(p && p->t <= node->t && list_item_next(p))
+    p = list_item_next(p);
+
+  if (p)
+    list_insert(queue, p, node);
+  else
+    list_push(queue, node);
+
+  return 1;
+}
+
+netq_t *
+netq_head(list_t queue) {
+  if (!queue)
+    return NULL;
+
+  return list_head(queue);
+}
+
+netq_t *
+netq_next(netq_t *p) {
+  if (!p)
+    return NULL;
+
+  return list_item_next(p);
+}
+
+void
+netq_remove(list_t queue, netq_t *p) {
+  if (!queue || !p)
+    return;
+
+  list_remove(queue, p);
+}
+
+netq_t *netq_pop_first(list_t queue) {
+  if (!queue)
+    return NULL;
+
+  return list_pop(queue);
+}
+
+netq_t *
+netq_node_new(size_t size) {
+  netq_t *node;
+  node = netq_malloc_node(size);
+
+#ifndef NDEBUG
+  if (!node)
+    dtls_warn("netq_node_new: malloc\n");
+#endif
+
+  if (node)
+    memset(node, 0, sizeof(netq_t));
+
+  return node;  
+}
+
+void 
+netq_node_free(netq_t *node) {
+  if (node)
+    netq_free_node(node);
+}
+
+void 
+netq_delete_all(list_t queue) {
+  netq_t *p;
+  if (queue) {
+    while((p = list_pop(queue)))
+      netq_free_node(p); 
+  }
+}
+
diff --git a/extlibs/tinydtls/netq.h b/extlibs/tinydtls/netq.h
new file mode 100644 (file)
index 0000000..a771b23
--- /dev/null
@@ -0,0 +1,103 @@
+/* netq.h -- Simple packet queue
+ *
+ * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * This file is part of the library tinyDTLS. Please see the file
+ * LICENSE for terms of use.
+ */
+
+#ifndef _DTLS_NETQ_H_
+#define _DTLS_NETQ_H_
+
+#include "tinydtls.h"
+#include "global.h"
+#include "dtls.h"
+#include "dtls_time.h"
+
+/**
+ * \defgroup netq Network Packet Queue
+ * The netq utility functions implement an ordered queue of data packets
+ * to send over the network and can also be used to queue received packets
+ * from the network.
+ * @{
+ */
+
+#ifndef NETQ_MAXCNT
+#ifdef DTLS_ECC
+#define NETQ_MAXCNT 5 /**< maximum number of elements in netq structure */
+#elif defined(DTLS_PSK)
+#define NETQ_MAXCNT 3 /**< maximum number of elements in netq structure */
+#endif
+#endif
+
+/** 
+ * Datagrams in the netq_t structure have a fixed maximum size of
+ * DTLS_MAX_BUF to simplify memory management on constrained nodes. */ 
+typedef unsigned char netq_packet_t[DTLS_MAX_BUF];
+
+typedef struct netq_t {
+  struct netq_t *next;
+
+  clock_time_t t;              /**< when to send PDU for the next time */
+  unsigned int timeout;                /**< randomized timeout value */
+
+  dtls_peer_t *peer;           /**< remote address */
+  uint16_t epoch;
+  uint8_t type;
+  unsigned char retransmit_cnt;        /**< retransmission counter, will be removed when zero */
+
+  size_t length;               /**< actual length of data */
+#ifndef WITH_CONTIKI
+  unsigned char data[];                /**< the datagram to send */
+#else
+  netq_packet_t data;          /**< the datagram to send */
+#endif
+} netq_t;
+
+#ifndef WITH_CONTIKI
+static inline void netq_init()
+{ }
+#else
+void netq_init();
+#endif
+
+/** 
+ * Adds a node to the given queue, ordered by their time-stamp t.
+ * This function returns @c 0 on error, or non-zero if @p node has
+ * been added successfully.
+ *
+ * @param queue A pointer to the queue head where @p node will be added.
+ * @param node  The new item to add.
+ * @return @c 0 on error, or non-zero if the new item was added.
+ */
+int netq_insert_node(list_t queue, netq_t *node);
+
+/** Destroys specified node and releases any memory that was allocated
+ * for the associated datagram. */
+void netq_node_free(netq_t *node);
+
+/** Removes all items from given queue and frees the allocated storage */
+void netq_delete_all(list_t queue);
+
+/** Creates a new node suitable for adding to a netq_t queue. */
+netq_t *netq_node_new(size_t size);
+
+/**
+ * Returns a pointer to the first item in given queue or NULL if
+ * empty. 
+ */
+netq_t *netq_head(list_t queue);
+
+netq_t *netq_next(netq_t *p);
+void netq_remove(list_t queue, netq_t *p);
+
+/**
+ * Removes the first item in given queue and returns a pointer to the
+ * removed element. If queue is empty when netq_pop_first() is called,
+ * this function returns NULL.
+ */
+netq_t *netq_pop_first(list_t queue);
+
+/**@}*/
+
+#endif /* _DTLS_NETQ_H_ */
diff --git a/extlibs/tinydtls/numeric.h b/extlibs/tinydtls/numeric.h
new file mode 100644 (file)
index 0000000..e319f5b
--- /dev/null
@@ -0,0 +1,142 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef _DTLS_NUMERIC_H_
+#define _DTLS_NUMERIC_H_
+
+#include <stdint.h>
+
+#ifndef min
+#define min(A,B) ((A) <= (B) ? (A) : (B))
+#endif
+
+#ifndef max
+#define max(A,B) ((A) < (B) ? (B) : (A))
+#endif
+
+/* this one is for consistency... */
+static inline int dtls_int_to_uint8(unsigned char *field, uint8_t value)
+{
+  field[0] = value & 0xff;
+  return 1;
+}
+
+static inline int dtls_int_to_uint16(unsigned char *field, uint16_t value)
+{
+  field[0] = (value >> 8) & 0xff;
+  field[1] = value & 0xff;
+  return 2;
+}
+
+static inline int dtls_int_to_uint24(unsigned char *field, uint32_t value)
+{
+  field[0] = (value >> 16) & 0xff;
+  field[1] = (value >> 8) & 0xff;
+  field[2] = value & 0xff;
+  return 3;
+}
+
+static inline int dtls_int_to_uint32(unsigned char *field, uint32_t value)
+{
+  field[0] = (value >> 24) & 0xff;
+  field[1] = (value >> 16) & 0xff;
+  field[2] = (value >> 8) & 0xff;
+  field[3] = value & 0xff;
+  return 4;
+}
+
+static inline int dtls_int_to_uint48(unsigned char *field, uint64_t value)
+{
+  field[0] = (value >> 40) & 0xff;
+  field[1] = (value >> 32) & 0xff;
+  field[2] = (value >> 24) & 0xff;
+  field[3] = (value >> 16) & 0xff;
+  field[4] = (value >> 8) & 0xff;
+  field[5] = value & 0xff;
+  return 6;
+}
+
+static inline int dtls_int_to_uint64(unsigned char *field, uint64_t value)
+{
+  field[0] = (value >> 56) & 0xff;
+  field[1] = (value >> 48) & 0xff;
+  field[2] = (value >> 40) & 0xff;
+  field[3] = (value >> 32) & 0xff;
+  field[4] = (value >> 24) & 0xff;
+  field[5] = (value >> 16) & 0xff;
+  field[6] = (value >> 8) & 0xff;
+  field[7] = value & 0xff;
+  return 8;
+}
+
+static inline uint8_t dtls_uint8_to_int(const unsigned char *field)
+{
+  return (uint8_t)field[0];
+}
+
+static inline uint16_t dtls_uint16_to_int(const unsigned char *field)
+{
+  return ((uint16_t)field[0] << 8)
+        | (uint16_t)field[1];
+}
+
+static inline uint32_t dtls_uint24_to_int(const unsigned char *field)
+{
+  return ((uint32_t)field[0] << 16)
+        | ((uint32_t)field[1] << 8)
+        | (uint32_t)field[2];
+}
+
+static inline uint32_t dtls_uint32_to_int(const unsigned char *field)
+{
+  return ((uint32_t)field[0] << 24)
+        | ((uint32_t)field[1] << 16)
+        | ((uint32_t)field[2] << 8)
+        | (uint32_t)field[3];
+}
+
+static inline uint64_t dtls_uint48_to_int(const unsigned char *field)
+{
+  return ((uint64_t)field[0] << 40)
+        | ((uint64_t)field[1] << 32)
+        | ((uint64_t)field[2] << 24)
+        | ((uint64_t)field[3] << 16)
+        | ((uint64_t)field[4] << 8)
+        | (uint64_t)field[5];
+}
+
+static inline uint64_t dtls_uint64_to_int(const unsigned char *field)
+{
+  return ((uint64_t)field[0] << 56)
+        | ((uint64_t)field[1] << 48)
+        | ((uint64_t)field[2] << 40)
+        | ((uint64_t)field[3] << 32)
+        | ((uint64_t)field[4] << 24)
+        | ((uint64_t)field[5] << 16)
+        | ((uint64_t)field[6] << 8)
+        | (uint64_t)field[7];
+}
+
+#endif /* _DTLS_NUMERIC_H_ */
diff --git a/extlibs/tinydtls/peer.c b/extlibs/tinydtls/peer.c
new file mode 100644 (file)
index 0000000..8f2876c
--- /dev/null
@@ -0,0 +1,90 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "global.h"
+#include "peer.h"
+#include "debug.h"
+
+#ifndef WITH_CONTIKI
+void peer_init()
+{
+}
+
+static inline dtls_peer_t *
+dtls_malloc_peer() {
+  return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
+}
+
+void
+dtls_free_peer(dtls_peer_t *peer) {
+  dtls_handshake_free(peer->handshake_params);
+  dtls_security_free(peer->security_params[0]);
+  dtls_security_free(peer->security_params[1]);
+  free(peer);
+}
+#else /* WITH_CONTIKI */
+
+#include "memb.h"
+MEMB(peer_storage, dtls_peer_t, DTLS_PEER_MAX);
+
+void
+peer_init() {
+  memb_init(&peer_storage);
+}
+
+static inline dtls_peer_t *
+dtls_malloc_peer() {
+  return memb_alloc(&peer_storage);
+}
+
+void
+dtls_free_peer(dtls_peer_t *peer) {
+  dtls_handshake_free(peer->handshake_params);
+  dtls_security_free(peer->security_params[0]);
+  dtls_security_free(peer->security_params[1]);
+  memb_free(&peer_storage, peer);
+}
+#endif /* WITH_CONTIKI */
+
+dtls_peer_t *
+dtls_new_peer(const session_t *session) {
+  dtls_peer_t *peer;
+
+  peer = dtls_malloc_peer();
+  if (peer) {
+    memset(peer, 0, sizeof(dtls_peer_t));
+    memcpy(&peer->session, session, sizeof(session_t));
+    peer->security_params[0] = dtls_security_new();
+
+    if (!peer->security_params[0]) {
+      dtls_free_peer(peer);
+      return NULL;
+    }
+
+    dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "dtls_new_peer", session);
+  }
+
+  return peer;
+}
diff --git a/extlibs/tinydtls/peer.h b/extlibs/tinydtls/peer.h
new file mode 100644 (file)
index 0000000..af7c205
--- /dev/null
@@ -0,0 +1,148 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file peer.h
+ * @brief information about peers in a DTLS session
+ */
+
+#ifndef _DTLS_PEER_H_
+#define _DTLS_PEER_H_
+
+#include <sys/types.h>
+
+#include "tinydtls.h"
+#include "global.h"
+#include "session.h"
+
+#include "state.h"
+#include "crypto.h"
+
+#ifndef WITH_CONTIKI
+#include "uthash.h"
+#endif /* WITH_CONTIKI */
+
+typedef enum { DTLS_CLIENT=0, DTLS_SERVER } dtls_peer_type;
+
+/** 
+ * Holds security parameters, local state and the transport address
+ * for each peer. */
+typedef struct dtls_peer_t {
+#ifndef WITH_CONTIKI
+  UT_hash_handle hh;
+#else /* WITH_CONTIKI */
+  struct dtls_peer_t *next;
+#endif /* WITH_CONTIKI */
+
+  session_t session;        /**< peer address and local interface */
+
+  dtls_peer_type role;       /**< denotes if this host is DTLS_CLIENT or DTLS_SERVER */
+  dtls_state_t state;        /**< DTLS engine state */
+
+  dtls_security_parameters_t *security_params[2];
+  dtls_handshake_parameters_t *handshake_params;
+} dtls_peer_t;
+
+static inline dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
+{
+  if (peer->security_params[0] && peer->security_params[0]->epoch == epoch) {
+    return peer->security_params[0];
+  } else if (peer->security_params[1] && peer->security_params[1]->epoch == epoch) {
+    return peer->security_params[1];
+  } else {
+    return NULL;
+  }
+}
+
+static inline dtls_security_parameters_t *dtls_security_params(dtls_peer_t *peer)
+{
+  return peer->security_params[0];
+}
+
+static inline dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t *peer)
+{
+  if (peer->security_params[1])
+    dtls_security_free(peer->security_params[1]);
+
+  peer->security_params[1] = dtls_security_new();
+  if (!peer->security_params[1]) {
+    return NULL;
+  }
+  peer->security_params[1]->epoch = peer->security_params[0]->epoch + 1;
+  return peer->security_params[1];
+}
+
+static inline void dtls_security_params_free_other(dtls_peer_t *peer)
+{
+  dtls_security_parameters_t * security0 = peer->security_params[0];
+  dtls_security_parameters_t * security1 = peer->security_params[1];
+
+  if (!security0 || !security1 || security0->epoch < security1->epoch)
+    return;
+
+  dtls_security_free(security1);
+  peer->security_params[1] = NULL;
+}
+
+static inline void dtls_security_params_switch(dtls_peer_t *peer)
+{
+  dtls_security_parameters_t * security = peer->security_params[1];
+
+  peer->security_params[1] = peer->security_params[0];
+  peer->security_params[0] = security;
+}
+
+void peer_init();
+
+/**
+ * Creates a new peer for given @p session. The current configuration
+ * is initialized with the cipher suite TLS_NULL_WITH_NULL_NULL (i.e.
+ * no security at all). This function returns a pointer to the new
+ * peer or NULL on error. The caller is responsible for releasing the
+ * storage allocated for this peer using dtls_free_peer().
+ *
+ * @param session  The remote peer's address and local interface index.
+ * @return A pointer to a newly created and initialized peer object
+ * or NULL on error.
+ */
+dtls_peer_t *dtls_new_peer(const session_t *session);
+
+/** Releases the storage allocated to @p peer. */
+void dtls_free_peer(dtls_peer_t *peer);
+
+/** Returns the current state of @p peer. */
+static inline dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
+  return peer->state;
+}
+
+/**
+ * Checks if given @p peer is connected. This function returns
+ * @c 1 if connected, or @c 0 otherwise.
+ */
+static inline int dtls_peer_is_connected(const dtls_peer_t *peer) {
+  return peer->state == DTLS_STATE_CONNECTED;
+}
+
+#endif /* _DTLS_PEER_H_ */
diff --git a/extlibs/tinydtls/platform-specific/Makefile.in b/extlibs/tinydtls/platform-specific/Makefile.in
new file mode 100644 (file)
index 0000000..6b30d21
--- /dev/null
@@ -0,0 +1,27 @@
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+
+top_builddir = @top_builddir@
+
+THIS=platform-specific
+DISTDIR?=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
+FILES:=Makefile.in $(wildcard *.h)
+
+clean:
+
+distclean:     clean
+       @rm -rf $(DISTDIR)
+       @rm -f *~ 
+
+dist:  
+       test -d $(DISTDIR)/$(THIS) || mkdir $(DISTDIR)/$(THIS)
+       cp -r $(FILES) $(DISTDIR)/$(THIS)
+
+# this directory contains no installation candidates
+install:
+       :
diff --git a/extlibs/tinydtls/platform-specific/config-cc2538dk.h b/extlibs/tinydtls/platform-specific/config-cc2538dk.h
new file mode 100644 (file)
index 0000000..38bc85e
--- /dev/null
@@ -0,0 +1,2 @@
+#define BYTE_ORDER 1234
+#define HAVE_ASSERT_H 1
diff --git a/extlibs/tinydtls/platform-specific/config-econotag.h b/extlibs/tinydtls/platform-specific/config-econotag.h
new file mode 100644 (file)
index 0000000..38bc85e
--- /dev/null
@@ -0,0 +1,2 @@
+#define BYTE_ORDER 1234
+#define HAVE_ASSERT_H 1
diff --git a/extlibs/tinydtls/platform-specific/config-minimal-net.h b/extlibs/tinydtls/platform-specific/config-minimal-net.h
new file mode 100644 (file)
index 0000000..547a1b6
--- /dev/null
@@ -0,0 +1 @@
+#define HAVE_ASSERT_H 1
diff --git a/extlibs/tinydtls/platform-specific/config-sky.h b/extlibs/tinydtls/platform-specific/config-sky.h
new file mode 100644 (file)
index 0000000..f49ff3b
--- /dev/null
@@ -0,0 +1,3 @@
+#define BYTE_ORDER 1234
+#define HAVE_ASSERT_H 1
+typedef int ssize_t;
diff --git a/extlibs/tinydtls/platform-specific/config-wismote.h b/extlibs/tinydtls/platform-specific/config-wismote.h
new file mode 100644 (file)
index 0000000..547a1b6
--- /dev/null
@@ -0,0 +1 @@
+#define HAVE_ASSERT_H 1
diff --git a/extlibs/tinydtls/prng.h b/extlibs/tinydtls/prng.h
new file mode 100644 (file)
index 0000000..48c1f95
--- /dev/null
@@ -0,0 +1,82 @@
+/* prng.h -- Pseudo Random Numbers
+ *
+ * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * This file is part of the library tinydtls. Please see
+ * README for terms of use. 
+ */
+
+/** 
+ * @file prng.h
+ * @brief Pseudo Random Numbers
+ */
+
+#ifndef _DTLS_PRNG_H_
+#define _DTLS_PRNG_H_
+
+#include "tinydtls.h"
+
+/** 
+ * @defgroup prng Pseudo Random Numbers
+ * @{
+ */
+
+#ifndef WITH_CONTIKI
+#include <stdlib.h>
+
+/**
+ * Fills \p buf with \p len random bytes. This is the default
+ * implementation for prng().  You might want to change prng() to use
+ * a better PRNG on your specific platform.
+ */
+static inline int
+dtls_prng(unsigned char *buf, size_t len) {
+  while (len--)
+    *buf++ = rand() & 0xFF;
+  return 1;
+}
+
+static inline void
+dtls_prng_init(unsigned short seed) {
+       srand(seed);
+}
+#else /* WITH_CONTIKI */
+#include <string.h>
+#include "random.h"
+
+#ifdef HAVE_PRNG
+static inline int
+dtls_prng(unsigned char *buf, size_t len)
+{
+       return contiki_prng_impl(buf, len);
+}
+#else
+/**
+ * Fills \p buf with \p len random bytes. This is the default
+ * implementation for prng().  You might want to change prng() to use
+ * a better PRNG on your specific platform.
+ */
+static inline int
+dtls_prng(unsigned char *buf, size_t len) {
+  unsigned short v = random_rand();
+  while (len > sizeof(v)) {
+    memcpy(buf, &v, sizeof(v));
+    len -= sizeof(v);
+    buf += sizeof(v);
+    v = random_rand();
+  }
+
+  memcpy(buf, &v, len);
+  return 1;
+}
+#endif /* HAVE_PRNG */
+
+static inline void
+dtls_prng_init(unsigned short seed) {
+       random_init(seed);
+}
+#endif /* WITH_CONTIKI */
+
+/** @} */
+
+#endif /* _DTLS_PRNG_H_ */
diff --git a/extlibs/tinydtls/session.c b/extlibs/tinydtls/session.c
new file mode 100644 (file)
index 0000000..9acf565
--- /dev/null
@@ -0,0 +1,83 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "dtls_config.h"
+#include "session.h"
+
+#ifdef HAVE_ASSERT_H
+#include <assert.h>
+#else
+#ifndef assert
+#warning "assertions are disabled"
+#  define assert(x)
+#endif
+#endif
+
+#ifdef WITH_CONTIKI
+#define _dtls_address_equals_impl(A,B)                         \
+  ((A)->size == (B)->size                                      \
+   && (A)->port == (B)->port                                   \
+   && uip_ipaddr_cmp(&((A)->addr),&((B)->addr))                        \
+   && (A)->ifindex == (B)->ifindex)
+
+#else /* WITH_CONTIKI */
+
+static inline int 
+_dtls_address_equals_impl(const session_t *a,
+                         const session_t *b) {
+  if (a->ifindex != b->ifindex ||
+      a->size != b->size || a->addr.sa.sa_family != b->addr.sa.sa_family)
+    return 0;
+  
+  /* need to compare only relevant parts of sockaddr_in6 */
+ switch (a->addr.sa.sa_family) {
+ case AF_INET:
+   return 
+     a->addr.sin.sin_port == b->addr.sin.sin_port && 
+     memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr, 
+           sizeof(struct in_addr)) == 0;
+ case AF_INET6:
+   return a->addr.sin6.sin6_port == b->addr.sin6.sin6_port && 
+     memcmp(&a->addr.sin6.sin6_addr, &b->addr.sin6.sin6_addr, 
+           sizeof(struct in6_addr)) == 0;
+ default: /* fall through and signal error */
+   ;
+ }
+ return 0;
+}
+#endif /* WITH_CONTIKI */
+
+void
+dtls_session_init(session_t *sess) {
+  assert(sess);
+  memset(sess, 0, sizeof(session_t));
+  sess->size = sizeof(sess->addr);
+}
+
+int
+dtls_session_equals(const session_t *a, const session_t *b) {
+  assert(a); assert(b);
+  return _dtls_address_equals_impl(a, b);
+}
diff --git a/extlibs/tinydtls/session.h b/extlibs/tinydtls/session.h
new file mode 100644 (file)
index 0000000..61b5661
--- /dev/null
@@ -0,0 +1,76 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef _DTLS_SESSION_H_
+#define _DTLS_SESSION_H_
+
+#include <string.h>
+
+#include "tinydtls.h"
+#include "global.h"
+
+#ifdef WITH_CONTIKI
+#include "ip/uip.h"
+typedef struct {
+  unsigned char size;
+  uip_ipaddr_t addr;
+  unsigned short port;
+  int ifindex;
+} session_t;
+
+#else /* WITH_CONTIKI */
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+typedef struct {
+  socklen_t size;              /**< size of addr */
+  union {
+    struct sockaddr     sa;
+    struct sockaddr_storage st;
+    struct sockaddr_in  sin;
+    struct sockaddr_in6 sin6;
+  } addr;
+  uint8_t ifindex;
+} session_t;
+#endif /* WITH_CONTIKI */
+
+/** 
+ * Resets the given session_t object @p sess to its default
+ * values.  In particular, the member rlen must be initialized to the
+ * available size for storing addresses.
+ * 
+ * @param sess The session_t object to initialize.
+ */
+void dtls_session_init(session_t *sess);
+
+/**
+ * Compares the given session objects. This function returns @c 0
+ * when @p a and @p b differ, @c 1 otherwise.
+ */
+int dtls_session_equals(const session_t *a, const session_t *b);
+
+#endif /* _DTLS_SESSION_H_ */
diff --git a/extlibs/tinydtls/sha2/Makefile.in b/extlibs/tinydtls/sha2/Makefile.in
new file mode 100644 (file)
index 0000000..85ce9ce
--- /dev/null
@@ -0,0 +1,78 @@
+# Makefile for tinydtls
+#
+# Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use, copy,
+# modify, merge, publish, distribute, sublicense, and/or sell copies
+# of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+
+abs_builddir = @abs_builddir@
+top_builddir = @top_builddir@
+top_srcdir:= @top_srcdir@
+
+SOURCES:= sha2.c
+HEADERS:=sha2.h
+OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
+CPPFLAGS=@CPPFLAGS@ -I$(top_srcdir)
+CFLAGS=-Wall -std=c99 -pedantic @CFLAGS@
+LDLIBS=@LIBS@
+FILES:=Makefile.in $(SOURCES) $(HEADERS) README sha2prog.c sha2speed.c sha2test.pl 
+DISTDIR=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
+
+.PHONY: all dirs clean install dist distclean .gitignore doc
+
+.SUFFIXES:
+.SUFFIXES:      .c .o
+
+all:
+
+check: 
+       echo DISTDIR: $(DISTDIR)
+       echo top_builddir: $(top_builddir)
+
+clean:
+       @rm -f $(PROGRAMS) main.o $(LIB) $(OBJECTS)
+       for dir in $(SUBDIRS); do \
+               $(MAKE) -C $$dir clean ; \
+       done
+
+distclean:     clean
+       @rm -rf $(DISTDIR)
+       @rm -f *~ $(DISTDIR).tar.gz
+
+dist:  $(FILES)
+       test -d $(DISTDIR)/sha2 || mkdir $(DISTDIR)/sha2
+       cp -p $(FILES) $(DISTDIR)/sha2
+       test -d $(DISTDIR)/sha2/testvectors || mkdir $(DISTDIR)/sha2/testvectors
+       cp -pr testvectors $(DISTDIR)/sha2/testvectors
+
+install:       $(HEADERS)
+       test -d $(includedir)/sha2 || mkdir -p $(includedir)/sha2
+       $(install) $(HEADERS) $(includedir)/sha2
+
+.gitignore:
+       echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@
diff --git a/extlibs/tinydtls/sha2/README b/extlibs/tinydtls/sha2/README
new file mode 100644 (file)
index 0000000..95e57f3
--- /dev/null
@@ -0,0 +1,272 @@
+VERSION:
+
+This is version 1.0 RELEASE
+
+While this is my "release" version, due to lack of additional
+official test vectors against which to verify this implementation's
+correctness, beware that there may be implementation bugs.  Also,
+it has not yet been tested on very many other architectures,
+big-endian machines in particular.
+
+
+LICENSE:
+
+This implementation is released freely under an open-source BSD
+license which appears at the top of each source code file.
+
+
+WHAT IT IS:
+
+The files sha2.h and sha2.c implement the SHA-256, SHA-384, and SHA-512
+hash algorithms as described in the PDF document found at the following
+web address:
+
+  http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf
+
+The interface is similar to the interface to SHA-1 found in the OpenSSL
+library.
+
+The file sha2prog.c is a simple program that accepts input from either
+STDIN or reads one or more files specified on the command line, and then
+generates the specified hash (either SHA-256, SHA-384, SHA-512, or any
+combination thereof, including all three at once).
+
+
+LIMITATIONS:
+
+This implementation has several limitations:
+
+ * Input data is only accepted in octet-length increments.  No sub-byte
+   data is handled.  The NIST document describes how to handle sub-byte
+   input data, but for ease of implementation this version will only
+   accept message data in multiples of bytes.
+ * This implementation utilizes 64-bit integer data types.  If your
+   system and compiler does not have a 64-bit integer data type, this
+   implementation will not work.
+ * Because of the use of 64-bit operations, many 32-bit architectures
+   that do have 64-bit data types but do operations most efficiently
+   on 32-bit words, this implementation may be slower than an
+   implementation designed to use only 32-bit words (emulating the
+   64-bit operations).
+ * On platforms with 128-bit integer data types, the SHA-384 and SHA-512
+   bit counters used by this implementation might be better off using
+   the 128-bit type instead of simulating it with two 64-bit integers.
+ * This implementation was written in C in hopes of portability and for
+   the fun of it during my spare time.  It is probably not the most
+   efficient or fastest C implementation.  I welcome suggestions,
+   however, that suggest ways to speed things up without breaking
+   portability.  I also welcome suggestions to improve portability.
+ * As mentioned above, this code has NOT been thoroughly tested.
+   This is perhaps the most severe limitation.
+
+
+BEFORE YOU COMPILE (OPTIONS):
+
+Each of the options described below may either be defined in the sha2.h
+header file (or in the sha2.c file in some cases), or on the command
+line at compile time if your compiler supports such things.  For
+example:
+
+  #define SHA2_USE_INTTYPES_H
+  #define SHA2_UNROLL_TRANSFORM
+
+Or:
+
+  cc -c -DSHA2_UNROLL_TRANSFORM sha2.c
+  cc -c -DBYTE_ORDER=4321 -DBIG_ENDIAN=4321 sha2.c
+
+Here are the available options.  Read on below for a description of
+each one:
+
+  SHA2_USE_INTTYPES_H
+  SHA2_USE_MEMSET_MEMCPY/SHA2_USE_BZERO_BCOPY
+  SHA2_UNROLL_TRANSFORM
+  BYTE_ORDER (LITTLE_ENDIAN/BIG_ENDIAN)
+
+* SHA2_USE_INTTYPES_H option:
+By default, this code uses u_intXX_t data types for 8 bit, 32 bit, and
+64 bit unsigned integer type definitions.  Most BSD systems define these,
+as does Linux.  However, some (like Compaq's Tru64 Unix) may instead
+use uintXX_t data types as defined by recent ANSI C standards and as
+included in the inttypes.h header file.  Those wanting to use inttypes.h
+need to define this either in sha.h or at compile time.
+
+On those systems where NEITHER definitions are available, you will need
+to edit both sha2.h and sha2.c and define things by hand in the appropriate
+sections.
+
+* BYTE_ORDER definitions:
+This code assumes that BYTE_ORDER will be defined by the system during
+compile to either equal LITTLE_ENDIAN or BIG_ENDIAN.  If your system
+does not define these, you may need to define them by hand in the sha.c
+file according to the byte ordering conventions of your system.
+
+* SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY
+The code in sha2.c can use either memset()/memcpy() for memory block
+operations, or bzero()/mcopy().  If you define neither of these, the
+code will default to memset()/memcpy().  You can define either at the
+command line or in sha2.h or in sha2.c.
+
+* SHA2_UNROLL_TRANSFORM
+By defining this either on the command line or in sha2.h or sha2.c,
+the code will use macros to partially "unroll" the SHA transform
+function.  This usually generates bigger executables.  It CAN (but
+not necessarily WILL) generate faster code when you tell your compiler
+to optimize things.  For example, on the FreeBSD and Linux x86 systems
+I tested things on (using gcc), when I optimized with just -O2 and
+unrolled the transform, the hash transform was faster by 15-30%.  On
+these same systems, if I did NO optimization, the unrolled transform
+was SLOWER, much slower (I'm guessing because the code was breaking
+the cache, but I'm not sure).  Your mileage may vary.
+
+
+PORTABILITY:
+
+The code in sha2.c and sha2.h is intended to be portable.  It may
+require that you do a few #definitions in the .h file.  I've successfully
+compiled and tested the sha2.c and sha2.h code on Apple's OS X (on
+a PPC), FreeBSD 4.1.1 on Intel, Linux on Intel, FreeBSD on the Alpha,
+and even under Windows98SE using Metrowerks C.  The utility/example
+programs (sha2prog.c, sha2test.c, and sha2speed.c) will very likely
+have more trouble in portability since they do I/O.
+
+To get sha2.c/sha2.h working under Windows, I had to define
+SHA2_USE_INTTYPES_H, BYTE_ORDER, LITTLE_ENDIAN, and had to comment
+out the include of <sys/types.h> in sha2.h.  With a bit more work
+I got the test program to run and verified that all the test
+cases passed.
+
+
+SUGGESTIONS/BUG FIXES:
+
+If you make changes to get it working on other architectures, if you fix
+any bugs, or if you make changes that improve this implementation's
+efficiency that would be relatively portable and you're willing to release
+your changes under the same license, please send them to me for possible
+inclusion in future versions.
+
+If you know where I can find some additional test vectors, please let me
+know.
+
+
+CHANGE HISTORY:
+
+0.8 to 0.9     - Fixed spelling errors, changed to u_intXX_t type usage,
+                 removed names from prototypes, added prototypes to sha2.c,
+                 and a few things I can't recall.
+
+0.9 to 0.9.5   - Add a new define in sha2.c that permits one to compile
+                 it to either use memcpy()/memset() or bcopy()/bzero()
+                 for memory block copying and zeroing.  Added support
+                 for unrolled SHA-256/384/512 transform loops.  Just
+                 compile with SHA2_UNROLL_TRANSFORM to enable.  It takes
+                 longer to compile, but I hope it is a bit faster.  I
+                 need to do some test to see whether or not it is. Oh,
+                 in sha2.c, you either need to define SHA2_USE_BZERO_BCOPY
+                 or SHA2_USE_MEMSET_MEMCPY to choose which way you want
+                 to compile.  *Whew*  It's amazing how quickly something
+                 simple starts to grow more complex even in the span of
+                 just a few hours.  I didn't really intend to do this much.
+0.9.5 to 0.9.6  - Added a test program (sha2test) which tests against several
+                  known test vectors.  WARNING: Some of the test output
+                  hashes are NOT from NIST's documentation and are the
+                  output of this implementation and so may be incorrect.
+0.9.6 to 0.9.7  - Fixed a bug that could cause invalid output in certain
+                 cases and added an assumed scenario where zero-length
+                 data is hashed.  Also changed the rotation macros to use
+                 a temporary variable as this reduces the number of operations.
+                 When data is fed in blocks of the right length, copying of
+                 data is reduced in this version.  Added SHAYXZ_Data()
+                 functions for ease of hashing a set of data.  Added another
+                 file sha2speed.c for doing speed testing.  Added another test
+                 vector with a larger data size (16KB).  Fixed u_intXX_t and
+                 uintXX_t handling by adding a define for SHA2_USE_INTTYPES_H
+                 as well as made a few other minor changes to get rid of
+                 warnings when compiling on Compaq's Tru64 Unix.
+0.9.7 to 0.9.8  - The bug fix in 0.9.7 was incomplete and in some cases made
+                  things worse.  I believe that 0.9.8 fixes the bug completely
+                  so that output is correct.  I cannot verify this, however,
+                  because of the lack of test vectors against which to do such
+                  verification.  All versions correctly matched the very few
+                  NIST-provided vectors, but unfortunately the bug only
+                  appeared in longer message data sets.
+0.9.8 to 0.9.9  - Fixed some really bad typos and mistakes on my part that
+                  only affected big-endian systems.  I didn't have direct
+                  access for testing before this version.  Thanks to
+                  Lucas Marshall for giving me access to his OS X system.
+0.9.9 to 1.0.0b1  Added a few more test samples and made a few changes to
+                  make things easier compiling on several other platforms.
+                  Also I experimented with alternate macro definitions
+                  in the SHA2_UNROLL_TRANSFORM version (see sha2.slower.c)
+                  and eliminated the T1 temporary variable (the compiler
+                  would of course still use internal temporary storage
+                  during expression evaluation, but I'd hoped the compiler
+                  would be more efficient), but unfortunately under FreeBSD
+                  4.1.1-STABLE on an x86 platform, the change slowed things
+                  down.
+1.0.0b1 to 1.0 RELEASE  Fixed an off-by-one implementation bug that affected
+                  SHA-256 when hashed data length L = 55 + 64 * X where X is
+                  either zero or a positive integer, and another (basically
+                  the same bug) bug in SHA-384 and SHA-512 that showed up when
+                  hashed data lengths L = 111 + 128 * X.  Thanks to Rogier
+                 van de Pol for sending me test data that revealed the bug.
+                  The fix was very simple (just two tiny changes).  Also,
+                  I finally put the files into RCS so future changes will be
+                  easier to manage.  The sha2prog.c file was rewritten to
+                  be more useful to me, and I got rid of the old C testing
+                  program and now use a perl script with a subdirectory full
+                  of test data.  It's a more flexible test system.
+
+
+LATEST VERSION:
+
+The latest version and documentation (if any ;) should always be available
+on the web at:
+
+  http://www.aarongifford.com/computers/sha.html
+
+
+CONTACT ME:
+
+I can be reached via email at:
+
+  Aaron Gifford   <m e @ a a r o n g i f f o r d . c o m>
+
+Please don't send support questions.  I don't have the time to answer and
+they'll probably be ignored.  Bug fixes, or patches that add something useful
+will be gratefully accepted, however.
+
+If you use this implementation, I would enjoy getting a brief email message
+letting me know who you are and what use to which it is being put.  There
+is no requirement to do so.  I just think it would be fun.
+
+
+EXAMPLES:
+
+Here's an example of compiling and using the sha2 program (in this example
+I build it using the unrolled transform version with -O2 optimizations),
+and then running the perl testing script:
+
+  cc -O2 -DSHA2_UNROLL_TRANSFORM -Wall -o sha2 sha2prog.c sha2.c
+  % ./sha2test.pl
+
+  [most of the perl script output deleted for brevity]
+
+  ===== RESULTS (18 VECTOR DATA FILES HASHED) =====
+
+  HASH TYPE       NO. OF TESTS    PASSED  FAILED
+  ---------       ------------    ------  ------
+  SHA-256                   18        18       0
+  SHA-384                   18        18       0
+  SHA-512                   18        18       0
+  ----------------------------------------------
+  TOTAL:                    54        54       0
+
+  NO ERRORS!  ALL TESTS WERE SUCCESSFUL!
+
+  ALL TEST VECTORS PASSED!
+
+That's all folks!  Have fun!
+
+Aaron out.
+
diff --git a/extlibs/tinydtls/sha2/sha2.c b/extlibs/tinydtls/sha2/sha2.c
new file mode 100644 (file)
index 0000000..2578f17
--- /dev/null
@@ -0,0 +1,1101 @@
+/*
+ * FILE:       sha2.c
+ * AUTHOR:     Aaron D. Gifford - http://www.aarongifford.com/
+ * 
+ * Copyright (c) 2000-2001, Aaron D. Gifford
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the copyright holder nor the names of contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $Id: sha2.c,v 1.1 2001/11/08 00:01:51 adg Exp adg $
+ */
+
+#include "tinydtls.h"
+#include "dtls_config.h"
+#include <string.h>    /* memcpy()/memset() or bcopy()/bzero() */
+#ifdef HAVE_ASSERT_H
+#include <assert.h>    /* assert() */
+#else
+#ifndef assert
+#warning "assertions are disabled"
+#  define assert(x)
+#endif
+#endif
+#include "sha2.h"
+
+/*
+ * ASSERT NOTE:
+ * Some sanity checking code is included using assert().  On my FreeBSD
+ * system, this additional code can be removed by compiling with NDEBUG
+ * defined.  Check your own systems manpage on assert() to see how to
+ * compile WITHOUT the sanity checking code on your system.
+ *
+ * UNROLLED TRANSFORM LOOP NOTE:
+ * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform
+ * loop version for the hash transform rounds (defined using macros
+ * later in this file).  Either define on the command line, for example:
+ *
+ *   cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c
+ *
+ * or define below:
+ *
+ *   #define SHA2_UNROLL_TRANSFORM
+ *
+ */
+
+
+/*** SHA-256/384/512 Machine Architecture Definitions *****************/
+/*
+ * BYTE_ORDER NOTE:
+ *
+ * Please make sure that your system defines BYTE_ORDER.  If your
+ * architecture is little-endian, make sure it also defines
+ * LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are
+ * equivilent.
+ *
+ * If your system does not define the above, then you can do so by
+ * hand like this:
+ *
+ *   #define LITTLE_ENDIAN 1234
+ *   #define BIG_ENDIAN    4321
+ *
+ * And for little-endian machines, add:
+ *
+ *   #define BYTE_ORDER LITTLE_ENDIAN 
+ *
+ * Or for big-endian machines:
+ *
+ *   #define BYTE_ORDER BIG_ENDIAN
+ *
+ * The FreeBSD machine this was written on defines BYTE_ORDER
+ * appropriately by including <sys/types.h> (which in turn includes
+ * <machine/endian.h> where the appropriate definitions are actually
+ * made).
+ */
+
+/* bergmann: define LITTLE_ENDIAN and BIG_ENDIAN to ease autoconf: */
+#ifndef LITTLE_ENDIAN
+#define LITTLE_ENDIAN 1234
+#endif
+#ifndef BIG_ENDIAN
+#define BIG_ENDIAN 4321
+#endif
+
+#ifndef BYTE_ORDER
+#  if defined(WORDS_BIGENDIAN) || (defined(AC_APPLE_UNIVERSAL_BUILD) && defined(__BIG_ENDIAN__))
+#    define BYTE_ORDER BIG_ENDIAN
+#  else /* WORDS_BIGENDIAN */
+#    define BYTE_ORDER LITTLE_ENDIAN
+#  endif
+#endif
+
+#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
+#error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN
+#endif
+
+/*
+ * Define the followingsha2_* types to types of the correct length on
+ * the native archtecture.   Most BSD systems and Linux define u_intXX_t
+ * types.  Machines with very recent ANSI C headers, can use the
+ * uintXX_t definintions from inttypes.h by defining SHA2_USE_INTTYPES_H
+ * during compile or in the sha.h header file.
+ *
+ * Machines that support neither u_intXX_t nor inttypes.h's uintXX_t
+ * will need to define these three typedefs below (and the appropriate
+ * ones in sha.h too) by hand according to their system architecture.
+ *
+ * Thank you, Jun-ichiro itojun Hagino, for suggesting using u_intXX_t
+ * types and pointing out recent ANSI C support for uintXX_t in inttypes.h.
+ */
+#ifdef SHA2_USE_INTTYPES_H
+
+typedef uint8_t  sha2_byte;    /* Exactly 1 byte */
+typedef uint32_t sha2_word32;  /* Exactly 4 bytes */
+typedef uint64_t sha2_word64;  /* Exactly 8 bytes */
+
+#else /* SHA2_USE_INTTYPES_H */
+
+typedef u_int8_t  sha2_byte;   /* Exactly 1 byte */
+typedef u_int32_t sha2_word32; /* Exactly 4 bytes */
+typedef u_int64_t sha2_word64; /* Exactly 8 bytes */
+
+#endif /* SHA2_USE_INTTYPES_H */
+
+
+/*** SHA-256/384/512 Various Length Definitions ***********************/
+/* NOTE: Most of these are in sha2.h */
+#define SHA256_SHORT_BLOCK_LENGTH      (SHA256_BLOCK_LENGTH - 8)
+#define SHA384_SHORT_BLOCK_LENGTH      (SHA384_BLOCK_LENGTH - 16)
+#define SHA512_SHORT_BLOCK_LENGTH      (SHA512_BLOCK_LENGTH - 16)
+
+
+/*** ENDIAN REVERSAL MACROS *******************************************/
+#if BYTE_ORDER == LITTLE_ENDIAN
+#define REVERSE32(w,x) { \
+       sha2_word32 tmp = (w); \
+       tmp = (tmp >> 16) | (tmp << 16); \
+       (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \
+}
+#define REVERSE64(w,x) { \
+       sha2_word64 tmp = (w); \
+       tmp = (tmp >> 32) | (tmp << 32); \
+       tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \
+             ((tmp & 0x00ff00ff00ff00ffULL) << 8); \
+       (x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \
+             ((tmp & 0x0000ffff0000ffffULL) << 16); \
+}
+#endif /* BYTE_ORDER == LITTLE_ENDIAN */
+
+/*
+ * Macro for incrementally adding the unsigned 64-bit integer n to the
+ * unsigned 128-bit integer (represented using a two-element array of
+ * 64-bit words):
+ */
+#define ADDINC128(w,n) { \
+       (w)[0] += (sha2_word64)(n); \
+       if ((w)[0] < (n)) { \
+               (w)[1]++; \
+       } \
+}
+
+/*
+ * Macros for copying blocks of memory and for zeroing out ranges
+ * of memory.  Using these macros makes it easy to switch from
+ * using memset()/memcpy() and using bzero()/bcopy().
+ *
+ * Please define either SHA2_USE_MEMSET_MEMCPY or define
+ * SHA2_USE_BZERO_BCOPY depending on which function set you
+ * choose to use:
+ */
+#if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
+/* Default to memset()/memcpy() if no option is specified */
+#define        SHA2_USE_MEMSET_MEMCPY  1
+#endif
+#if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
+/* Abort with an error if BOTH options are defined */
+#error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
+#endif
+
+#ifdef SHA2_USE_MEMSET_MEMCPY
+#define MEMSET_BZERO(p,l)      memset((p), 0, (l))
+#define MEMCPY_BCOPY(d,s,l)    memcpy((d), (s), (l))
+#endif
+#ifdef SHA2_USE_BZERO_BCOPY
+#define MEMSET_BZERO(p,l)      bzero((p), (l))
+#define MEMCPY_BCOPY(d,s,l)    bcopy((s), (d), (l))
+#endif
+
+
+/*** THE SIX LOGICAL FUNCTIONS ****************************************/
+/*
+ * Bit shifting and rotation (used by the six SHA-XYZ logical functions:
+ *
+ *   NOTE:  The naming of R and S appears backwards here (R is a SHIFT and
+ *   S is a ROTATION) because the SHA-256/384/512 description document
+ *   (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this
+ *   same "backwards" definition.
+ */
+/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
+#define R(b,x)                 ((x) >> (b))
+/* 32-bit Rotate-right (used in SHA-256): */
+#define S32(b,x)       (((x) >> (b)) | ((x) << (32 - (b))))
+/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
+#define S64(b,x)       (((x) >> (b)) | ((x) << (64 - (b))))
+
+/* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */
+#define Ch(x,y,z)      (((x) & (y)) ^ ((~(x)) & (z)))
+#define Maj(x,y,z)     (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
+
+/* Four of six logical functions used in SHA-256: */
+#define Sigma0_256(x)  (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
+#define Sigma1_256(x)  (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
+#define sigma0_256(x)  (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))
+#define sigma1_256(x)  (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))
+
+/* Four of six logical functions used in SHA-384 and SHA-512: */
+#define Sigma0_512(x)  (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x)))
+#define Sigma1_512(x)  (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x)))
+#define sigma0_512(x)  (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7,   (x)))
+#define sigma1_512(x)  (S64(19, (x)) ^ S64(61, (x)) ^ R( 6,   (x)))
+
+/*** INTERNAL FUNCTION PROTOTYPES *************************************/
+/* NOTE: These should not be accessed directly from outside this
+ * library -- they are intended for private internal visibility/use
+ * only.
+ */
+void SHA512_Last(SHA512_CTX*);
+void SHA256_Transform(SHA256_CTX*, const sha2_word32*);
+void SHA512_Transform(SHA512_CTX*, const sha2_word64*);
+
+#ifdef WITH_SHA256
+/*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
+/* Hash constant words K for SHA-256: */
+const static sha2_word32 K256[64] = {
+       0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL,
+       0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
+       0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL,
+       0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
+       0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
+       0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
+       0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL,
+       0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
+       0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL,
+       0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
+       0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL,
+       0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
+       0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL,
+       0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
+       0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
+       0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
+};
+
+/* Initial hash value H for SHA-256: */
+const static sha2_word32 sha256_initial_hash_value[8] = {
+       0x6a09e667UL,
+       0xbb67ae85UL,
+       0x3c6ef372UL,
+       0xa54ff53aUL,
+       0x510e527fUL,
+       0x9b05688cUL,
+       0x1f83d9abUL,
+       0x5be0cd19UL
+};
+#endif
+
+#if defined(WITH_SHA384) || defined(WITH_SHA512)
+/* Hash constant words K for SHA-384 and SHA-512: */
+const static sha2_word64 K512[80] = {
+       0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
+       0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
+       0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
+       0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
+       0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
+       0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
+       0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
+       0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
+       0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
+       0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
+       0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
+       0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
+       0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
+       0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
+       0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
+       0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
+       0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
+       0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
+       0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
+       0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
+       0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
+       0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
+       0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
+       0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
+       0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
+       0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
+       0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
+       0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
+       0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
+       0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
+       0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
+       0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
+       0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
+       0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
+       0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
+       0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
+       0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
+       0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
+       0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
+       0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
+};
+#endif
+
+#ifdef WITH_SHA384
+/* Initial hash value H for SHA-384 */
+const static sha2_word64 sha384_initial_hash_value[8] = {
+       0xcbbb9d5dc1059ed8ULL,
+       0x629a292a367cd507ULL,
+       0x9159015a3070dd17ULL,
+       0x152fecd8f70e5939ULL,
+       0x67332667ffc00b31ULL,
+       0x8eb44a8768581511ULL,
+       0xdb0c2e0d64f98fa7ULL,
+       0x47b5481dbefa4fa4ULL
+};
+#endif
+
+#ifdef WITH_SHA512
+/* Initial hash value H for SHA-512 */
+const static sha2_word64 sha512_initial_hash_value[8] = {
+       0x6a09e667f3bcc908ULL,
+       0xbb67ae8584caa73bULL,
+       0x3c6ef372fe94f82bULL,
+       0xa54ff53a5f1d36f1ULL,
+       0x510e527fade682d1ULL,
+       0x9b05688c2b3e6c1fULL,
+       0x1f83d9abfb41bd6bULL,
+       0x5be0cd19137e2179ULL
+};
+#endif
+
+/*
+ * Constant used by SHA256/384/512_End() functions for converting the
+ * digest to a readable hexadecimal character string:
+ */
+static const char *sha2_hex_digits = "0123456789abcdef";
+
+
+/*** SHA-256: *********************************************************/
+#ifdef WITH_SHA256
+void SHA256_Init(SHA256_CTX* context) {
+       if (context == (SHA256_CTX*)0) {
+               return;
+       }
+       MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH);
+       MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH);
+       context->bitcount = 0;
+}
+
+#ifdef SHA2_UNROLL_TRANSFORM
+
+/* Unrolled SHA-256 round macros: */
+
+#if BYTE_ORDER == LITTLE_ENDIAN
+
+#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h)      \
+       REVERSE32(*data++, W256[j]); \
+       T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
+             K256[j] + W256[j]; \
+       (d) += T1; \
+       (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
+       j++
+
+
+#else /* BYTE_ORDER == LITTLE_ENDIAN */
+
+#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h)      \
+       T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
+            K256[j] + (W256[j] = *data++); \
+       (d) += T1; \
+       (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
+       j++
+
+#endif /* BYTE_ORDER == LITTLE_ENDIAN */
+
+#define ROUND256(a,b,c,d,e,f,g,h)      \
+       s0 = W256[(j+1)&0x0f]; \
+       s0 = sigma0_256(s0); \
+       s1 = W256[(j+14)&0x0f]; \
+       s1 = sigma1_256(s1); \
+       T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
+            (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
+       (d) += T1; \
+       (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
+       j++
+
+void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
+       sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
+       sha2_word32     T1, *W256;
+       int             j;
+
+       W256 = (sha2_word32*)context->buffer;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+               /* Rounds 0 to 15 (unrolled): */
+               ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
+               ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
+               ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
+               ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
+               ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
+               ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
+               ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
+               ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
+       } while (j < 16);
+
+       /* Now for the remaining rounds to 64: */
+       do {
+               ROUND256(a,b,c,d,e,f,g,h);
+               ROUND256(h,a,b,c,d,e,f,g);
+               ROUND256(g,h,a,b,c,d,e,f);
+               ROUND256(f,g,h,a,b,c,d,e);
+               ROUND256(e,f,g,h,a,b,c,d);
+               ROUND256(d,e,f,g,h,a,b,c);
+               ROUND256(c,d,e,f,g,h,a,b);
+               ROUND256(b,c,d,e,f,g,h,a);
+       } while (j < 64);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = 0;
+}
+
+#else /* SHA2_UNROLL_TRANSFORM */
+
+void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
+       sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
+       sha2_word32     T1, T2, *W256;
+       int             j;
+
+       W256 = (sha2_word32*)context->buffer;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+#if BYTE_ORDER == LITTLE_ENDIAN
+               /* Copy data while converting to host byte order */
+               REVERSE32(*data++,W256[j]);
+               /* Apply the SHA-256 compression function to update a..h */
+               T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
+#else /* BYTE_ORDER == LITTLE_ENDIAN */
+               /* Apply the SHA-256 compression function to update a..h with copy */
+               T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++);
+#endif /* BYTE_ORDER == LITTLE_ENDIAN */
+               T2 = Sigma0_256(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 16);
+
+       do {
+               /* Part of the message block expansion: */
+               s0 = W256[(j+1)&0x0f];
+               s0 = sigma0_256(s0);
+               s1 = W256[(j+14)&0x0f]; 
+               s1 = sigma1_256(s1);
+
+               /* Apply the SHA-256 compression function to update a..h */
+               T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + 
+                    (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
+               T2 = Sigma0_256(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 64);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = T2 = 0;
+}
+
+#endif /* SHA2_UNROLL_TRANSFORM */
+
+void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
+       unsigned int    freespace, usedspace;
+
+       if (len == 0) {
+               /* Calling with no data is valid - we do nothing */
+               return;
+       }
+
+       /* Sanity check: */
+       assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0);
+
+       usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
+       if (usedspace > 0) {
+               /* Calculate how much free space is available in the buffer */
+               freespace = SHA256_BLOCK_LENGTH - usedspace;
+
+               if (len >= freespace) {
+                       /* Fill the buffer completely and process it */
+                       MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
+                       context->bitcount += freespace << 3;
+                       len -= freespace;
+                       data += freespace;
+                       SHA256_Transform(context, (sha2_word32*)context->buffer);
+               } else {
+                       /* The buffer is not yet full */
+                       MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
+                       context->bitcount += len << 3;
+                       /* Clean up: */
+                       usedspace = freespace = 0;
+                       return;
+               }
+       }
+       while (len >= SHA256_BLOCK_LENGTH) {
+               /* Process as many complete blocks as we can */
+               SHA256_Transform(context, (sha2_word32*)data);
+               context->bitcount += SHA256_BLOCK_LENGTH << 3;
+               len -= SHA256_BLOCK_LENGTH;
+               data += SHA256_BLOCK_LENGTH;
+       }
+       if (len > 0) {
+               /* There's left-overs, so save 'em */
+               MEMCPY_BCOPY(context->buffer, data, len);
+               context->bitcount += len << 3;
+       }
+       /* Clean up: */
+       usedspace = freespace = 0;
+}
+
+void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
+       sha2_word32     *d = (sha2_word32*)digest;
+       unsigned int    usedspace;
+
+       /* Sanity check: */
+       assert(context != (SHA256_CTX*)0);
+
+       /* If no digest buffer is passed, we don't bother doing this: */
+       if (digest != (sha2_byte*)0) {
+               usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
+#if BYTE_ORDER == LITTLE_ENDIAN
+               /* Convert FROM host byte order */
+               REVERSE64(context->bitcount,context->bitcount);
+#endif
+               if (usedspace > 0) {
+                       /* Begin padding with a 1 bit: */
+                       context->buffer[usedspace++] = 0x80;
+
+                       if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) {
+                               /* Set-up for the last transform: */
+                               MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace);
+                       } else {
+                               if (usedspace < SHA256_BLOCK_LENGTH) {
+                                       MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace);
+                               }
+                               /* Do second-to-last transform: */
+                               SHA256_Transform(context, (sha2_word32*)context->buffer);
+
+                               /* And set-up for the last transform: */
+                               MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
+                       }
+               } else {
+                       /* Set-up for the last transform: */
+                       MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
+
+                       /* Begin padding with a 1 bit: */
+                       *context->buffer = 0x80;
+               }
+               /* Set the bit count: */
+               *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount;
+
+               /* Final transform: */
+               SHA256_Transform(context, (sha2_word32*)context->buffer);
+
+#if BYTE_ORDER == LITTLE_ENDIAN
+               {
+                       /* Convert TO host byte order */
+                       int     j;
+                       for (j = 0; j < 8; j++) {
+                               REVERSE32(context->state[j],context->state[j]);
+                               *d++ = context->state[j];
+                       }
+               }
+#else
+               MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH);
+#endif
+       }
+
+       /* Clean up state data: */
+       MEMSET_BZERO(context, sizeof(*context));
+       usedspace = 0;
+}
+
+char *SHA256_End(SHA256_CTX* context, char buffer[]) {
+       sha2_byte       digest[SHA256_DIGEST_LENGTH], *d = digest;
+       int             i;
+
+       /* Sanity check: */
+       assert(context != (SHA256_CTX*)0);
+
+       if (buffer != (char*)0) {
+               SHA256_Final(digest, context);
+
+               for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
+                       *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
+                       *buffer++ = sha2_hex_digits[*d & 0x0f];
+                       d++;
+               }
+               *buffer = (char)0;
+       } else {
+               MEMSET_BZERO(context, sizeof(*context));
+       }
+       MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH);
+       return buffer;
+}
+
+char* SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) {
+       SHA256_CTX      context;
+
+       SHA256_Init(&context);
+       SHA256_Update(&context, data, len);
+       return SHA256_End(&context, digest);
+}
+#endif
+
+/*** SHA-512: *********************************************************/
+#ifdef WITH_SHA512
+void SHA512_Init(SHA512_CTX* context) {
+       if (context == (SHA512_CTX*)0) {
+               return;
+       }
+       MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH);
+       MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH);
+       context->bitcount[0] = context->bitcount[1] =  0;
+}
+
+#ifdef SHA2_UNROLL_TRANSFORM
+
+/* Unrolled SHA-512 round macros: */
+#if BYTE_ORDER == LITTLE_ENDIAN
+
+#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h)      \
+       REVERSE64(*data++, W512[j]); \
+       T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
+             K512[j] + W512[j]; \
+       (d) += T1, \
+       (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \
+       j++
+
+
+#else /* BYTE_ORDER == LITTLE_ENDIAN */
+
+#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h)      \
+       T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
+             K512[j] + (W512[j] = *data++); \
+       (d) += T1; \
+       (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
+       j++
+
+#endif /* BYTE_ORDER == LITTLE_ENDIAN */
+
+#define ROUND512(a,b,c,d,e,f,g,h)      \
+       s0 = W512[(j+1)&0x0f]; \
+       s0 = sigma0_512(s0); \
+       s1 = W512[(j+14)&0x0f]; \
+       s1 = sigma1_512(s1); \
+       T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \
+             (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \
+       (d) += T1; \
+       (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
+       j++
+
+void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
+       sha2_word64     a, b, c, d, e, f, g, h, s0, s1;
+       sha2_word64     T1, *W512 = (sha2_word64*)context->buffer;
+       int             j;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+               ROUND512_0_TO_15(a,b,c,d,e,f,g,h);
+               ROUND512_0_TO_15(h,a,b,c,d,e,f,g);
+               ROUND512_0_TO_15(g,h,a,b,c,d,e,f);
+               ROUND512_0_TO_15(f,g,h,a,b,c,d,e);
+               ROUND512_0_TO_15(e,f,g,h,a,b,c,d);
+               ROUND512_0_TO_15(d,e,f,g,h,a,b,c);
+               ROUND512_0_TO_15(c,d,e,f,g,h,a,b);
+               ROUND512_0_TO_15(b,c,d,e,f,g,h,a);
+       } while (j < 16);
+
+       /* Now for the remaining rounds up to 79: */
+       do {
+               ROUND512(a,b,c,d,e,f,g,h);
+               ROUND512(h,a,b,c,d,e,f,g);
+               ROUND512(g,h,a,b,c,d,e,f);
+               ROUND512(f,g,h,a,b,c,d,e);
+               ROUND512(e,f,g,h,a,b,c,d);
+               ROUND512(d,e,f,g,h,a,b,c);
+               ROUND512(c,d,e,f,g,h,a,b);
+               ROUND512(b,c,d,e,f,g,h,a);
+       } while (j < 80);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = 0;
+}
+
+#else /* SHA2_UNROLL_TRANSFORM */
+
+void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) {
+       sha2_word64     a, b, c, d, e, f, g, h, s0, s1;
+       sha2_word64     T1, T2, *W512 = (sha2_word64*)context->buffer;
+       int             j;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+#if BYTE_ORDER == LITTLE_ENDIAN
+               /* Convert TO host byte order */
+               REVERSE64(*data++, W512[j]);
+               /* Apply the SHA-512 compression function to update a..h */
+               T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
+#else /* BYTE_ORDER == LITTLE_ENDIAN */
+               /* Apply the SHA-512 compression function to update a..h with copy */
+               T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
+#endif /* BYTE_ORDER == LITTLE_ENDIAN */
+               T2 = Sigma0_512(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 16);
+
+       do {
+               /* Part of the message block expansion: */
+               s0 = W512[(j+1)&0x0f];
+               s0 = sigma0_512(s0);
+               s1 = W512[(j+14)&0x0f];
+               s1 =  sigma1_512(s1);
+
+               /* Apply the SHA-512 compression function to update a..h */
+               T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
+                    (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
+               T2 = Sigma0_512(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 80);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = T2 = 0;
+}
+
+#endif /* SHA2_UNROLL_TRANSFORM */
+
+void SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) {
+       unsigned int    freespace, usedspace;
+
+       if (len == 0) {
+               /* Calling with no data is valid - we do nothing */
+               return;
+       }
+
+       /* Sanity check: */
+       assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0);
+
+       usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
+       if (usedspace > 0) {
+               /* Calculate how much free space is available in the buffer */
+               freespace = SHA512_BLOCK_LENGTH - usedspace;
+
+               if (len >= freespace) {
+                       /* Fill the buffer completely and process it */
+                       MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
+                       ADDINC128(context->bitcount, freespace << 3);
+                       len -= freespace;
+                       data += freespace;
+                       SHA512_Transform(context, (sha2_word64*)context->buffer);
+               } else {
+                       /* The buffer is not yet full */
+                       MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
+                       ADDINC128(context->bitcount, len << 3);
+                       /* Clean up: */
+                       usedspace = freespace = 0;
+                       return;
+               }
+       }
+       while (len >= SHA512_BLOCK_LENGTH) {
+               /* Process as many complete blocks as we can */
+               SHA512_Transform(context, (sha2_word64*)data);
+               ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
+               len -= SHA512_BLOCK_LENGTH;
+               data += SHA512_BLOCK_LENGTH;
+       }
+       if (len > 0) {
+               /* There's left-overs, so save 'em */
+               MEMCPY_BCOPY(context->buffer, data, len);
+               ADDINC128(context->bitcount, len << 3);
+       }
+       /* Clean up: */
+       usedspace = freespace = 0;
+}
+
+void SHA512_Last(SHA512_CTX* context) {
+       unsigned int    usedspace;
+
+       usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
+#if BYTE_ORDER == LITTLE_ENDIAN
+       /* Convert FROM host byte order */
+       REVERSE64(context->bitcount[0],context->bitcount[0]);
+       REVERSE64(context->bitcount[1],context->bitcount[1]);
+#endif
+       if (usedspace > 0) {
+               /* Begin padding with a 1 bit: */
+               context->buffer[usedspace++] = 0x80;
+
+               if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) {
+                       /* Set-up for the last transform: */
+                       MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace);
+               } else {
+                       if (usedspace < SHA512_BLOCK_LENGTH) {
+                               MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace);
+                       }
+                       /* Do second-to-last transform: */
+                       SHA512_Transform(context, (sha2_word64*)context->buffer);
+
+                       /* And set-up for the last transform: */
+                       MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2);
+               }
+       } else {
+               /* Prepare for final transform: */
+               MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH);
+
+               /* Begin padding with a 1 bit: */
+               *context->buffer = 0x80;
+       }
+       /* Store the length of input data (in bits): */
+       *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1];
+       *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0];
+
+       /* Final transform: */
+       SHA512_Transform(context, (sha2_word64*)context->buffer);
+}
+
+void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
+       sha2_word64     *d = (sha2_word64*)digest;
+
+       /* Sanity check: */
+       assert(context != (SHA512_CTX*)0);
+
+       /* If no digest buffer is passed, we don't bother doing this: */
+       if (digest != (sha2_byte*)0) {
+               SHA512_Last(context);
+
+               /* Save the hash data for output: */
+#if BYTE_ORDER == LITTLE_ENDIAN
+               {
+                       /* Convert TO host byte order */
+                       int     j;
+                       for (j = 0; j < 8; j++) {
+                               REVERSE64(context->state[j],context->state[j]);
+                               *d++ = context->state[j];
+                       }
+               }
+#else
+               MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH);
+#endif
+       }
+
+       /* Zero out state data */
+       MEMSET_BZERO(context, sizeof(context));
+}
+
+char *SHA512_End(SHA512_CTX* context, char buffer[]) {
+       sha2_byte       digest[SHA512_DIGEST_LENGTH], *d = digest;
+       int             i;
+
+       /* Sanity check: */
+       assert(context != (SHA512_CTX*)0);
+
+       if (buffer != (char*)0) {
+               SHA512_Final(digest, context);
+
+               for (i = 0; i < SHA512_DIGEST_LENGTH; i++) {
+                       *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
+                       *buffer++ = sha2_hex_digits[*d & 0x0f];
+                       d++;
+               }
+               *buffer = (char)0;
+       } else {
+               MEMSET_BZERO(context, sizeof(context));
+       }
+       MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH);
+       return buffer;
+}
+
+char* SHA512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) {
+       SHA512_CTX      context;
+
+       SHA512_Init(&context);
+       SHA512_Update(&context, data, len);
+       return SHA512_End(&context, digest);
+}
+#endif
+
+/*** SHA-384: *********************************************************/
+#ifdef WITH_SHA384
+void SHA384_Init(SHA384_CTX* context) {
+       if (context == (SHA384_CTX*)0) {
+               return;
+       }
+       MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH);
+       MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH);
+       context->bitcount[0] = context->bitcount[1] = 0;
+}
+
+void SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) {
+       SHA512_Update((SHA512_CTX*)context, data, len);
+}
+
+void SHA384_Final(sha2_byte digest[], SHA384_CTX* context) {
+       sha2_word64     *d = (sha2_word64*)digest;
+
+       /* Sanity check: */
+       assert(context != (SHA384_CTX*)0);
+
+       /* If no digest buffer is passed, we don't bother doing this: */
+       if (digest != (sha2_byte*)0) {
+               SHA512_Last((SHA512_CTX*)context);
+
+               /* Save the hash data for output: */
+#if BYTE_ORDER == LITTLE_ENDIAN
+               {
+                       /* Convert TO host byte order */
+                       int     j;
+                       for (j = 0; j < 6; j++) {
+                               REVERSE64(context->state[j],context->state[j]);
+                               *d++ = context->state[j];
+                       }
+               }
+#else
+               MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH);
+#endif
+       }
+
+       /* Zero out state data */
+       MEMSET_BZERO(context, sizeof(context));
+}
+
+char *SHA384_End(SHA384_CTX* context, char buffer[]) {
+       sha2_byte       digest[SHA384_DIGEST_LENGTH], *d = digest;
+       int             i;
+
+       /* Sanity check: */
+       assert(context != (SHA384_CTX*)0);
+
+       if (buffer != (char*)0) {
+               SHA384_Final(digest, context);
+
+               for (i = 0; i < SHA384_DIGEST_LENGTH; i++) {
+                       *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
+                       *buffer++ = sha2_hex_digits[*d & 0x0f];
+                       d++;
+               }
+               *buffer = (char)0;
+       } else {
+               MEMSET_BZERO(context, sizeof(context));
+       }
+       MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH);
+       return buffer;
+}
+
+char* SHA384_Data(const sha2_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) {
+       SHA384_CTX      context;
+
+       SHA384_Init(&context);
+       SHA384_Update(&context, data, len);
+       return SHA384_End(&context, digest);
+}
+#endif
diff --git a/extlibs/tinydtls/sha2/sha2.h b/extlibs/tinydtls/sha2/sha2.h
new file mode 100644 (file)
index 0000000..709fc80
--- /dev/null
@@ -0,0 +1,215 @@
+/*
+ * FILE:       sha2.h
+ * AUTHOR:     Aaron D. Gifford - http://www.aarongifford.com/
+ * 
+ * Copyright (c) 2000-2001, Aaron D. Gifford
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the copyright holder nor the names of contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $Id: sha2.h,v 1.1 2001/11/08 00:02:01 adg Exp adg $
+ */
+
+#ifndef __SHA2_H__
+#define __SHA2_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*
+ * Import u_intXX_t size_t type definitions from system headers.  You
+ * may need to change this, or define these things yourself in this
+ * file.
+ */
+#include <sys/types.h>
+
+#ifdef SHA2_USE_INTTYPES_H
+
+#include <inttypes.h>
+
+#endif /* SHA2_USE_INTTYPES_H */
+
+
+/*** SHA-256/384/512 Various Length Definitions ***********************/
+#define SHA256_BLOCK_LENGTH            64
+#define SHA256_DIGEST_LENGTH           32
+#define SHA256_DIGEST_STRING_LENGTH    (SHA256_DIGEST_LENGTH * 2 + 1)
+#define SHA384_BLOCK_LENGTH            128
+#define SHA384_DIGEST_LENGTH           48
+#define SHA384_DIGEST_STRING_LENGTH    (SHA384_DIGEST_LENGTH * 2 + 1)
+#define SHA512_BLOCK_LENGTH            128
+#define SHA512_DIGEST_LENGTH           64
+#define SHA512_DIGEST_STRING_LENGTH    (SHA512_DIGEST_LENGTH * 2 + 1)
+
+
+/*** SHA-256/384/512 Context Structures *******************************/
+/* NOTE: If your architecture does not define either u_intXX_t types or
+ * uintXX_t (from inttypes.h), you may need to define things by hand
+ * for your system:
+ */
+#if 0
+typedef unsigned char u_int8_t;                /* 1-byte  (8-bits)  */
+typedef unsigned int u_int32_t;                /* 4-bytes (32-bits) */
+typedef unsigned long long u_int64_t;  /* 8-bytes (64-bits) */
+#endif
+/*
+ * Most BSD systems already define u_intXX_t types, as does Linux.
+ * Some systems, however, like Compaq's Tru64 Unix instead can use
+ * uintXX_t types defined by very recent ANSI C standards and included
+ * in the file:
+ *
+ *   #include <inttypes.h>
+ *
+ * If you choose to use <inttypes.h> then please define: 
+ *
+ *   #define SHA2_USE_INTTYPES_H
+ *
+ * Or on the command line during compile:
+ *
+ *   cc -DSHA2_USE_INTTYPES_H ...
+ */
+#ifdef SHA2_USE_INTTYPES_H
+
+typedef struct _SHA256_CTX {
+       uint32_t        state[8];
+       uint64_t        bitcount;
+       uint8_t buffer[SHA256_BLOCK_LENGTH];
+} SHA256_CTX;
+typedef struct _SHA512_CTX {
+       uint64_t        state[8];
+       uint64_t        bitcount[2];
+       uint8_t buffer[SHA512_BLOCK_LENGTH];
+} SHA512_CTX;
+
+#else /* SHA2_USE_INTTYPES_H */
+
+typedef struct _SHA256_CTX {
+       u_int32_t       state[8];
+       u_int64_t       bitcount;
+       u_int8_t        buffer[SHA256_BLOCK_LENGTH];
+} SHA256_CTX;
+typedef struct _SHA512_CTX {
+       u_int64_t       state[8];
+       u_int64_t       bitcount[2];
+       u_int8_t        buffer[SHA512_BLOCK_LENGTH];
+} SHA512_CTX;
+
+#endif /* SHA2_USE_INTTYPES_H */
+
+typedef SHA512_CTX SHA384_CTX;
+
+
+/*** SHA-256/384/512 Function Prototypes ******************************/
+#ifndef NOPROTO
+#ifdef SHA2_USE_INTTYPES_H
+
+#ifdef WITH_SHA256
+void SHA256_Init(SHA256_CTX *);
+void SHA256_Update(SHA256_CTX*, const uint8_t*, size_t);
+void SHA256_Final(uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*);
+char* SHA256_End(SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]);
+char* SHA256_Data(const uint8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]);
+#endif
+
+#ifdef WITH_SHA384
+void SHA384_Init(SHA384_CTX*);
+void SHA384_Update(SHA384_CTX*, const uint8_t*, size_t);
+void SHA384_Final(uint8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*);
+char* SHA384_End(SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH]);
+char* SHA384_Data(const uint8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH]);
+#endif
+
+#ifdef WITH_SHA512
+void SHA512_Init(SHA512_CTX*);
+void SHA512_Update(SHA512_CTX*, const uint8_t*, size_t);
+void SHA512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
+char* SHA512_End(SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]);
+char* SHA512_Data(const uint8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]);
+#endif
+
+#else /* SHA2_USE_INTTYPES_H */
+
+#ifdef WITH_SHA256
+void SHA256_Init(SHA256_CTX *);
+void SHA256_Update(SHA256_CTX*, const u_int8_t*, size_t);
+void SHA256_Final(u_int8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*);
+char* SHA256_End(SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]);
+char* SHA256_Data(const u_int8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]);
+#endif
+
+#ifdef WITH_SHA384
+void SHA384_Init(SHA384_CTX*);
+void SHA384_Update(SHA384_CTX*, const u_int8_t*, size_t);
+void SHA384_Final(u_int8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*);
+char* SHA384_End(SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH]);
+char* SHA384_Data(const u_int8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH]);
+#endif
+
+#ifdef WITH_SHA512
+void SHA512_Init(SHA512_CTX*);
+void SHA512_Update(SHA512_CTX*, const u_int8_t*, size_t);
+void SHA512_Final(u_int8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
+char* SHA512_End(SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]);
+char* SHA512_Data(const u_int8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]);
+#endif
+
+#endif /* SHA2_USE_INTTYPES_H */
+
+#else /* NOPROTO */
+
+#ifdef WITH_SHA256
+void SHA256_Init();
+void SHA256_Update();
+void SHA256_Final();
+char* SHA256_End();
+char* SHA256_Data();
+#endif
+
+#ifdef WITH_SHA384
+void SHA384_Init();
+void SHA384_Update();
+void SHA384_Final();
+char* SHA384_End();
+char* SHA384_Data();
+#endif
+
+#ifdef WITH_SHA512
+void SHA512_Init();
+void SHA512_Update();
+void SHA512_Final();
+char* SHA512_End();
+char* SHA512_Data();
+#endif
+
+#endif /* NOPROTO */
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __SHA2_H__ */
+
diff --git a/extlibs/tinydtls/sha2/sha2prog.c b/extlibs/tinydtls/sha2/sha2prog.c
new file mode 100644 (file)
index 0000000..8d9d6ae
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * FILE:       sha2prog.c
+ * AUTHOR:     Aaron D. Gifford - http://www.aarongifford.com/
+ * 
+ * Copyright (c) 2000-2001, Aaron D. Gifford
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the copyright holder nor the names of contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $Id: sha2prog.c,v 1.1 2001/11/08 00:02:11 adg Exp adg $
+ */
+
+#include <stdio.h>
+#include <sysexits.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+#include "sha2.h"
+
+void usage(char *prog, char *msg) {
+       fprintf(stderr, "%s\nUsage:\t%s [options] [<file>]\nOptions:\n\t-256\tGenerate SHA-256 hash\n\t-384\tGenerate SHA-284 hash\n\t-512\tGenerate SHA-512 hash\n\t-ALL\tGenerate all three hashes\n\t-q\tQuiet mode - only output hexadecimal hashes, one per line\n\n", msg, prog);
+       exit(-1);
+}
+
+#define BUFLEN 16384
+
+int main(int argc, char **argv) {
+       int             kl, l, fd, ac;
+       int             quiet = 0, hash = 0;
+       char            *av, *file = (char*)0;
+       FILE            *IN = (FILE*)0;
+       SHA256_CTX      ctx256;
+       SHA384_CTX      ctx384;
+       SHA512_CTX      ctx512;
+       unsigned char   buf[BUFLEN];
+
+       SHA256_Init(&ctx256);
+       SHA384_Init(&ctx384);
+       SHA512_Init(&ctx512);
+
+       /* Read data from STDIN by default */
+       fd = fileno(stdin);
+
+       ac = 1;
+       while (ac < argc) {
+               if (*argv[ac] == '-') {
+                       av = argv[ac] + 1;
+                       if (!strcmp(av, "q")) {
+                               quiet = 1;
+                       } else if (!strcmp(av, "256")) {
+                               hash |= 1;
+                       } else if (!strcmp(av, "384")) {
+                               hash |= 2;
+                       } else if (!strcmp(av, "512")) {
+                               hash |= 4;
+                       } else if (!strcmp(av, "ALL")) {
+                               hash = 7;
+                       } else {
+                               usage(argv[0], "Invalid option.");
+                       }
+                       ac++;
+               } else {
+                       file = argv[ac++];
+                       if (ac != argc) {
+                               usage(argv[0], "Too many arguments.");
+                       }
+                       if ((IN = fopen(file, "r")) == NULL) {
+                               perror(argv[0]);
+                               exit(-1);
+                       }
+                       fd = fileno(IN);
+               }
+       }
+       if (hash == 0)
+               hash = 7;       /* Default to ALL */
+
+       kl = 0;
+       while ((l = read(fd,buf,BUFLEN)) > 0) {
+               kl += l;
+               SHA256_Update(&ctx256, (unsigned char*)buf, l);
+               SHA384_Update(&ctx384, (unsigned char*)buf, l);
+               SHA512_Update(&ctx512, (unsigned char*)buf, l);
+       }
+       if (file) {
+               fclose(IN);
+       }
+
+       if (hash & 1) {
+               SHA256_End(&ctx256, buf);
+               if (!quiet)
+                       printf("SHA-256 (%s) = ", file);
+               printf("%s\n", buf);
+       }
+       if (hash & 2) {
+               SHA384_End(&ctx384, buf);
+               if (!quiet)
+                       printf("SHA-384 (%s) = ", file);
+               printf("%s\n", buf);
+       }
+       if (hash & 4) {
+               SHA512_End(&ctx512, buf);
+               if (!quiet)
+                       printf("SHA-512 (%s) = ", file);
+               printf("%s\n", buf);
+       }
+
+       return 1;
+}
+
diff --git a/extlibs/tinydtls/sha2/sha2speed.c b/extlibs/tinydtls/sha2/sha2speed.c
new file mode 100644 (file)
index 0000000..2e13575
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+ * FILE:       sha2speed.c
+ * AUTHOR:     Aaron D. Gifford - http://www.aarongifford.com/
+ * 
+ * Copyright (c) 2000-2001, Aaron D. Gifford
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the copyright holder nor the names of contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $Id: sha2speed.c,v 1.1 2001/11/08 00:02:23 adg Exp adg $
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/time.h>
+
+#include "sha2.h"
+
+#define BUFSIZE        16384
+
+void usage(char *prog) {
+       fprintf(stderr, "Usage:\t%s [<num-of-bytes>] [<num-of-loops>] [<fill-byte>]\n", prog);
+       exit(-1);
+}
+
+void printspeed(char *caption, unsigned long bytes, double time) {
+       if (bytes / 1073741824UL > 0) {
+                printf("%s %.4f sec (%.3f GBps)\n", caption, time, (double)bytes/1073741824UL/time);
+        } else if (bytes / 1048576 > 0) {
+                printf("%s %.4f (%.3f MBps)\n", caption, time, (double)bytes/1048576/time);
+        } else if (bytes / 1024 > 0) {
+                printf("%s %.4f (%.3f KBps)\n", caption, time, (double)bytes/1024/time);
+        } else {
+               printf("%s %.4f (%f Bps)\n", caption, time, (double)bytes/time);
+       }
+}
+
+
+int main(int argc, char **argv) {
+       SHA256_CTX      c256;
+       SHA384_CTX      c384;
+       SHA512_CTX      c512;
+       char            buf[BUFSIZE];
+       char            md[SHA512_DIGEST_STRING_LENGTH];
+       int             bytes, blocks, rep, i, j;
+       struct timeval  start, end;
+       double          t, ave256, ave384, ave512;
+       double          best256, best384, best512;
+
+       if (argc > 4) {
+               usage(argv[0]);
+       }
+
+       /* Default to 1024 16K blocks (16 MB) */
+       bytes = 1024 * 1024 * 16;
+       if (argc > 1) {
+               blocks = atoi(argv[1]);
+       }
+       blocks = bytes / BUFSIZE;
+
+       /* Default to 10 repetitions */
+       rep = 10;
+       if (argc > 2) {
+               rep = atoi(argv[2]);
+       }
+
+       /* Set up the input data */
+       if (argc > 3) {
+               memset(buf, atoi(argv[2]), BUFSIZE);
+       } else {
+               memset(buf, 0xb7, BUFSIZE);
+       }
+
+       ave256 = ave384 = ave512 = 0;
+       best256 = best384 = best512 = 100000;
+       for (i = 0; i < rep; i++) {
+               SHA256_Init(&c256);
+               SHA384_Init(&c384);
+               SHA512_Init(&c512);
+       
+               gettimeofday(&start, (struct timezone*)0);
+               for (j = 0; j < blocks; j++) {
+                       SHA256_Update(&c256, (unsigned char*)buf, BUFSIZE);
+               }
+               if (bytes % BUFSIZE) {
+                       SHA256_Update(&c256, (unsigned char*)buf, bytes % BUFSIZE);
+               }
+               SHA256_End(&c256, md);
+               gettimeofday(&end, (struct timezone*)0);
+               t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
+               ave256 += t;
+               if (t < best256) {
+                       best256 = t;
+               }
+               printf("SHA-256[%d] (%.4f/%.4f/%.4f seconds) = 0x%s\n", i+1, t, ave256/(i+1), best256, md);
+
+               gettimeofday(&start, (struct timezone*)0);
+               for (j = 0; j < blocks; j++) {
+                       SHA384_Update(&c384, (unsigned char*)buf, BUFSIZE);
+               }
+               if (bytes % BUFSIZE) {
+                       SHA384_Update(&c384, (unsigned char*)buf, bytes % BUFSIZE);
+               }
+               SHA384_End(&c384, md);
+               gettimeofday(&end, (struct timezone*)0);
+               t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
+               ave384 += t;
+               if (t < best384) {
+                       best384 = t;
+               }
+               printf("SHA-384[%d] (%.4f/%.4f/%.4f seconds) = 0x%s\n", i+1, t, ave384/(i+1), best384, md);
+
+               gettimeofday(&start, (struct timezone*)0);
+               for (j = 0; j < blocks; j++) {
+                       SHA512_Update(&c512, (unsigned char*)buf, BUFSIZE);
+               }
+               if (bytes % BUFSIZE) {
+                       SHA512_Update(&c512, (unsigned char*)buf, bytes % BUFSIZE);
+               }
+               SHA512_End(&c512, md);
+               gettimeofday(&end, (struct timezone*)0);
+               t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
+               ave512 += t;
+               if (t < best512) {
+                       best512 = t;
+               }
+               printf("SHA-512[%d] (%.4f/%.4f/%.4f seconds) = 0x%s\n", i+1, t, ave512/(i+1), best512, md);
+       }
+       ave256 /= rep;
+       ave384 /= rep;
+       ave512 /= rep;
+       printf("\nTEST RESULTS SUMMARY:\nTEST REPETITIONS: %d\n", rep);
+       if (bytes / 1073741824UL > 0) {
+               printf("TEST SET SIZE: %.3f GB\n", (double)bytes/1073741824UL);
+       } else if (bytes / 1048576 > 0) {
+               printf("TEST SET SIZE: %.3f MB\n", (double)bytes/1048576);
+       } else if (bytes /1024 > 0) {
+               printf("TEST SET SIZE: %.3f KB\n", (double)bytes/1024);
+       } else {
+               printf("TEST SET SIZE: %d B\n", bytes);
+       }
+       printspeed("SHA-256 average:", bytes, ave256);
+       printspeed("SHA-256 best:   ", bytes, best256);
+       printspeed("SHA-384 average:", bytes, ave384);
+       printspeed("SHA-384 best:   ", bytes, best384);
+       printspeed("SHA-512 average:", bytes, ave512);
+       printspeed("SHA-512 best:   ", bytes, best512);
+
+       return 1;
+}
+
diff --git a/extlibs/tinydtls/sha2/sha2test.pl b/extlibs/tinydtls/sha2/sha2test.pl
new file mode 100755 (executable)
index 0000000..dc884d8
--- /dev/null
@@ -0,0 +1,358 @@
+#!/usr/bin/perl
+#
+# FILE:                sha2test.pl
+# AUTHOR:      Aaron D. Gifford - http://www.aarongifford.com/
+# 
+# Copyright (c) 2001, Aaron D. Gifford
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+#    notice, this list of conditions and the following disclaimer in the
+#    documentation and/or other materials provided with the distribution.
+# 3. Neither the name of the copyright holder nor the names of contributors
+#    may be used to endorse or promote products derived from this software
+#    without specific prior written permission.
+# 
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+# $Id: sha2test.pl,v 1.1 2001/11/08 00:02:37 adg Exp adg $
+#
+
+sub usage {
+       my ($err) = shift(@_);
+
+       print <<EOM;
+Error:
+       $err
+Usage:
+       $0 [<options>] [<test-vector-info-file> [<test-vector-info-file> ...]]
+
+Options:
+       -256    Use SHA-256 hashes during testing
+       -384    Use SHA-384 hashes during testing
+       -512    Use SHA-512 hashes during testing
+       -ALL    Use all three hashes during testing
+       -c256 <command-spec>    Specify a command to execute to generate a
+                               SHA-256 hash.  Be sure to include a '%'
+                               character which will be replaced by the
+                               test vector data filename containing the
+                               data to be hashed.  This command implies
+                               the -256 option.
+       -c384 <command-spec>    Specify a command to execute to generate a
+                               SHA-384 hash.  See above.  Implies -384.
+       -c512 <command-spec>    Specify a command to execute to generate a
+                               SHA-512 hash.  See above.  Implies -512.
+       -cALL <command-spec>    Specify a command to execute that will
+                               generate all three hashes at once and output
+                               the data in hexadecimal.  See above for
+                               information about the <command-spec>.
+                               This option implies the -ALL option, and
+                               also overrides any other command options if
+                               present.
+
+By default, this program expects to execute the command ./sha2 within the
+current working directory to generate all hashes.  If no test vector
+information files are specified, this program expects to read a series of
+files ending in ".info" within a subdirectory of the current working
+directory called "testvectors".
+
+EOM
+       exit(-1);
+}
+
+$c256 = $c384 = $c512 = $cALL = "";
+$hashes = 0;
+@FILES = ();
+
+# Read all command-line options and files:
+while ($opt = shift(@ARGV)) {
+       if ($opt =~ s/^\-//) {
+               if ($opt eq "256") {
+                       $hashes |= 1;
+               } elsif ($opt eq "384") {
+                       $hashes |= 2;
+               } elsif ($opt eq "512") {
+                       $hashes |= 4;
+               } elsif ($opt =~ /^ALL$/i) {
+                       $hashes = 7;
+               } elsif ($opt =~ /^c256$/i) {
+                       $hashes |= 1;
+                       $opt = $c256 = shift(@ARGV);
+                       $opt =~ s/\s+.*$//;
+                       if (!$c256 || $c256 !~ /\%/ || !-x $opt) {
+                               usage("Missing or invalid command specification for option -c256: $opt\n");
+                       }
+               } elsif ($opt =~ /^c384$/i) {
+                       $hashes |= 2;
+                       $opt = $c384 = shift(@ARGV);
+                       $opt =~ s/\s+.*$//;
+                       if (!$c384 || $c384 !~ /\%/ || !-x $opt) {
+                               usage("Missing or invalid command specification for option -c384: $opt\n");
+                       }
+               } elsif ($opt =~ /^c512$/i) {
+                       $hashes |= 4;
+                       $opt = $c512 = shift(@ARGV);
+                       $opt =~ s/\s+.*$//;
+                       if (!$c512 || $c512 !~ /\%/ || !-x $opt) {
+                               usage("Missing or invalid command specification for option -c512: $opt\n");
+                       }
+               } elsif ($opt =~ /^cALL$/i) {
+                       $hashes = 7;
+                       $opt = $cALL = shift(@ARGV);
+                       $opt =~ s/\s+.*$//;
+                       if (!$cALL || $cALL !~ /\%/ || !-x $opt) {
+                               usage("Missing or invalid command specification for option -cALL: $opt\n");
+                       }
+               } else {
+                       usage("Unknown/invalid option '$opt'\n");
+               }
+       } else {
+               usage("Invalid, nonexistent, or unreadable file '$opt': $!\n") if (!-f $opt);
+               push(@FILES, $opt);
+       }
+}
+
+# Set up defaults:
+if (!$cALL && !$c256 && !$c384 && !$c512) {
+       $cALL = "./sha2 -ALL %";
+       usage("Required ./sha2 binary executable not found.\n") if (!-x "./sha2");
+}
+$hashes = 7 if (!$hashes);
+
+# Do some sanity checks:
+usage("No command was supplied to generate SHA-256 hashes.\n") if ($hashes & 1 == 1 && !$cALL && !$c256);
+usage("No command was supplied to generate SHA-384 hashes.\n") if ($hashes & 2 == 2 && !$cALL && !$c384);
+usage("No command was supplied to generate SHA-512 hashes.\n") if ($hashes & 4 == 4 && !$cALL && !$c512);
+
+# Default .info files:
+if (scalar(@FILES) < 1) {
+       opendir(DIR, "testvectors") || usage("Unable to scan directory 'testvectors' for vector information files: $!\n");
+       @FILES = grep(/\.info$/, readdir(DIR));
+       closedir(DIR);
+       @FILES = map { s/^/testvectors\//; $_; } @FILES;
+       @FILES = sort(@FILES);
+}
+
+# Now read in each test vector information file:
+foreach $file (@FILES) {
+       $dir = $file;
+       if ($file !~ /\//) {
+               $dir = "./";
+       } else {
+               $dir =~ s/\/[^\/]+$//;
+               $dir .= "/";
+       }
+       open(FILE, "<" . $file) ||
+               usage("Unable to open test vector information file '$file' for reading: $!\n");
+       $vec = { desc => "", file => "", sha256 => "", sha384 => "", sha512 => "" };
+       $data = $field = "";
+       $line = 0;
+       while(<FILE>) {
+               $line++;
+               s/\s*[\r\n]+$//;
+               next if ($field && $field ne "DESCRIPTION" && !$_);
+               if (/^(DESCRIPTION|FILE|SHA256|SHA384|SHA512):$/) {
+                       if ($field eq "DESCRIPTION") {
+                               $vec->{desc} = $data;
+                       } elsif ($field eq "FILE") {
+                               $data = $dir . $data if ($data !~ /^\//);
+                               $vec->{file} = $data;
+                       } elsif ($field eq "SHA256") {
+                               $vec->{sha256} = $data;
+                       } elsif ($field eq "SHA384") {
+                               $vec->{sha384} = $data;
+                       } elsif ($field eq "SHA512") {
+                               $vec->{sha512} = $data;
+                       }
+                       $data = "";
+                       $field = $1;
+               } elsif ($field eq "DESCRIPTION") {
+                       s/^    //;
+                       $data .= $_ . "\n";
+               } elsif ($field =~ /^SHA\d\d\d$/) {
+                       s/^\s+//;
+                       if (!/^([a-f0-9]{32}|[a-f0-9]{64})$/) {
+                               usage("Invalid SHA-256/384/512 test vector information " .
+                                     "file format at line $line of file '$file'\n");
+                       }
+                       $data .= $_;
+               } elsif ($field eq "FILE") {
+                       s/^    //;
+                       $data .= $_;
+               } else {
+                       usage("Invalid SHA-256/384/512 test vector information file " .
+                             "format at line $line of file '$file'\n");
+               }
+       }
+       if ($field eq "DESCRIPTION") {
+               $data = $dir . $data if ($data !~ /^\//);
+               $vec->{desc} = $data;
+       } elsif ($field eq "FILE") {
+               $vec->{file} = $data;
+       } elsif ($field eq "SHA256") {
+               $vec->{sha256} = $data;
+       } elsif ($field eq "SHA384") {
+               $vec->{sha384} = $data;
+       } elsif ($field eq "SHA512") {
+               $vec->{sha512} = $data;
+       } else {
+               usage("Invalid SHA-256/384/512 test vector information file " .
+                     "format.  Missing required fields in file '$file'\n");
+       }
+
+       # Sanity check all entries:
+       if (!$vec->{desc}) {
+               usage("Invalid SHA-256/384/512 test vector information file " .
+                     "format.  Missing required DESCRIPTION field in file '$file'\n");
+       }
+       if (!$vec->{file}) {
+               usage("Invalid SHA-256/384/512 test vector information file " .
+                     "format.  Missing required FILE field in file '$file'\n");
+       }
+       if (! -f $vec->{file}) {
+               usage("The test vector data file (field FILE) name " .
+                     "'$vec->{file}' is not a readable file.  Check the FILE filed in " .
+                     "file '$file'.\n");
+       }
+       if (!($vec->{sha256} || $vec->{sha384} || $vec->{sha512})) {
+               usage("Invalid SHA-256/384/512 test vector information file " .
+                     "format.  There must be at least one SHA256, SHA384, or SHA512 " .
+                     "field specified in file '$file'.\n");
+       }
+       if ($vec->{sha256} !~ /^(|[a-f0-9]{64})$/) {
+               usage("Invalid SHA-256/384/512 test vector information file " .
+                     "format.  The SHA256 field is invalid in file '$file'.\n");
+       }
+       if ($vec->{sha384} !~ /^(|[a-f0-9]{96})$/) {
+               usage("Invalid SHA-256/384/512 test vector information file " .
+                     "format.  The SHA384 field is invalid in file '$file'.\n");
+       }
+       if ($vec->{sha512} !~ /^(|[a-f0-9]{128})$/) {
+               usage("Invalid SHA-256/384/512 test vector information file " .
+                     "format.  The SHA512 field is invalid in file '$file'.\n");
+       }
+       close(FILE);
+       if ($hashes & (($vec->{sha256} ? 1 : 0) | ($vec->{sha384} ? 2 : 0) | ($vec->{sha512} ? 4 : 0))) {
+               push(@VECTORS, $vec);
+       }
+}
+
+usage("There were no test vectors for the specified hash(es) in any of the test vector information files you specified.\n") if (scalar(@VECTORS) < 1);
+
+$num = $errors = $error256 = $error384 = $error512 = $tests = $test256 = $test384 = $test512 = 0;
+foreach $vec (@VECTORS) {
+       $num++;
+       print "TEST VECTOR #$num:\n";
+       print "\t" . join("\n\t", split(/\n/, $vec->{desc})) . "\n";
+       print "VECTOR DATA FILE:\n\t$vec->{file}\n";
+       $sha256 = $sha384 = $sha512 = "";
+       if ($cALL) {
+               $prog = $cALL;
+               $prog =~ s/\%/'$vec->{file}'/g;
+               @SHA = grep(/[a-fA-f0-9]{64,128}/, split(/\n/, `$prog`));
+               ($sha256) = grep(/(^[a-fA-F0-9]{64}$|^[a-fA-F0-9]{64}[^a-fA-F0-9]|[^a-fA-F0-9][a-fA-F0-9]{64}$|[^a-fA-F0-9][a-fA-F0-9]{64}[^a-fA-F0-9])/, @SHA);
+               ($sha384) = grep(/(^[a-fA-F0-9]{96}$|^[a-fA-F0-9]{96}[^a-fA-F0-9]|[^a-fA-F0-9][a-fA-F0-9]{96}$|[^a-fA-F0-9][a-fA-F0-9]{96}[^a-fA-F0-9])/, @SHA);
+               ($sha512) = grep(/(^[a-fA-F0-9]{128}$|^[a-fA-F0-9]{128}[^a-fA-F0-9]|[^a-fA-F0-9][a-fA-F0-9]{128}$|[^a-fA-F0-9][a-fA-F0-9]{128}[^a-fA-F0-9])/, @SHA);
+       } else {
+               if ($c256) {
+                       $prog = $c256;
+                       $prog =~ s/\%/'$vec->{file}'/g;
+                       @SHA = grep(/[a-fA-f0-9]{64,128}/, split(/\n/, `$prog`));
+                       ($sha256) = grep(/(^[a-fA-F0-9]{64}$|^[a-fA-F0-9]{64}[^a-fA-F0-9]|[^a-fA-F0-9][a-fA-F0-9]{64}$|[^a-fA-F0-9][a-fA-F0-9]{64}[^a-fA-F0-9])/, @SHA);
+               }
+               if ($c384) {
+                       $prog = $c384;
+                       $prog =~ s/\%/'$vec->{file}'/g;
+                       @SHA = grep(/[a-fA-f0-9]{64,128}/, split(/\n/, `$prog`));
+                       ($sha384) = grep(/(^[a-fA-F0-9]{96}$|^[a-fA-F0-9]{96}[^a-fA-F0-9]|[^a-fA-F0-9][a-fA-F0-9]{96}$|[^a-fA-F0-9][a-fA-F0-9]{96}[^a-fA-F0-9])/, @SHA);
+               }
+               if ($c512) {
+                       $prog = $c512;
+                       $prog =~ s/\%/'$vec->{file}'/g;
+                       @SHA = grep(/[a-fA-f0-9]{64,128}/, split(/\n/, `$prog`));
+                       ($sha512) = grep(/(^[a-fA-F0-9]{128}$|^[a-fA-F0-9]{128}[^a-fA-F0-9]|[^a-fA-F0-9][a-fA-F0-9]{128}$|[^a-fA-F0-9][a-fA-F0-9]{128}[^a-fA-F0-9])/, @SHA);
+               }
+       }
+       usage("Unable to generate any hashes for file '$vec->{file}'!\n") if (!$sha256 && !$sha384 && $sha512);
+       $sha256 =~ tr/A-F/a-f/;
+       $sha384 =~ tr/A-F/a-f/;
+       $sha512 =~ tr/A-F/a-f/;
+       $sha256 =~ s/^.*([a-f0-9]{64}).*$/$1/;
+       $sha384 =~ s/^.*([a-f0-9]{96}).*$/$1/;
+       $sha512 =~ s/^.*([a-f0-9]{128}).*$/$1/;
+
+       if ($sha256 && $hashes & 1 == 1) {
+               if ($vec->{sha256} eq $sha256) {
+                       print "SHA256 MATCHES:\n\t$sha256\n"
+               } else {
+                       print "SHA256 DOES NOT MATCH:\n\tEXPECTED:\n\t\t$vec->{sha256}\n" .
+                             "\tGOT:\n\t\t$sha256\n\n";
+                       $error256++;
+               }
+               $test256++;
+       }
+       if ($sha384 && $hashes & 2 == 2) {
+               if ($vec->{sha384} eq $sha384) {
+                       print "SHA384 MATCHES:\n\t" . substr($sha384, 0, 64) . "\n\t" .
+                             substr($sha384, -32) . "\n";
+               } else {
+                       print "SHA384 DOES NOT MATCH:\n\tEXPECTED:\n\t\t" .
+                             substr($vec->{sha384}, 0, 64) . "\n\t\t" .
+                             substr($vec->{sha384}, -32) . "\n\tGOT:\n\t\t" .
+                             substr($sha384, 0, 64) . "\n\t\t" . substr($sha384, -32) . "\n\n";
+                       $error384++;
+               }
+               $test384++;
+       }
+       if ($sha512 && $hashes & 4 == 4) {
+               if ($vec->{sha512} eq $sha512) {
+                       print "SHA512 MATCHES:\n\t" . substr($sha512, 0, 64) . "\n\t" .
+                             substr($sha512, -64) . "\n";
+               } else {
+                       print "SHA512 DOES NOT MATCH:\n\tEXPECTED:\n\t\t" .
+                             substr($vec->{sha512}, 0, 64) . "\n\t\t" .
+                             substr($vec->{sha512}, -32) . "\n\tGOT:\n\t\t" .
+                             substr($sha512, 0, 64) . "\n\t\t" . substr($sha512, -64) . "\n\n";
+                       $error512++;
+               }
+               $test512++;
+       }
+}
+
+$errors = $error256 + $error384 + $error512;
+$tests = $test256 + $test384 + $test512;
+print "\n\n===== RESULTS ($num VECTOR DATA FILES HASHED) =====\n\n";
+print "HASH TYPE\tNO. OF TESTS\tPASSED\tFAILED\n";
+print "---------\t------------\t------\t------\n";
+if ($test256) {
+       $pass = $test256 - $error256;
+       print "SHA-256\t\t".substr("           $test256", -12)."\t".substr("     $pass", -6)."\t".substr("     $error256", -6)."\n";
+}
+if ($test384) {
+       $pass = $test384 - $error384;
+       print "SHA-384\t\t".substr("           $test384", -12)."\t".substr("     $pass", -6)."\t".substr("     $error384", -6)."\n";
+}
+if ($test512) {
+       $pass = $test512 - $error512;
+       print "SHA-512\t\t".substr("           $test512", -12)."\t".substr("     $pass", -6)."\t".substr("     $error512", -6)."\n";
+}
+print "----------------------------------------------\n";
+$pass = $tests - $errors;
+print "TOTAL:          ".substr("           $tests", -12)."\t".substr("     $pass", -6)."\t".substr("     $errors", -6)."\n\n";
+print "NO ERRORS!  ALL TESTS WERE SUCCESSFUL!\n\n" if (!$errors);
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector001.dat b/extlibs/tinydtls/sha2/testvectors/vector001.dat
new file mode 100644 (file)
index 0000000..f2ba8f8
--- /dev/null
@@ -0,0 +1 @@
+abc
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector001.info b/extlibs/tinydtls/sha2/testvectors/vector001.info
new file mode 100644 (file)
index 0000000..57b444e
--- /dev/null
@@ -0,0 +1,21 @@
+DESCRIPTION:
+    This test vector is taken from the PDF document that describes
+    the SHA-256/384/512 algorithms.  That document contains sample
+    output for all three versions (SHA-256, SHA-384, and SHA-512).
+    
+    (Total length of test vector data: 3)
+
+FILE:
+    vector001.dat
+
+SHA256:
+    ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
+
+SHA384:
+    cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed
+    8086072ba1e7cc2358baeca134c825a7
+
+SHA512:
+    ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a
+    2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector002.dat b/extlibs/tinydtls/sha2/testvectors/vector002.dat
new file mode 100644 (file)
index 0000000..199f24e
--- /dev/null
@@ -0,0 +1 @@
+abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector002.info b/extlibs/tinydtls/sha2/testvectors/vector002.info
new file mode 100644 (file)
index 0000000..0fc1ed3
--- /dev/null
@@ -0,0 +1,21 @@
+DESCRIPTION:
+    The PDF document only provided sample output for SHA-256 using
+    this test data.  I have provided SHA-384 and SHA-512 sample
+    output from my own implementation which may not be correct.
+    
+    (Total length of test vector data: 56)
+
+FILE:
+    vector002.dat
+
+SHA256:
+    248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1
+
+SHA384:
+    3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6
+    b0455a8520bc4e6f5fe95b1fe3c8452b
+
+SHA512:
+    204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335
+    96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector003.dat b/extlibs/tinydtls/sha2/testvectors/vector003.dat
new file mode 100644 (file)
index 0000000..4674ea4
--- /dev/null
@@ -0,0 +1 @@
+abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector003.info b/extlibs/tinydtls/sha2/testvectors/vector003.info
new file mode 100644 (file)
index 0000000..17a2ad8
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    For this test data (from the PDF document), no example output
+    was provided for SHA-256 (SHA-384 and SHA-512 samples were
+    provided), so the sample for SHA-256 comes from the output of
+    my own implementation and so may not be correct.
+    
+    (Total length of test vector data: 112)
+
+FILE:
+    vector003.dat
+
+SHA256:
+    cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1
+
+SHA384:
+    09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712
+    fcc7c71a557e2db966c3e9fa91746039
+
+SHA512:
+    8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018
+    501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector004.dat b/extlibs/tinydtls/sha2/testvectors/vector004.dat
new file mode 100644 (file)
index 0000000..3d71eba
--- /dev/null
@@ -0,0 +1 @@
+Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.  Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war.  We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live.  It is altogether fitting and proper that we should do this.  But, in a larger sense, we can not dedicate--we can not consecrate--we can not hallow--this ground.  The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract.  The world will little note, nor long remember what we say here, but it can never forget what they did here.  It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced.  It is rather for us to be here dedicated to the great task remaining before us--that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion--that we here highly resolve that these dead shall not have died in vain--that this nation, under God, shall have a new birth of freedom--and that government of the people, by the people, for the people, shall not perish from the earth.  -- President Abraham Lincoln, November 19, 1863
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector004.info b/extlibs/tinydtls/sha2/testvectors/vector004.info
new file mode 100644 (file)
index 0000000..eed148c
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for this test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample comes from...well
+    most anyone in the U.S. will know and many outside the U.S. too.
+    
+    (Total length of test vector data: 1515)
+
+FILE:
+    vector004.dat
+
+SHA256:
+    4d25fccf8752ce470a58cd21d90939b7eb25f3fa418dd2da4c38288ea561e600
+
+SHA384:
+    69cc75b95280bdd9e154e743903e37b1205aa382e92e051b1f48a6db9d0203f8
+    a17c1762d46887037275606932d3381e
+
+SHA512:
+    23450737795d2f6a13aa61adcca0df5eef6df8d8db2b42cd2ca8f783734217a7
+    3e9cabc3c9b8a8602f8aeaeb34562b6b1286846060f9809b90286b3555751f09
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector005.info b/extlibs/tinydtls/sha2/testvectors/vector005.info
new file mode 100644 (file)
index 0000000..37602d3
--- /dev/null
@@ -0,0 +1,23 @@
+DESCRIPTION:
+    The output samples for this test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample is EMPTY (no bits).
+    Mr. David A. Ireland's SHA-256 implementation agrees with my own
+    implementation on the output of this test vector (SHA-256 only).
+    
+    (Total length of test vector data: 0)
+
+FILE:
+    vector005.dat
+
+SHA256:
+    e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
+
+SHA384:
+    38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da
+    274edebfe76f65fbd51ad2f14898b95b
+
+SHA512:
+    cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce
+    47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector006.dat b/extlibs/tinydtls/sha2/testvectors/vector006.dat
new file mode 100644 (file)
index 0000000..7caf161
--- /dev/null
@@ -0,0 +1 @@
+This is exactly 64 bytes long, not counting the terminating byte
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector006.info b/extlibs/tinydtls/sha2/testvectors/vector006.info
new file mode 100644 (file)
index 0000000..2a0d78a
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample exactly the same
+    length as the SHA-256 block length.
+    
+    (Total length of test vector data: 64)
+
+FILE:
+    vector006.dat
+
+SHA256:
+    ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8
+
+SHA384:
+    e28e35e25a1874908bf0958bb088b69f3d742a753c86993e9f4b1c4c21988f95
+    8bd1fe0315b195aca7b061213ac2a9bd
+
+SHA512:
+    70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38
+    7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector007.dat b/extlibs/tinydtls/sha2/testvectors/vector007.dat
new file mode 100644 (file)
index 0000000..1caf01b
--- /dev/null
@@ -0,0 +1 @@
+For this sample, this 63-byte string will be used as input data
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector007.info b/extlibs/tinydtls/sha2/testvectors/vector007.info
new file mode 100644 (file)
index 0000000..fad860d
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample one byte shorter
+    than the SHA-256 block length.
+    
+    (Total length of test vector data: 63)
+
+FILE:
+    vector007.dat
+
+SHA256:
+    f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342
+
+SHA384:
+    37b49ef3d08de53e9bd018b0630067bd43d09c427d06b05812f48531bce7d2a6
+    98ee2d1ed1ffed46fd4c3b9f38a8a557
+
+SHA512:
+    b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e
+    6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector008.dat b/extlibs/tinydtls/sha2/testvectors/vector008.dat
new file mode 100644 (file)
index 0000000..baae226
--- /dev/null
@@ -0,0 +1 @@
+And this textual data, astonishing as it may appear, is exactly 128 bytes in length, as are both SHA-384 and SHA-512 block sizes
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector008.info b/extlibs/tinydtls/sha2/testvectors/vector008.info
new file mode 100644 (file)
index 0000000..22cfd81
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample exactly the same
+    length as the SHA-384 and SHA-512 block lengths.
+    
+    (Total length of test vector data: 128)
+
+FILE:
+    vector008.dat
+
+SHA256:
+    0ab803344830f92089494fb635ad00d76164ad6e57012b237722df0d7ad26896
+
+SHA384:
+    e3e3602f4d90c935321d788f722071a8809f4f09366f2825cd85da97ccd2955e
+    b6b8245974402aa64789ed45293e94ba
+
+SHA512:
+    97fb4ec472f3cb698b9c3c12a12768483e5b62bcdad934280750b4fa4701e5e0
+    550a80bb0828342c19631ba55a55e1cee5de2fda91fc5d40e7bee1d4e6d415b3
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector009.dat b/extlibs/tinydtls/sha2/testvectors/vector009.dat
new file mode 100644 (file)
index 0000000..9c64af4
--- /dev/null
@@ -0,0 +1 @@
+By hashing data that is one byte less than a multiple of a hash block length (like this 127-byte string), bugs may be revealed.
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector009.info b/extlibs/tinydtls/sha2/testvectors/vector009.info
new file mode 100644 (file)
index 0000000..d5fe515
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample is one byte shorter
+    in length than the SHA-384 and SHA-512 block lengths.
+    
+    (Total length of test vector data: 127)
+
+FILE:
+    vector009.dat
+
+SHA256:
+    e4326d0459653d7d3514674d713e74dc3df11ed4d30b4013fd327fdb9e394c26
+
+SHA384:
+    1ca650f38480fa9dfb5729636bec4a935ebc1cd4c0055ee50cad2aa627e06687
+    1044fd8e6fdb80edf10b85df15ba7aab
+
+SHA512:
+    d399507bbf5f2d0da51db1ff1fc51c1c9ff1de0937e00d01693b240e84fcc340
+    0601429f45c297acc6e8fcf1e4e4abe9ff21a54a0d3d88888f298971bd206cd5
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector010.dat b/extlibs/tinydtls/sha2/testvectors/vector010.dat
new file mode 100644 (file)
index 0000000..f1681bc
Binary files /dev/null and b/extlibs/tinydtls/sha2/testvectors/vector010.dat differ
diff --git a/extlibs/tinydtls/sha2/testvectors/vector010.info b/extlibs/tinydtls/sha2/testvectors/vector010.info
new file mode 100644 (file)
index 0000000..df7717d
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample is exactly 5 times
+    size of the SHA-256 block length.
+    
+    (Total length of test vector data: 320)
+
+FILE:
+    vector010.dat
+
+SHA256:
+    a7f001d996dd25af402d03b5f61aef950565949c1a6ad5004efa730328d2dbf3
+
+SHA384:
+    b8261ddcd7df7b3969a516b72550de6fbf0e394a4a7bb2bbc60ec603c2ceff64
+    3c5bf62bc6dcbfa5beb54b62d750b969
+
+SHA512:
+    caf970d3638e21053173a638c4b94d6d1ff87bc47b58f8ee928fbe9e245c23ab
+    f81019e45bf017ecc8610e5e0b95e3b025ccd611a772ca4fb3dfba26f0859725
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector011.dat b/extlibs/tinydtls/sha2/testvectors/vector011.dat
new file mode 100644 (file)
index 0000000..d1609a9
Binary files /dev/null and b/extlibs/tinydtls/sha2/testvectors/vector011.dat differ
diff --git a/extlibs/tinydtls/sha2/testvectors/vector011.info b/extlibs/tinydtls/sha2/testvectors/vector011.info
new file mode 100644 (file)
index 0000000..f36988c
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample is one byte less
+    than 7 times the size of the SHA-256 block length.
+    
+    (Total length of test vector data: 447)
+
+FILE:
+    vector011.dat
+
+SHA256:
+    6dcd63a07b0922cc3a9b3315b158478681cc32543b0a4180abe58a73c5e14cc2
+
+SHA384:
+    548e4e9a1ff57f469ed47b023bf5279dfb4d4ca08c65051e3a5c41fab84479a2
+    05496276906008b4b3c5b0970b2f5446
+
+SHA512:
+    ee5d07460183b130687c977e9f8d43110989b0864b18fe6ee00a53dec5eda111
+    f3aaa3bac7ab8dae26ed545a4de33ed45190f18fa0c327c44642ab9424265330
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector012.dat b/extlibs/tinydtls/sha2/testvectors/vector012.dat
new file mode 100644 (file)
index 0000000..d74f1db
Binary files /dev/null and b/extlibs/tinydtls/sha2/testvectors/vector012.dat differ
diff --git a/extlibs/tinydtls/sha2/testvectors/vector012.info b/extlibs/tinydtls/sha2/testvectors/vector012.info
new file mode 100644 (file)
index 0000000..a1574e1
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample is exactly 5 times
+    size of the SHA-384 and SHA-512 block lengths.
+    
+    (Total length of test vector data: 640)
+
+FILE:
+    vector012.dat
+
+SHA256:
+    af6ebfde7d93d5badb6cde6287ecc2061c1cafc5b1c1217cd984fbcdb9c61aaa
+
+SHA384:
+    c6fec3a3278dd6b5afc8c0971d32d38faf5802f1a21527c32563b32a1ac34065
+    6b433b44fe2648aa2232206f4301193a
+
+SHA512:
+    73ffeb67716c3495fbc33f2d62fe08e2616706a5599881c7e67e9ef2b68f4988
+    ea8b3b604ba87e50b07962692705c420fa31a00be41d6aaa9f3b11eafe9cf49b
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector013.dat b/extlibs/tinydtls/sha2/testvectors/vector013.dat
new file mode 100644 (file)
index 0000000..cc8a8ae
Binary files /dev/null and b/extlibs/tinydtls/sha2/testvectors/vector013.dat differ
diff --git a/extlibs/tinydtls/sha2/testvectors/vector013.info b/extlibs/tinydtls/sha2/testvectors/vector013.info
new file mode 100644 (file)
index 0000000..4fbd4cb
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample is one byte short
+    of 17 times size of the SHA-384 and SHA-512 block lengths.
+    
+    (Total length of test vector data: 2175)
+
+FILE:
+    vector013.dat
+
+SHA256:
+    8ff59c6d33c5a991088bc44dd38f037eb5ad5630c91071a221ad6943e872ac29
+
+SHA384:
+    92dca5655229b3c34796a227ff1809e273499adc2830149481224e0f54ff4483
+    bd49834d4865e508ef53d4cd22b703ce
+
+SHA512:
+    0e928db6207282bfb498ee871202f2337f4074f3a1f5055a24f08e912ac118f8
+    101832cdb9c2f702976e629183db9bacfdd7b086c800687c3599f15de7f7b9dd
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector014.dat b/extlibs/tinydtls/sha2/testvectors/vector014.dat
new file mode 100644 (file)
index 0000000..6ee6629
Binary files /dev/null and b/extlibs/tinydtls/sha2/testvectors/vector014.dat differ
diff --git a/extlibs/tinydtls/sha2/testvectors/vector014.info b/extlibs/tinydtls/sha2/testvectors/vector014.info
new file mode 100644 (file)
index 0000000..1780afc
--- /dev/null
@@ -0,0 +1,22 @@
+DESCRIPTION:
+    The output samples for thi test vector come exclusively from my
+    own implementation and so may be completely incorrect.  Use with
+    a very large grain of salt.  The input sample 4 KB of misc.
+    data.
+    
+    (Total length of test vector data: 16384)
+
+FILE:
+    vector014.dat
+
+SHA256:
+    1818e87564e0c50974ecaabbb2eb4ca2f6cc820234b51861e2590be625f1f703
+
+SHA384:
+    310fbb2027bdb7042f0e09e7b092e9ada506649510a7aa029825c8e8019e9c30
+    749d723f2de1bd8c043d8d89d3748c2f
+
+SHA512:
+    a001636f3ff1ce34f432f8e8f7785b78be84318beb8485a406650a8b243c419f
+    7db6435cf6bf3000c6524adb5b52bad01afb76b3ceff701331e18b85b0e4cbd3
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector015.dat b/extlibs/tinydtls/sha2/testvectors/vector015.dat
new file mode 100644 (file)
index 0000000..7d63021
--- /dev/null
@@ -0,0 +1 @@
+qwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwertyqwerty
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector015.info b/extlibs/tinydtls/sha2/testvectors/vector015.info
new file mode 100644 (file)
index 0000000..d035782
--- /dev/null
@@ -0,0 +1,21 @@
+DESCRIPTION:
+    This is yet another of my own test vectors for a larger
+    input data set.  The input data is the string "qwerty
+    repeated 65536 times.
+    
+    (Total length of test vector data: 393216)
+
+FILE:
+    vector015.dat
+
+SHA256:
+    5e3dfe0cc98fd1c2de2a9d2fd893446da43d290f2512200c515416313cdf3192
+
+SHA384:
+    0d5e45317bc7997cb9c8a23bad9bac9170d5bc81789b51af6bcd74ace379fd64
+    9a2b48cb56c4cb4ec1477e6933329e0e
+
+SHA512:
+    735bd6bebfe6f8070d70069105bc761f35ed1ac3742f2e372fdc14d2a51898e6
+    153ccaff9073324130abdc451c730dc5dab5a0452487b1171c4dd97f92e267b7
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector016.dat b/extlibs/tinydtls/sha2/testvectors/vector016.dat
new file mode 100644 (file)
index 0000000..fc00891
--- /dev/null
@@ -0,0 +1 @@
+Rijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AESRijndael is AES
\ No newline at end of file
diff --git a/extlibs/tinydtls/sha2/testvectors/vector016.info b/extlibs/tinydtls/sha2/testvectors/vector016.info
new file mode 100644 (file)
index 0000000..effb114
--- /dev/null
@@ -0,0 +1,23 @@
+DESCRIPTION:
+    This test vector came from Brian LaMacchia in his e-mail
+    message containing several samples of output from his SHA-256
+    and SHA-512 implementations.  My own implementations match
+    his output exactly.  The input data data set is the string
+    "Rijndael is AES" repeated 1024 times.
+    
+    (Total length of test vector data: 15360)
+
+FILE:
+    vector016.dat
+
+SHA256:
+    80fced5a97176a5009207cd119551b42c5b51ceb445230d02ecc2663bbfb483a
+
+SHA384:
+    aa1e77c094e5ce6db81a1add4c095201d020b7f8885a4333218da3b799b9fc42
+    f00d60cd438a1724ae03bd7b515b739b
+
+SHA512:
+    fae25ec70bcb3bbdef9698b9d579da49db68318dbdf18c021d1f76aaceff9628
+    38873235597e7cce0c68aabc610e0deb79b13a01c302abc108e459ddfbe9bee8
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector017.dat b/extlibs/tinydtls/sha2/testvectors/vector017.dat
new file mode 100644 (file)
index 0000000..4272d97
Binary files /dev/null and b/extlibs/tinydtls/sha2/testvectors/vector017.dat differ
diff --git a/extlibs/tinydtls/sha2/testvectors/vector017.info b/extlibs/tinydtls/sha2/testvectors/vector017.info
new file mode 100644 (file)
index 0000000..5d6c632
--- /dev/null
@@ -0,0 +1,32 @@
+DESCRIPTION:
+    Rogier van de Pol notified me that my implementation differed
+    with several others on several test data sets he had tested
+    against.  This test vector data set is one Rogier provided
+    to me that highlighted an off-by-one bug in my implementation
+    that affected SHA-256/384/512 hashes where the data set length
+    was of a certain length.  In the case of SHA512 or SHA384, if
+    the data length after subtracting 111 was an even multiple of
+    128 bytes, the bug surfaced.  In the case of SHA256, after
+    subtracting 55, the remaining length was an even multiple of 64,
+    the bug surfaced.  The fix was simple.  In SHA512_Last() and in
+    SHA256_Final() functions,  I simply replaced a single "<" test
+    with a "<=" test.
+
+    Thanks, Rogier!
+   
+    (Total length of test vector data: 12271)
+
+FILE:
+    vector017.dat
+
+SHA256:
+    88ee6ada861083094f4c64b373657e178d88ef0a4674fce6e4e1d84e3b176afb
+
+SHA384:
+    78cc6402a29eb984b8f8f888ab0102cabe7c06f0b9570e3d8d744c969db14397
+    f58ecd14e70f324bf12d8dd4cd1ad3b2
+
+SHA512:
+    211bec83fbca249c53668802b857a9889428dc5120f34b3eac1603f13d1b4796
+    5c387b39ef6af15b3a44c5e7b6bbb6c1096a677dc98fc8f472737540a332f378
+
diff --git a/extlibs/tinydtls/sha2/testvectors/vector018.dat b/extlibs/tinydtls/sha2/testvectors/vector018.dat
new file mode 100644 (file)
index 0000000..cc8a8d1
Binary files /dev/null and b/extlibs/tinydtls/sha2/testvectors/vector018.dat differ
diff --git a/extlibs/tinydtls/sha2/testvectors/vector018.info b/extlibs/tinydtls/sha2/testvectors/vector018.info
new file mode 100644 (file)
index 0000000..7ee3444
--- /dev/null
@@ -0,0 +1,26 @@
+DESCRIPTION:
+    I added this vector after fixing a bug first discovered by
+    Rogier van de Pol.  The length of this data set is designed to
+    test for that bug or similar bugs in SHA-256 hashes.  The bug
+    was an off-by-one bug where I used a "<" test instead of a "<="
+    test in SHA256_Final().  Whenever data set lengths were an even
+    multiple of 64 after subtracting 55, the bug showed up.  The
+    fix was easy, once the problem was fully diagnosed.
+
+    Thanks, Rogier!
+   
+    (Total length of test vector data: 1079)
+
+FILE:
+    vector018.dat
+
+SHA256:
+    5a2e925a7f8399fa63a20a1524ae83a7e3c48452f9af4df493c8c51311b04520
+
+SHA384:
+    72ec26cc742bc5fb1ef82541c9cadcf01a15c8104650d305f24ec8b006d7428e
+    8ebe2bb320a465dbdd5c6326bbd8c9ad
+
+SHA512:
+    ebad464e6d9f1df7e8aadff69f52db40a001b253fbf65a018f29974dcc7fbf8e
+    58b69e247975fbadb4153d7289357c9b6212752d0ab67dd3d9bbc0bb908aa98c
diff --git a/extlibs/tinydtls/state.h b/extlibs/tinydtls/state.h
new file mode 100644 (file)
index 0000000..72df125
--- /dev/null
@@ -0,0 +1,64 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file state.h
+ * @brief state information for DTLS FSM
+ */
+
+#ifndef _DTLS_STATE_H_
+#define _DTLS_STATE_H_
+
+#include <sys/types.h>
+#include <stdint.h>
+
+#include "global.h"
+#include "hmac.h"
+
+typedef enum { 
+  DTLS_STATE_INIT = 0, DTLS_STATE_WAIT_CLIENTHELLO, DTLS_STATE_WAIT_CLIENTCERTIFICATE,
+  DTLS_STATE_WAIT_CLIENTKEYEXCHANGE, DTLS_STATE_WAIT_CERTIFICATEVERIFY,
+  DTLS_STATE_WAIT_CHANGECIPHERSPEC,
+  DTLS_STATE_WAIT_FINISHED, DTLS_STATE_FINISHED, 
+  /* client states */
+  DTLS_STATE_CLIENTHELLO, DTLS_STATE_WAIT_SERVERCERTIFICATE, DTLS_STATE_WAIT_SERVERKEYEXCHANGE,
+  DTLS_STATE_WAIT_SERVERHELLODONE,
+
+  DTLS_STATE_CONNECTED,
+  DTLS_STATE_CLOSING,
+  DTLS_STATE_CLOSED
+} dtls_state_t;
+
+typedef struct {
+  uint16_t mseq_s;          /**< send handshake message sequence number counter */
+  uint16_t mseq_r;          /**< received handshake message sequence number counter */
+
+  /** pending config that is updated during handshake */
+  /* FIXME: dtls_security_parameters_t pending_config; */
+
+  /* temporary storage for the final handshake hash */
+  dtls_hash_ctx hs_hash;
+} dtls_hs_state_t;
+#endif /* _DTLS_STATE_H_ */
diff --git a/extlibs/tinydtls/t_list.h b/extlibs/tinydtls/t_list.h
new file mode 100644 (file)
index 0000000..eb72991
--- /dev/null
@@ -0,0 +1,147 @@
+/* t_list -- tinydtls lists
+ *
+ * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file t_list.h
+ * @brief Wrappers for list structures and functions
+ */
+
+#ifndef _DTLS_LIST_H_
+#define _DTLS_LIST_H_
+
+#include "tinydtls.h"
+
+#ifndef WITH_CONTIKI
+#include "uthash.h"
+#include "utlist.h"
+
+/* We define list structures and utility functions to be compatible
+ * with Contiki list structures. The Contiki list API is part of the
+ * Contiki operating system, and therefore the following licensing
+ * terms apply (taken from contiki/core/lib/list.h):
+ *
+ * Copyright (c) 2004, Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the Contiki operating system.
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ *
+ * $ Id: list.h,v 1.5 2010/09/13 13:31:00 adamdunkels Exp $
+ */
+
+typedef void **list_t;
+struct list {
+  struct list *next;
+};
+
+#define LIST_CONCAT(s1, s2) s1##s2
+
+#define LIST_STRUCT(name)                      \
+  void *LIST_CONCAT(name, _list);              \
+  list_t name
+
+#define LIST_STRUCT_INIT(struct_ptr, name)  {                          \
+    (struct_ptr)->name = &((struct_ptr)->LIST_CONCAT(name,_list));     \
+    (struct_ptr)->LIST_CONCAT(name,_list) = NULL;                      \
+  }
+
+static inline void *
+list_head(list_t list) {
+  return *list;
+}
+
+static inline void 
+list_remove(list_t list, void *item) {
+  LL_DELETE(*(struct list **)list, (struct list *)item);
+}
+
+static inline void 
+list_add(list_t list, void *item) {
+  list_remove(list, item);
+  LL_APPEND(*(struct list **)list, (struct list *)item);
+}
+
+static inline void 
+list_push(list_t list, void *item) {
+  LL_PREPEND(*(struct list **)list, (struct list *)item);
+}
+
+static inline void *
+list_pop(list_t list) {
+  struct list *l;
+  l = *list;
+  if(l)
+    list_remove(list, l);
+  
+  return l;
+}
+
+static inline void
+list_insert(list_t list, void *previtem, void *newitem) {
+  if(previtem == NULL) {
+    list_push(list, newitem);
+  } else {
+    ((struct list *)newitem)->next = ((struct list *)previtem)->next;
+    ((struct list *)previtem)->next = newitem;
+  } 
+}
+
+static inline void *
+list_item_next(void *item)
+{
+  return item == NULL? NULL: ((struct list *)item)->next;
+}
+
+#else /* WITH_CONTIKI */
+#include "list.h"
+#endif /* WITH_CONTIKI */
+
+#endif /* _DTLS_LIST_H_ */
+
diff --git a/extlibs/tinydtls/tests/Makefile.in b/extlibs/tinydtls/tests/Makefile.in
new file mode 100644 (file)
index 0000000..3a50695
--- /dev/null
@@ -0,0 +1,84 @@
+# Makefile for tinydtls
+#
+# Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use, copy,
+# modify, merge, publish, distribute, sublicense, and/or sell copies
+# of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+# the library's version
+VERSION:=@PACKAGE_VERSION@
+
+# tools
+@SET_MAKE@
+SHELL = /bin/sh
+MKDIR = mkdir
+
+abs_builddir = @abs_builddir@
+top_builddir = @top_builddir@
+top_srcdir:= @top_srcdir@
+
+# files and flags
+SOURCES:= dtls-server.c ccm-test.c prf-test.c \
+  dtls-client.c
+  #cbc_aes128-test.c #dsrv-test.c
+OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
+PROGRAMS:= $(patsubst %.c, %, $(SOURCES))
+HEADERS:=
+CFLAGS:=-Wall @CFLAGS@ 
+CPPFLAGS:=-I$(top_srcdir) @CPPFLAGS@
+LDFLAGS:=-L$(top_builddir) 
+LDLIBS:=-ltinydtls @LIBS@
+DISTDIR=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
+FILES:=Makefile.in $(SOURCES) ccm-testdata.c #cbc_aes128-testdata.c
+
+.PHONY: all dirs clean distclean .gitignore doc
+
+.SUFFIXES:
+.SUFFIXES:      .c .o
+
+all:   $(PROGRAMS)
+
+check: 
+       echo DISTDIR: $(DISTDIR)
+       echo top_builddir: $(top_builddir)
+
+clean:
+       @rm -f $(PROGRAMS) main.o $(LIB) $(OBJECTS)
+       for dir in $(SUBDIRS); do \
+               $(MAKE) -C $$dir clean ; \
+       done
+
+doc:   
+       $(MAKE) -C doc
+
+distclean:     clean
+       @rm -rf $(DISTDIR)
+       @rm -f *~ $(DISTDIR).tar.gz
+
+dist:  $(FILES)
+       test -d $(DISTDIR)/tests || mkdir $(DISTDIR)/tests
+       cp $(FILES) $(DISTDIR)/tests
+
+# this directory contains no installation candidates
+install:
+       :
+
+.gitignore:
+       echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@
diff --git a/extlibs/tinydtls/tests/cbc_aes128-test.c b/extlibs/tinydtls/tests/cbc_aes128-test.c
new file mode 100644 (file)
index 0000000..1f91920
--- /dev/null
@@ -0,0 +1,60 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "debug.h"
+#include "numeric.h"
+#include "crypto.h"
+
+#include "cbc_aes128-testdata.c"
+
+void 
+dump(unsigned char *buf, size_t len) {
+  size_t i = 0;
+  while (i < len) {
+    printf("%02x ", buf[i++]);
+    if (i % 4 == 0)
+      printf(" ");
+    if (i % 16 == 0)
+      printf("\n\t");
+  }
+  printf("\n");
+}
+
+int main(int argc, char **argv) {
+  int len, n;
+
+  for (n = 0; n < sizeof(data)/sizeof(struct test_vector); ++n) {
+    dtls_cipher_context_t *cipher;
+
+    cipher = dtls_new_cipher(&ciphers[AES128],
+                            data[n].key,
+                            sizeof(data[n].key));
+    
+    if (!cipher) {
+      fprintf(stderr, "cannot set key\n");
+      exit(-1);
+    }
+
+    dtls_init_cipher(cipher, data[n].nonce, sizeof(data[n].nonce));
+
+    if (data[n].M == 0)
+      len = dtls_encrypt(cipher, data[n].msg, data[n].lm);
+    else
+      len = dtls_decrypt(cipher, data[n].msg, data[n].lm);
+
+    printf("Packet Vector #%d ", n+1);
+    if (len != data[n].r_lm
+       || memcmp(data[n].msg, data[n].result, len))
+      printf("FAILED, ");
+    else 
+      printf("OK, ");
+    
+    printf("result is (total length = %d):\n\t", (int)len);
+    dump(data[n].msg, len);
+
+    free(cipher);
+  }
+
+  return 0;
+}
diff --git a/extlibs/tinydtls/tests/cbc_aes128-testdata.c b/extlibs/tinydtls/tests/cbc_aes128-testdata.c
new file mode 100644 (file)
index 0000000..0791679
--- /dev/null
@@ -0,0 +1,72 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/* test vectors from Appendix F.2.{1,2} of NIST SP 800-38A, ed. 2001 */
+
+struct test_vector {
+  size_t M;                    /* mode: 0 == encrypt, 1 == decrypt */
+  size_t lm;                   /* overall message length */
+  size_t la;                   /* not used */
+  unsigned char key[AES_BLKLEN];
+  unsigned char nonce[AES_BLKLEN];
+  unsigned char msg[2000];
+  size_t r_lm;                 /* overall result length */
+  unsigned char result[2000];  /* result */
+};
+
+struct test_vector data[] = {
+  /* F.2.1 (encrypt) */
+  { 0, 4 * AES_BLKLEN, 0,
+    { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c },        /* AES key */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f },        /* Nonce */
+    { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
+      0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
+      0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
+      0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 },        /* msg */
+    4 * AES_BLKLEN,    /* length of result */
+    { 0x76, 0x49, 0xab, 0xac, 0x81, 0x19, 0xb2, 0x46, 0xce, 0xe9, 0x8e, 0x9b, 0x12, 0xe9, 0x19, 0x7d,
+      0x50, 0x86, 0xcb, 0x9b, 0x50, 0x72, 0x19, 0xee, 0x95, 0xdb, 0x11, 0x3a, 0x91, 0x76, 0x78, 0xb2,
+      0x73, 0xbe, 0xd6, 0xb8, 0xe3, 0xc1, 0x74, 0x3b, 0x71, 0x16, 0xe6, 0x9e, 0x22, 0x22, 0x95, 0x16,
+      0x3f, 0xf1, 0xca, 0xa1, 0x68, 0x1f, 0xac, 0x09, 0x12, 0x0e, 0xca, 0x30, 0x75, 0x86, 0xe1, 0xa7
+    }  /* result */
+  },
+  
+  /* F.2.2 (decrypt) */
+  { 1, 4 * AES_BLKLEN, 0,
+    { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c },        /* AES key */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f },        /* Nonce */
+    { 0x76, 0x49, 0xab, 0xac, 0x81, 0x19, 0xb2, 0x46, 0xce, 0xe9, 0x8e, 0x9b, 0x12, 0xe9, 0x19, 0x7d,
+      0x50, 0x86, 0xcb, 0x9b, 0x50, 0x72, 0x19, 0xee, 0x95, 0xdb, 0x11, 0x3a, 0x91, 0x76, 0x78, 0xb2,
+      0x73, 0xbe, 0xd6, 0xb8, 0xe3, 0xc1, 0x74, 0x3b, 0x71, 0x16, 0xe6, 0x9e, 0x22, 0x22, 0x95, 0x16,
+      0x3f, 0xf1, 0xca, 0xa1, 0x68, 0x1f, 0xac, 0x09, 0x12, 0x0e, 0xca, 0x30, 0x75, 0x86, 0xe1, 0xa7
+    }, /* msg */
+    4 * AES_BLKLEN,    /* length of result */
+    { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
+      0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
+      0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
+      0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10
+    }  /* result */
+  }
+};
diff --git a/extlibs/tinydtls/tests/ccm-test.c b/extlibs/tinydtls/tests/ccm-test.c
new file mode 100644 (file)
index 0000000..cbb7d2a
--- /dev/null
@@ -0,0 +1,96 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif
+
+#ifdef WITH_CONTIKI
+#include "contiki.h"
+#include "contiki-lib.h"
+#include "contiki-net.h"
+#endif /* WITH_CONTIKI */
+
+//#include "debug.h"
+#include "numeric.h"
+#include "ccm.h"
+
+#include "ccm-testdata.c"
+
+#ifndef HAVE_FLS
+int fls(unsigned int i) {
+  int n;
+  for (n = 0; i; n++)
+    i >>= 1;
+  return n;
+}
+#endif
+
+void 
+dump(unsigned char *buf, size_t len) {
+  size_t i = 0;
+  while (i < len) {
+    printf("%02x ", buf[i++]);
+    if (i % 4 == 0)
+      printf(" ");
+    if (i % 16 == 0)
+      printf("\n\t");
+  }
+  printf("\n");
+}
+
+#ifdef WITH_CONTIKI
+PROCESS(ccm_test_process, "CCM test process");
+AUTOSTART_PROCESSES(&ccm_test_process);
+PROCESS_THREAD(ccm_test_process, ev, d)
+{
+#else  /* WITH_CONTIKI */
+int main(int argc, char **argv) {
+#endif /* WITH_CONTIKI */
+  long int len;
+  int n;
+
+  rijndael_ctx ctx;
+
+#ifdef WITH_CONTIKI
+  PROCESS_BEGIN();
+#endif /* WITH_CONTIKI */
+
+  for (n = 0; n < sizeof(data)/sizeof(struct test_vector); ++n) {
+
+    if (rijndael_set_key_enc_only(&ctx, data[n].key, 8*sizeof(data[n].key)) < 0) {
+      fprintf(stderr, "cannot set key\n");
+      return -1;
+    }
+
+    len = dtls_ccm_encrypt_message(&ctx, data[n].M, data[n].L, data[n].nonce, 
+                                  data[n].msg + data[n].la, 
+                                  data[n].lm - data[n].la, 
+                                  data[n].msg, data[n].la);
+    
+    len +=  + data[n].la;
+    printf("Packet Vector #%d ", n+1);
+    if (len != data[n].r_lm || memcmp(data[n].msg, data[n].result, len))
+      printf("FAILED, ");
+    else 
+      printf("OK, ");
+    
+    printf("result is (total length = %lu):\n\t", len);
+    dump(data[n].msg, len);
+
+    len = dtls_ccm_decrypt_message(&ctx, data[n].M, data[n].L, data[n].nonce, 
+                                  data[n].msg + data[n].la, len - data[n].la, 
+                                  data[n].msg, data[n].la);
+    
+    if (len < 0)
+      printf("Packet Vector #%d: cannot decrypt message\n", n+1);
+    else 
+      printf("\t*** MAC verified (total length = %lu) ***\n", len + data[n].la);
+  }
+
+#ifdef WITH_CONTIKI
+  PROCESS_END();
+#else /* WITH_CONTIKI */
+  return 0;
+#endif /* WITH_CONTIKI */
+}
diff --git a/extlibs/tinydtls/tests/ccm-testdata.c b/extlibs/tinydtls/tests/ccm-testdata.c
new file mode 100644 (file)
index 0000000..f0da4ae
--- /dev/null
@@ -0,0 +1,395 @@
+/* dtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/* test vectors from RFC 3610 */
+
+struct test_vector {
+  size_t M, L;
+  size_t lm;                   /* overall message length */
+  size_t la;                   /* number of bytes additional data */
+  unsigned char key[DTLS_CCM_BLOCKSIZE];
+  unsigned char nonce[DTLS_CCM_BLOCKSIZE];
+  unsigned char msg[200];
+  size_t r_lm;                 /* overall result length */
+  unsigned char result[200];   /* result */
+};
+
+struct test_vector data[] = {
+  /* #1 */
+  { 8, 2, 31, 8,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E},       /* msg */
+    39,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x58, 0x8C, 0x97, 0x9A, 0x61, 0xC6, 0x63, 0xD2, 0xF0, 0x66, 0xD0, 0xC2, 0xC0, 0xF9, 0x89, 0x80, 0x6D, 0x5F, 0x6B, 0x61, 0xDA, 0xC3, 0x84, 0x17, 0xE8, 0xD1, 0x2C, 0xFD, 0xF9, 0x26, 0xE0}        /* result */
+  },
+  
+  /* #2 */
+  { 8, 2, 32, 8,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x04, 0x03, 0x02, 0x01, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F}, /* msg */
+    40,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x72, 0xC9, 0x1A, 0x36, 0xE1, 0x35, 0xF8, 0xCF, 0x29, 0x1C, 0xA8, 0x94, 0x08, 0x5C, 0x87, 0xE3, 0xCC, 0x15, 0xC4, 0x39, 0xC9, 0xE4, 0x3A, 0x3B, 0xA0, 0x91, 0xD5, 0x6E, 0x10, 0x40, 0x09, 0x16}  /* result */
+  },
+
+  /* #3 */
+  { 8, 2, 33, 8,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x05, 0x04, 0x03, 0x02, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20},   /* msg */
+    41,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x51, 0xB1, 0xE5, 0xF4, 0x4A, 0x19, 0x7D, 0x1D, 0xA4, 0x6B, 0x0F, 0x8E, 0x2D, 0x28, 0x2A, 0xE8, 0x71, 0xE8, 0x38, 0xBB, 0x64, 0xDA, 0x85, 0x96, 0x57, 0x4A, 0xDA, 0xA7, 0x6F, 0xBD, 0x9F, 0xB0, 0xC5}    /* result */
+  },
+
+  /* #4 */
+  { 8, 2, 31, 12,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x06, 0x05, 0x04, 0x03, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E},       /* msg */
+    39,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xA2, 0x8C, 0x68, 0x65, 0x93, 0x9A, 0x9A, 0x79, 0xFA, 0xAA, 0x5C, 0x4C, 0x2A, 0x9D, 0x4A, 0x91, 0xCD, 0xAC, 0x8C, 0x96, 0xC8, 0x61, 0xB9, 0xC9, 0xE6, 0x1E, 0xF1}        /* result */
+  },
+
+  /* #5 */
+  { 8, 2, 32, 12,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x07, 0x06, 0x05, 0x04, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F}, /* msg */
+    40,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xDC, 0xF1, 0xFB, 0x7B, 0x5D, 0x9E, 0x23, 0xFB, 0x9D, 0x4E, 0x13, 0x12, 0x53, 0x65, 0x8A, 0xD8, 0x6E, 0xBD, 0xCA, 0x3E, 0x51, 0xE8, 0x3F, 0x07, 0x7D, 0x9C, 0x2D, 0x93}  /* result */
+  },
+
+  /* #6 */
+  { 8, 2, 33, 12,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x08, 0x07, 0x06, 0x05, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20},   /* msg */
+    41,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x6F, 0xC1, 0xB0, 0x11, 0xF0, 0x06, 0x56, 0x8B, 0x51, 0x71, 0xA4, 0x2D, 0x95, 0x3D, 0x46, 0x9B, 0x25, 0x70, 0xA4, 0xBD, 0x87, 0x40, 0x5A, 0x04, 0x43, 0xAC, 0x91, 0xCB, 0x94}    /* result */
+  },
+
+  /* #7 */
+  { 10, 2, 31, 8,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x09, 0x08, 0x07, 0x06, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E},       /* msg */
+    41,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x01, 0x35, 0xD1, 0xB2, 0xC9, 0x5F, 0x41, 0xD5, 0xD1, 0xD4, 0xFE, 0xC1, 0x85, 0xD1, 0x66, 0xB8, 0x09, 0x4E, 0x99, 0x9D, 0xFE, 0xD9, 0x6C, 0x04, 0x8C, 0x56, 0x60, 0x2C, 0x97, 0xAC, 0xBB, 0x74, 0x90}    /* result */
+  },
+
+  /* #8 */
+  { 10, 2, 32, 8,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x0A, 0x09, 0x08, 0x07, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F}, /* msg */
+    42,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x7B, 0x75, 0x39, 0x9A, 0xC0, 0x83, 0x1D, 0xD2, 0xF0, 0xBB, 0xD7, 0x58, 0x79, 0xA2, 0xFD, 0x8F, 0x6C, 0xAE, 0x6B, 0x6C, 0xD9, 0xB7, 0xDB, 0x24, 0xC1, 0x7B, 0x44, 0x33, 0xF4, 0x34, 0x96, 0x3F, 0x34, 0xB4}      /* result */
+  },
+
+  /* #9 */
+  { 10, 2, 33, 8,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x0B, 0x0A, 0x09, 0x08, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20},   /* msg */
+    43,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x82, 0x53, 0x1A, 0x60, 0xCC, 0x24, 0x94, 0x5A, 0x4B, 0x82, 0x79, 0x18, 0x1A, 0xB5, 0xC8, 0x4D, 0xF2, 0x1C, 0xE7, 0xF9, 0xB7, 0x3F, 0x42, 0xE1, 0x97, 0xEA, 0x9C, 0x07, 0xE5, 0x6B, 0x5E, 0xB1, 0x7E, 0x5F, 0x4E}        /* result */
+  },
+
+  /* #10 */
+  { 10, 2, 31, 12,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x0C, 0x0B, 0x0A, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E},       /* msg */
+    41,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x07, 0x34, 0x25, 0x94, 0x15, 0x77, 0x85, 0x15, 0x2B, 0x07, 0x40, 0x98, 0x33, 0x0A, 0xBB, 0x14, 0x1B, 0x94, 0x7B, 0x56, 0x6A, 0xA9, 0x40, 0x6B, 0x4D, 0x99, 0x99, 0x88, 0xDD}    /* result */
+  },
+
+  /* #11 */
+  { 10, 2, 32, 12,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x0D, 0x0C, 0x0B, 0x0A, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F}, /* msg */
+    42,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x67, 0x6B, 0xB2, 0x03, 0x80, 0xB0, 0xE3, 0x01, 0xE8, 0xAB, 0x79, 0x59, 0x0A, 0x39, 0x6D, 0xA7, 0x8B, 0x83, 0x49, 0x34, 0xF5, 0x3A, 0xA2, 0xE9, 0x10, 0x7A, 0x8B, 0x6C, 0x02, 0x2C}      /* result */
+  },
+
+  /* #12 */
+  { 10, 2, 33, 12,
+    { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, /* AES key */
+    { 0x00, 0x00, 0x00, 0x0E, 0x0D, 0x0C, 0x0B, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5},   /* Nonce */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20},   /* msg */
+    43,        /* length of result */
+    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xC0, 0xFF, 0xA0, 0xD6, 0xF0, 0x5B, 0xDB, 0x67, 0xF2, 0x4D, 0x43, 0xA4, 0x33, 0x8D, 0x2A, 0xA4, 0xBE, 0xD7, 0xB2, 0x0E, 0x43, 0xCD, 0x1A, 0xA3, 0x16, 0x62, 0xE7, 0xAD, 0x65, 0xD6, 0xDB}        /* result */
+  },
+
+  /* #13 */
+  { 8, 2, 31, 8,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x41, 0x2B, 0x4E, 0xA9, 0xCD, 0xBE, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0x0B, 0xE1, 0xA8, 0x8B, 0xAC, 0xE0, 0x18, 0xB1, 0x08, 0xE8, 0xCF, 0x97, 0xD8, 0x20, 0xEA, 0x25, 0x84, 0x60, 0xE9, 0x6A, 0xD9, 0xCF, 0x52, 0x89, 0x05, 0x4D, 0x89, 0x5C, 0xEA, 0xC4, 0x7C},       /* msg */
+    39,        /* length of result */
+    { 0x0B, 0xE1, 0xA8, 0x8B, 0xAC, 0xE0, 0x18, 0xB1, 0x4C, 0xB9, 0x7F, 0x86, 0xA2, 0xA4, 0x68, 0x9A, 0x87, 0x79, 0x47, 0xAB, 0x80, 0x91, 0xEF, 0x53, 0x86, 0xA6, 0xFF, 0xBD, 0xD0, 0x80, 0xF8, 0xE7, 0x8C, 0xF7, 0xCB, 0x0C, 0xDD, 0xD7, 0xB3}        /* result */
+  },
+
+  /* #14 */
+  { 8, 2, 32, 8,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x33, 0x56, 0x8E, 0xF7, 0xB2, 0x63, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0x63, 0x01, 0x8F, 0x76, 0xDC, 0x8A, 0x1B, 0xCB, 0x90, 0x20, 0xEA, 0x6F, 0x91, 0xBD, 0xD8, 0x5A, 0xFA, 0x00, 0x39, 0xBA, 0x4B, 0xAF, 0xF9, 0xBF, 0xB7, 0x9C, 0x70, 0x28, 0x94, 0x9C, 0xD0, 0xEC}, /* msg */
+    40,        /* length of result */
+    { 0x63, 0x01, 0x8F, 0x76, 0xDC, 0x8A, 0x1B, 0xCB, 0x4C, 0xCB, 0x1E, 0x7C, 0xA9, 0x81, 0xBE, 0xFA, 0xA0, 0x72, 0x6C, 0x55, 0xD3, 0x78, 0x06, 0x12, 0x98, 0xC8, 0x5C, 0x92, 0x81, 0x4A, 0xBC, 0x33, 0xC5, 0x2E, 0xE8, 0x1D, 0x7D, 0x77, 0xC0, 0x8A}  /* result */
+  },
+
+  /* #15 */
+  { 8, 2, 33, 8,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x10, 0x3F, 0xE4, 0x13, 0x36, 0x71, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0xAA, 0x6C, 0xFA, 0x36, 0xCA, 0xE8, 0x6B, 0x40, 0xB9, 0x16, 0xE0, 0xEA, 0xCC, 0x1C, 0x00, 0xD7, 0xDC, 0xEC, 0x68, 0xEC, 0x0B, 0x3B, 0xBB, 0x1A, 0x02, 0xDE, 0x8A, 0x2D, 0x1A, 0xA3, 0x46, 0x13, 0x2E},   /* msg */
+    41,        /* length of result */
+    { 0xAA, 0x6C, 0xFA, 0x36, 0xCA, 0xE8, 0x6B, 0x40, 0xB1, 0xD2, 0x3A, 0x22, 0x20, 0xDD, 0xC0, 0xAC, 0x90, 0x0D, 0x9A, 0xA0, 0x3C, 0x61, 0xFC, 0xF4, 0xA5, 0x59, 0xA4, 0x41, 0x77, 0x67, 0x08, 0x97, 0x08, 0xA7, 0x76, 0x79, 0x6E, 0xDB, 0x72, 0x35, 0x06}    /* result */
+  },
+
+  /* #16 */
+  { 8, 2, 31, 12,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x76, 0x4C, 0x63, 0xB8, 0x05, 0x8E, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0xD0, 0xD0, 0x73, 0x5C, 0x53, 0x1E, 0x1B, 0xEC, 0xF0, 0x49, 0xC2, 0x44, 0x12, 0xDA, 0xAC, 0x56, 0x30, 0xEF, 0xA5, 0x39, 0x6F, 0x77, 0x0C, 0xE1, 0xA6, 0x6B, 0x21, 0xF7, 0xB2, 0x10, 0x1C},       /* msg */
+    39,        /* length of result */
+    { 0xD0, 0xD0, 0x73, 0x5C, 0x53, 0x1E, 0x1B, 0xEC, 0xF0, 0x49, 0xC2, 0x44, 0x14, 0xD2, 0x53, 0xC3, 0x96, 0x7B, 0x70, 0x60, 0x9B, 0x7C, 0xBB, 0x7C, 0x49, 0x91, 0x60, 0x28, 0x32, 0x45, 0x26, 0x9A, 0x6F, 0x49, 0x97, 0x5B, 0xCA, 0xDE, 0xAF}        /* result */
+  },
+
+  /* #17 */
+  { 8, 2, 32, 12,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0xF8, 0xB6, 0x78, 0x09, 0x4E, 0x3B, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0x77, 0xB6, 0x0F, 0x01, 0x1C, 0x03, 0xE1, 0x52, 0x58, 0x99, 0xBC, 0xAE, 0xE8, 0x8B, 0x6A, 0x46, 0xC7, 0x8D, 0x63, 0xE5, 0x2E, 0xB8, 0xC5, 0x46, 0xEF, 0xB5, 0xDE, 0x6F, 0x75, 0xE9, 0xCC, 0x0D}, /* msg */
+    40,        /* length of result */
+    { 0x77, 0xB6, 0x0F, 0x01, 0x1C, 0x03, 0xE1, 0x52, 0x58, 0x99, 0xBC, 0xAE, 0x55, 0x45, 0xFF, 0x1A, 0x08, 0x5E, 0xE2, 0xEF, 0xBF, 0x52, 0xB2, 0xE0, 0x4B, 0xEE, 0x1E, 0x23, 0x36, 0xC7, 0x3E, 0x3F, 0x76, 0x2C, 0x0C, 0x77, 0x44, 0xFE, 0x7E, 0x3C}  /* result */
+  },
+
+  /* #18 */
+  { 8, 2, 33, 12,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0xD5, 0x60, 0x91, 0x2D, 0x3F, 0x70, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0xCD, 0x90, 0x44, 0xD2, 0xB7, 0x1F, 0xDB, 0x81, 0x20, 0xEA, 0x60, 0xC0, 0x64, 0x35, 0xAC, 0xBA, 0xFB, 0x11, 0xA8, 0x2E, 0x2F, 0x07, 0x1D, 0x7C, 0xA4, 0xA5, 0xEB, 0xD9, 0x3A, 0x80, 0x3B, 0xA8, 0x7F},   /* msg */
+    41,        /* length of result */
+    { 0xCD, 0x90, 0x44, 0xD2, 0xB7, 0x1F, 0xDB, 0x81, 0x20, 0xEA, 0x60, 0xC0, 0x00, 0x97, 0x69, 0xEC, 0xAB, 0xDF, 0x48, 0x62, 0x55, 0x94, 0xC5, 0x92, 0x51, 0xE6, 0x03, 0x57, 0x22, 0x67, 0x5E, 0x04, 0xC8, 0x47, 0x09, 0x9E, 0x5A, 0xE0, 0x70, 0x45, 0x51}    /* result */
+  },
+
+  /* #19 */
+  { 10, 2, 31, 8,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x42, 0xFF, 0xF8, 0xF1, 0x95, 0x1C, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0xD8, 0x5B, 0xC7, 0xE6, 0x9F, 0x94, 0x4F, 0xB8, 0x8A, 0x19, 0xB9, 0x50, 0xBC, 0xF7, 0x1A, 0x01, 0x8E, 0x5E, 0x67, 0x01, 0xC9, 0x17, 0x87, 0x65, 0x98, 0x09, 0xD6, 0x7D, 0xBE, 0xDD, 0x18},       /* msg */
+    41,        /* length of result */
+    { 0xD8, 0x5B, 0xC7, 0xE6, 0x9F, 0x94, 0x4F, 0xB8, 0xBC, 0x21, 0x8D, 0xAA, 0x94, 0x74, 0x27, 0xB6, 0xDB, 0x38, 0x6A, 0x99, 0xAC, 0x1A, 0xEF, 0x23, 0xAD, 0xE0, 0xB5, 0x29, 0x39, 0xCB, 0x6A, 0x63, 0x7C, 0xF9, 0xBE, 0xC2, 0x40, 0x88, 0x97, 0xC6, 0xBA}    /* result */
+  },
+
+  /* #20 */
+  { 10, 2, 32, 8,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x92, 0x0F, 0x40, 0xE5, 0x6C, 0xDC, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0x74, 0xA0, 0xEB, 0xC9, 0x06, 0x9F, 0x5B, 0x37, 0x17, 0x61, 0x43, 0x3C, 0x37, 0xC5, 0xA3, 0x5F, 0xC1, 0xF3, 0x9F, 0x40, 0x63, 0x02, 0xEB, 0x90, 0x7C, 0x61, 0x63, 0xBE, 0x38, 0xC9, 0x84, 0x37}, /* msg */
+    42,        /* length of result */
+    { 0x74, 0xA0, 0xEB, 0xC9, 0x06, 0x9F, 0x5B, 0x37, 0x58, 0x10, 0xE6, 0xFD, 0x25, 0x87, 0x40, 0x22, 0xE8, 0x03, 0x61, 0xA4, 0x78, 0xE3, 0xE9, 0xCF, 0x48, 0x4A, 0xB0, 0x4F, 0x44, 0x7E, 0xFF, 0xF6, 0xF0, 0xA4, 0x77, 0xCC, 0x2F, 0xC9, 0xBF, 0x54, 0x89, 0x44}      /* result */
+  },
+
+  /* #21 */
+  { 10, 2, 33, 8,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x27, 0xCA, 0x0C, 0x71, 0x20, 0xBC, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0x44, 0xA3, 0xAA, 0x3A, 0xAE, 0x64, 0x75, 0xCA, 0xA4, 0x34, 0xA8, 0xE5, 0x85, 0x00, 0xC6, 0xE4, 0x15, 0x30, 0x53, 0x88, 0x62, 0xD6, 0x86, 0xEA, 0x9E, 0x81, 0x30, 0x1B, 0x5A, 0xE4, 0x22, 0x6B, 0xFA},   /* msg */
+    43,        /* length of result */
+    { 0x44, 0xA3, 0xAA, 0x3A, 0xAE, 0x64, 0x75, 0xCA, 0xF2, 0xBE, 0xED, 0x7B, 0xC5, 0x09, 0x8E, 0x83, 0xFE, 0xB5, 0xB3, 0x16, 0x08, 0xF8, 0xE2, 0x9C, 0x38, 0x81, 0x9A, 0x89, 0xC8, 0xE7, 0x76, 0xF1, 0x54, 0x4D, 0x41, 0x51, 0xA4, 0xED, 0x3A, 0x8B, 0x87, 0xB9, 0xCE}        /* result */
+  },
+
+  /* #22 */
+  { 10, 2, 31, 12,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x5B, 0x8C, 0xCB, 0xCD, 0x9A, 0xF8, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0xEC, 0x46, 0xBB, 0x63, 0xB0, 0x25, 0x20, 0xC3, 0x3C, 0x49, 0xFD, 0x70, 0xB9, 0x6B, 0x49, 0xE2, 0x1D, 0x62, 0x17, 0x41, 0x63, 0x28, 0x75, 0xDB, 0x7F, 0x6C, 0x92, 0x43, 0xD2, 0xD7, 0xC2},       /* msg */
+    41,        /* length of result */
+    { 0xEC, 0x46, 0xBB, 0x63, 0xB0, 0x25, 0x20, 0xC3, 0x3C, 0x49, 0xFD, 0x70, 0x31, 0xD7, 0x50, 0xA0, 0x9D, 0xA3, 0xED, 0x7F, 0xDD, 0xD4, 0x9A, 0x20, 0x32, 0xAA, 0xBF, 0x17, 0xEC, 0x8E, 0xBF, 0x7D, 0x22, 0xC8, 0x08, 0x8C, 0x66, 0x6B, 0xE5, 0xC1, 0x97}    /* result */
+  },
+
+  /* #23 */
+  { 10, 2, 32, 12,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x3E, 0xBE, 0x94, 0x04, 0x4B, 0x9A, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0x47, 0xA6, 0x5A, 0xC7, 0x8B, 0x3D, 0x59, 0x42, 0x27, 0xE8, 0x5E, 0x71, 0xE2, 0xFC, 0xFB, 0xB8, 0x80, 0x44, 0x2C, 0x73, 0x1B, 0xF9, 0x51, 0x67, 0xC8, 0xFF, 0xD7, 0x89, 0x5E, 0x33, 0x70, 0x76}, /* msg */
+    42,        /* length of result */
+    { 0x47, 0xA6, 0x5A, 0xC7, 0x8B, 0x3D, 0x59, 0x42, 0x27, 0xE8, 0x5E, 0x71, 0xE8, 0x82, 0xF1, 0xDB, 0xD3, 0x8C, 0xE3, 0xED, 0xA7, 0xC2, 0x3F, 0x04, 0xDD, 0x65, 0x07, 0x1E, 0xB4, 0x13, 0x42, 0xAC, 0xDF, 0x7E, 0x00, 0xDC, 0xCE, 0xC7, 0xAE, 0x52, 0x98, 0x7D}      /* result */
+  },
+
+  /* #24 */
+  { 10, 2, 33, 12,
+    { 0xD7, 0x82, 0x8D, 0x13, 0xB2, 0xB0, 0xBD, 0xC3, 0x25, 0xA7, 0x62, 0x36, 0xDF, 0x93, 0xCC, 0x6B}, /* AES key */
+    { 0x00, 0x8D, 0x49, 0x3B, 0x30, 0xAE, 0x8B, 0x3C, 0x96, 0x96, 0x76, 0x6C, 0xFA},   /* Nonce */
+    { 0x6E, 0x37, 0xA6, 0xEF, 0x54, 0x6D, 0x95, 0x5D, 0x34, 0xAB, 0x60, 0x59, 0xAB, 0xF2, 0x1C, 0x0B, 0x02, 0xFE, 0xB8, 0x8F, 0x85, 0x6D, 0xF4, 0xA3, 0x73, 0x81, 0xBC, 0xE3, 0xCC, 0x12, 0x85, 0x17, 0xD4},   /* msg */
+    43,        /* length of result */
+    { 0x6E, 0x37, 0xA6, 0xEF, 0x54, 0x6D, 0x95, 0x5D, 0x34, 0xAB, 0x60, 0x59, 0xF3, 0x29, 0x05, 0xB8, 0x8A, 0x64, 0x1B, 0x04, 0xB9, 0xC9, 0xFF, 0xB5, 0x8C, 0xC3, 0x90, 0x90, 0x0F, 0x3D, 0xA1, 0x2A, 0xB1, 0x6D, 0xCE, 0x9E, 0x82, 0xEF, 0xA1, 0x6D, 0xA6, 0x20, 0x59}        /* result */
+  },
+
+  /* #25 */
+  /* Cipher: AES-128 M=16 L=2 K_LEN=1 N_LEN=13 K=0x00 N=0x00000000000000000000000000 */
+  { 16, 2, 0, 0,
+    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, /* AES key */  
+    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, /* Nonce */
+    { },       /* msg */
+    16,                /* length of result */
+    { 0x8b, 0x60, 0xab, 0xcd, 0x60, 0x43, 0x81, 0x0b, 
+      0xa3, 0x78, 0xa0, 0x1d, 0x4a, 0x29, 0x83, 0x0b
+    }          /* result */
+  },
+
+  /* #26 */
+  /* Cipher: AES-128 M=16 L=2 K_LEN=1 N_LEN=13 K=0x00 N=0x00000000000000000000000000 */
+  { 16, 2, 37, 0,
+    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, /* AES key */  
+    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
+      0x00, 0x00, 0x00, 0x00 }, /* Nonce */
+    { 0x45, 0x69, 0x6e, 0x20, 0x6b, 0x6c, 0x65, 0x69, 
+      0x6e, 0x65, 0x72, 0x20, 0x54, 0x65, 0x78, 0x74,
+      0x0a, 0x7a, 0x75, 0x6d, 0x20, 0x54, 0x65, 0x73,
+      0x74, 0x65, 0x6e, 0x20, 0x76, 0x6f, 0x6e, 0x20,
+      0x43, 0x43, 0x4d, 0x2e, 0x0a
+    }, /* msg */
+    53,                /* length of result */
+    { 0x90, 0x11, 0x9c, 0x2d, 0x6b, 0xf9, 0xe9, 0x05,
+      0x3e, 0x0b, 0x44, 0x56, 0xca, 0xc8, 0xb6, 0x1a,
+      0x00, 0x57, 0xa9, 0x8b, 0x6b, 0x69, 0x09, 0x7e, 
+      0x8e, 0x50, 0x50, 0x63, 0x50, 0x58, 0x0f, 0x78,
+      0x75, 0x69, 0x6e, 0x9f, 0x3d, 0x63, 0x93, 0xe7,
+      0x7a, 0x84, 0xe9, 0x9f, 0x11, 0x93, 0x95, 0xa0,
+      0x9a, 0xef, 0x0d, 0xa0, 0xed
+    } /* result */
+  },
+
+  /* #27 */
+  /* Cipher: AES-128 M=8 L=5 K_LEN=16 N_LEN=10 K=0x001234567890abcdefdcaffeed3921ee N=0x00112233445566778899 */
+  { 8, 5, 0, 0,
+    { 0x00, 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd,
+      0xef, 0xdc, 0xaf, 0xfe, 0xed, 0x39, 0x21, 0xee }, /* AES key */
+    { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
+      0x88, 0x99 }, /* Nonce */
+    { },           /* msg */
+    8,             /* length of result */
+    { 0xb1, 0x33, 0x51, 0xc8, 0xb3, 0xd5, 0x10, 0xa7 } /* result */
+  },
+
+  /* #28 */
+  /* Cipher: AES-128 M=8 L=5 K_LEN=16 N_LEN=10 K=0x001234567890abcdefdcaffeed3921ee N=0x00112233445566778899 */
+  { 8, 5, 37, 0,
+    { 0x00, 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd,
+      0xef, 0xdc, 0xaf, 0xfe, 0xed, 0x39, 0x21, 0xee }, /* AES key */
+    { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
+      0x88, 0x99 }, /* Nonce */
+    { 0x45, 0x69, 0x6e, 0x20, 0x6b, 0x6c, 0x65, 0x69, 
+      0x6e, 0x65, 0x72, 0x20, 0x54, 0x65, 0x78, 0x74,
+      0x0a, 0x7a, 0x75, 0x6d, 0x20, 0x54, 0x65, 0x73,
+      0x74, 0x65, 0x6e, 0x20, 0x76, 0x6f, 0x6e, 0x20,
+      0x43, 0x43, 0x4d, 0x2e, 0x0a
+    }, /* msg */
+    45,                    /* length of result */
+    { 0x44, 0x7a, 0x82, 0x70, 0x1d, 0xd0, 0x35, 0x7b,
+      0x68, 0xf7, 0x35, 0x4d, 0xbf, 0xd9, 0x16, 0x15,
+      0x97, 0x41, 0x3d, 0x1e, 0x89, 0xc1, 0x25, 0xe7,
+      0xd6, 0xa7, 0xde, 0x90, 0x1e, 0xf1, 0x69, 0x69,
+      0x9f, 0xce, 0x40, 0xdc, 0xf0, 0xd1, 0x74, 0x53,
+      0x2c, 0xa3, 0xb0, 0xcf, 0xb9
+    } /* result */
+  },
+
+  /* #29 */
+  /* Cipher: AES-128 M=14 L=3 K_LEN=16 N_LEN=12 K=0x001234567890abcdefdcaffeed3921ee N=0x001122334455667788990000 */
+  { 14, 3, 0, 0,
+    { 0x00, 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd,
+      0xef, 0xdc, 0xaf, 0xfe, 0xed, 0x39, 0x21, 0xee }, /* AES key */
+    { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
+      0x88, 0x99, 0x00, 0x00 }, /* Nonce */
+    { },           /* msg */
+    14,                    /* length of result */
+    { 0xa4, 0x06, 0xa4, 0x23, 0x93, 0x3d, 0xa0, 0xca,
+      0xb5, 0x90, 0xdb, 0x69, 0x69, 0x33 } /* result */
+  },
+
+  /* #30 */
+  /* Cipher: AES-128 M=14 L=3 K_LEN=16 N_LEN=12 K=0x001234567890abcdefdcaffeed3921ee N=0x001122334455667788990000 */
+  { 14, 3, 37, 0,
+    { 0x00, 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd,
+      0xef, 0xdc, 0xaf, 0xfe, 0xed, 0x39, 0x21, 0xee }, /* AES key */
+    { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
+      0x88, 0x99, 0x00, 0x00 }, /* Nonce */
+    { 0x45, 0x69, 0x6e, 0x20, 0x6b, 0x6c, 0x65, 0x69, 
+      0x6e, 0x65, 0x72, 0x20, 0x54, 0x65, 0x78, 0x74,
+      0x0a, 0x7a, 0x75, 0x6d, 0x20, 0x54, 0x65, 0x73,
+      0x74, 0x65, 0x6e, 0x20, 0x76, 0x6f, 0x6e, 0x20,
+      0x43, 0x43, 0x4d, 0x2e, 0x0a
+    }, /* msg */
+    51,
+    { 0x60, 0xaf, 0x87, 0x67, 0x4d, 0x9d, 0x54, 0x17,
+      0x16, 0xc0, 0x29, 0x10, 0x7e, 0x3e, 0x34, 0x93,
+      0x78, 0xe8, 0xd3, 0xc8, 0xc1, 0x03, 0x4f, 0xd6,
+      0xf5, 0x3b, 0xaf, 0xd3, 0xf0, 0xd7, 0x0b, 0xdd,
+      0x63, 0x93, 0xed, 0xf2, 0xb2, 0x72, 0xdc, 0xae,
+      0x7c, 0xa0, 0x01, 0xdb, 0x56, 0x2a, 0x06, 0xb6,
+      0xe9, 0xcf, 0x3c } /* result */
+  },
+
+  /* #31 */
+  /* Cipher: AES-128 M=8 L=5 K_LEN=6 N_LEN=10 K=0x11223344aabb N=0x00112233445566778899 */
+  { 8, 5, 0, 0,
+    { 0x11, 0x22, 0x33, 0x44, 0xaa, 0xbb },    /* AES key */
+    { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
+      0x88, 0x99 },                            /* Nonce */
+    { },                                       /* msg */
+    8,
+    { 0x28, 0x15, 0xfe, 0x81, 0xdd, 0xc3, 0x79, 0x04 } /* result */
+  },
+
+  /* #32 */
+  /* Cipher: AES-128 M=8 L=5 K_LEN=6 N_LEN=10 K=0x11223344aabb N=0x00112233445566778899 */
+
+  { 8, 5, 37, 0,
+    { 0x11, 0x22, 0x33, 0x44, 0xaa, 0xbb },    /* AES key */
+    { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
+      0x88, 0x99 },                            /* Nonce */
+    { 0x45, 0x69, 0x6e, 0x20, 0x6b, 0x6c, 0x65, 0x69, 
+      0x6e, 0x65, 0x72, 0x20, 0x54, 0x65, 0x78, 0x74,
+      0x0a, 0x7a, 0x75, 0x6d, 0x20, 0x54, 0x65, 0x73,
+      0x74, 0x65, 0x6e, 0x20, 0x76, 0x6f, 0x6e, 0x20,
+      0x43, 0x43, 0x4d, 0x2e, 0x0a
+    }, /* msg */
+    45,
+    { 0xdb, 0x31, 0x55, 0x9d, 0xab, 0x70, 0xdc, 0x62,
+      0xd7, 0x76, 0x41, 0xb2, 0x14, 0x9e, 0x9c, 0x26,
+      0x70, 0x61, 0xea, 0x36, 0xf8, 0x0e, 0xdf, 0x19,
+      0xa6, 0xc7, 0x46, 0x3d, 0x5a, 0xc3, 0x0a, 0x73,
+      0x14, 0x96, 0xa4, 0x84, 0x7f, 0x37, 0x55, 0x42,
+      0xce, 0x7e, 0xf9, 0x3b, 0xe5 } /* result */
+  }
+};
diff --git a/extlibs/tinydtls/tests/dsrv-test.c b/extlibs/tinydtls/tests/dsrv-test.c
new file mode 100644 (file)
index 0000000..e7b44a9
--- /dev/null
@@ -0,0 +1,108 @@
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <netinet/in.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+
+#include "dsrv.h" 
+
+void
+handle_read(struct dsrv_context_t *ctx) {
+  int len;
+  static char buf[200];
+  struct sockaddr_storage src;
+  socklen_t srclen = sizeof(src);
+  int fd = dsrv_get_fd(ctx, DSRV_READ);
+
+  len = recvfrom(fd, buf, sizeof(buf), 0, 
+                (struct sockaddr *)&src, &srclen);
+
+  if (len < 0) {
+    perror("recvfrom");
+  } else {
+    printf("read %d bytes: '%*s'\n", len, len, buf);
+    if (dsrv_sendto(ctx, (struct sockaddr *)&src, srclen, 0, buf, len) 
+       == NULL) {
+      fprintf(stderr, "cannot add packet to sendqueue\n");
+    }
+  }
+}
+
+int
+handle_write(struct dsrv_context_t *ctx) {
+  struct packet_t *p;
+  int fd = dsrv_get_fd(ctx, DSRV_WRITE);
+  int len;
+
+  p = ctx->rq ? nq_peek(ctx->wq) : NULL;
+
+  if (!p)
+    return -1;
+
+  len = sendto(fd, p->buf, p->len, 0, p->raddr, p->rlen);
+  
+  if (len < 0)
+    perror("sendto");
+  else 
+    nq_pop(ctx->wq);
+
+  return len;
+}
+
+int main(int argc, char **argv) {
+
+#if 1
+  struct sockaddr_in6 listen_addr = { AF_INET6, htons(20220), 0, IN6ADDR_ANY_INIT, 0 };
+#else
+  struct sockaddr_in listen_addr = { AF_INET, htons(20220), { htonl(0x7f000001) } };
+#endif
+  fd_set rfds, wfds;
+  struct timeval timeout;
+  struct dsrv_context_t *ctx;
+  int result;
+
+  ctx = dsrv_new_context((struct sockaddr *)&listen_addr, sizeof(listen_addr), 
+                        200,200);
+
+  if (!ctx) {
+    fprintf(stderr, "E: cannot create server context\n");
+    return -1;
+  }
+
+  while (1) {
+    FD_ZERO(&rfds);
+    FD_ZERO(&wfds);
+
+    dsrv_prepare(ctx, &rfds, DSRV_READ);
+    dsrv_prepare(ctx, &wfds, DSRV_WRITE);
+    
+#if 0
+    timeout.tv_sec = 0;
+    timeout.tv_usec = dsrv_get_timeout(ctx);
+#else
+    timeout.tv_sec = 5;
+    timeout.tv_usec = 0;
+#endif
+    
+    result = select( FD_SETSIZE, &rfds, &wfds, 0, &timeout);
+    
+    if (result < 0) {          /* error */
+      if (errno != EINTR)
+       perror("select");
+    } else if (result == 0) {  /* timeout */
+      printf(".");             
+    } else {                   /* ok */
+      if (dsrv_check(ctx, &wfds, DSRV_WRITE))
+       handle_write(ctx);
+      else if (dsrv_check(ctx, &rfds, DSRV_READ))
+       handle_read(ctx);
+    }
+  }
+
+  dsrv_close(ctx);
+  dsrv_free_context(ctx);
+
+  return 0;
+}
diff --git a/extlibs/tinydtls/tests/dtls-client.c b/extlibs/tinydtls/tests/dtls-client.c
new file mode 100644 (file)
index 0000000..1c48c1a
--- /dev/null
@@ -0,0 +1,544 @@
+#include "tinydtls.h" 
+
+/* This is needed for apple */
+#define __APPLE_USE_RFC_3542
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <ctype.h>
+#include <netinet/in.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <signal.h>
+
+#include "global.h" 
+#include "debug.h" 
+#include "dtls.h" 
+
+#define DEFAULT_PORT 20220
+
+#define PSK_CLIENT_IDENTITY  "Client_identity"
+#define PSK_SERVER_IDENTITY  "Server_identity"
+#define PSK_DEFAULT_KEY      "secretPSK"
+#define PSK_OPTIONS          "i:s:k:"
+
+#ifdef __GNUC__
+#define UNUSED_PARAM __attribute__((unused))
+#else
+#define UNUSED_PARAM
+#endif /* __GNUC__ */
+
+static char buf[200];
+static size_t len = 0;
+
+typedef struct {
+  size_t length;               /* length of string */
+  unsigned char *s;            /* string data */
+} dtls_str;
+
+static dtls_str output_file = { 0, NULL }; /* output file name */
+
+static dtls_context_t *dtls_context = NULL;
+static dtls_context_t *orig_dtls_context = NULL;
+
+
+static const unsigned char ecdsa_priv_key[] = {
+                       0x41, 0xC1, 0xCB, 0x6B, 0x51, 0x24, 0x7A, 0x14,
+                       0x43, 0x21, 0x43, 0x5B, 0x7A, 0x80, 0xE7, 0x14,
+                       0x89, 0x6A, 0x33, 0xBB, 0xAD, 0x72, 0x94, 0xCA,
+                       0x40, 0x14, 0x55, 0xA1, 0x94, 0xA9, 0x49, 0xFA};
+
+static const unsigned char ecdsa_pub_key_x[] = {
+                       0x36, 0xDF, 0xE2, 0xC6, 0xF9, 0xF2, 0xED, 0x29,
+                       0xDA, 0x0A, 0x9A, 0x8F, 0x62, 0x68, 0x4E, 0x91,
+                       0x63, 0x75, 0xBA, 0x10, 0x30, 0x0C, 0x28, 0xC5,
+                       0xE4, 0x7C, 0xFB, 0xF2, 0x5F, 0xA5, 0x8F, 0x52};
+
+static const unsigned char ecdsa_pub_key_y[] = {
+                       0x71, 0xA0, 0xD4, 0xFC, 0xDE, 0x1A, 0xB8, 0x78,
+                       0x5A, 0x3C, 0x78, 0x69, 0x35, 0xA7, 0xCF, 0xAB,
+                       0xE9, 0x3F, 0x98, 0x72, 0x09, 0xDA, 0xED, 0x0B,
+                       0x4F, 0xAB, 0xC3, 0x6F, 0xC7, 0x72, 0xF8, 0x29};
+
+#ifdef DTLS_PSK
+ssize_t
+read_from_file(char *arg, unsigned char *buf, size_t max_buf_len) {
+  FILE *f;
+  ssize_t result = 0;
+
+  f = fopen(arg, "r");
+  if (f == NULL)
+    return -1;
+
+  while (!feof(f)) {
+    size_t bytes_read;
+    bytes_read = fread(buf, 1, max_buf_len, f);
+    if (ferror(f)) {
+      result = -1;
+      break;
+    }
+
+    buf += bytes_read;
+    result += bytes_read;
+    max_buf_len -= bytes_read;
+  }
+
+  fclose(f);
+  return result;
+}
+
+/* The PSK information for DTLS */
+#define PSK_ID_MAXLEN 256
+#define PSK_MAXLEN 256
+static unsigned char psk_client_id[PSK_ID_MAXLEN];
+static size_t psk_client_id_length = 0;
+static unsigned char psk_server_id[PSK_ID_MAXLEN];
+static size_t psk_server_id_length = 0;
+static unsigned char psk_key[PSK_MAXLEN];
+static size_t psk_key_length = 0;
+
+/* This function is the "key store" for tinyDTLS. It is called to
+ * retrieve a key for the given identity within this particular
+ * session. */
+static int
+get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
+           const session_t *session UNUSED_PARAM,
+           dtls_credentials_type_t type,
+           const unsigned char *id, size_t id_len,
+           unsigned char *result, size_t result_length) {
+
+  switch (type) {
+  case DTLS_PSK_IDENTITY:
+    if (id_len) {
+      dtls_debug("got psk_identity_hint: '%.*s'\n", id_len, id);
+    }
+
+    if (result_length < psk_client_id_length) {
+      dtls_warn("cannot set psk_identity -- buffer too small\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    memcpy(result, psk_client_id, psk_client_id_length);
+    return psk_client_id_length;
+  case DTLS_PSK_KEY:
+    if (id_len != psk_server_id_length || memcmp(psk_server_id, id, id_len) != 0) {
+      dtls_warn("PSK for unknown id requested, exiting\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
+    } else if (result_length < psk_key_length) {
+      dtls_warn("cannot set psk -- buffer too small\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    memcpy(result, psk_key, psk_key_length);
+    return psk_key_length;
+  default:
+    dtls_warn("unsupported request type: %d\n", type);
+  }
+
+  return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+}
+#endif /* DTLS_PSK */
+
+#ifdef DTLS_ECC
+static int
+get_ecdsa_key(struct dtls_context_t *ctx,
+             const session_t *session,
+             const dtls_ecdsa_key_t **result) {
+  static const dtls_ecdsa_key_t ecdsa_key = {
+    .curve = DTLS_ECDH_CURVE_SECP256R1,
+    .priv_key = ecdsa_priv_key,
+    .pub_key_x = ecdsa_pub_key_x,
+    .pub_key_y = ecdsa_pub_key_y
+  };
+
+  *result = &ecdsa_key;
+  return 0;
+}
+
+static int
+verify_ecdsa_key(struct dtls_context_t *ctx,
+                const session_t *session,
+                const unsigned char *other_pub_x,
+                const unsigned char *other_pub_y,
+                size_t key_size) {
+  return 0;
+}
+#endif /* DTLS_ECC */
+
+static void
+try_send(struct dtls_context_t *ctx, session_t *dst) {
+  int res;
+  res = dtls_write(ctx, dst, (uint8 *)buf, len);
+  if (res >= 0) {
+    memmove(buf, buf + res, len - res);
+    len -= res;
+  }
+}
+
+static void
+handle_stdin() {
+  if (fgets(buf + len, sizeof(buf) - len, stdin))
+    len += strlen(buf + len);
+}
+
+static int
+read_from_peer(struct dtls_context_t *ctx, 
+              session_t *session, uint8 *data, size_t len) {
+  size_t i;
+  for (i = 0; i < len; i++)
+    printf("%c", data[i]);
+  return 0;
+}
+
+static int
+send_to_peer(struct dtls_context_t *ctx, 
+            session_t *session, uint8 *data, size_t len) {
+
+  int fd = *(int *)dtls_get_app_data(ctx);
+  return sendto(fd, data, len, MSG_DONTWAIT,
+               &session->addr.sa, session->size);
+}
+
+static int
+dtls_handle_read(struct dtls_context_t *ctx) {
+  int fd;
+  session_t session;
+#define MAX_READ_BUF 2000
+  static uint8 buf[MAX_READ_BUF];
+  int len;
+
+  fd = *(int *)dtls_get_app_data(ctx);
+  
+  if (!fd)
+    return -1;
+
+  memset(&session, 0, sizeof(session_t));
+  session.size = sizeof(session.addr);
+  len = recvfrom(fd, buf, MAX_READ_BUF, 0, 
+                &session.addr.sa, &session.size);
+  
+  if (len < 0) {
+    perror("recvfrom");
+    return -1;
+  } else {
+    dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer", &session);
+    dtls_debug_dump("bytes from peer", buf, len);
+  }
+
+  return dtls_handle_message(ctx, &session, buf, len);
+}    
+
+static void dtls_handle_signal(int sig)
+{
+  dtls_free_context(dtls_context);
+  dtls_free_context(orig_dtls_context);
+  signal(sig, SIG_DFL);
+  kill(getpid(), sig);
+}
+
+/* stolen from libcoap: */
+static int
+resolve_address(const char *server, struct sockaddr *dst) {
+  
+  struct addrinfo *res, *ainfo;
+  struct addrinfo hints;
+  static char addrstr[256];
+  int error;
+
+  memset(addrstr, 0, sizeof(addrstr));
+  if (server && strlen(server) > 0)
+    memcpy(addrstr, server, strlen(server));
+  else
+    memcpy(addrstr, "localhost", 9);
+
+  memset ((char *)&hints, 0, sizeof(hints));
+  hints.ai_socktype = SOCK_DGRAM;
+  hints.ai_family = AF_UNSPEC;
+
+  error = getaddrinfo(addrstr, "", &hints, &res);
+
+  if (error != 0) {
+    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
+    return error;
+  }
+
+  for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
+
+    switch (ainfo->ai_family) {
+    case AF_INET6:
+    case AF_INET:
+
+      memcpy(dst, ainfo->ai_addr, ainfo->ai_addrlen);
+      return ainfo->ai_addrlen;
+    default:
+      ;
+    }
+  }
+
+  freeaddrinfo(res);
+  return -1;
+}
+
+/*---------------------------------------------------------------------------*/
+static void
+usage( const char *program, const char *version) {
+  const char *p;
+
+  p = strrchr( program, '/' );
+  if ( p )
+    program = ++p;
+
+  fprintf(stderr, "%s v%s -- DTLS client implementation\n"
+         "(c) 2011-2014 Olaf Bergmann <bergmann@tzi.org>\n\n"
+#ifdef DTLS_PSK
+         "usage: %s [-i file] [-s file] [-k file] [-o file] [-p port] [-v num] addr [port]\n"
+#else /*  DTLS_PSK */
+         "usage: %s [-o file] [-p port] [-v num] addr [port]\n"
+#endif /* DTLS_PSK */
+#ifdef DTLS_PSK
+         "\t-i file\t\tread PSK Client identity from file\n"
+         "\t-s file\t\tread PSK Server identity from file\n"
+         "\t-k file\t\tread pre-shared key from file\n"
+#endif /* DTLS_PSK */
+         "\t-o file\t\toutput received data to this file (use '-' for STDOUT)\n"
+         "\t-p port\t\tlisten on specified port (default is %d)\n"
+         "\t-v num\t\tverbosity level (default: 3)\n",
+          program, version, program, DEFAULT_PORT);
+}
+
+static dtls_handler_t cb = {
+  .write = send_to_peer,
+  .read  = read_from_peer,
+  .event = NULL,
+#ifdef DTLS_PSK
+  .get_psk_info = get_psk_info,
+#endif /* DTLS_PSK */
+#ifdef DTLS_ECC
+  .get_ecdsa_key = get_ecdsa_key,
+  .verify_ecdsa_key = verify_ecdsa_key
+#endif /* DTLS_ECC */
+};
+
+#define DTLS_CLIENT_CMD_CLOSE "client:close"
+#define DTLS_CLIENT_CMD_RENEGOTIATE "client:renegotiate"
+
+/* As per RFC 6347 section 4.2.8, DTLS Server should support requests
+ * from clients who have silently abandoned the existing association
+ * and initiated a new handshake request by sending a ClientHello.
+ * Below command tests this feature.
+ */
+#define DTLS_CLIENT_CMD_REHANDSHAKE "client:rehandshake"
+int 
+main(int argc, char **argv) {
+  fd_set rfds, wfds;
+  struct timeval timeout;
+  unsigned short port = DEFAULT_PORT;
+  char port_str[NI_MAXSERV] = "0";
+  log_t log_level = DTLS_LOG_WARN;
+  int fd, result;
+  int on = 1;
+  int opt, res;
+  session_t dst;
+
+  dtls_init();
+  snprintf(port_str, sizeof(port_str), "%d", port);
+
+#ifdef DTLS_PSK
+  psk_client_id_length = strlen(PSK_CLIENT_IDENTITY);
+  psk_server_id_length = strlen(PSK_SERVER_IDENTITY);
+  psk_key_length = strlen(PSK_DEFAULT_KEY);
+  memcpy(psk_client_id, PSK_CLIENT_IDENTITY, psk_client_id_length);
+  memcpy(psk_server_id, PSK_SERVER_IDENTITY, psk_server_id_length);
+  memcpy(psk_key, PSK_DEFAULT_KEY, psk_key_length);
+#endif /* DTLS_PSK */
+
+  while ((opt = getopt(argc, argv, "p:o:v:" PSK_OPTIONS)) != -1) {
+    switch (opt) {
+#ifdef DTLS_PSK
+    case 'i' : {
+      ssize_t result = read_from_file(optarg, psk_client_id, PSK_ID_MAXLEN);
+      if (result < 0) {
+       dtls_warn("cannot read Client PSK identity\n");
+      } else {
+       psk_client_id_length = result;
+      }
+      break;
+    }
+    case 's' : {
+      ssize_t result = read_from_file(optarg, psk_server_id, PSK_ID_MAXLEN);
+      if (result < 0) {
+       dtls_warn("cannot read Server PSK identity\n");
+      } else {
+       psk_server_id_length = result;
+      }
+      break;
+    }
+    case 'k' : {
+      ssize_t result = read_from_file(optarg, psk_key, PSK_MAXLEN);
+      if (result < 0) {
+       dtls_warn("cannot read PSK\n");
+      } else {
+       psk_key_length = result;
+      }
+      break;
+    }
+#endif /* DTLS_PSK */
+    case 'p' :
+      strncpy(port_str, optarg, NI_MAXSERV-1);
+      port_str[NI_MAXSERV - 1] = '\0';
+      break;
+    case 'o' :
+      output_file.length = strlen(optarg);
+      output_file.s = (unsigned char *)malloc(output_file.length + 1);
+      
+      if (!output_file.s) {
+       dtls_crit("cannot set output file: insufficient memory\n");
+       exit(-1);
+      } else {
+       /* copy filename including trailing zero */
+       memcpy(output_file.s, optarg, output_file.length + 1);
+      }
+      break;
+    case 'v' :
+      log_level = strtol(optarg, NULL, 10);
+      break;
+    default:
+      usage(argv[0], dtls_package_version());
+      exit(1);
+    }
+  }
+
+  dtls_set_log_level(log_level);
+  
+  if (argc <= optind) {
+    usage(argv[0], dtls_package_version());
+    exit(1);
+  }
+  
+  memset(&dst, 0, sizeof(session_t));
+  /* resolve destination address where server should be sent */
+  res = resolve_address(argv[optind++], &dst.addr.sa);
+  if (res < 0) {
+    dtls_emerg("failed to resolve address\n");
+    exit(-1);
+  }
+  dst.size = res;
+
+  /* use port number from command line when specified or the listen
+     port, otherwise */
+  dst.addr.sin.sin_port = htons(atoi(optind < argc ? argv[optind++] : port_str));
+
+  
+  /* init socket and set it to non-blocking */
+  fd = socket(dst.addr.sa.sa_family, SOCK_DGRAM, 0);
+
+  if (fd < 0) {
+    dtls_alert("socket: %s\n", strerror(errno));
+    return 0;
+  }
+
+  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+    dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
+  }
+#if 0
+  flags = fcntl(fd, F_GETFL, 0);
+  if (flags < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
+    dtls_alert("fcntl: %s\n", strerror(errno));
+    goto error;
+  }
+#endif
+  on = 1;
+#ifdef IPV6_RECVPKTINFO
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+#else /* IPV6_RECVPKTINFO */
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+#endif /* IPV6_RECVPKTINFO */
+    dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
+  }
+
+  if (signal(SIGINT, dtls_handle_signal) == SIG_ERR) {
+    dtls_alert("An error occurred while setting a signal handler.\n");
+    return EXIT_FAILURE;
+  }
+
+  dtls_context = dtls_new_context(&fd);
+  if (!dtls_context) {
+    dtls_emerg("cannot create context\n");
+    exit(-1);
+  }
+
+  dtls_set_handler(dtls_context, &cb);
+
+  dtls_connect(dtls_context, &dst);
+
+  while (1) {
+    FD_ZERO(&rfds);
+    FD_ZERO(&wfds);
+
+    FD_SET(fileno(stdin), &rfds);
+    FD_SET(fd, &rfds);
+    /* FD_SET(fd, &wfds); */
+    
+    timeout.tv_sec = 5;
+    timeout.tv_usec = 0;
+    
+    result = select(fd+1, &rfds, &wfds, 0, &timeout);
+    
+    if (result < 0) {          /* error */
+      if (errno != EINTR)
+       perror("select");
+    } else if (result == 0) {  /* timeout */
+    } else {                   /* ok */
+      if (FD_ISSET(fd, &wfds))
+       /* FIXME */;
+      else if (FD_ISSET(fd, &rfds))
+       dtls_handle_read(dtls_context);
+      else if (FD_ISSET(fileno(stdin), &rfds))
+       handle_stdin();
+    }
+
+    if (len) {
+      if (len >= strlen(DTLS_CLIENT_CMD_CLOSE) &&
+         !memcmp(buf, DTLS_CLIENT_CMD_CLOSE, strlen(DTLS_CLIENT_CMD_CLOSE))) {
+       printf("client: closing connection\n");
+       dtls_close(dtls_context, &dst);
+       len = 0;
+      } else if (len >= strlen(DTLS_CLIENT_CMD_RENEGOTIATE) &&
+                !memcmp(buf, DTLS_CLIENT_CMD_RENEGOTIATE, strlen(DTLS_CLIENT_CMD_RENEGOTIATE))) {
+       printf("client: renegotiate connection\n");
+       dtls_renegotiate(dtls_context, &dst);
+       len = 0;
+      } else if (len >= strlen(DTLS_CLIENT_CMD_REHANDSHAKE) &&
+                !memcmp(buf, DTLS_CLIENT_CMD_REHANDSHAKE, strlen(DTLS_CLIENT_CMD_REHANDSHAKE))) {
+       printf("client: rehandshake connection\n");
+       if (orig_dtls_context == NULL) {
+         /* Cache the current context. We cannot free the current context as it will notify 
+          * the Server to close the connection (which we do not want).
+          */
+         orig_dtls_context = dtls_context;
+         /* Now, Create a new context and attempt to initiate a handshake. */
+         dtls_context = dtls_new_context(&fd);
+         if (!dtls_context) {
+           dtls_emerg("cannot create context\n");
+           exit(-1);
+          }
+         dtls_set_handler(dtls_context, &cb);
+         dtls_connect(dtls_context, &dst);
+       }
+       len = 0;
+      } else {
+       try_send(dtls_context, &dst);
+      }
+    }
+  }
+  
+  dtls_free_context(dtls_context);
+  dtls_free_context(orig_dtls_context);
+  exit(0);
+}
+
diff --git a/extlibs/tinydtls/tests/dtls-server.c b/extlibs/tinydtls/tests/dtls-server.c
new file mode 100644 (file)
index 0000000..ae1283e
--- /dev/null
@@ -0,0 +1,381 @@
+
+/* This is needed for apple */
+#define __APPLE_USE_RFC_3542
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <netinet/in.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <netdb.h>
+#include <signal.h>
+
+#include "tinydtls.h" 
+#include "dtls.h" 
+#include "debug.h" 
+
+#define DEFAULT_PORT 20220
+
+static const unsigned char ecdsa_priv_key[] = {
+                       0xD9, 0xE2, 0x70, 0x7A, 0x72, 0xDA, 0x6A, 0x05,
+                       0x04, 0x99, 0x5C, 0x86, 0xED, 0xDB, 0xE3, 0xEF,
+                       0xC7, 0xF1, 0xCD, 0x74, 0x83, 0x8F, 0x75, 0x70,
+                       0xC8, 0x07, 0x2D, 0x0A, 0x76, 0x26, 0x1B, 0xD4};
+
+static const unsigned char ecdsa_pub_key_x[] = {
+                       0xD0, 0x55, 0xEE, 0x14, 0x08, 0x4D, 0x6E, 0x06,
+                       0x15, 0x59, 0x9D, 0xB5, 0x83, 0x91, 0x3E, 0x4A,
+                       0x3E, 0x45, 0x26, 0xA2, 0x70, 0x4D, 0x61, 0xF2,
+                       0x7A, 0x4C, 0xCF, 0xBA, 0x97, 0x58, 0xEF, 0x9A};
+
+static const unsigned char ecdsa_pub_key_y[] = {
+                       0xB4, 0x18, 0xB6, 0x4A, 0xFE, 0x80, 0x30, 0xDA,
+                       0x1D, 0xDC, 0xF4, 0xF4, 0x2E, 0x2F, 0x26, 0x31,
+                       0xD0, 0x43, 0xB1, 0xFB, 0x03, 0xE2, 0x2F, 0x4D,
+                       0x17, 0xDE, 0x43, 0xF9, 0xF9, 0xAD, 0xEE, 0x70};
+
+#if 0
+/* SIGINT handler: set quit to 1 for graceful termination */
+void
+handle_sigint(int signum) {
+  dsrv_stop(dsrv_get_context());
+}
+#endif
+
+#ifdef DTLS_PSK
+
+#define PSK_SERVER_HINT  "Server_identity"
+
+/* This function is the "key store" for tinyDTLS. It is called to
+ * retrieve a key for the given identity within this particular
+ * session. */
+static int
+get_psk_info(struct dtls_context_t *ctx, const session_t *session,
+            dtls_credentials_type_t type,
+            const unsigned char *id, size_t id_len,
+            unsigned char *result, size_t result_length) {
+
+  struct keymap_t {
+    unsigned char *id;
+    size_t id_length;
+    unsigned char *key;
+    size_t key_length;
+  } psk[3] = {
+    { (unsigned char *)"Client_identity", 15,
+      (unsigned char *)"secretPSK", 9 },
+    { (unsigned char *)"default identity", 16,
+      (unsigned char *)"\x11\x22\x33", 3 },
+    { (unsigned char *)"\0", 2,
+      (unsigned char *)"", 1 }
+  };
+
+  switch (type) {
+  case DTLS_PSK_HINT:
+    if (result_length < strlen(PSK_SERVER_HINT)) {
+      dtls_warn("cannot set psk_hint -- buffer too small\n");
+      return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+    }
+
+    memcpy(result, PSK_SERVER_HINT, strlen(PSK_SERVER_HINT));
+    return strlen(PSK_SERVER_HINT);
+
+  case DTLS_PSK_KEY:
+    if (id) {
+      int i;
+      for (i = 0; i < sizeof(psk)/sizeof(struct keymap_t); i++) {
+        if (id_len == psk[i].id_length && memcmp(id, psk[i].id, id_len) == 0) {
+         if (result_length < psk[i].key_length) {
+           dtls_warn("buffer too small for PSK");
+           return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
+         }
+
+         memcpy(result, psk[i].key, psk[i].key_length);
+         return psk[i].key_length;
+        }
+      }
+    }
+    break;
+
+  default:
+    dtls_warn("unsupported request type: %d\n", type);
+  }
+
+  return dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
+}
+
+#endif /* DTLS_PSK */
+
+#ifdef DTLS_ECC
+static int
+get_ecdsa_key(struct dtls_context_t *ctx,
+             const session_t *session,
+             const dtls_ecdsa_key_t **result) {
+  static const dtls_ecdsa_key_t ecdsa_key = {
+    .curve = DTLS_ECDH_CURVE_SECP256R1,
+    .priv_key = ecdsa_priv_key,
+    .pub_key_x = ecdsa_pub_key_x,
+    .pub_key_y = ecdsa_pub_key_y
+  };
+
+  *result = &ecdsa_key;
+  return 0;
+}
+
+static int
+verify_ecdsa_key(struct dtls_context_t *ctx,
+                const session_t *session,
+                const unsigned char *other_pub_x,
+                const unsigned char *other_pub_y,
+                size_t key_size) {
+  return 0;
+}
+#endif /* DTLS_ECC */
+
+#define DTLS_SERVER_CMD_CLOSE "server:close"
+#define DTLS_SERVER_CMD_RENEGOTIATE "server:renegotiate"
+
+static int
+read_from_peer(struct dtls_context_t *ctx, 
+              session_t *session, uint8 *data, size_t len) {
+  size_t i;
+  for (i = 0; i < len; i++)
+    printf("%c", data[i]);
+  if (len >= strlen(DTLS_SERVER_CMD_CLOSE) &&
+      !memcmp(data, DTLS_SERVER_CMD_CLOSE, strlen(DTLS_SERVER_CMD_CLOSE))) {
+    printf("server: closing connection\n");
+    dtls_close(ctx, session);
+    return len;
+  } else if (len >= strlen(DTLS_SERVER_CMD_RENEGOTIATE) &&
+      !memcmp(data, DTLS_SERVER_CMD_RENEGOTIATE, strlen(DTLS_SERVER_CMD_RENEGOTIATE))) {
+    printf("server: renegotiate connection\n");
+    dtls_renegotiate(ctx, session);
+    return len;
+  }
+
+  return dtls_write(ctx, session, data, len);
+}
+
+static int
+send_to_peer(struct dtls_context_t *ctx, 
+            session_t *session, uint8 *data, size_t len) {
+
+  int fd = *(int *)dtls_get_app_data(ctx);
+  return sendto(fd, data, len, MSG_DONTWAIT,
+               &session->addr.sa, session->size);
+}
+
+static int
+dtls_handle_read(struct dtls_context_t *ctx) {
+  int *fd;
+  session_t session;
+  static uint8 buf[DTLS_MAX_BUF];
+  int len;
+
+  fd = dtls_get_app_data(ctx);
+
+  assert(fd);
+
+  memset(&session, 0, sizeof(session_t));
+  session.size = sizeof(session.addr);
+  len = recvfrom(*fd, buf, sizeof(buf), MSG_TRUNC,
+                &session.addr.sa, &session.size);
+
+  if (len < 0) {
+    perror("recvfrom");
+    return -1;
+  } else {
+    dtls_debug("got %d bytes from port %d\n", len, 
+            ntohs(session.addr.sin6.sin6_port));
+    if (sizeof(buf) < len) {
+      dtls_warn("packet was truncated (%d bytes lost)\n", len - sizeof(buf));
+    }
+  }
+
+  return dtls_handle_message(ctx, &session, buf, len);
+}    
+
+static int
+resolve_address(const char *server, struct sockaddr *dst) {
+  
+  struct addrinfo *res, *ainfo;
+  struct addrinfo hints;
+  static char addrstr[256];
+  int error;
+
+  memset(addrstr, 0, sizeof(addrstr));
+  if (server && strlen(server) > 0)
+    memcpy(addrstr, server, strlen(server));
+  else
+    memcpy(addrstr, "localhost", 9);
+
+  memset ((char *)&hints, 0, sizeof(hints));
+  hints.ai_socktype = SOCK_DGRAM;
+  hints.ai_family = AF_UNSPEC;
+
+  error = getaddrinfo(addrstr, "", &hints, &res);
+
+  if (error != 0) {
+    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
+    return error;
+  }
+
+  for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
+
+    switch (ainfo->ai_family) {
+    case AF_INET6:
+
+      memcpy(dst, ainfo->ai_addr, ainfo->ai_addrlen);
+      return ainfo->ai_addrlen;
+    default:
+      ;
+    }
+  }
+
+  freeaddrinfo(res);
+  return -1;
+}
+
+static void
+usage(const char *program, const char *version) {
+  const char *p;
+
+  p = strrchr( program, '/' );
+  if ( p )
+    program = ++p;
+
+  fprintf(stderr, "%s v%s -- DTLS server implementation\n"
+         "(c) 2011-2014 Olaf Bergmann <bergmann@tzi.org>\n\n"
+         "usage: %s [-A address] [-p port] [-v num]\n"
+         "\t-A address\t\tlisten on specified address (default is ::)\n"
+         "\t-p port\t\tlisten on specified port (default is %d)\n"
+         "\t-v num\t\tverbosity level (default: 3)\n",
+          program, version, program, DEFAULT_PORT);
+}
+
+static dtls_handler_t cb = {
+  .write = send_to_peer,
+  .read  = read_from_peer,
+  .event = NULL,
+#ifdef DTLS_PSK
+  .get_psk_info = get_psk_info,
+#endif /* DTLS_PSK */
+#ifdef DTLS_ECC
+  .get_ecdsa_key = get_ecdsa_key,
+  .verify_ecdsa_key = verify_ecdsa_key
+#endif /* DTLS_ECC */
+};
+
+int 
+main(int argc, char **argv) {
+  dtls_context_t *the_context = NULL;
+  log_t log_level = DTLS_LOG_WARN;
+  fd_set rfds, wfds;
+  struct timeval timeout;
+  int fd, opt, result;
+  int on = 1;
+  struct sockaddr_in6 listen_addr;
+
+  memset(&listen_addr, 0, sizeof(struct sockaddr_in6));
+
+  /* fill extra field for 4.4BSD-based systems (see RFC 3493, section 3.4) */
+#if defined(SIN6_LEN) || defined(HAVE_SOCKADDR_IN6_SIN6_LEN)
+  listen_addr.sin6_len = sizeof(struct sockaddr_in6);
+#endif
+
+  listen_addr.sin6_family = AF_INET6;
+  listen_addr.sin6_port = htons(DEFAULT_PORT);
+  listen_addr.sin6_addr = in6addr_any;
+
+  while ((opt = getopt(argc, argv, "A:p:v:")) != -1) {
+    switch (opt) {
+    case 'A' :
+      if (resolve_address(optarg, (struct sockaddr *)&listen_addr) < 0) {
+       fprintf(stderr, "cannot resolve address\n");
+       exit(-1);
+      }
+      break;
+    case 'p' :
+      listen_addr.sin6_port = htons(atoi(optarg));
+      break;
+    case 'v' :
+      log_level = strtol(optarg, NULL, 10);
+      break;
+    default:
+      usage(argv[0], dtls_package_version());
+      exit(1);
+    }
+  }
+
+  dtls_set_log_level(log_level);
+
+  /* init socket and set it to non-blocking */
+  fd = socket(listen_addr.sin6_family, SOCK_DGRAM, 0);
+
+  if (fd < 0) {
+    dtls_alert("socket: %s\n", strerror(errno));
+    return 0;
+  }
+
+  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+    dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
+  }
+#if 0
+  flags = fcntl(fd, F_GETFL, 0);
+  if (flags < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
+    dtls_alert("fcntl: %s\n", strerror(errno));
+    goto error;
+  }
+#endif
+  on = 1;
+#ifdef IPV6_RECVPKTINFO
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+#else /* IPV6_RECVPKTINFO */
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+#endif /* IPV6_RECVPKTINFO */
+    dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
+  }
+
+  if (bind(fd, (struct sockaddr *)&listen_addr, sizeof(listen_addr)) < 0) {
+    dtls_alert("bind: %s\n", strerror(errno));
+    goto error;
+  }
+
+  dtls_init();
+
+  the_context = dtls_new_context(&fd);
+
+  dtls_set_handler(the_context, &cb);
+
+  while (1) {
+    FD_ZERO(&rfds);
+    FD_ZERO(&wfds);
+
+    FD_SET(fd, &rfds);
+    /* FD_SET(fd, &wfds); */
+    
+    timeout.tv_sec = 5;
+    timeout.tv_usec = 0;
+    
+    result = select( fd+1, &rfds, &wfds, 0, &timeout);
+    
+    if (result < 0) {          /* error */
+      if (errno != EINTR)
+       perror("select");
+    } else if (result == 0) {  /* timeout */
+    } else {                   /* ok */
+      if (FD_ISSET(fd, &wfds))
+       ;
+      else if (FD_ISSET(fd, &rfds)) {
+       dtls_handle_read(the_context);
+      }
+    }
+  }
+  
+ error:
+  dtls_free_context(the_context);
+  exit(0);
+}
diff --git a/extlibs/tinydtls/tests/netq-test.c b/extlibs/tinydtls/tests/netq-test.c
new file mode 100644 (file)
index 0000000..d0dc66f
--- /dev/null
@@ -0,0 +1,103 @@
+#include <string.h>
+#include <netinet/in.h>
+
+#include "netq.h" 
+
+#ifndef NDEBUG
+extern void nq_dump(struct netq_t *);
+#endif
+
+int main(int argc, char **argv) {
+#ifndef NDEBUG
+  struct netq_t *nq;
+
+  struct sockaddr_in6 dst = { AF_INET6, htons(20220), 0, IN6ADDR_ANY_INIT, 0 };
+  struct packet_t *p;
+
+  char *pkt[20] = { 
+    "Packet #1",
+    "This is packet #2",
+    "The third packet #3 is the largest",
+    "Packet #4",
+    "Packet #5",
+    "Packet #6",
+    "Packet #7"
+  };
+
+  nq = nq_new(200);
+
+  if (!nq) {
+    fprintf(stderr, "E: cannot create network packet queue\n");
+    return -1;
+  }
+
+  if (!nq_new_packet(nq, (struct sockaddr *)&dst, sizeof(dst), 
+                    0, pkt[0], strlen(pkt[0]))) {
+    fprintf(stderr, "E: cannot add packet #1\n");
+  }
+
+  nq_dump(nq);
+
+  if (!nq_new_packet(nq, (struct sockaddr *)&dst, sizeof(dst), 
+                    0, pkt[1], strlen(pkt[1]))) {
+    fprintf(stderr, "E: cannot add packet #2\n");
+  }
+
+  nq_dump(nq);
+
+  if (!nq_new_packet(nq, (struct sockaddr *)&dst, sizeof(dst), 
+                    0, pkt[2], strlen(pkt[2]))) {
+    fprintf(stderr, "E: cannot add packet #3\n");
+  }
+
+  nq_dump(nq);
+
+  p = nq_pop(nq);
+  if (!p) {
+    fprintf(stderr, "E: no packet\n");
+  }
+
+  if (!nq_new_packet(nq, (struct sockaddr *)&dst, sizeof(dst), 
+                    0, pkt[3], strlen(pkt[3]))) {
+    fprintf(stderr, "E: cannot add packet #4\n");
+  }
+
+  nq_dump(nq);
+
+  if (!nq_new_packet(nq, (struct sockaddr *)&dst, sizeof(dst), 
+                    0, pkt[4], strlen(pkt[4]))) {
+    fprintf(stderr, "E: cannot add packet #5\n");
+  }
+
+  nq_dump(nq);
+
+  p = nq_pop(nq);
+  if (!p) {
+    fprintf(stderr, "E: no packet\n");
+  }
+
+  if (!nq_new_packet(nq, (struct sockaddr *)&dst, sizeof(dst), 
+                    0, pkt[5], strlen(pkt[5]))) {
+    fprintf(stderr, "E: cannot add packet #6\n");
+  }
+
+  nq_dump(nq);
+
+  p = nq_pop(nq);
+  p = nq_pop(nq);
+  p = nq_pop(nq);
+  p = nq_pop(nq);
+  p = nq_pop(nq);
+  p = nq_pop(nq);
+  p = nq_pop(nq);
+
+  if (!nq_new_packet(nq, (struct sockaddr *)&dst, sizeof(dst), 
+                    0, pkt[6], strlen(pkt[6]))) {
+    fprintf(stderr, "E: cannot add packet #7\n");
+  }
+
+  nq_dump(nq);
+#endif
+
+  return 0;
+}
diff --git a/extlibs/tinydtls/tests/pcap.c b/extlibs/tinydtls/tests/pcap.c
new file mode 100644 (file)
index 0000000..7534c5f
--- /dev/null
@@ -0,0 +1,478 @@
+#include <stdio.h>
+#include <string.h>
+#include <getopt.h>
+#include <pcap/pcap.h>
+
+#include "tinydtls.h"
+#include "debug.h"
+#include "dtls.h"
+
+#define TRANSPORT_HEADER_SIZE (14+20+8) /* Ethernet + IP + UDP */
+
+/* the pre_master_secret is generated from the PSK at startup */
+unsigned char pre_master_secret[60];
+size_t pre_master_len = 0;
+
+unsigned char master_secret[DTLS_MASTER_SECRET_LENGTH];
+size_t master_secret_len = 0;
+
+dtls_security_parameters_t security_params[2]; 
+int config = 0;
+unsigned int epoch[2] = { 0, 0 };
+
+#if DTLS_VERSION == 0xfeff
+dtls_hash_t hs_hash[2];
+#elif DTLS_VERSION == 0xfefd
+dtls_hash_t hs_hash[1];
+#endif
+
+static inline void
+update_hash(uint8 *record, size_t rlength, 
+           uint8 *data, size_t data_length) {
+  int i;
+
+  if (!hs_hash[0])
+    return;
+
+  for (i = 0; i < sizeof(hs_hash) / sizeof(dtls_hash_t *); ++i) {
+    dtls_hash_update(hs_hash[i], data, data_length);
+  }
+}
+
+static inline void
+finalize_hash(uint8 *buf) {
+#if DTLS_VERSION == 0xfeff
+  unsigned char statebuf[sizeof(md5_state_t) + sizeof(SHA_CTX)];
+#elif DTLS_VERSION == 0xfefd
+  unsigned char statebuf[sizeof(SHA256_CTX)];
+#endif
+
+  if (!hs_hash[0])
+    return;
+
+  /* temporarily store hash status for roll-back after finalize */
+#if DTLS_VERSION == 0xfeff
+  memcpy(statebuf, hs_hash[0], sizeof(md5_state_t));
+  memcpy(statebuf + sizeof(md5_state_t), 
+        hs_hash[1], 
+        sizeof(SHA_CTX));
+#elif DTLS_VERSION == 0xfefd
+  memcpy(statebuf, hs_hash[0], sizeof(statebuf));
+#endif
+
+  dtls_hash_finalize(buf, hs_hash[0]);
+#if DTLS_VERSION == 0xfeff
+  dtls_hash_finalize(buf + 16, hs_hash[1]);
+#endif
+
+  /* restore hash status */
+#if DTLS_VERSION == 0xfeff
+  memcpy(hs_hash[0], statebuf, sizeof(md5_state_t));
+  memcpy(hs_hash[1], 
+        statebuf + sizeof(md5_state_t), 
+        sizeof(SHA_CTX));
+#elif DTLS_VERSION == 0xfefd
+  memcpy(hs_hash[0], statebuf, sizeof(statebuf));
+#endif
+}
+
+static inline void
+clear_hash() {
+  int i;
+
+  for (i = 0; i < sizeof(hs_hash) / sizeof(dtls_hash_t *); ++i)
+    free(hs_hash[i]);
+  memset(hs_hash, 0, sizeof(hs_hash));
+}
+
+#undef CURRENT_CONFIG
+#undef OTHER_CONFIG
+#undef SWITCH_CONFIG
+#define CURRENT_CONFIG (&security_params[config])
+#define OTHER_CONFIG   (&security_params[!(config & 0x01)])
+#define SWITCH_CONFIG  (config = !(config & 0x01))
+
+int
+pcap_verify(dtls_security_parameters_t *sec,
+           int is_client, 
+           const unsigned char *record, size_t record_length,
+           const unsigned char *cleartext, size_t cleartext_length) {
+
+  unsigned char mac[DTLS_HMAC_MAX];
+  dtls_hmac_context_t hmac_ctx;
+  int ok;
+
+  if (cleartext_length < dtls_kb_digest_size(sec))
+    return 0;
+
+  dtls_hmac_init(&hmac_ctx, 
+                is_client 
+                ? dtls_kb_client_mac_secret(sec)
+                : dtls_kb_server_mac_secret(sec),
+                dtls_kb_mac_secret_size(sec));
+
+  cleartext_length -= dtls_kb_digest_size(sec);
+
+  /* calculate MAC even if padding is wrong */
+  dtls_mac(&hmac_ctx, 
+          record,              /* the pre-filled record header */
+          cleartext, cleartext_length,
+          mac);
+
+  ok = memcmp(mac, cleartext + cleartext_length, 
+             dtls_kb_digest_size(sec)) == 0;
+#ifndef NDEBUG
+  printf("MAC (%s): ", ok ? "valid" : "invalid");
+  dump(mac, dtls_kb_digest_size(sec));
+  printf("\n");
+#endif
+  return ok;
+}
+                   
+int
+decrypt_verify(int is_client, const uint8 *packet, size_t length,
+              uint8 **cleartext, size_t *clen) {
+  int res, ok = 0;
+  dtls_cipher_context_t *cipher;
+
+  static unsigned char buf[1000];
+  
+  switch (CURRENT_CONFIG->cipher) {
+  case AES128:                 /* TLS_PSK_WITH_AES128_CBC_SHA */
+    *cleartext = buf;
+    *clen = length - sizeof(dtls_record_header_t);
+
+    if (is_client)
+      cipher = CURRENT_CONFIG->read_cipher;
+    else 
+      cipher = CURRENT_CONFIG->write_cipher; 
+
+    res = dtls_decrypt(cipher,
+                      (uint8 *)packet + sizeof(dtls_record_header_t), *clen, 
+                      buf, NULL, 0);
+
+    if (res < 0) {
+      warn("decryption failed!\n");
+    } else {
+      ok = pcap_verify(CURRENT_CONFIG, is_client, (uint8 *)packet, length, 
+                      *cleartext, res);  
+
+      if (ok)
+       *clen = res - dtls_kb_digest_size(CURRENT_CONFIG);
+    }
+    break;
+  default:                     /* no cipher suite selected */
+    *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
+    *clen = length - sizeof(dtls_record_header_t);
+    
+    ok = 1;
+  }
+  
+  if (ok)
+    printf("verify OK\n");
+  else
+    printf("verification failed!\n");
+  return ok;
+}
+
+#define SKIP_ETH_HEADER(M,L)                   \
+  if ((L) < 14)                                        \
+    return;                                    \
+  else {                                       \
+    (M) += 14;                                 \
+    (L) -= 14;                                 \
+  }
+
+#define SKIP_IP_HEADER(M,L)                            \
+  if (((M)[0] & 0xF0) == 0x40) {       /* IPv4 */      \
+    (M) += (M[0] & 0x0F) * 4;                          \
+    (L) -= (M[0] & 0x0F) * 4;                          \
+  } else                                               \
+    if (((M)[0] & 0xF0) == 0x60) { /* IPv6 */          \
+      (M) += 40;                                       \
+      (L) -= 40;                                       \
+    } 
+
+#define SKIP_UDP_HEADER(M,L) {                 \
+    (M) += 8;                                  \
+    (L) -= 8;                                  \
+  }
+
+void
+handle_packet(const u_char *packet, int length) {
+  static int n = 0;
+  static unsigned char initial_hello[] = { 
+    0x16, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 
+  };
+  uint8 *data; 
+  size_t data_length, rlen;
+  int i, res;
+#if DTLS_VERSION == 0xfeff
+#ifndef SHA1_DIGEST_LENGTH
+#define SHA1_DIGEST_LENGTH 20
+#endif
+  uint8 hash_buf[16 + SHA1_DIGEST_LENGTH];
+#elif DTLS_VERSION == 0xfefd
+  uint8 hash_buf[SHA256_DIGEST_LENGTH];
+#endif
+#define verify_data_length 12
+  int is_client;
+  n++;
+
+  SKIP_ETH_HEADER(packet, length);
+  SKIP_IP_HEADER(packet, length);
+
+  /* determine from port if this is a client */
+  is_client = dtls_uint16_to_int(packet) != 20220;
+
+  SKIP_UDP_HEADER(packet, length);
+
+  while (length) {
+    rlen = dtls_uint16_to_int(packet + 11) + sizeof(dtls_record_header_t);
+
+    if (!rlen) {
+      fprintf(stderr, "invalid length!\n");
+      return;
+    }
+
+    /* skip packet if it is from a different epoch */
+    if (dtls_uint16_to_int(packet + 3) != epoch[is_client])
+      goto next;
+
+    res = decrypt_verify(is_client, packet, rlen,
+                        &data, &data_length);
+
+    if (res <= 0)
+      goto next;
+    
+    printf("packet %d (from %s):\n", n, is_client ? "client" : "server");
+    hexdump(packet, sizeof(dtls_record_header_t));
+    printf("\n");
+    hexdump(data, data_length);
+    printf("\n");
+    
+    if (packet[0] == 22 && data[0] == 1) { /* ClientHello */
+      if (memcmp(packet, initial_hello, sizeof(initial_hello)) == 0)
+       goto next;
+       
+      memcpy(dtls_kb_client_iv(OTHER_CONFIG), data + 14, 32);
+
+       clear_hash();
+#if DTLS_VERSION == 0xfeff
+      hs_hash[0] = dtls_new_hash(HASH_MD5);
+      hs_hash[1] = dtls_new_hash(HASH_SHA1);
+
+      hs_hash[0]->init(hs_hash[0]->data);
+      hs_hash[1]->init(hs_hash[1]->data);
+#elif DTLS_VERSION == 0xfefd
+      dtls_hash_init(hs_hash[0]);
+#endif
+    }
+    
+    if (packet[0] == 22 && data[0] == 2) { /* ServerHello */
+      memcpy(dtls_kb_server_iv(OTHER_CONFIG), data + 14, 32);
+      /* FIXME: search in ciphers */
+      OTHER_CONFIG->cipher = TLS_PSK_WITH_AES_128_CCM_8;
+    }
+    
+    if (packet[0] == 20 && data[0] == 1) { /* ChangeCipherSpec */
+      printf("client random: ");
+      dump(dtls_kb_client_iv(OTHER_CONFIG), 32);
+      printf("\nserver random: ");
+      dump(dtls_kb_server_iv(OTHER_CONFIG), 32);
+      printf("\n");
+      master_secret_len = 
+       dtls_prf(pre_master_secret, pre_master_len,
+                (unsigned char *)"master secret", 13,
+                dtls_kb_client_iv(OTHER_CONFIG), 32,
+                dtls_kb_server_iv(OTHER_CONFIG), 32,
+                master_secret, DTLS_MASTER_SECRET_LENGTH);
+  
+      printf("master_secret:\n  ");
+      for(i = 0; i < master_secret_len; i++) 
+       printf("%02x", master_secret[i]);
+      printf("\n");
+
+      /* create key_block from master_secret
+       * key_block = PRF(master_secret,
+                     "key expansion" + server_random + client_random) */
+      dtls_prf(master_secret, master_secret_len,
+              (unsigned char *)"key expansion", 13,
+              dtls_kb_server_iv(OTHER_CONFIG), 32,
+              dtls_kb_client_iv(OTHER_CONFIG), 32,
+              OTHER_CONFIG->key_block, 
+              dtls_kb_size(OTHER_CONFIG));
+
+      OTHER_CONFIG->read_cipher = 
+       dtls_cipher_new(OTHER_CONFIG->cipher,
+                       dtls_kb_client_write_key(OTHER_CONFIG),
+                       dtls_kb_key_size(OTHER_CONFIG));
+
+      if (!OTHER_CONFIG->read_cipher) {
+       warn("cannot create read cipher\n");
+      } else {
+       dtls_cipher_set_iv(OTHER_CONFIG->read_cipher,
+                          dtls_kb_client_iv(OTHER_CONFIG),
+                          dtls_kb_iv_size(OTHER_CONFIG));
+      }
+
+      OTHER_CONFIG->write_cipher = 
+       dtls_cipher_new(OTHER_CONFIG->cipher, 
+                       dtls_kb_server_write_key(OTHER_CONFIG),
+                       dtls_kb_key_size(OTHER_CONFIG));
+      
+      if (!OTHER_CONFIG->write_cipher) {
+       warn("cannot create write cipher\n");
+      } else {
+       dtls_cipher_set_iv(OTHER_CONFIG->write_cipher,
+                          dtls_kb_server_iv(OTHER_CONFIG),
+                          dtls_kb_iv_size(OTHER_CONFIG));
+      }
+
+      /* if (is_client) */
+       SWITCH_CONFIG;
+      epoch[is_client]++;
+
+      printf("key_block:\n");
+      printf("  client_MAC_secret:\t");  
+      dump(dtls_kb_client_mac_secret(CURRENT_CONFIG), 
+          dtls_kb_mac_secret_size(CURRENT_CONFIG));
+      printf("\n");
+
+      printf("  server_MAC_secret:\t");  
+      dump(dtls_kb_server_mac_secret(CURRENT_CONFIG), 
+          dtls_kb_mac_secret_size(CURRENT_CONFIG));
+      printf("\n");
+
+      printf("  client_write_key:\t");  
+      dump(dtls_kb_client_write_key(CURRENT_CONFIG), 
+          dtls_kb_key_size(CURRENT_CONFIG));
+      printf("\n");
+
+      printf("  server_write_key:\t");  
+      dump(dtls_kb_server_write_key(CURRENT_CONFIG), 
+          dtls_kb_key_size(CURRENT_CONFIG));
+      printf("\n");
+
+      printf("  client_IV:\t\t");  
+      dump(dtls_kb_client_iv(CURRENT_CONFIG), 
+          dtls_kb_iv_size(CURRENT_CONFIG));
+      printf("\n");
+      
+      printf("  server_IV:\t\t");  
+      dump(dtls_kb_server_iv(CURRENT_CONFIG), 
+          dtls_kb_iv_size(CURRENT_CONFIG));
+      printf("\n");
+      
+    }
+
+    if (packet[0] == 22) {
+      if (data[0] == 20) { /* Finished */
+       finalize_hash(hash_buf);
+       /* clear_hash(); */
+
+       update_hash((unsigned char *)packet, sizeof(dtls_record_header_t),
+                   data, data_length);
+
+       dtls_prf(master_secret, master_secret_len,
+                is_client 
+                ? (unsigned char *)"client finished" 
+                : (unsigned char *)"server finished" 
+                , 15,
+                hash_buf, sizeof(hash_buf),
+                NULL, 0,
+                data + sizeof(dtls_handshake_header_t),
+                verify_data_length);
+       printf("verify_data:\n");
+       dump(data, data_length);
+       printf("\n");
+      } else {
+       update_hash((unsigned char *)packet, sizeof(dtls_record_header_t),
+                   data, data_length);
+      }
+    }
+
+    if (packet[0] == 23) {     /* Application Data */
+      printf("Application Data:\n");
+      dump(data, data_length);
+      printf("\n");
+    }
+
+  next:
+    length -= rlen;
+    packet += rlen;
+  }
+}
+
+void init() {
+  memset(security_params, 0, sizeof(security_params));
+  CURRENT_CONFIG->cipher = -1;
+
+  memset(hs_hash, 0, sizeof(hs_hash));
+
+  /* set pre_master_secret to default if no PSK was given */
+  if (!pre_master_len) {
+    /* unsigned char psk[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }; */
+    pre_master_len =
+      dtls_pre_master_secret((unsigned char *)"secretPSK", 9,
+                            pre_master_secret);
+  }
+}
+
+int main(int argc, char **argv) {
+  pcap_t *pcap;
+  char errbuf[PCAP_ERRBUF_SIZE];
+  struct pcap_pkthdr *pkthdr;
+  const u_char *packet;
+  int res = 0;
+  int c, option_index = 0;
+
+  static struct option opts[] = {
+    { "psk",  1, 0, 'p' },
+    { 0, 0, 0, 0 }
+  };
+
+  /* handle command line options */
+  while (1) {
+    c = getopt_long(argc, argv, "p:", opts, &option_index);
+    if (c == -1)
+      break;
+
+    switch (c) {
+    case 'p':
+      pre_master_len = dtls_pre_master_secret((unsigned char *)optarg, 
+                                     strlen(optarg), pre_master_secret);
+      break;
+    }
+  }
+
+  if (argc <= optind) {
+    fprintf(stderr, "usage: %s [-p|--psk PSK] pcapfile\n", argv[0]);
+    return -1;
+  }
+
+  init();
+
+  pcap = pcap_open_offline(argv[optind], errbuf);
+  if (!pcap) {
+    fprintf(stderr, "pcap_open_offline: %s\n", errbuf);
+    return -2;
+  }
+
+  for (;;) {
+    res = pcap_next_ex(pcap, &pkthdr, &packet);
+    
+    switch(res) {
+    case -2: goto done;
+    case -1: pcap_perror(pcap, "read packet"); break;
+    case  1: handle_packet(packet, pkthdr->caplen); break;
+    default: 
+      ;
+    }      
+  }
+ done:
+
+  pcap_close(pcap);
+
+  return 0;
+}
diff --git a/extlibs/tinydtls/tests/prf-test.c b/extlibs/tinydtls/tests/prf-test.c
new file mode 100644 (file)
index 0000000..d8d83d9
--- /dev/null
@@ -0,0 +1,31 @@
+#include <stdio.h>
+
+#include "tinydtls.h"
+#include "debug.h"
+#include "global.h"
+#include "crypto.h"
+
+int 
+main() {
+  /* see http://www.ietf.org/mail-archive/web/tls/current/msg03416.html */
+  unsigned char key[] = { 0x9b, 0xbe, 0x43, 0x6b, 0xa9, 0x40, 0xf0, 0x17, 
+                         0xb1, 0x76, 0x52, 0x84, 0x9a, 0x71, 0xdb, 0x35 };
+  unsigned char label[] = { 0x74, 0x65, 0x73, 0x74, 0x20, 0x6c, 0x61, 0x62, 
+                           0x65, 0x6c};
+  unsigned char random1[] = { 0xa0, 0xba, 0x9f, 0x93, 0x6c, 0xda, 0x31, 0x18};
+  unsigned char random2[] = {0x27, 0xa6, 0xf7, 0x96, 0xff, 0xd5, 0x19, 0x8c
+  };
+  unsigned char buf[200];
+  size_t result;
+  
+  result = dtls_prf(key, sizeof(key),
+                   label, sizeof(label),
+                   random1, sizeof(random1),
+                   random2, sizeof(random2),
+                   buf, 100);
+
+  printf("PRF yields %zu bytes of random data:\n", result);
+  hexdump(buf, result);
+  printf("\n");
+  return 0;
+}
diff --git a/extlibs/tinydtls/tests/secure-server.c b/extlibs/tinydtls/tests/secure-server.c
new file mode 100644 (file)
index 0000000..6ba5258
--- /dev/null
@@ -0,0 +1,862 @@
+/* secure-server -- A (broken) DTLS server example
+ *
+ * Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <sys/select.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <signal.h>
+
+#include <openssl/ssl.h>
+#include <openssl/bio.h>
+#include <openssl/err.h>
+#include <openssl/rand.h>
+
+#ifdef WITH_DTLS
+#define SERVER_CERT_PEM "./server-cert.pem"
+#define SERVER_KEY_PEM  "./server-key.pem"
+#define CA_CERT_PEM     "./ca-cert.pem"
+#endif
+
+#ifdef HAVE_ASSERT_H
+# include <assert.h>
+#else
+# define assert(x)
+#endif /* HAVE_ASSERT_H */
+
+static int quit=0;
+
+/* SIGINT handler: set quit to 1 for graceful termination */
+void
+handle_sigint(int signum) {
+  quit = 1;
+}
+
+int 
+check_connect(int sockfd, char *buf, int buflen, 
+          struct sockaddr *src, int *ifindex) {
+
+  /* for some reason, the definition in netinet/in.h is not exported */
+#ifndef IN6_PKTINFO
+  struct in6_pktinfo
+  {
+    struct in6_addr ipi6_addr; /* src/dst IPv6 address */
+    unsigned int ipi6_ifindex; /* send/recv interface index */
+  };
+#endif
+
+  size_t bytes;
+
+  struct iovec iov[1] = { {buf, buflen} };
+  char cmsgbuf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
+  struct in6_pktinfo *p = NULL;
+  
+  struct msghdr msg = { 0 };
+  struct cmsghdr *cmsg;
+
+  msg.msg_name = src;
+  msg.msg_namelen = sizeof(struct sockaddr_in6);
+  msg.msg_iov = iov;
+  msg.msg_iovlen = 1;
+  msg.msg_control = cmsgbuf;
+  msg.msg_controllen = sizeof(cmsgbuf);
+
+  bytes = recvmsg(sockfd, &msg, MSG_DONTWAIT | MSG_PEEK);
+  if (bytes < 0) {
+    perror("recvmsg");
+    return bytes;
+  }
+
+  /* TODO: handle msg.msg_flags & MSG_TRUNC */
+  if (msg.msg_flags & MSG_CTRUNC) {
+    fprintf(stderr, "control was truncated!\n");
+    return -1;
+  }
+
+  if (ifindex) {
+    /* Here we try to retrieve the interface index where the packet was received */
+    *ifindex = 0;
+    for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
+        cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+
+      if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
+       p = (struct in6_pktinfo *)(CMSG_DATA(cmsg));
+       *ifindex = p->ipi6_ifindex;
+       break;
+      }
+    }
+  }
+
+  return bytes;
+}
+
+typedef enum { UNKNOWN=0, DTLS=1 } protocol_t;
+
+protocol_t
+demux_protocol(const char *buf, int len) {
+  return DTLS;
+}
+
+#ifdef WITH_DTLS
+typedef enum { 
+  PEER_ST_ESTABLISHED, PEER_ST_PENDING, PEER_ST_CLOSED 
+ } peer_state_t;
+typedef struct {
+  peer_state_t state;
+  unsigned long h;
+  SSL *ssl;
+} ssl_peer_t;
+
+#define MAX_SSL_PENDING      2 /* must be less than MAX_SSL_PEERS */
+#define MAX_SSL_PEERS       10 /* MAX_SSL_PENDING of these might be pending  */
+ssl_peer_t *ssl_peer_storage[MAX_SSL_PEERS];
+static int pending = 0;
+
+void
+check_peers() {
+typedef struct bio_dgram_data_st
+       {
+       union {
+               struct sockaddr sa;
+               struct sockaddr_in sa_in;
+               struct sockaddr_in6 sa_in6;
+       } peer;
+       unsigned int connected;
+       unsigned int _errno;
+       unsigned int mtu;
+       struct timeval next_timeout;
+       struct timeval socket_timeout;
+       } bio_dgram_data;
+
+  struct sockaddr_in6 peer;
+  int i;
+  BIO *bio;
+  for (i = 0; i < MAX_SSL_PEERS; i++) {
+    if (ssl_peer_storage[i]) {
+      if (!ssl_peer_storage[i]->ssl)
+       fprintf(stderr, "invalid SSL object for peer %d!\n",i);
+      else {
+       bio = SSL_get_rbio(ssl_peer_storage[i]->ssl);
+       if (bio) {
+         (void) BIO_dgram_get_peer(bio, (struct sockaddr *)&peer);
+         if (peer.sin6_port && ssl_peer_storage[i]->h != ntohs(peer.sin6_port)) {
+           fprintf(stderr, "   bio %p: port differs from hash: %d != %d! (%sconnected)\n", bio,
+                   ssl_peer_storage[i]->h, 
+                   ntohs(((struct sockaddr_in6 *)&peer)->sin6_port),
+                   ((bio_dgram_data *)bio->ptr)->connected ? "" : "not ");
+         }
+
+       }
+      }
+    }
+  }
+}
+
+/** Creates a hash value from the first num bytes of s, taking init as
+ * initialization value. */
+static inline unsigned long
+_hash(unsigned long init, const char *s, int num) {
+  int c;
+
+  while (num--)
+    while ( (c = *s++) ) {
+      init = ((init << 7) + init) + c;
+    }
+
+  return init;
+}
+
+static inline unsigned long
+hash_peer(const struct sockaddr *peer, int ifindex) {
+  unsigned long h;
+
+  /* initialize hash value to interface index */
+  h = _hash(0, (char *)&ifindex, sizeof(int));
+
+#define CAST(TYPE,VAR) ((TYPE)VAR)
+
+  assert(peer);
+  switch (peer->sa_family) {
+  case AF_INET: 
+    return ntohs(CAST(const struct sockaddr_in *, peer)->sin_port);
+    h = _hash(h, (char *) &CAST(const struct sockaddr_in *, peer)->sin_addr, 
+             sizeof(struct in_addr));
+    h = _hash(h, (char *) &CAST(const struct sockaddr_in *, peer)->sin_port, 
+             sizeof(in_port_t));
+    break;
+  case AF_INET6:
+    return ntohs(CAST(const struct sockaddr_in6 *, peer)->sin6_port);
+    h = _hash(h, 
+             (char *) &CAST(const struct sockaddr_in6 *, peer)->sin6_addr, 
+             sizeof(struct in6_addr));
+    h = _hash(h, 
+             (char *) &CAST(const struct sockaddr_in6 *, peer)->sin6_port, 
+             sizeof(in_port_t));
+    break;
+  default:
+    /* last resort */
+    h = _hash(h, (char *)peer, sizeof(struct sockaddr));
+  }
+
+  return 42;
+  return h;
+}
+
+/* Returns index of peer object for specified address/ifindex pair. */
+int
+get_index_of_peer(const struct sockaddr *peer, int ifindex) {
+  unsigned long h;
+  int idx;
+#ifndef NDEBUG
+  char addr[INET6_ADDRSTRLEN];
+  char port[6];
+#endif
+
+  if (!peer)
+    return -1;
+
+  h = hash_peer(peer,ifindex);
+
+  for (idx = 0; idx < MAX_SSL_PEERS; idx++) {
+    if (ssl_peer_storage[idx] && ssl_peer_storage[idx]->h == h) {
+#ifndef NDEBUG
+      getnameinfo((struct sockaddr *)peer, sizeof(struct sockaddr_in6), 
+                 addr, sizeof(addr), port, sizeof(port), 
+                 NI_NUMERICHOST | NI_NUMERICSERV);
+
+      fprintf(stderr, "get_index_of_peer: [%s]:%s  =>  %lu\n",
+             addr, port, h);
+#endif
+      return idx;
+    }
+  }
+  return -1;
+}
+
+SSL *
+get_ssl(SSL_CTX *ctx, int sockfd, struct sockaddr *src, int ifindex) {
+  int idx;
+  BIO *bio;
+  SSL *ssl;
+#ifndef NDEBUG
+  struct sockaddr_storage peer;
+  char addr[INET6_ADDRSTRLEN];
+  char port[6];
+  int i;
+#endif
+
+  idx = get_index_of_peer(src,ifindex);
+  if (idx >= 0) {
+    fprintf(stderr,"found peer %d ",idx);
+    switch (ssl_peer_storage[idx]->state) {
+    case PEER_ST_ESTABLISHED: fprintf(stderr,"established\n"); break;
+    case PEER_ST_PENDING:     fprintf(stderr,"pending\n"); break;
+    case PEER_ST_CLOSED:      fprintf(stderr,"closed\n"); break;
+    default:
+      OPENSSL_assert(0);
+    }
+
+#ifndef NDEBUG
+    memset(&peer, 0, sizeof(peer));
+    (void) BIO_dgram_get_peer(SSL_get_rbio(ssl_peer_storage[idx]->ssl), &peer);
+
+    getnameinfo((struct sockaddr *)&peer, sizeof(peer), 
+               addr, sizeof(addr), port, sizeof(port), 
+               NI_NUMERICHOST | NI_NUMERICSERV);
+
+    fprintf(stderr,"      [%s]:%s   \n", addr, port);
+#endif
+    return ssl_peer_storage[idx]->ssl;
+  }
+
+  /* none found, create new if sufficient space available */
+  if (pending < MAX_SSL_PENDING) {
+    for (idx = 0; idx < MAX_SSL_PEERS; idx++) {
+      if (ssl_peer_storage[idx] == NULL) { /* found space */
+       ssl = SSL_new(ctx);
+       
+       if (ssl) {
+         bio = BIO_new_dgram(sockfd, BIO_NOCLOSE);
+         if (!bio) {
+           SSL_free(ssl);
+           return NULL;
+         }
+         
+         SSL_set_bio(ssl, bio, bio);
+         SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
+         
+         SSL_set_accept_state(ssl);
+         ssl_peer_storage[idx] = (ssl_peer_t *) malloc(sizeof(ssl_peer_t));
+         if (!ssl_peer_storage[idx]) {
+           SSL_free(ssl);
+           return NULL;
+         }
+         ssl_peer_storage[idx]->state = PEER_ST_PENDING;
+         ssl_peer_storage[idx]->h = hash_peer(src,ifindex);
+         ssl_peer_storage[idx]->ssl = ssl;
+         
+         pending++;
+         
+         fprintf(stderr,
+                 "created new SSL peer %d for ssl object %p (storage: %p)\n", 
+                idx, ssl, ssl_peer_storage[idx]);
+#ifndef NDEBUG
+    if (getnameinfo((struct sockaddr *)&src, sizeof(src), 
+               addr, sizeof(addr), port, sizeof(port), 
+                   NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
+      perror("getnameinfo");
+      fprintf(stderr, "port was %u\n", ntohs(((struct sockaddr_in6 *)src)->sin6_port));
+    } else {
+    fprintf(stderr,"      [%s]:%s   \n", addr, port);
+      }
+#endif
+    OPENSSL_assert(ssl_peer_storage[idx]->ssl == ssl);
+         fprintf(stderr,"%d objects pending\n", pending);
+         check_peers();
+         return ssl;
+       }
+      }
+    }
+  } else {
+    fprintf(stderr, "too many pending SSL objects\n");
+    return NULL;
+  }
+
+  fprintf(stderr, "too many peers\n");
+  return NULL;
+}
+
+/** Deletes peer stored at index idx and frees allocated memory. */
+static inline void
+delete_peer(int idx) {
+  if (idx < 0 || !ssl_peer_storage[idx])
+    return;
+
+  if (ssl_peer_storage[idx]->state == PEER_ST_PENDING)
+    pending--;
+
+  OPENSSL_assert(ssl_peer_storage[idx]->ssl);
+  SSL_free(ssl_peer_storage[idx]->ssl);
+    
+  free(ssl_peer_storage[idx]);
+  ssl_peer_storage[idx] = NULL;
+
+  printf("deleted peer %d\n",idx);
+}
+
+/** Deletes all closed objects from ssl_peer_storage. */
+void
+remove_closed() {
+  int idx;
+
+  for (idx = 0; idx < MAX_SSL_PEERS; idx++)
+    if (ssl_peer_storage[idx] 
+       && ssl_peer_storage[idx]->state == PEER_ST_CLOSED)
+      delete_peer(idx);
+}
+
+#define min(a,b) ((a) < (b) ? (a) : (b))
+
+unsigned int
+psk_server_callback(SSL *ssl, const char *identity,
+                   unsigned char *psk, unsigned int max_psk_len) {
+  static char keybuf[] = "secretPSK";
+
+  printf("psk_server_callback: check identity of client %s\n", identity);
+  memcpy(psk, keybuf, min(strlen(keybuf), max_psk_len));
+
+  return min(strlen(keybuf), max_psk_len);
+}
+
+#endif
+
+#ifdef WITH_DTLS
+/**
+ * This function tracks the status changes from libssl to manage local
+ * object state.
+ */
+void
+info_callback(const SSL *ssl, int where, int ret) {
+  int idx, i;
+  struct sockaddr_storage peer;
+  struct sockaddr_storage peer2;
+  char addr[INET6_ADDRSTRLEN];
+  char port[6];
+
+  if (where & SSL_CB_LOOP)  /* do not care for intermediary states */
+    return;
+
+  memset(&peer, 0, sizeof(peer));
+  (void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
+
+  /* lookup SSL object */   /* FIXME: need to get the ifindex */
+  idx = get_index_of_peer((struct sockaddr *)&peer, 0);
+  
+  if (idx >= 0)
+    fprintf(stderr, "info_callback: assert: %d < 0 || %p == %p (storage: %p)\n",
+           idx, ssl, ssl_peer_storage[idx]->ssl, ssl_peer_storage[idx]); 
+  if (idx >= 0 && ssl != ssl_peer_storage[idx]->ssl) {
+    getnameinfo((struct sockaddr *)&peer, sizeof(peer), 
+               addr, sizeof(addr), port, sizeof(port), 
+               NI_NUMERICHOST | NI_NUMERICSERV);
+
+    fprintf(stderr," ssl: [%s]:%s   ", addr, port);
+    
+    (void) BIO_dgram_get_peer(SSL_get_rbio(ssl_peer_storage[idx]->ssl), &peer2);
+    getnameinfo((struct sockaddr *)&peer2, sizeof(peer2), 
+               addr, sizeof(addr), port, sizeof(port), 
+               NI_NUMERICHOST | NI_NUMERICSERV);
+
+    fprintf(stderr," ssl_peer_storage[idx]->ssl: [%s]:%s\n", addr, port);
+
+    fprintf(stderr, " hash:%lu     h: %lu\n",
+           hash_peer((const struct sockaddr *)&peer, 0),
+           ssl_peer_storage[idx]->h);
+
+    for (i = 0; i < MAX_SSL_PEERS; i++) {
+      if (ssl_peer_storage[i]) {
+       fprintf(stderr, "%02d: %p ssl: %p  ",
+               i, ssl_peer_storage[i] ,ssl_peer_storage[i]->ssl);
+
+       (void) BIO_dgram_get_peer(SSL_get_rbio(ssl_peer_storage[i]->ssl), &peer2);
+       getnameinfo((struct sockaddr *)&peer2, sizeof(peer2), 
+                   addr, sizeof(addr), port, sizeof(port), 
+                   NI_NUMERICHOST | NI_NUMERICSERV);
+       
+       fprintf(stderr," peer: [%s]:%s    h: %lu\n", addr, port, ssl_peer_storage[i]->h);
+      }
+    }
+    fprintf(stderr, "***** ASSERT FAILED ******\n");
+
+    memset(&peer, 0, sizeof(peer));
+    (void) BIO_dgram_get_peer(SSL_get_wbio(ssl), &peer);
+
+    idx = get_index_of_peer((struct sockaddr *)&peer, 0);
+    fprintf(stderr, "  get_index_of_peer for wbio returns %d, type is %04x\n",
+           idx, where);    
+  }
+#if 1
+         check_peers();
+  OPENSSL_assert((idx < 0) || (ssl == ssl_peer_storage[idx]->ssl));
+#endif
+
+  if (where & SSL_CB_ALERT) {
+#ifndef NDEBUG
+    if (ret != 0)
+      fprintf(stderr,"%s:%s:%s\n", SSL_alert_type_string(ret),
+             SSL_alert_desc_string(ret), SSL_alert_desc_string_long(ret));
+#endif
+
+    /* examine alert type */
+    switch (*SSL_alert_type_string(ret)) {
+    case 'F':
+      /* move SSL object from pending to close */
+      if (idx >= 0) {
+       ssl_peer_storage[idx]->state = PEER_ST_CLOSED;
+       pending--;
+      }
+      break;
+    case 'W': 
+      if ((ret & 0xff) == SSL_AD_CLOSE_NOTIFY) {
+       if (where == SSL_CB_WRITE_ALERT) 
+         fprintf(stderr,"sent CLOSE_NOTIFY\n");
+       else /* received CN */
+         fprintf(stderr,"received CLOSE_NOTIFY\n");
+      }
+      break;
+    default:                   /* handle unknown alert types */
+#ifndef NDEBUG
+      printf("not handled!\n");
+#endif
+    }
+  }
+
+  if (where & SSL_CB_HANDSHAKE_DONE) {
+    /* move SSL object from pending to established */
+    printf("HANDSHAKE_DONE ");
+    if (idx >= 0) {
+      
+      if (ssl_peer_storage[idx]->state == PEER_ST_PENDING) {
+       ssl_peer_storage[idx]->state = PEER_ST_ESTABLISHED;
+       pending--;
+       printf("moved SSL object %d to ESTABLISHED\n", idx);
+       printf("%d objects pending\n", pending);
+      } else {
+#ifndef NDEBUG
+       printf("huh, object %d was not pending? (%d)\n", idx,
+              ssl_peer_storage[idx]->state);
+#endif
+      }
+      return;
+    }
+    return;
+  }
+
+  return;
+}
+#endif
+
+#ifdef WITH_DTLS
+/* checks if ssl object was closed and can be removed */
+int 
+check_close(SSL *ssl) {
+  int res, err, idx;
+  struct sockaddr_storage peer;
+  
+  memset(&peer, 0, sizeof(peer));
+  (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
+
+  res = 0;
+  if (SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) {
+    printf("SSL_RECEIVED_SHUTDOWN\n");
+    res = SSL_shutdown(ssl);
+    if (res == 0) {
+      printf("must call SSL_shutdown again\n");
+      res = SSL_shutdown(ssl);
+    }
+    if (res < 0) {
+       err = SSL_get_error(ssl,res);   
+       fprintf(stderr, "shutdown: SSL error %d: %s\n", err,
+               ERR_error_string(err, NULL));
+    } 
+
+    /* we can close the SSL object anyway */
+    /* FIXME: need to get ifindex from somewhere */
+    idx = get_index_of_peer((struct sockaddr *)&peer, 0);
+    OPENSSL_assert(idx < 0 || ssl == ssl_peer_storage[idx]->ssl);
+    if (idx >= 0) {
+      ssl_peer_storage[idx]->state = PEER_ST_CLOSED;
+      printf("moved SSL object %d to CLOSED\n",idx);
+    }
+  }
+  
+  return res;
+}
+
+int 
+check_timeout() {
+  int i, result, err;
+
+  for (i = 0; i < MAX_SSL_PEERS; i++) {
+    if (ssl_peer_storage[i]) {
+      OPENSSL_assert(ssl_peer_storage[i]->ssl);
+      result = DTLSv1_handle_timeout(ssl_peer_storage[i]->ssl);
+      if (result < 0) {
+       err = SSL_get_error(ssl_peer_storage[i]->ssl,result);
+       fprintf(stderr, "dtls1_handle_timeout (%d): %s\n",
+               err, ERR_error_string(err, NULL));
+      }
+    }
+  }
+
+  /* remove outdated obbjects? */
+  
+  return 0;
+}
+#endif /* WITH_DTLS */
+  
+int 
+_read(SSL_CTX *ctx, int sockfd) {
+  char buf[2000];
+  struct sockaddr_in6 src;
+  int len, ifindex, i;
+  char addr[INET6_ADDRSTRLEN];
+  char port[6];
+  socklen_t sz = sizeof(struct sockaddr_in6);
+#ifdef WITH_DTLS
+  SSL *ssl;
+  int err;
+#endif
+
+  /* Retrieve remote address and interface index as well as the first
+     few bytes of the message to demultiplex protocols. */
+  memset(&src, 0, sizeof(struct sockaddr_in6));
+  len = check_connect(sockfd, buf, 4, (struct sockaddr *)&src, &ifindex);
+
+  if (len < 0)                 /* error */
+    return len;
+
+#ifndef NDEBUG
+  fprintf(stderr,"received packet");
+  
+  if (getnameinfo((struct sockaddr *)&src, sizeof(src), 
+                 addr, sizeof(addr), port, sizeof(port), 
+                 NI_NUMERICHOST | NI_NUMERICSERV) == 0)
+    fprintf(stderr," from [%s]:%s", addr, port);
+  
+  fprintf(stderr," on interface %d\n", ifindex);
+#endif
+
+  switch (demux_protocol(buf, len)) {
+#ifdef WITH_DTLS
+  case DTLS :
+    ssl = get_ssl(ctx, sockfd, (struct sockaddr *)&src, ifindex);
+    if (!ssl) {
+      fprintf(stderr, "cannot create new SSL object\n");
+      /*      return recv(sockfd, buf, sizeof(buf), MSG_DONTWAIT);*/
+      len = recvfrom(sockfd, buf, sizeof(buf), MSG_DONTWAIT,
+                    (struct sockaddr *)&src, &sz);
+      getnameinfo((struct sockaddr *)&src, sz, 
+                 addr, sizeof(addr), port, sizeof(port), 
+                 NI_NUMERICHOST | NI_NUMERICSERV);
+      printf("discarded %d bytes from [%s]:%s\n", len, addr, port);      
+      return len;
+    }
+    len = SSL_read(ssl, buf, sizeof(buf));
+    break;
+#endif
+  case UNKNOWN:
+  default :
+    len = recv(sockfd, buf, sizeof(buf), MSG_DONTWAIT);
+  }
+
+  if (len > 0) {
+    printf("here is the data:\n");
+    for (i=0; i<len; i++)
+      printf("%c",buf[i]);
+  } if (len == 0) {            /* session closed? */
+#ifdef WITH_DTLS
+    if (check_close(ssl) <= 0) {
+      fprintf(stderr, "not closed\n");
+    }
+#endif
+  } else {
+#ifdef WITH_DTLS
+    err = SSL_get_error(ssl,len);
+    switch (err) {
+    case SSL_ERROR_WANT_READ:
+      fprintf(stderr, "SSL_ERROR_WANT_READ\n");
+      return 0;
+    case SSL_ERROR_WANT_WRITE:
+      fprintf(stderr, "SSL_ERROR_WANT_WRITE\n");
+      return 0;
+    default:
+      fprintf(stderr, "read: SSL error %d: %s\n", err,
+             ERR_error_string(err, NULL));
+      return 0;
+    }
+#else
+    perror("recv");
+#endif
+  }
+
+  return len;
+}
+
+int 
+_write(SSL_CTX *ctx, int sockfd) {
+  int res = 0;
+#ifdef WITH_DTLS
+  SSL *ssl;
+  int err;
+
+  ssl = get_ssl(ctx, sockfd, NULL, 1);
+  if (!ssl) {
+    fprintf(stderr, "no SSL object for writing");
+    return 0;
+  }
+  res = SSL_write(ssl, NULL, 0);
+  if (res < 0) {
+    /*
+    if (SSL_want_write(ssl))
+      return 0;
+    */
+    /* FIXME: check SSL_want_read(ssl) */
+
+    err = SSL_get_error(ssl,res);
+    fprintf(stderr,"SSL_write returned %d (%s)\n", err, ERR_error_string(err, NULL));
+  } else {
+    printf("SSL_write successful\n");
+  }
+#else
+#endif
+  
+  return res;
+}
+
+
+int 
+generate_cookie(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) {
+  /* FIXME: generate secure client-specific cookie */
+#define DUMMYSTR "ABCDEFGHIJKLMNOP"
+  *cookie_len = strlen(DUMMYSTR);
+  memcpy(cookie, DUMMYSTR, *cookie_len);
+
+  return 1;
+}
+
+int 
+verify_cookie(SSL *ssl, unsigned char *cookie, unsigned int cookie_len) {
+  /* FIXME */
+  return 1;
+}
+
+enum { READ, WRITE };
+
+int
+main(int argc, char **argv) {
+  int sockfd = 0;
+  int on = 1;
+  struct sockaddr_in6 listen_addr = { AF_INET6, htons(20220), 0, IN6ADDR_ANY_INIT, 0 };
+  size_t addr_size = sizeof(struct sockaddr_in6);
+  fd_set fds[2];
+  int result, flags;
+  int idx, res = 0;
+  struct timeval timeout;
+  struct sigaction act, oact;
+  
+#ifdef WITH_DTLS
+  SSL_CTX *ctx;
+
+  memset(ssl_peer_storage, 0, sizeof(ssl_peer_storage));
+
+  SSL_load_error_strings();
+  SSL_library_init();
+  ctx = SSL_CTX_new(DTLSv1_server_method());
+
+  SSL_CTX_set_cipher_list(ctx, "ALL");
+  SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
+
+  res = SSL_CTX_use_certificate_file(ctx, SERVER_CERT_PEM, SSL_FILETYPE_PEM);
+  if (res != 1) {
+    fprintf(stderr, "cannot read server certificate from file '%s' (%s)\n", 
+           SERVER_CERT_PEM, ERR_error_string(res,NULL));
+    goto end;
+  }
+
+  res = SSL_CTX_use_PrivateKey_file(ctx, SERVER_KEY_PEM, SSL_FILETYPE_PEM);
+  if (res != 1) {
+    fprintf(stderr, "cannot read server key from file '%s' (%s)\n", 
+           SERVER_KEY_PEM, ERR_error_string(res,NULL));
+    goto end;
+  }
+
+  res = SSL_CTX_check_private_key (ctx);
+  if (res != 1) {
+    fprintf(stderr, "invalid private key\n");
+    goto end;
+  }
+
+  res = SSL_CTX_load_verify_locations(ctx, CA_CERT_PEM, NULL);
+  if (res != 1) {
+    fprintf(stderr, "cannot read ca file '%s'\n", CA_CERT_PEM);
+    goto end;
+  }
+
+  /* Client has to authenticate */
+
+  /* Client has to authenticate */
+  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL);
+
+  SSL_CTX_set_read_ahead(ctx, 1); /* disable read-ahead */
+  SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);
+  SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie);
+
+  SSL_CTX_use_psk_identity_hint(ctx, "Enter password for CoAP-Gateway");
+  SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
+
+  SSL_CTX_set_info_callback(ctx, info_callback);
+#endif
+
+  sockfd = socket(listen_addr.sin6_family, SOCK_DGRAM, 0);
+  if ( sockfd < 0 ) {
+    perror("socket");
+    return -1;
+  }
+
+  if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0)
+    perror("setsockopt SO_REUSEADDR");
+
+  flags = fcntl(sockfd, F_GETFL, 0);
+  if (flags < 0 || fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) {
+    perror("fcntl");
+    return -1;
+  }
+
+  on = 1;
+  if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+    perror("setsockopt IPV6_PKTINFO");
+  }
+
+  if (bind (sockfd, (const struct sockaddr *)&listen_addr, addr_size) < 0) {
+    perror("bind");
+    res = -2;
+    goto end;
+  }
+
+  act.sa_handler = handle_sigint;
+  sigemptyset(&act.sa_mask);
+  act.sa_flags = 0;
+  sigaction(SIGINT, &act, &oact);
+
+  while (!quit) {
+    FD_ZERO(&fds[READ]);
+    FD_ZERO(&fds[WRITE]);
+    FD_SET(sockfd, &fds[READ]);
+
+    timeout.tv_sec = 1;
+    timeout.tv_usec = 0;
+    result = select( FD_SETSIZE, &fds[READ], &fds[WRITE], 0, &timeout);
+
+    if (result < 0) {          /* error */
+      if (errno != EINTR)
+       perror("select");
+    } else if (result > 0) {   /* read from socket */
+      if ( FD_ISSET( sockfd, &fds[READ]) ) {
+       _read(ctx, sockfd);     /* read received data */
+      } else if ( FD_ISSET( sockfd, &fds[WRITE]) ) { /* write to socket */
+       _write(ctx, sockfd);            /* write data */
+      }
+    } else {                   /* timeout */
+      check_timeout();
+    }
+    remove_closed();
+  }
+  
+ end:
+#ifdef WITH_DTLS
+  for (idx = 0; idx < MAX_SSL_PEERS; idx++) {
+    if (ssl_peer_storage[idx] && ssl_peer_storage[idx]->ssl) {
+      if (ssl_peer_storage[idx]->state == PEER_ST_ESTABLISHED)
+       SSL_shutdown(ssl_peer_storage[idx]->ssl);
+      SSL_free(ssl_peer_storage[idx]->ssl);
+    }
+  }
+
+  SSL_CTX_free(ctx);
+#endif
+  close(sockfd);               /* don't care if we close stdin at this point */
+  return res;
+}
diff --git a/extlibs/tinydtls/tinydtls.h b/extlibs/tinydtls/tinydtls.h
new file mode 100644 (file)
index 0000000..3fa228a
--- /dev/null
@@ -0,0 +1,45 @@
+/* tinydtls.h.  Generated from tinydtls.h.in by configure.  */
+/* tinydtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file tinydtls.h
+ * @brief public tinydtls API
+ */
+
+#ifndef _DTLS_TINYDTLS_H_
+#define _DTLS_TINYDTLS_H_
+
+/** Defined to 1 if tinydtls is built with support for ECC */
+/* #undef DTLS_ECC */
+
+/** Defined to 1 if tinydtls is built with support for PSK */
+#define DTLS_PSK 1
+
+/** Defined to 1 if tinydtls is built for Contiki OS */
+/* #undef WITH_CONTIKI */
+
+#endif /* _DTLS_TINYDTLS_H_ */
diff --git a/extlibs/tinydtls/tinydtls.h.in b/extlibs/tinydtls/tinydtls.h.in
new file mode 100644 (file)
index 0000000..a2e6685
--- /dev/null
@@ -0,0 +1,44 @@
+/* tinydtls -- a very basic DTLS implementation
+ *
+ * Copyright (C) 2011--2014 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/**
+ * @file tinydtls.h
+ * @brief public tinydtls API
+ */
+
+#ifndef _DTLS_TINYDTLS_H_
+#define _DTLS_TINYDTLS_H_
+
+/** Defined to 1 if tinydtls is built with support for ECC */
+#undef DTLS_ECC
+
+/** Defined to 1 if tinydtls is built with support for PSK */
+#undef DTLS_PSK
+
+/** Defined to 1 if tinydtls is built for Contiki OS */
+#undef WITH_CONTIKI
+
+#endif /* _DTLS_TINYDTLS_H_ */
diff --git a/extlibs/tinydtls/uthash.h b/extlibs/tinydtls/uthash.h
new file mode 100644 (file)
index 0000000..786c956
--- /dev/null
@@ -0,0 +1,972 @@
+/*
+Copyright (c) 2003-2010, Troy D. Hanson     http://uthash.sourceforge.net
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef _DTLS_UTHASH_H
+#define _DTLS_UTHASH_H 
+
+#include <string.h>   /* memcmp,strlen */
+#include <stddef.h>   /* ptrdiff_t */
+
+/* These macros use decltype or the earlier __typeof GNU extension.
+   As decltype is only available in newer compilers (VS2010 or gcc 4.3+
+   when compiling c++ source) this code uses whatever method is needed
+   or, for VS2008 where neither is available, uses casting workarounds. */
+#ifdef _MSC_VER         /* MS compiler */
+#if _MSC_VER >= 1600 && defined(__cplusplus)  /* VS2010 or newer in C++ mode */
+#define DECLTYPE(x) (decltype(x))
+#else                   /* VS2008 or older (or VS2010 in C mode) */
+#define NO_DECLTYPE
+#define DECLTYPE(x)
+#endif
+#else                   /* GNU, Sun and other compilers */
+#define DECLTYPE(x) (__typeof(x))
+#endif
+
+#ifdef NO_DECLTYPE
+#define DECLTYPE_ASSIGN(dst,src)                                                 \
+do {                                                                             \
+  char **_da_dst = (char**)(&(dst));                                             \
+  *_da_dst = (char*)(src);                                                       \
+} while(0)
+#else 
+#define DECLTYPE_ASSIGN(dst,src)                                                 \
+do {                                                                             \
+  (dst) = DECLTYPE(dst)(src);                                                    \
+} while(0)
+#endif
+
+/* a number of the hash function use uint32_t which isn't defined on win32 */
+#ifdef _MSC_VER
+typedef unsigned int uint32_t;
+#else
+#include <inttypes.h>   /* uint32_t */
+#endif
+
+#define UTHASH_VERSION 1.9.3
+
+#define uthash_fatal(msg) exit(-1)        /* fatal error (out of memory,etc) */
+#define uthash_malloc(sz) malloc(sz)      /* malloc fcn                      */
+#define uthash_free(ptr,sz) free(ptr)     /* free fcn                        */
+
+#define uthash_noexpand_fyi(tbl)          /* can be defined to log noexpand  */
+#define uthash_expand_fyi(tbl)            /* can be defined to log expands   */
+
+/* initial number of buckets */
+#define HASH_INITIAL_NUM_BUCKETS 32      /* initial number of buckets        */
+#define HASH_INITIAL_NUM_BUCKETS_LOG2 5  /* lg2 of initial number of buckets */
+#define HASH_BKT_CAPACITY_THRESH 10      /* expand when bucket count reaches */
+
+/* calculate the element whose hash handle address is hhe */
+#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho)))
+
+#define HASH_FIND(hh,head,keyptr,keylen,out)                                     \
+do {                                                                             \
+  unsigned _hf_bkt,_hf_hashv;                                                    \
+  out=NULL;                                                                      \
+  if (head) {                                                                    \
+     HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt);   \
+     if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) {                           \
+       HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ],  \
+                        keyptr,keylen,out);                                      \
+     }                                                                           \
+  }                                                                              \
+} while (0)
+
+#ifdef HASH_BLOOM
+#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM)
+#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0)
+#define HASH_BLOOM_MAKE(tbl)                                                     \
+do {                                                                             \
+  (tbl)->bloom_nbits = HASH_BLOOM;                                               \
+  (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN);                 \
+  if (!((tbl)->bloom_bv))  { uthash_fatal( "out of memory"); }                   \
+  memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN);                                \
+  (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE;                                       \
+} while (0);
+
+#define HASH_BLOOM_FREE(tbl)                                                     \
+do {                                                                             \
+  uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN);                              \
+} while (0);
+
+#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8)))
+#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8)))
+
+#define HASH_BLOOM_ADD(tbl,hashv)                                                \
+  HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
+
+#define HASH_BLOOM_TEST(tbl,hashv)                                               \
+  HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
+
+#else
+#define HASH_BLOOM_MAKE(tbl) 
+#define HASH_BLOOM_FREE(tbl) 
+#define HASH_BLOOM_ADD(tbl,hashv) 
+#define HASH_BLOOM_TEST(tbl,hashv) (1)
+#endif
+
+#define HASH_MAKE_TABLE(hh,head)                                                 \
+do {                                                                             \
+  (head)->hh.tbl = (UT_hash_table*)uthash_malloc(                                \
+                  sizeof(UT_hash_table));                                        \
+  if (!((head)->hh.tbl))  { uthash_fatal( "out of memory"); }                    \
+  memset((head)->hh.tbl, 0, sizeof(UT_hash_table));                              \
+  (head)->hh.tbl->tail = &((head)->hh);                                          \
+  (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS;                        \
+  (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2;              \
+  (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head);                    \
+  (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc(                      \
+          HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket));               \
+  if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); }             \
+  memset((head)->hh.tbl->buckets, 0,                                             \
+          HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket));               \
+  HASH_BLOOM_MAKE((head)->hh.tbl);                                               \
+  (head)->hh.tbl->signature = HASH_SIGNATURE;                                    \
+} while(0)
+
+#define HASH_ADD(hh,head,fieldname,keylen_in,add)                                \
+        HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add)
+#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add)                            \
+do {                                                                             \
+ unsigned _ha_bkt;                                                               \
+ (add)->hh.next = NULL;                                                          \
+ (add)->hh.key = (char*)keyptr;                                                  \
+ (add)->hh.keylen = keylen_in;                                                   \
+ if (!(head)) {                                                                  \
+    head = (add);                                                                \
+    (head)->hh.prev = NULL;                                                      \
+    HASH_MAKE_TABLE(hh,head);                                                    \
+ } else {                                                                        \
+    (head)->hh.tbl->tail->next = (add);                                          \
+    (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail);         \
+    (head)->hh.tbl->tail = &((add)->hh);                                         \
+ }                                                                               \
+ (head)->hh.tbl->num_items++;                                                    \
+ (add)->hh.tbl = (head)->hh.tbl;                                                 \
+ HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets,                         \
+         (add)->hh.hashv, _ha_bkt);                                              \
+ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh);                   \
+ HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv);                                 \
+ HASH_EMIT_KEY(hh,head,keyptr,keylen_in);                                        \
+ HASH_FSCK(hh,head);                                                             \
+} while(0)
+
+#define HASH_TO_BKT( hashv, num_bkts, bkt )                                      \
+do {                                                                             \
+  bkt = ((hashv) & ((num_bkts) - 1));                                            \
+} while(0)
+
+/* delete "delptr" from the hash table.
+ * "the usual" patch-up process for the app-order doubly-linked-list.
+ * The use of _hd_hh_del below deserves special explanation.
+ * These used to be expressed using (delptr) but that led to a bug
+ * if someone used the same symbol for the head and deletee, like
+ *  HASH_DELETE(hh,users,users);
+ * We want that to work, but by changing the head (users) below
+ * we were forfeiting our ability to further refer to the deletee (users)
+ * in the patch-up process. Solution: use scratch space to
+ * copy the deletee pointer, then the latter references are via that
+ * scratch pointer rather than through the repointed (users) symbol.
+ */
+#define HASH_DELETE(hh,head,delptr)                                              \
+do {                                                                             \
+    unsigned _hd_bkt;                                                            \
+    struct UT_hash_handle *_hd_hh_del;                                           \
+    if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) )  {         \
+        uthash_free((head)->hh.tbl->buckets,                                     \
+                    (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \
+        HASH_BLOOM_FREE((head)->hh.tbl);                                         \
+        uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                      \
+        head = NULL;                                                             \
+    } else {                                                                     \
+        _hd_hh_del = &((delptr)->hh);                                            \
+        if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) {     \
+            (head)->hh.tbl->tail =                                               \
+                (UT_hash_handle*)((char*)((delptr)->hh.prev) +                   \
+                (head)->hh.tbl->hho);                                            \
+        }                                                                        \
+        if ((delptr)->hh.prev) {                                                 \
+            ((UT_hash_handle*)((char*)((delptr)->hh.prev) +                      \
+                    (head)->hh.tbl->hho))->next = (delptr)->hh.next;             \
+        } else {                                                                 \
+            DECLTYPE_ASSIGN(head,(delptr)->hh.next);                             \
+        }                                                                        \
+        if (_hd_hh_del->next) {                                                  \
+            ((UT_hash_handle*)((char*)_hd_hh_del->next +                         \
+                    (head)->hh.tbl->hho))->prev =                                \
+                    _hd_hh_del->prev;                                            \
+        }                                                                        \
+        HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt);   \
+        HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del);        \
+        (head)->hh.tbl->num_items--;                                             \
+    }                                                                            \
+    HASH_FSCK(hh,head);                                                          \
+} while (0)
+
+
+/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */
+#define HASH_FIND_STR(head,findstr,out)                                          \
+    HASH_FIND(hh,head,findstr,strlen(findstr),out)
+#define HASH_ADD_STR(head,strfield,add)                                          \
+    HASH_ADD(hh,head,strfield,strlen(add->strfield),add)
+#define HASH_FIND_INT(head,findint,out)                                          \
+    HASH_FIND(hh,head,findint,sizeof(int),out)
+#define HASH_ADD_INT(head,intfield,add)                                          \
+    HASH_ADD(hh,head,intfield,sizeof(int),add)
+#define HASH_FIND_PTR(head,findptr,out)                                          \
+    HASH_FIND(hh,head,findptr,sizeof(void *),out)
+#define HASH_ADD_PTR(head,ptrfield,add)                                          \
+    HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
+#define HASH_DEL(head,delptr)                                                    \
+    HASH_DELETE(hh,head,delptr)
+
+/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined.
+ * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined.
+ */
+#ifdef HASH_DEBUG
+#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0)
+#define HASH_FSCK(hh,head)                                                       \
+do {                                                                             \
+    unsigned _bkt_i;                                                             \
+    unsigned _count, _bkt_count;                                                 \
+    char *_prev;                                                                 \
+    struct UT_hash_handle *_thh;                                                 \
+    if (head) {                                                                  \
+        _count = 0;                                                              \
+        for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) {       \
+            _bkt_count = 0;                                                      \
+            _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head;                      \
+            _prev = NULL;                                                        \
+            while (_thh) {                                                       \
+               if (_prev != (char*)(_thh->hh_prev)) {                            \
+                   HASH_OOPS("invalid hh_prev %p, actual %p\n",                  \
+                    _thh->hh_prev, _prev );                                      \
+               }                                                                 \
+               _bkt_count++;                                                     \
+               _prev = (char*)(_thh);                                            \
+               _thh = _thh->hh_next;                                             \
+            }                                                                    \
+            _count += _bkt_count;                                                \
+            if ((head)->hh.tbl->buckets[_bkt_i].count !=  _bkt_count) {          \
+               HASH_OOPS("invalid bucket count %d, actual %d\n",                 \
+                (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count);              \
+            }                                                                    \
+        }                                                                        \
+        if (_count != (head)->hh.tbl->num_items) {                               \
+            HASH_OOPS("invalid hh item count %d, actual %d\n",                   \
+                (head)->hh.tbl->num_items, _count );                             \
+        }                                                                        \
+        /* traverse hh in app order; check next/prev integrity, count */         \
+        _count = 0;                                                              \
+        _prev = NULL;                                                            \
+        _thh =  &(head)->hh;                                                     \
+        while (_thh) {                                                           \
+           _count++;                                                             \
+           if (_prev !=(char*)(_thh->prev)) {                                    \
+              HASH_OOPS("invalid prev %p, actual %p\n",                          \
+                    _thh->prev, _prev );                                         \
+           }                                                                     \
+           _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh);                    \
+           _thh = ( _thh->next ?  (UT_hash_handle*)((char*)(_thh->next) +        \
+                                  (head)->hh.tbl->hho) : NULL );                 \
+        }                                                                        \
+        if (_count != (head)->hh.tbl->num_items) {                               \
+            HASH_OOPS("invalid app item count %d, actual %d\n",                  \
+                (head)->hh.tbl->num_items, _count );                             \
+        }                                                                        \
+    }                                                                            \
+} while (0)
+#else
+#define HASH_FSCK(hh,head) 
+#endif
+
+/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to 
+ * the descriptor to which this macro is defined for tuning the hash function.
+ * The app can #include <unistd.h> to get the prototype for write(2). */
+#ifdef HASH_EMIT_KEYS
+#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                                   \
+do {                                                                             \
+    unsigned _klen = fieldlen;                                                   \
+    write(HASH_EMIT_KEYS, &_klen, sizeof(_klen));                                \
+    write(HASH_EMIT_KEYS, keyptr, fieldlen);                                     \
+} while (0)
+#else 
+#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                    
+#endif
+
+/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */
+#ifdef HASH_FUNCTION 
+#define HASH_FCN HASH_FUNCTION
+#else
+#define HASH_FCN HASH_JEN
+#endif
+
+/* The Bernstein hash function, used in Perl prior to v5.6 */
+#define HASH_BER(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _hb_keylen=keylen;                                                    \
+  char *_hb_key=(char*)(key);                                                    \
+  (hashv) = 0;                                                                   \
+  while (_hb_keylen--)  { (hashv) = ((hashv) * 33) + *_hb_key++; }               \
+  bkt = (hashv) & (num_bkts-1);                                                  \
+} while (0)
+
+
+/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at 
+ * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */
+#define HASH_SAX(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _sx_i;                                                                \
+  char *_hs_key=(char*)(key);                                                    \
+  hashv = 0;                                                                     \
+  for(_sx_i=0; _sx_i < keylen; _sx_i++)                                          \
+      hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i];                     \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while (0)
+
+#define HASH_FNV(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _fn_i;                                                                \
+  char *_hf_key=(char*)(key);                                                    \
+  hashv = 2166136261UL;                                                          \
+  for(_fn_i=0; _fn_i < keylen; _fn_i++)                                          \
+      hashv = (hashv * 16777619) ^ _hf_key[_fn_i];                               \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0);
+#define HASH_OAT(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _ho_i;                                                                \
+  char *_ho_key=(char*)(key);                                                    \
+  hashv = 0;                                                                     \
+  for(_ho_i=0; _ho_i < keylen; _ho_i++) {                                        \
+      hashv += _ho_key[_ho_i];                                                   \
+      hashv += (hashv << 10);                                                    \
+      hashv ^= (hashv >> 6);                                                     \
+  }                                                                              \
+  hashv += (hashv << 3);                                                         \
+  hashv ^= (hashv >> 11);                                                        \
+  hashv += (hashv << 15);                                                        \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+
+#define HASH_JEN_MIX(a,b,c)                                                      \
+do {                                                                             \
+  a -= b; a -= c; a ^= ( c >> 13 );                                              \
+  b -= c; b -= a; b ^= ( a << 8 );                                               \
+  c -= a; c -= b; c ^= ( b >> 13 );                                              \
+  a -= b; a -= c; a ^= ( c >> 12 );                                              \
+  b -= c; b -= a; b ^= ( a << 16 );                                              \
+  c -= a; c -= b; c ^= ( b >> 5 );                                               \
+  a -= b; a -= c; a ^= ( c >> 3 );                                               \
+  b -= c; b -= a; b ^= ( a << 10 );                                              \
+  c -= a; c -= b; c ^= ( b >> 15 );                                              \
+} while (0)
+
+#define HASH_JEN(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _hj_i,_hj_j,_hj_k;                                                    \
+  char *_hj_key=(char*)(key);                                                    \
+  hashv = 0xfeedbeef;                                                            \
+  _hj_i = _hj_j = 0x9e3779b9;                                                    \
+  _hj_k = keylen;                                                                \
+  while (_hj_k >= 12) {                                                          \
+    _hj_i +=    (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 )                      \
+        + ( (unsigned)_hj_key[2] << 16 )                                         \
+        + ( (unsigned)_hj_key[3] << 24 ) );                                      \
+    _hj_j +=    (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 )                      \
+        + ( (unsigned)_hj_key[6] << 16 )                                         \
+        + ( (unsigned)_hj_key[7] << 24 ) );                                      \
+    hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 )                         \
+        + ( (unsigned)_hj_key[10] << 16 )                                        \
+        + ( (unsigned)_hj_key[11] << 24 ) );                                     \
+                                                                                 \
+     HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                          \
+                                                                                 \
+     _hj_key += 12;                                                              \
+     _hj_k -= 12;                                                                \
+  }                                                                              \
+  hashv += keylen;                                                               \
+  switch ( _hj_k ) {                                                             \
+     case 11: hashv += ( (unsigned)_hj_key[10] << 24 );                          \
+     case 10: hashv += ( (unsigned)_hj_key[9] << 16 );                           \
+     case 9:  hashv += ( (unsigned)_hj_key[8] << 8 );                            \
+     case 8:  _hj_j += ( (unsigned)_hj_key[7] << 24 );                           \
+     case 7:  _hj_j += ( (unsigned)_hj_key[6] << 16 );                           \
+     case 6:  _hj_j += ( (unsigned)_hj_key[5] << 8 );                            \
+     case 5:  _hj_j += _hj_key[4];                                               \
+     case 4:  _hj_i += ( (unsigned)_hj_key[3] << 24 );                           \
+     case 3:  _hj_i += ( (unsigned)_hj_key[2] << 16 );                           \
+     case 2:  _hj_i += ( (unsigned)_hj_key[1] << 8 );                            \
+     case 1:  _hj_i += _hj_key[0];                                               \
+  }                                                                              \
+  HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                             \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+
+/* The Paul Hsieh hash function */
+#undef get16bits
+#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__)             \
+  || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
+#define get16bits(d) (*((const uint16_t *) (d)))
+#endif
+
+#if !defined (get16bits)
+#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)             \
+                       +(uint32_t)(((const uint8_t *)(d))[0]) )
+#endif
+#define HASH_SFH(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  char *_sfh_key=(char*)(key);                                                   \
+  uint32_t _sfh_tmp, _sfh_len = keylen;                                          \
+                                                                                 \
+  int _sfh_rem = _sfh_len & 3;                                                   \
+  _sfh_len >>= 2;                                                                \
+  hashv = 0xcafebabe;                                                            \
+                                                                                 \
+  /* Main loop */                                                                \
+  for (;_sfh_len > 0; _sfh_len--) {                                              \
+    hashv    += get16bits (_sfh_key);                                            \
+    _sfh_tmp       = (get16bits (_sfh_key+2) << 11) ^ hashv;                     \
+    hashv     = (hashv << 16) ^ _sfh_tmp;                                        \
+    _sfh_key += 2*sizeof (uint16_t);                                             \
+    hashv    += hashv >> 11;                                                     \
+  }                                                                              \
+                                                                                 \
+  /* Handle end cases */                                                         \
+  switch (_sfh_rem) {                                                            \
+    case 3: hashv += get16bits (_sfh_key);                                       \
+            hashv ^= hashv << 16;                                                \
+            hashv ^= _sfh_key[sizeof (uint16_t)] << 18;                          \
+            hashv += hashv >> 11;                                                \
+            break;                                                               \
+    case 2: hashv += get16bits (_sfh_key);                                       \
+            hashv ^= hashv << 11;                                                \
+            hashv += hashv >> 17;                                                \
+            break;                                                               \
+    case 1: hashv += *_sfh_key;                                                  \
+            hashv ^= hashv << 10;                                                \
+            hashv += hashv >> 1;                                                 \
+  }                                                                              \
+                                                                                 \
+    /* Force "avalanching" of final 127 bits */                                  \
+    hashv ^= hashv << 3;                                                         \
+    hashv += hashv >> 5;                                                         \
+    hashv ^= hashv << 4;                                                         \
+    hashv += hashv >> 17;                                                        \
+    hashv ^= hashv << 25;                                                        \
+    hashv += hashv >> 6;                                                         \
+    bkt = hashv & (num_bkts-1);                                                  \
+} while(0);
+
+#ifdef HASH_USING_NO_STRICT_ALIASING
+/* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads.
+ * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error.
+ * So MurmurHash comes in two versions, the faster unaligned one and the slower
+ * aligned one. We only use the faster one on CPU's where we know it's safe. 
+ *
+ * Note the preprocessor built-in defines can be emitted using:
+ *
+ *   gcc -m64 -dM -E - < /dev/null                  (on gcc)
+ *   cc -## a.c (where a.c is a simple test file)   (Sun Studio)
+ */
+#if (defined(__i386__) || defined(__x86_64__)) 
+#define HASH_MUR HASH_MUR_UNALIGNED
+#else
+#define HASH_MUR HASH_MUR_ALIGNED
+#endif
+
+/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */
+#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt)                        \
+do {                                                                             \
+  const unsigned int _mur_m = 0x5bd1e995;                                        \
+  const int _mur_r = 24;                                                         \
+  hashv = 0xcafebabe ^ keylen;                                                   \
+  char *_mur_key = (char *)(key);                                                \
+  uint32_t _mur_tmp, _mur_len = keylen;                                          \
+                                                                                 \
+  for (;_mur_len >= 4; _mur_len-=4) {                                            \
+    _mur_tmp = *(uint32_t *)_mur_key;                                            \
+    _mur_tmp *= _mur_m;                                                          \
+    _mur_tmp ^= _mur_tmp >> _mur_r;                                              \
+    _mur_tmp *= _mur_m;                                                          \
+    hashv *= _mur_m;                                                             \
+    hashv ^= _mur_tmp;                                                           \
+    _mur_key += 4;                                                               \
+  }                                                                              \
+                                                                                 \
+  switch(_mur_len)                                                               \
+  {                                                                              \
+    case 3: hashv ^= _mur_key[2] << 16;                                          \
+    case 2: hashv ^= _mur_key[1] << 8;                                           \
+    case 1: hashv ^= _mur_key[0];                                                \
+            hashv *= _mur_m;                                                     \
+  };                                                                             \
+                                                                                 \
+  hashv ^= hashv >> 13;                                                          \
+  hashv *= _mur_m;                                                               \
+  hashv ^= hashv >> 15;                                                          \
+                                                                                 \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+
+/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */
+#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt)                          \
+do {                                                                             \
+  const unsigned int _mur_m = 0x5bd1e995;                                        \
+  const int _mur_r = 24;                                                         \
+  hashv = 0xcafebabe ^ (keylen);                                                 \
+  char *_mur_key = (char *)(key);                                                \
+  uint32_t _mur_len = keylen;                                                    \
+  int _mur_align = (int)_mur_key & 3;                                            \
+                                                                                 \
+  if (_mur_align && (_mur_len >= 4)) {                                           \
+    unsigned _mur_t = 0, _mur_d = 0;                                             \
+    switch(_mur_align) {                                                         \
+      case 1: _mur_t |= _mur_key[2] << 16;                                       \
+      case 2: _mur_t |= _mur_key[1] << 8;                                        \
+      case 3: _mur_t |= _mur_key[0];                                             \
+    }                                                                            \
+    _mur_t <<= (8 * _mur_align);                                                 \
+    _mur_key += 4-_mur_align;                                                    \
+    _mur_len -= 4-_mur_align;                                                    \
+    int _mur_sl = 8 * (4-_mur_align);                                            \
+    int _mur_sr = 8 * _mur_align;                                                \
+                                                                                 \
+    for (;_mur_len >= 4; _mur_len-=4) {                                          \
+      _mur_d = *(unsigned *)_mur_key;                                            \
+      _mur_t = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);                        \
+      unsigned _mur_k = _mur_t;                                                  \
+      _mur_k *= _mur_m;                                                          \
+      _mur_k ^= _mur_k >> _mur_r;                                                \
+      _mur_k *= _mur_m;                                                          \
+      hashv *= _mur_m;                                                           \
+      hashv ^= _mur_k;                                                           \
+      _mur_t = _mur_d;                                                           \
+      _mur_key += 4;                                                             \
+    }                                                                            \
+    _mur_d = 0;                                                                  \
+    if(_mur_len >= _mur_align) {                                                 \
+      switch(_mur_align) {                                                       \
+        case 3: _mur_d |= _mur_key[2] << 16;                                     \
+        case 2: _mur_d |= _mur_key[1] << 8;                                      \
+        case 1: _mur_d |= _mur_key[0];                                           \
+      }                                                                          \
+      unsigned _mur_k = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);               \
+      _mur_k *= _mur_m;                                                          \
+      _mur_k ^= _mur_k >> _mur_r;                                                \
+      _mur_k *= _mur_m;                                                          \
+      hashv *= _mur_m;                                                           \
+      hashv ^= _mur_k;                                                           \
+      _mur_k += _mur_align;                                                      \
+      _mur_len -= _mur_align;                                                    \
+                                                                                 \
+      switch(_mur_len)                                                           \
+      {                                                                          \
+        case 3: hashv ^= _mur_key[2] << 16;                                      \
+        case 2: hashv ^= _mur_key[1] << 8;                                       \
+        case 1: hashv ^= _mur_key[0];                                            \
+                hashv *= _mur_m;                                                 \
+      }                                                                          \
+    } else {                                                                     \
+      switch(_mur_len)                                                           \
+      {                                                                          \
+        case 3: _mur_d ^= _mur_key[2] << 16;                                     \
+        case 2: _mur_d ^= _mur_key[1] << 8;                                      \
+        case 1: _mur_d ^= _mur_key[0];                                           \
+        case 0: hashv ^= (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);              \
+        hashv *= _mur_m;                                                         \
+      }                                                                          \
+    }                                                                            \
+                                                                                 \
+    hashv ^= hashv >> 13;                                                        \
+    hashv *= _mur_m;                                                             \
+    hashv ^= hashv >> 15;                                                        \
+  } else {                                                                       \
+    for (;_mur_len >= 4; _mur_len-=4) {                                          \
+      unsigned _mur_k = *(unsigned*)_mur_key;                                    \
+      _mur_k *= _mur_m;                                                          \
+      _mur_k ^= _mur_k >> _mur_r;                                                \
+      _mur_k *= _mur_m;                                                          \
+      hashv *= _mur_m;                                                           \
+      hashv ^= _mur_k;                                                           \
+      _mur_key += 4;                                                             \
+    }                                                                            \
+    switch(_mur_len)                                                             \
+    {                                                                            \
+      case 3: hashv ^= _mur_key[2] << 16;                                        \
+      case 2: hashv ^= _mur_key[1] << 8;                                         \
+      case 1: hashv ^= _mur_key[0];                                              \
+      hashv *= _mur_m;                                                           \
+    }                                                                            \
+                                                                                 \
+    hashv ^= hashv >> 13;                                                        \
+    hashv *= _mur_m;                                                             \
+    hashv ^= hashv >> 15;                                                        \
+  }                                                                              \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+#endif  /* HASH_USING_NO_STRICT_ALIASING */
+
+/* key comparison function; return 0 if keys equal */
+#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) 
+
+/* iterate over items in a known bucket to find desired item */
+#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out)                       \
+do {                                                                             \
+ if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head));          \
+ else out=NULL;                                                                  \
+ while (out) {                                                                   \
+    if (out->hh.keylen == keylen_in) {                                           \
+        if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break;             \
+    }                                                                            \
+    if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \
+    else out = NULL;                                                             \
+ }                                                                               \
+} while(0)
+
+/* add an item to a bucket  */
+#define HASH_ADD_TO_BKT(head,addhh)                                              \
+do {                                                                             \
+ head.count++;                                                                   \
+ (addhh)->hh_next = head.hh_head;                                                \
+ (addhh)->hh_prev = NULL;                                                        \
+ if (head.hh_head) { (head).hh_head->hh_prev = (addhh); }                        \
+ (head).hh_head=addhh;                                                           \
+ if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH)             \
+     && (addhh)->tbl->noexpand != 1) {                                           \
+       HASH_EXPAND_BUCKETS((addhh)->tbl);                                        \
+ }                                                                               \
+} while(0)
+
+/* remove an item from a given bucket */
+#define HASH_DEL_IN_BKT(hh,head,hh_del)                                          \
+    (head).count--;                                                              \
+    if ((head).hh_head == hh_del) {                                              \
+      (head).hh_head = hh_del->hh_next;                                          \
+    }                                                                            \
+    if (hh_del->hh_prev) {                                                       \
+        hh_del->hh_prev->hh_next = hh_del->hh_next;                              \
+    }                                                                            \
+    if (hh_del->hh_next) {                                                       \
+        hh_del->hh_next->hh_prev = hh_del->hh_prev;                              \
+    }                                                                
+
+/* Bucket expansion has the effect of doubling the number of buckets
+ * and redistributing the items into the new buckets. Ideally the
+ * items will distribute more or less evenly into the new buckets
+ * (the extent to which this is true is a measure of the quality of
+ * the hash function as it applies to the key domain). 
+ * 
+ * With the items distributed into more buckets, the chain length
+ * (item count) in each bucket is reduced. Thus by expanding buckets
+ * the hash keeps a bound on the chain length. This bounded chain 
+ * length is the essence of how a hash provides constant time lookup.
+ * 
+ * The calculation of tbl->ideal_chain_maxlen below deserves some
+ * explanation. First, keep in mind that we're calculating the ideal
+ * maximum chain length based on the *new* (doubled) bucket count.
+ * In fractions this is just n/b (n=number of items,b=new num buckets).
+ * Since the ideal chain length is an integer, we want to calculate 
+ * ceil(n/b). We don't depend on floating point arithmetic in this
+ * hash, so to calculate ceil(n/b) with integers we could write
+ * 
+ *      ceil(n/b) = (n/b) + ((n%b)?1:0)
+ * 
+ * and in fact a previous version of this hash did just that.
+ * But now we have improved things a bit by recognizing that b is
+ * always a power of two. We keep its base 2 log handy (call it lb),
+ * so now we can write this with a bit shift and logical AND:
+ * 
+ *      ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)
+ * 
+ */
+#define HASH_EXPAND_BUCKETS(tbl)                                                 \
+do {                                                                             \
+    unsigned _he_bkt;                                                            \
+    unsigned _he_bkt_i;                                                          \
+    struct UT_hash_handle *_he_thh, *_he_hh_nxt;                                 \
+    UT_hash_bucket *_he_new_buckets, *_he_newbkt;                                \
+    _he_new_buckets = (UT_hash_bucket*)uthash_malloc(                            \
+             2 * tbl->num_buckets * sizeof(struct UT_hash_bucket));              \
+    if (!_he_new_buckets) { uthash_fatal( "out of memory"); }                    \
+    memset(_he_new_buckets, 0,                                                   \
+            2 * tbl->num_buckets * sizeof(struct UT_hash_bucket));               \
+    tbl->ideal_chain_maxlen =                                                    \
+       (tbl->num_items >> (tbl->log2_num_buckets+1)) +                           \
+       ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0);                    \
+    tbl->nonideal_items = 0;                                                     \
+    for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++)                \
+    {                                                                            \
+        _he_thh = tbl->buckets[ _he_bkt_i ].hh_head;                             \
+        while (_he_thh) {                                                        \
+           _he_hh_nxt = _he_thh->hh_next;                                        \
+           HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt);            \
+           _he_newbkt = &(_he_new_buckets[ _he_bkt ]);                           \
+           if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) {                \
+             tbl->nonideal_items++;                                              \
+             _he_newbkt->expand_mult = _he_newbkt->count /                       \
+                                        tbl->ideal_chain_maxlen;                 \
+           }                                                                     \
+           _he_thh->hh_prev = NULL;                                              \
+           _he_thh->hh_next = _he_newbkt->hh_head;                               \
+           if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev =               \
+                _he_thh;                                                         \
+           _he_newbkt->hh_head = _he_thh;                                        \
+           _he_thh = _he_hh_nxt;                                                 \
+        }                                                                        \
+    }                                                                            \
+    uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \
+    tbl->num_buckets *= 2;                                                       \
+    tbl->log2_num_buckets++;                                                     \
+    tbl->buckets = _he_new_buckets;                                              \
+    tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ?         \
+        (tbl->ineff_expands+1) : 0;                                              \
+    if (tbl->ineff_expands > 1) {                                                \
+        tbl->noexpand=1;                                                         \
+        uthash_noexpand_fyi(tbl);                                                \
+    }                                                                            \
+    uthash_expand_fyi(tbl);                                                      \
+} while(0)
+
+
+/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */
+/* Note that HASH_SORT assumes the hash handle name to be hh. 
+ * HASH_SRT was added to allow the hash handle name to be passed in. */
+#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)
+#define HASH_SRT(hh,head,cmpfcn)                                                 \
+do {                                                                             \
+  unsigned _hs_i;                                                                \
+  unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize;               \
+  struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail;            \
+  if (head) {                                                                    \
+      _hs_insize = 1;                                                            \
+      _hs_looping = 1;                                                           \
+      _hs_list = &((head)->hh);                                                  \
+      while (_hs_looping) {                                                      \
+          _hs_p = _hs_list;                                                      \
+          _hs_list = NULL;                                                       \
+          _hs_tail = NULL;                                                       \
+          _hs_nmerges = 0;                                                       \
+          while (_hs_p) {                                                        \
+              _hs_nmerges++;                                                     \
+              _hs_q = _hs_p;                                                     \
+              _hs_psize = 0;                                                     \
+              for ( _hs_i = 0; _hs_i  < _hs_insize; _hs_i++ ) {                  \
+                  _hs_psize++;                                                   \
+                  _hs_q = (UT_hash_handle*)((_hs_q->next) ?                      \
+                          ((void*)((char*)(_hs_q->next) +                        \
+                          (head)->hh.tbl->hho)) : NULL);                         \
+                  if (! (_hs_q) ) break;                                         \
+              }                                                                  \
+              _hs_qsize = _hs_insize;                                            \
+              while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) {           \
+                  if (_hs_psize == 0) {                                          \
+                      _hs_e = _hs_q;                                             \
+                      _hs_q = (UT_hash_handle*)((_hs_q->next) ?                  \
+                              ((void*)((char*)(_hs_q->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_qsize--;                                               \
+                  } else if ( (_hs_qsize == 0) || !(_hs_q) ) {                   \
+                      _hs_e = _hs_p;                                             \
+                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
+                              ((void*)((char*)(_hs_p->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_psize--;                                               \
+                  } else if ((                                                   \
+                      cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \
+                             DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \
+                             ) <= 0) {                                           \
+                      _hs_e = _hs_p;                                             \
+                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
+                              ((void*)((char*)(_hs_p->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_psize--;                                               \
+                  } else {                                                       \
+                      _hs_e = _hs_q;                                             \
+                      _hs_q = (UT_hash_handle*)((_hs_q->next) ?                  \
+                              ((void*)((char*)(_hs_q->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_qsize--;                                               \
+                  }                                                              \
+                  if ( _hs_tail ) {                                              \
+                      _hs_tail->next = ((_hs_e) ?                                \
+                            ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL);          \
+                  } else {                                                       \
+                      _hs_list = _hs_e;                                          \
+                  }                                                              \
+                  _hs_e->prev = ((_hs_tail) ?                                    \
+                     ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL);              \
+                  _hs_tail = _hs_e;                                              \
+              }                                                                  \
+              _hs_p = _hs_q;                                                     \
+          }                                                                      \
+          _hs_tail->next = NULL;                                                 \
+          if ( _hs_nmerges <= 1 ) {                                              \
+              _hs_looping=0;                                                     \
+              (head)->hh.tbl->tail = _hs_tail;                                   \
+              DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list));      \
+          }                                                                      \
+          _hs_insize *= 2;                                                       \
+      }                                                                          \
+      HASH_FSCK(hh,head);                                                        \
+ }                                                                               \
+} while (0)
+
+/* This function selects items from one hash into another hash. 
+ * The end result is that the selected items have dual presence 
+ * in both hashes. There is no copy of the items made; rather 
+ * they are added into the new hash through a secondary hash 
+ * hash handle that must be present in the structure. */
+#define HASH_SELECT(hh_dst, dst, hh_src, src, cond)                              \
+do {                                                                             \
+  unsigned _src_bkt, _dst_bkt;                                                   \
+  void *_last_elt=NULL, *_elt;                                                   \
+  UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL;                         \
+  ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst));                 \
+  if (src) {                                                                     \
+    for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) {     \
+      for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head;                \
+          _src_hh;                                                               \
+          _src_hh = _src_hh->hh_next) {                                          \
+          _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh);                       \
+          if (cond(_elt)) {                                                      \
+            _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho);               \
+            _dst_hh->key = _src_hh->key;                                         \
+            _dst_hh->keylen = _src_hh->keylen;                                   \
+            _dst_hh->hashv = _src_hh->hashv;                                     \
+            _dst_hh->prev = _last_elt;                                           \
+            _dst_hh->next = NULL;                                                \
+            if (_last_elt_hh) { _last_elt_hh->next = _elt; }                     \
+            if (!dst) {                                                          \
+              DECLTYPE_ASSIGN(dst,_elt);                                         \
+              HASH_MAKE_TABLE(hh_dst,dst);                                       \
+            } else {                                                             \
+              _dst_hh->tbl = (dst)->hh_dst.tbl;                                  \
+            }                                                                    \
+            HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt);    \
+            HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh);            \
+            (dst)->hh_dst.tbl->num_items++;                                      \
+            _last_elt = _elt;                                                    \
+            _last_elt_hh = _dst_hh;                                              \
+          }                                                                      \
+      }                                                                          \
+    }                                                                            \
+  }                                                                              \
+  HASH_FSCK(hh_dst,dst);                                                         \
+} while (0)
+
+#define HASH_CLEAR(hh,head)                                                      \
+do {                                                                             \
+  if (head) {                                                                    \
+    uthash_free((head)->hh.tbl->buckets,                                         \
+                (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket));      \
+    uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                          \
+    (head)=NULL;                                                                 \
+  }                                                                              \
+} while(0)
+
+#ifdef NO_DECLTYPE
+#define HASH_ITER(hh,head,el,tmp)                                                \
+for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL);       \
+  el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) 
+#else
+#define HASH_ITER(hh,head,el,tmp)                                                \
+for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL);                 \
+  el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL))
+#endif
+
+/* obtain a count of items in the hash */
+#define HASH_COUNT(head) HASH_CNT(hh,head) 
+#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0)
+
+typedef struct UT_hash_bucket {
+   struct UT_hash_handle *hh_head;
+   unsigned count;
+
+   /* expand_mult is normally set to 0. In this situation, the max chain length
+    * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
+    * the bucket's chain exceeds this length, bucket expansion is triggered). 
+    * However, setting expand_mult to a non-zero value delays bucket expansion
+    * (that would be triggered by additions to this particular bucket)
+    * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.
+    * (The multiplier is simply expand_mult+1). The whole idea of this
+    * multiplier is to reduce bucket expansions, since they are expensive, in
+    * situations where we know that a particular bucket tends to be overused.
+    * It is better to let its chain length grow to a longer yet-still-bounded
+    * value, than to do an O(n) bucket expansion too often. 
+    */
+   unsigned expand_mult;
+
+} UT_hash_bucket;
+
+/* random signature used only to find hash tables in external analysis */
+#define HASH_SIGNATURE 0xa0111fe1
+#define HASH_BLOOM_SIGNATURE 0xb12220f2
+
+typedef struct UT_hash_table {
+   UT_hash_bucket *buckets;
+   unsigned num_buckets, log2_num_buckets;
+   unsigned num_items;
+   struct UT_hash_handle *tail; /* tail hh in app order, for fast append    */
+   ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */
+
+   /* in an ideal situation (all buckets used equally), no bucket would have
+    * more than ceil(#items/#buckets) items. that's the ideal chain length. */
+   unsigned ideal_chain_maxlen;
+
+   /* nonideal_items is the number of items in the hash whose chain position
+    * exceeds the ideal chain maxlen. these items pay the penalty for an uneven
+    * hash distribution; reaching them in a chain traversal takes >ideal steps */
+   unsigned nonideal_items;
+
+   /* ineffective expands occur when a bucket doubling was performed, but 
+    * afterward, more than half the items in the hash had nonideal chain
+    * positions. If this happens on two consecutive expansions we inhibit any
+    * further expansion, as it's not helping; this happens when the hash
+    * function isn't a good fit for the key domain. When expansion is inhibited
+    * the hash will still work, albeit no longer in constant time. */
+   unsigned ineff_expands, noexpand;
+
+   uint32_t signature; /* used only to find hash tables in external analysis */
+#ifdef HASH_BLOOM
+   uint32_t bloom_sig; /* used only to test bloom exists in external analysis */
+   uint8_t *bloom_bv;
+   char bloom_nbits;
+#endif
+
+} UT_hash_table;
+
+typedef struct UT_hash_handle {
+   struct UT_hash_table *tbl;
+   void *prev;                       /* prev element in app order      */
+   void *next;                       /* next element in app order      */
+   struct UT_hash_handle *hh_prev;   /* previous hh in bucket order    */
+   struct UT_hash_handle *hh_next;   /* next hh in bucket order        */
+   void *key;                        /* ptr to enclosing struct's key  */
+   unsigned keylen;                  /* enclosing struct's key len     */
+   unsigned hashv;                   /* result of hash-fcn(key)        */
+} UT_hash_handle;
+
+#endif /* _DTLS_UTHASH_H */
diff --git a/extlibs/tinydtls/utlist.h b/extlibs/tinydtls/utlist.h
new file mode 100644 (file)
index 0000000..8b03b6b
--- /dev/null
@@ -0,0 +1,490 @@
+/*
+Copyright (c) 2007-2010, Troy D. Hanson   http://uthash.sourceforge.net
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef _DTLS_UTLIST_H
+#define _DTLS_UTLIST_H
+
+#define UTLIST_VERSION 1.9.1
+
+/* 
+ * This file contains macros to manipulate singly and doubly-linked lists.
+ *
+ * 1. LL_ macros:  singly-linked lists.
+ * 2. DL_ macros:  doubly-linked lists.
+ * 3. CDL_ macros: circular doubly-linked lists.
+ *
+ * To use singly-linked lists, your structure must have a "next" pointer.
+ * To use doubly-linked lists, your structure must "prev" and "next" pointers.
+ * Either way, the pointer to the head of the list must be initialized to NULL.
+ * 
+ * ----------------.EXAMPLE -------------------------
+ * struct item {
+ *      int id;
+ *      struct item *prev, *next;
+ * }
+ *
+ * struct item *list = NULL:
+ *
+ * int main() {
+ *      struct item *item;
+ *      ... allocate and populate item ...
+ *      DL_APPEND(list, item);
+ * }
+ * --------------------------------------------------
+ *
+ * For doubly-linked lists, the append and delete macros are O(1)
+ * For singly-linked lists, append and delete are O(n) but prepend is O(1)
+ * The sort macro is O(n log(n)) for all types of single/double/circular lists.
+ */
+
+/* These macros use decltype or the earlier __typeof GNU extension.
+   As decltype is only available in newer compilers (VS2010 or gcc 4.3+
+   when compiling c++ code), this code uses whatever method is needed
+   or, for VS2008 where neither is available, uses casting workarounds. */
+#ifdef _MSC_VER            /* MS compiler */
+#if _MSC_VER >= 1600 && __cplusplus  /* VS2010 and newer in C++ mode */
+#define LDECLTYPE(x) decltype(x)
+#else                     /* VS2008 or older (or VS2010 in C mode) */
+#define NO_DECLTYPE
+#define LDECLTYPE(x) char*
+#endif
+#else                      /* GNU, Sun and other compilers */
+#define LDECLTYPE(x) __typeof(x)
+#endif
+
+/* for VS2008 we use some workarounds to get around the lack of decltype,
+ * namely, we always reassign our tmp variable to the list head if we need
+ * to dereference its prev/next pointers, and save/restore the real head.*/
+#ifdef NO_DECLTYPE
+#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); }
+#define _NEXT(elt,list) ((char*)((list)->next))
+#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); }
+#define _PREV(elt,list) ((char*)((list)->prev))
+#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); }
+#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; }
+#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); }
+#else 
+#define _SV(elt,list)
+#define _NEXT(elt,list) ((elt)->next)
+#define _NEXTASGN(elt,list,to) ((elt)->next)=(to)
+#define _PREV(elt,list) ((elt)->prev)
+#define _PREVASGN(elt,list,to) ((elt)->prev)=(to)
+#define _RS(list)
+#define _CASTASGN(a,b) (a)=(b)
+#endif
+
+/******************************************************************************
+ * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort    *
+ * Unwieldy variable names used here to avoid shadowing passed-in variables.  *
+ *****************************************************************************/
+#define LL_SORT(list, cmp)                                                                     \
+do {                                                                                           \
+  LDECLTYPE(list) _ls_p;                                                                       \
+  LDECLTYPE(list) _ls_q;                                                                       \
+  LDECLTYPE(list) _ls_e;                                                                       \
+  LDECLTYPE(list) _ls_tail;                                                                    \
+  LDECLTYPE(list) _ls_oldhead;                                                                 \
+  LDECLTYPE(list) _tmp;                                                                        \
+  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
+  if (list) {                                                                                  \
+    _ls_insize = 1;                                                                            \
+    _ls_looping = 1;                                                                           \
+    while (_ls_looping) {                                                                      \
+      _CASTASGN(_ls_p,list);                                                                   \
+      _CASTASGN(_ls_oldhead,list);                                                             \
+      list = NULL;                                                                             \
+      _ls_tail = NULL;                                                                         \
+      _ls_nmerges = 0;                                                                         \
+      while (_ls_p) {                                                                          \
+        _ls_nmerges++;                                                                         \
+        _ls_q = _ls_p;                                                                         \
+        _ls_psize = 0;                                                                         \
+        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
+          _ls_psize++;                                                                         \
+          _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list);                               \
+          if (!_ls_q) break;                                                                   \
+        }                                                                                      \
+        _ls_qsize = _ls_insize;                                                                \
+        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
+          if (_ls_psize == 0) {                                                                \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else {                                                                             \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          }                                                                                    \
+          if (_ls_tail) {                                                                      \
+            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
+          } else {                                                                             \
+            _CASTASGN(list,_ls_e);                                                             \
+          }                                                                                    \
+          _ls_tail = _ls_e;                                                                    \
+        }                                                                                      \
+        _ls_p = _ls_q;                                                                         \
+      }                                                                                        \
+      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list);                            \
+      if (_ls_nmerges <= 1) {                                                                  \
+        _ls_looping=0;                                                                         \
+      }                                                                                        \
+      _ls_insize *= 2;                                                                         \
+    }                                                                                          \
+  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
+} while (0)
+
+#define DL_SORT(list, cmp)                                                                     \
+do {                                                                                           \
+  LDECLTYPE(list) _ls_p;                                                                       \
+  LDECLTYPE(list) _ls_q;                                                                       \
+  LDECLTYPE(list) _ls_e;                                                                       \
+  LDECLTYPE(list) _ls_tail;                                                                    \
+  LDECLTYPE(list) _ls_oldhead;                                                                 \
+  LDECLTYPE(list) _tmp;                                                                        \
+  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
+  if (list) {                                                                                  \
+    _ls_insize = 1;                                                                            \
+    _ls_looping = 1;                                                                           \
+    while (_ls_looping) {                                                                      \
+      _CASTASGN(_ls_p,list);                                                                   \
+      _CASTASGN(_ls_oldhead,list);                                                             \
+      list = NULL;                                                                             \
+      _ls_tail = NULL;                                                                         \
+      _ls_nmerges = 0;                                                                         \
+      while (_ls_p) {                                                                          \
+        _ls_nmerges++;                                                                         \
+        _ls_q = _ls_p;                                                                         \
+        _ls_psize = 0;                                                                         \
+        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
+          _ls_psize++;                                                                         \
+          _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list);                               \
+          if (!_ls_q) break;                                                                   \
+        }                                                                                      \
+        _ls_qsize = _ls_insize;                                                                \
+        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
+          if (_ls_psize == 0) {                                                                \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else {                                                                             \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          }                                                                                    \
+          if (_ls_tail) {                                                                      \
+            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
+          } else {                                                                             \
+            _CASTASGN(list,_ls_e);                                                             \
+          }                                                                                    \
+          _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list);                          \
+          _ls_tail = _ls_e;                                                                    \
+        }                                                                                      \
+        _ls_p = _ls_q;                                                                         \
+      }                                                                                        \
+      _CASTASGN(list->prev, _ls_tail);                                                         \
+      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list);                            \
+      if (_ls_nmerges <= 1) {                                                                  \
+        _ls_looping=0;                                                                         \
+      }                                                                                        \
+      _ls_insize *= 2;                                                                         \
+    }                                                                                          \
+  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
+} while (0)
+
+#define CDL_SORT(list, cmp)                                                                    \
+do {                                                                                           \
+  LDECLTYPE(list) _ls_p;                                                                       \
+  LDECLTYPE(list) _ls_q;                                                                       \
+  LDECLTYPE(list) _ls_e;                                                                       \
+  LDECLTYPE(list) _ls_tail;                                                                    \
+  LDECLTYPE(list) _ls_oldhead;                                                                 \
+  LDECLTYPE(list) _tmp;                                                                        \
+  LDECLTYPE(list) _tmp2;                                                                       \
+  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
+  if (list) {                                                                                  \
+    _ls_insize = 1;                                                                            \
+    _ls_looping = 1;                                                                           \
+    while (_ls_looping) {                                                                      \
+      _CASTASGN(_ls_p,list);                                                                   \
+      _CASTASGN(_ls_oldhead,list);                                                             \
+      list = NULL;                                                                             \
+      _ls_tail = NULL;                                                                         \
+      _ls_nmerges = 0;                                                                         \
+      while (_ls_p) {                                                                          \
+        _ls_nmerges++;                                                                         \
+        _ls_q = _ls_p;                                                                         \
+        _ls_psize = 0;                                                                         \
+        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
+          _ls_psize++;                                                                         \
+          _SV(_ls_q,list);                                                                     \
+          if (_NEXT(_ls_q,list) == _ls_oldhead) {                                              \
+            _ls_q = NULL;                                                                      \
+          } else {                                                                             \
+            _ls_q = _NEXT(_ls_q,list);                                                         \
+          }                                                                                    \
+          _RS(list);                                                                           \
+          if (!_ls_q) break;                                                                   \
+        }                                                                                      \
+        _ls_qsize = _ls_insize;                                                                \
+        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
+          if (_ls_psize == 0) {                                                                \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+            if (_ls_q == _ls_oldhead) { _ls_q = NULL; }                                        \
+          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+            if (_ls_p == _ls_oldhead) { _ls_p = NULL; }                                        \
+          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+            if (_ls_p == _ls_oldhead) { _ls_p = NULL; }                                        \
+          } else {                                                                             \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+            if (_ls_q == _ls_oldhead) { _ls_q = NULL; }                                        \
+          }                                                                                    \
+          if (_ls_tail) {                                                                      \
+            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
+          } else {                                                                             \
+            _CASTASGN(list,_ls_e);                                                             \
+          }                                                                                    \
+          _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list);                          \
+          _ls_tail = _ls_e;                                                                    \
+        }                                                                                      \
+        _ls_p = _ls_q;                                                                         \
+      }                                                                                        \
+      _CASTASGN(list->prev,_ls_tail);                                                          \
+      _CASTASGN(_tmp2,list);                                                                   \
+      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list);                           \
+      if (_ls_nmerges <= 1) {                                                                  \
+        _ls_looping=0;                                                                         \
+      }                                                                                        \
+      _ls_insize *= 2;                                                                         \
+    }                                                                                          \
+  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
+} while (0)
+
+/******************************************************************************
+ * singly linked list macros (non-circular)                                   *
+ *****************************************************************************/
+#define LL_PREPEND(head,add)                                                                   \
+do {                                                                                           \
+  (add)->next = head;                                                                          \
+  head = add;                                                                                  \
+} while (0)
+
+#define LL_APPEND(head,add)                                                                    \
+do {                                                                                           \
+  LDECLTYPE(head) _tmp;                                                                        \
+  (add)->next=NULL;                                                                            \
+  if (head) {                                                                                  \
+    _tmp = head;                                                                               \
+    while (_tmp->next) { _tmp = _tmp->next; }                                                  \
+    _tmp->next=(add);                                                                          \
+  } else {                                                                                     \
+    (head)=(add);                                                                              \
+  }                                                                                            \
+} while (0)
+
+#define LL_DELETE(head,del)                                                                    \
+do {                                                                                           \
+  LDECLTYPE(head) _tmp;                                                                        \
+  if ((head) == (del)) {                                                                       \
+    (head)=(head)->next;                                                                       \
+  } else {                                                                                     \
+    _tmp = head;                                                                               \
+    while (_tmp->next && (_tmp->next != (del))) {                                              \
+      _tmp = _tmp->next;                                                                       \
+    }                                                                                          \
+    if (_tmp->next) {                                                                          \
+      _tmp->next = ((del)->next);                                                              \
+    }                                                                                          \
+  }                                                                                            \
+} while (0)
+
+/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */
+#define LL_APPEND_VS2008(head,add)                                                             \
+do {                                                                                           \
+  if (head) {                                                                                  \
+    (add)->next = head;     /* use add->next as a temp variable */                             \
+    while ((add)->next->next) { (add)->next = (add)->next->next; }                             \
+    (add)->next->next=(add);                                                                   \
+  } else {                                                                                     \
+    (head)=(add);                                                                              \
+  }                                                                                            \
+  (add)->next=NULL;                                                                            \
+} while (0)
+
+#define LL_DELETE_VS2008(head,del)                                                             \
+do {                                                                                           \
+  if ((head) == (del)) {                                                                       \
+    (head)=(head)->next;                                                                       \
+  } else {                                                                                     \
+    char *_tmp = (char*)(head);                                                                \
+    while (head->next && (head->next != (del))) {                                              \
+      head = head->next;                                                                       \
+    }                                                                                          \
+    if (head->next) {                                                                          \
+      head->next = ((del)->next);                                                              \
+    }                                                                                          \
+    {                                                                                          \
+      char **_head_alias = (char**)&(head);                                                    \
+      *_head_alias = _tmp;                                                                     \
+    }                                                                                          \
+  }                                                                                            \
+} while (0)
+#ifdef NO_DECLTYPE
+#undef LL_APPEND
+#define LL_APPEND LL_APPEND_VS2008
+#undef LL_DELETE
+#define LL_DELETE LL_DELETE_VS2008
+#endif
+/* end VS2008 replacements */
+
+#define LL_FOREACH(head,el)                                                                    \
+    for(el=head;el;el=el->next)
+
+#define LL_FOREACH_SAFE(head,el,tmp)                                                           \
+  for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp)
+
+#define LL_SEARCH_SCALAR(head,out,field,val)                                                   \
+do {                                                                                           \
+    LL_FOREACH(head,out) {                                                                     \
+      if ((out)->field == (val)) break;                                                        \
+    }                                                                                          \
+} while(0) 
+
+#define LL_SEARCH(head,out,elt,cmp)                                                            \
+do {                                                                                           \
+    LL_FOREACH(head,out) {                                                                     \
+      if ((cmp(out,elt))==0) break;                                                            \
+    }                                                                                          \
+} while(0) 
+
+/******************************************************************************
+ * doubly linked list macros (non-circular)                                   *
+ *****************************************************************************/
+#define DL_PREPEND(head,add)                                                                   \
+do {                                                                                           \
+ (add)->next = head;                                                                           \
+ if (head) {                                                                                   \
+   (add)->prev = (head)->prev;                                                                 \
+   (head)->prev = (add);                                                                       \
+ } else {                                                                                      \
+   (add)->prev = (add);                                                                        \
+ }                                                                                             \
+ (head) = (add);                                                                               \
+} while (0)
+
+#define DL_APPEND(head,add)                                                                    \
+do {                                                                                           \
+  if (head) {                                                                                  \
+      (add)->prev = (head)->prev;                                                              \
+      (head)->prev->next = (add);                                                              \
+      (head)->prev = (add);                                                                    \
+      (add)->next = NULL;                                                                      \
+  } else {                                                                                     \
+      (head)=(add);                                                                            \
+      (head)->prev = (head);                                                                   \
+      (head)->next = NULL;                                                                     \
+  }                                                                                            \
+} while (0);
+
+#define DL_DELETE(head,del)                                                                    \
+do {                                                                                           \
+  if ((del)->prev == (del)) {                                                                  \
+      (head)=NULL;                                                                             \
+  } else if ((del)==(head)) {                                                                  \
+      (del)->next->prev = (del)->prev;                                                         \
+      (head) = (del)->next;                                                                    \
+  } else {                                                                                     \
+      (del)->prev->next = (del)->next;                                                         \
+      if ((del)->next) {                                                                       \
+          (del)->next->prev = (del)->prev;                                                     \
+      } else {                                                                                 \
+          (head)->prev = (del)->prev;                                                          \
+      }                                                                                        \
+  }                                                                                            \
+} while (0);
+
+
+#define DL_FOREACH(head,el)                                                                    \
+    for(el=head;el;el=el->next)
+
+/* this version is safe for deleting the elements during iteration */
+#define DL_FOREACH_SAFE(head,el,tmp)                                                           \
+  for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp)
+
+/* these are identical to their singly-linked list counterparts */
+#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR
+#define DL_SEARCH LL_SEARCH
+
+/******************************************************************************
+ * circular doubly linked list macros                                         *
+ *****************************************************************************/
+#define CDL_PREPEND(head,add)                                                                  \
+do {                                                                                           \
+ if (head) {                                                                                   \
+   (add)->prev = (head)->prev;                                                                 \
+   (add)->next = (head);                                                                       \
+   (head)->prev = (add);                                                                       \
+   (add)->prev->next = (add);                                                                  \
+ } else {                                                                                      \
+   (add)->prev = (add);                                                                        \
+   (add)->next = (add);                                                                        \
+ }                                                                                             \
+(head)=(add);                                                                                  \
+} while (0)
+
+#define CDL_DELETE(head,del)                                                                   \
+do {                                                                                           \
+  if ( ((head)==(del)) && ((head)->next == (head))) {                                          \
+      (head) = 0L;                                                                             \
+  } else {                                                                                     \
+     (del)->next->prev = (del)->prev;                                                          \
+     (del)->prev->next = (del)->next;                                                          \
+     if ((del) == (head)) (head)=(del)->next;                                                  \
+  }                                                                                            \
+} while (0);
+
+#define CDL_FOREACH(head,el)                                                                   \
+    for(el=head;el;el=(el->next==head ? 0L : el->next)) 
+
+#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2)                                                    \
+  for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL);                                        \
+      (el) && ((tmp2)=(el)->next, 1);                                                          \
+      ((el) = (((el)==(tmp1)) ? 0L : (tmp2))))
+
+#define CDL_SEARCH_SCALAR(head,out,field,val)                                                  \
+do {                                                                                           \
+    CDL_FOREACH(head,out) {                                                                    \
+      if ((out)->field == (val)) break;                                                        \
+    }                                                                                          \
+} while(0) 
+
+#define CDL_SEARCH(head,out,elt,cmp)                                                           \
+do {                                                                                           \
+    CDL_FOREACH(head,out) {                                                                    \
+      if ((cmp(out,elt))==0) break;                                                            \
+    }                                                                                          \
+} while(0) 
+
+#endif /* _DTLS_UTLIST_H */
+
index dc2e48e..6cd51b7 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
 #
@@ -11,25 +31,4 @@ target_os = env.get('TARGET_OS')
 target_arch = env.get('TARGET_ARCH')
 src_dir = env.get('SRC_DIR')
 
-if target_os == 'arduino':
-       # Add 'NET' build option, let user select board network connection type
-       vars = Variables()
-       vars.Add(EnumVariable('NET', 'Network connection type', 'Ethernet', ['Ethernet', 'Wifi']))
-       vars.Update(env)
-       Help(vars.GenerateHelpText(env))
-
-# check 'cereal' library, temporarily put it here
-if not os.path.exists(src_dir + '/extlibs/cereal'):
-       print '''
-*********************************** Error: **************************************
-*  'Cereal' library doesn't exist. please download cereal to extlibs directory  *
-* add apply the patch as following:                                             *
-*     $ git clone https://github.com/USCiLab/cereal.git <src_dir>/extlibs/cereal*
-*     $ cd <src_dir>/extlibs/cereal                                             *
-*     $ git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245               *
-*     $ git apply ../../resource/patches/cereal_gcc46.patch                     *
-*********************************************************************************
-'''
-       Exit(1)
-else:
-       env.AppendUnique(CPPPATH = [src_dir + '/extlibs/cereal/include'])
+env.SConscript('extlibs/cereal/SConscript')
diff --git a/gbsbuild.sh b/gbsbuild.sh
new file mode 100644 (file)
index 0000000..d4542f0
--- /dev/null
@@ -0,0 +1,59 @@
+#!/bin/sh
+
+spec=`ls tools/tizen/*.spec`
+version=`rpm --query --queryformat '%{version}\n' --specfile $spec`
+
+name=`echo $name|cut -d" " -f 1`
+version=`echo $version|cut -d" " -f 1`
+
+name=iotivity
+
+rm -rf $name-$version
+
+builddir=`pwd`
+sourcedir=`pwd`
+
+echo `pwd`
+
+mkdir ./tmp
+mkdir ./tmp/extlibs/
+mkdir ./tmp/packaging
+cp -R ./build_common $sourcedir/tmp
+cp -R ./examples $sourcedir/tmp
+cp -R ./extlibs/cereal $sourcedir/tmp/extlibs
+cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
+cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
+cp -R ./extlibs/timer $sourcedir/tmp/extlibs
+cp -R ./extlibs/rapidxml $sourcedir/tmp/extlibs
+cp -R ./resource $sourcedir/tmp
+cp -R ./service $sourcedir/tmp
+cp ./extra_options.scons $sourcedir/tmp
+cp ./tools/tizen/*.spec ./tmp/packaging
+cp ./SConstruct ./tmp
+cp ./tools/tizen/*.rpm ./tmp
+cp ./tools/tizen/.gbs.conf ./tmp
+cd $sourcedir/tmp
+
+echo `pwd`
+rm -rf ./extlibs/cereal/cereal/.git*
+
+# Initialize Git repository
+if [ ! -d .git ]; then
+   git init ./
+   git config user.email "you@example.com"
+   git config user.name "Your Name"
+   git add ./
+   git commit -m "Initial commit"
+fi
+
+echo "Calling core gbs build command"
+gbscommand="gbs build -A armv7l -B ~/GBS-ROOT --include-all --repository ./"
+echo $gbscommand
+if eval $gbscommand; then
+   echo "Build is successful"
+else
+   echo "Build failed!"
+fi
+
+cd $sourcedir
+rm -rf $sourcedir/tmp
diff --git a/resource/README.setup.txt b/resource/README.setup.txt
deleted file mode 100644 (file)
index d248d66..0000000
+++ /dev/null
@@ -1,266 +0,0 @@
-******************************************************************
-
- 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.
-
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-===============================================================================
-==                    NOTICE - Transition to SCONS                           ==
-===============================================================================
-
-The IoTivity build system is transitioning to SCONS. Although the 
-makefiles are still available (until v1.0) and some developers are 
-still using them, they are currently no longer supported. To learn more 
-about building using SCONS see Readme.scons.txt in the repository root 
-directory. The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
-===============================================================================
-==                      Rich Stack & Lite Stack                              ==
-===============================================================================
-
-The OIC-RESOURCE repository (referred as "<oic-resource>") contains two SDKs
-with underlying code (i.e. "stack"). The two SDKs are referred to as "Rich SDK"
-(or "C++ SDK") and "Lite SDK" (or "C SDK"). The associated stacks are referred
-to as "Rich Stack" (or "C++ Stack") and "Lite Stack" (or "C Stack"),
-respectively. The Rich Stack-SDK pair requires that the Lite Stack-SDK pair is
-built under it.
-
-For a list of artifact locations for all possible build processes in the
-OIC-RESOURCE repository, please refer to:
-<oic-resource>/artifact_output_locations.txt.
-
-===============================================================================
-
-The Rich Stack is intended ONLY for Linux Ubuntu 12.04 operating system.
-To build Rich Stack, please follow these requirements:
-- GCC compiler version is 4.6
-- Pre-install the "gnu-libc" libraries package.
-- You have pre-built the Lite Stack for Linux Ubuntu 12.04.
-- You have installed and pre-built Boost 1.54.
-- To compile Rich Unit Tests, you must have Google Test 1.7.0 and must also
-  create/append "local.properties" file at <oic-resource>/csdk/ with the
-  following specified:
-
-  GTEST_DIR=<gtest-1.7.0>
-
-The Lite Stack is intended ONLY for Linux Ubuntu 12.04, Arduino ATMega 2560 with
-Arduino Framework 1.0.5, and Arduino Due with Arduino Framework 1.5.7.
-Tip: Use Cutecom in Ubuntu 12.04 to view logs from Arduino ATMega 2560 and
-Arduino Due.
-
-To build Lite Stack, please follow these requirements for Linux Ubuntu 12.04:
-- GCC compiler version is 4.6
-- Pre-install the "gnu-libc" libraries package.
-
-To build Lite Stack, please follow these requirements for Arduino ATMega 2560:
-- Arduino Framework 1.0.5 is installed. (Newer versions of the Arduino
-  Framework for Arduino ATMega 2560 have not been tested.)
-- AVR-GCC compiler version is 4.5.3 (Distributed with Arduino 1.0.5, no further
-  action necessary if framework was obtained from
-  http://arduino.cc/en/Main/OldSoftwareReleases. Note: Frameworks obtained from
-  apt-get have had different compiler versions.)
-- Unzip the Time Library from here to your Arduino Directory Structure:
-  http://playground.arduino.cc/code/time
-- Apply patch "arduino-1.0.5_linux.patch" at
-  <oic-resource>/tools/arduino/patches to your Arduino Directory Structure at
-  location <Arduino 1.0.5>.
-- Create/Append "local.properties" file at location
-  <oic-resource>/resource/csdk/ with the following specified:
-
-  ARDUINO_DIR := <arduino-1.0.5>
-  ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/avr/bin
-
-To build Lite Stack, please follow these requirements for Arduino Due:
-- Arduino Framework 1.5.7 is installed. (Newer versions of the Arduino
-  Framework for Arduino Due have not been tested.)
-- AVR-GCC compiler version is 4.8.3 (Distributed with Arduino 1.5.7, no further
-  action necessary if framework was obtained from
-  http://arduino.cc/en/Main/OldSoftwareReleases. Note: Frameworks obtained from
-  apt-get have had different compiler versions.)
-- Unzip the Time Library from here to your Arduino Directory Structure:
-  http://www.pjrc.com/teensy/td_libs_Time.html
-- Apply patch "arduino-1.5.7_linux.patch" at
-  <oic-resource>/tools/arduino/patches to your Arduino Directory Structure at
-  location <Arduino 1.5.7>.
-- Create/Append "local.properties" file at location
-  <oic-resource>/resource/csdk/ with the following specified:
-
-  ARDUINO_DIR := <arduino-1.5.7>
-  ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/avr/bin
-
-Note: If you are building Unit Tests for Linux, building for Arduino Mega, and
-building for Arduino Due you may find it useful to set the "local.properties"
-file to look like this:
-
-GTEST_DIR=<gtest-1.7.0>
-
-ifeq ($(PLATFORM), arduinomega)
-       #Location of arduino sdk for Arduino Mega
-       ARDUINO_DIR := <arduino-1.0.5>
-       ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/avr/bin
-else
-       #Location of arduino sdk for Arduino Due
-       ARDUINO_DIR := <arduino-1.5.7>
-       ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin
-endif
-
-===============================================================================
-
-Instructions for Common Build Processes:
-
-NOTE: 'GNU Make' is required to utilize the build script at location:
-<oic-resource>/buildScript.mk.
-
-=======================================
-== All Targets - Linux, ATMega & Due ==
-=======================================
-
-- All Modules, including OCICUC, in Release & Debug (Lite Stack, Lite Unit
-  Tests, Lite Examples, Rich Stack, Rich Unit Tests, Rich Examples, Rich
-  OCICUC) for linux, Arduino ATMega 2560 with Ethernet Shield, Arduino ATMega
-  ATMega 2560 with WiFi Shield, Arduino Due with Ethernet Shield and Arduino
-  Due with WiFi Shield:
-  (This will be what is used on the Build Server(s) to limit regression.)
-
-       make -f buildScript.mk all_dev
-
-=======================================
-== All Targets - Linux & ATMega 2560 ==
-=======================================
-
-- All Modules in Release (Lite Stack, Lite Unit Tests, Lite Examples, Rich
-  Stack, Rich Unit Tests, Rich Examples) for Linux & Arduino ATMega 2560 with
-  Ethernet Shield:
-
-       make -f buildScript.mk all
-
-- All Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples, Rich Stack,
-  Rich Examples) for Linux & Arduino ATMega 2560 with Ethernet Shield:
-
-       make -f buildScript.mk all_debug
-
-=======================================
-==     All Targets - Linux & Due     ==
-=======================================
-
-- All Modules in Release (Lite Stack, Lite Unit Tests, Lite Examples, Rich
-  Stack, Rich Unit Tests, Rich Examples) for Linux & Arduino Due with Ethernet
-  Shield:
-
-       make -f buildScript.mk complement
-
-- All Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples, Rich Stack,
-  Rich Unit Tests, Rich Examples) for Linux & Arduino Due with Ethernet Shield:
-
-       make -f buildScript.mk complement_debug
-
-=======================================
-==     All Targets - Linux Only      ==
-=======================================
-
-- All Modules, without OCICUC, in Release (Lite Stack, Lite Unit Tests, Lite
-  Examples, Rich Stack, Rich Unit Tests, Rich Examples) for linux:
-
-       make -f buildScript.mk linux
-
-- All Modules, without OCICUC, in Debug (Lite Stack, Lite Unit Tests, Lite
-  Examples, Rich Stack, Rich Unit Tests, Rich Examples) for linux:
-
-       make -f buildScript.mk linux_debug
-
-- All Rich Stack Modules in Release, without OCICUC, (Lite Stack, Rich Stack,
-  Rich Unit Tests, Rich Examples) for Linux:
-
-       make -f buildScript.mk linux_ub
-
-- All Rich Stack Modules in Debug, without OCICUC, (Lite Stack, Rich Stack,
-  Rich Unit Tests, Rich Examples) for Linux:
-
-       make -f buildScript.mk linux_ub_debug
-
-- All Rich Stack Modules, including OCICUC, in Release & Debug (Lite Stack,
-  Rich Stack, Rich Unit Tests, Rich Examples, Rich OCICUC) for linux:
-
-       make -f buildScript.mk linux_ub_dev
-
-- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite
-  Examples) for Linux:
-
-       make -f buildScript.mk linux_tb
-
-- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples)
-  for Linux:
-
-       make -f buildScript.mk linux_tb_debug
-
-=======================================
-==      All Targets - Mega Only      ==
-=======================================
-
-- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite
-  Examples) for Arduino ATMega 2560 with Ethernet Shield:
-
-       make -f buildScript.mk arduinomega
-
-- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples)
-  for Arduino ATMega 2560 with Ethernet Shield:
-
-       make -f buildScript.mk arduinomega_debug
-
-- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite
-  Examples) for Arduino ATMega 2560 with WiFi Shield:
-
-       make -f buildScript.mk arduinomega_wifi
-
-- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples)
-  for Arduino ATMega 2560 with WiFi Shield:
-
-       make -f buildScript.mk arduinomega_wifi_debug
-
-=======================================
-==      All Targets - Due Only      ==
-=======================================
-
-- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite
-  Examples) for Arduino Due with Ethernet Shield:
-
-       make -f buildScript.mk arduinodue_all
-
-- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples)
-  Examples) for Arduino Due with Ethernet Shield:
-
-       make -f buildScript.mk arduinodue_all_debug
-
-- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite
-  Examples) for Arduino Due with WiFi Shield:
-
-       make -f buildScript.mk arduinodue_wifi
-
-- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples)
-  for Arduino Due with WiFi Shield:
-
-       make -f buildScript.mk arduinodue_wifi_debug
-
-=======================================
-==         Clean All Targets         ==
-=======================================
-
-- Clean All:
-
-       make -f buildScript.mk clean
-
index e1ad14e..9f96e77 100644 (file)
@@ -1,29 +1,74 @@
+#******************************************************************
+#
+# 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
 #
 ##
 
+import os
+
 Import('env')
 
 target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
+if target_os not in ['arduino', 'darwin', 'ios', 'android']:
+       env.AppendUnique(LIBS=['rt'])
 
 # Build libcoap
-SConscript('csdk/libcoap/SConscript')
+SConscript('csdk/connectivity/lib/libcoap-4.1.1/SConscript')
+
+# Build connectivity
+SConscript('csdk/connectivity/SConscript')
 
 # Build liboctbstack
 SConscript('csdk/SConscript')
 
-if target_os == 'android':
-       SConscript('android/SConscript')
-
-if target_os != 'arduino':
+if target_os not in ['arduino','darwin']:
        # Build liboc_logger
        SConscript('oc_logger/SConscript')
 
        # Build liboc
        SConscript('src/SConscript')
 
+if target_os not in ['arduino','darwin', 'android']:
        # Build examples
        SConscript('examples/SConscript')
-else:
-       SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
\ No newline at end of file
+
+if target_os == 'linux':
+       # Build C Samples
+       SConscript('csdk/stack/samples/linux/SimpleClientServer/SConscript')
+
+       # Build secure samples
+       SConscript('csdk/stack/samples/linux/secure/SConscript')
+
+       # Build C/C++ unit tests
+       SConscript('unit_tests.scons')
+
+elif target_os == 'darwin':
+       # Build linux samples for now.
+       SConscript('csdk/stack/samples/linux/SimpleClientServer/SConscript')
+
+       # Build C stack's unit tests.
+       SConscript('unit_tests.scons')
+
+elif target_os == 'arduino':
+       SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
index a43d578..46850cd 100644 (file)
@@ -82,23 +82,54 @@ namespace std {
                return ret;
        }
 
-       std::string to_string(int t) {
-               std::ostringstream os;
-                       os << t;
-               return os.str();
+       #define TO_STRING(_t) { \
+               std::ostringstream os; \
+               os << _t; \
+               return os.str(); \
+       } \
+
+       std::string to_string(int val)
+       {
+               TO_STRING(val)
+       }
+
+       std::string to_string(long val)
+       {
+               TO_STRING(val)
+       }
+
+       std::string to_string(long long val)
+       {
+               TO_STRING(val)
+       }
+
+       std::string to_string(unsigned val)
+       {
+               TO_STRING(val)
+       }
+
+       std::string to_string(unsigned long val)
+       {
+               TO_STRING(val)
+       }
+
+       std::string to_string(unsigned long long val)
+       {
+               TO_STRING(val)
        }
 
-       std::string to_string(double t) {
-               std::ostringstream os;
-                       os << t;
-               return os.str();
+       std::string to_string(float val)
+       {
+               TO_STRING(val)
        }
 
-       std::string to_string(uint32_t t)
+       std::string to_string(double val)
        {
-               std::ostringstream os;
-                       os << t;
-               return os.str();
+               TO_STRING(val)
        }
 
+       std::string to_string(long double val)
+       {
+               TO_STRING(val)
+       }
 } // std
index 35e3616..d7bce9f 100644 (file)
@@ -3,11 +3,7 @@
 ##
 Import('env')
 
-# Add third party libraries
-lib_env = env.Clone()
-#SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
-
-compatibilitylib_env = lib_env.Clone()
+compatibilitylib_env = env.Clone()
 ######################################################################
 # Build flags
 ######################################################################
@@ -17,8 +13,7 @@ target_os = env.get('TARGET_OS')
 
 if target_os == 'android':
        compatibilitylib_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       #oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-       compatibilitylib_env.AppendUnique(LIBS = ['gnustl_static'])
+       compatibilitylib_env.AppendUnique(LIBS = ['gnustl_shared'])
 
 ######################################################################
 # Source files and Targets
index d9234a0..72b2ca5 100644 (file)
@@ -33,10 +33,8 @@ Please refer to the readme file at <oic-resource>/README for more information.
 
 TB Stack:
        release:
-               <oic-resource>/csdk/libcoap/linux/release/libcoap.a
                <oic-resource>/csdk/linux/release/liboctbstack.a
        debug:
-               <oic-resource>/csdk/libcoap/linux/debug/libcoap.a
                <oic-resource>/csdk/linux/debug/liboctbstack.a
 
 TB Unit Tests:
@@ -95,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     ====
@@ -104,10 +102,8 @@ UB OCICUC:
 TB Stack:
        Ethernet Shield:
                release:
-                       <oic-resource>/csdk/libcoap/arduinomega/ethernet_shield/release/libcoap.a
                        <oic-resource>/csdk/arduinomega/ethernet_shield/release/liboctbstack.a
                debug:
-                       <oic-resource>/csdk/libcoap/arduinomega/ethernet_shield/debug/libcoap.a
                        <oic-resource>/csdk/arduinomega/ethernet_shield/debug/liboctbstack.a
 
 TB Examples:
@@ -124,10 +120,8 @@ TB Examples:
 TB Stack:
        WiFi Shield:
                release:
-                       <oic-resource>/csdk/libcoap/arduinomega/wifi_shield/release/libcoap.a
                        <oic-resource>/csdk/arduinomega/wifi_shield/release/liboctbstack.a
                debug:
-                       <oic-resource>/csdk/libcoap/arduinomega/wifi_shield/debug/libcoap.a
                        <oic-resource>/csdk/arduinomega/wifi_shield/debug/liboctbstack.a
 
 TB Examples:
@@ -144,10 +138,8 @@ TB Examples:
 TB Stack:
        Ethernet Shield:
                release:
-                       <oic-resource>/csdk/libcoap/arduinodue/ethernet_shield/release/libcoap.a
                        <oic-resource>/csdk/arduinodue/ethernet_shield/release/liboctbstack.a
                debug:
-                       <oic-resource>/csdk/libcoap/arduinodue/ethernet_shield/debug/libcoap.a
                        <oic-resource>/csdk/arduinodue/ethernet_shield/debug/liboctbstack.a
 
 TB Examples:
@@ -164,10 +156,8 @@ TB Examples:
 TB Stack:
        WiFi Shield:
                release:
-                       <oic-resource>/csdk/libcoap/arduinodue/wifi_shield/release/libcoap.a
                        <oic-resource>/csdk/arduinodue/wifi_shield/release/liboctbstack.a
                debug:
-                       <oic-resource>/csdk/libcoap/arduinodue/wifi_shield/debug/libcoap.a
                        <oic-resource>/csdk/arduinodue/wifi_shield/debug/liboctbstack.a
 
 TB Examples:
@@ -189,3 +179,4 @@ TB Examples:
 
 
 
+
diff --git a/resource/buildScript.mk b/resource/buildScript.mk
deleted file mode 100644 (file)
index 64afad1..0000000
+++ /dev/null
@@ -1,531 +0,0 @@
-# //******************************************************************
-# //
-# // 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 makefile build-script requires the following for each platform:
-# Note:  Refer to READMEs at "<oic-resource>/" & "<oic-resource>/csdk/" for
-#        more information.
-#
-# Linux:
-#    OS: Ubuntu 12.04
-#    GCC Version: 4.6.1
-#
-# Arduino ATMega 2560:
-#    Framework Version: Arduino 1.0.5
-#    AVR-GCC Version: 4.5.3
-#
-# Arduino Due:
-#    Framework Version: Arduino 1.5.7
-#    AVR-GCC Version: 4.8.3
-
-# Header Description:
-# ====NAME/TITLE - BUILD TYPE - OUT DIRECTORY====
-
-###############################################################################
-####       TB Stack, TB Unit Tests, TB Examples, UB Stack,                 ####
-####       & UB Examples - Linux & Arduino Mega                            ####
-#### Note: Default "all" target builds Release only "all" of Linux &       ####
-####       Release only "all" of Arduino Mega with Ethernet Shield.        ####
-###############################################################################
-
-all: all_release
-
-all_all: all_release all_debug
-
-dev: linux_ub_dev arduinomega_all_dev
-
-all_release: linux_release arduinomega_release
-
-all_debug: linux_debug arduinomega_debug
-
-###############################################################################
-####       TB Stack, TB Unit Tests, TB Examples, UB Stack,                 ####
-####       & UB Examples - Linux & Arduino Due                             ####
-#### Note: Default "all" target builds Release only "all" of Linux &       ####
-####       Release only "all" of Arduino Due with Ethernet Shield.         ####
-###############################################################################
-
-complement: complement_release
-
-complement_all: complement_release complement_debug
-
-complement_dev: linux_ub_dev arduinodue_all_dev
-
-complement_release: linux_release arduinodue_release
-
-complement_debug: linux_debug arduinodue_debug
-
-###############################################################################
-####       TB Stack, TB Unit Tests, TB Examples, UB Stack, UB Examples,    ####
-####       & OCICUC - Linux, Arduino Mega and Arduino Due                  ####
-#### Note: The "all_dev" target is intended for use on the build           ####
-####       server(s). This includes "all" targets for Release & Debug for  ####
-####       Linux, "all" Release & Debug for Arduino Mega with Ethernet     ####
-####       Shield & WiFi Shield, and "all" Release & Debug for Arduino     ####
-####       Due with Ethernet Shield & Wifi Shield.                         ####
-###############################################################################
-
-all_dev: linux_ub_dev arduinomega_all_dev arduinodue_all_dev
-
-###############################################################################
-## TB Stack, TB Unit Tests, TB Examples, UB Stack, & UB Examples - Linux Only #
-###############################################################################
-
-linux: linux_tb_release
-
-linux_all: linux_release linux_debug
-
-linux_release: linux_tb_release linux_ub_release
-
-linux_debug: linux_tb_debug linux_ub_debug
-
-###############################################################################
-####      TB Stack, TB Unit Tests, & TB Examples - Linux Only              ####
-###############################################################################
-
-linux_tb: linux_tb_release
-
-linux_tb_all: linux_tb_release linux_tb_debug
-
-linux_tb_release: linux_tb_stack_release linux_tb_unittests_release linux_tb_examples_release
-
-linux_tb_debug: linux_tb_stack_debug linux_tb_unittests_debug linux_tb_examples_debug
-
-###############################################################################
-####      UB Stack, TB Stack, & UB Examples - Linux Only                   ####
-###############################################################################
-
-linux_ub: linux_ub_release
-
-linux_ub_all: linux_ub_release linux_ub_debug
-
-linux_ub_release: linux_tb_stack_release linux_ub_unittests_release linux_ub_stack_release linux_ub_examples_release
-
-linux_ub_debug: linux_tb_stack_debug linux_ub_unittests_debug linux_ub_stack_debug linux_ub_examples_debug
-
-###############################################################################
-####      TB Stack - Linux Only                                            ####
-###############################################################################
-
-linux_tb_stack: linux_tb_stack_release
-
-linux_tb_stack_all: linux_tb_stack_release linux_tb_stack_debug
-
-linux_tb_stack_debug:
-       @echo "=====BUILD LIBCOAP FOR LINUX - DEBUG - <oic-resource>/csdk/libcoap/linux/debug/====="
-       $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=linux"
-       @echo "=====BUILD TB STACK FOR LINUX - DEBUG - <oic-resource>/csdk/linux/debug/====="
-       $(MAKE) -C csdk/ "buildScript_all" "BUILD=debug" "PLATFORM=linux"
-
-linux_tb_stack_release:
-       @echo "=====BUILD LIBCOAP FOR LINUX - RELEASE - <oic-resource>/csdk/libcoap/linux/release/====="
-       $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=linux"
-       @echo "=====BUILD TB STACK FOR LINUX - RELEASE - <oic-resource>/csdk/linux/release/====="
-       $(MAKE) -C csdk/ "buildScript_all" "BUILD=release" "PLATFORM=linux"
-
-###############################################################################
-####      TB Unit Tests - Linux Only                                       ####
-###############################################################################
-
-linux_tb_unittests: linux_tb_unittests_release
-
-linux_tb_unittests_all: linux_tb_unittests_release linux_tb_unittests_debug
-
-linux_tb_unittests_release: linux_tb_stack_release
-       @echo "=====BUILD TB UNITTESTS FOR LINUX - RELEASE - <oic-resource>/csdk/stack/test/linux/release/====="
-       $(MAKE) -C csdk/stack/test/linux/ "BUILD=release"
-
-linux_tb_unittests_debug: linux_tb_stack_debug
-       @echo "=====BUILD TB UNITTESTS FOR LINUX - DEBUG - <oic-resource>/csdk/stack/test/linux/debug/====="
-       $(MAKE) -C csdk/stack/test/linux/ "BUILD=debug"
-
-###############################################################################
-####      TB Examples - Linux Only                                         ####
-###############################################################################
-
-linux_tb_examples: linux_tb_stack_release linux_tb_examples_release
-
-linux_tb_examples_all: linux_tb_stack_release linux_tb_examples_debug
-
-linux_tb_examples_release: linux_tb_stack_release
-       @echo "=====BUILD TB SAMPLE APPS FOR LINUX - RELEASE - <oic-resource>/csdk/stack/samples/linux/SimpleClientServer/release/====="
-       $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "PLATFORM=linux" "BUILD=release"
-       $(MAKE) -C csdk/stack/samples/linux/secure "PLATFORM=linux" "BUILD=release"
-
-linux_tb_examples_debug: linux_tb_stack_debug
-       @echo "=====BUILD TB SAMPLE APPS FOR LINUX - DEBUG - <oic-resource>/csdk/stack/samples/linux/SimpleClientServer/debug/====="
-       $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "PLATFORM=linux" "BUILD=debug"
-       $(MAKE) -C csdk/stack/samples/linux/secure "PLATFORM=linux" "BUILD=debug"
-
-###############################################################################
-####      UB Stack (& TB Stack as prerequisite) - Linux Only               ####
-###############################################################################
-
-linux_ub_stack: linux_ub_stack_release
-
-linux_ub_stack_all: linux_ub_stack_release linux_ub_stack_debug
-
-linux_ub_stack_release: linux_tb_stack_release
-       @echo "=====BUILD UB STACK FOR LINUX - RELEASE - <oic-resource>/release/====="
-       $(MAKE) -C ./ "buildScript_all" "BUILD=release"
-
-linux_ub_stack_debug: linux_tb_stack_debug
-       @echo "=====BUILD UB STACK FOR LINUX - DEBUG - <oic-resource>/debug/====="
-       $(MAKE) -C ./ "buildScript_all" "BUILD=debug"
-
-###############################################################################
-####      UB Unit Tests (& TB Stack as prequisite) - Linux Only            ####
-###############################################################################
-
-linux_ub_unittests: linux_ub_unittests_release
-
-linux_ub_unittests_all: linux_ub_unittests_release linux_ub_unittests_debug
-
-linux_ub_unittests_release: linux_ub_stack_release
-       @echo "=====BUILD UB UNIT TESTS FOR LINUX - RELEASE - <oic-resource>/unittests/release====="
-       $(MAKE) -C unittests/ "BUILD=release"
-
-linux_ub_unittests_debug: linux_ub_stack_debug
-       @echo "=====BUILD UB UNIT TESTS FOR LINUX - DEBUG - <oic-resource>/unittests/debug====="
-       $(MAKE) -C unittests/ "BUILD=debug"
-
-###############################################################################
-####      UB Examples (& UB Stack as prerequisite) - Linux Only            ####
-###############################################################################
-
-linux_ub_examples: linux_ub_examples_release
-
-linux_ub_examples_all: linux_ub_examples_release linux_ub_examples_debug
-
-linux_ub_examples_release: linux_ub_stack_release
-       @echo "=====BUILD UB SAMPLE APPS FOR LINUX - RELEASE - <oic-resource>/examples/release/====="
-       $(MAKE) -C examples/ "buildScript_all" "BUILD=release"
-
-linux_ub_examples_debug: linux_ub_stack_debug
-       @echo "=====BUILD UB SAMPLE APPS FOR LINUX - DEBUG - <oic-resource>/examples/debug/====="
-       $(MAKE) -C examples/ "buildScript_all" "BUILD=debug"
-
-###############################################################################
-####      TB Stack, TB Unit Tests, TB Examples, UB Stack, UB Examples,     ####
-####      UB Unit Tests, & OCICUC - Linux Only                             ####
-###############################################################################
-
-linux_ub_dev: linux_ub_stack_all linux_ub_unittests_all linux_ub_examples_all linux_tb_examples_all
-       @echo "=====BUILD UB OCICUC - <oic-resource>/examples/ocicuc/====="
-       $(MAKE) -C examples/ocicuc/
-
-###############################################################################
-#TB Stack, TB Unit Tests, & TB Examples - Arduino Mega Only - Ethernet & WiFi #
-###############################################################################
-
-arduinomega: arduinomega_release
-
-arduinomega_all: arduinomega_release arduinomega_debug
-
-arduinomega_all_dev: arduinomega_release_dev arduinomega_debug_dev
-
-arduinomega_release: arduinomega_ethernet_release
-
-arduinomega_debug: arduinomega_ethernet_debug
-
-arduinomega_release_dev: arduinomega_ethernet_release arduinomega_wifi_release
-
-arduinomega_debug_dev: arduinomega_ethernet_debug arduinomega_wifi_debug
-
-###############################################################################
-## TB Stack, TB Unit Tests, & TB Examples - Arduino Mega Only - Ethernet Only #
-###############################################################################
-
-arduinomega_ethernet: arduinomega_ethernet_release
-
-arduinomega_ethernet_all: arduinomega_ethernet_release arduinomega_ethernet_debug
-
-arduinomega_ethernet_release: arduinomega_stack_ethernet_release arduinomega_samples_ethernet_release
-
-arduinomega_ethernet_debug: arduinomega_stack_ethernet_debug arduinomega_samples_ethernet_debug
-
-###############################################################################
-## TB Stack, TB Unit Tests, & TB Examples - Arduino Mega Only - Ethernet Only #
-###############################################################################
-
-arduinomega_wifi: arduinomega_wifi_release
-
-arduinomega_wifi_all: arduinomega_wifi_release arduinomega_wifi_debug
-
-arduinomega_wifi_release: arduinomega_stack_wifi_release arduinomega_samples_wifi_release
-
-arduinomega_wifi_debug: arduinomega_stack_wifi_debug arduinomega_samples_wifi_debug
-
-###############################################################################
-####             TB Stack - Arduino Mega Only - Ethernet Only              ####
-###############################################################################
-
-arduinomega_stack_ethernet: arduinomega_stack_ethernet_release
-
-arduinomega_stack_ethernet_all: arduinomega_stack_ethernet_release arduinomega_stack_ethernet_debug
-
-arduinomega_stack_ethernet_release:
-       @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - RELEASE - ETHERNET SHIELD======"
-       @echo "=====BUILD LIBCOAP - RELEASE - <oic-resource>/csdk/libcoap/arduinomega/ethernet_shield/release/====="
-       $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=0"
-       @echo "=====BUILD TB STACK - RELEASE - <oic-resource>/csdk/arduinomega/ethernet_shield/release/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=0"
-
-arduinomega_stack_ethernet_debug:
-       @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - DEBUG - ETHERNET SHIELD======"
-       @echo "=====BUILD LIBCOAP - DEBUG - <oic-resource>/csdk/libcoap/arduinomega/ethernet_shield/debug/====="
-       $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=0"
-       @echo "=====BUILD TB STACK - DEBUG - <oic-resource>/csdk/arduinomega/ethernet_shield/debug/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=0"
-
-###############################################################################
-####             TB Stack - Arduino Mega Only - WiFi Only                  ####
-###############################################################################
-
-arduinomega_stack_wifi: arduinomega_stack_wifi_release
-
-arduinomega_stack_wifi_all: arduinomega_stack_wifi_release arduinomega_stack_wifi_debug
-
-arduinomega_stack_wifi_release:
-       @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - RELEASE - WiFi SHIELD======"
-       @echo "=====BUILD LIBCOAP - RELEASE - <oic-resource>/csdk/libcoap/arduinomega/wifi_shield/release/====="
-       $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=1"
-       @echo "=====BUILD TB STACK - RELEASE - <oic-resource>/csdk/arduinomega/wifi_shield/release/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=1"
-
-arduinomega_stack_wifi_debug:
-       @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - DEBUG - WiFi SHIELD======"
-       @echo "=====BUILD LIBCOAP - DEBUG - <oic-resource>/csdk/libcoap/arduinomega/wifi_shield/debug/====="
-       $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=1"
-       @echo "=====BUILD TB STACK - DEBUG - <oic-resource>/csdk/arduinomega/wifi_shield/debug/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=1"
-
-###############################################################################
-####          TB Examples - Arduino Mega Only - Ethernet Only              ####
-###############################################################################
-
-arduinomega_samples_ethernet: arduinomega_samples_ethernet_release
-
-arduinomega_samples_ethernet_all: arduinomega_samples_ethernet_release arduinomega_samples_ethernet_debug
-
-arduinomega_samples_ethernet_release: arduinomega_stack_ethernet_release
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - RELEASE - ETHERNET SHIELD====="
-       @echo "=====BUILD OCSERVER - RELEASE - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/ethernet_shield/release/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=0"
-
-arduinomega_samples_ethernet_debug: arduinomega_stack_ethernet_debug
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - DEBUG - ETHERNET SHIELD====="
-       @echo "=====BUILD OCSERVER - DEBUG - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/ethernet_shield/debug/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=0"
-
-###############################################################################
-####             TB Examples - Arduino Mega Only - WiFi Only               ####
-###############################################################################
-
-arduinomega_samples_wifi: arduinomega_samples_wifi_release
-
-arduinomega_samples_wifi_all: arduinomega_samples_wifi_release arduinomega_samples_wifi_debug
-
-arduinomega_samples_wifi_release: arduinomega_stack_wifi_release
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - RELEASE - WIFI SHIELD====="
-       @echo "=====BUILD OCSERVER - RELEASE - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/wifi_shield/release/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=1"
-
-arduinomega_samples_wifi_debug: arduinomega_stack_wifi_debug
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - DEBUG - WIFI SHIELD====="
-       @echo "=====BUILD OCSERVER - DEBUG - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/wifi_shield/debug/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=1"
-
-
-###############################################################################
-#TB Stack, TB Unit Tests, & TB Examples - Arduino Due Only - Ethernet & WiFi ##
-###############################################################################
-
-arduinodue: arduinodue_release
-
-arduinodue_all: arduinodue_release arduinodue_debug
-
-arduinodue_all_dev: arduinodue_release_dev arduinodue_debug_dev
-
-arduinodue_release: arduinodue_ethernet_release
-
-arduinodue_debug: arduinodue_ethernet_debug
-
-arduinodue_release_dev: arduinodue_ethernet_release arduinodue_wifi_release
-
-arduinodue_debug_dev: arduinodue_ethernet_debug arduinodue_wifi_debug
-
-###############################################################################
-## TB Stack, TB Unit Tests, & TB Examples - Arduino Due Only - Ethernet Only ##
-###############################################################################
-
-arduinodue_ethernet: arduinodue_ethernet_release
-
-arduinodue_ethernet_all: arduinodue_ethernet_release arduinodue_ethernet_debug
-
-arduinodue_ethernet_release: arduinodue_stack_ethernet_release arduinodue_samples_ethernet_release
-
-arduinodue_ethernet_debug: arduinodue_stack_ethernet_debug arduinodue_samples_ethernet_debug
-
-###############################################################################
-## TB Stack, TB Unit Tests, & TB Examples - Arduino Due Only - Ethernet Only ##
-###############################################################################
-
-arduinodue_wifi: arduinodue_wifi_release
-
-arduinodue_wifi_all: arduinodue_wifi_release arduinodue_wifi_debug
-
-arduinodue_wifi_release: arduinodue_stack_wifi_release arduinodue_samples_wifi_release
-
-arduinodue_wifi_debug: arduinodue_stack_wifi_debug arduinodue_samples_wifi_debug
-
-###############################################################################
-####             TB Stack - Arduino Due Only - Ethernet Only               ####
-###############################################################################
-
-arduinodue_stack_ethernet: arduinodue_stack_ethernet_release
-
-arduinodue_stack_ethernet_all: arduinodue_stack_ethernet_release arduinodue_stack_ethernet_debug
-
-arduinodue_stack_ethernet_release:
-       @echo "=====BUILD C STACK FOR ARDUINO DUE - RELEASE - ETHERNET SHIELD======"
-       @echo "=====BUILD LIBCOAP - RELEASE - <oic-resource>/csdk/libcoap/arduinodue/ethernet_shield/release/====="
-       $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=0"
-       @echo "=====BUILD TB STACK - RELEASE - <oic-resource>/csdk/arduinodue/ethernet_shield/release/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=0"
-
-arduinodue_stack_ethernet_debug:
-       @echo "=====BUILD C STACK FOR ARDUINO DUE - DEBUG - ETHERNET SHIELD======"
-       @echo "=====BUILD LIBCOAP - DEBUG - <oic-resource>/csdk/libcoap/arduinodue/ethernet_shield/debug/====="
-       $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=0"
-       @echo "=====BUILD TB STACK - DEBUG - <oic-resource>/csdk/arduinodue/ethernet_shield/debug/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=0"
-
-###############################################################################
-####             TB Stack - Arduino Due Only - WiFi Only                   ####
-###############################################################################
-
-arduinodue_stack_wifi: arduinodue_stack_wifi_release
-
-arduinodue_stack_wifi_all: arduinodue_stack_wifi_release arduinodue_stack_wifi_debug
-
-arduinodue_stack_wifi_release:
-       @echo "=====BUILD C STACK FOR ARDUINO DUE - RELEASE - WiFi SHIELD======"
-       @echo "=====BUILD LIBCOAP - RELEASE - <oic-resource>/csdk/libcoap/arduinodue/wifi_shield/release/====="
-       $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=1"
-       @echo "=====BUILD TB STACK - RELEASE - <oic-resource>/csdk/arduinodue/wifi_shield/release/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=1"
-
-arduinodue_stack_wifi_debug:
-       @echo "=====BUILD C STACK FOR ARDUINO DUE - DEBUG - WiFi SHIELD======"
-       @echo "=====BUILD LIBCOAP - DEBUG - <oic-resource>/csdk/libcoap/arduinodue/wifi_shield/debug/====="
-       $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=1"
-       @echo "=====BUILD TB STACK - DEBUG - <oic-resource>/csdk/arduinodue/wifi_shield/debug/====="
-       $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=1"
-
-###############################################################################
-####          TB Examples - Arduino Due Only - Ethernet Only               ####
-###############################################################################
-
-arduinodue_samples_ethernet: arduinodue_samples_ethernet_release
-
-arduinodue_samples_ethernet_all: arduinodue_samples_ethernet_release arduinodue_samples_ethernet_debug
-
-arduinodue_samples_ethernet_release: arduinodue_stack_ethernet_release
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - RELEASE - ETHERNET SHIELD====="
-       @echo "=====BUILD OCSERVER - RELEASE - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/ethernet_shield/release/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=0"
-
-arduinodue_samples_ethernet_debug: arduinodue_stack_ethernet_debug
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - DEBUG - ETHERNET SHIELD====="
-       @echo "=====BUILD OCSERVER - DEBUG - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/ethernet_shield/debug/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=0"
-
-###############################################################################
-####             TB Examples - Arduino Due Only - WiFi Only                ####
-###############################################################################
-
-arduinodue_samples_wifi: arduinodue_samples_wifi_release
-
-arduinodue_samples_wifi_all: arduinodue_samples_wifi_release arduinodue_samples_wifi_debug
-
-arduinodue_samples_wifi_release: arduinodue_stack_wifi_release
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - RELEASE - WIFI SHIELD====="
-       @echo "=====BUILD OCSERVER - RELEASE - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/wifi_shield/release/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=1"
-
-arduinodue_samples_wifi_debug: arduinodue_stack_wifi_debug
-       @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - DEBUG - WIFI SHIELD====="
-       @echo "=====BUILD OCSERVER - DEBUG - <oic-resource>/csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/wifi_shield/debug/====="
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=1"
-
-###############################################################################
-####                Clean All - Linux Only - Ethernet Only                 ####
-###############################################################################
-
-linux_clean:
-       -rm -rf -C csdk/libcoap/linux
-       -rm -rf -C csdk/linux
-       $(MAKE) -C csdk/stack/test/linux "clean"
-       $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "clean"
-       $(MAKE) -C csdk/stack/samples/linux/secure "clean"
-       $(MAKE) -C . "clean"
-
-###############################################################################
-####            Clean All - Arduino Mega Only - Ethernet & WiFi            ####
-###############################################################################
-
-arduinomega_clean:
-       -rm -rf csdk/libcoap/arduinomega
-       -rm -rf csdk/arduinomega
-       -rm -rf csdk/stack/test/arduino/arduinomega
-       -rm -rf csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega
-
-###############################################################################
-####            Clean All - Arduino Due Only - Ethernet & WiFi             ####
-###############################################################################
-
-arduinodue_clean:
-       -rm -rf csdk/libcoap/arduinodue
-       -rm -rf csdk/arduinodue
-       -rm -rf csdk/stack/test/arduino/arduinodue
-       -rm -rf csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue
-
-
-###############################################################################
-####  Clean All - Linux, Arduino Mega & Arduino Due - Ethernet & WiFi      ####
-###############################################################################
-clean:
-       $(MAKE) -C csdk "clean" "deepclean"
-       $(MAKE) -C csdk/stack/test/linux "clean"
-       $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "clean"
-       $(MAKE) -C csdk/stack/samples/linux/secure "clean"
-       $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "clean"
-       $(MAKE) -C . "clean"
-       $(MAKE) -C unittests/ "clean"
-       $(MAKE) -C examples/ "clean"
-       $(MAKE) -C oc_logger/ "clean"
-
-###############################################################################
-### You must specify arduinomega or arduinodue when using an arduino target.###
-###############################################################################
-arduino:
-       $(error "You must specify "arduinomega" or "arduinodue" when trying to\
-       build arduino targets.")
diff --git a/resource/csdk/README b/resource/csdk/README
deleted file mode 100644 (file)
index fb92438..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
--------------------------------------------------------------------------------
-  NOTICE - Transition to SCONS
--------------------------------------------------------------------------------
-
-The IoTivity build system is transitioning to SCONS. Although the 
-makefiles are still available (until v1.0) and some developers are 
-still using them, they are currently no longer supported. To learn more 
-about building using SCONS see Readme.scons.txt in the repository root 
-directory. The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
--------------------------------------------------------------------------------
-**Linux**
--------------------------------------------------------------------------------
-To make octbstack.a in release mode:
-
-       make
-
-To make octbstack.a in debug mode:
-
-       make BUILD=debug
-
--------------------------------------------------------------------------------
-**Arduino**
--------------------------------------------------------------------------------
-Touch (i.e. create) file named "local.properties" at this directory level with
-the following definition(s):
-
-       ARDUINO_DIR = <PATH_TO_ARDUINO_INSTALL_DIR>/arduino-1.0.5
-    ARDUINO_TOOLS_DIR = <PATH_TO_ARDUINO_TOOLS> (location of avr-g++ and other avr tools)
-
-To make octbstack.a in release mode:
-       make PLATFORM=arduinomega (For Arduino Due, use <arduinodue>)
-
-To make octbstack.a in debug mode:
-       make PLATFORM=arduinomega BUILD=debug (For Arduino Due, use <arduinodue>)
-
-To make octbstack.a with Arduino WiFi Shield support:
-       make PLATFORM=arduinomega ARDUINOWIFI=1 (For Arduino Due, use <arduinodue>)
-
-Dependencies:
-    1) Patch the Wiznet Ethernet library with the patch available at :
-    oic-utilities/tb/arduino_linux_ethernet_socket_cpp.patch
-    2) Arduino builds are dependent on latest Time library. Download it from here:
-    http://www.pjrc.com/teensy/td_libs_Time.html
-    3) Arduino Due has been tested with Arduino 1.5.7 framework.
-    4) For Arduino Due, binary tools are located in:
-       /hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin
-    5) For Arduino WiFi, update the WiFi shield with the firmware patches provided
-       by Intel.
--------------------------------------------------------------------------------
-**Clean-Up**
--------------------------------------------------------------------------------
-To clean only stack modules:
-
-       make clean
-
-To clean stack modules and libcoap (i.e. networking) modules & its
-dependencies:
-
-       make deepclean
-
index 65d02a1..63e6462 100644 (file)
@@ -1,7 +1,26 @@
+#******************************************************************
+#
+# 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
 ##
-
 Import('env')
 
 lib_env = env.Clone()
@@ -21,15 +40,18 @@ if target_os == 'arduino':
 ######################################################################
 liboctbstack_env.PrependUnique(CPPPATH = [
                '../../extlibs/cjson/',
-               'ocsocket/include',
+               '../../extlibs/timer/',
                'logger/include',
                'ocrandom/include',
                'ocmalloc/include',
-               'libcoap',
-               'occoap/include',
                'stack/include',
                'stack/include/internal',
-               '../oc_logger/include'
+               '../oc_logger/include',
+               'connectivity/lib/libcoap-4.1.1',
+               'connectivity/inc',
+               'connectivity/api',
+               'security/include',
+               'security/include/internal',
                ])
 
 if target_os not in ['arduino', 'windows', 'winrt']:
@@ -39,21 +61,33 @@ if target_os not in ['arduino', 'windows', 'winrt']:
 if target_os not in ['windows', 'winrt']:
        liboctbstack_env.AppendUnique(CFLAGS = ['-Wall'])
 
-if target_os == 'android':
-       liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-       liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
+liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+if target_os in ['android', 'linux', 'tizen']:
+       liboctbstack_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
+
+if target_os == 'tizen':
+    liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
+
+if target_os not in ['android', 'arduino', 'windows', 'winrt']:
+       liboctbstack_env.AppendUnique(LIBS = ['pthread'])
 
 if target_os == 'arduino':
        liboctbstack_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-else:
+elif target_os not in ['darwin','ios']:
        liboctbstack_env.AppendUnique(CFLAGS = ['-fPIC'])
-
 if target_os in ['darwin', 'ios']:
+       env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
        liboctbstack_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
        liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-       liboctbstack_env.AppendUnique(LIBS = ['coap'])
+if target_os not in ['arduino']:
+       liboctbstack_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
+
+if env.get('SECURED') == '1':
+       liboctbstack_env.AppendUnique(LIBS = ['tinydtls'])
 
-if not env.get('RELEASE'):
+if env.get('LOGGING'):
        liboctbstack_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 ######################################################################
@@ -62,18 +96,20 @@ if not env.get('RELEASE'):
 OCTBSTACK_SRC = 'stack/src/'
 liboctbstack_src = [
        '../../extlibs/cjson/cJSON.c',
-       'occoap/src/occoap.c',
-       'occoap/src/occoaphelper.c',
+       '../../extlibs/timer/timer.c',
        OCTBSTACK_SRC + 'ocstack.c',
        OCTBSTACK_SRC + 'occlientcb.c',
        OCTBSTACK_SRC + 'ocresource.c',
        OCTBSTACK_SRC + 'ocobserve.c',
-    OCTBSTACK_SRC + 'ocserverrequest.c',
+       OCTBSTACK_SRC + 'ocserverrequest.c',
        OCTBSTACK_SRC + 'occollection.c',
-       OCTBSTACK_SRC + 'ocsecurity.c',
-    OCTBSTACK_SRC + 'oicgroup.c'
+       OCTBSTACK_SRC + 'oicgroup.c',
+       'security/src/ocsecurity.c',
+       'logger/src/logger.c',
+       'ocrandom/src/ocrandom.c',
+       'ocmalloc/src/ocmalloc.c'
        ]
-if target_os == 'arduino':
+if target_os in ['arduino','darwin','ios'] :
        static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
        liboctbstack_env.InstallTarget(static_liboctbstack, 'liboctbstack')
 else:
@@ -81,4 +117,3 @@ else:
        shared_liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
        liboctbstack_env.InstallTarget([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
 
-
index 2b76cee..58b46e8 100644 (file)
@@ -1,22 +1,22 @@
 
 #Source directories
-SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-SDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI
-SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet
-SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility
-SDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi
-SDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/utility
+SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+SDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet/src
+SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility
+SDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src
+SDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility
 SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
 SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE):$(SDIR_ARD_SPI):$(SDIR_ARD_TIME)
 
 #include directories
-INCD_ARD_CORE = -I$(ARDUINO_DIR)/hardware/arduino/cores/arduino
-INCD_ARD_VARIANT = -I$(ARDUINO_DIR)/hardware/arduino/variants/mega
-INCD_ARD_SPI = -I$(ARDUINO_DIR)/libraries/SPI
-INCD_ARD_ETH = -I$(ARDUINO_DIR)/libraries/Ethernet
-INCD_ARD_ETH_UTIL = -I$(ARDUINO_DIR)/libraries/Ethernet/utility
-INCD_ARD_WIFI = -I$(ARDUINO_DIR)/libraries/WiFi
-INCD_ARD_WIFI_UTIL = -I$(ARDUINO_DIR)/libraries/WiFi/utility
+INCD_ARD_CORE = -I$(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+INCD_ARD_VARIANT = -I$(ARDUINO_DIR)/hardware/arduino/avr/variants/mega
+INCD_ARD_SPI = -I$(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+INCD_ARD_ETH = -I$(ARDUINO_DIR)/libraries/Ethernet/src
+INCD_ARD_ETH_UTIL = -I$(ARDUINO_DIR)/libraries/Ethernet/src/utility
+INCD_ARD_WIFI = -I$(ARDUINO_DIR)/libraries/WiFi/src
+INCD_ARD_WIFI_UTIL = -I$(ARDUINO_DIR)/libraries/WiFi/src/utility
 INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time/Time
 
 INC_DIR_PLATFORM = $(INCD_ARD_CORE) $(INCD_ARD_VARIANT) $(INCD_ARD_SPI) $(INCD_ARD_TIME)
@@ -31,11 +31,12 @@ CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
 AR=$(ARDUINO_TOOLS_DIR)/avr-ar
 RANLIB=$(ARDUINO_TOOLS_DIR)/avr-ranlib
 AVR_OBJCOPY=$(ARDUINO_TOOLS_DIR)/avr-objcopy
-AVR_PROGRAMMER=$(ARDUINO_TOOLS_DIR)/../../avrdude
+AVR_PROGRAMMER=$(ARDUINO_TOOLS_DIR)/avrdude
 
 #Needed object files
-CORE_COBJ = WInterrupts.o wiring.o wiring_digital.o
-CORE_CPPOBJ = main.o Stream.o WMath.o WString.o HardwareSerial.o Print.o SPI.o IPAddress.o
+CORE_COBJ = hooks.o WInterrupts.o wiring.o wiring_digital.o wiring_analog.o wiring_shift.o wiring_pulse.o
+CORE_CPPOBJ = CDC.o HardwareSerial.o HardwareSerial0.o HardwareSerial1.o HardwareSerial2.o HardwareSerial3.o IPAddress.o HID.o \
+              main.o new.o Print.o Stream.o Tone.o USBCore.o WMath.o WString.o SPI.o
 ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o
 ETH_UTIL_CPPOBJ = socket.o w5100.o
 WIFI_COBJ = WiFi.o WiFiClient.o WiFiServer.o WiFiUdp.o server_drv.o spi_drv.o wifi_drv.o
diff --git a/resource/csdk/connectivity/RELEASE v0.1 b/resource/csdk/connectivity/RELEASE v0.1
deleted file mode 100644 (file)
index c1f3f27..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-Project Name: IoTivity
-Release Version No. / Label Name: CA_v0.1
-API Version: CA_v0.4
-
-Release Description:
-Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
-
-Scope of Release:
-1. Supported APIs ( please check below APIs)
-2. Samples to test Supported APIs.
-3. OIC Coding guidelines followed based on the current CSDK source.
-4. Multi-Threaded Connectivity abstraction
-5. Executed Open Source Verification and Prevent analysis.
-
-The following Connectivity Abstraction API features are supported in this release:
-
-Supported APIs
-CAInitialize()
-CATerminate()
-CAStartListeningServer()
-CAStartDiscoveryServer()
-CARegisterHandler()
-CAhandleRequestResponse()
-FindResource()
-SendRequest()
-SendResponse()
-SelectNetwork()
-UnselectNetwork()
-
-Non Supported APIs
-SendNotification()
-AdvertizeResource()
-CAGenerateToken()
-CADestryToken()
-CAGetNetworkInfo()
-
-Type of Release: Source,
-Platform OS: Ubuntu 12.0.4 and above:
-
-Connectivity: WIFI only
-Preconditions:
-1)gcc 4.6.3 and above.
-2)glib library (sudo apt-get install libglib2.0-dev)
-3)libcoap.a library ( do make @lib/libcoap-4.1.1)
-
-Known and Open Issues:
-1) OIC Log, OIC malloc will be removed once name changes applied to OIC Bases code
-2) Support only WIFI Interface.
-3) URI length is 16 characters.
-
-Nature of Release: Partial
-
-How to Build:
-Follow below steps to execute CA Client / server in different systems
-Step 1: Build Libcoap library
-Make File Location @connectivity\lib\libcoap-4.1.1
-Step 2: Build CA library
-Make File Location @connectivity\build\linux
-Step 3: Samples
-Make File Location @connectivity\samples\linux
-
-NOTE: sample.sh script can be used @connectivity\samples\linux for 3 steps together
-
-Execution:
-linux$ export LD_LIBRARY_PATH=../../build/out/
-linux$ ./out/sample_main
-
-Client Option : d, f, h Client
-Server Option : s, h
diff --git a/resource/csdk/connectivity/RELEASE v0.7 b/resource/csdk/connectivity/RELEASE v0.7
new file mode 100644 (file)
index 0000000..d3669a2
--- /dev/null
@@ -0,0 +1,97 @@
+Project Name: IoTivity
+Release Version No: CA_v0.7
+API Version: CA_v0.8
+
+Release Description:
+Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
+
+Supported Platform OS: 
+1) Ubuntu 12.0.4 and above:
+       Connectivity : WIFI, ETHERNET
+       Security : DTLS for WIFI
+2) Tizen 2.3
+       Connectivity : WIFI, EDR, BLE(1:1).
+3) Arduino Mega
+       Connectivity : WIFI, ETH,BLE
+4) Android 5.0s
+       Connectivity : WIFI, BLE
+
+Preconditions:
+1)gcc 4.6.3 and above.
+2)glib library (sudo apt-get install libglib2.0-dev) for linux, tizen and android devices
+3)libcoap.a library ( do make @lib/libcoap-4.1.1)
+4)tinyDTLS library for DTLS enabled applications( enable DTLS = 1 in makefile @connectivity\build/linux)
+5)Ethernet, BLE, TimedActions, Timer libraries for arduino support.
+6)scons for scons script compilation.
+
+Scope of Release:
+1. Supported APIs ( please check below APIs)
+2. Samples to test for Supported APIs.
+3. OIC Coding guidelines followed based on the current CSDK source.
+4. Multi-Threaded, Single threaded Connectivity abstraction.
+5. Executed Open Source Verification and Prevent analysis.
+Type of Release: Source
+The following Connectivity Abstraction API features are supported in this release:
+
+Supported APIs
+CAInitialize()
+CATerminate()
+CAStartListeningServer()
+CAStartDiscoveryServer()
+CARegisterHandler()
+CAhandleRequestResponse()
+FindResource()
+SendRequest()
+SendResponse()
+SelectNetwork()
+UnselectNetwork()
+SendNotification()
+AdvertizeResource()
+CAGenerateToken()
+CADestryToken()
+CAGetNetworkInfo()
+
+
+Known and Open Issues:
+1) OIC Log, OIC Malloc will be removed once name changes applied to OIC Bases code.
+2) Tizen platform BLE stack is not stable. So we may see random crashes.
+
+How to Build for Linux:
+Follow below steps to execute CA Client / server in different systems
+Step 1: Build Libcoap library
+Make File Location @connectivity\lib\libcoap-4.1.1
+Step 2: Build CA library
+Make File Location @connectivity\build\linux
+Step 3: Samples
+Make File Location @connectivity\samples\linux
+
+Execution:
+linux$ export LD_LIBRARY_PATH=../../build/out/
+linux$ ./out/sample_main
+
+
+Follow below sequence to test
+
+Client Option:   c
+Server Option:  s
+
+Client Option:  f (provide a/light)
+Server Option: h (will pick from queue and send response)
+Client Option:  h (to pick server response)
+
+Client Option:  r (provide “ServerIP:5383/a/request”)
+Server Option: h (will pick from queue and send response)
+Client Option:  h (to pick server response)
+
+Server Option: a
+Client Option: h (to pick server response)
+
+Server Option: b (provide ServerIP:5383/a/notify)
+Client Option: h (to pick server response)
+
+Client: Server side: n for network selection (WIFI enabled by default)
+
+
+How to Build for Linux/DTLS:
+./sample.sh WITH_DTLS @@connectivity\samples\linux
+
diff --git a/resource/csdk/connectivity/SConscript b/resource/csdk/connectivity/SConscript
new file mode 100644 (file)
index 0000000..acfbac7
--- /dev/null
@@ -0,0 +1,65 @@
+##
+# CA build script
+##
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+build_sample = env.get('BUILD_SAMPLE')
+
+print "Given Transport is %s" % transport
+print "Given OS is %s" % target_os
+print "BUILD_SAMPLE is %s" % build_sample
+
+targets_disallow_multitransport = ['arduino']
+
+if target_os in targets_disallow_multitransport:
+    if ('ALL' in transport) or (len(transport) != 1):
+        print "*** Error invalid option values: TARGET_TRANSPORT"
+        print "%s disallowed until testing can validate use of multiple transports on %s %d" % (transport, target_os, len(transport))
+        Exit(1)
+
+if 'ALL' in transport:
+       if target_os == 'linux':
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
+       elif target_os == 'tizen':
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
+       elif target_os == 'darwin':
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
+       else:
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
+       print "CA Transport is ALL"
+else:
+       if 'BT' in transport:
+               if target_os == 'linux':
+                       print "CA Transport BT is not supported in Linux"
+                       Exit(1)
+               else:
+                       env.AppendUnique(CPPDEFINES = ['EDR_ADAPTER'])
+                       print "CA Transport is BT"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_EDR_ADAPTER'])
+
+       if 'BLE' in transport:
+               if target_os == 'linux':
+                       print "CA Transport BLE is not supported in Linux"
+                       Exit(1)
+               else:
+                       env.AppendUnique(CPPDEFINES = ['LE_ADAPTER'])
+                       print "CA Transport is BLE"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_LE_ADAPTER'])
+
+       if 'IP' in transport:
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER'])
+               print "CA Transport is IP"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
+
+env.SConscript('./src/SConscript')
+
+if build_sample == 'ON':
+       if target_os in ['linux', 'arduino', 'android']:
+               env.SConscript('./samples/' + target_os + '/SConscript')
+       
diff --git a/resource/csdk/connectivity/SConstruct b/resource/csdk/connectivity/SConstruct
new file mode 100644 (file)
index 0000000..58d0fd9
--- /dev/null
@@ -0,0 +1,62 @@
+##
+# The main build script
+#
+##
+
+# Load common build config
+# Load common build config
+SConscript('./build/SConscript')
+
+Import('env')
+
+sample_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+secured = env.get('SECURED')
+release_mode = env.get('RELEASE')
+buildsample = env.get('BUILD_SAMPLE')
+
+print "Given Transport is %s" % transport
+print "Given OS is %s" % target_os
+print "Secured %s" % env.get('SECURED')
+print "Build sample is set to %s" % buildsample
+
+build_dir = env.get('BUILD_DIR')
+
+if target_os == 'tizen':
+       command = "sh build/tizen/gbsbuild.sh %s %s %s" % (transport, buildsample, release_mode)
+       print "Created Command is %s" % command
+       gbs_script = env.Command('gbs_build', None, command)
+       AlwaysBuild ('gbs_script')
+elif target_os == 'arduino':
+       SConscript('build/arduino/arduino.scons')
+
+        # Build 'libcoap' library
+        SConscript(build_dir + 'lib/libcoap-4.1.1/SConscript')
+
+        # Build 'src' sub-project
+        SConscript(build_dir + 'SConscript')
+
+        # Build 'samples' sub-project
+        SConscript(build_dir + 'samples/arduino/SConscript')
+elif target_os == 'linux':
+
+       # Build 'libcoap' library
+       SConscript(build_dir  + 'lib/libcoap-4.1.1/SConscript')
+
+       # Build 'src' sub-project
+       SConscript(build_dir + 'SConscript')
+
+       # Build 'samples' sub-project
+       env.SConscript(build_dir + 'samples/linux/SConscript')
+elif target_os == 'android':
+
+       # Build 'libcoap' library
+       SConscript(build_dir  + 'lib/libcoap-4.1.1/SConscript')
+
+       # Build 'src' sub-project
+       SConscript(build_dir + 'SConscript')
+
+       # Build 'samples' sub-project
+       env.SConscript(build_dir + 'samples/android/SConscript')
index 7e4cda1..1060410 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  * @file cacommon.h
  * @brief This file contains the common data structures between Resource , CA and adapters
  */
-#ifndef __CA_COMMON_H_
-#define __CA_COMMON_H_
+
+#ifndef CA_COMMON_H_
+#define CA_COMMON_H_
 
 #include <stdint.h>
 #include <stdlib.h>
+#include <stdbool.h>
+
 
 #ifdef __cplusplus
 extern "C"
@@ -34,232 +37,305 @@ extern "C"
 #endif
 
 /**
@brief IP Address Length
* @brief IP address Length
  */
 #define CA_IPADDR_SIZE 16
 
 /**
- @brief Mac Address Length for BT
+ * @brief Mac address length for BT port
  */
 #define CA_MACADDR_SIZE 18
 
 /**
@brief Max Header Options data length
* @brief Max header options data length
  */
 #define CA_MAX_HEADER_OPTION_DATA_LENGTH 16
 
 /**
- @brief CAPayload_t
+* @brief Max token length
+*/
+#define CA_MAX_TOKEN_LEN (8)
+
+/**
+ * @brief Max URI length
+ */
+#ifdef ARDUINO
+#define CA_MAX_URI_LENGTH 128  /* maximum size of URI for embedded platforms*/
+#else
+#define CA_MAX_URI_LENGTH 512 /* maximum size of URI for other platforms*/
+#endif
+
+/**
+ * @brief Max PDU length supported
  */
-typedef char* CAPayload_t;
+#ifdef ARDUINO
+#define COAP_MAX_PDU_SIZE           320  /* maximum size of a CoAP PDU for embedded platforms*/
+#else
+#define COAP_MAX_PDU_SIZE           1400 /* maximum size of a CoAP PDU for big platforms*/
+#endif
 
 /**
- @brief CAURI_t
+ * @brief option types - the highest option number 63
  */
-typedef char* CAURI_t;
+#define CA_OPTION_IF_MATCH 1
+#define CA_OPTION_ETAG 4
+#define CA_OPTION_IF_NONE_MATCH 5
+#define CA_OPTION_OBSERVE 6
+#define CA_OPTION_LOCATION_PATH 8
+#define CA_OPTION_URI_PATH 11
+#define CA_OPTION_CONTENT_FORMAT 12
+#define CA_OPTION_CONTENT_TYPE COAP_OPTION_CONTENT_FORMAT
+#define CA_OPTION_MAXAGE 14
+#define CA_OPTION_URI_QUERY 15
+#define CA_OPTION_ACCEPT 17
+#define CA_OPTION_LOCATION_QUERY 20
 
 /**
- @brief CAToken_t
+ * @brief Payload information from resource model
  */
-typedef char* CAToken_t;
+typedef char *CAPayload_t;
 
 /**
- @brief CABool_t
+ * @brief URI for the OIC base.CA considers relative URI as the URI.
  */
-typedef enum
-{
-    CA_FALSE = 0, CA_TRUE
-} CABool_t;
+typedef char *CAURI_t;
 
 /**
- @brief CAConnectivityType_t
+ * @brief Token information for mapping the request and responses by resource model
+ */
+typedef char *CAToken_t;
+
+/**
+ * @enum CATransportType_t
+ * @brief Different connectivities that are handled in Connectivity Abstraction
  */
 typedef enum
 {
-    CA_ETHERNET = (1 << 0), CA_WIFI = (1 << 1), CA_EDR = (1 << 2), CA_LE = (1 << 3)
-} CAConnectivityType_t;
+    CA_IPV4 = (1 << 0),     /**< IPV4 Transport Type */
+    CA_IPV6 = (1 << 1),     /**< IPV6 Transport Type */
+    CA_EDR = (1 << 2),      /**< EDR Transport Type */
+    CA_LE = (1 << 3)        /**< LE Transport Type */
+} CATransportType_t;
 
 /**
- @brief CANetworkStatus_t
+ * @enum CANetworkStatus_t
+ * @brief Information about the network status.
  */
 typedef enum
 {
-    CA_INTERFACE_UP, CA_INTERFACE_DOWN
+    CA_INTERFACE_DOWN,   /**< Connection is not available */
+    CA_INTERFACE_UP    /**< Connection is Available */
 } CANetworkStatus_t;
 
 /**
- @brief  Address of the local or remote endpoint
@brief  Address of the local or remote endpoint
  */
 typedef union
 {
     /**
-     @brief BT Information
+     * @brief BT Mac Information
      */
     struct
     {
-        /** @brief Bluettoth Mac Address **/
-        char btMacAddress[CA_MACADDR_SIZE];
+        char btMacAddress[CA_MACADDR_SIZE];   /**< BT mac address **/
     } BT;
+
     /**
-     @brief IP Information
+     * @brief LE MAC Information
      */
     struct
     {
-        /** Ip address of the interface**/
-        char ipAddress[CA_IPADDR_SIZE];
-        /** port information**/
-        uint32_t port;
+        char leMacAddress[CA_MACADDR_SIZE];   /**< BLE mac address **/
+    } LE;
+
+    /**
+     * @brief IP Information
+     */
+    struct
+    {
+        char ipAddress[CA_IPADDR_SIZE]; /**< Ip address of the interface**/
+        uint16_t port;                  /**< port information**/
     } IP;
 } CAAddress_t;
 
 /**
- @brief CAQualityOfService
+ * @enum CAMessageType_t
+ * @brief Message Type for Base source code
  */
 typedef enum
 {
-    CA_LOW_QOS = 0, CA_MEDIUM_QOS, CA_HIGH_QOS, CA_NA_QOS // No Quality is defined, let the stack decide
-} CAQualityOfService_t;
+    CA_MSG_CONFIRM = 0,  /**< confirmable message (requires ACK/RST) */
+    CA_MSG_NONCONFIRM,   /**< non-confirmable message (one-shot message) */
+    CA_MSG_ACKNOWLEDGE,  /**< used to acknowledge confirmable messages */
+    CA_MSG_RESET         /**< used to indicates not-interested or error (lack of context)in
+                                                  received messages */
+} CAMessageType_t;
 
 /**
- @brief CAMethod_t
+ * @enum CAMethod_t
+ * @brief Allowed method to be used by resource model
  */
 typedef enum
 {
-    CA_GET = 1, CA_POST, CA_PUT, CA_DELETE
+    CA_GET = 1, /**< GET Method  */
+    CA_POST,    /**< POST Method */
+    CA_PUT,     /**< PUT Method */
+    CA_DELETE   /**< DELETE Method */
 } CAMethod_t;
 
 /**
@brief RemoteEndpoint information for connectivities
* @brief Remote endpoint information for connectivities
  */
 typedef struct
 {
-    /** Resource URI information **/
-    CAURI_t resourceUri;
-    /** Remote Endpoint address **/
-    CAAddress_t addressInfo;
-    /** Connectivity of the endpoint**/
-    CAConnectivityType_t connectivityType;
+
+    CAURI_t resourceUri;                    /**< Resource URI information **/
+    CAAddress_t addressInfo;                /**< Remote Endpoint address **/
+    CATransportType_t transportType;  /**< Transport Type of the endpoint**/
+    bool isSecured;                     /**< Secure connection**/
 } CARemoteEndpoint_t;
 
+
+/**
+ * @brief Group endpoint information for connectivities
+ */
+typedef struct
+{
+    CAURI_t resourceUri;                    /**< Resource URI information **/
+    CATransportType_t transportType;  /**< Transport type of the endpoint**/
+} CAGroupEndpoint_t;
+
 /**
  @brief Local Connectivity information
  */
 typedef struct
 {
-    /** address of the interface  **/
-    CAAddress_t addressInfo;
-    /** Connectivity type that localconnectivity avaialble **/
-    CAConnectivityType_t type;
-} CALocalConnectivityt_t;
+    CAAddress_t addressInfo;    /**< Address of the interface  **/
+    CATransportType_t type;  /**< Transport type of local device **/
+    bool isSecured;         /**< Secure connection**/
+} CALocalConnectivity_t;
 
 /**
- @brief Enums for CA return values
+ * @enum CAResult_t
+ * @brief Enums for CA return values
  */
 typedef enum
 {
-    /* Success status code - START HERE */
-    CA_STATUS_OK = 0,
-    CA_STATUS_INVALID_PARAM,
-    CA_DESTINATION_NOT_REACHABLE,
-    CA_SEND_FAILED,
-    CA_RECEVIE_FAILED,
-    CA_MEMORY_ALLOC_FAILED,
-    CA_REQUEST_TIMEOUT,
-    CA_DESTINATION_DISCONNECTED,
-    CA_STATUS_FAILED,
-    CA_NOT_SUPPORTED
-/* Error status code - END HERE */
+    // Result code - START HERE
+    CA_STATUS_OK = 0,               /**< Success */
+    CA_STATUS_INVALID_PARAM,        /**< Invalid Parameter */
+    CA_ADAPTER_NOT_ENABLED,         /**< Adapter is not enabled */
+    CA_SERVER_STARTED_ALREADY,      /**< Server is started already */
+    CA_SERVER_NOT_STARTED,          /**< Server is not started*/
+    CA_DESTINATION_NOT_REACHABLE,   /**< Destination is not reachable */
+    CA_SOCKET_OPERATION_FAILED,     /**< Socket operation failed */
+    CA_SEND_FAILED,                 /**< Send request failed */
+    CA_RECEIVE_FAILED,              /**< Receive failed */
+    CA_MEMORY_ALLOC_FAILED,         /**< Memory allocation failed */
+    CA_REQUEST_TIMEOUT,             /**< Request is Timeout */
+    CA_DESTINATION_DISCONNECTED,    /**< Destination is disconnected */
+    CA_NOT_SUPPORTED,               /**< Not supported */
+    CA_STATUS_FAILED =255           /**< Failure */
+    /* Result code - END HERE */
 } CAResult_t;
 
 /**
- @brief Enums for CA Response  values
+ * @enum CAResponseResult_t
+ * @brief Enums for CA Response values
  */
 typedef enum
 {
-    /* Success status code - START HERE */
-    CA_CREATED = 201,
-    CA_DELETED = 202,
-    CA_VALID = 203,
-    CA_CONTENT = 205,
-    CA_BAD_REQ = 400,
-    CA_BAD_OPT = 402,
-    CA_NOT_FOUND = 404
-/* Error status code - END HERE */
+    /* Response status code - START HERE */
+    CA_EMPTY = 0,                    /**< Empty */
+    CA_SUCCESS = 200,                /**< Success */
+    CA_CREATED = 201,                /**< Created */
+    CA_DELETED = 202,                /**< Deleted */
+    CA_BAD_REQ = 400,                /**< Bad Request */
+    CA_BAD_OPT = 402,                /**< Bad Option */
+    CA_NOT_FOUND = 404,              /**< Not found */
+    CA_INTERNAL_SERVER_ERROR = 500,  /**< Internal Server Error */
+    CA_RETRANSMIT_TIMEOUT = 504      /**< Retransmit timeout */
+    /* Response status code - END HERE */
 } CAResponseResult_t;
 
 /**
- @brief Transport Protocol IDs
+ * @enum CATransportProtocolID_t
+ * @brief Transport Protocol IDs for additional options
  */
 typedef enum
 {
-    CA_INVALID_ID = (1 << 0), CA_COAP_ID = (1 << 1)
+    CA_INVALID_ID = (1 << 0),   /**< Invalid ID */
+    CA_COAP_ID = (1 << 1)       /**< COAP ID */
 } CATransportProtocolID_t;
 
 /**
+ * @enum CAAdapterState_t
+ * @brief Adapter State to indicate the network changed notifications.
+ */
+typedef enum
+{
+    CA_ADAPTER_DISABLED,   /**< Adapter is Disabled */
+    CA_ADAPTER_ENABLED     /**< Adapter is Enabled */
+} CAAdapterState_t;
+
+/**
  * @brief Header options structure to be filled
  *
  * This structure is used to hold header information.
  */
 typedef struct
 {
-    /** The protocol ID this option applies to**/
-    CATransportProtocolID_t protocolID;
-    /** The header option ID which will be added to communication packets**/
-    uint16_t optionID;
-    /** its length   191**/
-    uint16_t optionLength;
-    /** optional data values**/
-    uint8_t optionData[CA_MAX_HEADER_OPTION_DATA_LENGTH];
+    CATransportProtocolID_t protocolID;                     /**< Protocol ID of the Option */
+    uint16_t optionID;                                      /**< The header option ID which will be
+                                                            added to communication packets */
+    uint16_t optionLength;                                  /**< Option Length **/
+    uint8_t optionData[CA_MAX_HEADER_OPTION_DATA_LENGTH];   /**< Optional data values**/
 } CAHeaderOption_t;
 
 /**
- * @brief Request Information to be sent
- *
- * This structure is used to hold request information
- */
-
-/**
  * @brief Base Information received
  *
  * This structure is used to hold request & response base information
  */
 typedef struct
 {
-    /**Qos for the request **/
-    CAQualityOfService_t qos;
-    /** Token for CA**/
-    CAToken_t token;
-    /** Header Options for the request **/
-    CAHeaderOption_t * options;
-    /** Number of Header options**/
-    uint8_t numOptions;
-    /** payload of the request **/
-    CAPayload_t payload;
+
+    CAMessageType_t type;       /**< Qos for the request */
+    uint16_t messageId;         /**< Message id.
+                                 * if message id is zero, it will generated by CA inside.
+                                 * otherwise, you can use it */
+    CAToken_t token;            /**< Token for CA */
+    uint8_t tokenLength;        /**< token length*/
+    CAHeaderOption_t *options;  /** Header Options for the request */
+    uint8_t numOptions;         /**< Number of Header options */
+    CAPayload_t payload;        /**< payload of the request  */
 } CAInfo_t;
 
+/**
+ * @brief Request Information to be sent
+ *
+ * This structure is used to hold request information
+ */
 typedef struct
 {
-    /** Name of the Method Allowed **/
-    CAMethod_t method;
-    /** Base Information **/
-    CAInfo_t info;
+    CAMethod_t method;  /**< Name of the Method Allowed */
+    CAInfo_t info;      /**< Information of the request. */
 } CARequestInfo_t;
 
 /**
- * @brief Response Information received
+ * @brief Response information received
  *
  * This structure is used to hold response information
  */
 typedef struct
 {
-    /**Response Result by Resource Model**/
-    CAResponseResult_t result;
-    /**Base Information **/
-    CAInfo_t info;
+    CAResponseResult_t result;  /**< Result for response by resource model */
+    CAInfo_t info;              /**< Information of the response */
 } CAResponseInfo_t;
 
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif //#ifndef __CA_COMMON_H_
+#endif /* CA_COMMON_H_ */
+
index 8619f92..7607bfc 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  ******************************************************************/
 
 /**
- * @file cainterface.h
- * @brief This file contains the APIs for Resource Model to use
+ * @file
+ *
+ * This file contains the APIs for Resource Model to use.
  */
 
-#ifndef __CA_INTERFACE_H_
-#define __CA_INTERFACE_H_
+#ifndef CA_INTERFACE_H_
+#define CA_INTERFACE_H_
 
 /**
- * Connectivity Abstraction Interface Description APIs.
+ * Connectivity Abstraction Interface APIs.
  */
 #include "cacommon.h"
 
+#ifdef __WITH_DTLS__
+#include "ocsecurityconfig.h"
+#endif
+
 #ifdef __cplusplus
 extern "C"
 {
@@ -38,165 +43,234 @@ extern "C"
 
 /**
  * @brief   Callback function type for request delivery.
- *          requestInfo contains different parameters for resource model to understand about the request.
- * @param   object      [OUT]   Endpoint object from which the request is received. It contains endpoint
- *                              address based on the connectivity type.
- * @param   requestInfo [OUT]   Identifier which needs to be sent with request.
+ * @param   object      [OUT] Endpoint object from which the request is received. It contains
+ *                            endpoint address based on the connectivity type.
+ * @param   requestInfo [OUT] Info for resource model to understand about the request.
+ * @return  NONE
  */
-typedef void (*CARequestCallback)(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
+typedef void (*CARequestCallback)(const CARemoteEndpoint_t *object,
+                                  const CARequestInfo_t *requestInfo);
 
 /**
  * @brief   Callback function type for response delivery.
- *          responseInfor contains different parameters for resource model to understand about the request.
- * @param   object          [OUT]   Endpoint object from which the response is received.
- * @param   responseInfo    [OUT]   Identifier which needs to be mapped with response.
+ * @param   object          [OUT] Endpoint object from which the response is received.
+ * @param   responseInfo    [OUT] Identifier which needs to be mapped with response.
+ * @return  NONE
+ */
+typedef void (*CAResponseCallback)(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *responseInfo);
+
+#ifdef __WITH_DTLS__
+
+/**
+ * Binary blob containing device identity and the credentials for all devices
+ * trusted by this device.
  */
-typedef void (*CAResponseCallback)(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
+typedef struct
+{
+   unsigned char identity[DTLS_PSK_ID_LEN]; /** identity of self */
+   uint32_t num;                            /** number of credentials in this blob */
+   OCDtlsPskCreds *creds;                   /** list of credentials. Size of this
+                                                array is determined by 'num' variable. */
+} CADtlsPskCredsBlob_t;
+
+/**
+ * @brief   Callback function type for getting DTLS credentials.
+ * @param   credInfo          [OUT] DTLS credentials info. Handler has to allocate new memory for
+ *                                  both credInfo and credInfo->creds which is then freed by CA
+ * @return  NONE
+ */
+typedef void (*CAGetDTLSCredentialsHandler)(CADtlsPskCredsBlob_t **credInfo);
+#endif //__WITH_DTLS__
 
 /**
  * @brief   Initialize the connectivity abstraction module.
- *          It will initialize adapters, thread pool and other modules based on the platform compilation options.
+ *          It will initialize adapters, thread pool and other modules based on the platform
+ *          compilation options.
  *
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CAInitialize();
 
 /**
  * @brief   Terminate the connectivity abstraction module.
  *          All threads, data structures are destroyed for next initializations.
+ * @return  NONE
  */
 void CATerminate();
 
 /**
  * @brief   Starts listening servers.
  *          This API is used by resource hosting server for listening multicast requests.
- *          based on the adapters configurations , different kinds of servers are started.
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ *          Based on the adapters configurations, different kinds of servers are started.
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED
  */
 CAResult_t CAStartListeningServer();
 
 /**
  * @brief   Starts discovery servers.
  *          This API is used by resource required clients for listening multicast requests.
- *          based on the adapters configurations , different kinds of servers are started.
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ *          Based on the adapters configurations, different kinds of servers are started.
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED
  */
 CAResult_t CAStartDiscoveryServer();
 
 /**
  * @brief   Register request callbacks and response callbacks.
- *          requests and responses are delivered these callbacks .
- * @see     CARequestCallback CAResponseCallback
- * @param   ReqHandler   [IN]    Request callback ( for GET,PUT ..etc)
- * @param   RespHandler  [IN]    Response Handler Callback
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ *          Requests and responses are delivered these callbacks .
+ * @param   ReqHandler   [IN] Request callback ( for GET,PUT ..etc)
+ * @param   RespHandler  [IN] Response Handler Callback
+ * @see     CARequestCallback
+ * @see     CAResponseCallback
+ * @return  NONE
  */
-CAResult_t CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler);
+void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler);
+
+#ifdef __WITH_DTLS__
+/**
+ * @brief   Register callback to get DTLS PSK credentials.
+ * @param   GetDTLSCredentials   [IN] GetDTLS Credetials callback
+ * @return  #CA_STATUS_OK
+ */
+CAResult_t CARegisterDTLSCredentialsHandler(
+                                                   CAGetDTLSCredentialsHandler GetDTLSCredentials);
+#endif //__WITH_DTLS__
 
 /**
  * @brief   Create a Remote endpoint if the URI is available already.
- *          for FindResource-> unicast requests , this API is used.
- *          FindResource(URI)-> CACreateRemoteEndpoint , CASendRequest(GET)
- * @param   uri     [IN]    Absolute URI of the resource to be used to generate the Remote endpoint
- *                          for ex : coap://10.11.12.13:4545/resource_uri ( for IP)
- *                          coap://10:11:12:13:45:45/resource_uri ( for BT)
- * @param   object  [OUT ]  Endpoint object which contains the above parsed data
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ *          This is a Helper function which can be used before calling
+ *          CASendRequest / CASendNotification.
+ * @param   uri                 [IN]  Absolute URI of the resource to be used to generate the
+ *                                    Remote endpoint
+ *                                    \n For ex : coap://10.11.12.13:4545/resource_uri ( for IP)
+ *                                    \n coap://10:11:12:13:45:45/resource_uri ( for BT)
+ * @param   transportType    [IN]  Transport type of the endpoint
+ * @param   object              [OUT] Endpoint object which contains the above parsed data
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED
+ * @remark  The created Remote endpoint can be freed using CADestroyRemoteEndpoint() API.
+ * @see     CADestroyRemoteEndpoint
  */
-CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, CARemoteEndpoint_t** object);
+CAResult_t CACreateRemoteEndpoint(const CAURI_t uri,
+                                  const CATransportType_t transportType,
+                                  CARemoteEndpoint_t **object);
 
 /**
- * @brief   API Destroy the remote endpoint created
- * @param   object  [IN]    endpoint object created with CACreateRemoteEndpoint
+ * @brief   Destroy the remote endpoint created
+ * @param   object  [IN] Remote Endpoint object created with CACreateRemoteEndpoint
+ * @return  NONE
  */
-void CADestroyRemoteEndpoint(CARemoteEndpoint_tobject);
+void CADestroyRemoteEndpoint(CARemoteEndpoint_t *object);
 
 /**
- * @brief   Generating the token for the requests/response.
- *          Token memory is created and destroyed by the calle.
- * @param   token   [OUT]   token for the request
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief   Generating the token for matching the request and response.
+ * @param   token          [OUT] Token for the request
+ * @param   tokenLength    [IN]  length of the token
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
+ *          or #CA_STATUS_NOT_INITIALIZED
+ * @remark  Token memory is destroyed by the caller using CADestroyToken().
+ * @see     CADestroyToken
  */
-CAResult_t CAGenerateToken(CAToken_t* token);
+CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength);
 
 /**
  * @brief   Destroy the token generated by CAGenerateToken
- * @param   token   [IN]    token for the request
+ * @param   token   [IN] token to be freed
+ * @return  NONE
  */
 void CADestroyToken(CAToken_t token);
 
 /**
- * @brief   Find the resource in the network. This API internally sends multicast messages on the
- *          all connectivity adapters. Responses are delivered via response callbacks.
+ * @brief   Find the resource in the network. This API internally sends multicast messages on all
+ *          selected connectivity adapters. Responses are delivered via response callbacks.
  *
- * @param   resourceUri [IN]    Uri to send multicast search request
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @param   resourceUri [IN] Uri to send multicast search request. Must contain only relative
+ *                           path of Uri to be search.
+ * @param   token       [IN] Token for the request
+ * @param   tokenLength [IN]  length of the token
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_STATUS_NOT_INITIALIZED
  */
-CAResult_t CAFindResource(const CAURI_t resourceUri);
+CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token, uint8_t tokenLength);
 
 /**
  * @brief   Send control Request on a resource
- * @param   object      [IN]    Remote Endpoint where the payload need to be sent.
- *                              This Remote endpoint is delivered with Request or response callback.
- * @param   requestInfo [IN ]   information for the request.
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @param   object      [IN] Remote Endpoint where the payload need to be sent.
+ *                           This Remote endpoint is delivered with Request or response callback.
+ * @param   requestInfo [IN] Information for the request.
+ * @return  #CA_STATUS_OK #CA_STATUS_FAILED #CA_MEMORY_ALLOC_FAILED
  */
-CAResult_t CASendRequest(const CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
 
 /**
- * @brief   Sendi the response
- * @param   object          [IN]    Remote Endpoint where the payload need to be sent.
- *                                  This Remote endpoint is delivered with Request or response callback
- * @param   responseInfo    [IN ]   information for the response
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief   Send control Request on a resource to multicast group
+ * @param   object      [IN] Group Endpoint where the payload need to be sent.
+ *                           This Remote endpoint is delivered with Request or response callback.
+ * @param   requestInfo [IN] Information for the request.
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
  */
-CAResult_t CASendResponse(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
+CAResult_t CASendRequestToAll(const CAGroupEndpoint_t *object,
+                              const CARequestInfo_t *requestInfo);
+
+/**
+ * @brief   Send the response
+ * @param   object          [IN] Remote Endpoint where the payload need to be sent.
+ *                               This Remote endpoint is delivered with Request or response callback
+ * @param   responseInfo    [IN] Information for the response
+ * @return  #CA_STATUS_OK or  #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
+                const CAResponseInfo_t *responseInfo);
 
 /**
  * @brief   Send notification to the remote object
- * @param   object          [IN]    Remote Endpoint where the payload need to be sent.
- *                                  This Remote endpoint is delivered with Request or response callback.
- * @param   responseInfo    [IN ]   information for the response.
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @param   object          [IN] Remote Endpoint where the payload need to be sent.
+ *                               This Remote endpoint is delivered with Request or response callback.
+ * @param   responseInfo    [IN] Information for the response.
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
  */
-CAResult_t CASendNotification(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
+CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
+                      const  CAResponseInfo_t *responseInfo);
 
 /**
- * @brief   for advertise the resource
- * @param   resourceUri [IN]    URI to be advertised
- * @param   options     [IN]    header options information
- * @param   numOptions  [IN]    number of options
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief   To advertise the resource
+ * @param   resourceUri [IN] URI to be advertised
+ * @param   token       [IN] Token for the request
+ * @param   tokenLength [IN] length of the token
+ * @param   options     [IN] Header options information
+ * @param   numOptions  [IN] Number of options
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or
+ *          #CA_MEMORY_ALLOC_FAILED or #CA_STATUS_NOT_INITIALIZED
  */
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAHeaderOption_t* options,
-        uint8_t numOptions);
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
+                               uint8_t tokenLength, const CAHeaderOption_t *options,
+                               const uint8_t numOptions);
 
 /**
  * @brief   Select network to use
- * @param   interestedNetwork   [IN]    Connectivity Type enum
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @param   interestedNetwork   [IN] Connectivity Type enum
+ * @return  #CA_STATUS_OK or #CA_NOT_SUPPORTED or #CA_STATUS_FAILED or #CA_NOT_SUPPORTED
  */
 CAResult_t CASelectNetwork(const uint32_t interestedNetwork);
 
 /**
  * @brief   Select network to unuse
- * @param   nonInterestedNetwork    [IN]    Connectivity Type enum
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @param   nonInterestedNetwork    [IN] Connectivity Type enum
+ * @return  #CA_STATUS_OK or #CA_NOT_SUPPORTED or #CA_STATUS_FAILED
  */
 CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork);
 
 /**
  * @brief   Get network information
- *          It should be destroyed by the caller as its Get Information.
- * @param   info    [OUT]   LocalConnectivity objects
- * @param   size    [OUT]   No Of Array objects
- * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ *          It should be destroyed by the caller as it Get Information.
+ * @param   info    [OUT] LocalConnectivity objects
+ * @param   size    [OUT] No Of Array objects
+ * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_STATUS_INVALID_PARAM or
+*                #CA_MEMORY_ALLOC_FAILED
  */
-CAResult_t CAGetNetworkInformation(CALocalConnectivityt_t **info, uint32_t* size);
+CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size);
 
 /**
- * @brief   for usage of singled threaded application.
- * @return   CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief    To Handle the Request or Response
+ * @return   #CA_STATUS_OK
  */
 CAResult_t CAHandleRequestResponse();
 
@@ -204,4 +278,5 @@ CAResult_t CAHandleRequestResponse();
 } /* extern "C" */
 #endif
 
-#endif
+#endif /* CA_INTERFACE_H_ */
+
diff --git a/resource/csdk/connectivity/build/How_To_Build.txt b/resource/csdk/connectivity/build/How_To_Build.txt
new file mode 100644 (file)
index 0000000..2725deb
--- /dev/null
@@ -0,0 +1,125 @@
+=== Prerequisites ===
+
+* 1. Scons
+
+Please refer to the following page to install scons:
+   http://www.scons.org/doc/production/HTML/scons-user.html#chap-build-install
+(Note: on Windows, install Python 2.x before installing scons)
+
+* 2. IDE/SDK Pre-requites
+To build for some OS (Android / Arduino / IOS ...), an IDE/SDK may be required,
+please go to the relative page to download and install the required IDE/SDK.
+
+Note: Connectivity module building has been changed. We have to build connectivity
+      from the iotivity root folder.
+
+Linux Build:
+
+1) Go to "iotivity/" folder.
+
+2) Execute following command(s) to start build based on transport selection required :
+
+    -> Building for all transports :
+    $ scons resource/csdk/connectivity/samples/linux/ TARGET_OS=linux TARGET_TRANSPORT=ALL
+
+    -> Building for a specific transport :
+    $ scons resource/csdk/connectivity/samples/linux/ TARGET_OS=linux TARGET_TRANSPORT=IP
+
+    -> Building for multiple transports :
+    $ scons resource/csdk/connectivity/samples/linux/ TARGET_OS=linux TARGET_TRANSPORT=IP,BT
+
+    -> Clean Build (all transports) :
+    scons resource/csdk/connectivity/samples/linux/ TARGET_OS=linux TARGET_TRANSPORT=ALL -c (for clean)
+
+
+3) The above command will build sample also.
+
+    For Enabling Secured server,
+    * Note: tinydtls library has to copied to "connectivity/lib/tinydtls" for secured build.
+
+    Secured Server will be only used for IP transports.
+
+    Give command "scons resource/csdk/connectivity/samples/linux/ TARGET_OS=linux TARGET_TRANSPORT=IP SECURED=1
+
+Android Build:
+
+1) Go to "iotivity/" folder.
+
+2) Execute following command(s) to start build based on transport selection required :
+
+    -> Building for all transports :
+    $ scons resource/csdk/connectivity/samples/android/ TARGET_OS=android TARGET_TRANSPORT=ALL TARGET_ARCH=x86 ANDROID_NDK=your_ndk_path
+
+    -> Building for a specific transport :
+    $ scons resource/csdk/connectivity/samples/android/ TARGET_OS=android TARGET_TRANSPORT=IP TARGET_ARCH=x86 ANDROID_NDK=your_ndk_path
+
+    -> Building for multiple transports :
+    $ scons resource/csdk/connectivity/samples/android/ TARGET_OS=android TARGET_TRANSPORT=IP,BT TARGET_ARCH=x86 ANDROID_NDK=your_ndk_path
+
+Note :- Upon successful execution of above command(s) CA library will be generated at path
+        "iotivity/out/android/TARGET_ARCH/release or debug".
+
+Tizen Build:
+
+1) If you are building first time, then delete GBS-ROOT folder from home directory.
+
+2) Go to "iotivity/" folder.
+
+3) Execute following command(s) to start build based on transport selection required :
+
+    -> Building for all transports :
+    $ scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=ALL
+
+    -> Building for a specific transport :
+    $ scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP
+
+    -> Building for multiple transports :
+    $ scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP,BT,BLE
+
+4) By default, above command will build sample also.
+   To disable building sample, add BUILD_SAMPLE=OFF to the build command.
+   Ex: scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=ALL BUILD_SAMPLE=OFF
+   Making this flag ON builds the sample.
+
+Note :- Upon successful execution of above command(s) CA library and sample applications will be
+        generated at path "~/GBS-ROOT/local/repos/redwood/armv7l/RPMS".
+
+Arduino Build:
+
+Note :- Currently Mega & Due build is supported.
+
+1) Set up Arduino first before building. Refer to "connectivity\build\arduino\Arduino_Setup_README.txt" file for help.
+
+2) Go to "iotivity/" folder.
+
+3) Execute following command to start build :
+
+For Arduino Mega
+    $ scons resource/csdk/connectivity/samples/arduino/ TARGET_OS=arduino TARGET_TRANSPORT=<transport> TARGET_ARCH=avr BOARD=mega ARDUINO_HOME=<path_to_arduino_installation>
+For Arduino Due
+    $ scons resource/csdk/connectivity/samples/arduino/ TARGET_OS=arduino TARGET_TRANSPORT=<transport> TARGET_ARCH=arm BOARD=arduino_due_x_dbg ARDUINO_HOME=<path_to_arduino_installation>
+    NOTE: BOARD=arduino_due_x_dbg|arduino_due_x. Default is arduino_due_x_dbg.
+
+    Possible values for <transport> are:
+    -> IP :
+    $ scons resource/csdk/connectivity/samples/arduino/ TARGET_OS=arduino TARGET_TRANSPORT=IP TARGET_ARCH=avr BOARD=mega ARDUINO_HOME=<path_to_arduino_installation>
+    -> BLE :
+    $ scons resource/csdk/connectivity/samples/arduino/ TARGET_OS=arduino TARGET_TRANSPORT=BLE TARGET_ARCH=avr BOARD=mega ARDUINO_HOME=<path_to_arduino_installation>
+
+    Note :- Only single transport can be built at a time for Arduino.
+
+4) The above command will build sample also. The "CASample.hex" can be found at "/samples/arduino/"
+
+5) After building sample, script will try to install on "/dev/ttyACM0" port in 'sudo' mode.
+   To skip installation, set command line argument 'UPLOAD=false'.
+   "scons resource/csdk/connectivity/samples/arduino/ TARGET_OS=arduino TARGET_TRANSPORT=ETHERNET TARGET_ARCH=avr BOARD=mega ARDUINO_HOME=<path_to_arduino_installation> UPLOAD=false"
+
+6) To set BLE Shield Name, include the option DEVICE_NAME during scons build.
+
+   -> $ scons resource/csdk/connectivity/samples/arduino/ TARGET_OS=arduino TARGET_TRANSPORT=ETHERNET TARGET_ARCH=avr BOARD=mega ARDUINO_HOME=<path_to_arduino_installation> DEVICE_NAME=OIC
+
+   Specified Device name length MUST be less than 10 characters. RBL Library has this limitation.
+   By Default DEVICE_NAME=OIC-DEVICE, if device name option is not specified
+
+   To change the port number, please modify  "port" variable in __upload() function in: "/build/arduino/SConscript".
+
diff --git a/resource/csdk/connectivity/build/SConscript b/resource/csdk/connectivity/build/SConscript
new file mode 100644 (file)
index 0000000..b901f1a
--- /dev/null
@@ -0,0 +1,269 @@
+##
+# This script includes generic build options:
+#    release/debug, target os, target arch, cross toolchain, build environment etc
+##
+import os
+import platform
+
+# Map of host os and allowed target os (host: allowed target os)
+host_target_map = {
+               'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
+               'windows': ['windows', 'winrt', 'android', 'arduino'],
+               'darwin': ['darwin', 'ios', 'android', 'arduino'],
+               }
+
+# Map of os and allowed archs (os: allowed archs)
+os_arch_map = {
+               'linux': ['x86', 'x86_64', 'arm', 'arm64'],
+               'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
+               'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
+               'windows': ['x86', 'amd64', 'arm'],
+               'winrt': ['arm'],
+               'darwin': ['i386', 'x86_64'],
+               'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
+               'arduino': ['avr', 'arm'],
+                'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
+               }
+
+host = platform.system().lower()
+
+if not host_target_map.has_key(host):
+       print "\nError: Current system (%s) isn't supported\n" % host
+       Exit(1)
+
+######################################################################
+# Get build options (the optins from command line)
+######################################################################
+target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
+
+if target_os not in host_target_map[host]:
+       print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
+       Exit(1)
+
+default_arch = platform.machine()
+if default_arch not in os_arch_map[target_os]:
+       default_arch = os_arch_map[target_os][0].lower()
+
+target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
+
+# True if binary needs to be installed on board. (Might need root permissions)
+# set to 'no', 'false' or 0 for only compilation
+require_upload = ARGUMENTS.get('UPLOAD', True)
+
+# Get the device name
+device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
+
+######################################################################
+# Common build options (release, target os, target arch)
+######################################################################
+help_vars = Variables()
+help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
+help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', False))
+help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
+help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP']))
+help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
+help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
+help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
+help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
+
+help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
+
+######################################################################
+# Platform(build target) specific options: SDK/NDK & toolchain
+######################################################################
+targets_support_cc = ['linux', 'arduino', 'tizen']
+
+if target_os in targets_support_cc:
+       # Set cross compile toolchain
+       help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
+       help_vars.Add(PathVariable('TC_PATH',
+                       'Toolchain path (Generally only be required for cross-compiling)',
+                       os.environ.get('TC_PATH')))
+
+if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
+       env = Environment(variables = help_vars,
+                       tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
+                       )
+else:
+       env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os)
+
+Help(help_vars.GenerateHelpText(env))
+
+# Set device name to __OIC_DEVICE_NAME__
+env.AppendUnique(CPPDEFINES = ['-D__OIC_DEVICE_NAME__=' + "\'\"" + device_name + "\"\'"])
+
+tc_set_msg = '''
+************************************ Warning **********************************
+*   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
+* toolchain, if it isn't what you expect you should unset it, otherwise it may*
+* cause inexplicable errors.                                                  *
+*******************************************************************************
+'''
+
+if target_os in targets_support_cc:
+       prefix = env.get('TC_PREFIX')
+       tc_path = env.get('TC_PATH')
+       if prefix:
+               env.Replace(CC = prefix + 'gcc')
+               env.Replace(CXX = prefix + 'g++')
+               env.Replace(AR = prefix + 'ar')
+               env.Replace(AS = prefix + 'as')
+               env.Replace(LINK = prefix + 'ld')
+               env.Replace(RANLIB = prefix + 'ranlib')
+
+       if tc_path:
+               env.PrependENVPath('PATH', tc_path)
+               sys_root = os.path.abspath(tc_path + '/../')
+               env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
+               env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
+
+       if prefix or tc_path:
+               print tc_set_msg
+
+# Ensure scons be able to change its working directory
+env.SConscriptChdir(1)
+
+# Set the source directory and build directory
+#   Source directory: 'dir'
+#   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
+#
+# You can get the directory as following:
+#   env.get('SRC_DIR')
+#   env.get('BUILD_DIR')
+
+def __set_dir(env, dir):
+       if not os.path.exists(dir + '/SConstruct'):
+               print '''
+*************************************** Error *********************************
+* The directory(%s) seems isn't a source code directory, no SConstruct file is
+* found. *
+*******************************************************************************
+''' % dir
+               Exit(1)
+
+       if env.get('RELEASE'):
+               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
+       else:
+               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
+       env.VariantDir(build_dir, dir, duplicate=0)
+
+       env.Replace(BUILD_DIR = build_dir)
+       env.Replace(SRC_DIR = dir)
+
+def __src_to_obj(env, src, home = ''):
+       obj = env.get('BUILD_DIR') + src.replace(home, '')
+       if env.get('OBJSUFFIX'):
+               obj += env.get('OBJSUFFIX')
+       return env.Object(obj, src)
+
+def __install(ienv, targets, name):
+       i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+       Alias(name, i_n)
+       env.AppendUnique(TS = [name])
+
+def __append_target(ienv, target):
+       env.AppendUnique(TS = [target])
+
+def __print_targets(env):
+       Help('''
+===============================================================================
+Targets:\n    ''')
+       for t in env.get('TS'):
+               Help(t + ' ')
+       Help('''
+\nDefault all targets will be built. You can specify the target to build:
+
+    $ scons [options] [target]
+===============================================================================
+''')
+
+env.AddMethod(__set_dir, 'SetDir')
+env.AddMethod(__print_targets, 'PrintTargets')
+env.AddMethod(__src_to_obj, 'SrcToObj')
+env.AddMethod(__append_target, 'AppendTarget')
+env.AddMethod(__install, 'InstallTarget')
+env.SetDir(env.GetLaunchDir())
+env['ROOT_DIR']=env.GetLaunchDir()+'/..'
+
+Export('env')
+
+######################################################################
+# Link scons to Yocto cross-toolchain ONLY when target_os is yocto
+######################################################################
+if target_os == "yocto":
+    '''
+    This code injects Yocto cross-compilation tools+flags into scons'
+    build environment in order to invoke the relevant tools while
+    performing a build.
+    '''
+    import os.path
+    try:
+        CC = os.environ['CC']
+        target_prefix = CC.split()[0]
+        target_prefix = target_prefix[:len(target_prefix)-3]
+        tools = {"CC" : target_prefix+"gcc",
+                "CXX" : target_prefix+"g++",
+                "AS" : target_prefix+"as",
+                "LD" : target_prefix+"ld",
+                "GDB" : target_prefix+"gdb",
+                "STRIP" : target_prefix+"strip",
+                "RANLIB" : target_prefix+"ranlib",
+                "OBJCOPY" : target_prefix+"objcopy",
+                "OBJDUMP" : target_prefix+"objdump",
+                "AR" : target_prefix+"ar",
+                "NM" : target_prefix+"nm",
+                "M4" : "m4",
+                "STRINGS": target_prefix+"strings"}
+        PATH = os.environ['PATH'].split(os.pathsep)
+        for tool in tools:
+            if tool in os.environ:
+                for path in PATH:
+                    if os.path.isfile(os.path.join(path, tools[tool])):
+                        env[tool] = os.path.join(path, os.environ[tool])
+                        break
+        env['CROSS_COMPILE'] = target_prefix[:len(target_prefix) - 1]
+    except:
+        print "ERROR in Yocto cross-toolchain environment"
+        Exit(1)
+    '''
+    Now reset TARGET_OS to linux so that all linux specific build configurations
+    hereupon apply for the entirety of the build process.
+    '''
+    env['TARGET_OS'] = 'linux'
+    '''
+    We want to preserve debug symbols to allow BitBake to generate both DEBUG and
+    RELEASE packages for OIC.
+    '''
+    env.AppendUnique(CCFLAGS = ['-g'])
+    '''
+    Additional flags to pass to the Yocto toolchain.
+    '''
+    if env.get('RELEASE'):
+        env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+    if env.get('LOGGING'):
+        env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+    env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE'])
+    env.AppendUnique(CFLAGS = ['-std=gnu99'])
+    env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+    env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
+    Export('env')
+else:
+    '''
+    If target_os is not Yocto, continue with the regular build process
+    '''
+    # Load config of target os
+    if target_os in ['linux', 'tizen']:
+               env.SConscript('linux/SConscript')
+    else:
+               env.SConscript(target_os + '/SConscript')
+
+# Delete the temp files of configuration
+if env.GetOption('clean'):
+       dir = env.get('SRC_DIR')
+
+       if os.path.exists(dir + '/config.log'):
+               Execute(Delete(dir + '/config.log'))
+               Execute(Delete(dir + '/.sconsign.dblite'))
+               Execute(Delete(dir + '/.sconf_temp'))
+
+Return('env')
diff --git a/resource/csdk/connectivity/build/android/Makefile b/resource/csdk/connectivity/build/android/Makefile
new file mode 100644 (file)
index 0000000..038e36b
--- /dev/null
@@ -0,0 +1,19 @@
+#Assumes ndk directory is at ~/
+#set ndk directory PATH in .bashrc and use the ndk-build directly
+#change NDK_PATH to ${your_ndk_path}
+NDK_PATH = ~/ndk
+NDK_BUILD = $(NDK_PATH)/ndk-build
+
+BUILD_DIR = $(CURDIR)
+APPLICATION_BUILD = $(BUILD_DIR)
+ROOT_DIR = $(BUILD_DIR)
+
+#Clean files
+LIBS_DIR = $(ROOT_DIR)/libs
+OBJ_DIR = $(ROOT_DIR)/obj
+
+all:
+       $(NDK_BUILD) NDK_PROJECT_PATH=$(APPLICATION_BUILD)
+
+clean :
+       @$(RM) -rf $(LIBS_DIR) $(OBJ_DIR)
diff --git a/resource/csdk/connectivity/build/android/README.txt b/resource/csdk/connectivity/build/android/README.txt
new file mode 100644 (file)
index 0000000..10fb9a3
--- /dev/null
@@ -0,0 +1,17 @@
+Compiling Interface APIs FOR Android:
+===================================
+•Preconditons :
+       Please download the following
+       1) tinydlts library and keep at $(CA_HOME)/lib/tinydtls
+•Supported version : 5.0 ( Lollipop )
+•Required NDK version : android-ndk-r10d ( https://developer.android.com/tools/sdk/ndk/index.html )
+• Modify Makefile ( connectivity/build/android/Makefile )
+    $ cd ${CA_HOME}/connectivity/build/android
+    $ vi Makefile
+  #  Change the NDK_PATH
+    NDK_PATH = ${your_ndk_path}
+ Build : $(CA_HOME)/build/android/Makefile
+    $ cd ${CA_HOME}/connectivity/build/android
+    $ ndk-build clean; ndk-build
+
+
diff --git a/resource/csdk/connectivity/build/android/SConscript b/resource/csdk/connectivity/build/android/SConscript
new file mode 100644 (file)
index 0000000..32880e7
--- /dev/null
@@ -0,0 +1,184 @@
+##
+# This script includes android specific config (GNU GCC)
+##
+import os
+import platform
+import subprocess
+
+Import('env')
+
+help_vars = Variables()
+help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK root directory', os.environ.get('ANDROID_NDK')))
+help_vars.Update(env)
+Help(help_vars.GenerateHelpText(env))
+
+android_ndk = env.get('ANDROID_NDK')
+if not android_ndk:
+       print '''
+*************************************** Error *********************************
+*    Android NDK path isn't set, you can set enviornment variable ANDROID_NDK *
+* or add it in command line as:                                               *
+*      # scons ANDROID_NDK=<path to android NDK> ...                          *
+*******************************************************************************
+'''
+       Exit(1)
+
+# Overwrite suffixes and prefixes
+if env['HOST_OS'] == 'win32':
+       env['OBJSUFFIX'] = '.o'
+       env['SHOBJSUFFIX'] = '.os'
+       env['LIBPREFIX'] = 'lib'
+       env['LIBSUFFIX'] = '.a'
+       env['SHLIBPREFIX'] = 'lib'
+       env['SHLIBSUFFIX'] = '.so'
+       env['LIBPREFIXES'] = ['lib']
+       env['LIBSUFFIXES'] = ['.a', '.so']
+       env['PROGSUFFIX'] = ''
+elif platform.system().lower() == 'darwin':
+       env['SHLIBSUFFIX'] = '.so'
+       env['LIBSUFFIXES'] = ['.a', '.so']
+       env['PROGSUFFIX'] = ''
+
+######################################################################
+# Set common flags
+######################################################################
+
+# Android build system default cofig
+env.AppendUnique(CPPDEFINES = ['ANDROID'])
+env.AppendUnique(CFLAGS = ['-std=c99'])
+env.AppendUnique(SHCFLAGS = ['-Wa,--noexecstack'])
+env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections', '-Wl,-z,nocopyreloc'])
+
+######################################################################
+# Probe Android NDK default flags
+######################################################################
+ndk_build_cmd = android_ndk + '/ndk-build'
+if env['HOST_OS'] == 'win32':
+       if os.path.isfile(ndk_build_cmd + '.cmd'):
+               ndk_build_cmd += '.cmd'
+
+if not os.path.isfile(ndk_build_cmd):
+       print '''
+*************************************** Error *********************************
+*   It seems android ndk path is not set properly, please check if "%s"
+* is the root directory of android ndk.                                       *
+*******************************************************************************
+''' % android_ndk
+       Exit(1)
+
+ANDROID_HOME = os.environ.get('ANDROID_HOME')
+if ANDROID_HOME is not None:
+       ANDROID_HOME = os.path.abspath(ANDROID_HOME)
+
+if ANDROID_HOME is None or not os.path.exists(ANDROID_HOME):
+       print '''
+*************************************** Warning *******************************
+*   Enviornment variable ANDROID_HOME is not set properly. It should be the   *
+* root directory of android sdk. If you'd like build Java code, it's required.*
+*******************************************************************************
+'''
+
+target_arch = env.get('TARGET_ARCH')
+
+# Android ndk early version doesn't support C++11. Detect the toolchain version
+# to make sure proper toolchain is used
+for tc_ver in ['4.7', '4.8', '4.9', '']:
+       if os.path.exists(android_ndk + '/toolchains/x86-' + tc_ver):
+               break
+
+cmd = [ndk_build_cmd]
+cmd.append('APP_ABI=' + target_arch)
+cmd.append('APP_STL=gnustl_shared')
+if env.get('RELEASE'):
+       cmd.append('APP_OPTIM=release')
+else:
+       cmd.append('APP_OPTIM=debug')
+if tc_ver != '':
+       cmd.append('NDK_TOOLCHAIN_VERSION=' + tc_ver)
+else:
+       print '''
+*************************************** Warning *******************************
+*   To support C++11, the toolchain should be >= 4.7, please make sure your   *
+* android NDK is at least r8e!                                                *
+*******************************************************************************
+'''
+
+cmd.append('-n')
+
+p = subprocess.Popen(cmd, stdout = subprocess.PIPE)
+
+for flags in p.stdout.readlines():
+       if cmp(flags[0:10], 'TC_PREFIX=') == 0: # toolchain prefix (include path)
+               prefix = flags[10:].strip()
+               env.Replace(CC = prefix + 'gcc')
+               env.Replace(CXX = prefix + 'g++')
+               env.Replace(AR = prefix + 'ar')
+               env.Replace(RANLIB = prefix + 'ranlib')
+
+       elif cmp(flags[0:7], 'CFLAGS=') == 0:
+               env.AppendUnique(CFLAGS = Split(flags[7:]))
+
+       elif cmp(flags[0:9], 'CXXFLAGS=') == 0:
+               env.AppendUnique(CXXFLAGS = Split(flags[9:]))
+
+       elif cmp(flags[0:8], 'CPPPATH=') == 0:
+               env.AppendUnique(CPPPATH = Split(flags[8:]))
+
+       elif cmp(flags[0:8], 'SYSROOT=') == 0:
+               sysroot = flags[8:].strip()
+               env.AppendUnique(LINKFLAGS = ['--sysroot=' + sysroot])
+               env.AppendUnique(LIBPATH = [sysroot + '/usr/lib'])
+
+       elif cmp(flags[0:8], 'LDFLAGS=') == 0:
+               env.AppendUnique(LINKFLAGS = Split(flags[8:]))
+
+       elif cmp(flags[0:7], 'TC_VER=') == 0:  # set gnustl library path
+               ver = flags[7:].strip()
+               env.AppendUnique(LIBPATH = [android_ndk + '/sources/cxx-stl/gnu-libstdc++/'
+                               + ver + '/libs/' + target_arch])
+
+       elif cmp(flags[0:9], 'PLATFORM=') == 0:  # get target platform: android-x
+               platform_ver = flags[9+8:].strip()
+               if not platform_ver.isdigit():
+                       platform_ver = ''
+
+# Determine dependency faux SYS_ROOT
+dep_sys_root = os.path.join(env.get('SRC_DIR'), 'dep', 'android', target_arch, 'usr')
+dep_src_dir =  os.path.join(dep_sys_root, 'include')
+dep_lib_dir =  os.path.join(dep_sys_root, 'lib')
+
+env['DEP_SYS_ROOT'] = dep_sys_root
+
+# Add external libraries including boost
+env.AppendUnique(CPPPATH = [ dep_src_dir ])
+env.AppendUnique(LIBPATH = [ dep_lib_dir ])
+
+######################################################################
+# Set release/debug flags
+######################################################################
+if env.get('RELEASE'):
+       env.AppendUnique(CCFLAGS = ['-Os'])
+       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+       env.AppendUnique(LINKFLAGS = ['-s'])
+else:
+       env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+        env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__ANDROID__'])
+env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+#env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
+
+env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+src_dir = env.get('SRC_DIR')
+env.AppendUnique(LIBPATH = [src_dir + '/lib/android'])
+env.AppendUnique(LIBS = ['log', 'coap'])
+if env.get('SECURED') == '1':
+       env.AppendUnique(LIBS = ['tinydtls'])
+
+# From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'.
+# Due to the limitation of Scons, it's required to added it into the command line
+# directly (otherwise, it will also be added when build share library)
+env.Replace(CCCOM = '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES')
+env.Replace(CXXCOM = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES')
diff --git a/resource/csdk/connectivity/build/android/jni/Android.mk b/resource/csdk/connectivity/build/android/jni/Android.mk
new file mode 100644 (file)
index 0000000..54233f6
--- /dev/null
@@ -0,0 +1,162 @@
+$(info TC_PREFIX=$(TOOLCHAIN_PREFIX))
+$(info CFLAGS=$(TARGET_CFLAGS))
+$(info CXXFLAGS=$(TARGET_CXXFLAGS) $(TARGET_NO_EXECUTE_CFLAGS))
+$(info CPPPATH=$(TARGET_C_INCLUDES) $(__ndk_modules.$(APP_STL).EXPORT_C_INCLUDES))
+$(info SYSROOT=$(SYSROOT_LINK))
+$(info LDFLAGS=$(TARGET_LDFLAGS) $(TARGET_NO_EXECUTE_LDFLAGS) $(TARGET_NO_UNDEFINED_LDFLAGS) $(TARGET_RELRO_LDFLAGS))
+$(info TC_VER=$(TOOLCHAIN_VERSION))
+$(info PLATFORM=$(APP_PLATFORM))
+
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#define build type
+BUILD = debug
+
+PROJECT_ROOT_PATH                       ?= ../..
+EXT_LIB_PATH                            = ../../../../../../extlibs
+PROJECT_API_PATH                        = $(PROJECT_ROOT_PATH)/api
+PROJECT_INC_PATH                        = $(PROJECT_ROOT_PATH)/inc
+PROJECT_SRC_PATH                        = $(PROJECT_ROOT_PATH)/src
+PROJECT_COMMON_PATH                     = $(PROJECT_ROOT_PATH)/common
+PROJECT_COMMON_INC_PATH                 = $(PROJECT_COMMON_PATH)/inc
+PROJECT_COMMON_SRC_PATH                 = $(PROJECT_COMMON_PATH)/src
+PROJECT_LIB_PATH                        = $(PROJECT_ROOT_PATH)/lib
+PROJECT_EXTERNAL_PATH                   = $(PROJECT_ROOT_PATH)/external/inc
+DTLS_LIB                                = $(EXT_LIB_PATH)/tinydtls
+#GLIB_PATH                               = ../../../../../../extlibs/glib/glib-2.40.2
+
+#Modify below values to enable/disable the Adapter
+#Suffix "NO_" to disable given adapter
+EDR             = EDR_ADAPTER
+IP              = IP_ADAPTER
+LE              = LE_ADAPTER
+
+#Add Pre processor definitions
+DEFINE_FLAG =  -DWITH_POSIX -D__ANDROID__
+DEFINE_FLAG =  -D__WITH_DTLS__
+DEFINE_FLAG += -D$(EDR) -D$(LE) -D$(IP)
+
+#Add Debug flags here
+DEBUG_FLAG      = -DTB_LOG
+
+BUILD_FLAG.debug        = $(DEFINE_FLAG) $(DEBUG_FLAG)
+BUILD_FLAG.release      =       $(DEFINE_FLAG)
+BUILD_FLAG = $(BUILD_FLAG.$(BUILD))
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#include glib
+
+#include $(CLEAR_VARS)
+#LOCAL_PATH = $(PROJECT_LIB_PATH)/android
+#LOCAL_MODULE = Glib
+#LOCAL_SRC_FILES := libglib-2.40.2.so
+#LOCAL_EXPORT_C_INCLUDES = $(GLIB_PATH) \
+#                          $(GLIB_PATH)/glib
+#
+#include $(PREBUILT_SHARED_LIBRARY)
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#include glibthread
+
+#include $(CLEAR_VARS)
+#LOCAL_PATH = $(PROJECT_LIB_PATH)/android
+#LOCAL_MODULE = GLibThread
+#LOCAL_SRC_FILES := libgthread-2.40.2.so
+#LOCAL_EXPORT_C_INCLUDES = $(GLIB_PATH) \
+#                          $(GLIB_PATH)/glib
+#
+#include $(PREBUILT_SHARED_LIBRARY)
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#Build TinyDtls
+
+include $(CLEAR_VARS)
+include $(DTLS_LIB)/Android.mk
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#Build CACommon
+
+include $(CLEAR_VARS)
+
+#Build Common Libraries
+LOCAL_PATH = $(PROJECT_COMMON_SRC_PATH)
+LOCAL_MODULE = CACommon
+LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
+#LOCAL_SHARED_LIBRARIES = Glib GLibThread
+LOCAL_STATIC_LIBRARIES = rt pthread
+
+LOCAL_CFLAGS = -D__ANDROID__ $(DEBUG_FLAG)
+LOCAL_CFLAGS += -std=c99
+
+LOCAL_C_INCLUDES = $(PROJECT_COMMON_INC_PATH)
+LOCAL_C_INCLUDES += $(PROJECT_API_PATH)
+
+LOCAL_SRC_FILES =       oic_logger.c \
+                        oic_console_logger.c logger.c oic_malloc.c \
+                        uarraylist.c uqueue.c oic_string.c \
+                        cathreadpool_pthreads.c camutex_pthreads.c
+
+include $(BUILD_STATIC_LIBRARY)
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#Build CACoap
+
+include $(CLEAR_VARS)
+
+LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
+LOCAL_PATH = $(PROJECT_LIB_PATH)/libcoap-4.1.1
+LOCAL_MODULE = CACoap
+LOCAL_EXPORT_C_INCLUDES = $(PROJECT_LIB_PATH)/libcoap-4.1.1
+LOCAL_CFLAGS = -DWITH_POSIX
+LOCAL_SRC_FILES = pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \
+                                        str.c option.c async.c subscribe.c block.c
+
+include $(BUILD_STATIC_LIBRARY)
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#Build CA
+
+#Relative path to LOCAL_PATH (PROJECT_SRC_PATH)
+LOCAL_PLATFORM                          = android
+
+ENET_ADAPTER_PATH                       = ethernet_adapter/$(LOCAL_PLATFORM)
+EDR_ADAPTER_PATH                        = bt_edr_adapter/$(LOCAL_PLATFORM)
+LE_ADAPTER_PATH                         = bt_le_adapter/$(LOCAL_PLATFORM)
+IP_ADAPTER_PATH                         = ip_adapter
+ADAPTER_UTILS                           = adapter_util
+
+include $(CLEAR_VARS)
+
+LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
+LOCAL_PATH = $(PROJECT_SRC_PATH)
+LOCAL_MODULE = CA
+
+LOCAL_STATIC_LIBRARIES = CACommon CACoap TinyDtls
+
+LOCAL_C_INCLUDES = $(PROJECT_API_PATH)
+LOCAL_C_INCLUDES += $(PROJECT_COMMON_INC_PATH)
+LOCAL_C_INCLUDES += $(PROJECT_INC_PATH)
+LOCAL_C_INCLUDES += $(PROJECT_LIB_PATH)/libcoap-4.1.1
+LOCAL_C_INCLUDES += $(PROJECT_EXTERNAL_PATH)
+LOCAL_C_INCLUDES += $(DTLS_LIB)
+
+LOCAL_CFLAGS += $(BUILD_FLAG)
+LOCAL_CFLAGS += -std=c99 -DWITH_POSIX
+
+LOCAL_SRC_FILES = \
+                caconnectivitymanager.c caremotehandler.c cainterfacecontroller.c \
+                camessagehandler.c canetworkconfigurator.c caprotocolmessage.c \
+                caretransmission.c caqueueingthread.c \
+                $(ADAPTER_UTILS)/caadapternetdtls.c $(ADAPTER_UTILS)/caadapterutils.c \
+                $(ADAPTER_UTILS)/camsgparser.c \
+                bt_le_adapter/caleadapter.c $(LE_ADAPTER_PATH)/caleclient.c \
+                $(LE_ADAPTER_PATH)/caleserver.c $(LE_ADAPTER_PATH)/caleutils.c \
+                $(LE_ADAPTER_PATH)/calenwmonitor.c \
+                bt_edr_adapter/caedradapter.c $(EDR_ADAPTER_PATH)/caedrutils.c \
+                $(EDR_ADAPTER_PATH)/caedrclient.c $(EDR_ADAPTER_PATH)/caedrserver.c \
+                $(EDR_ADAPTER_PATH)/caedrnwmonitor.c \
+                $(IP_ADAPTER_PATH)/caipadapter.c $(IP_ADAPTER_PATH)/caipserver.c \
+                $(IP_ADAPTER_PATH)/caipclient.c $(IP_ADAPTER_PATH)/android/caipnwmonitor.c \
+
+include $(BUILD_STATIC_LIBRARY)
+
diff --git a/resource/csdk/connectivity/build/android/jni/Application.mk b/resource/csdk/connectivity/build/android/jni/Application.mk
new file mode 100644 (file)
index 0000000..1de4715
--- /dev/null
@@ -0,0 +1,9 @@
+#Specify Android.mk path w.r.t APPLICATION_BUILD in the Makefile
+APP_PROJECT_PATH = ./
+
+APP_STL = gnustl_shared
+APP_MODULES := CA
+APP_PLATFORM = android-21
+APP_CPPFLAGS += -fexceptions
+APP_CPPFLAGS += -frtti += -Wno-error=format-security
+APP_CFLAGS = -Wno-error=format-security
diff --git a/resource/csdk/connectivity/build/arduino/Arduino_Setup_README.txt b/resource/csdk/connectivity/build/arduino/Arduino_Setup_README.txt
new file mode 100644 (file)
index 0000000..359ded0
--- /dev/null
@@ -0,0 +1,54 @@
+STEPS to setup Arduino on linux machine for building CA code:
+
+1) Download the Arduino package as per your system specification from the given link :
+       http://arduino.cc/en/main/software
+
+2) Unzip the downloaded package to some location say ARDUINO_DIR(This is the arduino installation directory).
+       ARDUINO_DIR = <PATH_TO_ARDUINO_INSTALL_DIR>/arduino-1.5.x
+
+3) Change permissions for executable in your "ARDUINO_DIR"
+               chmod -R +x <ARDUINO_DIR>
+
+4.1) ONE TIME ONLY - ADDITIONAL LIBRARIES (Time)
+       Arduino builds are dependent on latest Time library. Download it from here:
+               I. http://playground.arduino.cc/uploads/Code/Time.zip
+       Place this library in the "ARDUINO_DIR/libraries/Time" folder where other libraries are present.
+               [P.S - The Time library files path should be as follows "ARDUINO_DIR/libraries/Time/Time/{***files***}"]
+       Some files in this library has windows style line endings, for patch to run properly, please execute following command:
+               cd <ARDUINO_DIR>
+               find ./libraries/Time/ -type f -exec dos2unix {} \;
+
+4.2) ONE TIME ONLY - ADDITIONAL LIBRARIES (BLE)
+       Note: Prior to building for BLE Transport, following additional steps are required:
+       (1) Download RedBearLab Arduino RBL_nRF8001 Library from link(https://github.com/RedBearLab/nRF8001/archive/25643e7b1b7da3740406325a471e3faa4b948747.zip)
+       (2) Extract zip file and apply RBL patch(connectivity/lib/arduino/RBL_nRF8001.patch) to "RBL_nRF8001" folder by following below steps,
+               i)  Go to downloaded RBL_Library Folder ("nRF8001-master/Arduino/libraries/RBL_nRF8001")
+               ii) Apply dos2unix for RBL_Library Folder and RBL Patch File (RBL_nRF8001.patch), if we have downloaded Library in Non UNIX Platform.
+               iii) Apply RBL Patch[connectivity\lib\arduino\RBL_nRF8001.patch] by using the below command
+                       patch -p1 < RBL_Patch_File_Location(RBL_nRF8001.patch)
+       (3) Copy the patched RBL_nRF8001 Library and place it in "arduino-<x.x.x>/libraries" folder
+       (4) Download Nordic Arduino BLE library [Tag: "0.9.5.Beta" Version] from the link (https://github.com/NordicSemiconductor/ble-sdk-arduino/archive/0.9.5.beta.zip).
+               Extract the zip file and copy the "BLE" folder available under "libraries" folder and place it in "arduino-<x.x.x>/libraries" folder
+               i)  Apply dos2unix for the "BLE" folder.
+               ii) Go to the BLE folder and apply the patch[connectivity\lib\arduino\arduino_due_ble.patch] using the below command.
+                       patch -p1 < path/to/arduino_due_ble.patch
+
+5) ONE TIME ONLY - PATCH
+       Complete patch has been provided at : "connectivity\lib\arduino\arduino_libraries.patch"
+               Copy this patch file to "ARDUINO_DIR/"
+
+6) To apply patch give the command :
+               patch -p1 < arduino_libraries.patch
+       To undo the patch give the command :
+               patch -R -p1 < arduino_libraries.patch
+
+7) ONE TIME ONLY - FIRMWARE UPGRADE (FOR WIFI SHIELD)
+       To support UDP over WiFi, WiFi shield needs to run latest firmware. Please refer:
+       (http://arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading)
+       for instructions on how to upgrade your firmware.
+
+8) Launch Arduino IDE (required for logs and port and board selection.)
+       Goto to "ARDUINO_DIR" directory.
+       Launch command := sudo ./arduino
+
+9) Select your board and port under the tools option in Arduino IDE.
diff --git a/resource/csdk/connectivity/build/arduino/Makefile b/resource/csdk/connectivity/build/arduino/Makefile
new file mode 100644 (file)
index 0000000..7524a33
--- /dev/null
@@ -0,0 +1,75 @@
+#
+# override with `make BUILD=debug`
+# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
+# TRANSPORT can be ETHERNET, WIFI, BT, BLE. Include Corresponding Transport during compilation. For Eg: `make PLATFORM=arduinomega TRANSPORT=BLE
+# default to release build
+# default to build for arduinomega
+# default to build for BLE Transport
+BUILD   := release
+PLATFORM := arduinomega
+TRANSPORT := BLE
+OBJ_DIR := ./bin
+APP_NAME := casample
+ARDUINO_PORT := ttyACM0
+
+include ./local.properties
+include ./$(PLATFORM).properties
+
+VPATH := $(SDIR_ARD_PLATFORM)
+
+#Include __ARDUINO_BLE__ flag for BLE Transport. Currently, BLE Sample APP is segregated with this MACRO
+ifeq ($(TRANSPORT),BLE)
+CFLAGS         := -Os -Wall -c -DTB_LOG -DOIC_ARDUINODUE -DINTERFACESAMPLE_ARDUINO -DARDUINO -DOIC_ARDUINODUE -D__ARDUINO__ -DWITH_ARDUINO -D__ARDUINO_BLE__ -DLE_ADAPTER
+else ifeq ($(TRANSPORT),WIFI)
+CFLAGS         := -Os -Wall -c -DTB_LOG -DOIC_ARDUINODUE -DINTERFACESAMPLE_ARDUINO -DARDUINO -DOIC_ARDUINODUE -D__ARDUINO__ -DWITH_ARDUINO -DWIFI_ADAPTER
+else
+CFLAGS         := -Os -Wall -c -DTB_LOG -DOIC_ARDUINODUE -DINTERFACESAMPLE_ARDUINO -DARDUINO -DOIC_ARDUINODUE -D__ARDUINO__ -DWITH_ARDUINO -DETHERNET_ADAPTER
+endif
+
+all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
+
+$(info *********PLATFORM_OBJS!!**********)
+core.a: $(PLATFORM_OBJS)
+       @cd $(OBJ_DIR) && $(AR) -x ../../../lib/libcoap-4.1.1/$(BUILD)/libcoap.a
+       $(AR) rcs $@ $(CORE_COBJ) $(CORE_CPPOBJ) $(PLATFORM_OBJS) $(OBJ_DIR)/*.o
+       $(RANLIB) $@
+
+prep_dirs:
+       -mkdir $(OBJ_DIR)
+
+logger.c.o: logger.c
+       $(CCPLUS) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+%.c.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+%.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+%.o: %.cpp
+       $(CCPLUS) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+%.cpp.o: %.cpp
+       $(CCPLUS) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+# core.a and $(APP_NAME).cpp.o are combined to generate $(APP_NAME).elf.
+# For Integration with Top Layer, we can link top layer with core.a
+$(APP_NAME).elf: $(APP_NAME).cpp.o core.a
+       $(CC) -w -Os -Wl,--gc-sections,--relax -mmcu=atmega2560 -o $@ $^ -L$(ARDUINO_DIR)/libraries -lm
+
+$(APP_NAME).hex: $(APP_NAME).elf
+       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(APP_NAME).eep
+       $(AVR_OBJCOPY) -O ihex -R .eeprom $< $@
+
+install: all
+       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i
+
+
+.PHONY: clean
+clean:
+       @rm -f *.o *.d *.elf *.eep core.a *.hex *.bin *.map *-
+       @rm -rf $(OBJ_DIR)
+
+
+
+
diff --git a/resource/csdk/connectivity/build/arduino/README.txt b/resource/csdk/connectivity/build/arduino/README.txt
new file mode 100644 (file)
index 0000000..17bff7d
--- /dev/null
@@ -0,0 +1,20 @@
+BUILDING for ARDUINOMEGA:
+========================================
+PREREQ: Arduino MUST be installed in the machine where we compile. Refer to Arduino_Setup_README file for help.
+
+1) Go to "connectivity\build\arduino" directory, Open Makefile and change ARDUINO_PORT according to the PORT selected in ARDUINO IDE.
+2) BUILD : Go to "connectivity\build" directory. To build for a specific TRANSPORT [ETHERNET,BLE,WIFI], use the following command :
+       sudo make PLATFORM=arduinomega TRANSPORT=<ETHERNET/BLE/WIFI> ARDUINO_DIR = <PATH_TO_ARDUINO_INSTALL_DIR>/arduino-1.5.x
+       P.S : For PATH_TO_ARDUINO_INSTALL_DIR value refer Arduino_Setup_README.txt file.
+
+Flashing Interface APIs for ARDUINOMEGA:
+========================================
+Precondition: Connect Arduino Mega Board to Linux PC. Open Arduino IDE and select corresponding connected PORT
+1) To Install, connect the ArduinoMega Board with corresponding Shields to Linux PC.
+2) Perform sudo make install PLATFORM=arduinomega TRANSPORT=BLE
+   It will flash BLE Transport Adaptor in Arduino Board. Similarly, TRANSPORT can be changed to ETHERNET, BLE, WIFI etc..
+
+To Run Adapter code in ARDUINOMEGA Board:
+========================================
+PreCondition: Flash the executable in ARDUINO MEGA BOARD. Follow above Step(Flashing Interface APIs for ARDUINOMEGA)
+1) Open Serial Monitor in Arduino IDE. It will execute the flashed binary and logs will be available in serial Monitor under BaudRate(115200)
diff --git a/resource/csdk/connectivity/build/arduino/SConscript b/resource/csdk/connectivity/build/arduino/SConscript
new file mode 100644 (file)
index 0000000..d97d596
--- /dev/null
@@ -0,0 +1,438 @@
+##
+# This script includes arduino specific config
+##
+import os
+import platform
+
+Import('env')
+
+def __parse_config(f):
+       dict = {}
+
+       if not os.path.isfile(f):
+               return dict
+
+       file = open(f, 'r')
+       strs = file.readlines()
+       for str in strs:
+               str = str.strip()
+               if len(str) > 0 and str[0] == '#':
+                       continue
+
+               idx = str.find('=')
+               if idx > 0:
+                       dict.setdefault(str[0:idx], str[idx + 1:])
+
+       return dict
+
+def __get_boards(dict):
+       boards = []
+       keys = dict.keys()
+       for key in keys:
+               idx = key.find('.name')
+               if idx > 0:
+                       if key.endswith('.name'):
+                               boards.append(key[0:idx])
+       return boards
+
+def __get_cpu(dict, board):
+       cpus = []
+       keys = dict.keys()
+       for key in keys:
+               idx = key.find(board + '.menu.cpu.')
+               start = len(board + '.menu.cpu.')
+               if idx >= 0:
+                       end = key.find('.', start)
+                       if end > 0:
+                               cpu = key[start:end]
+                               exist = False
+                               for c in cpus:
+                                       if c == cpu:
+                                               exist = True
+                                               break
+
+                               if not exist:
+                                       cpus.append(cpu)
+       return cpus
+
+def __get_board_info(board, key):
+       if cpu:
+               v = boards_info.get(board + '.menu.cpu.' + cpu + key)
+               if not v:
+                       v = boards_info.get(board + key)
+       else:
+               v = boards_info.get(board + key)
+       return v
+
+def __search_files(path, pattern, ondisk=True, source=True, strings=False, recursive=True):
+       if not recursive:
+               return Glob(pattern, ondisk, source, strings)
+
+       matches = []
+       for root, dirnames, filenames in os.walk(path):
+               #BLE library examples throw lot of errors. We dont need examples.
+               if 'examples' not in root:
+                       matches.extend(Glob(root + '/' + pattern, ondisk, source, strings))
+       return matches
+
+# To make sure the src is built in 'BUILD_DIR' (by default it will be built at
+# the same directory as the .c .cpp .S)
+def __src_to_obj(env, srcs):
+       objs = []
+       prefix = env.get('BOARD') + '_'
+       if env.get('CPU'):
+               prefix += env.get('CPU') + '_'
+
+       build_dir = env.get('BUILD_DIR') + '/arduino/'
+       for src in srcs:
+               obj = src.path.replace(arduino_home, build_dir)
+               i = obj.rfind('.')
+               obj = obj[0:i]
+               if env.get('OBJSUFFIX'):
+                       obj += env.get('OBJSUFFIX')
+               objs.extend(env.Object(obj, src, OBJPREFIX=prefix))
+       return objs
+
+def __import_lib(env, lib):
+       lib_path = arduino_home + '/libraries/' + lib
+       if not os.path.exists(lib_path):
+               if target_arch == 'avr':
+                       lib_path = arduino_home + '/hardware/arduino/avr/libraries/' + lib
+               else:
+                       lib_path = arduino_home + '/hardware/arduino/sam/libraries/' + lib
+
+       if os.path.exists(lib_path + '/src'):
+               lib_path = lib_path + '/src'
+
+       env.AppendUnique(CPPPATH = [lib_path])
+
+       if os.path.exists(lib_path + '/utility'):
+               env.AppendUnique(CPPPATH = [lib_path + '/utility'])
+
+       lib_src = []
+       lib_src.extend(__search_files(lib_path, '*.S'))
+       lib_src.extend(__search_files(lib_path, '*.c'))
+       lib_src.extend(__search_files(lib_path, '*.cpp'))
+
+       lib_obj = __src_to_obj(env, lib_src)
+       build_dir = env.get('BUILD_DIR')
+       if build_dir:
+               lib_a = env.StaticLibrary(build_dir + lib, lib_obj)
+       else:
+               lib_a = env.StaticLibrary(lib, lib_obj)
+
+       # If we link libSPI.a, the final binary is not getting launched
+       # on the board.  Which is not the case if we directly use SPI.o.
+
+       if env.get('TARGET_ARCH') == 'arm':
+               if lib == 'SPI':
+                       for obj in lib_obj:
+                               if obj.name.endswith('SPI.o'):
+                                       env.PrependUnique(LIBS = [File(obj)])
+               else:
+                       env.AppendUnique(LIBS = [File(lib_a[0])])
+       else:
+               env.PrependUnique(LIBS = [File(lib_a[0])])
+
+def __build_core(env):
+       core_src = __search_files(core_folder, '*.S')
+       core_src.extend(__search_files(core_folder, '*.c'))
+       core_src.extend(__search_files(core_folder, '*.cpp'))
+
+       core_src.extend(__search_files(variant_folder, '*.S'))
+       core_src.extend(__search_files(variant_folder, '*.c'))
+       core_src.extend(__search_files(variant_folder, '*.cpp'))
+
+       core_obj = __src_to_obj(env, core_src)
+       build_dir = env.get('BUILD_DIR')
+       if build_dir:
+               s_core = env.StaticLibrary(build_dir + 'core', core_obj)
+       else:
+               s_core = env.StaticLibrary('core', core_obj)
+       env.AppendUnique(LIBS = [File(s_core[0])])
+
+       # To avoid compiler issue. Otherewise there may be warnings:
+       #       undefined reference to '_exit' '_close', '_getpid' ...
+       # Above functions are used in libc.a and implemented in syscalls_sam3.c
+       if env.get('TARGET_ARCH') == 'arm':
+               for obj in core_obj:
+                       if obj.name.endswith('syscalls_sam3.o'):
+                               env.AppendUnique(LIBS = [File(obj)])
+
+def __create_bin(env, source):
+       name = source
+       if target_arch == 'avr':
+               eep = env.Command(name + '.eep', source, 'avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $SOURCE $TARGET')
+               hex = env.Command(name + '.hex', source, 'avr-objcopy -O ihex -R .eeprom $SOURCE $TARGET')
+       else:
+               hex = env.Command(name + '.hex', source, 'arm-none-eabi-objcopy -O binary $SOURCE $TARGET')
+
+#Currently Mega and Due build is supported.
+def __upload(env, binary):
+        if target_arch == 'avr':
+                protocol = __get_board_info(board, '.upload.protocol')
+                speed = __get_board_info(board, '.upload.speed')
+                port = '/dev/ttyACM0'
+                upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
+                + mcu + ' -c' + protocol + ' -P' + port + ' -b' + speed + ' -D -Uflash:w:' + binary + ':i'
+
+                print "Upload command: %s" %upload_cmd
+                install_cmd = env.Command('install_cmd', None, upload_cmd)
+                env.Default('install_cmd')
+        else:
+               uu = __get_board_info(board, '.upload.native_usb')
+                port = 'ttyACM0'
+               upload_cmd = 'stty -F /dev/' + port + ' speed 1200 cs8 -cstopb -parenb \n' + arduino_home + '/hardware/tools/bossac -i -d --port=' + port + ' -U ' + uu + ' -e -w -v -b ' + binary + ' -R'
+                print "Upload command: %s" %upload_cmd
+                install_cmd = env.Command('install_cmd', None, upload_cmd)
+                env.Default('install_cmd')
+
+# Print the command line that to upload binary to the board
+def __upload_help(env):
+       if target_arch == 'avr':
+               protocol = __get_board_info(board, '.upload.protocol')
+               speed = __get_board_info(board, '.upload.speed')
+
+               upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
+       + mcu + ' -c' + protocol + ' -P<serial_port>' + ' -b' + speed + ' -D -Uflash:w:<hex_file>:i'
+       else:
+               uu = __get_board_info(board, '.upload.native_usb')
+               upload_cmd = arduino_home + '/hardware/tools/bossac -i -d --port=<serial_port> -U ' + uu + ' -e -w -v -b <bin file> -R'
+
+       Help('''
+===============================================================================
+You can upload the bin file with following command line:
+''')
+       Help('\n   $ ' + upload_cmd)
+       Help('''
+\nPlease replace <xxx> according to the actual situation.
+===============================================================================
+''')
+
+# ARDUINO_HOME build option
+help_vars = Variables()
+help_vars.Add(PathVariable('ARDUINO_HOME', 'ARDUINO root directory', os.environ.get('ARDUINO_HOME')))
+help_vars.Update(env)
+Help(help_vars.GenerateHelpText(env))
+
+target_arch = env.get('TARGET_ARCH')
+arduino_home = env.get('ARDUINO_HOME')
+if not arduino_home:
+       print '''
+************************************* Error ***********************************
+*   Arduino root directory isn't set, you can set enviornment variable        *
+* ARDUINO_HOME or add it in command line as:                                  *
+*      # scons ARDUINO_HOME=<path to arduino root directory> ...              *
+*******************************************************************************
+'''
+       Exit(1)
+
+# Overwrite suffixes and prefixes
+if env['HOST_OS'] == 'win32':
+       env['OBJSUFFIX'] = '.o'
+       env['SHOBJSUFFIX'] = '.os'
+       env['LIBPREFIX'] = 'lib'
+       env['LIBSUFFIX'] = '.a'
+       env['SHLIBPREFIX'] = 'lib'
+       env['SHLIBSUFFIX'] = '.so'
+       env['LIBPREFIXES'] = ['lib']
+       env['LIBSUFFIXES'] = ['.a', '.so']
+       env['PROGSUFFIX'] = ''
+elif platform.system().lower() == 'darwin':
+       env['SHLIBSUFFIX'] = '.so'
+       env['LIBSUFFIXES'] = ['.a', '.so']
+       env['PROGSUFFIX'] = ''
+
+# Debug/release relative flags
+if env.get('RELEASE'):
+       env.AppendUnique(CCFLAGS = ['-Os'])
+       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+       env.AppendUnique(CCFLAGS = ['-g'])
+
+# BOARD / CPU option
+
+# Get IDE version
+if os.path.exists(arduino_home + '/lib/version.txt'):
+       vf = open(arduino_home + '/lib/version.txt', 'r')
+       version = vf.readline().replace('.', '')
+else:
+       print '''
+************************************* Error ***********************************
+* Can't find version file (lib/version.txt), please check if (%s)
+* is arduino root directory.                                                  *
+*******************************************************************************
+''' % arduino_home
+       Exit(1)
+
+if version[0:2] == '10':
+       is_1_0_x = True
+       boards_info = __parse_config(arduino_home + '/hardware/arduino/boards.txt')
+       env.PrependENVPath('PATH', arduino_home + '/hardware/tools/avr/bin/')
+       env.Replace(CC = 'avr-gcc')
+       env.Replace(CXX = 'avr-gcc')
+       env.Replace(AR = 'avr-ar')
+       env.Replace(AS = 'avr-as')
+       env.Replace(LINK = 'avr-gcc')
+       env.Replace(RANLIB = 'avr-ranlib')
+       if target_arch != 'avr':
+               print '''
+************************************* Error ***********************************
+* Arduino 1.0.x IDE only support 'avr', to support other arch at least 1.5.x  *
+* is required.
+*******************************************************************************
+'''
+               Exit(1)
+else:
+       is_1_0_x = False
+       if target_arch == 'avr':
+               boards_info = __parse_config(arduino_home + '/hardware/arduino/avr/boards.txt')
+               platform_info = __parse_config(arduino_home + '/hardware/arduino/avr/platform.txt')
+       elif target_arch == 'arm':
+               boards_info = __parse_config(arduino_home + '/hardware/arduino/sam/boards.txt')
+               platform_info = __parse_config(arduino_home + '/hardware/arduino/sam/platform.txt')
+       else:
+               print '''
+************************************* Error ***********************************
+* CPU arch %s isn't supported currently.
+*******************************************************************************
+''' % target_arch
+
+#Board option, let user to select the board
+boards = __get_boards(boards_info)
+help_vars = Variables()
+help_vars.Add(EnumVariable('BOARD', 'arduino board', boards[0], boards))
+help_vars.Update(env)
+Help(help_vars.GenerateHelpText(env))
+
+#CPU option
+board = env.get('BOARD')
+cpus = __get_cpu(boards_info, board)
+if len(cpus) > 0:
+       help_vars = Variables()
+       help_vars.Add(EnumVariable('CPU', 'arduino board cpu', cpus[0], cpus))
+       help_vars.Update(env)
+       Help(help_vars.GenerateHelpText(env))
+
+# Arduino commom flags
+cpu = env.get('CPU')
+board = env.get('BOARD')
+mcu = __get_board_info(board, '.build.mcu')
+f_cpu = __get_board_info(board, '.build.f_cpu')
+usb_vid = __get_board_info(board, '.build.vid')
+usb_pid = __get_board_info(board, '.build.pid')
+variant = __get_board_info(board, '.build.variant')
+
+if not usb_vid:
+       usb_vid = __get_board_info(board, '.vid.0')
+if not usb_pid:
+       usb_pid = __get_board_info(board, '.pid.0')
+
+if is_1_0_x:
+       core_base = arduino_home + '/hardware/arduino/'
+else:
+       if target_arch == 'avr':
+               core_base = arduino_home + '/hardware/arduino/avr/'
+       else:
+               core_base = arduino_home + '/hardware/arduino/sam/'
+
+variant_folder = core_base + 'variants/' + variant
+env.AppendUnique(CPPPATH = [variant_folder])
+
+core = __get_board_info(board, '.build.core')
+core_folder = core_base + 'cores/' + core + '/'
+env.AppendUnique(CPPPATH = [core_folder])
+
+if is_1_0_x:
+       comm_flags = ['-std=c99']
+       if mcu:
+               comm_flags.extend(['-mmcu=' + mcu])
+       if f_cpu:
+               comm_flags.extend(['-DF_CPU=' + f_cpu])
+       comm_flags.extend(['-DARDUINO=' + version])
+       if usb_vid:
+               comm_flags.extend(['-DUSB_VID=' + usb_vid])
+       if usb_pid:
+               comm_flags.extend(['-DUSB_PID=' + usb_pid])
+
+       env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
+       env.AppendUnique(ASFLAGS = comm_flags)
+
+       env.AppendUnique(CFLAGS = ['-Os', '-ffunction-sections', '-fdata-sections', '-MMD'])
+       env.AppendUnique(CFLAGS = comm_flags)
+
+       env.AppendUnique(CXXFLAGS = ['-Os', '-fno-exceptions', '-ffunction-sections', '-fdata-sections','-MMD'])
+       env.AppendUnique(CXXFLAGS = comm_flags)
+
+       env.AppendUnique(LINKFLAGS = ['-Os'])
+       if mcu == 'atmega2560':
+               env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections,--relax'])
+       else:
+               env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections'])
+       env.AppendUnique(LINKFLAGS = ['-mmcu=' + mcu])
+else:
+       if target_arch == 'avr':
+               cpu_flag = '-mmcu=' + mcu
+       else:
+               cpu_flag = '-mcpu=' + mcu
+
+       comm_flag = [cpu_flag, '-DF_CPU=' + f_cpu, '-DARDUINO=' + version, '-DARDUINO_' + __get_board_info(board, '.build.board')]
+       if target_arch == 'arm':
+               # As of 1.5.8 the arduino headers had asm bugs with ARM and
+               # require gnu99 to be used.
+               comm_flag.extend(['-std=gnu99', '-DARDUINO_ARCH_SAM'])
+       else:
+               comm_flag.extend(['-std=c99', '-DARDUINO_ARCH_AVR'])
+
+       compiler_path = platform_info.get('compiler.path')
+       compiler_path = compiler_path.replace('{runtime.ide.path}', arduino_home)
+       env.PrependENVPath('PATH', compiler_path)
+       env.Replace(CC = platform_info.get('compiler.c.cmd'))
+       env.Replace(CXX = platform_info.get('compiler.cpp.cmd'))
+       env.Replace(AR = platform_info.get('compiler.ar.cmd'))
+       if target_arch == 'arm':
+               env.AppendUnique(CPPPATH = [arduino_home + '/hardware/arduino/sam/system/libsam',
+                                                       arduino_home + '/hardware/arduino/sam/system/CMSIS/CMSIS/Include/',
+                                                       arduino_home + '/hardware/arduino/sam/system//CMSIS/Device/ATMEL'])
+       env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
+       env.AppendUnique(ASFLAGS = comm_flag)
+       env.AppendUnique(CFLAGS = Split(platform_info.get('compiler.c.flags')))
+       env.AppendUnique(CXXFLAGS = Split(platform_info.get('compiler.cpp.flags')))
+       env.AppendUnique(ARFLAGS = Split(platform_info.get('compiler.ar.flags')))
+       env.AppendUnique(CCFLAGS = comm_flag)
+
+       extra_flags = __get_board_info(board, '.build.extra_flags')
+       if extra_flags:
+               extra_flags = extra_flags.replace('{build.usb_flags}', '')
+               env.AppendUnique(CCFLAGS = Split(extra_flags))
+               usb_flags = ['-DUSB_VID=' + usb_vid, '-DUSB_PID=' + usb_pid, '-DUSBCON', '-DUSB_MANUFACTURER="Unknown"']
+               env.AppendUnique(CCFLAGS = usb_flags)
+
+       if target_arch == 'arm':
+               env.AppendUnique(LINKFLAGS = ['-Os', '-Wl,--gc-sections', cpu_flag,
+                                       '-T' + variant_folder + '/' + __get_board_info(board, '.build.ldscript'),
+                                       '-Wl,-Map,' + env.get('BUILD_DIR') + 'arduino_prj.map'])
+               env.AppendUnique(LINKFLAGS = Split('-lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group'))
+
+               variant_system_lib = __get_board_info(board, '.build.variant_system_lib')
+               if variant_system_lib:
+                       if variant_folder.find(' ') >= 0:
+                               variant_folder = '"' + variant_folder + '"'
+                       env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS '
+                                       + variant_folder + '/' + variant_system_lib + ' -Wl,--end-group')
+               else:
+                       env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS -Wl,--end-group')
+       else:
+               env.AppendUnique(LINKFLAGS = Split(platform_info.get('compiler.c.elf.flags')))
+               env.AppendUnique(LINKFLAGS = [cpu_flag])
+               env.AppendUnique(LIBS = 'm')
+       env.Replace(ARCOM = '$AR ' + platform_info.get('compiler.ar.flags') + ' $TARGET $SOURCES')
+
+__build_core(env)
+
+env.AddMethod(__import_lib, "ImportLib") #import arduino library
+#env.AddMethod(__build_core, "BuildCore") #build arduino core
+env.AddMethod(__create_bin, "CreateBin") #create binary files(.eep and .hex)
+env.AddMethod(__upload, "Upload") #Upload binary to board
+env.AddMethod(__upload_help, "UploadHelp") #print the command line that to upload binary to the boardf
+
diff --git a/resource/csdk/connectivity/build/arduino/arduino.scons b/resource/csdk/connectivity/build/arduino/arduino.scons
new file mode 100644 (file)
index 0000000..4c13ebd
--- /dev/null
@@ -0,0 +1,29 @@
+##
+# This script includes arduino specific config for oic-resource
+##
+Import('env')
+
+# Add 'SHIELD' build option, let user select board network connection type
+vars = Variables()
+if 'IP' in env.get('TARGET_TRANSPORT'):
+       vars.Add(EnumVariable('SHIELD', 'Network connection type', 'WIFI', ['ETH', 'WIFI']))
+elif 'BLE' in env.get('TARGET_TRANSPORT'):
+       vars.Add(EnumVariable('SHIELD', 'Network connection type', 'RBL_NRF8001', ['RBL_NRF8001']))
+vars.Update(env)
+Help(vars.GenerateHelpText(env))
+
+env.ImportLib('SPI')
+if 'ETH' in env.get('SHIELD'):
+       env.ImportLib('Ethernet')
+if 'WIFI' in env.get('SHIELD'):
+       env.ImportLib('WiFi')
+if 'RBL_NRF8001' in env.get('SHIELD'):
+       env.ImportLib('BLE')
+       env.ImportLib('RBL_nRF8001')
+
+env.ImportLib('Time/Time')
+# we have variety of macros for arduino!!
+env.AppendUnique(CPPDEFINES = ['WITH_ARDUINO', '__ARDUINO__'])
+if env.get('LOGGING'):
+       env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
diff --git a/resource/csdk/connectivity/build/arduino/arduinomega.properties b/resource/csdk/connectivity/build/arduino/arduinomega.properties
new file mode 100755 (executable)
index 0000000..9d55105
--- /dev/null
@@ -0,0 +1,121 @@
+#Source directories
+BASE_DIR = ../..
+SDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+SDIR_ARD_BASE1 = $(BASE_DIR)/common/src/
+SDIR_ARD_BASE2 = $(BASE_DIR)/samples/arduino/
+SDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+SDIR_ARD_CALOGIC = $(BASE_DIR)/src/
+SDIR_ARD_UTIL = $(BASE_DIR)/src/adapter_util/
+
+ifeq ($(TRANSPORT),ETHERNET)
+       SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet/src
+       SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility
+       SDIR_ARD_ETH1 = $(BASE_DIR)/src/ethernet_adapter/arduino/:$(BASE_DIR)/src/ethernet_adapter/
+       SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_BASE1):$(SDIR_ARD_BASE2):$(SDIR_ARD_SPI) \
+                                               $(SDIR_ARD_CALOGIC):$(SDIR_ARD_UTIL):$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL):$(SDIR_ARD_ETH1)
+else ifeq ($(TRANSPORT),WIFI)
+       SDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src
+       SDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility
+       SDIR_ARD_WIFI1 = $(BASE_DIR)/src/wifi_adapter/arduino/:$(BASE_DIR)/src/wifi_adapter/
+       SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_BASE1):$(SDIR_ARD_BASE2):$(SDIR_ARD_SPI) \
+                                               $(SDIR_ARD_CALOGIC):$(SDIR_ARD_UTIL):$(SDIR_ARD_WIFI):$(SDIR_ARD_WIFI_UTIL):$(SDIR_ARD_WIFI1)
+else ifeq ($(TRANSPORT),BLE)
+       SDIR_ARD_BLE = $(ARDUINO_DIR)/libraries/BLE
+       SDIR_ARD_RBL = $(ARDUINO_DIR)/libraries/RBL_nRF8001
+       SDIR_ARD_BLE1 = $(BASE_DIR)/src/bt_le_adapter/arduino/
+       SDIR_ARD_BLE2 = $(BASE_DIR)/src/bt_le_adapter/
+       SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_BASE1):$(SDIR_ARD_BASE2):$(SDIR_ARD_SPI) \
+                                               $(SDIR_ARD_CALOGIC):$(SDIR_ARD_UTIL):$(SDIR_ARD_BLE):$(SDIR_ARD_RBL):$(SDIR_ARD_BLE1):$(SDIR_ARD_BLE2)
+else
+   $(info *********error**********)
+   $(error Wrong value for TRANSPORT !!)
+endif
+
+#include directories
+IDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+IDIR_ARD_CORE2 = $(ARDUINO_DIR)/hardware/tools/avr/avr/include/
+IDIR_ARD_CORE3 = $(ARDUINO_DIR)/hardware/arduino/avr/variants/mega
+INCD_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+IDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+INCD_ARD_BASE1 = $(BASE_DIR)/inc/
+INCD_ARD_BASE2 = $(BASE_DIR)/common/inc/
+INCD_ARD_BASE3 = $(BASE_DIR)/api/
+INCD_ARD_BASE4 = $(BASE_DIR)/lib/libcoap-4.1.1/
+#ntohs and htons are defined in util.h in the below path
+IDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility
+
+ifeq ($(TRANSPORT),ETHERNET)
+       IDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet/src
+       IDIR_ARD_ETH1 = $(BASE_DIR)/src/ethernet_adapter/arduino/
+       INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) \
+                                               -I$(INCD_ARD_TIME) -I$(IDIR_ARD_SPI) \
+                                               -I$(INCD_ARD_BASE1) -I$(INCD_ARD_BASE2) -I$(INCD_ARD_BASE3) \
+                                               -I$(INCD_ARD_BASE4) -I$(IDIR_ARD_ETH) -I$(IDIR_ARD_ETH_UTIL) \
+                                               -I$(IDIR_ARD_ETH1)
+else ifeq ($(TRANSPORT),WIFI)
+       IDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src
+       IDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility
+       INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) \
+                                       -I$(INCD_ARD_TIME) -I$(IDIR_ARD_SPI) \
+                                       -I$(INCD_ARD_BASE1) -I$(INCD_ARD_BASE2) -I$(INCD_ARD_BASE3)  \
+                                       -I$(INCD_ARD_BASE4) -I$(IDIR_ARD_ETH_UTIL) -I$(IDIR_ARD_WIFI) \
+                                       -I$(IDIR_ARD_WIFI_UTIL)
+else ifeq ($(TRANSPORT),BLE)
+       IDIR_ARD_BLE = $(ARDUINO_DIR)/libraries/BLE
+       IDIR_ARD_RBL = $(ARDUINO_DIR)/libraries/RBL_nRF8001
+       INCD_ARD_BLE1 = $(BASE_DIR)/src/bt_le_adapter/arduino/
+       INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) \
+                                               -I$(INCD_ARD_TIME) -I$(IDIR_ARD_SPI) \
+                                               -I$(INCD_ARD_BASE1) -I$(INCD_ARD_BASE2) -I$(INCD_ARD_BASE3)  \
+                                               -I$(INCD_ARD_BASE4) -I$(IDIR_ARD_ETH_UTIL) -I$(IDIR_ARD_BLE) \
+                                               -I$(IDIR_ARD_RBL) -I$(INCD_ARD_BLE1)
+else
+   $(info *********error**********)
+   $(error Wrong value for TRANSPORT !!)
+endif
+
+#Compiler/Linker flags
+CFLAGS_PLATFORM =  -mmcu=atmega2560 -DF_CPU=16000000L -fno-exceptions -ffunction-sections -fdata-sections -MMD -DARDUINO=157 -DARDUINO_ARCH_AVR \
+                       -DARDUINO_AVR_ADK
+
+#Compilers
+$(info ************ arduinoMEGA file*****************)
+
+CCPLUS=$(ARDUINO_TOOLS_DIR)/avr-g++
+CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
+AR=$(ARDUINO_TOOLS_DIR)/avr-ar
+RANLIB=$(ARDUINO_TOOLS_DIR)/avr-ranlib
+AVR_OBJCOPY=$(ARDUINO_TOOLS_DIR)/avr-objcopy
+AVR_PROGRAMMER=$(ARDUINO_TOOLS_DIR)/avrdude
+
+#Objects
+CORE_COBJ = hooks.c.o WInterrupts.c.o wiring.c.o wiring_digital.c.o wiring_analog.c.o wiring_shift.c.o wiring_pulse.c.o
+CORE_CPPOBJ = CDC.cpp.o HardwareSerial.cpp.o HardwareSerial0.cpp.o HardwareSerial1.cpp.o HardwareSerial2.cpp.o HardwareSerial3.cpp.o IPAddress.cpp.o HID.cpp.o \
+              main.cpp.o new.cpp.o Print.cpp.o Stream.cpp.o Tone.cpp.o USBCore.cpp.o WMath.cpp.o WString.cpp.o
+SPI_OBJ = SPI.cpp.o
+LOGGER_OBJ = logger.c.o oic_logger.c.o oic_console_logger.c.o oic_malloc.c.o oic_string.c.o uarraylist.c.o
+UTIL_OBJ = caadapterutils.c.o camsgparser.c.o
+CACOMMON_OBJ = caconnectivitymanager_singlethread.c.o cainterfacecontroller_singlethread.c.o camessagehandler_singlethread.c.o canetworkconfigurator_singlethread.c.o caprotocolmessage_singlethread.c.o \
+                          caremotehandler.c.o caretransmission_singlethread.c.o
+
+ifeq ($(TRANSPORT),ETHERNET)
+       ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o EthernetClient.o
+       ETH_UTIL_CPPOBJ = socket.o w5100.o
+       INTERFACE_OBJ = caethernetadapterutils.cpp.o caethernetclient.cpp.o caethernetserver.cpp.o caethernetnwmonitor.cpp.o caethernetadapter_singlethread.c.o
+       PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
+else ifeq ($(TRANSPORT),WIFI)
+       WIFI_CPPOBJ = WiFi.cpp.o WiFiClient.cpp.o WiFiServer.cpp.o WiFiUdp.cpp.o
+       WIFI_UTIL_CPPOBJ = server_drv.cpp.o spi_drv.cpp.o wifi_drv.cpp.o
+       INTERFACE_OBJ = cawificlient.cpp.o cawifiserver.cpp.o cawifinwmonitor.cpp.o cawifiadapter_singlethread.c.o
+       PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(WIFI_CPPOBJ) $(WIFI_UTIL_CPPOBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
+else ifeq ($(TRANSPORT),BLE)
+       BLE_OBJ = aci_queue.cpp.o aci_setup.cpp.o acilib.cpp.o hal_aci_tl.cpp.o lib_aci.cpp.o
+       RBL_OBJ = RBL_nRF8001.cpp.o
+       INTERFACE_OBJ = caleadapter_singlethread.c.o cableserver.cpp.o cablenwmonitor.cpp.o
+       PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(BLE_OBJ) $(RBL_OBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
+else
+   $(info *********error**********)
+   $(error Wrong value for TRANSPORT !!)
+endif
+
diff --git a/resource/csdk/connectivity/build/arduino/build.sh b/resource/csdk/connectivity/build/arduino/build.sh
new file mode 100755 (executable)
index 0000000..ccedb4c
--- /dev/null
@@ -0,0 +1,21 @@
+#!/bin/sh
+if echo $1 | grep -q -i "clean"
+then
+cd ../lib/libcoap-4.1.1/
+make -f makefile_arduino.mak clean
+cd ../../build/arduino
+make clean
+else
+if echo $1 | grep -q -i "make"
+then
+cd ../lib/libcoap-4.1.1/
+make -f makefile_arduino.mak PLATFORM=$2 ARDUINO_DIR=$4
+cd ../../build/arduino
+make PLATFORM=$2 TRANSPORT=$3 ARDUINO_DIR=$4 APP_NAME=$5
+else
+cd ../lib/libcoap-4.1.1/
+make $1 -f makefile_arduino.mak PLATFORM=$2 ARDUINO_DIR=$4
+cd ../../build/arduino/
+make $1 PLATFORM=$2 TRANSPORT=$3 ARDUINO_DIR=$4 APP_NAME=$5
+fi
+fi
\ No newline at end of file
diff --git a/resource/csdk/connectivity/build/arduino/local.properties b/resource/csdk/connectivity/build/arduino/local.properties
new file mode 100755 (executable)
index 0000000..633e822
--- /dev/null
@@ -0,0 +1,3 @@
+ARDUINO_DIR = /usr/share/arduino
+ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
+
diff --git a/resource/csdk/connectivity/build/common.mk b/resource/csdk/connectivity/build/common.mk
new file mode 100644 (file)
index 0000000..858dda1
--- /dev/null
@@ -0,0 +1,60 @@
+#/******************************************************************
+# *
+# * 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.
+# *
+#******************************************************************/
+
+##
+##     Definitions
+##
+SHELL                                          = /bin/bash
+PROJECT_NAME                           = connectivity_abstraction
+PROJECT_ROOT_PATH                      = ..
+PROJECT_API_PATH                               = $(PROJECT_ROOT_PATH)/api
+PROJECT_INC_PATH                               = $(PROJECT_ROOT_PATH)/inc
+PROJECT_SRC_PATH                       = $(PROJECT_ROOT_PATH)/src
+PROJECT_COMMON_INC_PATH        = $(PROJECT_ROOT_PATH)/common/inc
+PROJECT_COMMON_SRC_PATH        = $(PROJECT_ROOT_PATH)/common/src
+PROJECT_COMMON_PATH            = $(PROJECT_ROOT_PATH)/common
+PROJECT_OUT_PATH                       = $(PROJECT_ROOT_PATH)/build/out
+PROJECT_LIB_PATH                               = $(PROJECT_ROOT_PATH)/lib
+
+##
+##     macro
+##
+define MAKE_PROJECT_OUT_PATH
+       @if     [ ! -d $(PROJECT_OUT_PATH) ]; then      \
+       mkdir $(PROJECT_OUT_PATH);      \
+       fi
+endef
+
+
+##
+##     Commands
+##
+CC                     = gcc
+CXX                    = g++
+RM                     = rm -rf
+CP                     = cp
+MV                     = mv
+AR                     = ar
+LD                     = ld
+LN                     = ln
+CD                     = cd
+RANLIB         = ranlib
+
+
diff --git a/resource/csdk/connectivity/build/linux/Makefile b/resource/csdk/connectivity/build/linux/Makefile
deleted file mode 100644 (file)
index 7fb550a..0000000
+++ /dev/null
@@ -1,161 +0,0 @@
-#/******************************************************************
-# *
-# * Copyright 2014 Samsung Electronics All Rights Reserved.
-# *
-# *
-# *
-# * Licensed under the Apache License, Version 2.0 (the "License");
-# * you may not use this file except in compliance with the License.
-# * You may obtain a copy of the License at
-# *
-# *      http://www.apache.org/licenses/LICENSE-2.0
-# *
-# * Unless required by applicable law or agreed to in writing, software
-# * distributed under the License is distributed on an "AS IS" BASIS,
-# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# * See the License for the specific language governing permissions and
-# * limitations under the License.
-# *
-#******************************************************************/
-
-# override with `make BUILD=debug`
-# default to release build
-# default to build for linux
-BUILD = release
-PLATFORM = linux
-TRANSPORT = ALL
-OBJ_DIR = ./$(BUILD)
-VERSION_MAJOR = 0
-VERSION_MINOR = 1
-VERSION_PATCH = 0
-
-COMMON_MAKE = common.mk
-
-include $(COMMON_MAKE)
-
-#Modify below values to enable/disable the Adapter
-#Suffix "NO_" to disable given adapter  
-EDR = NO_EDR_ADAPTER
-WIFI = WIFI_ADAPTER
-LE = NO_LE_ADAPTER
-ETHERNET = NO_ETHERNET_ADAPTER
-
-#Add Pre processor definitions
-DEFINE_FLAG = -D$(EDR) -D$(LE) -D$(WIFI) -D$(ETHERNET)
-
-#Add Debug flags here
-DEBUG_FLAG = -DTB_LOG
-
-##
-##     definitions
-##
-LIB_PREFIX                             = CA
-ETHERNET_ADAPTER               = ethernet_adapter
-WIFI_ADAPTER                   = wifi_adapter
-BT_ADAPTER                             = bt_edr_adapter
-BLE_ADAPTER                            = bt_le_adapter
-ETHERNET_ADAPTER_PATH  = $(PROJECT_SRC_PATH)/$(ETHERNET_ADAPTER)/$(PLATFORM)
-WIFI_ADAPTER_PATH              = $(PROJECT_SRC_PATH)/$(WIFI_ADAPTER)/$(PLATFORM)
-BT_ADAPTER_PATH                        = $(PROJECT_SRC_PATH)/$(BT_ADAPTER)/$(PLATFORM)
-BLE_ADAPTER_PATH               = $(PROJECT_SRC_PATH)/$(BLE_ADAPTER)/$(PLATFORM)
-TARGET                                 = lib$(PROJECT_NAME).so.$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH)
-TARGET_ALIAS                   = lib$(PROJECT_NAME).so
-
-##
-##     libcoap
-##
-libcoap_build_dir = $(PROJECT_LIB_PATH)/libcoap-4.1.1
-
-LDFLAGS:=-L$(libcoap_build_dir)
-LDLIBS:=-lcoap
-
-BUILD_FLAG.debug       = $(DEFINE_FLAG) $(DEBUG_FLAG) 
-BUILD_FLAG.release     =       $(DEFINE_FLAG)
-BUILD_FLAG = $(BUILD_FLAG.$(BUILD))
-
-DEBUG_DIR = ./debug
-RELEASE_DIR = ./release
-
-##
-##     file declaration
-##
-COMPONENT_SRCS                 =  \
-logger.c oic_malloc.c oic_logger.c oic_console_logger.c \
-caconnectivitymanager.c caremotehandler.c cainterfacecontroller.c camessagehandler.c   \
-canetworkconfigurator.c caedradapter.c caleadapter.c   \
-caethernetadapter.c cawifiadapter.c \
-caprotocolmessage.c cawificore.c       \
-uqueue.c uarraylist.c umutex.c uthreadpool.c \
-
-COMPONENT_OBJS                 = $(COMPONENT_SRCS:%.c=$(OBJ_DIR)/%.o)
-
-##
-##     compiler flags
-##
-CFLAGS                         =       -g -c -Wall -fPIC `pkg-config --cflags glib-2.0`
-
-LFLAGS                         =       -ldl -lpthread `pkg-config --libs glib-2.0`
-
-IFLAGS                         =       -I$(PROJECT_COMMON_INC_PATH)    \
-                                               -I$(PROJECT_API_PATH)   \
-                                               -I$(PROJECT_INC_PATH)   \
-                                               -I$(ETHERNET_ADAPTER_PATH)      \
-                                               -I$(WIFI_ADAPTER_PATH)  \
-                                               -I$(BT_ADAPTER_PATH)    \
-                                               -I$(BLE_ADAPTER_PATH)   \
-                        -I$(libcoap_build_dir)
-
-DFLAGS                         = -DLINUX               \
-                      -DWITH_POSIX             \
-                      $(BUILD_FLAG)\
-##
-##     compile and link rules
-##
-vpath %.c $(PROJECT_COMMON_SRC_PATH)
-vpath %.c $(ETHERNET_ADAPTER_PATH)
-vpath %.c $(WIFI_ADAPTER_PATH)
-vpath %.c $(BT_ADAPTER_PATH)
-vpath %.c $(BLE_ADAPTER_PATH)
-vpath %.c $(PROJECT_SRC_PATH)
-
-$(OBJ_DIR)/%.o: %.c
-       @$(MAKE_OBJ_PATH)
-       @$(CC) -o $@ $(CFLAGS) $(DFLAGS) $(IFLAGS) $<
-
-all : $(TARGET)
-       @echo   " "
-       @echo   "======================"
-       @echo   "       Success!!"
-       @echo   "======================"
-
-$(TARGET) : $(COMPONENT_OBJS)
-       @$(MAKE_PROJECT_OUT_PATH)
-       @$(CC) -shared -Wl,-soname,$(TARGET) -o $@ $(COMPONENT_OBJS) $(LFLAGS) $(LDFLAGS) $(LDLIBS) 
-       @$(MV) $(TARGET) $(PROJECT_OUT_PATH)/.
-       @$(CD) $(PROJECT_OUT_PATH); $(MAKE_TARGET_ALIAS)
-
-clean :        
-       @$(RM) $(DEBUG_DIR) $(RELEASE_DIR)\
-                       $(PROJECT_OUT_PATH)
-
-install :
-       @$(MAKE_PROJECT_OUT_PATH)
-
-##
-##     macros
-##
-define MAKE_OBJ_PATH
-       @if [ ! -d $(OBJ_DIR) ]; then \
-       mkdir $(OBJ_DIR); \
-       fi
-endef
-
-define MAKE_TARGET_ALIAS
-       if [ ! -f $(TARGET_ALIAS) ]; then \
-       $(LN) -s $(TARGET) $(TARGET_ALIAS); \
-       fi
-endef
-
-.PHONY:        all clean install
-
-
diff --git a/resource/csdk/connectivity/build/linux/SConscript b/resource/csdk/connectivity/build/linux/SConscript
new file mode 100644 (file)
index 0000000..bc0176d
--- /dev/null
@@ -0,0 +1,41 @@
+##
+# This script set linux specific flags (GNU GCC)
+#
+##
+Import('env')
+
+print "Reading linux configuration script"
+
+# Set release/debug flags
+if env.get('RELEASE'):
+       env.AppendUnique(CCFLAGS = ['-Os'])
+       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+       env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+       env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__'])
+env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
+
+# Set arch flags
+target_arch = env.get('TARGET_ARCH')
+if target_arch in ['x86']:
+       env.AppendUnique(CCFLAGS = ['-m32'])
+       env.AppendUnique(LINKFLAGS = ['-m32'])
+elif target_arch in ['x86_64']:
+       env.AppendUnique(CCFLAGS = ['-m64'])
+       env.AppendUnique(LINKFLAGS = ['-m64'])
+elif target_arch.find('v7a-hard') > 0:
+       env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
+       env.AppendUnique(CPPFLAGS = ['-mfloat-abi=hard'])
+       env.AppendUnique(CCFLAGS = ['-mfloat-abi=hard'])
+       env.AppendUnique(LINKFLAGS = ['-mfloat-abi=hard'])
+elif target_arch.find('v7a') > 0:
+       env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
+elif target_arch.find('arm64') > 0:
+       env.AppendUnique(CPPFLAGS = ['-march=armv8-a'])
+else:
+       env.AppendUnique(CPPFLAGS = ['-march=armv5te'])
diff --git a/resource/csdk/connectivity/build/linux/common.mk b/resource/csdk/connectivity/build/linux/common.mk
deleted file mode 100644 (file)
index fe66585..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-#/******************************************************************
-# *
-# * Copyright 2014 Samsung Electronics All Rights Reserved.
-# *
-# *
-# *
-# * Licensed under the Apache License, Version 2.0 (the "License");
-# * you may not use this file except in compliance with the License.
-# * You may obtain a copy of the License at
-# *
-# *      http://www.apache.org/licenses/LICENSE-2.0
-# *
-# * Unless required by applicable law or agreed to in writing, software
-# * distributed under the License is distributed on an "AS IS" BASIS,
-# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# * See the License for the specific language governing permissions and
-# * limitations under the License.
-# *
-#******************************************************************/
-
-##
-##     Definitions
-##
-SHELL                                          = /bin/bash
-PROJECT_NAME                           = connectivity_abstraction
-PROJECT_ROOT_PATH                      = ../..
-PROJECT_API_PATH                       = $(PROJECT_ROOT_PATH)/api
-PROJECT_INC_PATH                       = $(PROJECT_ROOT_PATH)/inc
-PROJECT_SRC_PATH                       = $(PROJECT_ROOT_PATH)/src
-PROJECT_COMMON_INC_PATH                = $(PROJECT_ROOT_PATH)/common/inc
-PROJECT_COMMON_SRC_PATH                = $(PROJECT_ROOT_PATH)/common/src
-PROJECT_COMMON_PATH                    = $(PROJECT_ROOT_PATH)/common
-PROJECT_OUT_PATH                       = $(PROJECT_ROOT_PATH)/build/out
-PROJECT_LIB_PATH                       = $(PROJECT_ROOT_PATH)/lib
-
-##
-##     macro
-##
-define MAKE_PROJECT_OUT_PATH
-       @if     [ ! -d $(PROJECT_OUT_PATH) ]; then      \
-       mkdir $(PROJECT_OUT_PATH);      \
-       fi
-endef
-
-
-##
-##     Commands
-##
-CC                     = gcc
-CXX                    = g++
-RM                     = rm -rf
-CP                     = cp
-MV                     = mv
-AR                     = ar
-LD                     = ld
-LN                     = ln
-CD                     = cd
-RANLIB         = ranlib
-
diff --git a/resource/csdk/connectivity/build/tizen/Makefile b/resource/csdk/connectivity/build/tizen/Makefile
new file mode 100644 (file)
index 0000000..8e56590
--- /dev/null
@@ -0,0 +1,65 @@
+##
+# override with `make BUILD=debug`
+# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
+# default to release build
+# default to build for linux
+BUILD   := debug
+PLATFORM := tizen
+OBJ_DIR := ./bin
+ROOT_DIR := .
+VERSION_MAJOR := 0
+VERSION_MINOR := 1
+VERSION_PATCH := 0
+ADAPTER_MACRO := -DWIFI_ADAPTER
+
+$(info *******************tizen Build !!******************)
+
+CC=gcc
+LIBCOAP=./lib/libcoap-4.1.1/
+LIBCOAP_OBJ_DIR=./lib/libcoap-4.1.1/obj
+
+TINYDTLS=./lib/extlibs/tinydtls
+TINYDTLS_OBJ_DIR=./lib/extlibs/tinydtls/obj
+
+# TODO : Currently Hardcoded WIFI_ADAPTER. Change it to generic
+CFLAGS.debug = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -g -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
+CFLAGS.release = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
+COMPILEFLAG = `pkg-config --cflags --libs capi-network-wifi dlog capi-network-bluetooth glib-2.0`
+
+# Include files will be copied into a single folder on gbsbuild.
+# NO NEED to mention the path explicitly.
+
+CA_INC              = $(ROOT_DIR)/
+DTLS_INC           = $(ROOT_DIR)/dtls/
+
+INC_DIRS        := -I$(CA_INC)
+INC_DIRS        += -I$(DTLS_INC)
+
+SRC = $(wildcard *.c)
+OBJECTS = $(patsubst %.c, %.o, $(SRC))
+
+#Currently compiling libcoap objects. If it's provided by external party. 
+#Then don't compile, Instead directly extract objects and create liboicinterface.a
+all: $(OBJECTS)
+       $(MAKE) -C $(LIBCOAP) clean
+       $(MAKE) -C $(LIBCOAP)
+       -mkdir $(LIBCOAP_OBJ_DIR)
+       @cd $(LIBCOAP_OBJ_DIR) && $(AR) -x ../libcoap.a
+       ar rcs liboicinterface.a $(OBJECTS) $(LIBCOAP_OBJ_DIR)/*.o
+
+%.o : %.c
+       $(CC) -c $(CFLAGS.$(BUILD)) $(COMPILEFLAG) $(INC_DIRS) $< -o $@
+
+
+pack:
+#$(CC) $(CFLAGS) $(COMPILEFLAG) WiFiInterface.c bt_interface.c tc_interface.c sample_main.c -o sample /usr/lib/liboctbstack.a -lm -pthread
+       $(info **************************************TEST***************************)
+install:
+#cp -rf sample ./usr/apps/com.samsung.oicca/bin/sample
+
+clean:
+       rm -rf *.o sample
+       rm -f *.o *.d *.elf *.eep core.a *.hex *.bin *.map *-
+       rm -rf $(OBJ_DIR)
+       rm -rf $(LIBCOAP_OBJ_DIR)
+
diff --git a/resource/csdk/connectivity/build/tizen/SConscript b/resource/csdk/connectivity/build/tizen/SConscript
new file mode 100644 (file)
index 0000000..c8c105c
--- /dev/null
@@ -0,0 +1,23 @@
+##
+# CA build script
+##
+
+SConscript('./resource/csdk/connectivity/build/SConscript')
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+buildsample = env.get('BUILD_SAMPLE')
+release_mode = env.get('RELEASE')
+secured = env.get('SECURED')
+logging = env.get('LOGGING')
+
+print "Given Transport is %s" % transport
+print "Given OS is %s" % target_os
+
+if target_os == 'tizen':
+       command = "sh resource/csdk/connectivity/build/tizen/gbsbuild.sh %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging)
+       print "Created Command is %s" % command
+       gbs_script = env.Command('gbs_build', None, command)
+       AlwaysBuild ('gbs_script')
\ No newline at end of file
diff --git a/resource/csdk/connectivity/build/tizen/SConstruct b/resource/csdk/connectivity/build/tizen/SConstruct
new file mode 100644 (file)
index 0000000..eb0f0d2
--- /dev/null
@@ -0,0 +1,19 @@
+##
+# The main build script
+#
+##
+
+# Load common build config
+
+# Load common build config
+env = SConscript('SConscript')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+release_mode = env.get('RELEASE')
+
+print "Given Transport is %s" % transport
+print "Given OS is %s" % target_os
+print "Given release mode is %s" % release_mode
+
+env.SConscript('scons/SConscript')
diff --git a/resource/csdk/connectivity/build/tizen/com.oic.ca.manifest b/resource/csdk/connectivity/build/tizen/com.oic.ca.manifest
new file mode 100644 (file)
index 0000000..c26f59d
--- /dev/null
@@ -0,0 +1,23 @@
+<manifest>
+       <define>
+         <domain name="calib" />
+         <permit>
+               <smack permit="system::use_internet" type="rwx"/>
+         </permit>
+         <request>
+                <smack request="system::use_internet" type="rwx"/>
+                <smack request="bt-service" type="rwx"/>
+                               <smack request="sap" type="rwx"/>
+                <smack request="bt-service::spp" type="rwx"/>
+                <smack request="bt-service::gap" type="rwx"/>
+                <smack request="bt-service::admin" type="rwx"/>
+                <smack request="bt-service::manager" type="rwx"/>
+                <smack request="bt-service::public" type="rwx"/>
+                 <smack request="bt-service::platform" type="rwx"/>
+         </request>
+       </define>
+       <request>
+               <domain name="calib" />
+       </request>
+</manifest>
+
diff --git a/resource/csdk/connectivity/build/tizen/com.oic.ca.pc b/resource/csdk/connectivity/build/tizen/com.oic.ca.pc
new file mode 100644 (file)
index 0000000..fbfa187
--- /dev/null
@@ -0,0 +1,10 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include/OICHeaders
+
+Name: com-oic-ca
+Description: Oic core library
+Version: 1.0
+Cflags: -I${includedir}
+
diff --git a/resource/csdk/connectivity/build/tizen/gbsbuild.sh b/resource/csdk/connectivity/build/tizen/gbsbuild.sh
new file mode 100755 (executable)
index 0000000..528b060
--- /dev/null
@@ -0,0 +1,117 @@
+#!/bin/sh
+
+cur_dir="./resource/csdk/connectivity/"
+
+spec=`ls ./resource/csdk/connectivity/build/tizen/packaging/*.spec`
+version=`rpm --query --queryformat '%{version}\n' --specfile $spec`
+
+name=`echo $name|cut -d" " -f 1`
+version=`echo $version|cut -d" " -f 1`
+
+name=oicca
+
+echo $1
+export TARGET_TRANSPORT=$1
+
+echo $2
+export SECURED=$2
+
+echo $3
+export BUILD_SAMPLE=$3
+
+echo $4
+export RELEASE=$4
+
+echo $5
+export LOGGING=$5
+
+
+echo $TARGET_TRANSPORT
+echo $BUILD_SAMPLE
+
+rm -rf $name-$version
+
+builddir=`pwd`
+sourcedir=`pwd`
+
+echo `pwd`
+
+mkdir ./tmp
+mkdir ./tmp/con/
+cp -R $cur_dir/* $sourcedir/tmp/con
+cp -R $cur_dir/SConscript $sourcedir/tmp/con
+cp -R $cur_dir/src/ip_adapter/SConscript $sourcedir/tmp/con/src/ip_adapter/
+cp -R $cur_dir/src/bt_le_adapter/SConscript $sourcedir/tmp/con/src/bt_le_adapter/
+cp -R $cur_dir/src/bt_edr_adapter/SConscript $sourcedir/tmp/con/src/bt_edr_adapter/
+cp -R $cur_dir/common/SConscript $sourcedir/tmp/con/common/
+cp -R $cur_dir/lib/libcoap-4.1.1/SConscript $sourcedir/tmp/con/lib/libcoap-4.1.1/
+cp -R $cur_dir/samples/tizen/ $sourcedir/tmp/con/sample/
+mkdir -p $sourcedir/tmp/con/sample/lib/tizen/ble/libs
+cp -R $cur_dir/lib/tizen/ble/libs/* $sourcedir/tmp/con/sample/lib/tizen/ble/libs/
+
+cd $sourcedir
+cd $cur_dir/build/tizen
+
+cp -R ./* $sourcedir/tmp/
+rm -f $sourcedir/tmp/SConscript
+cp SConstruct $sourcedir/tmp/
+cp scons/SConscript $sourcedir/tmp/scons/
+
+mkdir -p $sourcedir/tmp/iotivityconfig
+cd $sourcedir/build_common/
+cp -R ./iotivityconfig/* $sourcedir/tmp/iotivityconfig/
+cp -R ./SConscript $sourcedir/tmp/
+
+cd $sourcedir/tmp
+
+echo `pwd`
+
+whoami
+# Initialize Git repository
+if [ ! -d .git ]; then
+   git init ./
+   git config user.email "you@example.com"
+   git config user.name "Your Name"
+   git add ./
+   git commit -m "Initial commit"
+fi
+
+echo "Calling core gbs build command"
+gbscommand="gbs build -A armv7l --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --repository ./"
+echo $gbscommand
+if eval $gbscommand; then
+   echo "Core build is successful"
+else
+   echo "Core build failed. Try 'sudo find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+   cd $sourcedir
+   rm -rf $sourcedir/tmp
+   exit
+fi
+
+if echo $BUILD_SAMPLE|grep -qi '^ON$'; then
+   cd con/sample
+   echo `pwd`
+   # Initialize Git repository
+   if [ ! -d .git ]; then
+      git init ./
+      git config user.email "you@example.com"
+      git config user.name "Your Name"
+      git add ./
+      git commit -m "Initial commit"
+   fi
+   echo "Calling sample gbs build command"
+   gbscommand="gbs build -A armv7l --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'LOGGING $5' --repository ./"
+   echo $gbscommand
+   if eval $gbscommand; then
+      echo "Sample build is successful"
+   else
+      echo "Sample build is failed. Try 'sudo find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+   fi
+else
+       echo "Sample build is not enabled"
+fi
+
+
+cd $sourcedir
+rm -rf $sourcedir/tmp
+
diff --git a/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec b/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec
new file mode 100644 (file)
index 0000000..aba2653
--- /dev/null
@@ -0,0 +1,62 @@
+%define PREFIX /usr/apps/com.oic.ca
+%define ROOTDIR  %{_builddir}/%{name}-%{version}
+%define DEST_INC_DIR  %{buildroot}/%{_includedir}/OICHeaders
+%define DEST_LIB_DIR  %{buildroot}/%{_libdir}
+
+Name: com-oic-ca
+Version:    0.1
+Release:    1
+Summary: Tizen oicca application
+URL: http://slp-source.sec.samsung.net
+Source: %{name}-%{version}.tar.gz
+License: Apache-2.0
+Group: Applications/OIC
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(glib-2.0)
+BuildRequires: pkgconfig(capi-network-wifi)
+BuildRequires: pkgconfig(capi-network-bluetooth)
+BuildRequires: boost-devel
+BuildRequires: boost-thread
+BuildRequires: boost-system
+BuildRequires: boost-filesystem
+BuildRequires: scons
+
+
+%description
+SLP oicca application
+
+%prep
+
+%setup -q
+
+%build
+
+echo %{ROOTDIR}
+
+scons TARGET_OS=tizen -c
+scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING}
+
+%install
+mkdir -p %{DEST_INC_DIR}
+mkdir -p %{DEST_LIB_DIR}/pkgconfig
+
+cp -f %{ROOTDIR}/con/src/libconnectivity_abstraction.so %{buildroot}/%{_libdir}
+cp -f %{ROOTDIR}/con/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
+cp -rf %{ROOTDIR}/con/api/cacommon.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/inc/caadapterinterface.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/common/inc/cathreadpool.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/inc/caipadapter.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/inc/caedradapter.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/inc/caleadapter.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/api/cainterface.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/com.oic.ca.pc %{DEST_LIB_DIR}/pkgconfig/
+
+
+%files
+%manifest com.oic.ca.manifest
+%defattr(-,root,root,-)
+%{_libdir}/lib*.so*
+%{_libdir}/lib*.a*
+%{_includedir}/OICHeaders/*
+%{_libdir}/pkgconfig/*.pc
+
diff --git a/resource/csdk/connectivity/build/tizen/scons/SConscript b/resource/csdk/connectivity/build/tizen/scons/SConscript
new file mode 100644 (file)
index 0000000..318d954
--- /dev/null
@@ -0,0 +1,46 @@
+##
+# 'resource' sub-project main build script
+#
+##
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+
+print "Given Transport is %s" % transport
+
+if env.get('RELEASE'):
+       env.AppendUnique(CFLAGS = ['-std=c99', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE'])
+else:
+       env.AppendUnique(CFLAGS = ['-std=c99', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall', '-DSLP_SDK_LOG', '-g','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE'])
+
+if env.get('LOGGING'):
+       env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+env.ParseConfig("pkg-config --cflags --libs capi-network-wifi dlog glib-2.0")
+if 'ALL' in transport:
+               env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'NO_ETHERNET_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
+               print "CA Transport is ALL"
+else:
+       if 'BT' in transport:
+               env.AppendUnique(CPPDEFINES = ['EDR_ADAPTER'])
+               print "CA Transport is BT"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_EDR_ADAPTER'])
+
+       if 'BLE' in transport:
+               env.AppendUnique(CPPDEFINES = ['LE_ADAPTER'])
+               print "CA Transport is BLE"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_LE_ADAPTER'])
+
+       if 'WIFI' in transport:
+               env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER'])
+               print "CA Transport is WIFI"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER'])
+
+
+env.SConscript(['../con/lib/libcoap-4.1.1/SConscript'])
+env.SConscript(['../con/SConscript'])
diff --git a/resource/csdk/connectivity/common/SConscript b/resource/csdk/connectivity/common/SConscript
new file mode 100644 (file)
index 0000000..7c6c558
--- /dev/null
@@ -0,0 +1,60 @@
+##
+# CA build script
+##
+
+Import('env')
+
+print "Reading common folder script"
+
+ca_os = env.get('TARGET_OS')
+
+root_dir = './../'
+
+
+ca_common_path = root_dir + 'common/'
+ca_common_src_path = ca_common_path + 'src/'
+
+env.AppendUnique(CPPPATH = [
+       'common/inc/',
+       ])
+
+temp = env['CPPPATH']
+header = ' '
+for item in temp:
+       header = header + ' -I' + item
+
+######################################################################
+# Source files and Target(s)
+######################################################################
+ca_common_src = [
+               ca_common_src_path + 'oic_malloc.c',
+               ca_common_src_path + 'oic_string.c',
+               ca_common_src_path + 'uarraylist.c',
+               ca_common_src_path + 'uqueue.c',
+       ]
+
+if ca_os == 'arduino':
+       env.Command(env.get('BUILD_DIR') + 'logger.c.o', None, '$CXX -o ' + env.get('BUILD_DIR') + 'logger.c.o' + ' $LINKFLAGS  $CCFLAGS  $CXXFLAGS ' + '-I' + Dir('.').srcnode().path + '/inc' + header + ' ' + Dir('.').srcnode().path + '/src/logger.c')
+       platform_src = [
+               env.get('BUILD_DIR') + 'logger.c.o',
+       ]
+elif env['POSIX_SUPPORTED']:
+       platform_src = [
+                                       ca_common_src_path + 'logger.c',
+                                       ca_common_src_path + 'oic_logger.c',
+                                       ca_common_src_path + 'oic_console_logger.c',
+                                       ca_common_src_path + 'cathreadpool_pthreads.c',
+                                       ca_common_src_path + 'camutex_pthreads.c'
+       ]
+else:
+       platform_src = [
+               ca_common_src_path + 'logger.c',
+               ca_common_src_path + 'oic_logger.c',
+               ca_common_src_path + 'oic_console_logger.c'
+               ]
+
+
+
+env.AppendUnique(CA_SRC = ca_common_src)
+env.AppendUnique(CA_SRC = platform_src)
+
diff --git a/resource/csdk/connectivity/common/inc/camutex.h b/resource/csdk/connectivity/common/inc/camutex.h
new file mode 100644 (file)
index 0000000..be7b085
--- /dev/null
@@ -0,0 +1,155 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs related to mutex and semaphores.
+ */
+
+#ifndef CA_MUTEX_H_
+#define CA_MUTEX_H_
+
+#include "cacommon.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+typedef struct ca_mutex_internal *ca_mutex;
+typedef struct ca_cond_internal *ca_cond;
+
+/**
+ * Enums for ca_cond_wait_for return values
+ */
+typedef enum
+{
+   CA_WAIT_SUCCESS = 0,    /**< Condition Signal */
+   CA_WAIT_INVAL = -1,     /**< Invalid Condition */
+   CA_WAIT_TIMEDOUT = -2   /**< Condition Timed Out */
+} CAWaitResult_t;
+
+/**
+ * Creates new mutex.
+ *
+ * @return  Reference to newly created mutex, otherwise NULL.
+ *
+ */
+ca_mutex ca_mutex_new(void);
+
+/**
+ * Lock the mutex.
+ *
+ * @param  mutex  The mutex to be locked
+ *
+ */
+void ca_mutex_lock(ca_mutex mutex);
+
+/**
+ * Checks if the mutex can be locked.
+ *
+ * @param  mutex  The mutex to be locked
+ *
+ * @return  true if the mutex is not locked currently, otherwise false.
+ *
+ */
+bool ca_mutex_trylock(ca_mutex mutex);
+
+/**
+ * Unlock the mutex.
+ *
+ * @param  mutex  The mutex to be unlocked
+ *
+ */
+void ca_mutex_unlock(ca_mutex mutex);
+
+/**
+ * Free the mutex.
+ *
+ * @param  mutex  The mutex to be freed
+ *
+ */
+bool ca_mutex_free(ca_mutex mutex);
+
+/**
+ * Creates new condition.
+ *
+ * @return  Reference to newly created @ca_cond, otherwise NULL.
+ *
+ */
+ca_cond ca_cond_new(void);
+
+/**
+ * One of threads is woken up if multiple threads are waiting for @cond.
+ *
+ * @param  cond  The condtion to be signaled
+ *
+ */
+void ca_cond_signal(ca_cond cond);
+
+/**
+ * All of threads are woken up if multiple threads are waiting for @cond.
+ *
+ * @param  cond  The condtion to be signaled
+ *
+ */
+void ca_cond_broadcast(ca_cond cond);
+
+/**
+ * Waits until this thread woken up on @cond.
+ *
+ * @param  cond  The condtion to be wait for to signal
+ * @param  mutex  The mutex which is currently locked from calling thread
+ *
+ */
+void ca_cond_wait(ca_cond cond, ca_mutex mutex);
+
+/**
+ * Waits until this thread woken up on @cond,
+ * but not longer than the interval specified by microseconds.
+ * The mutex is unlocked before falling asleep and locked again before resuming.
+ * If microseconds is 0, ca_cond_wait_for() acts like ca_cond_wait().
+ *
+ * @param  cond  The condtion to be wait for to signal
+ * @param  mutex  The mutex which is currently locked from calling thread
+ * @param  microseconds  relative time for waiting, microseconds
+ *
+ * @return CA_WAIT_SUCCESS if the condition was signaled.
+ *         CA_WAIT_TIMEDDOUT if wait period exceeded
+ *         CA_WAIT_INVAL for invalid parameters
+ *
+ */
+CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds);
+
+/**
+ * Free the condition.
+ *
+ * @param  cond  The condition to be freed
+ *
+ */
+void ca_cond_free(ca_cond cond);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* CA_MUTEX_H_ */
+
diff --git a/resource/csdk/connectivity/common/inc/cathreadpool.h b/resource/csdk/connectivity/common/inc/cathreadpool.h
new file mode 100644 (file)
index 0000000..9df11e9
--- /dev/null
@@ -0,0 +1,90 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs related to thread pool.  Implementations are provided
+ * by adding a new .c file for each implementation, and adding them conditionally
+ * via the SCONS build script.  Currently, cathreadpool_pthreads.c is implemented,
+ * with cathreadpool_winthreads.c being considered.  RTOS implementations should use
+ * a name that best describes the used technology, not the OS.
+ */
+
+#ifndef CA_THREAD_POOL_H_
+#define CA_THREAD_POOL_H_
+
+#include "cacommon.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif // __cplusplus
+
+/**
+ * Callback type can be registered to thread pool.
+ */
+typedef void (*ca_thread_func)(void *);
+
+struct ca_thread_pool_details_t;
+/**
+ * Thread pool type.
+ */
+typedef struct ca_thread_pool
+{
+    struct ca_thread_pool_details_t* details;
+}*ca_thread_pool_t;
+
+/**
+ * This function creates a newly allocated thread pool.
+ *
+ * @param num_of_threads The number of worker thread used in this pool.
+ * @param thread_pool_handle Handle to newly create thread pool.
+ * @return Error code, CA_STATUS_OK if success, else error number.
+ */
+CAResult_t ca_thread_pool_init(int32_t num_of_threads, ca_thread_pool_t *thread_pool_handle);
+
+/**
+ * This function adds a routine to be executed by the thread pool at some future time.
+ *
+ * @param thread_pool The thread pool structure.
+ * @param method The routine to be executed.
+ * @param data The data to be passed to the routine.
+ *
+ * @return CA_STATUS_OK on success.
+ * @return Error on failure.
+ */
+CAResult_t ca_thread_pool_add_task(ca_thread_pool_t thread_pool, ca_thread_func method,
+                    void *data);
+
+/**
+ * This function stops all the worker threads (stop & exit). And frees all the allocated memory.
+ * Function will return only after joining all threads executing the currently scheduled tasks.
+ *
+ * @param thread_pool The thread pool structure.
+ */
+void ca_thread_pool_free(ca_thread_pool_t thread_pool);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* CA_THREAD_POOL_H_ */
+
index b19b037..bf6f130 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _U_LOGGER_H_
-#define _U_LOGGER_H_
+#ifndef U_LOGGER_H_
+#define U_LOGGER_H_
 
 #include <stdint.h>
 #include <stdio.h>
 
 #ifdef __ANDROID__
 #include <android/log.h>
+#elif defined(__TIZEN__)
+#include <dlog.h>
 #elif defined ARDUINO
 #include "Arduino.h"
-#include <avr/pgmspace.h>
+#include "avr/pgmspace.h"
 #endif
 
 #ifdef __cplusplus
@@ -42,22 +44,38 @@ extern "C"
 // Use the PCF macro to wrap strings stored in FLASH on the Arduino
 // Example:  OC_LOG(INFO, TAG, PCF("Entering function"));
 #ifdef ARDUINO
+
+#ifdef __cplusplus
 #define PCF(str)  ((PROGMEM const char *)(F(str)))
 #else
+#define PCF(str)  ((PROGMEM const char *)(PSTR(str)))
+#endif //__cplusplus
+
+#else
 #define PCF(str) str
-#endif
+#endif //ARDUINO
 
 // Max buffer size used in variable argument log function
 #define MAX_LOG_V_BUFFER_SIZE (256)
 
 // Log levels
+#ifndef __TIZEN__
 typedef enum
 {
     DEBUG = 0, INFO, WARNING, ERROR, FATAL
 } LogLevel;
+#else
+#define DEBUG DLOG_DEBUG
+#define INFO DLOG_INFO
+#define WARNING DLOG_WARNING
+#define ERROR DLOG_ERROR
+#define FATAL DLOG_ERROR
+#endif
 
-#ifndef ARDUINO
-
+#ifdef __TIZEN__
+#define OICLog(level,tag,mes) LOG(level,tag,mes)
+#define OICLogv(level,tag,fmt,args...) LOG(level,tag,fmt,##args)
+#elif defined(ANDROID) || defined(__linux__) || defined(__APPLE__)
 /**
  * Configure logger to use a context that defines a custom logger function
  *
@@ -85,7 +103,7 @@ void OICLogShutdown();
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, const char * tag, const char * logStr);
+void OICLog(LogLevel level, const char *tag, const char *logStr);
 
 /**
  * Output a variable argument list log string with the specified priority level.
@@ -95,7 +113,7 @@ void OICLog(LogLevel level, const char * tag, const char * logStr);
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, const char * tag, const char * format, ...);
+void OICLogv(LogLevel level, const char *tag, const char *format, ...);
 
 /**
  * Output the contents of the specified buffer (in hex) with the specified priority level.
@@ -105,8 +123,8 @@ void OICLogv(LogLevel level, const char * tag, const char * format, ...);
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize);
-#else
+void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize);
+#else  // For arduino platforms
 /**
  * Initialize the serial logger for Arduino
  * Only defined for Arduino
@@ -121,7 +139,8 @@ void OICLogInit();
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr);
+void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+              PROGMEM const char *logStr);
 
 /**
  * Output the contents of the specified buffer (in hex) with the specified priority level.
@@ -131,7 +150,7 @@ void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logSt
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize);
+void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize);
 
 /**
  * Output a variable argument list log string with the specified priority level.
@@ -140,28 +159,44 @@ void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buff
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, const char * tag, const char * format, ...);
+void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+               PROGMEM const char *format, ...);
 #endif
 
 #ifdef TB_LOG
-// These macros are defined for Linux, Android, and Arduino
+
+#ifdef __TIZEN__
+#define OIC_LOG(level,tag,mes) LOG_(LOG_ID_MAIN, level, tag, mes)
+#define OIC_LOG_V(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, level, tag, fmt,##args)
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
+#else // These macros are defined for Linux, Android, and Arduino
 #define OIC_LOG_INIT()    OICLogInit()
-#define OIC_LOG(level, tag, logStr)  OICLog((level), (tag), (logStr))
-#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)  OICLogBuffer((level), (tag), (buffer), (bufferSize))
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
+    OICLogBuffer((level), (tag), (buffer), (bufferSize))
 
 #ifdef ARDUINO
 #define OIC_LOG_CONFIG(ctx)
 #define OIC_LOG_SHUTDOWN()
-// Use full namespace for logInit to avoid function name collision
-#define OIC_LOG_INIT()    OICLogInit()
-// Don't define variable argument log function for Arduino
-#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__)
+#define OIC_LOG(level, tag, logStr) OICLog((level), PCF(tag), __LINE__, PCF(logStr))
+#define OIC_LOG_V(level, tag, ...)
+// To enable OIC_LOG_V, uncomment the below
+//#define OIC_LOG_V(level, tag, format, ...)  OICLogv((level), PCF(tag), __LINE__, PCF(format), __VA_ARGS__)
 #else
 #define OIC_LOG_CONFIG(ctx)    OICLogConfig((ctx))
 #define OIC_LOG_SHUTDOWN()     OICLogShutdown()
-// Define variable argument log function for Linux and Android
-#define OIC_LOG_V(level, tag, ...)  OICLogv((level), (tag), __VA_ARGS__)
-#endif
+#define OIC_LOG(level, tag, logStr)  OICLog((level), (tag), (logStr))
+#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__)
+#endif //ARDUINO
+#endif //__TIZEN__
+#else //TB_LOG
+
+#ifdef __ANDROID__
+#define OIC_LOG_CONFIG(ctx)
+#define OIC_LOG_SHUTDOWN()
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
+#define OIC_LOG_INIT()
+#define OIC_LOG(level,tag,mes) __android_log_print(ANDROID_LOG_INFO, tag, mes)
+#define OIC_LOG_V(level,tag,fmt,args...) __android_log_print(ANDROID_LOG_INFO, tag, fmt,##args)
 
 #else
 #define OIC_LOG_CONFIG(ctx)
@@ -170,9 +205,12 @@ void OICLogv(LogLevel level, const char * tag, const char * format, ...);
 #define OIC_LOG_V(level, tag, ...)
 #define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
 #define OIC_LOG_INIT()
-#endif
+#endif //__ANDROID__
+#endif // TB_LOG
+
 
 #ifdef __cplusplus
 }
 #endif // __cplusplus
-#endif /* _U_LOGGER_H_ */
+#endif /* U_LOGGER_H_ */
+
index 6ff5894..bb09eb0 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OIC_CONSOLE_LOGGER_
-#define __OIC_CONSOLE_LOGGER_
+#ifndef OIC_CONSOLE_LOGGER_
+#define OIC_CONSOLE_LOGGER_
 
 #include "oic_logger_types.h"
 
@@ -41,4 +41,5 @@ int oic_console_logger_set_module(oic_log_ctx_t *ctx, const char *module_name);
 } // extern "C"
 #endif
 
-#endif
+#endif /* OIC_CONSOLE_LOGGER_ */
+
index df738c2..d1a5b8d 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OIC_LOGGER_H_
-#define __OIC_LOGGER_H_
+#ifndef OIC_LOGGER_H_
+#define OIC_LOGGER_H_
 
 #include "oic_logger_types.h"
 
@@ -29,9 +29,10 @@ extern "C"
 #endif
 
 /* Basic interface: */
-oic_log_ctx_t *oic_log_make_ctx(void* world, const oic_log_level level, oic_log_init_t init,
-        oic_log_destroy_t destroy, oic_log_flush_t flush, oic_log_set_level_t set_level,
-        oic_log_write_level_t write_level, oic_log_set_module_t set_module);
+oic_log_ctx_t *oic_log_make_ctx(void *world, const oic_log_level level, oic_log_init_t init,
+                                    oic_log_destroy_t destroy, oic_log_flush_t flush,
+                                    oic_log_set_level_t set_level,oic_log_write_level_t write_level,
+                                    oic_log_set_module_t set_module);
 
 void oic_log_destroy(oic_log_ctx_t *ctx);
 
@@ -45,4 +46,5 @@ int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name);
 } // extern "C"
 #endif
 
-#endif
+#endif /* OIC_LOGGER_H_ */
+
index f372a4c..121270b 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef __OIC_LOGGER_TYPES_H_
-#define __OIC_LOGGER_TYPES_H_
+#ifndef OIC_LOGGER_TYPES_H_
+#define OIC_LOGGER_TYPES_H_
 
 #include <stddef.h>
 
@@ -43,11 +43,11 @@ typedef enum
 
 typedef struct _oic_log_ctx
 {
-    voidctx;
+    void *ctx;
 
     oic_log_level log_level;
 
-    charmodule_name;
+    char *module_name;
 
     /* Required interface: */
     int (*init)(struct _oic_log_ctx *, void *);
@@ -83,4 +83,5 @@ typedef int (*oic_log_try_lock_t)(oic_log_ctx_t *);
 } // extern "C"
 #endif
 
-#endif
+#endif /* OIC_LOGGER_TYPES_H_ */
+
index ae06f14..df0b7b2 100644 (file)
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef _OIC_MALLOC_H_
-#define _OIC_MALLOC_H_
+#ifndef OIC_MALLOC_H_
+#define OIC_MALLOC_H_
 
 // The purpose of this module is to allow custom dynamic memory allocation
 // code to easily be added to the TB Stack by redefining the OICMalloc and
@@ -68,6 +68,19 @@ extern "C"
 void *OICMalloc(size_t size);
 
 /**
+ * Allocates a block of memory for an array of num elements, each of them
+ * size bytes long and initializes all its bits to zero.
+ *
+ * @param num - The number of elements
+ * @param size - Size of the element type in bytes, where size > 0
+ *
+ * @return
+ *     on success, a pointer to the allocated memory block
+ *     on failure, a null pointer is returned
+ */
+void *OICCalloc(size_t num, size_t size);
+
+/**
  * Deallocate a block of memory previously allocated by a call to OCMalloc
  *
  * NOTE: This function is intended to be used internally by the TB Stack.
@@ -81,4 +94,5 @@ void OICFree(void *ptr);
 #ifdef __cplusplus
 }
 #endif // __cplusplus
-#endif /* _OIC_MALLOC_H_ */
+#endif /* OIC_MALLOC_H_ */
+
diff --git a/resource/csdk/connectivity/common/inc/oic_string.h b/resource/csdk/connectivity/common/inc/oic_string.h
new file mode 100644 (file)
index 0000000..5c823ba
--- /dev/null
@@ -0,0 +1,44 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#ifndef OIC_STRING_H_
+#define OIC_STRING_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif // __cplusplus
+
+/**
+ * Duplicates the source string and returns it.
+ *
+ * NOTE: Caller needs to clear this memory by calling OICFree.
+ *
+ * @param str - Original valid string which needs to be duplicated
+ *
+ * @return
+ *     on success, a pointer to the duplicated string
+ *     on failure, a null pointer is returned
+ */
+char *OICStrdup(const char *str);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+#endif /* OIC_STRING_H_ */
index b26734e..17edead 100644 (file)
@@ -18,8 +18,8 @@
  *
  ******************************************************************/
 
-#ifndef __U_ARRAYLIST_H_
-#define __U_ARRAYLIST_H_
+#ifndef U_ARRAYLIST_H_
+#define U_ARRAYLIST_H_
 
 #include <stdint.h>
 #include "cacommon.h"
@@ -30,11 +30,6 @@ extern "C"
 #endif
 
 /**
- * Use this default size when initialized
- */
-#define U_ARRAYLIST_DEFAULT_SIZE 1
-
-/**
  * @struct u_arraylist_t
  * @brief array list structure
  */
@@ -49,51 +44,52 @@ typedef struct u_arraylist_t
  * @brief API to creates array list and initializes the elements.
  * @return  u_arraylist_t if Success, NULL otherwise
  */
-u_arraylist_tu_arraylist_create();
+u_arraylist_t *u_arraylist_create();
 
 /**
  * @brief Resets and deletes the array list
- * application should free the memory of data in array list
- * @param u_arraylist_t- u_arraylist pointer
+ * Arraylist elements are deleted. Calling function must take care of free
+ * dynamic memory allocated before freeing the arraylist
+ * @param list- u_arraylist pointer
  * @return CAResult_t
- * CA_STATUS_OK if Success, CA_STATUS_FAILED otherwise
+ * CA_STATUS_OK if Success, CA_STATUS_INVALID_PARAM if pointer to list is NULL
  */
-CAResult_t u_arraylist_free(u_arraylist_t *list);
+CAResult_t u_arraylist_free(u_arraylist_t **list);
 
 /**
  * @brief Returns the data of the index from the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param index
  *     [IN] index of array list
- * @return void pointer of the data
+ * @return void pointer of data if success or NULL pointer otherwise
  */
-voidu_arraylist_get(const u_arraylist_t *list, uint32_t index);
+void *u_arraylist_get(const u_arraylist_t *list, uint32_t index);
 
 /**
  * @brief Add data in the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param data
  *     [IN] pointer of data
  * @return CAResult_t
- * CA_STATUS_OK if Success, CA_STATUS_FAILED otherwise
+ * CA_STATUS_OK if Success, CA_MEMORY_ALLOC_FAILED if memory allocation fails
  */
 CAResult_t u_arraylist_add(u_arraylist_t *list, void *data);
 
 /**
  * @brief Remove the data of the index from the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param index
  *     [IN] index of array list
- * @return void pointer of the data
+ * @return void pointer of the data if success or NULL pointer otherwise
  */
-voidu_arraylist_remove(u_arraylist_t *list, uint32_t index);
+void *u_arraylist_remove(u_arraylist_t *list, uint32_t index);
 
 /**
  * @brief Returns the length of the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @return length of the array list
  */
@@ -101,16 +97,16 @@ uint32_t u_arraylist_length(const u_arraylist_t *list);
 
 /**
  * @brief Returns whether the data exists or not
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param data
  *     [IN] pointer of data
- * @return 1 if exists, 0 otherwise
+ * @return true if exists, false otherwise
  */
-uint8_t u_arraylist_contains(const u_arraylist_t *list, void *data);
+bool u_arraylist_contains(const u_arraylist_t *list,const void *data);
 
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* _U_ARRAYLIST_H_ */
+#endif /* U_ARRAYLIST_H_ */
diff --git a/resource/csdk/connectivity/common/inc/umutex.h b/resource/csdk/connectivity/common/inc/umutex.h
deleted file mode 100644 (file)
index 30f8336..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-/**
- * @file    umutex.h
- * @brief   This file provides APIs related to mutex and semaphores
- */
-
-#ifndef __UMUTEX_H_
-#define __UMUTEX_H_
-
-#include "cacommon.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-typedef void *u_mutex;
-typedef void *u_cond;
-
-/**
- * @fn  u_mutex_init
- * @brief  Initializes the thread system for using other mutex related APIs
- *
- */
-void u_mutex_init(void);
-
-/**
- * @fn  u_mutex_new
- * @brief  Creates new mutex
- *
- * @return  Reference to newly created mutex, otherwise NULL.
- *
- * @see u_mutex_Init
- */
-u_mutex u_mutex_new(void);
-
-/**
- * @fn  u_mutex_lock
- * @brief  Lock the mutex
- *
- * @param  mutex  The mutex to be locked
- *
- */
-void u_mutex_lock(u_mutex mutex);
-
-/**
- * @fn  u_mutex_trylock
- * @brief  Checks if the mutex can be locked
- *
- * @param  mutex  The mutex to be locked
- *
- * @return  CA_TRUE if the mutex is not locked currently, otherwise CA_FALSE.
- *
- */
-CABool_t u_mutex_trylock(u_mutex mutex);
-
-/**
- * @fn  u_mutex_unlock
- * @brief  Unlock the mutex
- *
- * @param  mutex  The mutex to be unlocked
- *
- */
-void u_mutex_unlock(u_mutex mutex);
-
-/**
- * @fn  u_mutex_free
- * @brief  Free the mutex
- *
- * @param  mutex  The mutex to be freed
- *
- */
-void u_mutex_free(u_mutex mutex);
-
-/**
- * @fn  u_cond_new
- * @brief  Creates new condition
- *
- * @return  Reference to newly created @u_cond, otherwise NULL.
- *
- * @see u_mutex_Init
- */
-u_cond u_cond_new(void);
-
-/**
- * @fn  u_cond_signal
- * @brief  One of threads is woken up if multiple threads are waiting for @cond
- *
- * @param  cond  The condtion to be signaled
- *
- */
-void u_cond_signal(u_cond cond);
-
-/**
- * @fn  u_cond_broadcast
- * @brief  All of threads are woken up if multiple threads are waiting for @cond
- *
- * @param  cond  The condtion to be signaled
- *
- */
-void u_cond_broadcast(u_cond cond);
-
-/**
- * @fn  u_cond_wait
- * @brief  Waits untill this thread woken up on @cond
- *
- * @param  cond  The condtion to be wait for to signal
- * @param  mutex  The mutex which is currently locked from calling thread
- *
- */
-void u_cond_wait(u_cond cond, u_mutex mutex);
-
-/**
- * @fn  u_cond_free
- * @brief  Free the condition
- *
- * @param  mutex  The condition to be freed
- *
- */
-void u_cond_free(u_cond cond);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif /* __cplusplus */
-
-#endif //__UMUTEX_H_
index b40be81..cc9a8bb 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  ******************************************************************/
 
 /**
- * @file uqueue.h
- * @brief This file contains the APIs for queue to be implemented
+ * @file
+ *
+ * This file contains the APIs for queue to be implemented.
  */
-#ifndef __U_QUEUE_H_
-#define __U_QUEUE_H_
+
+#ifndef U_QUEUE_H_
+#define U_QUEUE_H_
 
 #include "cacommon.h"
 
@@ -53,9 +55,9 @@ typedef struct u_queue_element_t u_queue_element;
 struct u_queue_element_t
 {
     /* pointer to queue message */
-    u_queue_message_tmessage;
+    u_queue_message_t *message;
     /* Pointer to next queue element*/
-    u_queue_elementnext;
+    u_queue_element *next;
 };
 
 /**
@@ -65,7 +67,7 @@ struct u_queue_element_t
 typedef struct u_queue_t
 {
     /* Head of the queue */
-    u_queue_elementelement;
+    u_queue_element *element;
     /* Number of messages in Queue*/
     uint32_t count;
 } u_queue_t;
@@ -74,7 +76,7 @@ typedef struct u_queue_t
  * @brief API to creates queue and initializes the elements.
  * @return  u_queue_t pointer if Success, NULL otherwise
  */
-u_queue_tu_queue_create();
+u_queue_t *u_queue_create();
 
 /**
  * @fn u_queue_delete
@@ -83,7 +85,7 @@ u_queue_t* u_queue_create();
  * @return CAResult_t - CA_STATUS_OK, if Success
  * @return            CA_STATUS_FAILED - otherwise
  */
-CAResult_t u_queue_delete(u_queue_tqueue);
+CAResult_t u_queue_delete(u_queue_t *queue);
 
 /**
  * @fn u_queue_add_element
@@ -93,7 +95,7 @@ CAResult_t u_queue_delete(u_queue_t* queue);
  * @return CAResult_t - CA_STATUS_OK, if Success
  * @return            CA_STATUS_FAILED - otherwise
  */
-CAResult_t u_queue_add_element(u_queue_tqueue, u_queue_message_t *message);
+CAResult_t u_queue_add_element(u_queue_t *queue, u_queue_message_t *message);
 
 /**
  * @fn u_queue_get_element
@@ -103,7 +105,7 @@ CAResult_t u_queue_add_element(u_queue_t* queue, u_queue_message_t *message);
  * @return pointer to Message, if Success
  * @return NULL - otherwise
  */
-u_queue_message_t* u_queue_get_element(u_queue_t* queue);
+u_queue_message_t *u_queue_get_element(u_queue_t *queue);
 
 /**
  * @fn u_queueRemoveElement
@@ -112,15 +114,14 @@ u_queue_message_t* u_queue_get_element(u_queue_t* queue);
  * @return CAResult_t - CA_STATUS_OK, if Success
  * @return            CA_STATUS_FAILED - otherwise
  */
-CAResult_t u_queue_remove_element(u_queue_tqueue);
+CAResult_t u_queue_remove_element(u_queue_t *queue);
 
 /**
  * @fn u_queue_get_size
- * Returns number of elements in queue
- * Input : queue - pointer to queue
- * Return : number of elements in queue
+ * @param queue - pointer to queue
+ * @return number of elements in queue
  */
-uint32_t u_queue_get_size(u_queue_tqueue);
+uint32_t u_queue_get_size(u_queue_t *queue);
 
 /**
  * @fn u_queue_reset
@@ -129,7 +130,7 @@ uint32_t u_queue_get_size(u_queue_t* queue);
  * @return CAResult_t - CA_STATUS_OK, if Success
  * @return            CA_STATUS_FAILED - otherwise
  */
-CAResult_t u_queue_reset(u_queue_tqueue);
+CAResult_t u_queue_reset(u_queue_t *queue);
 
 /**
  * @fn u_queue_get_head
@@ -138,10 +139,11 @@ CAResult_t u_queue_reset(u_queue_t* queue);
  * @return pointer to Message, if Success
  * @return NULL - otherwise
  */
-u_queue_message_t* u_queue_get_head(u_queue_t* queue);
+u_queue_message_t *u_queue_get_head(u_queue_t *queue);
 
 #ifdef __cplusplus
 } /* extern "C" */
 #endif /* __cplusplus */
 
-#endif /* _U_QUEUE_H_ */
+#endif /* U_QUEUE_H_ */
+
diff --git a/resource/csdk/connectivity/common/inc/uthreadpool.h b/resource/csdk/connectivity/common/inc/uthreadpool.h
deleted file mode 100644 (file)
index fefb852..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-/**
- * @file    uthreadpool.h
- * @brief   This file provides APIs related to thread pool
- */
-
-#ifndef __UTHREAD_POOL_H_
-#define __UTHREAD_POOL_H_
-
-#include <stdio.h>
-#include <malloc.h>
-#include <glib.h>
-#include <glib/gthreadpool.h>
-
-#include "cacommon.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-/**
- * @var u_thread_func
- * @brief Callback type can be registered to thread pool.
- */
-typedef void (*u_thread_func)(void *);
-
-/**
- * @struct u_thread_msg_t
- * @brief Structure to maintain the data which needs to send to task function.
- */
-typedef struct
-{
-    void *data;
-    u_thread_func func;
-} u_thread_msg_t;
-
-/**
- * @var u_thread_pool_t
- * @brief Thread pool type.
- */
-typedef void *u_thread_pool_t;
-
-/**
- * This function creates a newly allocated thread pool.
- *
- * @param num_of_threads The number of worker thread used in this pool.
- * @param thread_pool_handle Handle to newly create thread pool.
- * @return Error code, CA_STATUS_OK if success, else error number.
- */
-CAResult_t u_thread_pool_init(uint32_t num_of_threads, u_thread_pool_t *thread_pool_handle);
-
-/**
- * This function adds a routine to be executed by the thread pool at some future time.
- *
- * @param pool The thread pool structure.
- * @param routine The routine to be executed.
- * @param data The data to be passed to the routine.
- *
- * @return CA_STATUS_OK on success.
- * @return Error on failure.
- */
-CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(void *), void *data);
-
-/**
- * This function stops all the worker threads (stop & exit). And frees all the allocated memory.
- * Function will return only after joining all threads executing the currently scheduled tasks.
- *
- * @param pool The thread pool structure.
- */
-void u_thread_pool_free(u_thread_pool_t thread_pool);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif /* __cplusplus */
-
-#endif /* __UTHREAD_POOL_H_ */
diff --git a/resource/csdk/connectivity/common/src/camutex_pthreads.c b/resource/csdk/connectivity/common/src/camutex_pthreads.c
new file mode 100644 (file)
index 0000000..fea62f2
--- /dev/null
@@ -0,0 +1,378 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+//
+//*********************************************************************
+
+/**
+ * @file
+ * This file provides APIs related to mutex and semaphores.
+ */
+
+// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1b, Real-time extensions
+// (IEEE Std 1003.1b-1993) specification
+//
+// For this specific file, see use of clock_gettime and PTHREAD_MUTEX_DEFAULT
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif
+
+#include <string.h>
+#include <pthread.h>
+#include <errno.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/time.h>
+#include <assert.h>
+#include <oic_malloc.h>
+
+#include "camutex.h"
+#include "logger.h"
+
+/**
+ * TAG
+ * Logging tag for module name
+ */
+#define TAG PCF("UMUTEX")
+
+static const uint64_t USECS_PER_SEC         = 1000000;
+static const uint64_t NANOSECS_PER_USECS    = 1000;
+static const uint64_t NANOSECS_PER_SEC      = 1000000000L;
+
+typedef struct _tagMutexInfo_t
+{
+    pthread_mutex_t mutex;
+} ca_mutex_internal;
+
+typedef struct _tagEventInfo_t
+{
+    pthread_cond_t cond;
+    pthread_condattr_t condattr;
+} ca_cond_internal;
+
+ca_mutex ca_mutex_new(void)
+{
+    ca_mutex retVal = NULL;
+    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) OICMalloc(sizeof(ca_mutex_internal));
+    if (NULL != mutexInfo)
+    {
+        // create the mutex with the attributes set
+        int ret=pthread_mutex_init(&(mutexInfo->mutex), PTHREAD_MUTEX_DEFAULT);
+        if (0 == ret)
+        {
+            retVal = (ca_mutex) mutexInfo;
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
+            OICFree(mutexInfo);
+        }
+    }
+
+    return retVal;
+}
+
+bool ca_mutex_free(ca_mutex mutex)
+{
+    bool bRet=false;
+
+    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+    if (mutexInfo)
+    {
+        int ret = pthread_mutex_destroy(&mutexInfo->mutex);
+        if (0 == ret)
+        {
+            OICFree(mutexInfo);
+            bRet=true;
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
+        }
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+    }
+
+    return bRet;
+}
+
+void ca_mutex_lock(ca_mutex mutex)
+{
+    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+    if (mutexInfo)
+    {
+        int ret = pthread_mutex_lock(&mutexInfo->mutex);
+        assert(0 == ret);
+        if(ret != 0)
+        {
+            OIC_LOG_V(ERROR, TAG, "Pthread Mutex lock failed: %d", ret);
+            exit(ret);
+        }
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+        return;
+    }
+}
+
+bool ca_mutex_trylock(ca_mutex mutex)
+{
+    if (NULL == mutex)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+        return false;
+    }
+
+    bool bRet = false;
+
+    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+
+    int result = pthread_mutex_trylock(&mutexInfo->mutex);
+
+    switch (result)
+    {
+        case 0:
+            // Success
+            bRet = true;
+            break;
+        case EINVAL:
+            OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+            break;
+        case EBUSY:
+        default:
+            break;
+    }
+
+    return bRet;
+}
+
+void ca_mutex_unlock(ca_mutex mutex)
+{
+    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+    if (mutexInfo)
+    {
+        int ret = pthread_mutex_unlock(&mutexInfo->mutex);
+
+        assert ( 0 == ret);
+        if(ret != 0)
+        {
+            OIC_LOG_V(ERROR, TAG, "Pthread Mutex unlock failed: %d", ret);
+            exit(ret);
+        }
+        (void)ret;
+    }
+    else
+    {
+          OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+          return;
+    }
+}
+
+ca_cond ca_cond_new(void)
+{
+    ca_cond retVal = NULL;
+    ca_cond_internal *eventInfo = (ca_cond_internal*) OICMalloc(sizeof(ca_cond_internal));
+    if (NULL != eventInfo)
+    {
+        int ret = pthread_condattr_init(&(eventInfo->condattr));
+        if(0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "%s: Failed to initialize condition variable attribute %d!",
+                    __func__, ret);
+            OICFree(eventInfo);
+            return retVal;
+        }
+
+#if defined(__ANDROID__) || _POSIX_TIMERS > 0
+        ret = pthread_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
+
+        if(0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "%s: Failed to set condition variable clock %d!",
+                    __func__, ret);
+            pthread_condattr_destroy(&(eventInfo->condattr));
+            OICFree(eventInfo);
+            return retVal;
+        }
+#endif
+        ret = pthread_cond_init(&(eventInfo->cond), &(eventInfo->condattr));
+        if (0 == ret)
+        {
+            retVal = (ca_cond) eventInfo;
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "%s: Failed to initialize condition variable %d!", __func__, ret);
+            pthread_condattr_destroy(&(eventInfo->condattr));
+            OICFree(eventInfo);
+        }
+    }
+
+    return retVal;
+}
+
+void ca_cond_free(ca_cond cond)
+{
+    ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+    if (eventInfo != NULL)
+    {
+        int ret = pthread_cond_destroy(&(eventInfo->cond));
+        int ret2 = pthread_condattr_destroy(&(eventInfo->condattr));
+        if (0 == ret && 0 == ret2)
+        {
+            OICFree(cond);
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "%s: Failed to destroy condition variable %d, %d",
+                    __func__, ret, ret2);
+        }
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+    }
+}
+
+void ca_cond_signal(ca_cond cond)
+{
+    ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+    if (eventInfo != NULL)
+    {
+        int ret = pthread_cond_signal(&(eventInfo->cond));
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "%s: Failed to signal condition variable", __func__);
+        }
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+    }
+}
+
+void ca_cond_broadcast(ca_cond cond)
+{
+    ca_cond_internal* eventInfo = (ca_cond_internal*) cond;
+    if (eventInfo != NULL)
+    {
+        int ret = pthread_cond_broadcast(&(eventInfo->cond));
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "%s: failed to signal condition variable", __func__);
+        }
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+    }
+}
+
+void ca_cond_wait(ca_cond cond, ca_mutex mutex)
+{
+    ca_cond_wait_for(cond, mutex, 0L);
+}
+
+struct timespec ca_get_current_time()
+{
+#if defined(__ANDROID__) || _POSIX_TIMERS > 0
+    struct timespec ts;
+    clock_gettime(CLOCK_MONOTONIC, &ts);
+    return ts;
+#else
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    struct timespec ts;
+    TIMEVAL_TO_TIMESPEC(&tv, &ts);
+    return ts;
+#endif
+}
+
+void ca_add_microseconds_to_timespec(struct timespec* ts, uint64_t microseconds)
+{
+    time_t secPart = microseconds/USECS_PER_SEC;
+    uint64_t nsecPart = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
+    uint64_t totalNs = ts->tv_nsec + nsecPart;
+    time_t secOfNs = totalNs/NANOSECS_PER_SEC;
+
+    ts->tv_nsec = (totalNs)% NANOSECS_PER_SEC;
+    ts->tv_sec += secPart + secOfNs;
+}
+
+CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds)
+{
+    CAWaitResult_t retVal = CA_WAIT_INVAL;
+
+    ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+
+    if (NULL == mutexInfo)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex", __func__);
+        return CA_WAIT_INVAL;
+    }
+
+    if (NULL == eventInfo)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid condition", __func__);
+        return CA_WAIT_INVAL;
+    }
+
+    if (microseconds > 0)
+    {
+        struct timespec abstime = ca_get_current_time();
+        ca_add_microseconds_to_timespec(&abstime, microseconds);
+
+        //Wait for the given time
+        int ret = pthread_cond_timedwait(&(eventInfo->cond), &(mutexInfo->mutex), &abstime);
+        switch (ret)
+        {
+            case 0:
+                // Success
+                retVal = CA_WAIT_SUCCESS;
+                break;
+            case ETIMEDOUT:
+                retVal = CA_WAIT_TIMEDOUT;
+                break;
+            case EINVAL:
+                OIC_LOG_V(ERROR, TAG, "%s: condition, mutex, or abstime is Invalid", __func__);
+                retVal = CA_WAIT_INVAL;
+                break;
+            default:
+                OIC_LOG_V(ERROR, TAG, "%s: pthread_cond_timedwait returned %d", __func__, retVal);
+                retVal = CA_WAIT_INVAL;
+                break;
+        }
+    }
+    else
+    {
+        // Wait forever
+        int ret = pthread_cond_wait(&eventInfo->cond, &mutexInfo->mutex);
+        retVal = ret == 0 ? CA_WAIT_SUCCESS : CA_WAIT_INVAL;
+    }
+
+    return retVal;
+}
+
diff --git a/resource/csdk/connectivity/common/src/cathreadpool_pthreads.c b/resource/csdk/connectivity/common/src/cathreadpool_pthreads.c
new file mode 100644 (file)
index 0000000..744b1a5
--- /dev/null
@@ -0,0 +1,216 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs related to thread pool.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <pthread.h>
+#include "cathreadpool.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "uarraylist.h"
+#include "camutex.h"
+
+#define TAG PCF("UTHREADPOOL")
+
+/**
+ * empty struct to represent the details.  This implementation has no data
+ * that it needs to keep track of, so it only uses NULL for the internal value.
+ */
+typedef struct ca_thread_pool_details_t
+{
+    u_arraylist_t* threads_list;
+    ca_mutex list_lock;
+} ca_thread_pool_details_t;
+
+/**
+ * struct to wrap the pthreads callback properly.  The function pointer for
+ * pthreads requires a void* return value, however u_thread_func is a void.
+ */
+typedef struct ca_thread_pool_callback_info_t
+{
+    ca_thread_func func;
+    void* data;
+} ca_thread_pool_callback_info_t;
+
+// passthrough function to convert the pthreads call to a u_thread_func call
+void* ca_thread_pool_pthreads_delegate(void* data)
+{
+    ca_thread_pool_callback_info_t* info = (ca_thread_pool_callback_info_t*)data;
+    info->func(info->data);
+    OICFree(info);
+    return NULL;
+}
+
+// this implementation doesn't do a thread pool, so this function is essentially
+// a no-op besides creating a valid ca_thread_pool_t object.  It was determined after
+// reading through the existing implementation that the thread-pooling was unnecessary
+// for the posix platforms.  Behavior shouldn't be changed since previously num_of_threads
+// was greater than the number of requested threads.
+CAResult_t ca_thread_pool_init(int32_t num_of_threads, ca_thread_pool_t *thread_pool)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if(!thread_pool)
+    {
+        OIC_LOG(ERROR, TAG, "Parameter thread_pool was null!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if(num_of_threads <= 0)
+    {
+        OIC_LOG(ERROR, TAG, "num_of_threads must be positive and non-zero");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    *thread_pool = OICMalloc(sizeof(struct ca_thread_pool));
+
+    if(!*thread_pool)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate for thread-pool");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    (*thread_pool)->details = OICMalloc(sizeof(struct ca_thread_pool_details_t));
+    if(!(*thread_pool)->details)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate for thread-pool details");
+        OICFree(*thread_pool);
+        *thread_pool=NULL;
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    (*thread_pool)->details->list_lock = ca_mutex_new();
+
+    if(!(*thread_pool)->details->list_lock)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create thread-pool mutex");
+        OICFree((*thread_pool)->details);
+        OICFree(*thread_pool);
+        *thread_pool = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    (*thread_pool)->details->threads_list = u_arraylist_create();
+
+    if(!(*thread_pool)->details->threads_list)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create thread-pool list");
+        if(!ca_mutex_free((*thread_pool)->details->list_lock))
+        {
+            OIC_LOG(ERROR, TAG, "Failed to free thread-pool mutex");
+        }
+
+        OICFree((*thread_pool)->details);
+        OICFree(*thread_pool);
+        *thread_pool = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t ca_thread_pool_add_task(ca_thread_pool_t thread_pool, ca_thread_func method,
+                                    void *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if(NULL == thread_pool || NULL == method)
+    {
+        OIC_LOG(ERROR, TAG, "thread_pool or method was NULL");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    ca_thread_pool_callback_info_t* info = OICMalloc(sizeof(ca_thread_pool_callback_info_t));
+    if(!info)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate for memory wrapper");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    info->func = method;
+    info->data = data;
+
+    pthread_t threadHandle;
+
+    int result = pthread_create(&threadHandle, NULL, ca_thread_pool_pthreads_delegate, info);
+
+    if(result != 0)
+    {
+        OIC_LOG_V(ERROR, TAG, "Thread start failed with error %d", result);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(thread_pool->details->list_lock);
+    CAResult_t addResult = u_arraylist_add(thread_pool->details->threads_list, (void*)threadHandle);
+    ca_mutex_unlock(thread_pool->details->list_lock);
+
+    if(addResult != CA_STATUS_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Arraylist Add failed, may not be properly joined: %d", addResult);
+        return addResult;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void ca_thread_pool_free(ca_thread_pool_t thread_pool)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if(!thread_pool)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid parameter thread_pool was NULL");
+        return;
+    }
+
+    ca_mutex_lock(thread_pool->details->list_lock);
+
+    for(uint32_t i = 0; i<u_arraylist_length(thread_pool->details->threads_list); ++i)
+    {
+        pthread_t tid = (pthread_t)u_arraylist_get(thread_pool->details->threads_list, i);
+        int joinres = pthread_join(tid, NULL);
+        if(0 != joinres)
+        {
+            OIC_LOG_V(ERROR, TAG, "Failed to join thread at index %u with error %d", i, joinres);
+        }
+    }
+
+    CAResult_t freeres = u_arraylist_free(&(thread_pool->details->threads_list));
+    if(CA_STATUS_OK != freeres)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to free array list, error was: %d", freeres);
+    }
+
+    ca_mutex_unlock(thread_pool->details->list_lock);
+    ca_mutex_free(thread_pool->details->list_lock);
+
+    OICFree(thread_pool->details);
+    OICFree(thread_pool);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
index 03b6f85..9772f99 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1b, Real-time extensions
+// (IEEE Std 1003.1b-1993) specification
+//
+// For this specific file, see use of clock_gettime,
+// Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
+// and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif
+
+// Platform check can be extended to check and/or define more, or could be
+// moved into a config.h
+#if !defined(__ARDUINO__) && !defined(ARDUINO)
+#define HAVE_UNISTD_H 1
+#endif
+
+// Pull in _POSIX_TIMERS feature test macro to check for
+// clock_gettime() support.
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+
+// if we have unistd.h, we're a Unix system
+#include <time.h>
+#include <sys/time.h>
+#endif
+
 #include "logger.h"
 #include "string.h"
 #include "oic_logger.h"
 #include "oic_console_logger.h"
 
+#ifndef __TIZEN__
 static oic_log_ctx_t *logCtx = 0;
 
 static oic_log_level LEVEL_XTABLE[] =
 { OIC_LOG_DEBUG, OIC_LOG_INFO, OIC_LOG_WARNING, OIC_LOG_ERROR, OIC_LOG_FATAL };
 
-static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#endif
+
+static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 +
+        1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
 
 // Convert LogLevel to platform-specific severity level.  Store in PROGMEM on Arduino
 #ifdef __ANDROID__
+#ifdef ADB_SHELL
+static const char *LEVEL[] =
+{   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+
+#else
 static android_LogPriority LEVEL[] =
 {   ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
+#endif
 #elif defined __linux__
-static const char * LEVEL[] __attribute__ ((unused)) =
+static const char *LEVEL[] __attribute__ ((unused)) =
 {   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
 #elif defined ARDUINO
 #include <stdarg.h>
+#include "Arduino.h"
 
 PROGMEM const char level0[] = "DEBUG";
 PROGMEM const char level1[] = "INFO";
@@ -46,10 +85,10 @@ PROGMEM const char level2[] = "WARNING";
 PROGMEM const char level3[] = "ERROR";
 PROGMEM const char level4[] = "FATAL";
 
-PROGMEM const char * const LEVEL[] =
+PROGMEM const char *const LEVEL[] =
 {   level0, level1, level2, level3, level4};
 
-static void OICLogString(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr);
+static void OICLogString(LogLevel level, PROGMEM const char *tag, PROGMEM const char *logStr);
 #ifdef ARDUINO_ARCH_AVR
 //Mega2560 and other 8-bit AVR microcontrollers
 #define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_word(addr));}
@@ -60,8 +99,9 @@ static void OICLogString(LogLevel level, PROGMEM const char * tag, PROGMEM const
 #define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';}
 #endif
 #endif // __ANDROID__
-#ifndef ARDUINO
 
+#ifndef ARDUINO
+#ifndef __TIZEN__
 void OICLogConfig(oic_log_ctx_t *ctx)
 {
     logCtx = ctx;
@@ -90,7 +130,7 @@ void OICLogShutdown()
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, const char * tag, const char * logStr)
+void OICLog(LogLevel level, const char *tag, const char *logStr)
 {
     if (!logStr || !tag)
     {
@@ -98,7 +138,13 @@ void OICLog(LogLevel level, const char * tag, const char * logStr)
     }
 
 #ifdef __ANDROID__
+
+#ifdef ADB_SHELL
+    printf("%s: %s: %s\n", LEVEL[level], tag, logStr);
+#else
     __android_log_write(LEVEL[level], tag, logStr);
+#endif
+
 #elif defined __linux__
     if (logCtx && logCtx->write_level)
     {
@@ -107,7 +153,31 @@ void OICLog(LogLevel level, const char * tag, const char * logStr)
     }
     else
     {
-        printf("%s: %s: %s\n", LEVEL[level], tag, logStr);
+        int min = 0;
+        int sec = 0;
+        int ms = 0;
+#ifdef _POSIX_TIMERS
+        struct timespec when = {};
+        clockid_t clk = CLOCK_REALTIME;
+#ifdef CLOCK_REALTIME_COARSE
+        clk = CLOCK_REALTIME_COARSE;
+#endif
+        if (!clock_gettime(clk, &when))
+        {
+            min = (when.tv_sec / 60) % 60;
+            sec = when.tv_sec % 60;
+            ms = when.tv_nsec / 1000000;
+        }
+#else
+        struct timeval now;
+        if (!gettimeofday(&now, NULL))
+        {
+            min = (now.tv_sec / 60) % 60;
+            sec = now.tv_sec % 60;
+            ms = now.tv_usec * 1000;
+        }
+#endif
+        printf("%02d:%02d.%03d %s: %s: %s\n", min, sec, ms, LEVEL[level], tag, logStr);
     }
 #endif
 }
@@ -120,7 +190,7 @@ void OICLog(LogLevel level, const char * tag, const char * logStr)
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, const char * tag, const char * format, ...)
+void OICLogv(LogLevel level, const char *tag, const char *format, ...)
 {
     if (!format || !tag)
     {
@@ -143,7 +213,7 @@ void OICLogv(LogLevel level, const char * tag, const char * format, ...)
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize)
+void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize)
 {
     if (!buffer || !tag || (bufferSize == 0))
     {
@@ -173,8 +243,9 @@ void OICLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint
         OICLog(level, tag, lineBuffer);
     }
 }
-
-#else
+#endif //__TIZEN__
+#endif //ARDUINO
+#ifdef ARDUINO
 /**
  * Initialize the serial logger for Arduino
  * Only defined for Arduino
@@ -193,67 +264,68 @@ void OICLogInit()
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLogString(LogLevel level, PROGMEM const char * tag, const char * logStr)
-{
-    if (!logStr || !tag)
-    {
-        return;
-    }
-
-    char buffer[LINE_BUFFER_SIZE];
-
-    GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
-    Serial.print(buffer);
-
-    char c;
-    Serial.print(F(": "));
-    while ((c = pgm_read_byte(tag)))
-    {
-        Serial.write(c);
-        tag++;
-    }
-    Serial.print(F(": "));
-
-    Serial.println(logStr);
-}
+ void OICLogString(LogLevel level, PROGMEM const char * tag,
+         const char * logStr)
+ {
+     if (!logStr || !tag)
+     {
+         return;
+     }
+
+     char buffer[LINE_BUFFER_SIZE] = {0};
+     strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
+     Serial.print(buffer);
+
+     char c = NULL;
+     Serial.print(F(": "));
+     while ((c = pgm_read_byte(tag)))
+     {
+         Serial.write(c);
+         tag++;
+     }
+     Serial.print(F(": "));
+
+     Serial.println(logStr);
+ }
 
 /**
- * Output the contents of the specified buffer (in hex) with the specified priority level.
+ * Output the contents of the specified buffer (in hex) with the specified
+ * priority level.
  *
  * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
  * @param tag        - Module name
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize)
-{
-    if (!buffer || !tag || (bufferSize == 0))
-    {
-        return;
-    }
-
-    char lineBuffer[LINE_BUFFER_SIZE] =
-    {   0};
-    uint8_t lineIndex = 0;
-    for (uint8_t i = 0; i < bufferSize; i++)
-    {
+ void OICLogBuffer(LogLevel level, PROGMEM const char * tag,
+         const uint8_t * buffer, uint16_t bufferSize)
+ {
+     if (!buffer || !tag || (bufferSize == 0))
+     {
+         return;
+     }
+
+     char lineBuffer[LINE_BUFFER_SIZE] = {0};
+     uint8_t lineIndex = 0;
+     for (uint8_t i = 0; i < bufferSize; i++)
+     {
         // Format the buffer data into a line
         snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]);
         lineIndex++;
-        // Output 16 values per line
-        if (((i+1)%16) == 0)
-        {
-            OICLogString(level, tag, lineBuffer);
-            memset(lineBuffer, 0, sizeof lineBuffer);
-            lineIndex = 0;
-        }
-    }
-    // Output last values in the line, if any
-    if (bufferSize % 16)
-    {
-        OICLogString(level, tag, lineBuffer);
-    }
-}
+         // Output 16 values per line
+         if (((i+1)%16) == 0)
+         {
+             OICLogString(level, tag, lineBuffer);
+             memset(lineBuffer, 0, sizeof lineBuffer);
+             lineIndex = 0;
+         }
+     }
+     // Output last values in the line, if any
+     if (bufferSize % 16)
+     {
+         OICLogString(level, tag, lineBuffer);
+     }
+ }
 
 /**
  * Output a log string with the specified priority level.
@@ -263,18 +335,16 @@ void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buff
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr)
+void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+              PROGMEM const char *logStr)
 {
     if (!logStr || !tag)
     {
         return;
     }
-
-    char buffer[LINE_BUFFER_SIZE];
-
+    char buffer[LINE_BUFFER_SIZE] = {0};
     GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
     Serial.print(buffer);
-
     char c;
     Serial.print(F(": "));
     while ((c = pgm_read_byte(tag)))
@@ -283,7 +353,8 @@ void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logSt
         tag++;
     }
     Serial.print(F(": "));
-
+    Serial.print(lineNum);
+    Serial.print(F(": "));
     while ((c = pgm_read_byte(logStr)))
     {
         Serial.write(c);
@@ -300,29 +371,34 @@ void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logSt
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, PROGMEM const char * tag, const char * format, ...)
+void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+                PROGMEM const char *format, ...)
 {
     char buffer[LINE_BUFFER_SIZE];
     va_list ap;
     va_start(ap, format);
-
     GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
     Serial.print(buffer);
 
     char c;
     Serial.print(F(": "));
-
-    while ((c = pgm_read_byte(tag)))
-    {
-        Serial.write(c);
-        tag++;
-    }
+    while ((c = pgm_read_byte(tag))) {
+     Serial.write(c);
+     tag++;
+     }
+    Serial.print(F(": "));
+    Serial.print(lineNum);
     Serial.print(F(": "));
 
+#ifdef __AVR__
+    vsnprintf_P(buffer, sizeof(buffer), format, ap);
+#else
     vsnprintf(buffer, sizeof(buffer), format, ap);
-    for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines
+#endif
+    for (char *p = &buffer[0]; *p; p++)
     {
-        if(*p == '\n')
+        // emulate cooked mode for newlines
+        if (*p == '\n')
         {
             Serial.write('\r');
         }
@@ -339,23 +415,23 @@ void OICLogv(LogLevel level, PROGMEM const char * tag, const char * format, ...)
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, PROGMEM const char * tag, const __FlashStringHelper *format, ...)
+void OICLogv(LogLevel level, const char *tag, const __FlashStringHelper *format, ...)
 {
     char buffer[LINE_BUFFER_SIZE];
     va_list ap;
     va_start(ap, format);
+    // strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
+    // Serial.print(buffer);
 
-    GET_PROGMEM_BUFFER(buffer, &(LEVEL[level]));
-    Serial.print(buffer);
-
-    char c;
+    Serial.print(LEVEL[level]);
+    // char c;
     Serial.print(F(": "));
 
-    while ((c = pgm_read_byte(tag)))
-    {
-        Serial.write(c);
-        tag++;
-    }
+    /*while ((c = pgm_read_byte(tag))) {
+     Serial.write(c);
+     tag++;
+     }*/
+    Serial.print(tag);
     Serial.print(F(": "));
 
 #ifdef __AVR__
@@ -363,17 +439,20 @@ void OICLogv(LogLevel level, PROGMEM const char * tag, const __FlashStringHelper
 #else
     vsnprintf(buffer, sizeof(buffer), (const char *)format, ap); // for the rest of the world
 #endif
-    for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines
+    for (char *p = &buffer[0]; *p; p++)
     {
-        if(*p == '\n')
+        // emulate cooked mode for newlines
+        if (*p == '\n')
         {
-            Serial.write('\r');
+            // Serial.write('\r');
+            Serial.print('\r');
         }
-        Serial.write(*p);
+        //Serial.write(*p);
+        Serial.print(p);
     }
     Serial.println();
     va_end(ap);
 }
 
-#endif
+#endif //ARDUINO
 
index 500f5a6..bbad2c1 100644 (file)
@@ -32,8 +32,8 @@ typedef struct
 oic_log_ctx_t *oic_make_console_logger()
 {
     return oic_log_make_ctx(NULL, OIC_LOG_ALL, oic_console_logger_init, oic_console_logger_destroy,
-            oic_console_logger_flush, oic_console_logger_set_level, oic_console_logger_write,
-            oic_console_logger_set_module);
+                            oic_console_logger_flush, oic_console_logger_set_level,
+                            oic_console_logger_write,oic_console_logger_set_module);
 }
 
 int oic_console_logger_init(oic_log_ctx_t *ctx, void *world)
@@ -91,3 +91,4 @@ int oic_console_logger_set_module(oic_log_ctx_t *ctx, const char *module_name)
     /* We don't do anything special when the module name changes: */
     return 1;
 }
+
index 7c1d7e9..46106c6 100644 (file)
 #include <string.h>
 #include <stdlib.h>
 
-oic_log_ctx_t *oic_log_make_ctx(void* world, const oic_log_level level, oic_log_init_t init,
-        oic_log_destroy_t destroy, oic_log_flush_t flush, oic_log_set_level_t set_level,
-        oic_log_write_level_t write_level, oic_log_set_module_t set_module)
+oic_log_ctx_t *oic_log_make_ctx(void *world, const oic_log_level level, oic_log_init_t init,
+                                oic_log_destroy_t destroy, oic_log_flush_t flush,
+                                oic_log_set_level_t set_level,oic_log_write_level_t write_level,
+                                oic_log_set_module_t set_module)
 {
     oic_log_ctx_t *log_ctx;
 
     if (0 == init || 0 == destroy || 0 == flush || 0 == set_level || 0 == write_level
-            || 0 == set_module)
+        || 0 == set_module)
         return 0;
 
     if (__OIC_LOG_MIN__ > level || __OIC_LOG_MAX__ < level)
@@ -133,7 +134,11 @@ int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name)
     mn = (char *) malloc(1 + l);
 
     if (0 == mn)
+    {
+        if (0 != ctx->module_name)
+            free(ctx->module_name);
         return 0;
+    }
 
     memcpy(mn, module_name, 1 + l);
 
@@ -146,3 +151,4 @@ int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name)
     return ctx->set_module(ctx, ctx->module_name);
 }
 
+
index 8136c97..40b7363 100644 (file)
 #include "oic_malloc.h"
 
 // Enable extra debug logging for malloc.  Comment out to disable
-//#define ENABLE_MALLOC_DEBUG  (1)
-
 #ifdef ENABLE_MALLOC_DEBUG
 #include "logger.h"
-#define TAG PCF("OICMalloc")
+#define TAG "OICMalloc"
 #endif
 
 //-----------------------------------------------------------------------------
@@ -55,6 +53,9 @@
 //-----------------------------------------------------------------------------
 // Public APIs
 //-----------------------------------------------------------------------------
+#ifdef ENABLE_MALLOC_DEBUG
+static uint32_t count;
+#endif
 
 void *OICMalloc(size_t size)
 {
@@ -67,7 +68,8 @@ void *OICMalloc(size_t size)
     }
 
     ptr = malloc(size);
-    OIC_LOG_V(INFO, TAG, "malloc: ptr=%p, size=%u", ptr, size);
+    count++;
+    OIC_LOG_V(INFO, TAG, "malloc: ptr=%p, size=%u, count=%u", ptr, size, count);
     return ptr;
 #else
     if (0 == size)
@@ -78,12 +80,31 @@ void *OICMalloc(size_t size)
 #endif
 }
 
+void *OICCalloc(size_t num, size_t size)
+{
+    if(0 == size || 0 == num)
+    {
+        return NULL;
+    }
+
+#ifdef ENABLE_MALLOC_DEBUG
+    void *ptr = 0;
+
+    ptr = calloc(num, size);
+    OIC_LOG_V(INFO, TAG, "calloc: ptr=%p, num=%u, size=%u", ptr, num, size);
+    return ptr;
+#else
+    return calloc(num, size);
+#endif
+}
+
 void OICFree(void *ptr)
 {
 #ifdef ENABLE_MALLOC_DEBUG
-    OIC_LOG_V(INFO, TAG, "free: ptr=%p", ptr);
+    OIC_LOG_V(INFO, TAG, "free: ptr=%p, count=%u", ptr, --count);
 #endif
 
     free(ptr);
 }
 
+
diff --git a/resource/csdk/connectivity/common/src/oic_string.c b/resource/csdk/connectivity/common/src/oic_string.c
new file mode 100644 (file)
index 0000000..199b6f6
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "oic_string.h"
+
+#include <string.h>
+#include "oic_malloc.h"
+
+char *OICStrdup(const char *str)
+{
+    // Allocate memory for original string length and 1 extra byte for '\0'
+    size_t length = strlen(str);
+    char *dup = (char *)OICMalloc(length + 1);
+    if (NULL != dup)
+    {
+        memcpy(dup, str, length + 1);
+    }
+    return dup;
+}
+
index a618e51..7c569d4 100644 (file)
 #include "logger.h"
 #include "oic_malloc.h"
 
-#define TAG PCF("UARRAYLIST")
+#define TAG "UARRAYLIST"
+
+/**
+ * Use this default size when initialized
+ */
+#define U_ARRAYLIST_DEFAULT_SIZE 1
 
 u_arraylist_t *u_arraylist_create()
 {
     u_arraylist_t *list = NULL;
 
-    if (!(list = (u_arraylist_t*) OICMalloc(sizeof(u_arraylist_t))))
+    list = (u_arraylist_t *) OICMalloc(sizeof(u_arraylist_t));
+    if (!list)
     {
         return NULL;
     }
@@ -38,33 +44,39 @@ u_arraylist_t *u_arraylist_create()
     list->size = U_ARRAYLIST_DEFAULT_SIZE;
     list->length = 0;
 
-    if (!(list->data = (void*) OICMalloc(list->size * sizeof(void*))))
+    list->data = (void *) OICMalloc(list->size * sizeof(void *));
+    if (!list->data)
     {
+        OIC_LOG(DEBUG, TAG, "Out of memory");
         OICFree(list);
         return NULL;
     }
-
     return list;
 }
 
-CAResult_t u_arraylist_free(u_arraylist_t *list)
+CAResult_t u_arraylist_free(u_arraylist_t **list)
 {
-    OICFree(list->data);
-    OICFree(list);
+    if (!list || !(*list))
+    {
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    OICFree((*list)->data);
+    OICFree(*list);
 
-    list = NULL;
+    *list = NULL;
 
     return CA_STATUS_OK;
 }
 
 void *u_arraylist_get(const u_arraylist_t *list, uint32_t index)
 {
-    if (index >= list->length)
+    if (!list )
     {
         return NULL;
     }
 
-    if (list->data)
+    if ((index < list->length) && (list->data))
     {
         return list->data[index];
     }
@@ -74,31 +86,39 @@ void *u_arraylist_get(const u_arraylist_t *list, uint32_t index)
 
 CAResult_t u_arraylist_add(u_arraylist_t *list, void *data)
 {
-    uint32_t new_size = 0;
+    if (!list)
+    {
+        return CA_STATUS_INVALID_PARAM;
+    }
 
     if (list->size <= list->length)
     {
 
-        new_size = list->size + 1;
+       uint32_t new_size = list->size + 1;
         if (!(list->data = (void **) realloc(list->data, new_size * sizeof(void *))))
         {
-            return -1;
+            return CA_MEMORY_ALLOC_FAILED;
         }
 
-        (void) memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
+        memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
         list->size = new_size;
     }
 
     list->data[list->length] = data;
     list->length++;
 
-    return 0;
+    return CA_STATUS_OK;
 }
 
 void *u_arraylist_remove(u_arraylist_t *list, uint32_t index)
 {
     void *removed = NULL;
 
+    if (!list)
+    {
+        return NULL;
+    }
+
     if (index >= list->length)
     {
         return NULL;
@@ -115,6 +135,9 @@ void *u_arraylist_remove(u_arraylist_t *list, uint32_t index)
     list->size--;
     list->length--;
 
+    // check minimum size.
+    list->size = (list->size <= U_ARRAYLIST_DEFAULT_SIZE) ? U_ARRAYLIST_DEFAULT_SIZE : list->size;
+
     if (!(list->data = (void **) realloc(list->data, list->size * sizeof(void *))))
     {
         return NULL;
@@ -125,25 +148,34 @@ void *u_arraylist_remove(u_arraylist_t *list, uint32_t index)
 
 uint32_t u_arraylist_length(const u_arraylist_t *list)
 {
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "Invalid Parameter");
+        return 0;
+    }
     return list->length;
 }
 
-uint8_t u_arraylist_contains(const u_arraylist_t *list, void *data)
+bool u_arraylist_contains(const u_arraylist_t *list,const void *data)
 {
     uint32_t i = 0;
 
-    for (i = 0; i < u_arraylist_length(list); i++)
+    if (!list)
+    {
+        return false;
+    }
+
+    uint32_t length = u_arraylist_length(list);
+
+    for (i = 0; i < length; i++)
     {
         if (data == u_arraylist_get(list, i))
         {
-            return 1;
-        }
-        else
-        {
-            continue;
+            return true;
         }
     }
 
-    return 0;
+    return false;
 }
 
+
diff --git a/resource/csdk/connectivity/common/src/umutex.c b/resource/csdk/connectivity/common/src/umutex.c
deleted file mode 100644 (file)
index 6575453..0000000
+++ /dev/null
@@ -1,169 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-/**
- * @file    umutex.c
- * @brief   This file provides APIs related to mutex and semaphores
- */
-
-#include "umutex.h"
-#include <glib.h>
-
-#include "logger.h"
-#define TAG PCF("UMUTEX")
-
-void u_mutex_init(void)
-{
-    /*Initialize the glib thread system if it is not. GMutex works only if the threadsystem is initialized*/
-    if (!g_thread_supported())
-    {
-        g_thread_init(NULL);
-    }
-}
-
-u_mutex u_mutex_new(void)
-{
-    if (!g_thread_supported())
-    {
-        return NULL;
-    }
-
-    GMutex *mutexLock = g_mutex_new();
-    return (u_mutex) mutexLock;
-}
-
-void u_mutex_lock(u_mutex mutex)
-{
-    if (NULL == mutex)
-    {
-        OIC_LOG_V(ERROR, TAG ,"Invalid mutex !");
-        return;
-    }
-
-    GMutex *mutexLock = (GMutex*) mutex;
-    g_mutex_lock(mutexLock);
-}
-
-CABool_t u_mutex_trylock(u_mutex mutex)
-{
-    if (NULL == mutex)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
-        return CA_FALSE;
-    }
-
-    GMutex *mutexLock = (GMutex*) mutex;
-    gboolean ret = g_mutex_trylock(mutexLock);
-    if (TRUE == ret)
-    {
-        return CA_TRUE;
-    }
-
-    return CA_FALSE;
-}
-
-void u_mutex_unlock(u_mutex mutex)
-{
-    if (NULL == mutex)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
-        return;
-    }
-
-    GMutex *mutexLock = (GMutex*) mutex;
-    g_mutex_unlock(mutexLock);
-}
-
-void u_mutex_free(u_mutex mutex)
-{
-    if (NULL == mutex)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
-        return;
-    }
-
-    GMutex *mutexLock = (GMutex*) mutex;
-    g_mutex_free(mutexLock);
-}
-
-u_cond u_cond_new(void)
-{
-    if (!g_thread_supported())
-    {
-        return NULL;
-    }
-
-    GCond *condition = g_cond_new();
-    return (u_cond) condition;
-}
-
-void u_cond_signal(u_cond cond)
-{
-    if (NULL == cond)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
-        return;
-    }
-
-    GCond *condition = (GCond*) cond;
-    g_cond_signal(condition);
-}
-
-void u_cond_broadcast(u_cond cond)
-{
-    if (NULL == cond)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
-        return;
-    }
-
-    GCond *condition = (GCond*) cond;
-    g_cond_broadcast(condition);
-}
-
-void u_cond_wait(u_cond cond, u_mutex mutex)
-{
-    if (NULL == mutex)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
-        return;
-    }
-
-    if (NULL == cond)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
-        return;
-    }
-
-    GMutex *mutexLock = (GMutex*) mutex;
-    GCond *condition = (GCond*) cond;
-    g_cond_wait(condition, mutexLock);
-}
-
-void u_cond_free(u_cond cond)
-{
-    if (NULL == cond)
-    {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
-        return;
-    }
-
-    GCond *condition = (GCond*) cond;
-    g_cond_free(condition);
-}
-
index 5b04830..f9e0ada 100644 (file)
  * limitations under the License.
  *
  ******************************************************************/
+#include "uqueue.h"
 
 #include <stddef.h>
 #include <stdlib.h>
 #include <stdio.h>
-
 #include "logger.h"
-#include "uqueue.h"
 #include "oic_malloc.h"
 
+/**
+ * @def NO_MESSAGES
+ * @brief Number of messages in the queue
+ */
 #define NO_MESSAGES 0
-#define TAG PCF("UQUEUE")
 
-u_queue_t* u_queue_create()
+/**
+ * @def TAG
+ * @brief Logging tag for module name
+ */
+#define TAG "UQUEUE"
+
+u_queue_t *u_queue_create()
 {
-    u_queue_t* queuePtr = (u_queue_t*) OICMalloc(sizeof(u_queue_t));
+    u_queue_t *queuePtr = (u_queue_t *) OICMalloc(sizeof(u_queue_t));
     if (NULL == queuePtr)
     {
         OIC_LOG(DEBUG, TAG, "QueueCreate FAIL");
@@ -44,10 +52,10 @@ u_queue_t* u_queue_create()
     return queuePtr;
 }
 
-CAResult_t u_queue_add_element(u_queue_tqueue, u_queue_message_t *message)
+CAResult_t u_queue_add_element(u_queue_t *queue, u_queue_message_t *message)
 {
-    u_queue_elementelement = NULL;
-    u_queue_elementptr = NULL;
+    u_queue_element *element = NULL;
+    u_queue_element *ptr = NULL;
 
     if (NULL == queue)
     {
@@ -61,7 +69,7 @@ CAResult_t u_queue_add_element(u_queue_t* queue, u_queue_message_t *message)
         return CA_STATUS_FAILED;
     }
 
-    element = (u_queue_element*) OICMalloc(sizeof(u_queue_element));
+    element = (u_queue_element *) OICMalloc(sizeof(u_queue_element));
     if (NULL == element)
     {
         OIC_LOG(DEBUG, TAG, "QueueAddElement FAIL, memory allocation failed");
@@ -99,18 +107,15 @@ CAResult_t u_queue_add_element(u_queue_t* queue, u_queue_message_t *message)
         queue->element = element;
         queue->count++;
         OIC_LOG_V(DEBUG, TAG, "Queue Count : %d", queue->count);
-
-        return CA_STATUS_OK;
     }
 
     return CA_STATUS_OK;
 }
 
-u_queue_message_t* u_queue_get_element(u_queue_t* queue)
+u_queue_message_t *u_queue_get_element(u_queue_t *queue)
 {
-    u_queue_element* next = NULL;
-    u_queue_element* element = NULL;
-    u_queue_message_t* message = NULL;
+    u_queue_element *element = NULL;
+    u_queue_message_t *message = NULL;
 
     if (NULL == queue)
     {
@@ -122,12 +127,11 @@ u_queue_message_t* u_queue_get_element(u_queue_t* queue)
 
     if (NULL == element)
     {
-        OIC_LOG(DEBUG, TAG, "QueueGetElement : FAIL, no messages");
+        OIC_LOG(DEBUG, TAG, "QueueGetElement : empty, no messages");
         return NULL;
     }
 
-    next = element->next;
-    queue->element = next;
+    queue->element = element->next;;
     queue->count--;
 
     message = element->message;
@@ -135,10 +139,10 @@ u_queue_message_t* u_queue_get_element(u_queue_t* queue)
     return message;
 }
 
-CAResult_t u_queue_remove_element(u_queue_tqueue)
+CAResult_t u_queue_remove_element(u_queue_t *queue)
 {
-    u_queue_elementnext = NULL;
-    u_queue_elementremove = NULL;
+    u_queue_element *next = NULL;
+    u_queue_element *remove = NULL;
 
     if (NULL == queue)
     {
@@ -165,7 +169,7 @@ CAResult_t u_queue_remove_element(u_queue_t* queue)
     return CA_STATUS_OK;
 }
 
-uint32_t u_queue_get_size(u_queue_tqueue)
+uint32_t u_queue_get_size(u_queue_t *queue)
 {
     if (NULL == queue)
     {
@@ -176,10 +180,8 @@ uint32_t u_queue_get_size(u_queue_t* queue)
     return queue->count;
 }
 
-CAResult_t u_queue_reset(u_queue_tqueue)
+CAResult_t u_queue_reset(u_queue_t *queue)
 {
-    CAResult_t error = CA_STATUS_FAILED;
-
     if (NULL == queue)
     {
         OIC_LOG(DEBUG, TAG, "QueueReset FAIL, Invalid Queue");
@@ -194,9 +196,7 @@ CAResult_t u_queue_reset(u_queue_t* queue)
 
     while (NULL != queue->element)
     {
-        error = u_queue_remove_element(queue);
-        if (error == CA_STATUS_FAILED)
-            break;
+       u_queue_remove_element(queue);
     }
 
     if (NO_MESSAGES != queue->count)
@@ -209,7 +209,7 @@ CAResult_t u_queue_reset(u_queue_t* queue)
 
 }
 
-CAResult_t u_queue_delete(u_queue_tqueue)
+CAResult_t u_queue_delete(u_queue_t *queue)
 {
     CAResult_t error = CA_STATUS_FAILED;
 
@@ -230,7 +230,7 @@ CAResult_t u_queue_delete(u_queue_t* queue)
     return (CA_STATUS_OK);
 }
 
-u_queue_message_t* u_queue_get_head(u_queue_t* queue)
+u_queue_message_t *u_queue_get_head(u_queue_t *queue)
 {
     if (NULL == queue)
     {
@@ -245,3 +245,4 @@ u_queue_message_t* u_queue_get_head(u_queue_t* queue)
     }
     return queue->element->message;
 }
+
diff --git a/resource/csdk/connectivity/common/src/uthreadpool.c b/resource/csdk/connectivity/common/src/uthreadpool.c
deleted file mode 100644 (file)
index 477d5fd..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-/**
- * @file    uthreadpool.c
- * @brief   This file provides APIs related to thread pool
- */
-
-#include "uthreadpool.h"
-#include "logger.h"
-#include "oic_malloc.h"
-#define TAG PCF("UTHREADPOOL")
-
-/**
- * @var gThreadpool
- * @brief Glib thread pool.
- */
-static GThreadPool *gThreadpool;
-
-/**
- * @fn run
- * @brief function which is registed to glib thread pool.
- */
-static void run(void *thread_data, void *user_data);
-
-CAResult_t u_thread_pool_init(uint32_t num_of_threads, u_thread_pool_t *thread_pool)
-{
-    OIC_LOG_V(DEBUG, TAG, "IN");
-
-    GError *error = NULL;
-    gThreadpool = g_thread_pool_new(run, NULL, num_of_threads, FALSE, &error);
-    if (NULL == gThreadpool)
-    {
-        OIC_LOG_V(ERROR, TAG, "Error: g_thread_pool_new failed!");
-        if (NULL != error)
-        {
-            OIC_LOG_V(ERROR, TAG, "Error is: %s", error->message);
-            g_error_free(error);
-        }
-        return CA_STATUS_FAILED;
-    }
-    *thread_pool = (u_thread_pool_t) gThreadpool;
-
-    OIC_LOG_V(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(void *), void *data)
-{
-    OIC_LOG_V(DEBUG, TAG, "IN");
-
-    gboolean result = FALSE;
-    if (NULL == routine)
-    {
-        OIC_LOG_V(ERROR, TAG, "Error: routine is NULL!");
-        return CA_STATUS_FAILED;
-    }
-
-    u_thread_msg_t *message = (u_thread_msg_t *) OICMalloc(sizeof(u_thread_msg_t));
-    message->data = data;
-    message->func = routine;
-    result = g_thread_pool_push((GThreadPool *) thread_pool, (void *) message, NULL);
-    if (FALSE == result)
-    {
-        OIC_LOG_V(ERROR, TAG, "Error: Failed to push the task to threadpool!");
-        return CA_STATUS_FAILED;
-    }
-
-    OIC_LOG_V(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-void u_thread_pool_free(u_thread_pool_t thread_pool)
-{
-    OIC_LOG_V(DEBUG, TAG, "IN");
-
-    GThreadPool *threadpool = (GThreadPool *) thread_pool;
-    g_thread_pool_free(threadpool, TRUE, TRUE);
-
-    OIC_LOG_V(DEBUG, TAG, "OUT");
-}
-
-void run(void *thread_data, void *user_data)
-{
-    u_thread_msg_t *message = (u_thread_msg_t *) thread_data;
-
-    if (message && message->func)
-    {
-        OIC_LOG_V(DEBUG, TAG, "Calling routine with data as parameter");
-        message->func(message->data);
-    }
-    else
-    {
-        OIC_LOG_V(ERROR, TAG, "Error: Invalid task data");
-        return;
-    }
-
-    //Free message
-    OICFree(message);
-    message = NULL;
-}
diff --git a/resource/csdk/connectivity/external/inc/ocsecurityconfig.h b/resource/csdk/connectivity/external/inc/ocsecurityconfig.h
new file mode 100644 (file)
index 0000000..9ad8af4
--- /dev/null
@@ -0,0 +1,56 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Corporation All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OC_SECURITY_CONFIG_H
+#define OC_SECURITY_CONFIG_H
+
+#include <stdint.h>
+
+#define DTLS_PSK_ID_LEN 16
+#define DTLS_PSK_PSK_LEN 16
+
+#define DtlsPskCredsBlobVer_1 1 /**< Credentials stored in plaintext */
+#define DtlsPskCredsBlobVer_CurrentVersion DtlsPskCredsBlobVer_1
+
+/**
+ * Credentials for a device. Includes identity and the associated PSK.
+ */
+typedef struct
+{
+   unsigned char id[DTLS_PSK_ID_LEN];
+   unsigned char psk[DTLS_PSK_PSK_LEN];
+} OCDtlsPskCreds;
+
+/**
+ * Binary blob containing device identity and the credentials for all devices
+ * trusted by this device.
+ */
+typedef struct
+{
+   unsigned char identity[DTLS_PSK_ID_LEN]; /** identity of self */
+   uint32_t num;                            /** number of credentials in this blob */
+   OCDtlsPskCreds creds[1];                 /** list of credentials. Size of this
+                                                array is determined by 'num' variable. */
+} OCDtlsPskCredsBlob;
+
+#endif //OC_SECURITY_CONFIG_H
+
+
+
index 67a44cb..d0da447 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  ******************************************************************/
 
 /**
- * @file caadapterinterface.h
- * @brief This file contains the APIs for adapters to be implemented
+ * @file
+ *
+ * This file contains the APIs for adapters to be implemented.
  */
-#ifndef __CA_ADAPTER_INTERFACE_H_
-#define __CA_ADAPTER_INTERFACE_H_
+
+#ifndef CA_ADAPTER_INTERFACE_H_
+#define CA_ADAPTER_INTERFACE_H_
 
 #include "cacommon.h"
 
@@ -34,72 +36,60 @@ extern "C"
 
 /**
  * @brief Starting connectivity adapters and each adapter have transport specific behavior.
- *  Transport Specific Behavior:
- *   WIFI/ETH connectivity Starts unicast server on  all available IPs and defined port number as per specification.
- *   EDR will not start any specific servers.
- *   LE will not start any specific servers.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * Transport Specific Behavior:
+ * WIFI/ETH connectivity Starts unicast server on  all available IPs and defined
+ * port number as per specification.
+ * EDR will not start any specific servers.
+ * LE will not start any specific servers.
+ * @return CA_STATUS_OK or CA_STATUS_FAILED
+ *  ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 typedef CAResult_t (*CAAdapterStart)();
 
 /**
  * @brief Starting listening server for receiving multicast search requests
  * Transport Specific Behavior:
- *   WIFI/ETH Starts multicast server on  all available IPs and defined port number and as per specification.
- *   EDR  Starts RFCOMM Server with prefixed UUID as per specification.
- *   LE Start GATT Server with prefixed UUID and Characteristics as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * WIFI/ETH Starts multicast server on  all available IPs and defined
+ * port number and as per specification.
+ * EDR  Starts RFCOMM Server with prefixed UUID as per specification.
+ * LE Start GATT Server with prefixed UUID and Characteristics as per OIC Specification.
+ * @return CA_STATUS_OK or CA_STATUS_FAILED
+ * ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 typedef CAResult_t (*CAAdapterStartListeningServer)();
 
 /**
  * @brief for starting discovery servers for receiving multicast advertisements
  * Transport Specific Behavior:
- *   WIFI/ETH Starts multicast server on all available IPs and defined port number as per OIC Specification.
- *   EDR Starts RFCOMM Server with prefixed UUID as per OIC Specification.
- *   LE Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * WIFI/ETH Starts multicast server on all available IPs and defined port
+ * number as per OIC Specification.
+ * EDR Starts RFCOMM Server with prefixed UUID as per OIC Specification.
+ * LE Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification.
+ * @return CA_STATUS_OK or CA_STATUS_FAILED
+ * ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 typedef CAResult_t (*CAAdapterStartDiscoveryServer)();
 
 /**
  * @brief Sends data to the endpoint using the adapter connectivity.
  * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port,
+ * reference uri and connectivity type) to which the unicast data has to be sent.
  * @param   data        [IN]    Data which required to be sent.
  * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
  */
-typedef uint32_t (*CAAdapterSendUnitcastData)(const CARemoteEndpoint_t* endpoint, void* data,
-        uint32_t dataLen);
+typedef int32_t (*CAAdapterSendUnitcastData)(const CARemoteEndpoint_t *endpoint,
+        const void *data, uint32_t dataLen);
 
 /**
  * @brief Sends Multicast data to the endpoint using the adapter connectivity.
  * Note: length must be > 0.
  * @param   data        [IN]    Data which required to be sent.
  * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
  */
-typedef uint32_t (*CAAdapterSendMulticastData)(void* data, uint32_t dataLen);
-
-/**
- * @brief Starts notification server on adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-typedef CAResult_t (*CAAdapterStartNotificationRecvServer)();
-
-/**
- * @brief Send notification information to the given endpoint.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-typedef uint32_t (*CAAdapterSendNotification)(const CARemoteEndpoint_t* endpoint, void* data,
-        uint32_t dataLen);
+typedef int32_t (*CAAdapterSendMulticastData)(const void *data, uint32_t dataLen);
 
 /**
  * @brief Get Network Information
@@ -107,7 +97,7 @@ typedef uint32_t (*CAAdapterSendNotification)(const CARemoteEndpoint_t* endpoint
  * @param   size        [OUT]   Number of local connectivity structures.
  * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-typedef CAResult_t (*CAAdapterGetNetworkInfo)(CALocalConnectivityt_t** info, uint32_t* size);
+typedef CAResult_t (*CAAdapterGetNetworkInfo)(CALocalConnectivity_t **info, uint32_t *size);
 
 /**
  * @brief Read Synchronous API callback.
@@ -118,15 +108,16 @@ typedef CAResult_t (*CAAdapterReadData)();
 /**
  * @brief Stopping the adapters and close socket connections
  * Transport Specific Behavior:
- *   WIFI/ETH Stops all listening servers and close sockets.
- *   EDR Stops all RFCOMM servers and close sockets.
- *   LE Stops all GATT servers and close sockets.
+ * WIFI/ETH Stops all listening servers and close sockets.
+ * EDR Stops all RFCOMM servers and close sockets.
+ * LE Stops all GATT servers and close sockets.
  * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
 typedef CAResult_t (*CAAdapterStop)();
 
 /**
- * @brief Terminate the connectivity adapter.Configuration information will be deleted from further use
+ * @brief Terminate the connectivity adapter.Configuration information will be deleted from
+ * further use. Freeing Memory of threadpool and mutexs and cleanup will be done.
  */
 typedef void (*CAAdapterTerminate)();
 
@@ -137,24 +128,28 @@ typedef struct
 {
     /** Start Transport specific functions*/
     CAAdapterStart startAdapter;
+
     /** Listening Server function address*/
     CAAdapterStartListeningServer startListenServer;
+
     /** Discovery Server function address **/
-    CAAdapterStartDiscoveryServer startDiscoverServer;
+    CAAdapterStartDiscoveryServer startDiscoveryServer;
+
     /** Unicast data function address**/
     CAAdapterSendUnitcastData sendData;
+
     /** Multicast data function address**/
     CAAdapterSendMulticastData sendDataToAll;
-    /** Notify server function address**/
-    CAAdapterStartNotificationRecvServer startNotifyServer;
-    /** Send Notification function address**/
-    CAAdapterSendNotification sendNotification;
+
     /** Get Networking information  **/
     CAAdapterGetNetworkInfo GetnetInfo;
+
     /** Read Data function address**/
     CAAdapterReadData readData;
+
     /** Stop Transport specific functions*/
     CAAdapterStop stopAdapter;
+
     /** Terminate function address stored in this pointer**/
     CAAdapterTerminate terminate;
 
@@ -162,26 +157,27 @@ typedef struct
 
 /**
  * @brief This will be used during the registration of adapters call backs to the common logic
- * @see CAConnectivityHandler_t , CAConnectivityType_t
+ * @see CAConnectivityHandler_t , CATransportType_t
  */
 typedef void (*CARegisterConnectivityCallback)(CAConnectivityHandler_t handler,
-        CAConnectivityType_t cType);
+        CATransportType_t cType);
 
 /**
  * @brief This will be used during the recive of network requests and response.
  * @see SendUnitcastData(), SendMulticastData()
  */
-typedef void (*CANetworkPacketReceivedCallback)(CARemoteEndpoint_t* endPoint, void* data,
+typedef void (*CANetworkPacketReceivedCallback)(CARemoteEndpoint_t *endPoint, void *data,
         uint32_t dataLen);
 
 /**
- * @brief This will be used to intimate network changes to the connectivity common logic layer
+ * @brief This will be used to notify network changes to the connectivity common logic layer
  * @see SendUnitcastData(), SendMulticastData()
  */
-typedef void (*CANetworkChangeCallback)(CALocalConnectivityt_t* info, CANetworkStatus_t status);
+typedef void (*CANetworkChangeCallback)(CALocalConnectivity_t *info, CANetworkStatus_t status);
 
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif  // __CA_ADAPTER_INTERFACE_H_
+#endif  /* CA_ADAPTER_INTERFACE_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caadapternetdtls.h b/resource/csdk/connectivity/inc/caadapternetdtls.h
new file mode 100644 (file)
index 0000000..debf3d3
--- /dev/null
@@ -0,0 +1,230 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#ifndef CA_ADAPTER_NET_DTLS_H_
+#define CA_ADAPTER_NET_DTLS_H_
+
+#include "dtls.h"
+#include "uarraylist.h"
+#include "camutex.h"
+#include "caadapterutils.h"
+#include "ocsecurityconfig.h"
+#include "cainterface.h"
+
+/**
+ *   Currently DTLS supported adapters(2) WIFI and ETHENET for linux platform.
+ */
+#define MAX_SUPPORTED_ADAPTERS 2
+
+/**
+ * @brief The implementation will be provided by OIC RI layer.
+ */
+extern void OCGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo);
+
+typedef void (*CAPacketReceivedCallback)(const char *ipAddress, const uint16_t port,
+         const void *data, const uint32_t dataLength, const bool isSecured);
+
+typedef uint32_t (*CAPacketSendCallback)(const char *ipAddress, const uint16_t port,
+        const void *data, const uint32_t dataLength);
+
+/**
+ * @struct stCAAdapterCallbacks_t
+ * @brief  Data structure for holding the send and recv callbacks.
+ */
+typedef struct CAAdapterCallbacks
+{
+    CAPacketReceivedCallback recvCallback;  /**< Callback used to send data to upper layer. */
+    CAPacketSendCallback sendCallback;      /**< Callback used to send data to socket layer. */
+} stCAAdapterCallbacks_t;
+
+/**
+ * @struct stCADtlsContext_t
+ * @brief  Data structure for holding the tinyDTLS interface
+ *              related info.
+ */
+typedef struct stCADtlsContext
+{
+    u_arraylist_t *cacheList;            /**< PDU's are cached until DTLS session is formed. */
+    struct dtls_context_t *dtlsContext;  /**< Pointer to tinyDTLS context. */
+    struct stPacketInfo *packetInfo;     /**< used by callback during
+                                             decryption to hold address/length. */
+    dtls_handler_t callbacks;            /**< Pointer to callbacks needed by tinyDTLS. */
+    stCAAdapterCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
+} stCADtlsContext_t;
+
+/**
+ * @struct stPacketInfo_t
+ * @brief  Data structure for holding the decrypted data address
+ *              and length provided by tinyDTLS callback interface.
+ */
+typedef struct stPacketInfo
+{
+    uint8_t *dataAddress;
+    uint16_t dataLen;
+} stPacketInfo_t;
+
+/**
+ * @enum eDtlsRet_t
+ * @brief tinyDTLS library error codes.
+ *
+ */
+typedef enum
+{
+    DTLS_OK = 0,
+    DTLS_FAIL,
+    DTLS_SESSION_INITIATED,
+    DTLS_HS_MSG
+} eDtlsRet_t;
+
+
+/** Structure to have address information which will match with DTLS session_t struct.*/
+typedef struct
+{
+    socklen_t size;                 /**< Size of address. */
+    union
+    {
+        struct sockaddr     sa;
+        struct sockaddr_storage st;
+        struct sockaddr_in  sin;
+        struct sockaddr_in6 sin6;
+    } addr;                         /**< Address information. */
+    uint8_t ifIndex;                /**< Holds adpater index to get callback info. */
+} stCADtlsAddrInfo_t;
+
+/**
+ * @struct stCACacheMessage_t
+ * @brief structure to holds the information of cachemessage and address info.
+ *
+ */
+typedef struct CACacheMessage
+{
+    void *data;
+    uint32_t dataLen;
+    stCADtlsAddrInfo_t *destSession;
+} stCACacheMessage_t;
+
+/**
+ * @enum eDtlsAdapterType_t
+ * @brief This enum is used as array index for storing adapter level callbacks.
+ *        So Keeping 0 instead of "1 << 0". It is not going to be used as addition
+ *        and removal of adapter.
+ *
+ */
+typedef enum
+{
+    DTLS_IP = 0,
+} eDtlsAdapterType_t;
+
+/**
+ * @fn  CADTLSSetAdapterCallbacks
+ * @brief  Used set send and recv callbacks for different adapters(WIFI,EtherNet)
+ *
+ * @param[in]  recvCallback  packet received callback
+ * @param[in]  sendCallback  packet sent callback
+ * @param[in]  type  type of adapter
+ *
+ * @retval  void
+ *
+ */
+void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
+                               CAPacketSendCallback sendCallback, eDtlsAdapterType_t type);
+
+/**
+ * @brief   Register callback to get DTLS PSK credentials.
+ * @param   credCallback   [IN] callback to get DTLS credentials
+ * @retval  void
+ */
+void CADTLSSetCredentialsCallback(CAGetDTLSCredentialsHandler credCallback);
+
+/**
+ * @fn  CAAdapterNetDtlsInit
+ * @brief  initialize tinyDTLS library and other necessary intialization.
+ *
+ * @return  0 on success otherwise a positive error value.
+ * @retval  CA_STATUS_OK  Successful
+ * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAAdapterNetDtlsInit();
+
+/**
+ * @fn  CAAdapterNetDtlsDeInit
+ * @brief  de-inits tinyDTLS library and free the allocated memory.
+ *
+ * @return  void
+ *
+ */
+void CAAdapterNetDtlsDeInit();
+
+/**
+ * @fn  CAAdapterNetDtlsEncrypt
+ * @brief  Performs DTLS encryption of the CoAP PDU. If a
+ *              DTLS session does not exist yet with the @dst,
+ *              a DTLS handshake will be started. In case where
+ *              a new DTLS handshake is started, pdu info is
+ *              cached to be send when session setup is finished.
+ *
+ * @param[in]  remoteAddress  address to which data will be sent.
+ * @param[in]  port  port to which data will be sent.
+ * @param[in]  data  length of data.
+ * @param[in]  dataLen  length of given data
+ * @param[out]  decdata  output variable to store the starting address
+ *                        of decrypted plaintext.
+ * @param[out]  cacheFlag  utput variable to indicate if pdu
+ *                        is cached and inform the caller to
+ *                       NOT free the memory holding pdu.
+ * @return  0 on success otherwise a positive error value.
+ * @retval  CA_STATUS_OK  Successful
+ * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  CA_STATUS_FAILED Operation failed
+ *
+ */
+
+CAResult_t CAAdapterNetDtlsEncrypt(const char *remoteAddress,
+                                   const uint16_t port,
+                                   void *data,
+                                   uint32_t dataLen,
+                                   uint8_t *cacheFlag,
+                                   eDtlsAdapterType_t type);
+
+/**
+ * @fn  CAAdapterNetDtlsDecrypt
+ * @brief  Performs DTLS decryption of the data received on
+ *            secure port. This method performs in-place decryption
+ *            of the cipher-text buffer. If a DTLS handshake message
+ *            is received or decryption failure happens, this method
+ *            returns -1. If a valid application PDU is decrypted, it
+ *            returns the length of the decrypted pdu.
+ *
+ * @return  0 on success otherwise a positive error value.
+ * @retval  CA_STATUS_OK  Successful
+ * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAAdapterNetDtlsDecrypt(const char *remoteAddress,
+                                   const uint16_t port,
+                                   uint8_t *data,
+                                   uint32_t dataLen,
+                                   eDtlsAdapterType_t type);
+
+#endif /* CA_ADAPTER_NET_DTLS_H_ */
+
+
diff --git a/resource/csdk/connectivity/inc/caadapterutils.h b/resource/csdk/connectivity/inc/caadapterutils.h
new file mode 100644 (file)
index 0000000..f78cebb
--- /dev/null
@@ -0,0 +1,312 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains common utility function for CA transport adaptors.
+ */
+
+#ifndef CA_ADAPTER_UTILS_H_
+#define CA_ADAPTER_UTILS_H_
+
+#include <stdbool.h>
+#ifdef __ANDROID__
+#include <jni.h>
+#endif
+
+#include "cacommon.h"
+#include "logger.h"
+#include "pdu.h"
+#include "uarraylist.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @def VERIFY_NON_NULL
+ * @brief Macro to verify the validity of input argument
+ */
+#define VERIFY_NON_NULL(arg, log_tag, log_message) \
+    if (NULL == arg ){ \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        return CA_STATUS_INVALID_PARAM; \
+    } \
+
+/**
+ * @def VERIFY_NON_NULL_RET
+ * @brief Macro to verify the validity of input argument
+ */
+#define VERIFY_NON_NULL_RET(arg, log_tag, log_message,ret) \
+    if (NULL == arg ){ \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        return ret; \
+    } \
+
+/**
+ * @def VERIFY_NON_NULL_VOID
+ * @brief Macro to verify the validity of input argument
+ */
+#define VERIFY_NON_NULL_VOID(arg, log_tag, log_message) \
+    if (NULL == arg ){ \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        return; \
+    } \
+
+/**
+ * @brief Length of network interface name.
+ */
+#define CA_INTERFACE_NAME_SIZE 16
+
+/**
+ * @def IPV4_ADDR_ONE_OCTECT_LEN
+ * @brief Macro to allocate memory for ipv4 address in the form of uint8_t.
+ */
+#define IPV4_ADDR_ONE_OCTECT_LEN 4
+
+/**
+ * @brief Network Interface Information.
+ */
+typedef struct
+{
+    char ipAddress[CA_IPADDR_SIZE];             /**< Address of the interface  **/
+    char subnetMask[CA_IPADDR_SIZE];            /**< Maintains interface subnetmask **/
+    char interfaceName[CA_INTERFACE_NAME_SIZE]; /**< Interface  name**/
+} CANetInfo_t;
+
+/**
+ * @brief unicast and multicast server information.
+ */
+typedef struct
+{
+    int socketFd;                               /**< Socket decriptor **/
+    char ipAddress[CA_IPADDR_SIZE];             /**< Address of the ip **/
+    uint16_t port;                              /**< Server port number **/
+    bool isSecured;                             /**< Indicates secured server **/
+    bool isServerStarted;                       /**< Indicates server started **/
+    bool isMulticastServer;                     /**< Indicates multicast server **/
+    char ifAddr[CA_IPADDR_SIZE];                /**< Address of the multicast interface  **/
+    char interfaceName[CA_INTERFACE_NAME_SIZE]; /**< Interface Name **/
+    char subNetMask[CA_IPADDR_SIZE];            /**< Subnet Mask **/
+} CAServerInfo_t;
+
+/**
+ * @brief To log the PDU data
+ */
+void CALogPDUData(coap_pdu_t *pdu);
+
+/**
+ * @fn CAAdapterCreateLocalEndpoint
+ * @brief Create CALocalConnectivity_t instance.
+ */
+CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CATransportType_t type, const char *address);
+
+/**
+ * @fn CAAdapterCopyLocalEndpoint
+ * @brief Create CALocalConnectivity_t duplicate instance.
+ */
+CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *connectivity);
+
+/**
+ * @fn CAAdapterFreeLocalEndpoint
+ * @brief Deallocate CALocalConnectivity_t instance.
+ */
+void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndPoint);
+
+/**
+ * @fn CAAdapterCreateRemoteEndpoint
+ * @brief Allocate CARemoteEndpoint_t instance.
+ */
+CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CATransportType_t type, const char *address,
+                                                  const char *resourceUri);
+
+/**
+ * @fn CAAdapterCopyRemoteEndpoint
+ * @brief Create CARemoteEndpoint_t duplicate instance.
+ */
+CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(
+    const CARemoteEndpoint_t *remoteEndpoint);
+
+/**
+ * @fn CAAdapterFreeRemoteEndpoint
+ * @brief Deallocate CARemoteEndpoint_t instance.
+ */
+void CAAdapterFreeRemoteEndpoint(CARemoteEndpoint_t *remoteEndPoint);
+
+/**
+ * @fn CAParseIPv4AddressInternal
+ * @brief   To parse the IP address and port from "ipaddress:port"
+ * @param   ipAddrStr   [IN]   IP address to be parsed
+ * @param   ipAddr      [OUT]  Parsed IP address
+ * @param   ipAddr      [IN]   Buffer length for parsed IP address
+ * @param   port        [OUT]  Parsed Port number
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
+                                      size_t ipAddrLen, uint16_t *port);
+
+/**
+ * @fn CAAdapterIsSameSubnet
+ * @brief Check if two ip address belong to same subnet.
+ * @param   ipAddress1   [IN]   IP address to be checked
+ * @param   ipAddress2   [IN]   IP address to be checked
+ * @param   netMask      [IN]   Subnet mask
+ * @return  true if same subnet and false if not same subnet
+ */
+bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2,
+                           const char *netMask);
+/**
+ * @brief  Used to check the multicast server is running or not.
+ *
+ * @param   serverInfoList    [IN] Server information list.
+ * @param   ipAddress         [IN] Interface address of the server.
+ * @param   multicastAddress  [IN] Multicast address of the server.
+ * @param   port              [IN] Port number of the server.
+ *
+ * @return  true or false.
+ */
+bool CAIsMulticastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress,
+                                const char *multicastAddress, uint16_t port);
+
+/**
+ * @brief  Used to check the unicast server is running or not.
+ *
+ * @param   serverInfoList  [IN] Server information list.
+ * @param   ipAddress       [IN] Ip address of the server.
+ * @param   port            [IN] Port number of the server.
+ *
+ * @return  true or false.
+ */
+bool CAIsUnicastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress,
+                              uint16_t port);
+
+/**
+ * @brief  Used to get the port number based on given information.
+ *
+ * @param   serverInfoList  [IN] Server information list.
+ * @param   ipAddress       [IN] Ip address of the server.
+ * @param   isSecured       [IN] specifies whether to get secured or normal unicast server port.
+ *
+ * @return  positive value on success and 0 on error.
+ */
+uint16_t CAGetServerPort(const u_arraylist_t *serverInfoList, const char *ipAddress,
+                         bool isSecured);
+
+/**
+ * @brief  Used to get the socket fd for given server information.
+ *
+ * @param   serverInfoList  [IN] Server information list.
+ * @param   ipAddress       [IN] Ip address of the server.
+ * @param   isSecured       [IN] To check whether it is secured server or not.
+ * @param   isMulticast     [IN] To check whether it is multicast server or not.
+ * @param   type            [IN] CA_IPV4, CA_IPV6 etc.
+
+ * @return  positive value on success and -1 on error.
+ */
+int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList, const char *ipAddress,
+                                  bool isSecured, bool isMulticast, CATransportType_t type);
+
+/**
+ * @brief  Used to add the server information into serverinfo list
+ *
+ * @param   serverInfoList     [INOUT] server information list.
+ * @param   info               [IN] server informations like ip, port.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Initialization failed
+ */
+CAResult_t CAAddServerInfo(u_arraylist_t *serverInfoList, CAServerInfo_t *info);
+
+/**
+ * @brief  Used to remove the server information based on socket fd from server info list.
+ *
+ * @param   serverInfoList  [INOUT] server information list.
+ * @param   sockFd          [IN] Socket descriptor.
+ *
+ * @return  None
+ */
+void CARemoveServerInfo(u_arraylist_t *serverInfoList, int sockFd);
+
+/**
+ * @brief  Used to clear the memory of network inteface list
+ *         Memory pointed by infoList will become invalid after this function call.
+ *
+ * @param   infoList  [IN] Network interface list.
+ *
+ * @return  None
+ */
+void CAClearNetInterfaceInfoList(u_arraylist_t *infoList);
+
+/**
+ * @brief  Used to clear the memory of server info list.
+ *         Memory pointed by serverInfoList will become invalid after this function call.
+ *
+ * @param   infoList  [IN] Server information list.
+ *
+ * @return  None
+ */
+void CAClearServerInfoList(u_arraylist_t *serverInfoList);
+
+#ifdef __ANDROID__
+/**
+ * @fn CANativeJNISetContext
+ * @brief   To set context of JNI Application
+ *          This must be called by the Android API before CA Initialization
+ * @param   env         [IN] JNI interface pointer
+ * @param   context     [IN] context object
+ * @return  None
+ */
+void CANativeJNISetContext(JNIEnv *env, jobject context);
+
+/**
+ * @fn CANativeJNISetJavaVM
+ * @brief   To set jvm object
+ *          This must be called by the Android API before CA Initialization
+ * @param   jvm         [IN] jvm object
+ * @return  None
+ */
+void CANativeJNISetJavaVM(JavaVM *jvm);
+
+/**
+ * @fn CANativeJNISetContext
+ * @brief   To get context
+ *          Called by adapters to get Application context
+ * @return  context object
+ */
+jobject CANativeJNIGetContext();
+
+/**
+ * @fn CANativeJNIGetJavaVM
+ * @brief   To get JVM object
+ *          Called from adapters to get JavaVM object
+ * @return  JVM object
+ */
+JavaVM *CANativeJNIGetJavaVM();
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+#endif  /* CA_ADAPTER_UTILS_H_ */
+
index 2b68a07..678f864 100644 (file)
  * limitations under the License.
  *
  ******************************************************************/
+
 /**
- * @file caedradapter.h
- * @brief This file contains the APIs for EDR adapters to be implemented
+ * @file
+ *
+ * This file contains the APIs for EDR adapters.
  */
-#ifndef __CA_EDRADAPTER_H_
-#define __CA_EDRADAPTER_H_
+
+#ifndef CA_EDRADAPTER_H_
+#define CA_EDRADAPTER_H_
 
 /**
- * BT Interface AP
+ * EDR Interface AP
  **/
 #include "cacommon.h"
 #include "caadapterinterface.h"
+#include "cathreadpool.h" /* for thread pool */
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
-#ifndef BLUETOOTH_ADAPTER_TAG
-#define BLUETOOTH_ADAPTER_TAG "CA_EDR"
-#endif //BLUETOOTH_ADAPTER_TAG
 /**
- * @brief Initialize EDR connectivity interface.
- * @param registerCallback [IN] To register EDR interfaces to Connectivity Abstraction Layer
- * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
- * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief   Initialize EDR Interface.
+ * @param   registerCallback  [IN] Callback to register EDR interface to Connectivity
+ *                                 Abstraction Layer
+ * @param   reqRespCallback   [IN] Callback to notify request and response messages from server(s)
+ *                                 started at Connectivity Abstraction Layer.
+ * @param   netCallback       [IN] Callback to notify the network additions to Connectivity
+ *                                 Abstraction Layer.
+ * @param   handle            [IN] Threadpool Handle
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
+                           CANetworkPacketReceivedCallback reqRespCallback,
+                           CANetworkChangeCallback netCallback, ca_thread_pool_t handle);
 
 /**
- * @brief Starting EDR connectivity adapters .As its peer to peer it doesnot require to start any servers
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief   Starts EDR connectivity adapters. As its peer to peer it doesnot require to start
+ *          any servers.
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 CAResult_t CAStartEDR();
 
 /**
- * @brief Starting listening server for receiving multicast search requests
- * Transport Specific Behavior:
- *   EDR  Starts RFCOMM Server with prefixed UUID as per specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief  Starts listening server for receiving multicast search requests.
+ * Starts  RFCOMM Server with prefixed UUID as per OIC specification.
+ *
+ * @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 CAResult_t CAStartEDRListeningServer();
 
 /**
- * @brief for starting discovery servers for receiving multicast advertisements
- * Transport Specific Behavior:
- *   EDR Starts RFCOMM server with prefixed UUID as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief  Starting discovery server for receiving multicast advertisements.
+ * Starts  RFCOMM Server with prefixed UUID as per OIC specification.
+ *
+ * @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 CAResult_t CAStartEDRDiscoveryServer();
 
 /**
- * @brief Sends data to the endpoint using the adapter connectivity.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
-
-/**
- * @brief Sends Multicast data to the endpoint using the EDR connectivity.
- * Note: length must be > 0.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendEDRMulticastData(void* data, uint32_t dataLen);
-
-/**
- * @brief Starts notification server on EDR adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief  Sends data to the peer bluetooth OIC device using the adapter connectivity.
+ * @param  remoteEndpoint  [IN] Remote Endpoint information (like ipaddress, port, reference uri and
+ *                              connectivity type) to which the unicast data has to be sent.
+ * @param  data            [IN] Data to be sent.
+ * @param  dataLength      [IN] Size of data to be sent.
+ * @return The number of bytes sent on the network. Returns -1 on error.
+ *
  */
-CAResult_t CAStartEDRNotifyServer();
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                             uint32_t dataLength);
 
 /**
- * @brief Send notification information.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @brief  Sends multicast data to all discovered bluetooth OIC devices using the adapter
+ *         connectivity.
+ * @param  data         [IN]  Data which needs to be sent to all discovered bluetooth OIC device.
+ * @param  dataLength   [IN]  Length of data in bytes.
+ * @return Number of bytes sent on the network. Returns -1 on error.
  */
-uint32_t CASendEDRNotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength);
 
 /**
- * @brief Get EDR Connectivity network information
- * @param   info        [OUT]   Local connectivity information structures
- * @param   size        [OUT]   Number of local connectivity structures.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief  Get EDR Connectivity network information.
+ *
+ * @param  info [OUT] Array of local connectivity information structures.
+ * @param  size [OUT] Size of the array @info.
+ *
+ * @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
  */
-CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size);
+CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
 
 /**
- * @brief Read Synchronous API callback.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief  Read Synchronous API callback.
+ * @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 CAResult_t CAReadEDRData();
 
 /**
- * @brief Stopping the adapters and close socket connections
- *   EDR Stops all RFCOMM servers and close sockets.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief  EDR Stops all RFCOMM servers and close sockets.
+ * @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
  */
 CAResult_t CAStopEDR();
 
 /**
- * @brief Terminate the EDR connectivity adapter.
- * Configuration information will be deleted from further use
+ * @brief  Terminate the EDR connectivity adapter.
+ * Configuration information will be deleted from further use.
+ * @return NONE
  */
 void CATerminateEDR();
 
+/**
+ * @brief  Initializes the adapter queues.
+ * This will initiates both server and receiver adapter queues.
+ * @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAAdapterStartQueue();
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif  //__CA_EDRADAPTER_H_
+#endif  /* CA_EDRADAPTER_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caedradapter_singlethread.h b/resource/csdk/connectivity/inc/caedradapter_singlethread.h
new file mode 100644 (file)
index 0000000..a5996d0
--- /dev/null
@@ -0,0 +1,153 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the APIs for EDR adapters to be implemented.
+ */
+
+#ifndef CA_EDRADAPTER_SINGLETHREAD_H_
+#define CA_EDRADAPTER_SINGLETHREAD_H_
+
+/**
+ * EDR Interface AP
+ **/
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief  Initialize EDR Interface.
+ * @param  registerCallback  [IN] Callback to register EDR interface to Connectivity
+ *                                Abstraction Layer
+ * @param  reqRespCallback   [IN] Callback to notify request and response messages from server(s)
+ *                                started at Connectivity Abstraction Layer.
+ * @param  netCallback       [IN] Callback to notify the network additions to Connectivity
+ *                                Abstraction Layer.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval #CA_ADAPTER_NOT_ENABLED Initialization is successful, but bluetooth adapter is not
+ *                                 enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
+                           CANetworkPacketReceivedCallback reqRespCallback,
+                           CANetworkChangeCallback netCallback);
+
+/**
+ * @brief  Starting EDR connectivity adapters. As its peer to peer it doesnot require to start
+ *         any servers.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED Bluetooth adapter is not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStartEDR();
+
+/**
+ * @brief  Starts listening server for receiving multicast search requests.
+ *         Starts RFCOMM Server with prefixed UUID as per OIC specification.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_SERVER_STARTED_ALREADY  Server is already started and running for the predefined
+ *                                     service UUID
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStartEDRListeningServer();
+
+/**
+ * @brief  Starts discovery server for receiving multicast advertisements.
+ *         Starts RFCOMM Server with prefixed UUID as per OIC specification.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_SERVER_STARTED_ALREADY Server is already started and running for the predefined
+ *                                    service UUID
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStartEDRDiscoveryServer();
+
+/**
+ * @brief  Sends data to the peer bluetooth OIC device using the adapter connectivity.
+ * @param  remoteEndpoint  [IN] Remote Endpoint information (like ipaddress, port, reference uri and
+ *                              connectivity type) to which the unicast data has to be sent.
+ * @param  data            [IN] Data to be sent.
+ * @param  dataLength      [IN] Size of data to be sent.
+ * @return Number of bytes sent on the network. Returns -1 on error.
+ */
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                              uint32_t dataLength);
+
+/**
+ * @brief  Sends multicast data to all discovered bluetooth OIC devices using the adapter
+ *         connectivity.
+ * @param  data         [IN]  Data which needs to be sent to all discovered bluetooth OIC device.
+ * @param  dataLength   [IN]  Length of data in bytes.
+ * @return Number of bytes sent on the network. Returns -1 on error.
+ */
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength);
+
+/**
+ * @brief  Get EDR Connectivity network information.
+ *
+ * @param  info [OUT] Array of local connectivity information structures.
+ * @param  size [OUT] Size of the array @info.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input parameters
+ * @retval #CA_MEMORY_ALLOC_FAILED  Failed to allocate memory
+ * @retval #CA_STATUS_FAILED Operation failed
+ * @remarks info is allocated in this API and should be freed by the caller.
+ */
+CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief  Read Synchronous API callback.
+ * @return #CA_STATUS_OK on success otherwise proper error code.
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAReadEDRData();
+
+/**
+ * @brief  EDR Stops all RFCOMM servers and close sockets.
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStopEDR();
+
+/**
+ * @brief  Terminate the EDR connectivity adapter.
+ * Configuration information will be deleted from further use.
+ * @return NONE
+ */
+void CATerminateEDR();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  /* CA_EDRADAPTER_SINGLETHREAD_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caedrinterface.h b/resource/csdk/connectivity/inc/caedrinterface.h
new file mode 100644 (file)
index 0000000..57ac40e
--- /dev/null
@@ -0,0 +1,288 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs for EDR adapter - client, server, network monitor
+ * modules.
+ */
+
+#ifndef CA_EDR_INTERFACE_H_
+#define CA_EDR_INTERFACE_H_
+
+#include "caedradapter.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#ifndef OIC_EDR_SERVICE_ID
+#define OIC_EDR_SERVICE_ID "12341234-1C25-481F-9DFB-59193D238280"
+#endif //OIC_EDR_SERVICE_ID
+
+typedef enum
+{
+    STATE_DISCONNECTED, /**< State is Disconnected */
+    STATE_CONNECTED /**< State is Connected */
+} CAConnectedState_t;
+
+typedef struct connected_state
+{
+    uint8_t address[CA_MACADDR_SIZE];
+    CAConnectedState_t state;
+} state_t;
+
+/**
+ * @enum  CAAdapterServerType_t
+ * @brief Enum for defining different server types.
+ */
+typedef enum
+{
+    CA_UNICAST_SERVER = 0,    /**< Unicast Server */
+    CA_MULTICAST_SERVER,      /**< Multicast Server */
+    CA_SECURED_UNICAST_SERVER /**< Secured Unicast Server */
+} CAAdapterServerType_t;
+
+/**
+ * @struct CAEDRData
+ * @brief  Structure to maintain the information of data in message queue.
+ */
+typedef struct
+{
+    CARemoteEndpoint_t *remoteEndpoint; /**< Remote Endpoint */
+    void *data;                         /**< Data to be sent */
+    uint32_t dataLen;                   /**< Length of the data to be sent */
+} CAEDRData;
+
+/**
+ * @struct CAEDRNetworkEvent
+ * @brief  Structure to maintain the adapter information and its status.
+ */
+typedef struct
+{
+    CALocalConnectivity_t *info; /**< Local Connectivity Information */
+    CANetworkStatus_t status;    /**< Network Status */
+} CAEDRNetworkEvent;
+
+/**
+ * @brief This will be used during the recive of network requests and response.
+ * @param remoteAddress [IN] EDR address of remote OIC device from which data received.
+ * @param data          [IN] Data received
+ * @param dataLength    [IN] Length of the Data received
+ * @param sentLength    [OUT] Length of the sent data
+ * @return NONE
+ * @pre Callback must be registered using CAEDRSetPacketReceivedCallback()
+ */
+typedef void (*CAEDRDataReceivedCallback)(const char *remoteAddress, const void *data,
+                                          uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief This will be used during change in network status.
+ * @param status        [IN] Network Status of the adapter
+ * @return NONE
+ */
+typedef void (*CAEDRNetworkStatusCallback)(CANetworkStatus_t status);
+
+/**
+ * @brief  Initialize the network monitor module
+ * @param  threadPool   [IN] Threadpool Handle
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED Initialization is successful, but bluetooth adapter is
+ *                                 not enabled.
+ * @retval #CA_STATUS_FAILED Operation failed
+ * @see  CAEDRTerminateNetworkMonitor()
+ */
+CAResult_t CAEDRInitializeNetworkMonitor(const ca_thread_pool_t threadPool);
+
+/**
+ * @brief  Deinitialize with bluetooth adapter.
+ * @return NONE
+ * @pre    CAEDRInitializeNetworkMonitor() should be invoked before using this API.
+ * @see    CAEDRInitializeNetworkMonitor()
+ */
+void CAEDRTerminateNetworkMonitor();
+
+/**
+ * @brief  Start Network Monitoring Process
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRStartNetworkMonitor();
+
+/**
+ * @brief  Stop Network Monitoring Process
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRStopNetworkMonitor();
+
+/**
+ * @brief  Sets the callback and Starts discovery for nearby OIC bluetooth devices.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRClientSetCallbacks();
+
+/**
+ * @brief  Resetting callbacks with bluetooth framework and stop OIC device discovery.
+ * @return NONE
+ * @pre    CAEDRClientSetCallbacks() should be invoked before using this API.
+ * @see    CAEDRClientSetCallbacks()
+ */
+void CAEDRClientUnsetCallbacks();
+
+/**
+ * @brief  Used to initialize the EDR client module where mutex is initialized
+ * @return NONE
+ */
+void CAEDRInitializeClient(ca_thread_pool_t handle);
+
+/**
+ * @brief  Destroys the Device list and mutex.
+ * @return NONE
+ */
+void CAEDRClientTerminate();
+
+/**
+ * @brief  Closes all the client connection to peer bluetooth devices.
+ * @return NONE
+ */
+void CAEDRClientDisconnectAll();
+
+/**
+ * @brief  Register callback to send the received packets from remote bluetooth device to BTAdapter.
+ *
+ * @param  packetReceivedCallback [IN] Callback function to register for sending network
+ *                                     packets to EDR Adapter.
+ * @return NONE
+ */
+void CAEDRSetPacketReceivedCallback(CAEDRDataReceivedCallback packetReceivedCallback);
+
+/**
+ * @brief  Register callback for receiving local bluetooth adapter state.
+ *
+ * @param  networkStateChangeCallback [IN] Callback function to register for receiving local
+ *                                         bluetooth adapter status.
+ * @return NONE
+ */
+void CAEDRSetNetworkChangeCallback(CAEDRNetworkStatusCallback networkStateChangeCallback);
+
+/**
+ * @brief  Get the local bluetooth adapter information.
+ *
+ * @param  info [OUT] Local bluetooth adapter information
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ * @see #CALocalConnectivity_t
+ *
+ */
+CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info);
+
+/**
+ * @brief  Start RFCOMM server for given service UUID
+ *
+ * @param  serviceUUID  [IN] The UUID of service with which RFCOMM server needs to be started.
+ * @param  serverFD     [IN] The RFCOMM server socket file descriptor.
+ * @param  handle       [IN] Threadpool Handle
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAEDRServerStart(const char *serviceUUID, int *serverFD, ca_thread_pool_t handle);
+
+/**
+ * @brief  Stop RFCOMM server
+ *
+ * @param  serverFD [IN] The RFCOMM server socket file descriptor which needs to be stopped.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRServerStop(int serverFD);
+
+/**
+ * @brief   Terminate server for EDR
+ * @return  None
+ */
+void CAEDRServerTerminate();
+
+/**
+ * @brief  All received data will be notified to upper layer.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAEDRManagerReadData();
+
+/**
+ * @brief  This function gets bluetooth adapter enable state.
+ * @param  state    [OUT] State of the Adapter.
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRGetAdapterEnableState(bool *state);
+
+/**
+ * @brief  This function sends data to specified remote bluetooth device.
+ * @param  remoteAddress   [IN] Remote EDR Address
+ * @param  serviceUUID     [IN] Service UUID of the device
+ * @param  data            [IN] Data to be sent
+ * @param  dataLength      [IN] Length of the data to be sent
+ * @param  sentLength      [OUT] Length of the actual sent data
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress, const char *serviceUUID,
+                                      const void *data, uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief  This function sends data to all bluetooth devices running OIC service.
+ * @param  serviceUUID     [IN] Service UUID of the device
+ * @param  data            [IN] Data to be sent
+ * @param  dataLength      [IN] Length of the data to be sent
+ * @param  sentLength      [OUT] Length of the actual sent data
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, const void *data,
+                                        uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief This function gets bonded bluetooth device list
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRGetBondedDeviceList();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_INTERFACE_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caerrorcode.h b/resource/csdk/connectivity/inc/caerrorcode.h
deleted file mode 100644 (file)
index 80905b4..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef __CA_ERROR_CODE_H_
-#define __CA_ERROR_CODE_H_
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/**
- * Declares Stack Results & Errors
- */
-typedef enum
-{
-    OC_STACK_OK = 0,
-    OC_STACK_INVALID_URI,
-    OC_STACK_INVALID_QUERY,
-    OC_STACK_INVALID_IP,
-    OC_STACK_INVALID_PORT,
-    OC_STACK_INVALID_CALLBACK,
-    OC_STACK_INVALID_METHOD,
-    OC_STACK_INVALID_PARAM,
-    OC_STACK_INVALID_OBSERVE_PARAM,
-    OC_STACK_NO_MEMORY,
-    OC_STACK_COMM_ERROR,
-    OC_STACK_NOTIMPL,
-    OC_STACK_NO_RESOURCE, /* resource not found*/
-    OC_STACK_RESOURCE_ERROR, /*ex: not supported method or interface*/
-    OC_STACK_SLOW_RESOURCE,
-    OC_STACK_NO_OBSERVERS, /* resource has no registered observers */
-    OC_STACK_OBSERVER_NOT_FOUND,
-    OC_STACK_OBSERVER_NOT_ADDED,
-    OC_STACK_OBSERVER_NOT_REMOVED,
-#ifdef WITH_PRESENCE
-    OC_STACK_PRESENCE_NO_UPDATE,
-    OC_STACK_PRESENCE_STOPPED,
-    OC_STACK_PRESENCE_DO_NOT_HANDLE,
-#endif
-    OC_STACK_ERROR
-} OCStackResult;
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif //#ifndef __CA_ERROR_CODE_H_
diff --git a/resource/csdk/connectivity/inc/caethernetadapter.h b/resource/csdk/connectivity/inc/caethernetadapter.h
deleted file mode 100644 (file)
index 61e8a4d..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-/**
- * @file caethernetadapter.h
- * @brief This file contains the APIs for Ethernet Adapter.
- */
-#ifndef __CA_ETHERNET_ADAPTER_H__
-#define __CA_ETHERNET_ADAPTER_H__
-
-#include "cacommon.h"
-#include "caadapterinterface.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/**
- * @brief Initialize Ethernet connectivity interface.
- * @param registerCallback [IN] To register Ethernet interfaces to Connectivity Abstraction Layer
- * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
- * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
-
-/**
- * @brief Start Ethernet Interface adapter.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartEthernet();
-
-/**
- * @brief Starting listening server for receiving multicast search requests
- * Transport Specific Behavior:
- *   Ethernet Starts Multicast Server on  all available IPs and prefixed port number and as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartEthernetListeningServer();
-
-/**
- * @brief for starting discovery servers for receiving multicast advertisements
- * Transport Specific Behavior:
- *  Ethernet Starts Start multicast server on all available IPs and prefixed port number as per OIC Specification
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartEthernetDiscoveryServer();
-
-/**
- * @brief Sends data to the endpoint using the adapter connectivity.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t* endpoint, void* data,
-        uint32_t dataLen);
-
-/**
- * @brief Sends Multicast data to the endpoint using the WIFI connectivity.
- * Note: length must be > 0.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendEthernetMulticastData(void* data, uint32_t dataLen);
-
-/**
- * @brief Starts notification server on Ethernet adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartEthernetNotifyServer();
-
-/**
- * @brief Send notification information.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendEthernetNotification(const CARemoteEndpoint_t* endpoint, void* data,
-        uint32_t dataLen);
-/**
- * @brief Get Ethernet Connectivity network information
- * @param   info        [OUT]   Local connectivity information structures
- * @param   size        [OUT]   Number of local connectivity structures.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size);
-
-/**
- * @brief Read Synchronous API callback.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAReadEthernetData();
-
-/**
- * @brief Stopping the adapters and close socket connections
- *   Ethernet Stops all multicast and unicast servers and close sockets.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStopEthernet();
-
-/**
- * @brief Terminate the Ethernet connectivity adapter.
- * Configuration information will be deleted from further use
- */
-void CATerminateEthernet();
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif
index d2af4d2..8aa5940 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  * limitations under the License.
  *
  ******************************************************************/
-#ifndef __CA_INTERFACE_CONTROLLER_H_
-#define __CA_INTERFACE_CONTROLLER_H_
+
+/**
+ * @file
+ *
+ * This file contains common utility function for CA transport adaptors.
+ */
+
+#ifndef CA_INTERFACE_CONTROLLER_H_
+#define CA_INTERFACE_CONTROLLER_H_
 
 #include "caadapterinterface.h"
+#include "cathreadpool.h" /* for thread pool */
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
-void CAInitializeAdapters();
+/**
+ * @brief   Initializes different adapters based on the compilation flags.
+ * @param   handle         [IN]    thread pool handle created by message handler for different adapters.
+ * @return  none
+ */
+void CAInitializeAdapters(ca_thread_pool_t handle);
 
+/**
+ * @brief   Set the received packets callback for message handler
+ * @param   callback       [IN]    message handler callback to receive packets from different adapters.
+ * @return  none
+ */
 void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback);
 
-void CAStartAdapter(CAConnectivityType_t connectivity);
+/**
+ * @brief   Set the network status changed callback for message handler
+ * @param   callback       [IN]    message handler network status callback to receive network changes.
+ * @return  none
+ */
+void CASetNetworkChangeCallback(CANetworkChangeCallback callback);
+
+/**
+ * @brief   Starting different connectivity adapters based on the network selection.
+ * @param   transportType   [IN]    interested network for starting
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartAdapter(CATransportType_t transportType);
 
-void CAStopAdapter(CAConnectivityType_t connectivity);
+/**
+ * @brief   Stopping different connectivity adapters based on the network un-selection.
+ * @param   transportType   [IN]    network type that want to stop
+ * @return  none
+ */
+void CAStopAdapter(CATransportType_t transportType);
 
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t length);
+/**
+ * @brief   Get network information such as ipaddress and mac information
+ * @param   info           [OUT]    connectivity information such as ipaddress and mac information
+ * @param   size           [OUT]    number of connectivity information structures
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
 
-CAResult_t CASendMulticastData(void* data, uint32_t length);
+/**
+ * @brief   Sends unicast data to the remote endpoint
+ * @param   endpoint       [IN]    endpoint information where the data has to be sent
+ * @param   data           [IN]    data that needs to be sent
+ * @param   length         [IN]    length of the data that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length);
 
+/**
+ * @brief   Sends multicast data to all endpoints in the network.
+ * @param   data           [IN]    data that needs to be sent
+ * @param   length         [IN]    length of the data that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+
+CAResult_t CASendMulticastData(const void *data, uint32_t length);
+
+/**
+ * @brief   Start listening servers to receive search requests from clients
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
 CAResult_t CAStartListeningServerAdapters();
 
+/**
+ * @brief   Start discovery servers to receive advertisements from server
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
 CAResult_t CAStartDiscoveryServerAdapters();
 
+/**
+ * @brief   Terminates  the adapters which are initialized during the initialization
+ * @return  none
+ */
 void CATerminateAdapters();
 
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif //#ifndef __CA_INTERFACE_CONTROLLER_H_
+#endif /* CA_INTERFACE_CONTROLLER_H_ */
+
diff --git a/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h b/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h
new file mode 100644 (file)
index 0000000..70f0759
--- /dev/null
@@ -0,0 +1,131 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the APIs for the interface controller.
+ */
+
+#ifndef CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_
+#define CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_
+
+#include "caadapterinterface.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   Initializes different adapters based on the compilation flags.
+ * @param   handle          [IN]    thread pool handle created by message handler for different
+ *                                  adapters.
+ * @return   none
+ */
+void CAInitializeAdapters();
+
+/**
+ * @brief   Set the received packets callback for message handler
+ * @param   callback        [IN]    message handler callback to receive packets from different
+ *                                  adapters.
+ * @return   none
+ */
+void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback);
+
+/**
+ * @brief   Set the network status changed callback for message handler
+ * @param   callback        [IN]    message handler network status callback to receive network
+ *                                  changes.
+ * @return   none
+ */
+void CASetNetworkChangeCallback(CANetworkChangeCallback callback);
+
+/**
+ * @brief   Starting different connectivity adapters based on the network selection.
+ * @param   transportType    [IN]    network type that want to stop
+ * @return  none
+ */
+CAResult_t CAStartAdapter(CATransportType_t transportType);
+
+/**
+ * @brief   Stopping different connectivity adapters based on the network un-selection.
+ * @param   transportType    [IN]    un selected network for stopping the packets transfer
+ * @return   none
+ */
+void CAStopAdapter(CATransportType_t transportType);
+
+/**
+ * @brief   Get network information such as ipaddress and mac information.  Gets the network
+ *          information of the adapter whichever is enabled. Otherwise info is NULL.
+ * @param   info            [OUT]    connectivity information such as ipaddress and mac information
+ * @param   size            [OUT]    number of connectivity information structures
+ * @return   CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief   Sends unicast data to the remote endpoint
+ * @param   endpoint        [IN]    endpoint information where the data has to be sent
+ * @param   data            [IN]    data that needs to be sent
+ * @param   length          [IN]    length of the data that needs to be sent
+ * @return   CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length);
+
+/**
+ * @brief   Sends multicast data to all endpoints in the network.
+ * @param   data            [IN]    data that needs to be sent
+ * @param   length          [IN]    length of the data that needs to be sent
+ * @return   CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CASendMulticastData(const void *data, uint32_t length);
+
+/**
+ * @brief   Start listening servers to receive search requests from clients
+ * @return   CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartListeningServerAdapters();
+
+/**
+ * @brief   Start discovery servers to receive advertisements from server
+ * @return   CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartDiscoveryServerAdapters();
+
+/**
+ * @brief   Terminates  the adapters which are initialized during the initialization
+ * @return  none
+ */
+void CATerminateAdapters();
+
+/**
+ * @brief   Checks for available data and reads it
+ * @return   CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAReadData();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caipadapter.h b/resource/csdk/connectivity/inc/caipadapter.h
new file mode 100644 (file)
index 0000000..fc1e697
--- /dev/null
@@ -0,0 +1,131 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caipadapter.h
+ * @brief This file contains the APIs for IP Adapter.
+ */
+#ifndef CA_IP_ADAPTER_H_
+#define CA_IP_ADAPTER_H_
+
+#include "cacommon.h"
+#include "caadapterinterface.h"
+#include "cathreadpool.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief API to initialize IP Interface.
+ * @param registerCallback      [IN] Callback to register IP interfaces to Connectivity
+ *                                   Abstraction Layer
+ * @param networkPacketCallback [IN] Callback to notify request and response messages from server(s)
+ *                                   started at Connectivity Abstraction Layer.
+ * @param netCallback           [IN] Callback to notify the network additions to Connectivity
+ *                                   Abstraction Layer.
+ * @param handle                [IN] Threadpool Handle
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+    CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
+                              CANetworkPacketReceivedCallback networkPacketCallback,
+                              CANetworkChangeCallback netCallback, ca_thread_pool_t handle);
+
+
+/**
+ * @brief Start IP Interface adapter.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartIP();
+
+/**
+ * @brief Start listening server for receiving multicast search requests
+ * Transport Specific Behavior:
+ * IP Starts Multicast Server on a particular interface and prefixed port number and
+ * as per OIC Specification.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartIPListeningServer();
+
+/**
+ * @brief Start discovery servers for receiving multicast advertisements
+ * Transport Specific Behavior:
+ * IP Starts Start multicast server on a particular interface and prefixed port
+ * number as per OIC Specification
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartIPDiscoveryServer();
+
+/**
+ * @brief Sends data to the endpoint using the adapter connectivity.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port,
+ * reference uri and transport type) to which the unicast data has to be sent.
+ * @param   data        [IN]    Data which is required to be sent.
+ * @param   dataLen     [IN]    Size of data to be sent.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
+ * @remarks dataLen must be > 0.
+ */
+int32_t CASendIPUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+                                   uint32_t dataLen);
+
+/**
+ * @brief Sends Multicast data to the endpoint using the IP connectivity.
+ * @param   data        [IN]    Data which required to be sent.
+ * @param   dataLen     [IN]    Size of data to be sent.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
+ * @remarks dataLen must be > 0.
+ */
+int32_t CASendIPMulticastData(const void *data, uint32_t dataLen);
+
+/**
+ * @brief Get IP Connectivity network information
+ * @param   info        [OUT]   Local connectivity information structures
+ * @param   size        [OUT]   Number of local connectivity structures.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @remarks info is allocated in this API and should be freed by the caller.
+ */
+CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief Read Synchronous API callback.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAReadIPData();
+
+/**
+ * @brief Stops Unicast, Multicast servers and close the sockets.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStopIP();
+
+/**
+ * @brief Terminate the IP connectivity adapter.
+ * Configuration information will be deleted from further use
+ * @return  NONE
+ */
+void CATerminateIP();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  // #ifndef CA_IP_ADAPTER_H_
+
diff --git a/resource/csdk/connectivity/inc/caipadapter_singlethread.h b/resource/csdk/connectivity/inc/caipadapter_singlethread.h
new file mode 100644 (file)
index 0000000..7625a04
--- /dev/null
@@ -0,0 +1,128 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caipadapter_singlethread.h
+ * @brief This file contains the APIs for IP Adapter.
+ */
+#ifndef CA_IP_ADAPTER_SINGLETHREAD_H_
+#define CA_IP_ADAPTER_SINGLETHREAD_H_
+
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief API to initialize IP Interface.
+ * @param registerCallback      [IN] Callback to register IP interfaces to Connectivity
+ *                                   Abstraction Layer
+ * @param networkPacketCallback [IN] Callback to notify request and response messages from server(s)
+ *                                   started at Connectivity Abstraction Layer.
+ * @param netCallback           [IN] Callback to notify the network additions to Connectivity
+ *                                   Abstraction Layer.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
+                                CANetworkPacketReceivedCallback networkPacketCallback,
+                                CANetworkChangeCallback netCallback);
+
+/**
+ * @brief Start IP Interface adapter.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartIP();
+
+/**
+ * @brief Start listening server for receiving multicast search requests
+ * Transport Specific Behavior:
+ * IP Starts Multicast Server on  all available IPs and prefixed port number and
+ * as per OIC Specification.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartIPListeningServer();
+
+/**
+ * @brief Start discovery servers for receiving multicast advertisements
+ * Transport Specific Behavior:
+ * IP Starts multicast server on all available IPs and prefixed port
+ * number as per OIC Specification
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartIPDiscoveryServer();
+
+/**
+ * @brief Sends data to the endpoint using the adapter connectivity.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port,
+ * reference uri and connectivity type) to which the unicast data has to be sent.
+ * @param   data        [IN]    Data which required to be sent.
+ * @param   dataLen     [IN]    Size of data to be sent.
+ * @return  The number of bytes sent on the network. Return value equal to -1 indicates error.
+ * @remark  dataLen must be > 0.
+ */
+int32_t CASendIPUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+                                  uint32_t dataLen);
+
+/**
+ * @brief Send Multicast data to the endpoint using the IP connectivity.
+ * @param   data        [IN]    Data which is required to be sent.
+ * @param   dataLen     [IN]    Size of data to be sent.
+ * @return  The number of bytes sent on the network. Return value equal to -1 indicates error.
+ * @remark  dataLen must be > 0.
+ */
+int32_t CASendIPMulticastData(const void *data, uint32_t dataLen);
+
+/**
+ * @brief Get IP Connectivity network information
+ * @param   info        [OUT]   Local connectivity information structures
+ * @param   size        [OUT]   Number of local connectivity structures.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @remarks info is allocated in this API and should be freed by the caller.
+ */
+CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief Read Synchronous API callback.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAReadIPData();
+
+/**
+ * @brief Stops Unicast, Multicast servers and close the sockets.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStopIP();
+
+/**
+ * @brief Terminate the Ethernet connectivity adapter.
+ * Configuration information will be deleted from further use
+ * @return NONE
+ */
+void CATerminateIP();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  /* CA_IP_ADAPTER_SINGLETHREAD_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caipinterface.h b/resource/csdk/connectivity/inc/caipinterface.h
new file mode 100644 (file)
index 0000000..092a51e
--- /dev/null
@@ -0,0 +1,328 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caipinterface.h
+ * @brief This file provides APIs IP client/server/network monitor modules
+ */
+
+#ifndef CA_IP_INTERFACE_H_
+#define CA_IP_INTERFACE_H_
+
+#include <stdbool.h>
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @enum CAAdapterServerType_t
+ * @brief Enum for defining different server types.
+ */
+typedef enum
+{
+    CA_UNICAST_SERVER = 0,    /**< Unicast Server */
+    CA_MULTICAST_SERVER,      /**< Multicast Server */
+    CA_SECURED_UNICAST_SERVER /**< Secured Unicast Server */
+} CAAdapterServerType_t;
+
+/**
+ * @brief Callback to be notified on reception of any data from remote OIC devices.
+ *
+ * @param  ipAddress    [IN] IP address of remote OIC device.
+ * @param  port         [IN] Port number on which data is received.
+ * @param  data         [IN] Data received from remote OIC device.
+ * @param  dataLength   [IN] Length of data in bytes.
+ * @param  isSecured    [IN] Indicates the data is secure or not.
+ *
+ * @return NONE
+ * @pre  Callback must be registered using CAIPSetPacketReceiveCallback()
+ */
+typedef void (*CAIPPacketReceivedCallback)(const char *ipAddress, uint16_t port,
+                                           const void *data, uint32_t dataLength,
+                                           bool isSecured);
+
+/**
+ * @brief  Callback to be notified when exception occures on multicast/unicast server.
+ * @param  type  [IN] Type of server(#CAAdapterServerType_t)
+ * @return NONE
+ * @pre  Callback must be registered using CAIPSetExceptionCallback()
+ */
+typedef void (*CAIPExceptionCallback)(CAAdapterServerType_t type);
+
+/**
+ * @brief  Initialize IP server
+ *
+ * @param   threadPool  [IN] Thread pool for managing Unicast/Multicast server threads.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Initialization failed
+ */
+CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool);
+
+/**
+ * @brief  Terminate IP server
+ * @return NONE
+ */
+void CAIPTerminateServer();
+
+/**
+ * @brief  Start multicast server for specified multicast address and port
+ *
+ * @param   localAddress        [IN]      Local adapter address to which server to be binded.
+ * @param   multicastAddress    [IN]      Multicast group address.
+ * @param   multicastPort       [IN,OUT]  Port number on which server will be running. If binding
+ *                                        the port failed, server starts in the next available port.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_SERVER_STARTED_ALREADY Multicast server is already started and running.
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
+                                    uint16_t multicastPort);
+
+/**
+ * @brief  Start unicast server for specified local address and port
+ *
+ * @param  localAddress [IN]      Local adapter address to which server to be binded.
+ * @param  port         [IN,OUT]  Port number on which server will be running. If binding
+ *                                the port failed, server starts in the next available port.
+ * @param  forceStart   [IN]      Indicate whether to start server forcesfully on specified port
+ *                                or not.
+ * @param  secured      [IN]      True if the secure server to be started, otherwise false.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_SERVER_STARTED_ALREADY Unicast server is already started and running.
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, bool forceStart,
+                                  bool secured);
+
+/**
+ * @brief  Stop servers that are running in particular interface address.
+ *
+ * @param   interfaceAddress  [IN] interface address in which servers are running.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStopServer(const char *interfaceAddress);
+
+/**
+ * @brief  Used to stop all unicast and multicast servers.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStopAllServers();
+
+/**
+ * @brief  Used to get the socket fd based on index value of server info list.
+ *
+ * @param   index      [IN] Index where we need socket fd value.
+ * @param   isSecured  [IN] For secured unicast server or normal server.
+ *
+ * @return  positive value on success and -1 on error.
+ */
+int CAGetSocketFdFromUnicastIPServerbyIndex(int16_t index, bool isSecured);
+
+/**
+ * @brief  Used to get the number of unicast server currently running.
+ *
+ * @param   isSecured  [IN] To identify whether its secured unicast server or normal server.
+ *
+ * @return  positive value on success and -1 on error.
+ */
+int16_t CAGetNumberOfUnicastIPServers(bool isSecured);
+
+/**
+ * @brief  Used to get the stored socket fd for corresponding ipAddress.
+ *
+ * @param   ipAddress    [IN] IpAddress of server.
+ * @param   isSecured    [IN] Used to check the server is secured or not.
+ * @param   isMulticast  [IN] To identify whether its for multicast or unicast.
+ *
+ * @return  socket fd on success and -1 on error.
+ */
+int CAGetSocketFdFromUnicastIPServer(const char *ipAddress, bool isSecured, bool isMulticast);
+
+/**
+ * @brief  Used to get the port number to the corresponding ip for giving interface info.
+ *
+ * @param   ipAddress  [IN] IpAddress of server.
+ * @param   isSecured  [IN] Used to check the server is secured or not.
+ *
+ * @return  port number on success and -1 on error.
+ */
+uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured);
+
+/**
+ * @brief  Used to get the port number for corresponding ipAddress.
+ *
+ * @param   serverInfoList  [OUT] ServerInfoList holds unicast and multicast server informations.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Initialization failed
+ */
+CAResult_t CAGetIPServerInfoList(u_arraylist_t **serverInfoList);
+
+/**
+ * @brief  Set this callback for receiving data packets from peer devices.
+ *
+ * @param  callback   [IN] Callback to be notified on reception of unicast/multicast data packets.
+ *
+ * @return  NONE
+ */
+void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback);
+
+/**
+ * @brief  Set this callback for receiving exception notifications.
+ *
+ * @param  callback [IN] Callback to be notified on occurance of exception on running servers.
+ *
+ * @return  NONE
+ */
+void CAIPSetExceptionCallback(CAIPExceptionCallback callback);
+
+/**
+ * @brief  API to send unicast UDP data
+ *
+ * @param  remoteAddress    [IN] IP address to which data needs to be sent.
+ * @param  port             [IN] Port to which data needs to be send.
+ * @param  data             [IN] Data to be send.
+ * @param  dataLength       [IN] Length of data in bytes
+ * @param  isMulticast      [IN] Whether data needs to be sent to multicast ip
+ * @param  isSecured        [IN] Whether data to be sent on secured channel.
+ *
+ * @return  The number of bytes sent on the network. Returns 0 on error.
+ * @remarks isSecure will be ignored when isMulticast is true.
+ */
+uint32_t CAIPSendData(const char *remoteAddress, uint16_t port, const void *data,
+                      uint32_t dataLength, bool isMulticast, bool isSecure);
+
+/**
+ * @brief  Callback to be notified when IP adapter connection state changes.
+ *
+ * @param  ipAddress    [IN] IP address of remote OIC device.
+ * @param  status       [IN] Connection status either #CA_INTERFACE_UP or #CA_INTERFACE_DOWN.
+ * @return  NONE
+ * @pre  Callback must be registered using CAIPSetConnectionStateChangeCallback()
+ */
+typedef void (*CAIPConnectionStateChangeCallback)(const char *ipAddress,
+                                                  CANetworkStatus_t status);
+
+/**
+ * @brief Initialize IP network monitor
+ *
+ * @param  threadPool [IN] Thread pool for managing network monitor thread.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Initialization failed
+ */
+CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool);
+
+/**
+ * @brief Terminate IP network monitor by removing interface list.
+ * @return  NONE
+ */
+void CAIPTerminateNetworkMonitor();
+
+/**
+ * @brief  Start network monitoring process. It will start the monitor thread.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStartNetworkMonitor();
+
+/**
+ * @brief  Stop network monitoring process. It will stop the monitor thread.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStopNetworkMonitor();
+
+/**
+ * @brief  Get local adapter network information.
+ *
+ * @param  netInterfaceList [OUT] network interface information list
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Operation failed
+ * @remarks  interfaceName and ipAddress must be freed using free().
+ */
+CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList);
+
+/**
+ * @brief  Get local adapter network subnet mask.
+ *
+ * @param  ipAddress  [IN]  IpAddress which is used for getting subnet mask.
+ * @param  subnetMask [OUT] Local adapter interface subnet mask
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Operation failed
+ * @remarks subnetMask must be freed using free().
+ */
+CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask);
+
+/**
+ * @brief  Get IP adapter connection state.
+ *
+ * @return  True if IP adapter is connected, otherwise false
+ */
+ bool CAIPIsConnected();
+
+/**
+ * @brief  Set callback for receiving local IP adapter connection status.
+ *
+ * @param  callback [IN] Callback to be notified when IP adapter connection state changes.
+ * @return NONE
+ */
+void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CA_IP_INTERFACE_H_ */
diff --git a/resource/csdk/connectivity/inc/caipinterface_singlethread.h b/resource/csdk/connectivity/inc/caipinterface_singlethread.h
new file mode 100644 (file)
index 0000000..69133c3
--- /dev/null
@@ -0,0 +1,307 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file caipinterface_singlethread.h
+ * @brief This file provides APIs IP client/server/network monitor modules
+ */
+
+#ifndef CA_IP_INTERFACE_SINGLETHREAD_H_
+#define CA_IP_INTERFACE_SINGLETHREAD_H_
+
+#include <stdbool.h>
+
+#include "cacommon.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @enum CAAdapterServerType_t
+ * @brief Enum for defining different server types.
+ */
+typedef enum
+{
+    CA_UNICAST_SERVER = 0,      /**< Unicast Server */
+    CA_MULTICAST_SERVER,        /**< Multicast Server */
+    CA_SECURED_UNICAST_SERVER   /**< Secured Unicast Server */
+} CAAdapterServerType_t;
+
+/**
+ * @brief Callback to be notified on reception of any data from remote OIC devices.
+ * @param  ipAddress    [IN] IP address of remote OIC device.
+ * @param  port         [IN] Port number on which data is received.
+ * @param  data         [IN] Data received from remote OIC device.
+ * @param  dataLength   [IN] Length of data in bytes.
+ * @return NONE
+ * @pre  Callback must be registered using CAIPSetPacketReceiveCallback()
+ */
+typedef void (*CAIPPacketReceivedCallback)(const char *ipAddress, uint16_t port,
+                                                 const void *data, uint32_t dataLength);
+
+/**
+ * @brief  Callback to be notified when exception occures on multicast/unicast server.
+ * @param  type  [IN] Type of server(#CAAdapterServerType_t)
+ * @return NONE
+ * @pre  Callback must be registered using CAIPSetExceptionCallback()
+ */
+typedef void (*CAIPExceptionCallback)(CAAdapterServerType_t type);
+
+/**
+ * @brief  Initialize IP server
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Initialization failed
+ */
+CAResult_t CAIPInitializeServer(void);
+
+/**
+ * @brief  Terminate IP server
+ * @return NONE
+ */
+void CAIPTerminateServer(void);
+
+/**
+ * @brief  Start multicast server for specified multicast address and port
+ *
+ * @param   localAddress        [IN]      Local adapter address to which server to be binded.
+ * @param   multicastAddress    [IN]      Multicast group address.
+ * @param   multicastPort       [IN,OUT]  Port number on which server will be running. If binding
+                                          the port failed, server starts in the next available port.
+ * @param   serverFD            [OUT]     Multicast server socket FD.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_SERVER_STARTED_ALREADY Multicast server is already started and running.
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
+                                          uint16_t multicastPort, int *serverFD);
+
+/**
+ * @brief  Start unicast server for specified local address and port
+ *
+ * @param  localAddress [IN]      Local adapter address to which server to be binded.
+ * @param  port         [IN,OUT]  Port number on which server will be running. If binding
+                                  the port failed, server starts in the next available port.
+ * @param  forceStart   [IN]      Indicate whether to start server forcesfully on specified port
+ *                                or not.
+ * @param  serverFD     [OUT]     Unicast server socket FD.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_SERVER_STARTED_ALREADY Unicast server is already started and running.
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
+                                        bool forceStart, int *serverFD);
+
+/**
+ * @brief  Stop multicast server.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStopMulticastServer(void);
+
+/**
+ * @brief  Stop unicast server.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStopUnicastServer();
+
+#ifdef __WITH_DTLS__
+/**
+ * @brief  Stop secured unicast server.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStopSecureUnicastServer();
+#endif
+
+/**
+ * @brief  Get the Unicast Server Information if it is started
+ * @param  ipAddress    [OUT] IP address on which server is binded and running.
+ * @param  port         [OUT]Port number on which server is running
+ * @param  serverFD     [OUT]Server socket fd.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Operation failed
+ * @remarks  ipAddress must be freed using free().
+ */
+CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port, int *serverFD);
+
+/**
+ * @brief  Set this callback for receiving data packets from peer devices.
+ * @param  callback   [IN] Callback to be notified on reception of unicast/multicast data packets.
+ *
+ * @return  NONE
+ */
+void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback);
+
+/**
+ * @brief  Pull the Received Data
+ * @return NONE
+ */
+void CAIPPullData();
+
+/**
+ * @brief  Set this callback for receiving exception notifications.
+ *
+ * @param  callback [IN] Callback to be notified on occurance of exception on running servers.
+ *
+ * @return  NONE
+ */
+void CAIPSetExceptionCallback(CAIPExceptionCallback callback);
+
+/**
+ * @brief  Set socket description for sending unicast UDP data. Once the Unicast server is started,
+ *         the same socket descriptor is used for sending the Unicast UDP data.
+ *
+ * @param  socketFD [IN]  Socket descriptor used for sending UDP data.
+ * @return  NONE
+ */
+void CAIPSetUnicastSocket(int socketFD);
+
+/**
+ * @brief  Set the port number for sending unicast UDP data
+ * @param  port [IN] Port number used for sending UDP data.
+ * @return NONE
+ */
+void CAIPSetUnicastPort(uint16_t port);
+
+#ifdef __WITH_DTLS__
+/**
+ * @brief  Set socket description for sending secured (encrypted) unicast UDP data
+ *
+ * @param socketFD [IN] Socket descriptor used for sending secured (encrypted) UDP data.
+ * @return  NONE
+ */
+void CAIPSetSecureUnicastSocket(int socketFD);
+#endif
+
+/**
+ * @brief  API to send unicast UDP data
+ *
+ * @param  remoteAddress    [IN] IP address to which data needs to be sent.
+ * @param  port             [IN] Port to which data needs to be send.
+ * @param  buf              [IN] Data to be send.
+ * @param  bufLen           [IN] Length of data in bytes
+ * @param  isMulticast      [IN] Whether data needs to be sent to multicast ip
+ *
+ * @return  The number of bytes sent on the network. Returns 0 on error.
+ */
+uint32_t CAIPSendData(const char *remoteAddress, uint16_t port,
+                            const char *buf, uint32_t bufLen, bool isMulticast);
+
+/**
+ * @brief  Callback to be notified when IP adapter connection state changes.
+ *
+ * @param  ipAddress    [IN] IP address of remote OIC device.
+ * @param  status       [IN] Connection status either #CA_INTERFACE_UP or #CA_INTERFACE_DOWN.
+ * @return  NONE
+ * @pre  Callback must be registered using CAIPSetConnectionStateChangeCallback()
+ */
+typedef void (*CAIPConnectionStateChangeCallback)(const char *ipAddress,
+                                                        CANetworkStatus_t status);
+
+/**
+ * @brief Initialize IP network monitor
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Initialization failed
+ */
+CAResult_t CAIPInitializeNetworkMonitor(void);
+
+/**
+ * @brief Terminate IP network monitor
+ * @return  NONE
+ */
+void CAIPTerminateNetworkMonitor(void);
+
+/**
+ * @brief  Start network monitoring process.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStartNetworkMonitor(void);
+
+/**
+ * @brief  Stop network monitoring process.
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAIPStopNetworkMonitor(void);
+
+/**
+ * @brief  Get local adapter network information.
+ *
+ * @param  interfaceName [OUT] Local adapter interface name
+ * @param  ipAddress     [OUT] IP address
+ *
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input data
+ * @retval  #CA_STATUS_FAILED Operation failed
+ * @remarks  interfaceName and ipAddress must be freed using free().
+ */
+CAResult_t CAIPGetInterfaceInfo(char **ipAddress, char **interfaceName);
+
+/**
+ * @brief  Get Ethernet adapter connection state.
+ *
+ * @return  True if Ethernet adapter is connected, otherwise false
+ */
+bool CAIPIsConnected(void);
+
+/**
+ * @brief  Set callback for receiving local ethernet adapter connection status.
+ *
+ * @param  callback [IN] Callback to be notified when local Ethernet adapter connection state
+ *                       changes.
+ * @return NONE
+ */
+void CAIPSetConnectionStateChangeCallback
+                (CAIPConnectionStateChangeCallback callback);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CA_IP_INTERFACE_SINGLETHREAD_H_ */
+
index a99d161..ad6e4bb 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  ******************************************************************/
 
 /**
- * @file caleadapter.h
- * @brief This file contains the APIs for LE adapters to be implemented
+ * @file
+ *
+ * This file contains the APIs for LE adapters to be implemented.
  */
-#ifndef _CA_LEADAPTER_H_
-#define _CA_LEADAPTER_H_
+
+#ifndef CA_LEADAPTER_H_
+#define CA_LEADAPTER_H_
 
 #include "cacommon.h"
 #include "caadapterinterface.h"
+#include "cathreadpool.h" /* for thread pool */
 
 /**
  * BLE Interface APIs.
@@ -37,17 +40,38 @@ extern "C"
 #endif
 
 /**
- * @brief Initialize LE connectivity interface.
- * @param registerCallback [IN] To register LE interfaces to Connectivity Abstraction Layer
- * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
- * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @struct CALEData_t
+ * @brief Stores the information of the Data to be sent from the queues.
+ *        This structure will be pushed to the sender/receiver queue for processing.
+ */
+typedef struct
+{
+    CARemoteEndpoint_t
+    *remoteEndpoint;   /**< Remote endpoint contains the inforamtion of remote device */
+    void *data;        /**< Data to be transmitted over LE tranport */
+    uint32_t dataLen;  /**< Length of the data being transmitted */
+} CALEData_t;
+
+/**
+ * @brief  Initialize LE connectivity interface.
+ * @param  registerCallback [IN] Callback to register LE interfaces to Connectivity
+ *                               Abstraction Layer
+ * @param  reqRespCallback  [IN] Callback to notify request and response messages from server(s)
+ *                               started at Connectivity Abstraction Layer.
+ * @param  netCallback      [IN] Callback to notify the network additions to Connectivity
+ *                               Abstraction Layer.
+ * @param  handle           [IN] Threadpool Handle
+ * @return #CA_STATUS_OK or Appropriate error code
  */
 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
+                          CANetworkPacketReceivedCallback reqRespCallback,
+                          CANetworkChangeCallback netCallback,
+                          ca_thread_pool_t handle);
+
 /**
- * @brief Starting LE connectivity adapters .As its peer to peer it doesnot require to start any servers
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief Starting LE connectivity adapters.
+ *        As its peer to peer it doesnot require to start any servers
+ * @return  #CA_STATUS_OK or Appropriate error code
  */
 CAResult_t CAStartLE();
 
@@ -55,7 +79,7 @@ CAResult_t CAStartLE();
  * @brief Starting listening server for receiving multicast search requests
  * Transport Specific Behavior:
  *   LE  Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return  #CA_STATUS_OK or Appropriate error code
  */
 CAResult_t CAStartLEListeningServer();
 
@@ -63,65 +87,67 @@ CAResult_t CAStartLEListeningServer();
  * @brief for starting discovery servers for receiving multicast advertisements
  * Transport Specific Behavior:
  *   LE  Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return  #CA_STATUS_OK or Appropriate error code
  */
 CAResult_t CAStartLEDiscoveryServer();
 
 /**
  * @brief Sends data to the endpoint using the adapter connectivity.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @param   endpoint  [IN]  Remote Endpoint information (like ipaddress , port, reference uri \
+ *                          and connectivity type) to which the unicast data has to be sent.
+ * @param   data      [IN]  Data which required to be sent.
+ * @param   dataLen   [IN]  Size of data to be sent.
+ * @return  The number of bytes sent on the network. Returns -1 on error.
+ * @remarks  dataLen must be > 0.
  */
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+                             uint32_t dataLen);
 
 /**
  * @brief Sends Multicast data to the endpoint using the LE connectivity.
- * Note: length must be > 0.
  * @param   data        [IN]    Data which required to be sent.
  * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return  The number of bytes sent on the network. Returns -1 on error.
+ * @remarks  dataLen must be > 0.
  */
-uint32_t CASendLEMulticastData(void* data, uint32_t dataLen);
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen);
 
 /**
  * @brief Starts notification server on EDR adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return  #CA_STATUS_OK or Appropriate error code
  */
 CAResult_t CAStartLENotifyServer();
 
 /**
- * @brief Send notification information.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @brief   Send notification information.
+ * @param   endpoint  [IN]    Remote Endpoint information (like ipaddress , port, reference uri \
+ *                            and connectivity type) to which the unicast data has to be sent.
+ * @param   data      [IN]    Data which required to be sent.
+ * @param   dataLen   [IN]    Size of data to be sent.
+ * @return  The number of bytes sent on the network. Returns 0 on error.
+ * @remarks dataLen must be > 0.
  */
-uint32_t CASendLENotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
+                              uint32_t dataLen);
 
 /**
- * @brief Get LE Connectivity network information
- * @param   info        [OUT]   Local connectivity information structures
- * @param   size        [OUT]   Number of local connectivity structures.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @brief  Get LE Connectivity network information
+ * @param  info        [OUT]   Local connectivity information structures
+ * @param  size        [OUT]   Number of local connectivity structures.
+ * @return #CA_STATUS_OK or Appropriate error code
  */
-CAResult_t CAGetLEInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size);
+CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
 
 /**
  * @brief Read Synchronous API callback.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return  #CA_STATUS_OK or Appropriate error code
  */
 CAResult_t CAReadLEData();
 
 /**
  * @brief Stopping the adapters and close socket connections
- *   LE Stops all GATT servers and close sockets.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ *   LE Stops all GATT servers and GATT Clients.
+ * @return  #CA_STATUS_OK or Appropriate error code
  */
 CAResult_t CAStopLE();
 
@@ -131,8 +157,284 @@ CAResult_t CAStopLE();
  */
 void CATerminateLE();
 
+/**
+ * @brief  This function will receive the data from the GattServer and add the data to
+ *         the Server receiver queue.
+ * @param  remoteAddress [IN] Remote address of the device from where data is received.
+ * @param  serviceUUID   [IN] Uuid of the OIC service running on the remote device
+ * @param  data          [IN] Actual data recevied from the remote device.
+ * @param  dataLength    [IN] Length of the data received from the remote device.
+ * @param  sentLength    [IN] Length of the data sent from the remote device.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
+                                   const void *data, uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief  This function will receive the data from the GattClient and add the data into the
+ *         Client receiver queue.
+ * @param  remoteAddress [IN] Remote address of the device from where data is received.
+ * @param  serviceUUID   [IN] Uuid of the OIC service running on the remote device
+ * @param  data          [IN] Actual data recevied from the remote device.
+ * @param  dataLength    [IN] Length of the data received from the remote device.
+ * @param  sentLength    [IN] Length of the data sent from the remote device.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABLEClientReceivedData(const char *remoteAddress, const char *serviceUUID,
+                                   const void *data, uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief  This function is used to set the NetworkPacket received callback to CA layer from
+ *         adapter layer.
+ * @param  callback [IN] callback handle sent from the upper layer.
+ * @return NONE
+ */
+void CASetBLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
+
+/**
+ * @brief  This function will push the data from CA layer to the Sender processor queue.
+ *
+ * @param  remoteEndpoint [IN] Remote endpoint information of the server.
+ * @param  data           [IN] Data to be transmitted from LE.
+ * @param  dataLen        [IN] length of the Data being transmitted.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
+                               const void *data, uint32_t dataLen);
+
+/**
+ * @brief  This function will push the data from CA layer to the Sender processor queue.
+ *
+ * @param  remoteEndpoint [IN] Remote endpoint information of the server.
+ * @param  data           [IN] Data to be transmitted from LE.
+ * @param  dataLen        [IN] length of the Data being transmitted.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
+                               const void *data,  uint32_t dataLen);
+
+/**
+ * @brief  This function will be associated with the sender queue for GattServer.This function will
+ *         fragment the data to the MTU of the transport and send the data in fragments to the
+ *         adapters. The function will be blocked untill all data is sent out from the adapter.
+ *
+ * @param threadData [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                        and Data.
+ *
+ * @return  NONE
+ */
+void CABLEServerSendDataThread(void *threadData);
+
+/**
+ * @brief  This function will be associated with the sender queue for GattClient.This function will
+ *         fragment the data to the MTU of the transport and send the data in fragments to the
+ *         adapters. The function will be blocked untill all data is sent out from the adapter.
+ *
+ * @param  threadData [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                         and Data.
+ *
+ * @return NONE
+ */
+void CABLEClientSendDataThread(void *threadData);
+
+/**
+ * @brief  This function will be associated with the receiver queue of GattServer. This function
+ *         will defragment the data received and will send the data UP to the CA layer only after
+ *         it collects all the data from the adapter layer. Adapter Header will provide the
+ *         length of the data sent from the server.
+ *
+ * @param  threadData [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                         and Data.
+ *
+ * @return  NONE
+ */
+void CABLEServerDataReceiverHandler(void *threadData);
+
+/**
+ * @brief  This function will be associated with the receiver queue of GattClient. This function
+ *         will defragment the data received and will send the data UP to the CA layer only after
+ *         it collects all the data from the adapter layer. Adapter Header will provide the length
+ *         of the data sent from the server.
+ *
+ * @param  threadData [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                         and Data.
+ * @return NONE
+ */
+void CABLEClientDataReceiverHandler(void *threadData);
+
+/**
+ * @brief  This function is used to Initalize both GattServer and GattClient queues. All four
+ *         queues will be initialized with this function invocations.
+ * @return  NONE
+ */
+void CAInitBleQueues();
+
+/**
+ * @brief  This function will stop all queues created for GattServer and GattClient. All
+ *         four queues will be be stopped with this function invocations.
+ * @return  NONE
+ */
+void CAStopBleQueues();
+
+/**
+ * @brief  This function will terminate all queues created for GattServer and GattClient. All
+ *         four queues will be be terminated with this function invocations.
+ * @return  NONE
+ */
+void CATerminateBleQueues();
+
+/**
+ * @brief  This function will initalize the Receiver and Sender queues for GattServer. This
+ *         function will inturn call the functions CAInitBleServerReceiverQueue() and
+ *         CAInitBleServerSenderQueue() to initialize the queues.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleServerQueues();
+
+/**
+ * @brief  This function will initalize the Receiver and Sender queues for GattClient. This
+ *         function will inturn call the functions CAInitBleClientReceiverQueue() and
+ *         CAInitBleClientSenderQueue() to initialize the queues.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAInitBleClientQueues();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattServer. This will initialize
+ *         the queue to process the function CABLEServerSendDataThread() when ever the task is
+ *         added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleServerSenderQueue();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattClient. This will initialize
+ *         the queue to process the function CABLEClientSendDataThread() when ever the task is
+ *         added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleClientSenderQueue();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattServer. This will initialize
+ *         the queue to process the function CABLEServerDataReceiverHandler() when ever the task
+ *         is added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAInitBleServerReceiverQueue();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattClient. This will initialize
+ *         the queue to process the function CABLEClientDataReceiverHandler() when ever the task
+ *         is added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleClientReceiverQueue();
+
+/**
+ * @brief  This function will create the Data required to send it in the queue.
+ *
+ * @param  remoteEndpoint [IN] Remote endpoint information of the server.
+ * @param  data           [IN] Data to be transmitted from LE.
+ * @param  dataLength     [IN] length of the Data being transmitted.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                           uint32_t dataLength);
+
+/**
+ * @brief Used to free the BLE information stored in the sender/receiver queues.
+ * @param bleData [IN] Structure contains the information of a particular data segment.
+ * @return NONE
+ */
+void CAFreeBLEData(CALEData_t *bleData);
+
+/**
+ * @brief This will be used to notify device status changes to the LE adapter layer
+ * @param  adapter_state [IN] State of the adapter
+ * @return NONE
+ */
+typedef void (*CALEDeviceStateChangedCallback)(CAAdapterState_t adapter_state);
+
+/**
+ * @brief This will be used to notify that network packet recieved from GATTClient to adapter layer.
+ * @param  remoteAddress  [IN] Remote endpoint Address
+ * @param  serviceUUID    [IN] Service UUID
+ * @param  data           [IN] Data received
+ * @param  dataLength     [IN] Length of the data received
+ * @param  sentLength     [IN] Length of the data sent
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+typedef CAResult_t (*CABLEClientDataReceivedCallback)(const char *remoteAddress,
+                                                      const char *serviceUUID, const void *data,
+                                                      uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief This will be used to notify that network packet recieved from GATTServer to adapter layer.
+ * @param  remoteAddress  [IN] Remote endpoint Address
+ * @param  serviceUUID    [IN] Service UUID
+ * @param  data           [IN] Data received
+ * @param  dataLength     [IN] Length of the data received
+ * @param  sentLength     [IN] Length of the data sent
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+typedef CAResult_t (*CABLEServerDataReceivedCallback)(const char *remoteAddress,
+                                                      const char *serviceUUID, const void *data,
+                                                      uint32_t dataLength, uint32_t *sentLength);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif //#ifndef _CA_LEADAPTER_H_
+#endif /* CA_LEADAPTER_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caleadapter_singlethread.h b/resource/csdk/connectivity/inc/caleadapter_singlethread.h
new file mode 100644 (file)
index 0000000..c790889
--- /dev/null
@@ -0,0 +1,427 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the APIs for LE adapters to be implemented.
+ */
+
+#ifndef CA_LEADAPTER_SINGLETHREAD_H_
+#define CA_LEADAPTER_SINGLETHREAD_H_
+
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+/**
+ * BLE Interface APIs.
+ */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @struct CALEData_t
+ * @brief Stores the information of the Data to be sent from the queues.
+ *        This structure will be pushed to the sender/receiver queue for processing.
+ */
+typedef struct
+{
+    CARemoteEndpoint_t
+    *remoteEndpoint;    /**< Remote endpoint contains the inforamtion of remote device */
+    void *data;         /**< Data to be transmitted over LE tranport */
+    uint32_t dataLen;   /**< Length of the data being transmitted */
+} CALEData_t;
+
+/**
+ * @brief Initialize LE connectivity interface.
+ * @param registerCallback [IN] Callback to register LE interfaces to Connectivity Abstraction Layer
+ * @param reqRespCallback  [IN] Callback to notify request and response messages from server(s)
+ *                              started at Connectivity Abstraction Layer.
+ * @param netCallback      [IN] Callback to notify the network additions to Connectivity
+ *                              Abstraction Layer.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
+                          CANetworkPacketReceivedCallback reqRespCallback,
+                          CANetworkChangeCallback netCallback);
+
+/**
+ * @brief Starting LE connectivity adapters.
+ *        As its peer to peer it doesnot require to start any servers
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartLE();
+
+/**
+ * @brief Starting listening server for receiving multicast search requests
+ * Transport Specific Behavior:
+ *   LE  Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartLEListeningServer();
+
+/**
+ * @brief for starting discovery servers for receiving multicast advertisements
+ * Transport Specific Behavior:
+ *   LE  Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartLEDiscoveryServer();
+
+/**
+ * @brief Sends data to the endpoint using the adapter connectivity.
+ * @param  endpoint  [IN]  Remote Endpoint information (like ipaddress , port, reference uri
+ *                         and connectivity type) to which the unicast data has to be sent.
+ * @param  data      [IN]  Data which required to be sent.
+ * @param  dataLen   [IN]  Size of data to be sent.
+ * @return  The number of bytes sent on the network. Returns -1 on error.
+ * @remarks dataLen must be > 0.
+ */
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+                             uint32_t dataLen);
+
+/**
+ * @brief Sends Multicast data to the endpoint using the LE connectivity.
+ * @param   data        [IN]    Data which required to be sent.
+ * @param   dataLen     [IN]    Size of data to be sent.
+ * @return  The number of bytes sent on the network. Returns -1 on error.
+ * @remarks  dataLen must be > 0.
+ */
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen);
+
+/**
+ * @brief Starts notification server on EDR adapters.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStartLENotifyServer();
+
+/**
+ * @brief Send notification information.
+ * @param   endpoint  [IN]    Remote Endpoint information (like ipaddress , port, reference uri
+ *                            and connectivity type) to which the unicast data has to be sent.
+ * @param   data      [IN]    Data which required to be sent.
+ * @param   dataLen   [IN]    Size of data to be sent.
+ * @return  The number of bytes sent on the network. Returns 0 on error.
+ * @remarks dataLen must be > 0.
+ */
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
+                              uint32_t dataLen);
+
+/**
+ * @brief   Get LE Connectivity network information
+ * @param   info        [OUT]   Local connectivity information structures
+ * @param   size        [OUT]   Number of local connectivity structures.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief Read Synchronous API callback.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAReadLEData();
+
+/**
+ * @brief Stopping the adapters and close socket connections
+ *   LE Stops all GATT servers and close sockets.
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStopLE();
+
+/**
+ * @brief Terminate the LE connectivity adapter.
+ * Configuration information will be deleted from further use
+ */
+void CATerminateLE();
+
+/**
+ * @brief  This function will receive the data from the GattServer and add the data to
+ *         the Server receiver queue.
+ * @param  remoteAddress [IN] Remote address of the device from where data is received.
+ * @param  serviceUUID   [IN] Uuid of the OIC service running on the remote device
+ * @param  data          [IN] Actual data recevied from the remote device.
+ * @param  dataLength    [IN] Length of the data received from the remote device.
+ * @param  sentLength    [IN] Length of the data sent from the remote device.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
+                                   const void *data, uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief  This function will receive the data from the GattClient and add the data into the
+ *         Client receiver queue.
+ * @param  remoteAddress [IN] Remote address of the device from where data is received.
+ * @param  serviceUUID   [IN] Uuid of the OIC service running on the remote device
+ * @param  data          [IN] Actual data recevied from the remote device.
+ * @param  dataLength    [IN] Length of the data received from the remote device.
+ * @param  sentLength    [IN] Length of the data sent from the remote device.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABLEClientReceivedData(const char *remoteAddress, const char *serviceUUID,
+                                   const void *data, uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @brief  This function is used to set the NetworkPacket received callback to CA layer from
+ *         adapter layer.
+ * @param  callback [IN] callback handle sent from the upper layer.
+ * @return NONE
+ */
+void CASetBLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
+
+/**
+ * @brief  This function will push the data from CA layer to the Sender processor queue.
+ *
+ * @param  remoteEndpoint [IN] Remote endpoint information of the server.
+ * @param  data           [IN] Data to be transmitted from LE.
+ * @param  dataLen        [IN] length of the Data being transmitted.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
+                               const void *data, uint32_t dataLen);
+
+/**
+ * @brief  This function will push the data from CA layer to the Sender processor queue.
+ *
+ * @param  remoteEndpoint [IN] Remote endpoint information of the server.
+ * @param  data           [IN] Data to be transmitted from LE.
+ * @param  dataLen        [IN] length of the Data being transmitted.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
+                               const void *data, uint32_t dataLen);
+
+/**
+ * @brief  This function will be associated with the sender queue for GattClient.This function will
+ *         fragment the data to the MTU of the transport and send the data in fragments to the
+ *         adapters. The function will be blocked untill all data is sent out from the adapter.
+ *
+ * @param  threadData [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                         and Data.
+ *
+ * @return NONE
+ */
+void CABLEClientSendDataThread(void *threadData);
+
+/**
+ * @brief  This function will be associated with the receiver queue of GattClient. This function
+ *         will defragment the data received and will send the data UP to the CA layer only after
+ *         it collects all the data from the adapter layer. Adapter Header will provide the length
+ *         of the data sent from the server.
+ *
+ * @param  threadData [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                         and Data.
+ * @return NONE
+ */
+void CABLEClientDataReceiverHandler(void *threadData);
+
+/**
+ * @brief  This function will terminate all queues created for GattServer and GattClient. All
+ *         four queues will be be terminated with this function invocations.
+ * @return  NONE
+ */
+void CATerminateBleQueues();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattClient. This will initialize
+ *         the queue to process the function CABLEClientDataReceiverHandler() when ever the task
+ *         is added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleClientReceiverQueue();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattServer. This will initialize
+ *         the queue to process the function CABLEServerDataReceiverHandler() when ever the task
+ *         is added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAInitBleServerReceiverQueue();
+
+/**
+ * @brief  This function is used to Initalize both GattServer and GattClient queues. All four
+ *         queues will be initialized with this function invocations.
+ * @return  NONE
+ */
+void CAInitBleQueues();
+
+/**
+ * @brief  This function will initalize the Receiver and Sender queues for GattServer. This
+ *         function will inturn call the functions CAInitBleServerReceiverQueue() and
+ *         CAInitBleServerSenderQueue() to initialize the queues.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleServerQueues();
+
+/**
+ * @brief  This function will initalize the Receiver and Sender queues for GattClient. This
+ *         function will inturn call the functions CAInitBleClientReceiverQueue() and
+ *         CAInitBleClientSenderQueue() to initialize the queues.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CAInitBleClientQueues();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattServer. This will initialize
+ *         the queue to process the function CABLEServerSendDataThread() when ever the task is
+ *         added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleServerSenderQueue();
+
+/**
+ * @brief  This function will initalize the Receiver queue for GattClient. This will initialize
+ *         the queue to process the function CABLEClientSendDataThread() when ever the task is
+ *         added to this queue.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleClientSenderQueue();
+
+/**
+ * @brief  This function will be associated with the receiver queue of GattServer. This function
+ *         will defragment the data received and will send the data UP to the CA layer only after
+ *         it collects all the data from the adapter layer. Adapter Header will provide the
+ *         length of the data sent from the server.
+ *
+ * @param  context [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                      and Data.
+ *
+ * @return  NONE
+ */
+void CABLEServerDataReceiverHandler(void *context);
+
+/**
+ * @brief  This function will be associated with the sender queue for GattServer.This function will
+ *         fragment the data to the MTU of the transport and send the data in fragments to the
+ *         adapters. The function will be blocked untill all data is sent out from the adapter.
+ *
+ * @param threadData [IN] Data pushed to the queue which contains the info about RemoteEndpoint
+ *                        and Data.
+ *
+ * @return  NONE
+ */
+void CABLEServerSendDataThread(void *threadData);
+
+/**
+ * @brief  This function will create the Data required to send it in the queue.
+ *
+ * @param  remoteEndpoint [IN] Remote endpoint information of the server.
+ * @param  data           [IN] Data to be transmitted from LE.
+ * @param  dataLength     [IN] length of the Data being transmitted.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                            uint32_t dataLength);
+
+/**
+ * @brief Used to free the BLE information stored in the sender/receiver queues.
+ * @param bleData [IN] Structure contains the information of a particular data segment.
+ * @return NONE
+ */
+void CAFreeBLEData(CALEData_t *bleData);
+
+/**
+ * @brief This will be used to notify the device status changes to the LE adapter layer
+ * @param  adapter_state [IN] State of the adapter
+ * @return NONE
+ */
+typedef void (*CALEDeviceStateChangedCallback)(CAAdapterState_t adapter_state);
+
+/**
+ * @brief This will be used to notify that network packet recieved from GATTClient to adapter layer.
+ * @param  remoteAddress  [IN] Remote endpoint Address
+ * @param  serviceUUID    [IN] Service UUID
+ * @param  data           [IN] Data received
+ * @param  dataLength     [IN] Length of the data received
+ * @param  sentLength     [IN] Length of the data sent
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+typedef CAResult_t (*CABLEClientDataReceivedCallback)(const char *remoteAddress,
+                    const char *serviceUUID, const void *data, uint32_t dataLength,
+                    uint32_t *sentLength);
+
+/**
+ * @brief This will be used to notify that network packet recieved from GATTServer to adapter layer.
+ * @param  remoteAddress  [IN] Remote endpoint Address
+ * @param  serviceUUID    [IN] Service UUID
+ * @param  data           [IN] Data received
+ * @param  dataLength     [IN] Length of the data received
+ * @param  sentLength     [IN] Length of the data sent
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+typedef CAResult_t (*CABLEServerDataReceivedCallback)(const char *remoteAddress,
+        const char *serviceUUID, const void *data, uint32_t dataLength, uint32_t *sentLength);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_LEADAPTER_SINGLETHREAD_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caleinterface.h b/resource/csdk/connectivity/inc/caleinterface.h
new file mode 100644 (file)
index 0000000..ff1ab29
--- /dev/null
@@ -0,0 +1,294 @@
+/* ****************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs for BLE modules.
+ */
+
+#ifndef CA_LE_INTERFACE_H_
+#define CA_LE_INTERFACE_H_
+
+#include <stdbool.h>
+
+#include "cacommon.h"
+#include "caleadapter.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @enum CALETransferType_t
+ * @brief Provide info about different mode of data transfer
+ *        This enum is used to differentiate between unicast and multicast data transfer.
+ */
+typedef enum
+{
+    LE_MULTICAST,    /**< When this enum is selected, data will be updated to all OIC servers. */
+    LE_UNICAST       /**< When this enum is selected, data will be updated to desired OIC Server. */
+} CALETransferType_t;
+
+
+/**
+ * @brief  Initialize the LE adapter layer. This will be invoked from the CA layer.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitializeLEAdapter();
+
+/**
+ * @brief  Used to get the current state of the LE adapter.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED  adapter not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAGetLEAdapterState();
+
+/**
+ * @brief  Used to initialize the network monitor layer of the LE adapter. Mutex variables required
+ *         to operate in this layer and other paramters can be initialized in this function.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitializeLENetworkMonitor();
+
+/**
+ * @brief  Used to terminate the network monitor layer of the LE adapter. The variables intialized
+ *         in CAInitializeLEAdapterController() must be cleared in this function.
+ * @return NONE
+ */
+void CATerminateLENetworkMonitor();
+
+/**
+ * @brief  This function is used to set the callback for the Device state changes in the adapter.
+ *
+ * @param  callback  [IN] Callback to notify the Device state change to the CA Layer
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback);
+
+/**
+ * @brief  Used to initilaze all the mutex variables required to operate the LE network monitor
+ *         layer.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitLENetworkMonitorMutexVariables();
+
+/**
+ * @brief  Used to terminate all the mutex variables required to operate the LE network monitor
+ *         layer.
+ * @return NONE
+ */
+void CATerminateLENetworkMonitorMutexVariables();
+
+/**
+ * @brief  Provides the BD address of the local adapter.
+ * @param  local_address [OUT] pointer to the location where bd address needs to be stored.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAGetLEAddress(char **local_address);
+
+/**
+ * @brief  Used to start Gatt Server thread for service creation and advertise ble service.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStartBleGattServer();
+
+/**
+ * @brief  Used to stop BLE Gatt Service.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStopBleGattServer();
+
+/**
+ * @brief  Used to stop Gatt Server thread and remove service registration, stop advertising.
+ * @return NONE
+ */
+void CATerminateBleGattServer();
+
+/**
+ * @brief  Used to store upper layer callback locally which will be used to send the data to
+ *         application
+ * @param  callback [IN] Callback function to pass the data to CA layer.
+ * @return NONE
+ */
+void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback);
+
+/**
+ * @brief  Used to update characteristics(Read/Write) value that we want to send to particular
+ *         client.
+ *
+ * @param  address     [IN] BD address of Gatt client
+ * @param  charValue     [IN] Data that we want to send to client(unicast)
+ * @param  charValueLen  [IN] Length of the data.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAUpdateCharacteristicsToGattClient(const char* address, const char *charValue,
+                                               const uint32_t charValueLen);
+
+/**
+ * @brief  Used to update characteristics(Read/Write) value that we want to multicast to all clients
+ *
+ * @param  charValue     [IN] Data that we want to send to clients(multicast)
+ * @param  charValueLen  [IN] Length of the data.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
+                                                   const uint32_t charValueLen);
+
+/**
+ * @brief  Used to start CAStartBleGattClientThread for initializing Gatt Client
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStartBLEGattClient();
+
+/**
+ * @brief  Used to stop Gatt Client gracefully in turn it will call CATerminateBLEGattClient
+ *         function.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+void CAStopBLEGattClient();
+
+/**
+ * @brief  Used to unset all the callbacks and stop service discovery
+ * @return NONE
+ */
+void CATerminateBLEGattClient();
+
+/**
+ * @brief  Sets the value of characteristic and update the value to GATTServer(unicast).
+ *
+ * @param  remoteAddress [IN] The address of the remote device
+ * @param  data          [IN] The value of characteristic (byte array)
+ * @param  dataLen       [IN] The length of value
+ * @param  type          [IN] Type of the transfer(#CALETransferType_t)
+ * @param  position      [IN] The unique index of each ble server. Used for multicast feature.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char  *data,
+                                                const uint32_t dataLen, CALETransferType_t type,
+                                                const int32_t position);
+
+/**
+ * @brief  Sets the value of characteristic and update the value to all registered
+ *         GATTServer -> Multicast
+ * @param  data     [IN] The value of characteristic (byte array)
+ * @param  dataLen  [IN] The length of value
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t  CAUpdateCharacteristicsToAllGattServers(const char  *data, uint32_t dataLen);
+
+/**
+ * @brief  Used to store upper layer callback locally which will be used to send the data to
+ *         application
+ * @param  callback  [IN] Callback function to pass the data to CA layer.
+ *
+ * @return  void
+ */
+void CASetBLEReqRespClientCallback(CABLEClientDataReceivedCallback callback);
+
+/**
+ * @brief  Used to Set the gThreadPool handle which is required for spawning new thread.
+ *
+ * @param handle [IN] Thread pool handle which is given by above layer for using thread
+ *                    creation task.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+void CASetBleServerThreadPoolHandle(ca_thread_pool_t handle);
+
+/**
+* @brief  Used to Set the gThreadPool handle which is required for spawning new thread.
+* @param handle [IN] Thread pool handle which is given by above layer for using thread creation
+*                    task.
+* @return NONE
+*/
+void CASetBleClientThreadPoolHandle(ca_thread_pool_t handle);
+
+/**
+ * @brief  Used to unset the callback of adapter connection state change.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAUnSetLEAdapterStateChangedCb();
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CA_LE_INTERFACE_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caleinterface_singlethread.h b/resource/csdk/connectivity/inc/caleinterface_singlethread.h
new file mode 100644 (file)
index 0000000..6cc639b
--- /dev/null
@@ -0,0 +1,216 @@
+/* ****************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs for BLE modules.
+ */
+
+#ifndef CA_LE_INTERFACE_SINGLETHREAD_H_
+#define CA_LE_INTERFACE_SINGLETHREAD_H_
+
+#include <stdbool.h>
+
+#include "cacommon.h"
+#include "caleadapter_singlethread.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @enum CALETransferType_t
+ * @brief Provide information about different mode of data transfer
+ *        This enum is used to differentiate between unicast and multicast data transfer.
+ */
+typedef enum
+{
+    LE_MULTICAST,    /**< When this enum is selected, data will be updated to all OIC servers. */
+    LE_UNICAST       /**< When this enum is selected, data will be updated to desired OIC Server. */
+} CALETransferType_t;
+
+
+/**
+ * @brief  Used to get the current state of the LE adapter.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED  adapter not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAGetLEAdapterState();
+
+/**
+ * @brief  Used to initialize the network monitor layer of the LE adapter.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEInitializeNetworkMonitor();
+
+/**
+ * @brief  Used to terminate the network monitor layer of the LE adapter.
+ * @return NONE
+ */
+void CALETerminateNetworkMonitor();
+
+/**
+ * @brief  This function is used to set the callback for the Device state changes in the adapter.
+ *
+ * @param  callback  [IN]  Callback to notify the Device state change to the CA Layer
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback);
+
+/**
+ * @brief  Provides the BD address of the local adapter.
+ * @param  local_address [OUT] pointer to the location where bd address needs to be stored.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAGetLEAddress(char **local_address);
+
+/**
+ * @brief  Used to start Gatt Server thread for service creation and advertise ble service.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStartBleGattServer();
+
+/**
+ * @brief  Used to stop BLE Gatt Service.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStopBleGattServer();
+
+/**
+ * @brief  Used to store upper layer callback locally which will be used to send the data to
+ *         application
+ * @param  callback [IN] Callback function to pass the data to CA layer.
+ * @return NONE
+ */
+void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback);
+
+/**
+ * @brief  Used to update characteristics(Read/Write) value that we want to send to particular
+ *         client. Both unicast and multicast will use the same api. In mulicast, we will be
+ *         sending in loop to all clients.
+ *
+ * @param  charValue     [IN] Data that we want to send to client(unicast)/clients(multicast)
+ * @param  charValueLen  [IN] Length of the data.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
+                                                   uint8_t charValueLen);
+
+/**
+ * @brief  Used to start CAStartBleGattClientThread for initializing Gatt Client
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAStartBLEGattClient();
+
+/**
+ * @brief  Used to stop Gatt Client gracefully in turn it will call CATerminateBLEGattClient
+ *         function.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+void CAStopBLEGattClient();
+
+/**
+ * @brief  Used to unset all the callbacks and stop service discovery
+ * @return NONE
+ */
+void CATerminateBLEGattClient();
+
+/**
+ * @brief  Sets the value of characteristic and update the value to GATTServer(unicast).
+ *
+ * @param  remoteAddress [IN] The address of the remote device
+ * @param  data          [IN] The value of characteristic (byte array)
+ * @param  dataLen       [IN] The length of value
+ * @param  type          [IN] Type of the transfer(#CALETransferType_t)
+ * @param  position      [IN] The unique index of each ble server. Used for multicast feature.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char  *data,
+                                                const uint32_t dataLen, CALETransferType_t type,
+                                                const int32_t position);
+
+/**
+ * @brief  Sets the value of characteristic and update the value to all registered
+ *         GATTServer -> Multicast
+ * @param  data     [IN] The value of characteristic (byte array)
+ * @param  dataLen  [IN] The length of value
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t  CAUpdateCharacteristicsToAllGattServers(const char  *data, uint32_t dataLen);
+
+/**
+ * @brief  Used to store upper layer callback locally which will be used to send the data to
+ *         application
+ * @param  callback  [IN] Callback function to pass the data to CA layer.
+ *
+ * @return  void
+ */
+void CASetBLEReqRespClientCallback(CABLEClientDataReceivedCallback callback);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CA_LE_INTERFACE_SINGLETHREAD_H_ */
+
index 597da7b..e5ee5cb 100644 (file)
  * limitations under the License.
  *
  ******************************************************************/
-#ifndef __CA_MESSAGE_HANDLER_H_
-#define __CA_MESSAGE_HANDLER_H_
 
-#include <stdint.h>
+/**
+ * @file camessagehandler.h
+ * @brief This file contains message functionality.
+ */
+
+#ifndef CA_MESSAGE_HANDLER_H_
+#define CA_MESSAGE_HANDLER_H_
+
 #include "cacommon.h"
+#include "coap.h"
+
+/**
+ * @def VERIFY_NON_NULL
+ * @brief Macro to verify the validity of input argument.
+ */
+#define VERIFY_NON_NULL(arg, log_tag, log_message) \
+    if (NULL == arg ){ \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        return CA_STATUS_INVALID_PARAM; \
+    } \
+
+/**
+ * @def VERIFY_NON_NULL_VOID
+ * @brief Macro to verify the validity of input argument.
+ */
+#define VERIFY_NON_NULL_VOID(arg, log_tag, log_message) \
+    if (NULL == arg ){ \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        return; \
+    } \
+
+#define CA_MEMORY_ALLOC_CHECK(arg) { if (NULL == arg) {OIC_LOG(ERROR, TAG, "Out of memory"); \
+goto memory_error_exit;} }
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
-typedef enum
-{
-    SUCCESS = 0, NETWORK_ERROR, FAIL
-} CADetachErrorCode;
-
-typedef void (*CAMessageHandlerCallback)(int32_t id, CADetachErrorCode code);
-
-int32_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequestInfo_t* request);
+/**
+ * @brief   Detaches control from the caller for sending unicast request
+ * @param   endpoint       [IN]    endpoint information where the data has to be sent
+ * @param   request        [IN]    request that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *endpoint,
+                                  const CARequestInfo_t *request);
 
-int32_t CADetachResponseMessage(const CARemoteEndpoint_t* object, const CAResponseInfo_t* response);
+/**
+ * @brief   Detaches control from the caller for sending multicast request
+ * @param   object         [IN]    Group endpoint information where the data has to be sent
+ * @param   request        [IN]    request that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
+                                       const CARequestInfo_t *request);
 
-int32_t CADetachMessageResourceUri(const CAURI_t resourceUri);
+/**
+ * @brief   Detaches control from the caller for sending response
+ * @param   endpoint       [IN]    endpoint information where the data has to be sent
+ * @param   response       [IN]    response that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *endpoint,
+                                   const CAResponseInfo_t *response);
 
-void CASetMessageHandlerCallback(CAMessageHandlerCallback callback);
+/**
+ * @brief   Detaches control from the caller for sending request
+ * @param   resourceUri    [IN]    resource uri that needs to  be sent in the request
+ * @param   token          [IN]    token information of the request
+ * @param   tokenLength    [IN]    length of the token
+ * @param   options        [IN]    header options that need to be append in the request
+ * @param   numOptions     [IN]    number of options be appended
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
+                                      uint8_t tokenLength, const CAHeaderOption_t *options,
+                                      uint8_t numOptions);
 
+/**
+ * @brief   Setting the request and response callbacks for network packets
+ * @param   ReqHandler     [IN]    callback for receiving the requests
+ * @param   RespHandler    [IN]    callback for receiving the response
+ * @return  NONE
+ */
 void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler);
 
+/**
+ * @brief   Initialize the message handler by starting thread pool and initializing the
+ *          send and receive queue
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
 CAResult_t CAInitializeMessageHandler();
 
+/**
+ * @brief   Terminate the message handler by stopping  the thread pool and destroying the queues
+ * @return  NONE
+ */
 void CATerminateMessageHandler();
 
+/**
+ * @brief   Handler for receiving request and response callback in single thread model
+ */
 void CAHandleRequestResponseCallbacks();
 
+/**
+ * @brief To log the PDU data
+ * @param   pdu            [IN]    pdu data
+ */
+void CALogPDUInfo(coap_pdu_t *pdu);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif //#ifndef __CA_MESSAGE_HANDLER_H_
+#endif /* CA_MESSAGE_HANDLER_H_ */
+
diff --git a/resource/csdk/connectivity/inc/camessagehandler_singlethread.h b/resource/csdk/connectivity/inc/camessagehandler_singlethread.h
new file mode 100644 (file)
index 0000000..469c6ea
--- /dev/null
@@ -0,0 +1,137 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file camessagehandler_singlethread.h
+ * @brief This file contains message functionality.
+ */
+
+#ifndef CA_MESSAGE_HANDLER_SINGLETHREAD_H_
+#define CA_MESSAGE_HANDLER_SINGLETHREAD_H_
+
+#include "cacommon.h"
+#include "coap.h"
+
+/**
+ * @def VERIFY_NON_NULL
+ * @brief Macro to verify the validity of input argument.
+ */
+#define VERIFY_NON_NULL(arg, log_tag, log_message) \
+    if (NULL == arg ){ \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        return CA_STATUS_INVALID_PARAM; \
+    } \
+
+/**
+ * @def VERIFY_NON_NULL_VOID
+ * @brief Macro to verify the validity of input argument.
+ */
+#define VERIFY_NON_NULL_VOID(arg, log_tag, log_message) \
+    if (NULL == arg ){ \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+        return; \
+    } \
+
+#define CA_MEMORY_ALLOC_CHECK(arg) { if (NULL == arg) {OIC_LOG(ERROR, TAG, "Out of memory"); \
+goto memory_error_exit;} }
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   Detaches control from the caller for sending unicast request
+ * @param   endpoint       [IN]    endpoint information where the data has to be sent
+ * @param   request        [IN]    request that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *endpoint,
+                                  const CARequestInfo_t *request);
+
+/**
+ * @brief   Detaches control from the caller for sending multicast request
+ * @param   object         [IN]    Group endpoint information where the data has to be sent
+ * @param   request        [IN]    request that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
+                                       const CARequestInfo_t *request);
+
+/**
+ * @brief   Detaches control from the caller for sending response
+ * @param   endpoint       [IN]    endpoint information where the data has to be sent
+ * @param   response       [IN]    response that needs to be sent
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *endpoint,
+                                   const CAResponseInfo_t *response);
+
+/**
+ * @brief   Detaches control from the caller for sending request
+ * @param   resourceUri    [IN]    resource uri that needs to  be sent in the request
+ * @param   token          [IN]    token information of the request
+ * @param   tokenLength    [IN]    length of the token
+ * @param   options        [IN]    header options that need to be append in the request
+ * @param   numOptions     [IN]    number of options be appended
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
+                                      uint8_t tokenLength, const CAHeaderOption_t *options,
+                                      uint8_t numOptions);
+
+/**
+ * @brief   Setting the request and response callbacks for network packets
+ * @param   ReqHandler     [IN]    callback for receiving the requests
+ * @param   RespHandler    [IN]    callback for receiving the response
+ * @return  NONE
+ */
+void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler);
+
+/**
+ * @brief   Initialize the message handler by starting thread pool and initializing the
+ *          send and receive queue
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAInitializeMessageHandler();
+
+/**
+ * @brief   Terminate the message handler by stopping  the thread pool and destroying the queues
+ * @return  NONE
+ */
+void CATerminateMessageHandler();
+
+/**
+ * @brief   Handler for receiving request and response callback in single thread model
+ */
+void CAHandleRequestResponseCallbacks();
+
+/**
+ * @brief To log the PDU data
+ * @param   pdu            [IN]    pdu data
+ */
+void CALogPDUInfo(coap_pdu_t *pdu);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_MESSAGE_HANDLER_SINGLETHREAD_H_ */
+
diff --git a/resource/csdk/connectivity/inc/camsgparser.h b/resource/csdk/connectivity/inc/camsgparser.h
new file mode 100644 (file)
index 0000000..6780860
--- /dev/null
@@ -0,0 +1,171 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains common utility functions to manage the CA msg
+ * fragmentation and reassemebly.
+ */
+
+#ifndef CA_MSG_PARSER_H_
+#define CA_MSG_PARSER_H_
+
+#include "cacommon.h"
+#include "logger.h"
+
+/**
+ * @var MAX_DATA_LENGTH_SUPPORTED
+ * @brief From the adapter level, this is the maximum data length is supported
+ *        for the data transmission.
+ */
+#define MAX_DATA_LENGTH_SUPPORTED 4095
+
+/**
+ * @var NUMBER_OF_BITS_TO_IDENTIFY_DATA
+ * @brief The number of bits allocated to represent data length in header.
+ */
+#define NUMBER_OF_BITS_TO_IDENTIFY_DATA 12
+
+/**
+ * @var NUMBER_OF_BITS_IN_CA_HEADER
+ * @brief The length of the header in bits.
+ */
+#define NUMBER_OF_BITS_IN_CA_HEADER 15
+
+/**
+ * @var CA_HEADER_LENGTH
+ * @brief The length of the header in bytes.
+ */
+#define CA_HEADER_LENGTH 2
+
+/**
+ * @var CA_SUPPORTED_BLE_MTU_SIZE
+ * @brief The MTU supported for BLE adapter
+ */
+#define CA_SUPPORTED_BLE_MTU_SIZE  20
+
+#ifdef __TIZEN__
+/**
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
+#define PLATFORM_IDENTIFIER_BIT 1
+
+/**
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported from Tizen platform for EDR adapter.
+ */
+#define CA_SUPPORTED_EDR_MTU_SIZE  512
+
+#elif __ANDROID__
+/**
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
+#define PLATFORM_IDENTIFIER_BIT 0
+
+/**
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported from Android platform for EDR adapter.
+ */
+#define CA_SUPPORTED_EDR_MTU_SIZE  200
+
+#elif __ARDUINO__
+/**
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
+#define PLATFORM_IDENTIFIER_BIT 0
+
+/**
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported from Arduino platform for EDR adapter.
+ */
+#define CA_SUPPORTED_EDR_MTU_SIZE  200
+
+#else //Other Platforms
+/**
+ * @var PLATFORM_IDENTIFIER_BIT
+ * @brief Reserved bit to differentiating the platform. Currently not in use.
+ */
+#define PLATFORM_IDENTIFIER_BIT 0
+
+/**
+ * @var CA_SUPPORTED_EDR_MTU_SIZE
+ * @brief The MTU supported for EDR adapter
+ */
+#define CA_SUPPORTED_EDR_MTU_SIZE  200
+
+#endif
+
+/**
+ * @var HEADER_VERSION
+ * @brief Current Header version.
+ */
+#define HEADER_VERSION 1
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/*****************************************************************
+ * @file The CA Header format
+ * @brief CA Header will be difined by 2 bytes of Header.
+ * First two bits : Header version(Currently Its not being used)
+ * Third bit and fourth bit: Reserved bits for future use.
+ * 5th to 16th bit : 12 bits to provide the length of the data.
+ *****************************************************************/
+
+/**
+* @fn CAGenerateHeader
+* @brief This function is used to generate the CA specific header to maintain the fragmentation
+*           logic. The header sturcture explained above will be formed and returned to the caller.
+*
+* @param[in]  data    Pointer to the charcter data which needs to be printed.
+* @param[in]  length The total legth of the data which will be represented from 5th -16th bits
+*                              in the header.
+*
+* @return  CA_STATUS_OK on success. One of theCA_STATUS_FAILED or other error values on error.
+* @retval  CA_STATUS_OK  Successful
+* @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
+* @retval  CA_STATUS_FAILED Operation failed
+*/
+CAResult_t CAGenerateHeader(char *header, uint32_t length);
+
+/**
+* @fn CAParseHeader
+* @brief This function is used to parse the header in the receiver end. This function will
+*            provide the information of the total length of the data which has been fragmented.
+*
+* @param[in]  header  Pointer to the charcter data which contains the header information.
+*                                Note that pointer should point to two bytes of data header
+*                                 which needs to be parsed.
+*
+*/
+uint32_t CAParseHeader(const char *header);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  /* CA_MSG_PARSER_H_ */
+
index 4117bf7..2031ab6 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  * limitations under the License.
  *
  ******************************************************************/
-#ifndef _NETWORK_CONFIGURATOR_H_
-#define _NETWORK_CONFIGURATOR_H_
 
+/**
+ * @file
+ *
+ * This file contains  utility function for network configurations.
+ */
+
+#ifndef NETWORK_CONFIGURATOR_H_
+#define NETWORK_CONFIGURATOR_H_
+
+#include "cacommon.h"
 #include "uarraylist.h"
 
 #ifdef __cplusplus
@@ -27,19 +35,44 @@ extern "C"
 {
 #endif
 
-static uint32_t NETWORK_ETHERNET = CA_ETHERNET;
-static uint32_t NETWORK_WIFI = CA_WIFI;
-static uint32_t NETWORK_EDR = CA_EDR;
-static uint32_t NETWORK_LE = CA_LE;
+/**
+ * @brief   Add network type to the selected networks for network packets reception
+ * @param   transportType       [IN]    Transport type that needs to be added
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAAddNetworkType(CATransportType_t transportType);
 
-CAResult_t CAAddNetworkType(uint32_t CAConnectivityType);
+/**
+ * @brief   Remove network type from the selected configuration
+ * @param   transportType       [IN]    Transport type that needs to be removed
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARemoveNetworkType(CATransportType_t transportType);
 
-CAResult_t CARemoveNetworkType(uint32_t CAConnectivityType);
+/**
+ * @brief   Get selected network information
+ * @return array list having the connectivity types
+ */
+u_arraylist_t *CAGetSelectedNetworkList();
+
+/**
+ * @brief  Getnetwork informations of the selected networks
+ * @param   info    [OUT]   LocalConnectivity objects
+ * @param   size    [OUT]   No Of Array objects
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief   Terminate network type from selected configuration
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CATerminateNetworkType();
 
-u_arraylist_t* CAGetSelectedNetworkList();
 
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif //#ifndef _NETWORK_CONFIGURATOR_H_
+#endif /* NETWORK_CONFIGURATOR_H_ */
+
index baeb261..d96c7a3 100644 (file)
  * limitations under the License.
  *
  ******************************************************************/
-#ifndef __CA_PROTOCOL_MESSAGE_H_
-#define __CA_PROTOCOL_MESSAGE_H_
+/**
+ * @file caprotocolmessage.h
+ * @brief This file contains common function for handling protocol messages.
+ */
+
+#ifndef CA_PROTOCOL_MESSAGE_H_
+#define CA_PROTOCOL_MESSAGE_H_
 
 #include "cacommon.h"
 #include "config.h"
 #include "coap.h"
+#include "debug.h"
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
-uint32_t flags = 0;
+typedef uint32_t code_t;
 
-uint8_t msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */
+#define CA_RESPONSE_CLASS(C) (((C) >> 5)*100)
+#define CA_RESPONSE_CODE(C) (CA_RESPONSE_CLASS(C) + (C - COAP_RESPONSE_CODE(CA_RESPONSE_CLASS(C))))
 
-coap_block_t block =
-{   .num = 0, .m = 0, .szx = 6};
+/**
+ * @brief   generates pdu structure from the given information.
+ * @param   uri              [IN]    uri information of the pdu
+ * @param   code             [IN]    code of the pdu packet
+ * @param   info             [IN]    pdu information
+ * @return  generated pdu
+ */
+coap_pdu_t *CAGeneratePDU(const char *uri, uint32_t code, const CAInfo_t info);
 
-typedef uint32_t code_t;
+/**
+ * function for generating
+ */
 
 /**
- * function for generate
+ * @brief   extracts request information from received pdu.
+ * @param   pdu              [IN]     received pdu
+ * @param   outReqInfo       [OUT]    request info structure made from received pdu
+ * @param   outUri           [OUT]    uri received in the received pdu
+ * @param   buflen           [IN]     Buffer Length for outUri parameter
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-coap_pdu_t* CAGeneratePdu(const char* uri, const uint32_t code, const CAInfo_t info);
+CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri,
+                                   uint32_t buflen);
+
 /**
- * function for parsing
+ * @brief   extracts response information from received pdu.
+ * @param   pdu              [IN]     received pdu
+ * @param   outResInfo       [OUT]    response info structure made from received pdu
+ * @param   outUri           [OUT]    uri received in the received pdu
+ * @param   buflen           [IN]     Buffer Length for outUri parameter
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t* outReqInfo);
+CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
+                                    char *outUri, uint32_t buflen);
 
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t* outResInfo);
+/**
+ * @brief   creates pdu from the request information
+ * @param   code             [IN]    request or response code
+ * @param   options          [OUT]   options for the request and response
+ * @param   info             [IN]    information to create pdu
+ * @param   payload          [IN]    payload for the request or response consumed
+ * @return  generated pdu
+ */
+coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t info,
+                              const char *payload, size_t payloadSize);
 
-coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options);
+/**
+ * @brief   parse the URI and creates the options
+ * @param   uriInfo          [IN]    uri information
+ * @param   options          [OUT]   options information
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAParseURI(const char *uriInfo, coap_list_t **options);
 
-coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *optlist,
-        const char* payload);
+/**
+ * @brief   Helper that uses libcoap to parse either the path or the parameters of a URI
+ *          and populate the supplied options list.
+ *
+ * @param   str              [IN]    the input partial URI string (either path or query)
+ * @param   length           [IN]    the length of the supplied partial URI
+ * @param   target           [IN]    the part of the URI to parse (either COAP_OPTION_URI_PATH
+ *                                   or COAP_OPTION_URI_QUERY)
+ * @param   optlist          [OUT]   options information
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
+                             coap_list_t **optlist);
 
-void CAParseURI(const char* uriInfo, coap_list_t **options);
+/**
+ * @brief   create option list from header information in the info
+ * @param   code             [IN]    uri information
+ * @param   info             [IN]    information of the request/response
+ * @param   optlist          [OUT]   options information
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t info, coap_list_t **optlist);
 
-void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist);
+/**
+ * @brief   creates option node from key length and data
+ * @param   key              [IN]    key for the that needs to be sent
+ * @param   length           [IN]    length of the data that needs to be sent
+ * @param   data             [IN]    data that needs to be sent
+ * @return  created list
+ */
+coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const uint8_t *data);
 
-coap_list_t* CACreateNewOptionNode(const uint16_t key, const uint32_t length, const uint8_t *data);
+/**
+ * @brief   order the inserted options
+ *          need to replace queue head if new node has to be added before the existing queue head
+ * @param   a                [IN]    option 1 for insertion
+ * @param   b                [IN]    option 2 for insertion
+ * @return  0 or 1
+ */
+int CAOrderOpts(void *a, void *b);
 
-int32_t CAOrderOpts(void *a, void *b);
+/**
+ * @brief   number of options count
+ * @param   opt_iter         [IN]   option iteration for count
+ * @return number of options
+ */
+uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter);
 
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* outInfo);
+/**
+ * @brief   gets option data
+ * @param   data             [IN]    data that is received
+ * @param   length           [IN]    length of the data
+ * @param   option           [OUT]   result of the operation
+ * @param   buflen           [IN]    buffer length of the result
+ * @return  option count
+ */
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *option, uint32_t buflen);
+
+/**
+ * @brief   extracts request information from received pdu.
+ * @param   pdu              [IN]     received pdu
+ * @param   outCode          [OUT]    code of the received pdu
+ * @param   outInfo          [OUT]    request info structure made from received pdu
+ * @param   outUri           [OUT]    uri received in the received pdu
+ * @param   buflen           [IN]     Buffer Length for outUri parameter
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
+                            char *outUri, uint32_t buflen);
+
+/**
+ * @brief   create pdu from received data
+ * @param   data             [IN]   received data
+ * @param   length           [IN]   length of the data received
+ * @param   outCode          [OUT]  code received
+ * @return  coap_pdu_t value
+ */
+coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode);
 
-coap_pdu_t* CAParsePDU(const char* data, uint32_t* outCode);
+/**
+ * @brief   get Token fromn received data(pdu)
+ * @param   pdu_hdr          [IN]   header of received pdu
+ * @param   outInfo          [OUT]  information with token received
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo);
 
 /**
- * function for token
+ * @brief   generates the token
+ * @param   token        [OUT]  generated token
+ * @param   tokenLength  [IN]   length of the token
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CAGenerateTokenInternal(CAToken_t* token);
+CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength);
 
+/**
+ * @brief   destroys the token
+ * @param   token            [IN]   generated token
+ * @return  None
+ */
 void CADestroyTokenInternal(CAToken_t token);
 
+/**
+ * @brief   destroy the ca info structure
+ * @param   info             [IN]   info structure  created from received  packet
+ * @return  None
+ */
+void CADestroyInfo(CAInfo_t *info);
+
+/**
+ * @brief   gets message type from PDU binary data
+ * @param   pdu              [IN]   pdu data
+ * @param   size             [IN]   size of pdu data
+ * @return  message type
+ */
+CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size);
+
+/**
+ * @brief   gets message ID PDU binary data
+ * @param   pdu              [IN]   pdu data
+ * @param   size             [IN]   size of pdu data
+ * @return  message ID
+ */
+uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size);
+
+/**
+ * @brief   gets code PDU binary data
+ * @param   pdu              [IN]   pdu data
+ * @param   size             [IN]   size of pdu data
+ * @return  code
+ */
+CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif //#ifndef __CA_PROTOCOL_MESSAGE_H_
+#endif /* CA_PROTOCOL_MESSAGE_H_ */
diff --git a/resource/csdk/connectivity/inc/caqueueingthread.h b/resource/csdk/connectivity/inc/caqueueingthread.h
new file mode 100644 (file)
index 0000000..b3d282d
--- /dev/null
@@ -0,0 +1,113 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains common utility function for handling message ques.
+ */
+
+#ifndef CA_QUEUEING_THREAD_H_
+#define CA_QUEUEING_THREAD_H_
+
+#include <stdint.h>
+
+#include "cathreadpool.h"
+#include "camutex.h"
+#include "uqueue.h"
+#include "cacommon.h"
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**Thread function to be invoked**/
+typedef void (*CAThreadTask)(void *threadData);
+
+/**Data destroy function**/
+typedef void (*CADataDestroyFunction)(void *data, uint32_t size);
+
+typedef struct
+{
+    /** Thread pool of the thread started **/
+    ca_thread_pool_t threadPool;
+    /** mutex for synchrnoization **/
+    ca_mutex threadMutex;
+    /** conditional mutex for synchrnoization **/
+    ca_cond threadCond;
+    /**Thread function to be invoked**/
+    CAThreadTask threadTask;
+    /**Data destroy function**/
+    CADataDestroyFunction destroy;
+    /** Variable to inform the thread to stop **/
+    bool isStop;
+    /** Que on which the thread is operating. **/
+    u_queue_t *dataQueue;
+} CAQueueingThread_t;
+
+/**
+ * @brief   Initializes the queing thread
+ * @param   thread      [IN] thread data for each thread
+ * @param   handle      [IN] thread pool handle created
+ * @param   task        [IN] function to be called for each data
+ * @param   destroy     [IN] function to data destroy
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAQueueingThreadInitialize(CAQueueingThread_t *thread, ca_thread_pool_t handle,
+                                      CAThreadTask task, CADataDestroyFunction destroy);
+
+/**
+ * @brief   Starting the queueing thread
+ * @param   thread       [IN] thread data that needs to be started
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread);
+
+/**
+ * @brief   Add queueing thread data for new thread
+ * @param   thread      [IN] thread data for new thread control
+ * @param   data        [IN] data that needs to be given for each thread
+ * @param   size        [IN] length of the data
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAQueueingThreadAddData(CAQueueingThread_t *thread, void *data, uint32_t size);
+
+/**
+ * @brief   Stopping the queueing thread
+ * @param   thread      [IN] thread data that needs to be started
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+
+CAResult_t CAQueueingThreadStop(CAQueueingThread_t *thread);
+
+/**
+ * @brief   Terminating  the queing thread
+ * @param   thread      [IN] thread data for each thread
+ * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+
+CAResult_t CAQueueingThreadDestroy(CAQueueingThread_t *thread);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  /* CA_QUEUEING_THREAD_H_ */
+
index 4c3a984..002a6c5 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
  * limitations under the License.
  *
  ******************************************************************/
-#ifndef __CA_REMOTE_HANDLER_H_
-#define __CA_REMOTE_HANDLER_H_
 
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+/**
+ * @file
+ *
+ * This file contains common utility function for remote endpoints.
+ */
+
+#ifndef CA_REMOTE_HANDLER_H_
+#define CA_REMOTE_HANDLER_H_
 
 #include "cacommon.h"
 
@@ -31,25 +34,71 @@ extern "C"
 {
 #endif
 
-CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep);
+/**
+ * @brief   Creates a new remote endpoint from the input endpoint
+ * @param   endpoint       [IN]    endpoint information where the data has to be sent
+ * @return  remote endpoint created
+ */
+CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *endpoint);
 
-CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri);
+/**
+ * @brief   Creates a new remote endpoint from the input uri
+ * @param   uri                 [IN]    absolute uri information to create remote endpoint
+ * @param   transportType       [IN]    transport type of the endpoint
+ * @return  remote endpoint created
+ */
+CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri,
+                                                      const CATransportType_t transportType);
 
-CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
-        const CAAddress_t addr, const CAConnectivityType_t type);
+/**
+ * @brief   Creates a new remote endpoint from the input and other information
+ * @param   resourceUri         [IN]    absolute uri information to create remote endpoint
+ * @param   addr                [IN]    address of the endpoint
+ * @param   type                [IN]    transport  type of the endpoint
+ * @return  remote endpoint created
+ */
+CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
+                                                   const CAAddress_t addr,
+                                                   const CATransportType_t type);
 
-void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t* rep);
+/**
+ * @brief   Destroy remote endpoint
+ * @param   endpoint       [IN]    endpoint information where the data has to be sent
+ * @return  none
+ */
+void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t *rep);
 
-CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep);
+/**
+ * @brief   Creates a new request information
+ * @param   request       [IN]    request information that needs to be duplicated
+ * @return  remote endpoint created
+ */
+CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *request);
 
-void CADestroyRequestInfoInternal(CARequestInfo_t* rep);
+/**
+ * @brief   Destroy the request information
+ * @param   request       [IN]    request information that needs to be destroyed
+ * @return none
+ */
+void CADestroyRequestInfoInternal(CARequestInfo_t *request);
 
-CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep);
+/**
+ * @brief   Creates a new response information
+ * @param   response       [IN]    response information that needs to be duplicated
+ * @return  remote endpoint created
+ */
+CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *response);
 
-void CADestroyResponseInfoInternal(CAResponseInfo_t* rep);
+/**
+ * @brief   Destroy the response information
+ * @param   response       [IN]    response information that needs to be destroyed
+ * @return
+ */
+void CADestroyResponseInfoInternal(CAResponseInfo_t *response);
 
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
 
-#endif //#ifndef __CA_REMOTE_HANDLER_H_
+#endif /* CA_REMOTE_HANDLER_H_ */
+
diff --git a/resource/csdk/connectivity/inc/caretransmission.h b/resource/csdk/connectivity/inc/caretransmission.h
new file mode 100644 (file)
index 0000000..052fa41
--- /dev/null
@@ -0,0 +1,166 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caretransmission.h
+ * @brief This file contains common function for retransmission messages.
+ */
+
+#ifndef CA_RETRANSMISSION_H_
+#define CA_RETRANSMISSION_H_
+
+#include <stdint.h>
+
+#include "cathreadpool.h"
+#include "camutex.h"
+#include "uarraylist.h"
+#include "cacommon.h"
+
+/** CA_IPV4, CA_EDR, CA_LE **/
+#define DEFAULT_RETRANSMISSION_TYPE     (CA_IPV4 | CA_EDR | CA_LE)
+
+/** default ACK time is 2 sec.(CoAP) **/
+#define DEFAULT_ACK_TIMEOUT_SEC     2
+
+/** default max retransmission trying count is 4.(CoAP) **/
+#define DEFAULT_MAX_RETRANSMIT      4
+
+/** check period is 1 sec. **/
+#define RETRANSMISSION_CHECK_PERIOD_SEC     1
+
+/** retransmission data send method type**/
+typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                         uint32_t size);
+
+/** retransmission timeout callback type**/
+typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                    uint32_t size);
+
+typedef struct
+{
+    /** retransmission support transport type **/
+    CATransportType_t supportType;
+
+    /** retransmission trying count **/
+    uint8_t tryingCount;
+
+} CARetransmissionConfig_t;
+
+typedef struct
+{
+    /** Thread pool of the thread started **/
+    ca_thread_pool_t threadPool;
+
+    /** mutex for synchronization **/
+    ca_mutex threadMutex;
+
+    /** conditional mutex for synchronization **/
+    ca_cond threadCond;
+
+    /** send method for retransmission data **/
+    CADataSendMethod_t dataSendMethod;
+
+    /** callback function for retransmit timeout **/
+    CATimeoutCallback_t timeoutCallback;
+
+    /** retransmission configure data **/
+    CARetransmissionConfig_t config;
+
+    /** Variable to inform the thread to stop **/
+    bool isStop;
+
+    /** array list on which the thread is operating. **/
+    u_arraylist_t *dataList;
+
+} CARetransmission_t;
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   Initializes the retransmission context
+ * @param   context                     [IN] context for retransmission
+ * @param   handle                      [IN] thread pool handle
+ * @param   retransmissionSendMethod    [IN] function to be called for retransmission
+ * @param   timeoutCallback             [IN] callback for retransmit timeout
+ * @param   config                      [IN] configuration for retransmission.
+ *                                           if NULL is coming, it will set default values.
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionInitialize(CARetransmission_t *context, ca_thread_pool_t handle,
+                                      CADataSendMethod_t retransmissionSendMethod,
+                                      CATimeoutCallback_t timeoutCallback,
+                                      CARetransmissionConfig_t* config);
+
+/**
+ * @brief   Starting the retransmission context
+ * @param   context     [IN] context for retransmission
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionStart(CARetransmission_t *context);
+
+/**
+ * @brief   Pass the sent pdu data. if retransmission process need, internal thread will wake up and
+ *          process the retransmission data
+ * @param   context     [IN] context for retransmission
+ * @param   endpoint    [IN] endpoint information
+ * @param   pdu         [IN] sent pdu binary data
+ * @param   size        [IN] sent pdu binary data size
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionSentData(CARetransmission_t* context,
+                                    const CARemoteEndpoint_t* endpoint, const void* pdu,
+                                    uint32_t size);
+
+/**
+ * @brief   Pass the received pdu data. if received pdu is ACK data for the retransmission CON data,
+ *          the specified CON data will remove on retransmission list.
+ * @param   context             [IN] context for retransmission
+ * @param   endpoint            [IN] endpoint information
+ * @param   pdu                 [IN] received pdu binary data
+ * @param   size                [IN] received pdu binary data size
+ * @param   retransmissionPdu   [OUT] pdu data of the request for reset and ack
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
+                                        const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                        uint32_t size, void **retransmissionPdu);
+
+/**
+ * @brief   Stopping the retransmission context
+ * @param   context     [IN] context for retransmission
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionStop(CARetransmission_t *context);
+
+/**
+ * @brief   Terminating the retransmission context
+ * @param   context     [IN] context for retransmission
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionDestroy(CARetransmission_t *context);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  /* CA_RETRANSMISSION_H_ */
diff --git a/resource/csdk/connectivity/inc/caretransmission_singlethread.h b/resource/csdk/connectivity/inc/caretransmission_singlethread.h
new file mode 100644 (file)
index 0000000..5e581be
--- /dev/null
@@ -0,0 +1,155 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caretransmission_singlethread.h
+ * @brief This file contains common function for retransmission messages.
+ */
+
+#ifndef CA_RETRANSMISSION_SINGLETHREAD_H_
+#define CA_RETRANSMISSION_SINGLETHREAD_H_
+
+#include <stdint.h>
+
+#include "uarraylist.h"
+#include "cacommon.h"
+
+/** CA_IPV4, CA_LE **/
+#define DEFAULT_RETRANSMISSION_TYPE     (CA_IPV4 | CA_LE)
+
+/** default retransmission trying count is 4. **/
+#define DEFAULT_RETRANSMISSION_COUNT    4
+
+/** check period is 1 sec. **/
+#define RETRANSMISSION_CHECK_PERIOD_SEC     1
+
+/** retransmission data send method type**/
+typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                         uint32_t size);
+
+/** retransmission timeout callback type**/
+typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                    uint32_t size);
+
+typedef struct
+{
+    /** retransmission support transport type **/
+    CATransportType_t supportType;
+
+    /** retransmission trying count **/
+    uint8_t tryingCount;
+
+} CARetransmissionConfig_t;
+
+typedef struct
+{
+    /** send method for retransmission data **/
+    CADataSendMethod_t dataSendMethod;
+
+    /** callback function for retransmit timeout **/
+    CATimeoutCallback_t timeoutCallback;
+
+    /** retransmission configure data **/
+    CARetransmissionConfig_t config;
+
+    /** Variable to inform the thread to stop **/
+    bool isStop;
+
+    /** array list on which the thread is operating. **/
+    u_arraylist_t *dataList;
+
+} CARetransmission_t;
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   Initializes the retransmission context
+ * @param   context                   [IN]    context for retransmission
+ * @param   retransmissionSendMethod  [IN]    function to be called for retransmission
+ * @param   timeoutCallback           [IN]    callback for retransmit timeout
+ * @param   config                    [IN]    configuration for retransmission.
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
+                                      CADataSendMethod_t retransmissionSendMethod,
+                                      CATimeoutCallback_t timeoutCallback,
+                                      CARetransmissionConfig_t *config);
+
+/**
+ * @brief   Pass the sent pdu data. if retransmission process need, internal thread will wake up
+ *          and process the retransmission data.
+ * @param   context     [IN]    context for retransmission
+ * @param   endpoint    [IN]    endpoint information
+ * @param   pdu         [IN]    sent pdu binary data
+ * @param   size        [IN]    sent pdu binary data size
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionSentData(CARetransmission_t *context,
+                                    const CARemoteEndpoint_t *endpoint,
+                                    const void *pdu, uint32_t size);
+
+/**
+ * @brief   Paas the received pdu data. if received pdu is ACK data for the retransmission CON data,
+ *          the specified CON data will remove on retransmission list.
+ * @param   context             [IN]    context for retransmission
+ * @param   endpoint            [IN]    endpoint information
+ * @param   pdu                 [IN]    received pdu binary data
+ * @param   size                [IN]    received pdu binary data size
+ * @param   retransmissionPdu   [OUT]   pdu data of the request for reset and ack
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
+                                        const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                        uint32_t size, void **retransmissionPdu);
+
+/**
+ * @brief   Stopping the retransmission context
+ * @param   context     [IN]    context for retransmission
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionStop(CARetransmission_t *context);
+
+/**
+ * @brief   Terminating the retransmission context
+ * @param   context     [IN]    context for retransmission
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CARetransmissionDestroy(CARetransmission_t *context);
+
+/**
+ * @brief   Retransmitting the request/response for CONFIRMABLE type
+ */
+void CACheckRetransmissionList();
+
+/**
+ * @brief   Invoke Retransmission according to TimedAction Response
+ * @param   threadValue [IN]    context for retransmission
+ */
+void CARetransmissionBaseRoutine(void *threadValue);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  /* CA_RETRANSMISSION_SINGLETHREAD_H_ */
+
diff --git a/resource/csdk/connectivity/inc/cawifiadapter.h b/resource/csdk/connectivity/inc/cawifiadapter.h
deleted file mode 100644 (file)
index 07ad36a..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-/**
- * @file cawifiadapter.h
- * @brief This file contains the APIs for WiFi Adapter.
- */
-#ifndef __CA_WIFI_ADAPTER_H__
-#define __CA_WIFI_ADAPTER_H__
-
-#include "cacommon.h"
-#include "caadapterinterface.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/**
- * @brief API to initialize WiFi Interface.
- * @param registerCallback [IN] To register WIFI interfaces to Connectivity Abstraction Layer
- * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
- * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
-
-/**
- * @brief Start WiFi Interface adapter.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartWIFI();
-
-/**
- * @brief Starting listening server for receiving multicast search requests
- * Transport Specific Behavior:
- *   WIFI Starts Multicast Server on  all available IPs and prefixed port number and as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartWIFIListeningServer();
-
-/**
- * @brief for starting discovery servers for receiving multicast advertisements
- * Transport Specific Behavior:
- *   WIFI Starts Start multicast server on all available IPs and prefixed port number as per OIC Specification
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartWIFIDiscoveryServer();
-
-/**
- * @brief Sends data to the endpoint using the adapter connectivity.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
-
-/**
- * @brief Sends Multicast data to the endpoint using the WIFI connectivity.
- * Note: length must be > 0.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendWIFIMulticastData(void* data, uint32_t dataLen);
-
-/**
- * @brief Starts notification server on WIFI adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartWIFINotifyRecvServers();
-
-/**
- * @brief Send notification information.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to
- *                              which the unicast data has to be sent.
- * @param   data        [IN]    Data which required to be sent.
- * @param   dataLen     [IN]    Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
-/**
- * @brief Get WIFI Connectivity network information
- * @param   info        [OUT]   Local connectivity information structures
- * @param   size        [OUT]   Number of local connectivity structures.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size);
-
-/**
- * @brief Read Synchronous API callback.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAReadWIFIData();
-
-/**
- * @brief Stopping the adapters and close socket connections
- *   WIFI Stops all multicast and unicast servers and close sockets.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStopWIFI();
-
-/**
- * @brief Terminate the WIFI connectivity adapter.
- * Configuration information will be deleted from further use
- */
-void CATerminateWIfI();
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif//#ifndef __CA_WIFI_ADAPTER_H__
diff --git a/resource/csdk/connectivity/inc/cawificore.h b/resource/csdk/connectivity/inc/cawificore.h
deleted file mode 100644 (file)
index 64e7a20..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-/**
- * @file cawificore.h
- * @brief This file contains the APIs for Wi-Fi communications.
- */
-#ifndef __CA_WIFICORE_H_
-#define __CA_WIFICORE_H_
-
-#include "cacommon.h"
-#include "config.h"
-#include "coap.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-typedef void (*CAPacketReceiveCallback)(const char* address, const char* data);
-
-void CAWiFiInitialize();
-
-void CAWiFiTerminate();
-
-int32_t CAWiFiSendUnicastMessage(const char* address, const char* data, int32_t length);
-
-int32_t CAWiFiSendMulticastMessage(const char* m_address, const char* data);
-
-int32_t CAWiFiStartUnicastServer(const char* address, int32_t port);
-
-int32_t CAWiFiStartMulticastServer(const char* m_address, int32_t port);
-
-int32_t CAWiFiStopUnicastServer(int32_t server_id);
-
-int32_t CAWiFiStopMulticastServer(int32_t server_id);
-
-void CAWiFiSetCallback(CAPacketReceiveCallback callback);
-
-void* CAUnicastReceiveThread(void* data);
-
-void* CAUnicastSendThread(void* data);
-
-void CASendUnicastMessage(char* address, void* data);
-
-int32_t CASendUnicastMessageImpl(const char* address, const char* data, int32_t lengh);
-
-void CAStopUnicastSendThread();
-
-void* CAMulticastReceiveThread(void* data);
-
-void* CAMulticastSendThread(void* data);
-
-void CASendMulticastMessage(void* data);
-
-int32_t CASendMulticastMessageImpl(const char* msg);
-
-void CAStopMulticastSendThread();
-
-void CAGetLocalAddress(char* addressBuffer);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif
diff --git a/resource/csdk/connectivity/inc/cawifiethernetadapter.h b/resource/csdk/connectivity/inc/cawifiethernetadapter.h
deleted file mode 100644 (file)
index 45dcab8..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-/**
- * @file cawifiethernetadapter.h
- * @brief This file contains the APIs for WiFi/Ethernet Adapter.
- */
-#ifndef __CA_WIFI_ETHERNET_ADAPTER_H__
-#define __CA_WIFI_ETHERNET_ADAPTER_H__
-
-#include "cacommon.h"
-#include "caadapterinterface.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/**
- * @brief API to initialize WiFi Interface.
- * @param registerCallback to register WIFI interfaces to things communication
- * @param reqRespCallback for sending responses and discovery messages from unicast , multicast servers
- * @param netCallback to intimate the network additions to things communication
- * @return Error Code
- */
-CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
-
-/**
- * @brief API to Start WiFi Interface.
- * @return Error Code
- */
-CAResult_t CAStartWIFI();
-
-/**
- * @brief starting listening server
- * Transport Specific Behaviour
- *      IP :- Start Multicast Server on  all available IPs and prefixed port number and as per OIC Specification.
- * @return Error Code CAResult_t.
- */
-CAResult_t CAStartWIFIListeningServer();
-
-/**
- * @brief for starting discovery servers.
- * Transport Specific Behaviour
- *      IP :- Start Multicast Server on all available IPs and prefixed port number as per OIC Specification.
- * @return CAResult_t.
- * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartWIFIDiscoveryServer();
-
-/**
- * @brief Send Multicast Data interface API callback.
- * Note: length must be > 0
- * @param endpoint - Endpoint information (like ipaddress , port, reference uri and connectivity type) to which the multicast data has to be sent.
- * @param data - void pointer data which will be sent via client
- * @param dataLen - size of data to be sent
- * @return - Will return the number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
-
-/**
- * @brief API to send data to a group of remote addresses.
- * @param endpoint - Endpoint information (like ipaddress , port, reference uri and connectivity type) to which the multicast data has to be sent.
- * @param data - void pointer data which will be sent via client
- * @param dataLen - size of data to be sent
- * @return - size of data sent or -1 on error
- */
-uint32_t CASendWIFIMulticastData(void* data, uint32_t dataLen);
-
-/**
- * @brief Start Notification Server interface API callback.
- *
- * @return CAResult_t.
- * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartWIFINotifyRecvServers();
-
-/**
- * @brief Send Notification Data interface API callback.
- * Note: length must be > 0
- * @param endpoint - remote endpoint having endpoint details
- *  @param data - data to be sent
- *  @param dataLen - length of data to be sent
- *  @return Will return the number of bytes sent on the network. Return value equal to zero indicates error.
- */
-uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen);
-/**
- * @brief Get Network Information
- *
- * @return CAResult_t.
- * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size);
-
-/**
- * @brief Read Synchronous API callback.
- * @return Error Code CAResult_t.
- * @return CAResult_t.
- * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAReadWIFIData();
-
-/**
- * @brief API to Stop WiFi Interface.
- * @return CAResult_t
- */
-CAResult_t CAStopWIFI();
-
-/**
- * @brief API to terminate WiFi Interface.
- * @return none.
- */
-void CATerminateWifi();
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif
diff --git a/resource/csdk/connectivity/lib/android/jni/Android.mk b/resource/csdk/connectivity/lib/android/jni/Android.mk
new file mode 100644 (file)
index 0000000..ee3d6a1
--- /dev/null
@@ -0,0 +1,31 @@
+#/******************************************************************
+#*
+#* Copyright 2015 Samsung Electronics All Rights Reserved.
+#*
+#*
+#*
+#* Licensed under the Apache License, Version 2.0 (the "License");
+#* you may not use this file except in compliance with the License.
+#* You may obtain a copy of the License at
+#*
+#*      http://www.apache.org/licenses/LICENSE-2.0
+#*
+#* Unless required by applicable law or agreed to in writing, software
+#* distributed under the License is distributed on an "AS IS" BASIS,
+#* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#* See the License for the specific language governing permissions and
+#* limitations under the License.
+#*
+#******************************************************************/
+#define build type
+BUILD = debug
+
+DEFINE_FLAG = -D__ANDROID__
+
+
+BUILD_FLAG.debug       = $(DEFINE_FLAG)
+BUILD_FLAG = $(BUILD_FLAG.$(BUILD))
+
+LOCAL_PATH = ../
+
+include $(CLEAR_VARS)
diff --git a/resource/csdk/connectivity/lib/android/jni/Application.mk b/resource/csdk/connectivity/lib/android/jni/Application.mk
new file mode 100644 (file)
index 0000000..46e2863
--- /dev/null
@@ -0,0 +1,28 @@
+#/******************************************************************
+#*
+#* Copyright 2015 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.
+#*
+#******************************************************************/
+
+#Specify Android.mk path w.r.t APPLICATION_BUILD in the Makefile
+APP_PROJECT_PATH = ./
+
+APP_STL = gnustl_shared
+APP_PLATFORM = android-21
+APP_CPPFLAGS += -fexceptions
+APP_CPPFLAGS += -frtti += -Wno-error=format-security
+APP_CFLAGS = -Wno-error=format-security
diff --git a/resource/csdk/connectivity/lib/arduino/RBL_nRF8001.patch b/resource/csdk/connectivity/lib/arduino/RBL_nRF8001.patch
new file mode 100644 (file)
index 0000000..ab0e231
--- /dev/null
@@ -0,0 +1,137 @@
+diff -rupN RBL_nRF8001_old/RBL_nRF8001.cpp RBL_nRF8001/RBL_nRF8001.cpp
+--- RBL_nRF8001_old/RBL_nRF8001.cpp    2015-01-13 12:25:32.000000000 +0530
++++ RBL_nRF8001/RBL_nRF8001.cpp        2015-01-13 12:40:41.740244741 +0530
+@@ -22,7 +22,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOU
+ #endif
+ /* Store the setup for the nRF8001 in the flash of the AVR to save on RAM */
+-static hal_aci_data_t setup_msgs[NB_SETUP_MESSAGES] PROGMEM = SETUP_MESSAGES_CONTENT;
++static const hal_aci_data_t setup_msgs[NB_SETUP_MESSAGES] PROGMEM = SETUP_MESSAGES_CONTENT;
+ #if defined(BLEND_MICRO)
+ static char device_name[11] = "BlendMicro";
+@@ -31,7 +31,10 @@ static char device_name[11] = "Blend
+ #else
+ static char device_name[11] = "BLE Shield";
+ #endif
+-              
++
++#define BLE_ADDRESS_SIZE 18
++static unsigned char *gLeAddress = NULL;
++
+ static uint16_t Adv_Timeout = 0;      // Advertising all the time
+ static uint16_t Adv_Interval = 0x0050; /* advertising interval 50ms
+@@ -117,7 +120,7 @@ void ble_begin()
+         aci_state.aci_setup_info.services_pipe_type_mapping = NULL;
+     }
+     aci_state.aci_setup_info.number_of_pipes    = NUMBER_OF_PIPES;
+-    aci_state.aci_setup_info.setup_msgs         = setup_msgs;
++    aci_state.aci_setup_info.setup_msgs         = (hal_aci_data_t*)setup_msgs;
+     aci_state.aci_setup_info.num_setup_msgs     = NB_SETUP_MESSAGES;
+     /*
+@@ -159,7 +162,7 @@ void ble_begin()
+ static volatile byte ack = 0;
+ void ble_write(unsigned char data)
+-{         
++{
+     if(tx_buffer_len == MAX_TX_BUFF)
+     {
+             return;
+@@ -199,13 +202,13 @@ unsigned char ble_connected()
+ }
+ void ble_set_name(char *name)
+-{       
++{
+     unsigned char len=0;
+-    
++
+     len = strlen(name);
+     if(len > 10)
+     {
+-        Serial.print("the new name is too long");        
++        Serial.print("the new name is too long");
+     }
+     else
+     {
+@@ -236,6 +239,10 @@ void ble_reset(uint8_t reset_pin)
+ void ble_disconnect(void)
+ {
+       lib_aci_disconnect(&aci_state, ACI_REASON_TERMINATE);
++    if (NULL != gLeAddress)
++    {
++        free(gLeAddress);
++    }
+ }
+ static void process_events()
+@@ -271,6 +278,7 @@ static void process_events()
+                             lib_aci_set_local_data(&aci_state, PIPE_GAP_DEVICE_NAME_SET , (uint8_t *)&device_name , strlen(device_name));
+                             lib_aci_connect(Adv_Timeout/* in seconds */, Adv_Interval /* advertising interval 50ms*/);
+                             Serial.println(F("Advertising started"));
++                            lib_aci_get_address();
+                         }
+                         break;
+                 }
+@@ -294,6 +302,32 @@ static void process_events()
+                     lib_aci_set_local_data(&aci_state, PIPE_DEVICE_INFORMATION_HARDWARE_REVISION_STRING_SET,
+                     (uint8_t *)&(aci_evt->params.cmd_rsp.params.get_device_version), sizeof(aci_evt_cmd_rsp_params_get_device_version_t));
+                 }
++
++                if (ACI_CMD_GET_DEVICE_ADDRESS == aci_evt->params.cmd_rsp.cmd_opcode)
++                {
++                    if (NULL != gLeAddress)
++                    {
++                        free(gLeAddress);
++                    }
++                    gLeAddress = (unsigned char *) malloc (BLE_ADDRESS_SIZE);
++                    if (NULL == gLeAddress)
++                    {
++                        Serial.println("error");
++                        break;
++                    }
++                    char *tempAddr = (char *) gLeAddress;
++                    int8_t iter = 0;
++                    for (iter = BTLE_DEVICE_ADDRESS_SIZE - 1; iter >= 0; iter--)
++                    {
++                        sprintf(tempAddr, "%02x%c",
++                                 (uint8_t)aci_evt->params.cmd_rsp.params.get_device_address.bd_addr_own[iter], 58);
++                        tempAddr += 3;
++                    }
++                    gLeAddress[BLE_ADDRESS_SIZE - 1] = '\0';
++                    Serial.println("LEAddress :");
++                    Serial.println((char *)gLeAddress);
++                    return;
++                }
+                 break;
+             case ACI_EVT_CONNECTED:
+@@ -471,3 +505,12 @@ void ble_do_events()
+ #endif
+ }
++unsigned char* ble_getAddress()
++{
++    return gLeAddress;
++}
++
++void ble_radio_reset()
++{
++    lib_aci_radio_reset();
++}
+diff -rupN RBL_nRF8001_old/RBL_nRF8001.h RBL_nRF8001/RBL_nRF8001.h
+--- RBL_nRF8001_old/RBL_nRF8001.h      2015-01-13 12:25:32.000000000 +0530
++++ RBL_nRF8001/RBL_nRF8001.h  2015-01-13 12:40:41.740244741 +0530
+@@ -48,6 +48,8 @@ void ble_set_pins(uint8_t reqn, uint8_t
+ unsigned char ble_busy();
+ void ble_reset(uint8_t reset_pin);
+ void ble_disconnect(void);
++unsigned char* ble_getAddress();
++void ble_radio_reset();
+ #endif
+
diff --git a/resource/csdk/connectivity/lib/arduino/arduino_due_ble.patch b/resource/csdk/connectivity/lib/arduino/arduino_due_ble.patch
new file mode 100644 (file)
index 0000000..2e0b165
--- /dev/null
@@ -0,0 +1,69 @@
+diff -rupN BLE_Old/aci_setup.cpp BLE_New/aci_setup.cpp
+--- BLE_Old/aci_setup.cpp      2015-02-26 08:59:03.289267311 +0530
++++ BLE_New/aci_setup.cpp      2015-02-26 08:59:02.985267313 +0530
+@@ -63,6 +63,9 @@ static bool aci_setup_fill(aci_state_t *
+               //Add 2 bytes to the length byte for status byte, length for the total number of bytes
+               memcpy(&msg_to_send, &(aci_stat->aci_setup_info.setup_msgs[*num_cmd_offset]), 
+                                 (aci_stat->aci_setup_info.setup_msgs[*num_cmd_offset].buffer[0]+2)); 
++      #elif defined(__SAM3X8E__)
++              memcpy(&msg_to_send, &(aci_stat->aci_setup_info.setup_msgs[*num_cmd_offset]),
++                                (aci_stat->aci_setup_info.setup_msgs[*num_cmd_offset].buffer[0]+2));
+       #endif
+     //Put the Setup ACI message in the command queue
+diff -rupN BLE_Old/hal_aci_tl.cpp BLE_New/hal_aci_tl.cpp
+--- BLE_Old/hal_aci_tl.cpp     2015-02-26 08:59:03.521267309 +0530
++++ BLE_New/hal_aci_tl.cpp     2015-02-26 08:59:03.285267311 +0530
+@@ -346,6 +346,12 @@ void hal_aci_tl_init(aci_pins_t *a_pins,
+   The SPI library assumes that the hardware pins are used
+   */
++#if defined(__SAM3X8E__)
++      SPI.begin          (DUE_SPI_CSN);
++  SPI.setBitOrder    (DUE_SPI_CSN, LSBFIRST);
++  SPI.setClockDivider(DUE_SPI_CSN, a_pins->spi_clock_divider); /* This will run the SPI at 3MHz assuming a 84MHz clock to the mcu*/
++  SPI.setDataMode    (DUE_SPI_CSN, SPI_MODE0);
++#else
+   SPI.begin();
+   //Board dependent defines
+   #if defined (__AVR__)
+@@ -357,6 +363,7 @@ void hal_aci_tl_init(aci_pins_t *a_pins,
+   #endif
+   SPI.setClockDivider(a_pins->spi_clock_divider);
+   SPI.setDataMode(SPI_MODE0);
++#endif
+   /* Initialize the ACI Command queue. This must be called after the delay above. */
+   aci_queue_init(&aci_tx_q);
+@@ -429,6 +436,8 @@ static uint8_t spi_readwrite(const uint8
+     uint8_t tmp_bits;
+     tmp_bits = SPI.transfer(REVERSE_BITS(aci_byte));
+       return REVERSE_BITS(tmp_bits);
++#elif defined(__SAM3X8E__)
++      return SPI.transfer(DUE_SPI_CSN, aci_byte, SPI_CONTINUE);
+ #endif
+ }
+diff -rupN BLE_Old/hal_platform.h BLE_New/hal_platform.h
+--- BLE_Old/hal_platform.h     2015-02-26 08:59:03.293267311 +0530
++++ BLE_New/hal_platform.h     2015-02-26 08:59:02.989267313 +0530
+@@ -71,6 +71,19 @@
+       
+       //Redefine the function for reading from flash in ChipKit
+       #define memcpy_P        memcpy
++#elif defined(__SAM3X8E__)
++              /* definition for DUE */
++              #include "Arduino.h"
++
++              #define F(X) (X)
++              #undef PSTR
++              #define PSTR(x) (x)
++              #define PROGMEM
++
++              #define pgm_read_byte_near(x) (x)
++              #define memcpy_P memcpy
++
++              #define DUE_SPI_CSN            52
+ #endif
+ #endif /* PLATFORM_H__ */
diff --git a/resource/csdk/connectivity/lib/arduino/arduino_libraries.patch b/resource/csdk/connectivity/lib/arduino/arduino_libraries.patch
new file mode 100644 (file)
index 0000000..507aa99
--- /dev/null
@@ -0,0 +1,340 @@
+diff -rupN ./libraries/Ethernet/src/Ethernet.cpp ./arduino-1.5.8/libraries/Ethernet/src/Ethernet.cpp
+--- ./libraries/Ethernet/src/Ethernet.cpp      2014-10-01 20:45:35.000000000 +0530
++++ ./arduino-1.5.8/libraries/Ethernet/src/Ethernet.cpp        2015-02-05 15:51:09.000000000 +0530
+@@ -7,10 +7,10 @@ uint8_t EthernetClass::_state[MAX_SOCK_N
+   0, 0, 0, 0 };
+ uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = { 
+   0, 0, 0, 0 };
++static DhcpClass s_dhcp;
+ int EthernetClass::begin(uint8_t *mac_address)
+ {
+-  static DhcpClass s_dhcp;
+   _dhcp = &s_dhcp;
+diff -rupN ./libraries/Ethernet/src/utility/socket.cpp ./arduino-1.5.8/libraries/Ethernet/src/utility/socket.cpp
+--- ./libraries/Ethernet/src/utility/socket.cpp        2014-10-01 20:45:35.000000000 +0530
++++ ./arduino-1.5.8/libraries/Ethernet/src/utility/socket.cpp  2015-02-05 15:55:18.000000000 +0530
+@@ -295,6 +295,7 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+ {
+   uint8_t head[8];
+   uint16_t data_len=0;
++  uint16_t data_copied=0;
+   uint16_t ptr=0;
+   if ( len > 0 )
+@@ -316,10 +317,6 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+       data_len = head[6];
+       data_len = (data_len << 8) + head[7];
+-      W5100.read_data(s, ptr, buf, data_len); // data copy.
+-      ptr += data_len;
+-
+-      W5100.writeSnRX_RD(s, ptr);
+       break;
+     case SnMR::IPRAW :
+@@ -332,11 +329,6 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+       addr[3] = head[3];
+       data_len = head[4];
+       data_len = (data_len << 8) + head[5];
+-
+-      W5100.read_data(s, ptr, buf, data_len); // data copy.
+-      ptr += data_len;
+-
+-      W5100.writeSnRX_RD(s, ptr);
+       break;
+     case SnMR::MACRAW:
+@@ -344,19 +336,22 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+       ptr+=2;
+       data_len = head[0];
+       data_len = (data_len<<8) + head[1] - 2;
+-
+-      W5100.read_data(s, ptr, buf, data_len);
+-      ptr += data_len;
+-      W5100.writeSnRX_RD(s, ptr);
+       break;
+     default :
+       break;
+     }
++      
++      if (data_len > 0)
++      {
++          data_copied = (data_len <= len) ? data_len : len;// only copy the len bytes, rest of is discarded.
++              W5100.read_data(s, ptr, buf, data_copied); // data copy.
++              ptr += data_len;
++              W5100.writeSnRX_RD(s, ptr);
++      }
+     W5100.execCmdSn(s, Sock_RECV);
+-    SPI.endTransaction();
+   }
+-  return data_len;
++  return data_copied;
+ }
+ /**
+diff -rupN ./libraries/Time/Time/DateStrings.cpp ./arduino-1.5.8/libraries/Time/Time/DateStrings.cpp
+--- ./libraries/Time/Time/DateStrings.cpp      2010-03-06 11:09:22.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/DateStrings.cpp        2015-02-05 16:35:01.000000000 +0530
+@@ -6,8 +6,18 @@
+  * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h
+  * 
+  */
+- 
+-#include <avr/pgmspace.h> 
++
++#if defined(__AVR__)
++#include <avr/pgmspace.h>
++#else
++// for compatiblity with Arduino Due and Teensy 3.0 and maybe others?
++#define PROGMEM
++#define PGM_P  const char *
++#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
++#define pgm_read_word(addr) (*(const unsigned char **)(addr))
++#define strcpy_P(dest, src) strcpy((dest), (src))
++#endif
++#include <string.h> // for strcpy_P or strcpy
+ #include "Time.h"
+  
+ // the short strings for each day or month must be exactly dt_SHORT_STR_LEN
+@@ -15,38 +25,38 @@
+ static char buffer[dt_MAX_STRING_LEN+1];  // must be big enough for longest string and the terminating null
+-char monthStr1[] PROGMEM = "January";
+-char monthStr2[] PROGMEM = "February";
+-char monthStr3[] PROGMEM = "March";
+-char monthStr4[] PROGMEM = "April";
+-char monthStr5[] PROGMEM = "May";
+-char monthStr6[] PROGMEM = "June";
+-char monthStr7[] PROGMEM = "July";
+-char monthStr8[] PROGMEM = "August";
+-char monthStr9[] PROGMEM = "September";
+-char monthStr10[] PROGMEM = "October";
+-char monthStr11[] PROGMEM = "November";
+-char monthStr12[] PROGMEM = "December";
++const char monthStr1[] PROGMEM = "January";
++const char monthStr2[] PROGMEM = "February";
++const char monthStr3[] PROGMEM = "March";
++const char monthStr4[] PROGMEM = "April";
++const char monthStr5[] PROGMEM = "May";
++const char monthStr6[] PROGMEM = "June";
++const char monthStr7[] PROGMEM = "July";
++const char monthStr8[] PROGMEM = "August";
++const char monthStr9[] PROGMEM = "September";
++const char monthStr10[] PROGMEM = "October";
++const char monthStr11[] PROGMEM = "November";
++const char monthStr12[] PROGMEM = "December";
+-PGM_P monthNames_P[] PROGMEM = 
++PGM_P const monthNames_P[] PROGMEM = 
+ {
+     "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
+       monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
+ };
+-char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";
++const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";
+-char dayStr0[] PROGMEM = "Err";
+-char dayStr1[] PROGMEM = "Sunday";
+-char dayStr2[] PROGMEM = "Monday";
+-char dayStr3[] PROGMEM = "Tuesday";
+-char dayStr4[] PROGMEM = "Wednesday";
+-char dayStr5[] PROGMEM = "Thursday";
+-char dayStr6[] PROGMEM = "Friday";
+-char dayStr7[] PROGMEM = "Saturday";
++const char dayStr0[] PROGMEM = "Err";
++const char dayStr1[] PROGMEM = "Sunday";
++const char dayStr2[] PROGMEM = "Monday";
++const char dayStr3[] PROGMEM = "Tuesday";
++const char dayStr4[] PROGMEM = "Wednesday";
++const char dayStr5[] PROGMEM = "Thursday";
++const char dayStr6[] PROGMEM = "Friday";
++const char dayStr7[] PROGMEM = "Saturday";
+-PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
+-char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
++PGM_P const dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
++const char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
+ /* functions to return date strings */
+diff -rupN ./libraries/Time/Time/keywords.txt ./arduino-1.5.8/libraries/Time/Time/keywords.txt
+--- ./libraries/Time/Time/keywords.txt 2010-01-05 12:02:50.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/keywords.txt   2015-02-05 16:35:47.000000000 +0530
+@@ -22,7 +22,7 @@ weekday KEYWORD2
+ setTime KEYWORD2
+ adjustTime KEYWORD2
+ setSyncProvider KEYWORD2
+-setSyncInteval KEYWORD2
++setSyncInterval KEYWORD2
+ timeStatus KEYWORD2
+ #######################################
+ # Instances (KEYWORD2)
+diff -rupN ./libraries/Time/Time/Time.cpp ./arduino-1.5.8/libraries/Time/Time/Time.cpp
+--- ./libraries/Time/Time/Time.cpp     2010-11-01 18:02:50.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/Time.cpp       2015-02-05 16:32:08.000000000 +0530
+@@ -31,7 +31,7 @@
+ static tmElements_t tm;          // a cache of time elements
+ static time_t       cacheTime;   // the time the cache was updated
+-static time_t       syncInterval = 300;  // time sync will be attempted after this many seconds
++static uint32_t     syncInterval = 300;  // time sync will be attempted after this many seconds
+ void refreshCache( time_t t){
+   if( t != cacheTime)
+@@ -143,15 +143,17 @@ int year(time_t t) { // the year for the
+ static  const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
+  
+-void breakTime(time_t time, tmElements_t &tm){
++void breakTime(time_t timeInput, tmElements_t &tm){
+ // break the given time_t into time components
+ // this is a more compact version of the C library localtime function
+ // note that year is offset from 1970 !!!
+   uint8_t year;
+   uint8_t month, monthLength;
++  uint32_t time;
+   unsigned long days;
+-  
++
++  time = (uint32_t)timeInput;
+   tm.Second = time % 60;
+   time /= 60; // now it is minutes
+   tm.Minute = time % 60;
+@@ -200,7 +202,7 @@ time_t makeTime(tmElements_t &tm){
+ // previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
+   
+   int i;
+-  time_t seconds;
++  uint32_t seconds;
+   // seconds from 1970 till 1 jan 00:00:00 of the given year
+   seconds= tm.Year*(SECS_PER_DAY * 365);
+@@ -222,14 +224,14 @@ time_t makeTime(tmElements_t &tm){
+   seconds+= tm.Hour * SECS_PER_HOUR;
+   seconds+= tm.Minute * SECS_PER_MIN;
+   seconds+= tm.Second;
+-  return seconds; 
++  return (time_t)seconds; 
+ }
+ /*=====================================================*/     
+ /* Low level system time functions  */
+-static time_t sysTime = 0;
+-static time_t prevMillis = 0;
+-static time_t nextSyncTime = 0;
++static uint32_t sysTime = 0;
++static uint32_t prevMillis = 0;
++static uint32_t nextSyncTime = 0;
+ static timeStatus_t Status = timeNotSet;
+ getExternalTime getTimePtr;  // pointer to external sync function
+@@ -251,13 +253,15 @@ time_t now(){
+   if(nextSyncTime <= sysTime){
+       if(getTimePtr != 0){
+         time_t t = getTimePtr();
+-      if( t != 0)
++      if( t != 0) {
+         setTime(t);
+-      else
++      } else {
++        nextSyncTime = sysTime + syncInterval;
+         Status = (Status == timeNotSet) ?  timeNotSet : timeNeedsSync;        
++      }
+     }
+   }  
+-  return sysTime;
++  return (time_t)sysTime;
+ }
+ void setTime(time_t t){ 
+@@ -266,9 +270,9 @@ void setTime(time_t t){
+    sysUnsyncedTime = t;   // store the time of the first call to set a valid Time   
+ #endif
+-  sysTime = t;  
+-  nextSyncTime = t + syncInterval;
+-  Status = timeSet; 
++  sysTime = (uint32_t)t;  
++  nextSyncTime = (uint32_t)t + syncInterval;
++  Status = timeSet;
+   prevMillis = millis();  // restart counting from now (thanks to Korman for this fix)
+ } 
+@@ -293,6 +297,7 @@ void adjustTime(long adjustment){
+ }
+ timeStatus_t timeStatus(){ // indicates if time has been set and recently synchronized
++  now(); // required to actually update the status
+   return Status;
+ }
+@@ -303,5 +308,6 @@ void setSyncProvider( getExternalTime ge
+ }
+ void setSyncInterval(time_t interval){ // set the number of seconds between re-sync
+-  syncInterval = interval;
++  syncInterval = (uint32_t)interval;
++  nextSyncTime = sysTime + syncInterval;
+ }
+\ No newline at end of file
+diff -rupN ./libraries/Time/Time/Time.h ./arduino-1.5.8/libraries/Time/Time/Time.h
+--- ./libraries/Time/Time/Time.h       2011-07-22 17:30:06.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/Time.h 2015-02-05 16:22:27.000000000 +0530
+@@ -8,12 +8,29 @@
+ */     
+ #ifndef _Time_h
++#ifdef __cplusplus
+ #define _Time_h
+ #include <inttypes.h>
++#ifndef __AVR__
++#include <sys/types.h> // for __time_t_defined, but avr libc lacks sys/types.h
++#endif
++
++#if !defined(__time_t_defined) // avoid conflict with newlib or other posix libc
+ typedef unsigned long time_t;
++#endif
++
++// This ugly hack allows us to define C++ overloaded functions, when included
++// from within an extern "C", as newlib's sys/stat.h does.  Actually it is
++// intended to include "time.h" from the C library (on ARM, but AVR does not
++// have that file at all).  On Mac and Windows, the compiler will find this
++// "Time.h" instead of the C library "time.h", so we may cause other weird
++// and unpredictable effects by conflicting with the C library header "time.h",
++// but at least this hack lets us define C++ functions as intended.  Hopefully
++// nothing too terrible will result from overriding the C library header?!
++extern "C++" {
+ typedef enum {timeNotSet, timeNeedsSync, timeSet
+ }  timeStatus_t ;
+@@ -100,7 +117,11 @@ int     month(time_t t);   // the month
+ int     year();            // the full four digit year: (2009, 2010 etc) 
+ int     year(time_t t);    // the year for the given time
++extern "C"
++{
+ time_t now();              // return the current time as seconds since Jan 1 1970 
++}
++
+ void    setTime(time_t t);
+ void    setTime(int hr,int min,int sec,int day, int month, int yr);
+ void    adjustTime(long adjustment);
+@@ -121,6 +142,7 @@ void    setSyncInterval(time_t interval)
+ void breakTime(time_t time, tmElements_t &tm);  // break time_t into elements
+ time_t makeTime(tmElements_t &tm);  // convert time elements into time_t
+-
++} // extern "C++"
++#endif // __cplusplus
+ #endif /* _Time_h */
diff --git a/resource/csdk/connectivity/lib/arduino/arduinomega.properties b/resource/csdk/connectivity/lib/arduino/arduinomega.properties
new file mode 100644 (file)
index 0000000..3da589e
--- /dev/null
@@ -0,0 +1,33 @@
+#Source directories
+SDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+#SDIR_ARD_CORE2 = $(ARDUINO_DIR)/hardware/arduino/sam/cores/arduino/avr
+SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+SDIR_ARD_TIMED_ACTION = $(ARDUINO_DIR)/libraries/TimedAction
+SDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+
+SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_TIMED_ACTION):$(SDIR_ARD_SPI)
+
+#include directories
+IDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+IDIR_ARD_CORE2 = $(ARDUINO_DIR)/hardware/tools/avr/avr/include/
+IDIR_ARD_CORE3 = $(ARDUINO_DIR)/hardware/arduino/avr/variants/mega
+INCD_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+INCD_ARD_TIMED_ACTION = $(ARDUINO_DIR)/libraries/TimedAction
+IDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+IDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility
+
+
+INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) -I$(INCD_ARD_TIME) -I$(INCD_ARD_TIMED_ACTION) \
+                    -I$(IDIR_ARD_SPI) -I$(IDIR_ARD_ETH_UTIL)
+
+#Compiler/Linker flags
+CFLAGS_PLATFORM = -mmcu=atmega2560 -DF_CPU=16000000L -fno-exceptions -ffunction-sections -fdata-sections -MMD \
+                                       -DARDUINO=157 -DARDUINO_ARCH_AVR -DARDUINO_AVR_ADK -DWITH_ARDUINO -D__AVR__
+                                        
+#Compilers
+$(info ************ arduinodue file*****************)
+CCPLUS=$(ARDUINO_TOOLS_DIR)/avr-g++
+CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
+AR=$(ARDUINO_TOOLS_DIR)/avr-ar
+RANLIB=$(ARDUINO_TOOLS_DIR)/avr-ranlib
+
diff --git a/resource/csdk/connectivity/lib/arduino/local.properties b/resource/csdk/connectivity/lib/arduino/local.properties
new file mode 100644 (file)
index 0000000..e318153
--- /dev/null
@@ -0,0 +1,2 @@
+ARDUINO_DIR = /usr/share/arduino
+ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile b/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile
deleted file mode 100644 (file)
index 23475f8..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-# Makefile for libcoap
-#
-# Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
-#
-# This file is part of the CoAP library libcoap. Please see
-# README for terms of use. 
-
-# the library's version
-VERSION:=4.1.1
-
-# tools
-
-RANLIB=ranlib
-SHELL = /bin/sh
-MKDIR = mkdir
-ETAGS = /bin/false
-
-abs_builddir = /connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1
-top_builddir = .
-package = libcoap-4.1.1
-
-# files and flags
-SOURCES:= pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \
-        str.c option.c async.c subscribe.c block.c
-OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
-HEADERS:=coap.h config.h debug.h pdu.h net.h encode.h uri.h coap_list.h mem.h \
-       str.h option.h bits.h uthash.h utlist.h resource.h hashkey.h async.h \
-       subscribe.h block.h address.h prng.h coap_time.h t_list.h
-CFLAGS:=-Wall -Wextra -std=c99 -pedantic -g -O2
-CPPFLAGS:= -DWITH_POSIX
-DISTDIR=$(top_builddir)/$(package)
-SUBDIRS:=#examples #doc tests
-FILES:=ChangeLog README LICENSE.BSD LICENSE.GPL Makefile.in configure configure.in config.h.in $(SOURCES) $(HEADERS)
-LIB:=libcoap.a
-LDSOFLAGS=-shared
-LDFLAGS:=
-ARFLAGS:=cru
-examples:=examples
-doc:=doc
-
-
-ifdef BUILD_SO
-  MACHINE?=$(shell $(CC) -dumpmachine)
-  ifeq ($(findstring Darwin, $(MACHINE)), Darwin)
-    LDSOFLAGS=-dynamiclib
-    LIBSO=libcoap.dylib
-  endif
-  ifeq ($(findstring Windows, $(MACHINE)), Windows)
-    LIBSO=libcoap.dll
-  endif
-  # more platforms go here
-  ifndef LIBSO
-    LIBSO=libcoap.so
-  endif
-  ifndef PICFLAG
-    CFLAGS+=-fPIC
-  else
-    CFLAGS+=$(PICFLAG)
-  endif
-endif
-
-.PHONY: all dirs clean distclean .gitignore doc TAGS
-
-.SUFFIXES:
-.SUFFIXES:      .c .o
-
-all:   $(LIB) $(LIBSO) dirs
-
-check: 
-       echo DISTDIR: $(DISTDIR)
-       echo top_builddir: $(top_builddir)
-       $(MAKE) -C examples check
-
-dirs:  $(SUBDIRS)
-       for dir in $^; do \
-               $(MAKE) -C $$dir ; \
-       done
-
-$(LIB):        $(OBJECTS)
-       $(AR) $(ARFLAGS) $@ $^ 
-       $(RANLIB) $@
-
-$(LIBSO):      $(OBJECTS)
-       $(LD) $(LDSOFLAGS) $(LDFLAGS) -o $@ $^
-
-clean:
-       @rm -f $(PROGRAM) main.o $(LIB) $(LIBSO) $(OBJECTS)
-       for dir in $(SUBDIRS); do \
-               $(MAKE) -C $$dir clean ; \
-       done
-
-doc:   
-       $(MAKE) -C doc
-
-distclean:     clean
-       @rm -rf $(DISTDIR)
-       @rm -f *~ $(DISTDIR).tar.gz
-
-dist:  $(FILES) $(SUBDIRS)
-       test -d $(DISTDIR) || mkdir $(DISTDIR)
-       cp $(FILES) $(DISTDIR)
-       for dir in $(SUBDIRS); do \
-               $(MAKE) -C $$dir dist; \
-       done
-       tar czf $(package).tar.gz $(DISTDIR)
-
-TAGS:  
-       $(ETAGS) -o $@.new $(SOURCES) 
-       $(ETAGS) -a -o $@.new $(HEADERS) 
-       mv $@.new $@
-
-.gitignore:
-       echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript b/resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript
new file mode 100644 (file)
index 0000000..167613c
--- /dev/null
@@ -0,0 +1,71 @@
+##
+# libcoap (share library) build script
+##
+
+Import('env')
+
+libcoap_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+# As in the source code(C) includes arduino Time library head file(C++)
+# It requires compile the .c with g++
+if target_os == 'arduino':
+       libcoap_env.Replace(CFLAGS = env.get('CXXFLAGS'))
+
+######################################################################
+# Build flags
+######################################################################
+       libcoap_env.PrependUnique(CPPPATH = [
+               './',
+               env.get('ARDUINO_HOME')+'/',
+               env.get('ARDUINO_HOME')+'/hardware/arduino/avr/cores/arduino',
+               env.get('ARDUINO_HOME')+'/hardware/tools/avr/avr/include/',
+               env.get('ARDUINO_HOME')+'/hardware/arduino/avr/variants/mega',
+               env.get('ARDUINO_HOME')+'/libraries/Time/Time',
+               env.get('ARDUINO_HOME')+'/libraries/TimedAction',
+               env.get('ARDUINO_HOME')+'/hardware/arduino/avr/libraries/SPI',
+               env.get('ARDUINO_HOME')+'/libraries/Ethernet/src/utility',
+               ])
+
+if target_os not in ['arduino', 'windows', 'winrt']:
+       libcoap_env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_BSD_SOURCE'])
+       libcoap_env.AppendUnique(CFLAGS = ['-std=gnu99','-fPIC'])
+
+if target_os not in ['windows', 'winrt']:
+       libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
+                       '-fdata-sections', '-fno-exceptions'])
+
+if target_os == 'android':
+       libcoap_env.AppendUnique(LIBS = ['log'])
+
+if target_os == 'arduino':
+       libcoap_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
+
+if target_os in ['darwin', 'ios']:
+       libcoap_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+
+if env.get('LOGGING'):
+       libcoap_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Target(s)
+######################################################################
+libcoap_src = [
+       'pdu.c',
+       'net.c',
+       'debug.c',
+       'encode.c',
+       'uri.c',
+       'coap_list.c',
+       'resource.c',
+       'hashkey.c',
+       'str.c',
+       'option.c',
+       'async.c',
+       'subscribe.c',
+       'block.c'
+       ]
+
+libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
+
+libcoap_env.InstallTarget([libcoap], 'libcoap')
index 24ebce7..bb44a99 100644 (file)
@@ -3,10 +3,10 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
-/** 
+/**
  * @file address.h
  * @brief representation of network addresses
  */
 #include <sys/socket.h>
 #endif
 
+#ifdef WITH_ARDUINO
+#define DEV_ADDR_SIZE_MAX (16)
+#endif
+
 #ifdef WITH_LWIP
 #include <lwip/ip_addr.h>
 
@@ -117,29 +121,65 @@ _coap_is_mcast_impl(const coap_address_t *a)
 {
     if (!a)
     {
-        printf("[COAP] address - coap_address_t is false\n");
         return 0;
     }
     switch (a->addr.sa.sa_family)
     {
         case AF_INET:
-        printf("[COAP] address - local address : %s\n", a->addr.sin.sin_addr.s_addr);
         return IN_MULTICAST(a->addr.sin.sin_addr.s_addr);
         case AF_INET6:
         return IN6_IS_ADDR_MULTICAST(&a->addr.sin6.sin6_addr);
         default: /* fall through and signal error */
-        printf("[COAP] address - sa_family is default value\n");
         ;
     }
     return 0;
 }
 #endif /* WITH_POSIX */
 
-/** 
+#ifdef WITH_ARDUINO
+typedef struct coap_address_t
+{
+    uint32_t     size;                    /**< length of the address stored in addr field. */
+    uint8_t      addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
+} coap_address_t;
+
+static inline int
+_coap_address_equals_impl(const coap_address_t *a,
+                          const coap_address_t *b)
+{
+    uint32_t i;
+
+    if ((a == NULL) || (b == NULL))
+        return 0;
+
+    if (a->size != b->size)
+        return 0;
+
+    for (i = 0; i < a->size; i++)
+    {
+        if (a->addr[i] != b->addr[i])
+            return 0;
+    }
+    return 1;
+}
+
+static inline int
+_coap_is_mcast_impl(const coap_address_t *a)
+{
+    if (!a)
+        return 0;
+
+    /* TODO */
+    return 0;
+}
+
+#endif /* WITH_ARDUINO */
+
+/**
  * Resets the given coap_address_t object @p addr to its default
  * values.  In particular, the member size must be initialized to the
  * available size for storing addresses.
- * 
+ *
  * @param addr The coap_address_t object to initialize.
  */
 static inline void coap_address_init(coap_address_t *addr)
index 9f6c7b0..879cb38 100644 (file)
@@ -3,10 +3,10 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
-/** 
+/**
  * @file async.h
  * @brief state management for asynchronous messages
  */
@@ -32,7 +32,7 @@ typedef struct coap_async_state_t
 {
     unsigned char flags; /**< holds the flags to control behaviour */
 
-    /** 
+    /**
      * Holds the internal time when the object was registered with a
      * resource. This field will be updated whenever
      * coap_register_async() is called for a specific resource.
@@ -63,7 +63,7 @@ typedef struct coap_async_state_t
 /** release application data on destruction */
 #define COAP_ASYNC_RELEASE_DATA  0x08
 
-/** 
+/**
  * Allocates a new coap_async_state_t object and fills its fields
  * according to the given @p request. The @p flags are used to control
  * generation of empty ACK responses to stop retransmissions and to
@@ -72,7 +72,7 @@ typedef struct coap_async_state_t
  * coap_async_t object or @c NULL on error. Note that this function will
  * return @c NULL in case that an object with the same identifier is
  * already registered.
- * 
+ *
  * @param context  The context to use.
  * @param peer     The remote peer that is to be asynchronously notified.
  * @param request  The request that is handled asynchronously.
@@ -80,7 +80,7 @@ typedef struct coap_async_state_t
  * @param data     Opaque application data to register. Note that the
  *                 storage occupied by @p data is released on destruction
  *                 only if flag COAP_ASYNC_RELEASE_DATA is set.
- * 
+ *
  * @return A pointer to the registered coap_async_state_t object or
  * @c NULL in case of an error.
  */
@@ -88,52 +88,52 @@ coap_async_state_t *
 coap_register_async(coap_context_t *context, coap_address_t *peer, coap_pdu_t *request,
         unsigned char flags, void *data);
 
-/** 
+/**
  * Removes the state object identified by @p id from @p context. The
  * removed object is returned in @p s, if found. Otherwise, @p s is
  * undefined. This function returns @c 1 if the object was removed, @c
  * 0 otherwise. Note that the storage allocated for the stored object
  * is not released by this functions. You will have to call
  * coap_free_async() to do so.
- * 
+ *
  * @param context The context where the async object is registered.
  * @param id      The identifier of the asynchronous transaction.
- * @param s       Will be set to the object identified by @p id 
+ * @param s       Will be set to the object identified by @p id
  * after removal.
- * 
+ *
  * @return @c 1 if object was removed and @p s updated, or @c 0 if no
  * object was found with the given id. @p s is valid only if the
  * return value is @c 1.
  */
 int coap_remove_async(coap_context_t *context, coap_tid_t id, coap_async_state_t **s);
 
-/** 
+/**
  * Releases the memory that was allocated by coap_async_state_init()
  * for the object @p s. The registered application data will be
  * released automatically if COAP_ASYNC_RELEASE_DATA is set.
- * 
+ *
  * @param s The object to delete.
  */
 void
 coap_free_async(coap_async_state_t *state);
 
-/** 
+/**
  * Retrieves the object identified by @p id from the list of asynchronous
  * transactions that are registered with @p context. This function returns
  * a pointer to that object or @c NULL if not found.
- * 
- * @param context The context where the asynchronous objects are 
+ *
+ * @param context The context where the asynchronous objects are
  * registered with.
  * @param id      The id of the object to retrieve.
- * 
+ *
  * @return A pointer to the object identified by @p id or @c NULL if
  * not found.
  */
 coap_async_state_t *coap_find_async(coap_context_t *context, coap_tid_t id);
 
-/** 
+/**
  * Updates the time stamp of @p s.
- * 
+ *
  * @param s The state object to update.
  */
 static inline void coap_touch_async(coap_async_state_t *s)
index 487af39..20281a0 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 /**
 #ifndef _BITS_H_
 #define _BITS_H_
 
+#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
+#endif
 #include <stdint.h>
 
-/** 
+/**
  * Sets the bit @p bit in bit-vector @p vec. This function returns @c
  * 1 if bit was set or @c -1 on error (i.e. when the given bit does
  * not fit in the vector).
- * 
+ *
  * @param vec  The bit-vector to change.
  * @param size The size of @p vec in bytes.
  * @param bit  The bit to set in @p vec.
- * 
+ *
  * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
  */
 inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
@@ -38,15 +40,15 @@ inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
     return 1;
 }
 
-/** 
+/**
  * Clears the bit @p bit from bit-vector @p vec. This function returns
  * @c 1 if bit was cleared or @c -1 on error (i.e. when the given bit
  * does not fit in the vector).
- * 
+ *
  * @param vec  The bit-vector to change.
  * @param size The size of @p vec in bytes.
  * @param bit  The bit to clear from @p vec.
- * 
+ *
  * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
  */
 inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
@@ -58,14 +60,14 @@ inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
     return 1;
 }
 
-/** 
+/**
  * Gets the status of bit @p bit from bit-vector @p vec. This function returns
  * @c 1 if the bit is set, @c 0 otherwise (even in case of an error)..
- * 
+ *
  * @param vec  The bit-vector to read from..
  * @param size The size of @p vec in bytes.
  * @param bit  The bit to get from @p vec.
- * 
+ *
  * @return @c 1 if the bit is set, @c 0 otherwise.
  */
 inline static int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
index 3ad47e3..c0373f7 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
 # include <assert.h>
 #endif
 
+#ifdef WITH_ARDUINO
+/* On Arduino the abort function, needed for assert, is defined in std lib */
+#include <stdlib.h>
+#endif
+
 #include "debug.h"
 #include "block.h"
 
index 6451383..2d5ef07 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2012,2014 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_BLOCK_H_
 #endif
 
 /**
- * Structure of Block options. 
+ * Structure of Block options.
  */
 typedef struct
 {
-    unsigned int num :20; /**< block number */
-    unsigned int m :1; /**< 1 if more blocks follow, 0 otherwise */
-    unsigned int szx :3; /**< block size */
+#ifdef WITH_ARDUINO
+    unsigned long int num : 20;
+#else
+    unsigned int num : 20;
+#endif
+    unsigned int m : 1; /**< 1 if more blocks follow, 0 otherwise */
+    unsigned int szx : 3; /**< block size */
 } coap_block_t;
 
 /**
- * Returns the value of the least significant byte of a Block option @p opt. 
+ * Returns the value of the least significant byte of a Block option @p opt.
  * For zero-length options (i.e. num == m == szx == 0), COAP_OPT_BLOCK_LAST
  * returns @c NULL.
  */
@@ -88,7 +92,7 @@ static inline void coap_opt_block_set_m(coap_opt_t *block_opt, int m)
  * value @c 1. Otherwise, @c 0 is returned.
  *
  * @param pdu   The pdu to search for option @p type.
- * @param type  The option to search for (must be COAP_OPTION_BLOCK1 or 
+ * @param type  The option to search for (must be COAP_OPTION_BLOCK1 or
  *              COAP_OPTION_BLOCK2)
  * @param block The block structure to initilize.
  * @return @c 1 on success, @c 0 otherwise.
@@ -102,9 +106,9 @@ int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block);
  * space is required. The actual length of the resource is specified
  * in @p data_length.
  *
- * This function may change *block to reflect the values written to 
+ * This function may change *block to reflect the values written to
  * @p pdu. As the function takes into consideration the remaining space
- * @p pdu, no more options should be added after coap_write_block_opt() 
+ * @p pdu, no more options should be added after coap_write_block_opt()
  * has returned.
  *
  * @param block      The block structure to use. On return, this object
@@ -120,7 +124,7 @@ int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block);
 int coap_write_block_opt(coap_block_t *block, unsigned short type, coap_pdu_t *pdu,
         size_t data_length);
 
-/** 
+/**
  * Adds the @p block_num block of size 1 << (@p block_szx + 4) from
  * source @p data to @p pdu.
  *
index ba31c54..73f1595 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
@@ -75,7 +75,7 @@ void coap_delete_list(coap_list_t *queue)
 coap_list_t *
 coap_new_listnode(void *data, void (*delete_func)(void *))
 {
-    coap_list_t *node = coap_malloc( sizeof(coap_list_t) );
+    coap_list_t *node = (coap_list_t *) coap_malloc( sizeof(coap_list_t) );
     if (!node)
     {
 #ifndef NDEBUG
index 0c1334b..22d8fba 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_LIST_H_
index 041d9a8..76dcd9d 100644 (file)
@@ -3,10 +3,10 @@
  * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
-/** 
+/**
  * @file coap_time.h
  * @brief Clock Handling
  */
@@ -106,20 +106,52 @@ extern "C"
     extern time_t clock_offset;
 #endif /* WITH_POSIX */
 
+#ifdef WITH_ARDUINO
+#include "Time.h"
+#ifdef ARDUINO_ARCH_SAM
+#include <sys/types.h>  // time_t is defined in sys/types.h for ARM compiler
+#else
+typedef unsigned long time_t; //AVR compiler doesnt define time_t
+#endif
+typedef time_t coap_tick_t;
+
+/**
+ * This data type is used to represent the difference between two
+ * clock_tick_t values. This data type must have the same size in
+ * memory as coap_tick_t to allow wrapping.
+ */
+typedef int coap_tick_diff_t;
+
+/* TODO: Ticks per second value for Arduino needs verification from
+ * documentation */
+#define COAP_TICKS_PER_SECOND 1000
+
+extern time_t clock_offset;
+
+#endif /* WITH_ARDUINO */
+
 #ifndef coap_clock_init
     static inline void coap_clock_init_impl(void)
     {
 #ifdef HAVE_TIME_H
         clock_offset = time(NULL);
 #else
-#  ifdef __GNUC__
-        /* Issue a warning when using gcc. Other prepropressors do 
-         *  not seem to have a similar feature. */
-#   warning "cannot initialize clock"
-#  endif
-        clock_offset = 0;
+#  ifdef WITH_ARDUINO
+#ifdef __AVR__
+    clock_offset = 1; //now();
+#else
+    clock_offset = now();
 #endif
-    }
+#  else
+#    ifdef __GNUC__
+    /* Issue a warning when using gcc. Other prepropressors do
+     *  not seem to have a similar feature. */
+#     warning "cannot initialize clock"
+#    endif
+    clock_offset = 0;
+#  endif /* WITH_ARDUINO */
+#endif /* HAVE_TIME */
+}
 #define coap_clock_init coap_clock_init_impl
 #endif /* coap_clock_init */
 
@@ -132,9 +164,19 @@ extern "C"
         *t = (tv.tv_sec - clock_offset) * COAP_TICKS_PER_SECOND
                 + (tv.tv_usec * COAP_TICKS_PER_SECOND / 1000000);
 #else
-#error "clock not implemented"
+#  ifdef WITH_ARDUINO
+    coap_tick_t tv;
+#ifdef __AVR__
+    tv = 1; //now();
+#else
+    tv = now();
 #endif
-    }
+    *t = (tv - clock_offset) * COAP_TICKS_PER_SECOND;
+#  else
+#    error "clock not implemented"
+#  endif /* WITH_ARDUINO */
+#endif /* HAVE_SYS_TIME_H */
+}
 #define coap_ticks coap_ticks_impl
 #endif /* coap_ticks */
 
index 654c4ea..6d2beb6 100644 (file)
@@ -5,7 +5,9 @@
 /* #undef AC_APPLE_UNIVERSAL_BUILD */
 
 /* Define to 1 if you have the <arpa/inet.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_ARPA_INET_H 1
+#endif
 
 /* Define to 1 if you have the <assert.h> header file. */
 #define HAVE_ASSERT_H 1
@@ -36,7 +38,9 @@
 #define HAVE_NETDB_H 1
 
 /* Define to 1 if you have the <netinet/in.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_NETINET_IN_H 1
+#endif
 
 /* Define to 1 if you have the `select' function. */
 #define HAVE_SELECT 1
 #define HAVE_STRRCHR 1
 
 /* Define to 1 if you have the <syslog.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYSLOG_H 1
+#endif
 
 /* Define to 1 if you have the <sys/socket.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_SOCKET_H 1
+#endif
 
 /* Define to 1 if you have the <sys/stat.h> header file. */
 #define HAVE_SYS_STAT_H 1
 
 /* Define to 1 if you have the <sys/time.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_TIME_H 1
+#endif
 
 /* Define to 1 if you have the <sys/types.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_TYPES_H 1
+#endif
 
 /* Define to 1 if you have the <sys/unistd.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_UNISTD_H 1
+#endif
 
 /* Define to 1 if you have the <time.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_TIME_H 1
+#endif
 
 /* Define to 1 if you have the <unistd.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_UNISTD_H 1
+#endif
 
 /* Define to the address where bug reports for this package should be sent. */
 #define PACKAGE_BUGREPORT ""
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/config.status b/resource/csdk/connectivity/lib/libcoap-4.1.1/config.status
deleted file mode 100644 (file)
index 4984732..0000000
+++ /dev/null
@@ -1,1020 +0,0 @@
-#! /bin/bash
-# Generated by configure.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-
-SHELL=${CONFIG_SHELL-/bin/bash}
-export SHELL
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-       expr "X$arg" : "X\\(.*\\)$as_nl";
-       arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
-      PATH_SEPARATOR=';'
-  }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""       $as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-  done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
-  as_status=$1; test $as_status -eq 0 && as_status=1
-  if test "$4"; then
-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
-  fi
-  $as_echo "$as_me: error: $2" >&2
-  as_fn_exit $as_status
-} # as_fn_error
-
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
-  return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
-  set +e
-  as_fn_set_status $1
-  exit $1
-} # as_fn_exit
-
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
-  { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
-  eval 'as_fn_append ()
-  {
-    eval $1+=\$2
-  }'
-else
-  as_fn_append ()
-  {
-    eval $1=\$$1\$2
-  }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
-  eval 'as_fn_arith ()
-  {
-    as_val=$(( $* ))
-  }'
-else
-  as_fn_arith ()
-  {
-    as_val=`expr "$@" || test $? -eq 1`
-  }
-fi # as_fn_arith
-
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-        X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
-  case `echo 'xy\c'` in
-  *c*) ECHO_T='        ';;     # ECHO_T is single tab character.
-  xy)  ECHO_C='\c';;
-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
-       ECHO_T='        ';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
-  if ln -s conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s='ln -s'
-    # ... but there are two gotchas:
-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -pR'.
-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -pR'
-  elif ln conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s=ln
-  else
-    as_ln_s='cp -pR'
-  fi
-else
-  as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || eval $as_mkdir_p || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_dir" : 'X\(//\)[^/]' \| \
-        X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p='mkdir -p "$as_dir"'
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
-  test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-## ----------------------------------- ##
-## Main body of $CONFIG_STATUS script. ##
-## ----------------------------------- ##
-# Save the log message, to keep $0 and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by libcoap $as_me 4.1.1, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
-
-  CONFIG_FILES    = $CONFIG_FILES
-  CONFIG_HEADERS  = $CONFIG_HEADERS
-  CONFIG_LINKS    = $CONFIG_LINKS
-  CONFIG_COMMANDS = $CONFIG_COMMANDS
-  $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-# Files that config.status was made for.
-config_files=" Makefile doc/Makefile doc/Doxyfile examples/Makefile tests/Makefile"
-config_headers=" config.h"
-
-ac_cs_usage="\
-\`$as_me' instantiates files and other configuration actions
-from templates according to the current configuration.  Unless the files
-and actions are specified as TAGs, all are instantiated by default.
-
-Usage: $0 [OPTION]... [TAG]...
-
-  -h, --help       print this help, then exit
-  -V, --version    print version number and configuration settings, then exit
-      --config     print configuration, then exit
-  -q, --quiet, --silent
-                   do not print progress messages
-  -d, --debug      don't remove temporary files
-      --recheck    update $as_me by reconfiguring in the same conditions
-      --file=FILE[:TEMPLATE]
-                   instantiate the configuration file FILE
-      --header=FILE[:TEMPLATE]
-                   instantiate the configuration header FILE
-
-Configuration files:
-$config_files
-
-Configuration headers:
-$config_headers
-
-Report bugs to the package provider."
-
-ac_cs_config=""
-ac_cs_version="\
-libcoap config.status 4.1.1
-configured by ./configure, generated by GNU Autoconf 2.69,
-  with options \"$ac_cs_config\"
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='/connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1'
-srcdir='.'
-test -n "$AWK" || AWK=awk
-# The default lists apply if the user does not specify any file.
-ac_need_defaults=:
-while test $# != 0
-do
-  case $1 in
-  --*=?*)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
-    ac_shift=:
-    ;;
-  --*=)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=
-    ac_shift=:
-    ;;
-  *)
-    ac_option=$1
-    ac_optarg=$2
-    ac_shift=shift
-    ;;
-  esac
-
-  case $ac_option in
-  # Handling of the options.
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    ac_cs_recheck=: ;;
-  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    $as_echo "$ac_cs_version"; exit ;;
-  --config | --confi | --conf | --con | --co | --c )
-    $as_echo "$ac_cs_config"; exit ;;
-  --debug | --debu | --deb | --de | --d | -d )
-    debug=: ;;
-  --file | --fil | --fi | --f )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    '') as_fn_error $? "missing file argument" ;;
-    esac
-    as_fn_append CONFIG_FILES " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --header | --heade | --head | --hea )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --he | --h)
-    # Conflict between --help and --header
-    as_fn_error $? "ambiguous option: \`$1'
-Try \`$0 --help' for more information.";;
-  --help | --hel | -h )
-    $as_echo "$ac_cs_usage"; exit ;;
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil | --si | --s)
-    ac_cs_silent=: ;;
-
-  # This is an error.
-  -*) as_fn_error $? "unrecognized option: \`$1'
-Try \`$0 --help' for more information." ;;
-
-  *) as_fn_append ac_config_targets " $1"
-     ac_need_defaults=false ;;
-
-  esac
-  shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
-  exec 6>/dev/null
-  ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-if $ac_cs_recheck; then
-  set X /bin/bash './configure'  $ac_configure_extra_args --no-create --no-recursion
-  shift
-  $as_echo "running CONFIG_SHELL=/bin/bash $*" >&6
-  CONFIG_SHELL='/bin/bash'
-  export CONFIG_SHELL
-  exec "$@"
-fi
-
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-  $as_echo "$ac_log"
-} >&5
-
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
-  case $ac_config_target in
-    "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
-    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-    "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;;
-    "doc/Doxyfile") CONFIG_FILES="$CONFIG_FILES doc/Doxyfile" ;;
-    "examples/Makefile") CONFIG_FILES="$CONFIG_FILES examples/Makefile" ;;
-    "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;;
-
-  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
-  esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used.  Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
-fi
-
-# Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
-  tmp= ac_tmp=
-  trap 'exit_status=$?
-  : "${ac_tmp:=$tmp}"
-  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
-' 0
-  trap 'as_fn_exit 1' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
-  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
-  test -d "$tmp"
-}  ||
-{
-  tmp=./conf$$-$RANDOM
-  (umask 077 && mkdir "$tmp")
-} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
-ac_tmp=$tmp
-
-# Set up the scripts for CONFIG_FILES section.
-# No need to generate them if there are no CONFIG_FILES.
-# This happens for instance with `./config.status config.h'.
-if test -n "$CONFIG_FILES"; then
-
-
-ac_cr=`echo X | tr X '\015'`
-# On cygwin, bash can eat \r inside `` if the user requested igncr.
-# But we know of no other shell where ac_cr would be empty at this
-# point, so we can use a bashism as a fallback.
-if test "x$ac_cr" = x; then
-  eval ac_cr=\$\'\\r\'
-fi
-ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
-if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
-  ac_cs_awk_cr='\\r'
-else
-  ac_cs_awk_cr=$ac_cr
-fi
-
-echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
-cat >>"$ac_tmp/subs1.awk" <<\_ACAWK &&
-S["LTLIBOBJS"]=""
-S["BUILD_SO"]=""
-S["TESTS"]=""
-S["LIBOBJS"]=""
-S["EGREP"]="/bin/grep -E"
-S["GREP"]="/bin/grep"
-S["CPP"]="gcc -E"
-S["ETAGS"]="/bin/false"
-S["DOXYGEN"]=":"
-S["RANLIB"]="ranlib"
-S["OBJEXT"]="o"
-S["EXEEXT"]=""
-S["ac_ct_CC"]="gcc"
-S["CPPFLAGS"]=" -DWITH_POSIX"
-S["LDFLAGS"]=""
-S["CFLAGS"]="-g -O2"
-S["CC"]="gcc"
-S["SET_MAKE"]=""
-S["target_alias"]=""
-S["host_alias"]=""
-S["build_alias"]=""
-S["LIBS"]=""
-S["ECHO_T"]=""
-S["ECHO_N"]="-n"
-S["ECHO_C"]=""
-S["DEFS"]="-DHAVE_CONFIG_H"
-S["mandir"]="${datarootdir}/man"
-S["localedir"]="${datarootdir}/locale"
-S["libdir"]="${exec_prefix}/lib"
-S["psdir"]="${docdir}"
-S["pdfdir"]="${docdir}"
-S["dvidir"]="${docdir}"
-S["htmldir"]="${docdir}"
-S["infodir"]="${datarootdir}/info"
-S["docdir"]="${datarootdir}/doc/${PACKAGE_TARNAME}"
-S["oldincludedir"]="/usr/include"
-S["includedir"]="${prefix}/include"
-S["localstatedir"]="${prefix}/var"
-S["sharedstatedir"]="${prefix}/com"
-S["sysconfdir"]="${prefix}/etc"
-S["datadir"]="${datarootdir}"
-S["datarootdir"]="${prefix}/share"
-S["libexecdir"]="${exec_prefix}/libexec"
-S["sbindir"]="${exec_prefix}/sbin"
-S["bindir"]="${exec_prefix}/bin"
-S["program_transform_name"]="s,x,x,"
-S["prefix"]="/usr/local"
-S["exec_prefix"]="${prefix}"
-S["PACKAGE_URL"]=""
-S["PACKAGE_BUGREPORT"]=""
-S["PACKAGE_STRING"]="libcoap 4.1.1"
-S["PACKAGE_VERSION"]="4.1.1"
-S["PACKAGE_TARNAME"]="libcoap"
-S["PACKAGE_NAME"]="libcoap"
-S["PATH_SEPARATOR"]=":"
-S["SHELL"]="/bin/bash"
-_ACAWK
-cat >>"$ac_tmp/subs1.awk" <<_ACAWK &&
-  for (key in S) S_is_set[key] = 1
-  FS = "\a"
-
-}
-{
-  line = $ 0
-  nfields = split(line, field, "@")
-  substed = 0
-  len = length(field[1])
-  for (i = 2; i < nfields; i++) {
-    key = field[i]
-    keylen = length(key)
-    if (S_is_set[key]) {
-      value = S[key]
-      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
-      len += length(value) + length(field[++i])
-      substed = 1
-    } else
-      len += 1 + keylen
-  }
-
-  print line
-}
-
-_ACAWK
-if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
-  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
-else
-  cat
-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
-  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
-fi # test -n "$CONFIG_FILES"
-
-# Set up the scripts for CONFIG_HEADERS section.
-# No need to generate them if there are no CONFIG_HEADERS.
-# This happens for instance with `./config.status Makefile'.
-if test -n "$CONFIG_HEADERS"; then
-cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
-BEGIN {
-D["PACKAGE_NAME"]=" \"libcoap\""
-D["PACKAGE_TARNAME"]=" \"libcoap\""
-D["PACKAGE_VERSION"]=" \"4.1.1\""
-D["PACKAGE_STRING"]=" \"libcoap 4.1.1\""
-D["PACKAGE_BUGREPORT"]=" \"\""
-D["PACKAGE_URL"]=" \"\""
-D["STDC_HEADERS"]=" 1"
-D["HAVE_SYS_TYPES_H"]=" 1"
-D["HAVE_SYS_STAT_H"]=" 1"
-D["HAVE_STDLIB_H"]=" 1"
-D["HAVE_STRING_H"]=" 1"
-D["HAVE_MEMORY_H"]=" 1"
-D["HAVE_STRINGS_H"]=" 1"
-D["HAVE_INTTYPES_H"]=" 1"
-D["HAVE_STDINT_H"]=" 1"
-D["HAVE_UNISTD_H"]=" 1"
-D["HAVE_ASSERT_H"]=" 1"
-D["HAVE_ARPA_INET_H"]=" 1"
-D["HAVE_LIMITS_H"]=" 1"
-D["HAVE_NETDB_H"]=" 1"
-D["HAVE_NETINET_IN_H"]=" 1"
-D["HAVE_STDLIB_H"]=" 1"
-D["HAVE_STRING_H"]=" 1"
-D["HAVE_STRINGS_H"]=" 1"
-D["HAVE_SYS_SOCKET_H"]=" 1"
-D["HAVE_SYS_TIME_H"]=" 1"
-D["HAVE_TIME_H"]=" 1"
-D["HAVE_UNISTD_H"]=" 1"
-D["HAVE_SYS_UNISTD_H"]=" 1"
-D["HAVE_SYSLOG_H"]=" 1"
-D["HAVE_STDLIB_H"]=" 1"
-D["HAVE_MALLOC"]=" 1"
-D["HAVE_MEMSET"]=" 1"
-D["HAVE_SELECT"]=" 1"
-D["HAVE_SOCKET"]=" 1"
-D["HAVE_STRCASECMP"]=" 1"
-D["HAVE_STRRCHR"]=" 1"
-D["HAVE_GETADDRINFO"]=" 1"
-D["HAVE_STRNLEN"]=" 1"
-  for (key in D) D_is_set[key] = 1
-  FS = "\a"
-}
-/^[\t ]*#[\t ]*(define|undef)[\t ]+[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*([\t (]|$)/ {
-  line = $ 0
-  split(line, arg, " ")
-  if (arg[1] == "#") {
-    defundef = arg[2]
-    mac1 = arg[3]
-  } else {
-    defundef = substr(arg[1], 2)
-    mac1 = arg[2]
-  }
-  split(mac1, mac2, "(") #)
-  macro = mac2[1]
-  prefix = substr(line, 1, index(line, defundef) - 1)
-  if (D_is_set[macro]) {
-    # Preserve the white space surrounding the "#".
-    print prefix "define", macro P[macro] D[macro]
-    next
-  } else {
-    # Replace #undef with comments.  This is necessary, for example,
-    # in the case of _POSIX_SOURCE, which is predefined and required
-    # on some systems where configure will not decide to define it.
-    if (defundef == "undef") {
-      print "/*", prefix defundef, macro, "*/"
-      next
-    }
-  }
-}
-{ print }
-_ACAWK
-  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
-fi # test -n "$CONFIG_HEADERS"
-
-
-eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "
-shift
-for ac_tag
-do
-  case $ac_tag in
-  :[FHLC]) ac_mode=$ac_tag; continue;;
-  esac
-  case $ac_mode$ac_tag in
-  :[FHL]*:*);;
-  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
-  :[FH]-) ac_tag=-:-;;
-  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
-  esac
-  ac_save_IFS=$IFS
-  IFS=:
-  set x $ac_tag
-  IFS=$ac_save_IFS
-  shift
-  ac_file=$1
-  shift
-
-  case $ac_mode in
-  :L) ac_source=$1;;
-  :[FH])
-    ac_file_inputs=
-    for ac_f
-    do
-      case $ac_f in
-      -) ac_f="$ac_tmp/stdin";;
-      *) # Look for the file first in the build tree, then in the source tree
-        # (if the path is not absolute).  The absolute path cannot be DOS-style,
-        # because $ac_f cannot contain `:'.
-        test -f "$ac_f" ||
-          case $ac_f in
-          [\\/$]*) false;;
-          *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
-          esac ||
-          as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
-      esac
-      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
-      as_fn_append ac_file_inputs " '$ac_f'"
-    done
-
-    # Let's still pretend it is `configure' which instantiates (i.e., don't
-    # use $as_me), people would be surprised to read:
-    #    /* config.h.  Generated by config.status.  */
-    configure_input='Generated from '`
-         $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
-       `' by configure.'
-    if test x"$ac_file" != x-; then
-      configure_input="$ac_file.  $configure_input"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
-$as_echo "$as_me: creating $ac_file" >&6;}
-    fi
-    # Neutralize special characters interpreted by sed in replacement strings.
-    case $configure_input in #(
-    *\&* | *\|* | *\\* )
-       ac_sed_conf_input=`$as_echo "$configure_input" |
-       sed 's/[\\\\&|]/\\\\&/g'`;; #(
-    *) ac_sed_conf_input=$configure_input;;
-    esac
-
-    case $ac_tag in
-    *:-:* | *:-) cat >"$ac_tmp/stdin" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
-    esac
-    ;;
-  esac
-
-  ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$ac_file" : 'X\(//\)[^/]' \| \
-        X"$ac_file" : 'X\(//\)$' \| \
-        X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-  as_dir="$ac_dir"; as_fn_mkdir_p
-  ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
-  case $ac_mode in
-  :F)
-  #
-  # CONFIG_FILE
-  #
-
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-ac_sed_dataroot='
-/datarootdir/ {
-  p
-  q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p'
-case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-  ac_datarootdir_hack='
-  s&@datadir@&${datarootdir}&g
-  s&@docdir@&${datarootdir}/doc/${PACKAGE_TARNAME}&g
-  s&@infodir@&${datarootdir}/info&g
-  s&@localedir@&${datarootdir}/locale&g
-  s&@mandir@&${datarootdir}/man&g
-  s&\${datarootdir}&${prefix}/share&g' ;;
-esac
-ac_sed_extra="/^[       ]*VPATH[        ]*=[    ]*/{
-h
-s///
-s/^/:/
-s/[     ]*$/:/
-s/:\$(srcdir):/:/g
-s/:\${srcdir}:/:/g
-s/:@srcdir@:/:/g
-s/^:*//
-s/:*$//
-x
-s/\(=[  ]*\).*/\1/
-G
-s/\n//
-s/^[^=]*=[      ]*$//
-}
-
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s|@configure_input@|$ac_sed_conf_input|;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@top_build_prefix@&$ac_top_build_prefix&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-$ac_datarootdir_hack
-"
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
-  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
-  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
-  { ac_out=`sed -n '/^[         ]*datarootdir[  ]*:*=/p' \
-      "$ac_tmp/out"`; test -z "$ac_out"; } &&
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&5
-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&2;}
-
-  rm -f "$ac_tmp/stdin"
-  case $ac_file in
-  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
-  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
-  esac \
-  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- ;;
-  :H)
-  #
-  # CONFIG_HEADER
-  #
-  if test x"$ac_file" != x-; then
-    {
-      $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
-    } >"$ac_tmp/config.h" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
-$as_echo "$as_me: $ac_file is unchanged" >&6;}
-    else
-      rm -f "$ac_file"
-      mv "$ac_tmp/config.h" "$ac_file" \
-       || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    fi
-  else
-    $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
-      || as_fn_error $? "could not create -" "$LINENO" 5
-  fi
- ;;
-
-
-  esac
-
-done # for ac_tag
-
-
-as_fn_exit 0
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/configure b/resource/csdk/connectivity/lib/libcoap-4.1.1/configure
deleted file mode 100644 (file)
index b6f5dad..0000000
+++ /dev/null
@@ -1,5411 +0,0 @@
-#! /bin/sh
-# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for libcoap 4.1.1.
-#
-#
-# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
-#
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-       expr "X$arg" : "X\\(.*\\)$as_nl";
-       arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
-      PATH_SEPARATOR=';'
-  }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""       $as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-  done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-# Use a proper internal environment variable to ensure we don't fall
-  # into an infinite loop, continuously re-executing ourselves.
-  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
-    _as_can_reexec=no; export _as_can_reexec;
-    # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
-  *v*x* | *x*v* ) as_opts=-vx ;;
-  *v* ) as_opts=-v ;;
-  *x* ) as_opts=-x ;;
-  * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-as_fn_exit 255
-  fi
-  # We don't want this to propagate to other subprocesses.
-          { _as_can_reexec=; unset _as_can_reexec;}
-if test "x$CONFIG_SHELL" = x; then
-  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '\${1+\"\$@\"}'='\"\$@\"'
-  setopt NO_GLOB_SUBST
-else
-  case \`(set -o) 2>/dev/null\` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-"
-  as_required="as_fn_return () { (exit \$1); }
-as_fn_success () { as_fn_return 0; }
-as_fn_failure () { as_fn_return 1; }
-as_fn_ret_success () { return 0; }
-as_fn_ret_failure () { return 1; }
-
-exitcode=0
-as_fn_success || { exitcode=1; echo as_fn_success failed.; }
-as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
-as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
-as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
-if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
-
-else
-  exitcode=1; echo positional parameters were not saved.
-fi
-test x\$exitcode = x0 || exit 1
-test -x / || exit 1"
-  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
-  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
-  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
-  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
-test \$(( 1 + 1 )) = 2 || exit 1"
-  if (eval "$as_required") 2>/dev/null; then :
-  as_have_required=yes
-else
-  as_have_required=no
-fi
-  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
-
-else
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-as_found=false
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  as_found=:
-  case $as_dir in #(
-        /*)
-          for as_base in sh bash ksh sh5; do
-            # Try only shells that exist, to save several forks.
-            as_shell=$as_dir/$as_base
-            if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
-                   { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
-  CONFIG_SHELL=$as_shell as_have_required=yes
-                  if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
-  break 2
-fi
-fi
-          done;;
-       esac
-  as_found=false
-done
-$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
-             { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
-  CONFIG_SHELL=$SHELL as_have_required=yes
-fi; }
-IFS=$as_save_IFS
-
-
-      if test "x$CONFIG_SHELL" != x; then :
-  export CONFIG_SHELL
-             # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
-  *v*x* | *x*v* ) as_opts=-vx ;;
-  *v* ) as_opts=-v ;;
-  *x* ) as_opts=-x ;;
-  * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-exit 255
-fi
-
-    if test x$as_have_required = xno; then :
-  $as_echo "$0: This script requires a shell more modern than all"
-  $as_echo "$0: the shells that I found on your system."
-  if test x${ZSH_VERSION+set} = xset ; then
-    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
-    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
-  else
-    $as_echo "$0: Please tell bug-autoconf@gnu.org about your system,
-$0: including any error possibly output before this
-$0: message. Then install a modern shell, or manually run
-$0: the script under such a shell if you do have one."
-  fi
-  exit 1
-fi
-fi
-fi
-SHELL=${CONFIG_SHELL-/bin/sh}
-export SHELL
-# Unset more variables known to interfere with behavior of common tools.
-CLICOLOR_FORCE= GREP_OPTIONS=
-unset CLICOLOR_FORCE GREP_OPTIONS
-
-## --------------------- ##
-## M4sh Shell Functions. ##
-## --------------------- ##
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
-  { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
-  return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
-  set +e
-  as_fn_set_status $1
-  exit $1
-} # as_fn_exit
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || eval $as_mkdir_p || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_dir" : 'X\(//\)[^/]' \| \
-        X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
-  test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
-  eval 'as_fn_append ()
-  {
-    eval $1+=\$2
-  }'
-else
-  as_fn_append ()
-  {
-    eval $1=\$$1\$2
-  }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
-  eval 'as_fn_arith ()
-  {
-    as_val=$(( $* ))
-  }'
-else
-  as_fn_arith ()
-  {
-    as_val=`expr "$@" || test $? -eq 1`
-  }
-fi # as_fn_arith
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
-  as_status=$1; test $as_status -eq 0 && as_status=1
-  if test "$4"; then
-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
-  fi
-  $as_echo "$as_me: error: $2" >&2
-  as_fn_exit $as_status
-} # as_fn_error
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-        X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-
-  as_lineno_1=$LINENO as_lineno_1a=$LINENO
-  as_lineno_2=$LINENO as_lineno_2a=$LINENO
-  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
-  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
-  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=
-  ' <$as_myself |
-    sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
-      N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
-      t loop
-      s/-\n.*//
-    ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
-    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
-
-  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
-  # already done that, so ensure we don't try to do so again and fall
-  # in an infinite loop.  This has already happened in practice.
-  _as_can_reexec=no; export _as_can_reexec
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensitive to this).
-  . "./$as_me.lineno"
-  # Exit status is that of the last command.
-  exit
-}
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
-  case `echo 'xy\c'` in
-  *c*) ECHO_T='        ';;     # ECHO_T is single tab character.
-  xy)  ECHO_C='\c';;
-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
-       ECHO_T='        ';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
-  if ln -s conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s='ln -s'
-    # ... but there are two gotchas:
-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -pR'.
-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -pR'
-  elif ln conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s=ln
-  else
-    as_ln_s='cp -pR'
-  fi
-else
-  as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p='mkdir -p "$as_dir"'
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-test -n "$DJDIR" || exec 7<&0 </dev/null
-exec 6>&1
-
-# Name of the host.
-# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
-# so uname gets run too.
-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
-
-#
-# Initializations.
-#
-ac_default_prefix=/usr/local
-ac_clean_files=
-ac_config_libobj_dir=.
-LIBOBJS=
-cross_compiling=no
-subdirs=
-MFLAGS=
-MAKEFLAGS=
-
-# Identity of this package.
-PACKAGE_NAME='libcoap'
-PACKAGE_TARNAME='libcoap'
-PACKAGE_VERSION='4.1.1'
-PACKAGE_STRING='libcoap 4.1.1'
-PACKAGE_BUGREPORT=''
-PACKAGE_URL=''
-
-ac_unique_file="coap.h"
-# Factoring default headers for most tests.
-ac_includes_default="\
-#include <stdio.h>
-#ifdef HAVE_SYS_TYPES_H
-# include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_STAT_H
-# include <sys/stat.h>
-#endif
-#ifdef STDC_HEADERS
-# include <stdlib.h>
-# include <stddef.h>
-#else
-# ifdef HAVE_STDLIB_H
-#  include <stdlib.h>
-# endif
-#endif
-#ifdef HAVE_STRING_H
-# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
-#  include <memory.h>
-# endif
-# include <string.h>
-#endif
-#ifdef HAVE_STRINGS_H
-# include <strings.h>
-#endif
-#ifdef HAVE_INTTYPES_H
-# include <inttypes.h>
-#endif
-#ifdef HAVE_STDINT_H
-# include <stdint.h>
-#endif
-#ifdef HAVE_UNISTD_H
-# include <unistd.h>
-#endif"
-
-ac_subst_vars='LTLIBOBJS
-BUILD_SO
-TESTS
-LIBOBJS
-EGREP
-GREP
-CPP
-ETAGS
-DOXYGEN
-RANLIB
-OBJEXT
-EXEEXT
-ac_ct_CC
-CPPFLAGS
-LDFLAGS
-CFLAGS
-CC
-SET_MAKE
-target_alias
-host_alias
-build_alias
-LIBS
-ECHO_T
-ECHO_N
-ECHO_C
-DEFS
-mandir
-localedir
-libdir
-psdir
-pdfdir
-dvidir
-htmldir
-infodir
-docdir
-oldincludedir
-includedir
-localstatedir
-sharedstatedir
-sysconfdir
-datadir
-datarootdir
-libexecdir
-sbindir
-bindir
-program_transform_name
-prefix
-exec_prefix
-PACKAGE_URL
-PACKAGE_BUGREPORT
-PACKAGE_STRING
-PACKAGE_VERSION
-PACKAGE_TARNAME
-PACKAGE_NAME
-PATH_SEPARATOR
-SHELL'
-ac_subst_files=''
-ac_user_opts='
-enable_option_checking
-with_contiki
-with_debug
-with_async
-with_block
-with_observe
-with_query_filter
-with_tests
-with_shared
-'
-      ac_precious_vars='build_alias
-host_alias
-target_alias
-CC
-CFLAGS
-LDFLAGS
-LIBS
-CPPFLAGS
-CPP'
-
-
-# Initialize some variables set by options.
-ac_init_help=
-ac_init_version=false
-ac_unrecognized_opts=
-ac_unrecognized_sep=
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-cache_file=/dev/null
-exec_prefix=NONE
-no_create=
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-verbose=
-x_includes=NONE
-x_libraries=NONE
-
-# Installation directory options.
-# These are left unexpanded so users can "make install exec_prefix=/foo"
-# and all the variables that are supposed to be based on exec_prefix
-# by default will actually change.
-# Use braces instead of parens because sh, perl, etc. also accept them.
-# (The list follows the same order as the GNU Coding Standards.)
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datarootdir='${prefix}/share'
-datadir='${datarootdir}'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
-infodir='${datarootdir}/info'
-htmldir='${docdir}'
-dvidir='${docdir}'
-pdfdir='${docdir}'
-psdir='${docdir}'
-libdir='${exec_prefix}/lib'
-localedir='${datarootdir}/locale'
-mandir='${datarootdir}/man'
-
-ac_prev=
-ac_dashdash=
-for ac_option
-do
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval $ac_prev=\$ac_option
-    ac_prev=
-    continue
-  fi
-
-  case $ac_option in
-  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
-  *=)   ac_optarg= ;;
-  *)    ac_optarg=yes ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case $ac_dashdash$ac_option in
-  --)
-    ac_dashdash=yes ;;
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir=$ac_optarg ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build_alias ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build_alias=$ac_optarg ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file=$ac_optarg ;;
-
-  --config-cache | -C)
-    cache_file=config.cache ;;
-
-  -datadir | --datadir | --datadi | --datad)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=*)
-    datadir=$ac_optarg ;;
-
-  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
-  | --dataroo | --dataro | --datar)
-    ac_prev=datarootdir ;;
-  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
-  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
-    datarootdir=$ac_optarg ;;
-
-  -disable-* | --disable-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"enable_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval enable_$ac_useropt=no ;;
-
-  -docdir | --docdir | --docdi | --doc | --do)
-    ac_prev=docdir ;;
-  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
-    docdir=$ac_optarg ;;
-
-  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
-    ac_prev=dvidir ;;
-  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
-    dvidir=$ac_optarg ;;
-
-  -enable-* | --enable-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"enable_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval enable_$ac_useropt=\$ac_optarg ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix=$ac_optarg ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he | -h)
-    ac_init_help=long ;;
-  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
-    ac_init_help=recursive ;;
-  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
-    ac_init_help=short ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host_alias ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host_alias=$ac_optarg ;;
-
-  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
-    ac_prev=htmldir ;;
-  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
-  | --ht=*)
-    htmldir=$ac_optarg ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir=$ac_optarg ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir=$ac_optarg ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir=$ac_optarg ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir=$ac_optarg ;;
-
-  -localedir | --localedir | --localedi | --localed | --locale)
-    ac_prev=localedir ;;
-  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
-    localedir=$ac_optarg ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst | --locals)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
-    localstatedir=$ac_optarg ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir=$ac_optarg ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c | -n)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir=$ac_optarg ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix=$ac_optarg ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix=$ac_optarg ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix=$ac_optarg ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name=$ac_optarg ;;
-
-  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
-    ac_prev=pdfdir ;;
-  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
-    pdfdir=$ac_optarg ;;
-
-  -psdir | --psdir | --psdi | --psd | --ps)
-    ac_prev=psdir ;;
-  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
-    psdir=$ac_optarg ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir=$ac_optarg ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir=$ac_optarg ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site=$ac_optarg ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir=$ac_optarg ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir=$ac_optarg ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target_alias ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target_alias=$ac_optarg ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers | -V)
-    ac_init_version=: ;;
-
-  -with-* | --with-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"with_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval with_$ac_useropt=\$ac_optarg ;;
-
-  -without-* | --without-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"with_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval with_$ac_useropt=no ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes=$ac_optarg ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries=$ac_optarg ;;
-
-  -*) as_fn_error $? "unrecognized option: \`$ac_option'
-Try \`$0 --help' for more information"
-    ;;
-
-  *=*)
-    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
-    # Reject names that are not valid shell variable names.
-    case $ac_envvar in #(
-      '' | [0-9]* | *[!_$as_cr_alnum]* )
-      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
-    esac
-    eval $ac_envvar=\$ac_optarg
-    export $ac_envvar ;;
-
-  *)
-    # FIXME: should be removed in autoconf 3.0.
-    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
-    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
-  as_fn_error $? "missing argument to $ac_option"
-fi
-
-if test -n "$ac_unrecognized_opts"; then
-  case $enable_option_checking in
-    no) ;;
-    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
-    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
-  esac
-fi
-
-# Check all directory arguments for consistency.
-for ac_var in  exec_prefix prefix bindir sbindir libexecdir datarootdir \
-               datadir sysconfdir sharedstatedir localstatedir includedir \
-               oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-               libdir localedir mandir
-do
-  eval ac_val=\$$ac_var
-  # Remove trailing slashes.
-  case $ac_val in
-    */ )
-      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
-      eval $ac_var=\$ac_val;;
-  esac
-  # Be sure to have absolute directory names.
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* )  continue;;
-    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
-  esac
-  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
-done
-
-# There might be people who depend on the old broken behavior: `$host'
-# used to hold the argument of --host etc.
-# FIXME: To remove some day.
-build=$build_alias
-host=$host_alias
-target=$target_alias
-
-# FIXME: To remove some day.
-if test "x$host_alias" != x; then
-  if test "x$build_alias" = x; then
-    cross_compiling=maybe
-  elif test "x$build_alias" != "x$host_alias"; then
-    cross_compiling=yes
-  fi
-fi
-
-ac_tool_prefix=
-test -n "$host_alias" && ac_tool_prefix=$host_alias-
-
-test "$silent" = yes && exec 6>/dev/null
-
-
-ac_pwd=`pwd` && test -n "$ac_pwd" &&
-ac_ls_di=`ls -di .` &&
-ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
-  as_fn_error $? "working directory cannot be determined"
-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
-  as_fn_error $? "pwd does not report name of working directory"
-
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then the parent directory.
-  ac_confdir=`$as_dirname -- "$as_myself" ||
-$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_myself" : 'X\(//\)[^/]' \| \
-        X"$as_myself" : 'X\(//\)$' \| \
-        X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_myself" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-  srcdir=$ac_confdir
-  if test ! -r "$srcdir/$ac_unique_file"; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r "$srcdir/$ac_unique_file"; then
-  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
-  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
-fi
-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
-ac_abs_confdir=`(
-       cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
-       pwd)`
-# When building in place, set srcdir=.
-if test "$ac_abs_confdir" = "$ac_pwd"; then
-  srcdir=.
-fi
-# Remove unnecessary trailing slashes from srcdir.
-# Double slashes in file names in object file debugging info
-# mess up M-x gdb in Emacs.
-case $srcdir in
-*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
-esac
-for ac_var in $ac_precious_vars; do
-  eval ac_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_env_${ac_var}_value=\$${ac_var}
-  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_cv_env_${ac_var}_value=\$${ac_var}
-done
-
-#
-# Report the --help message.
-#
-if test "$ac_init_help" = "long"; then
-  # Omit some internal or obsolete options to make the list less imposing.
-  # This message is too long to be a string in the A/UX 3.1 sh.
-  cat <<_ACEOF
-\`configure' configures libcoap 4.1.1 to adapt to many kinds of systems.
-
-Usage: $0 [OPTION]... [VAR=VALUE]...
-
-To assign environment variables (e.g., CC, CFLAGS...), specify them as
-VAR=VALUE.  See below for descriptions of some of the useful variables.
-
-Defaults for the options are specified in brackets.
-
-Configuration:
-  -h, --help              display this help and exit
-      --help=short        display options specific to this package
-      --help=recursive    display the short help of all the included packages
-  -V, --version           display version information and exit
-  -q, --quiet, --silent   do not print \`checking ...' messages
-      --cache-file=FILE   cache test results in FILE [disabled]
-  -C, --config-cache      alias for \`--cache-file=config.cache'
-  -n, --no-create         do not create output files
-      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
-
-Installation directories:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-                          [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-                          [PREFIX]
-
-By default, \`make install' will install all the files in
-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
-an installation prefix other than \`$ac_default_prefix' using \`--prefix',
-for instance \`--prefix=\$HOME'.
-
-For better control, use the options below.
-
-Fine tuning of the installation directories:
-  --bindir=DIR            user executables [EPREFIX/bin]
-  --sbindir=DIR           system admin executables [EPREFIX/sbin]
-  --libexecdir=DIR        program executables [EPREFIX/libexec]
-  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
-  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
-  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
-  --libdir=DIR            object code libraries [EPREFIX/lib]
-  --includedir=DIR        C header files [PREFIX/include]
-  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
-  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
-  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
-  --infodir=DIR           info documentation [DATAROOTDIR/info]
-  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
-  --mandir=DIR            man documentation [DATAROOTDIR/man]
-  --docdir=DIR            documentation root [DATAROOTDIR/doc/libcoap]
-  --htmldir=DIR           html documentation [DOCDIR]
-  --dvidir=DIR            dvi documentation [DOCDIR]
-  --pdfdir=DIR            pdf documentation [DOCDIR]
-  --psdir=DIR             ps documentation [DOCDIR]
-_ACEOF
-
-  cat <<\_ACEOF
-_ACEOF
-fi
-
-if test -n "$ac_init_help"; then
-  case $ac_init_help in
-     short | recursive ) echo "Configuration of libcoap 4.1.1:";;
-   esac
-  cat <<\_ACEOF
-
-Optional Packages:
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --with-contiki          build libcoap for the Contiki OS
-  --without-debug         disable all debug output and assertions
-  --without-async         disable handling of asynchronous transactions and
-                          observe
-  --without-block         disable block transfer
-  --without-observe       disable resource observation
-  --without-query-filter  disable support for filters on /.well-known/core
-  --with-tests            enable unit tests (requires cunit)
-  --with-shared           build shared library
-
-Some influential environment variables:
-  CC          C compiler command
-  CFLAGS      C compiler flags
-  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
-              nonstandard directory <lib dir>
-  LIBS        libraries to pass to the linker, e.g. -l<library>
-  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
-              you have headers in a nonstandard directory <include dir>
-  CPP         C preprocessor
-
-Use these variables to override the choices made by `configure' or to help
-it to find libraries and programs with nonstandard names/locations.
-
-Report bugs to the package provider.
-_ACEOF
-ac_status=$?
-fi
-
-if test "$ac_init_help" = "recursive"; then
-  # If there are subdirs, report their specific --help.
-  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d "$ac_dir" ||
-      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
-      continue
-    ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-    cd "$ac_dir" || { ac_status=$?; continue; }
-    # Check for guested configure.
-    if test -f "$ac_srcdir/configure.gnu"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
-    elif test -f "$ac_srcdir/configure"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure" --help=recursive
-    else
-      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi || ac_status=$?
-    cd "$ac_pwd" || { ac_status=$?; break; }
-  done
-fi
-
-test -n "$ac_init_help" && exit $ac_status
-if $ac_init_version; then
-  cat <<\_ACEOF
-libcoap configure 4.1.1
-generated by GNU Autoconf 2.69
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This configure script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it.
-_ACEOF
-  exit
-fi
-
-## ------------------------ ##
-## Autoconf initialization. ##
-## ------------------------ ##
-
-# ac_fn_c_try_compile LINENO
-# --------------------------
-# Try to compile conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_compile ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext
-  if { { ac_try="$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compile") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && {
-        test -z "$ac_c_werror_flag" ||
-        test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_compile
-
-# ac_fn_c_try_run LINENO
-# ----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
-# that executables *can* be run.
-ac_fn_c_try_run ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
-  { { case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_try") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: program exited with status $ac_status" >&5
-       $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=$ac_status
-fi
-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_run
-
-# ac_fn_c_try_cpp LINENO
-# ----------------------
-# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_cpp ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } > conftest.i && {
-        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-        test ! -s conftest.err
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-    ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_cpp
-
-# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists and can be compiled using the include files in
-# INCLUDES, setting the cache variable VAR accordingly.
-ac_fn_c_check_header_compile ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  eval "$3=yes"
-else
-  eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_compile
-
-# ac_fn_c_try_link LINENO
-# -----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_link ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext conftest$ac_exeext
-  if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && {
-        test -z "$ac_c_werror_flag" ||
-        test ! -s conftest.err
-       } && test -s conftest$ac_exeext && {
-        test "$cross_compiling" = yes ||
-        test -x conftest$ac_exeext
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=1
-fi
-  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
-  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
-  # interfere with the next link command; also delete a directory that is
-  # left behind by Apple's compiler.  We do this before executing the actions.
-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_link
-
-# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists, giving a warning if it cannot be compiled using
-# the include files in INCLUDES and setting the cache variable VAR
-# accordingly.
-ac_fn_c_check_header_mongrel ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if eval \${$3+:} false; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
-$as_echo_n "checking $2 usability... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_header_compiler=yes
-else
-  ac_header_compiler=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
-$as_echo "$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
-$as_echo_n "checking $2 presence... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <$2>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  ac_header_preproc=yes
-else
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
-$as_echo "$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
-  yes:no: )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
-$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-  no:yes:* )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
-$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
-$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
-$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
-$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-esac
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eval "$3=\$ac_header_compiler"
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_mongrel
-
-# ac_fn_c_check_type LINENO TYPE VAR INCLUDES
-# -------------------------------------------
-# Tests whether TYPE exists after having included INCLUDES, setting cache
-# variable VAR accordingly.
-ac_fn_c_check_type ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eval "$3=no"
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-int
-main ()
-{
-if (sizeof ($2))
-        return 0;
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-int
-main ()
-{
-if (sizeof (($2)))
-           return 0;
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
-  eval "$3=yes"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_type
-
-# ac_fn_c_check_func LINENO FUNC VAR
-# ----------------------------------
-# Tests whether FUNC exists, setting the cache variable VAR accordingly
-ac_fn_c_check_func ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-/* Define $2 to an innocuous variant, in case <limits.h> declares $2.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $2 innocuous_$2
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $2 (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $2
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $2 ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$2 || defined __stub___$2
-choke me
-#endif
-
-int
-main ()
-{
-return $2 ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  eval "$3=yes"
-else
-  eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_func
-cat >config.log <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by libcoap $as_me 4.1.1, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
-
-  $ $0 $@
-
-_ACEOF
-exec 5>>config.log
-{
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
-
-/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
-/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
-/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
-
-_ASUNAME
-
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    $as_echo "PATH: $as_dir"
-  done
-IFS=$as_save_IFS
-
-} >&5
-
-cat >&5 <<_ACEOF
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-_ACEOF
-
-
-# Keep a trace of the command line.
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Strip out --silent because we don't want to record it for future runs.
-# Also quote any args containing shell meta-characters.
-# Make two passes to allow for proper duplicate-argument suppression.
-ac_configure_args=
-ac_configure_args0=
-ac_configure_args1=
-ac_must_keep_next=false
-for ac_pass in 1 2
-do
-  for ac_arg
-  do
-    case $ac_arg in
-    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
-    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-    | -silent | --silent | --silen | --sile | --sil)
-      continue ;;
-    *\'*)
-      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    case $ac_pass in
-    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
-    2)
-      as_fn_append ac_configure_args1 " '$ac_arg'"
-      if test $ac_must_keep_next = true; then
-       ac_must_keep_next=false # Got value, back to normal.
-      else
-       case $ac_arg in
-         *=* | --config-cache | -C | -disable-* | --disable-* \
-         | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
-         | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
-         | -with-* | --with-* | -without-* | --without-* | --x)
-           case "$ac_configure_args0 " in
-             "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
-           esac
-           ;;
-         -* ) ac_must_keep_next=true ;;
-       esac
-      fi
-      as_fn_append ac_configure_args " '$ac_arg'"
-      ;;
-    esac
-  done
-done
-{ ac_configure_args0=; unset ac_configure_args0;}
-{ ac_configure_args1=; unset ac_configure_args1;}
-
-# When interrupted or exit'd, cleanup temporary files, and complete
-# config.log.  We remove comments because anyway the quotes in there
-# would cause problems or look ugly.
-# WARNING: Use '\'' to represent an apostrophe within the trap.
-# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
-trap 'exit_status=$?
-  # Save into config.log some information that might help in debugging.
-  {
-    echo
-
-    $as_echo "## ---------------- ##
-## Cache variables. ##
-## ---------------- ##"
-    echo
-    # The following way of writing the cache mishandles newlines in values,
-(
-  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
-      *) { eval $ac_var=; unset $ac_var;} ;;
-      esac ;;
-    esac
-  done
-  (set) 2>&1 |
-    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      sed -n \
-       "s/'\''/'\''\\\\'\'''\''/g;
-         s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
-      ;; #(
-    *)
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-)
-    echo
-
-    $as_echo "## ----------------- ##
-## Output variables. ##
-## ----------------- ##"
-    echo
-    for ac_var in $ac_subst_vars
-    do
-      eval ac_val=\$$ac_var
-      case $ac_val in
-      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-      esac
-      $as_echo "$ac_var='\''$ac_val'\''"
-    done | sort
-    echo
-
-    if test -n "$ac_subst_files"; then
-      $as_echo "## ------------------- ##
-## File substitutions. ##
-## ------------------- ##"
-      echo
-      for ac_var in $ac_subst_files
-      do
-       eval ac_val=\$$ac_var
-       case $ac_val in
-       *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-       esac
-       $as_echo "$ac_var='\''$ac_val'\''"
-      done | sort
-      echo
-    fi
-
-    if test -s confdefs.h; then
-      $as_echo "## ----------- ##
-## confdefs.h. ##
-## ----------- ##"
-      echo
-      cat confdefs.h
-      echo
-    fi
-    test "$ac_signal" != 0 &&
-      $as_echo "$as_me: caught signal $ac_signal"
-    $as_echo "$as_me: exit $exit_status"
-  } >&5
-  rm -f core *.core core.conftest.* &&
-    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
-    exit $exit_status
-' 0
-for ac_signal in 1 2 13 15; do
-  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
-done
-ac_signal=0
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -f -r conftest* confdefs.h
-
-$as_echo "/* confdefs.h */" > confdefs.h
-
-# Predefined preprocessor variables.
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_URL "$PACKAGE_URL"
-_ACEOF
-
-
-# Let the site file select an alternate cache file if it wants to.
-# Prefer an explicitly selected file to automatically selected ones.
-ac_site_file1=NONE
-ac_site_file2=NONE
-if test -n "$CONFIG_SITE"; then
-  # We do not want a PATH search for config.site.
-  case $CONFIG_SITE in #((
-    -*)  ac_site_file1=./$CONFIG_SITE;;
-    */*) ac_site_file1=$CONFIG_SITE;;
-    *)   ac_site_file1=./$CONFIG_SITE;;
-  esac
-elif test "x$prefix" != xNONE; then
-  ac_site_file1=$prefix/share/config.site
-  ac_site_file2=$prefix/etc/config.site
-else
-  ac_site_file1=$ac_default_prefix/share/config.site
-  ac_site_file2=$ac_default_prefix/etc/config.site
-fi
-for ac_site_file in "$ac_site_file1" "$ac_site_file2"
-do
-  test "x$ac_site_file" = xNONE && continue
-  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
-$as_echo "$as_me: loading site script $ac_site_file" >&6;}
-    sed 's/^/| /' "$ac_site_file" >&5
-    . "$ac_site_file" \
-      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5; }
-  fi
-done
-
-if test -r "$cache_file"; then
-  # Some versions of bash will fail to source /dev/null (special files
-  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
-  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
-$as_echo "$as_me: loading cache $cache_file" >&6;}
-    case $cache_file in
-      [\\/]* | ?:[\\/]* ) . "$cache_file";;
-      *)                      . "./$cache_file";;
-    esac
-  fi
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
-$as_echo "$as_me: creating cache $cache_file" >&6;}
-  >$cache_file
-fi
-
-# Check that the precious variables saved in the cache have kept the same
-# value.
-ac_cache_corrupted=false
-for ac_var in $ac_precious_vars; do
-  eval ac_old_set=\$ac_cv_env_${ac_var}_set
-  eval ac_new_set=\$ac_env_${ac_var}_set
-  eval ac_old_val=\$ac_cv_env_${ac_var}_value
-  eval ac_new_val=\$ac_env_${ac_var}_value
-  case $ac_old_set,$ac_new_set in
-    set,)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,set)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,);;
-    *)
-      if test "x$ac_old_val" != "x$ac_new_val"; then
-       # differences in whitespace do not lead to failure.
-       ac_old_val_w=`echo x $ac_old_val`
-       ac_new_val_w=`echo x $ac_new_val`
-       if test "$ac_old_val_w" != "$ac_new_val_w"; then
-         { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
-$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
-         ac_cache_corrupted=:
-       else
-         { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
-$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
-         eval $ac_var=\$ac_old_val
-       fi
-       { $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
-$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
-       { $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
-$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
-      fi;;
-  esac
-  # Pass precious variables to config.status.
-  if test "$ac_new_set" = set; then
-    case $ac_new_val in
-    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
-    *) ac_arg=$ac_var=$ac_new_val ;;
-    esac
-    case " $ac_configure_args " in
-      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
-      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
-    esac
-  fi
-done
-if $ac_cache_corrupted; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
-$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
-  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
-fi
-## -------------------- ##
-## Main body of script. ##
-## -------------------- ##
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-
-# First check for Contiki build to quit configure before any other test
-
-# Check whether --with-contiki was given.
-if test "${with_contiki+set}" = set; then :
-  withval=$with_contiki; cp -p Makefile.contiki Makefile
-   cp -p config.h.contiki config.h
-   { $as_echo "$as_me:${as_lineno-$LINENO}: Contiki build prepared" >&5
-$as_echo "$as_me: Contiki build prepared" >&6;}
-   exit 0
-fi
-
-
-# Checks for programs.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
-$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
-set x ${MAKE-make}
-ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
-if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat >conftest.make <<\_ACEOF
-SHELL = /bin/sh
-all:
-       @echo '@@@%%%=$(MAKE)=@@@%%%'
-_ACEOF
-# GNU make sometimes prints "make[1]: Entering ...", which would confuse us.
-case `${MAKE-make} -f conftest.make 2>/dev/null` in
-  *@@@%%%=?*=@@@%%%*)
-    eval ac_cv_prog_make_${ac_make}_set=yes;;
-  *)
-    eval ac_cv_prog_make_${ac_make}_set=no;;
-esac
-rm -f conftest.make
-fi
-if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-  SET_MAKE=
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_CC"; then
-  ac_ct_CC=$CC
-  # Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_CC" = x; then
-    CC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
-else
-  CC="$ac_cv_prog_CC"
-fi
-
-if test -z "$CC"; then
-          if test -n "$ac_tool_prefix"; then
-    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  fi
-fi
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  ac_prog_rejected=no
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
-       ac_prog_rejected=yes
-       continue
-     fi
-    ac_cv_prog_CC="cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# != 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
-  fi
-fi
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$CC"; then
-  if test -n "$ac_tool_prefix"; then
-  for ac_prog in cl.exe
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-    test -n "$CC" && break
-  done
-fi
-if test -z "$CC"; then
-  ac_ct_CC=$CC
-  for ac_prog in cl.exe
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$ac_ct_CC" && break
-done
-
-  if test "x$ac_ct_CC" = x; then
-    CC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
-fi
-
-fi
-
-
-test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5; }
-
-# Provide some information about the compiler.
-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
-set X $ac_compile
-ac_compiler=$2
-for ac_option in --version -v -V -qversion; do
-  { { ac_try="$ac_compiler $ac_option >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    sed '10a\
-... rest of stderr output deleted ...
-         10q' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-  fi
-  rm -f conftest.er1 conftest.err
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-done
-
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
-# Try to create an executable without -o first, disregard a.out.
-# It will help us diagnose broken compilers, and finding out an intuition
-# of exeext.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
-$as_echo_n "checking whether the C compiler works... " >&6; }
-ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-
-# The possible output files:
-ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
-
-ac_rmfiles=
-for ac_file in $ac_files
-do
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
-    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
-  esac
-done
-rm -f $ac_rmfiles
-
-if { { ac_try="$ac_link_default"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link_default") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
-# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
-# in a Makefile.  We should not override ac_cv_exeext if it was cached,
-# so that the user can short-circuit this test for compilers unknown to
-# Autoconf.
-for ac_file in $ac_files ''
-do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
-       ;;
-    [ab].out )
-       # We found the default executable, but exeext='' is most
-       # certainly right.
-       break;;
-    *.* )
-       if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
-       then :; else
-          ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-       fi
-       # We set ac_cv_exeext here because the later test for it is not
-       # safe: cross compilers may not add the suffix if given an `-o'
-       # argument, so we may need to know it at that point already.
-       # Even if this section looks crufty: it has the advantage of
-       # actually working.
-       break;;
-    * )
-       break;;
-  esac
-done
-test "$ac_cv_exeext" = no && ac_cv_exeext=
-
-else
-  ac_file=''
-fi
-if test -z "$ac_file"; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-$as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
-$as_echo_n "checking for C compiler default output file name... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
-$as_echo "$ac_file" >&6; }
-ac_exeext=$ac_cv_exeext
-
-rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
-$as_echo_n "checking for suffix of executables... " >&6; }
-if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  # If both `conftest.exe' and `conftest' are `present' (well, observable)
-# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
-# work properly (i.e., refer to `conftest.exe'), while it won't with
-# `rm'.
-for ac_file in conftest.exe conftest conftest.*; do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
-    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-         break;;
-    * ) break;;
-  esac
-done
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest conftest$ac_cv_exeext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
-$as_echo "$ac_cv_exeext" >&6; }
-
-rm -f conftest.$ac_ext
-EXEEXT=$ac_cv_exeext
-ac_exeext=$EXEEXT
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdio.h>
-int
-main ()
-{
-FILE *f = fopen ("conftest.out", "w");
- return ferror (f) || fclose (f) != 0;
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files="$ac_clean_files conftest.out"
-# Check that the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
-$as_echo_n "checking whether we are cross compiling... " >&6; }
-if test "$cross_compiling" != yes; then
-  { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-  if { ac_try='./conftest$ac_cv_exeext'
-  { { case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_try") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then
-    cross_compiling=no
-  else
-    if test "$cross_compiling" = maybe; then
-       cross_compiling=yes
-    else
-       { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5; }
-    fi
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
-$as_echo "$cross_compiling" >&6; }
-
-rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
-$as_echo_n "checking for suffix of object files... " >&6; }
-if ${ac_cv_objext+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.o conftest.obj
-if { { ac_try="$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compile") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  for ac_file in conftest.o conftest.obj conftest.*; do
-  test -f "$ac_file" || continue;
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
-    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
-       break;;
-  esac
-done
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest.$ac_cv_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
-$as_echo "$ac_cv_objext" >&6; }
-OBJEXT=$ac_cv_objext
-ac_objext=$OBJEXT
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-#ifndef __GNUC__
-       choke me
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_compiler_gnu=yes
-else
-  ac_compiler_gnu=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_c_compiler_gnu=$ac_compiler_gnu
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
-$as_echo "$ac_cv_c_compiler_gnu" >&6; }
-if test $ac_compiler_gnu = yes; then
-  GCC=yes
-else
-  GCC=
-fi
-ac_test_CFLAGS=${CFLAGS+set}
-ac_save_CFLAGS=$CFLAGS
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
-$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_save_c_werror_flag=$ac_c_werror_flag
-   ac_c_werror_flag=yes
-   ac_cv_prog_cc_g=no
-   CFLAGS="-g"
-   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_g=yes
-else
-  CFLAGS=""
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
-  ac_c_werror_flag=$ac_save_c_werror_flag
-        CFLAGS="-g"
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_g=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-   ac_c_werror_flag=$ac_save_c_werror_flag
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
-$as_echo "$ac_cv_prog_cc_g" >&6; }
-if test "$ac_test_CFLAGS" = set; then
-  CFLAGS=$ac_save_CFLAGS
-elif test $ac_cv_prog_cc_g = yes; then
-  if test "$GCC" = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-g"
-  fi
-else
-  if test "$GCC" = yes; then
-    CFLAGS="-O2"
-  else
-    CFLAGS=
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_prog_cc_c89=no
-ac_save_CC=$CC
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdarg.h>
-#include <stdio.h>
-struct stat;
-/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
-struct buf { int x; };
-FILE * (*rcsopen) (struct buf *, struct stat *, int);
-static char *e (p, i)
-     char **p;
-     int i;
-{
-  return p[i];
-}
-static char *f (char * (*g) (char **, int), char **p, ...)
-{
-  char *s;
-  va_list v;
-  va_start (v,p);
-  s = g (p, va_arg (v,int));
-  va_end (v);
-  return s;
-}
-
-/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
-   function prototypes and stuff, but not '\xHH' hex character constants.
-   These don't provoke an error unfortunately, instead are silently treated
-   as 'x'.  The following induces an error, until -std is added to get
-   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
-   array size at least.  It's necessary to write '\x00'==0 to get something
-   that's true only with -std.  */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
-
-/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
-   inside strings and character constants.  */
-#define FOO(x) 'x'
-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
-
-int test (int i, double x);
-struct s1 {int (*f) (int a);};
-struct s2 {int (*f) (double a);};
-int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
-int argc;
-char **argv;
-int
-main ()
-{
-return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
-  ;
-  return 0;
-}
-_ACEOF
-for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
-       -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
-do
-  CC="$ac_save_CC $ac_arg"
-  if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_c89=$ac_arg
-fi
-rm -f core conftest.err conftest.$ac_objext
-  test "x$ac_cv_prog_cc_c89" != "xno" && break
-done
-rm -f conftest.$ac_ext
-CC=$ac_save_CC
-
-fi
-# AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
-  x)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
-$as_echo "none needed" >&6; } ;;
-  xno)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; } ;;
-  *)
-    CC="$CC $ac_cv_prog_cc_c89"
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
-esac
-if test "x$ac_cv_prog_cc_c89" != xno; then :
-
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
-$as_echo "$RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_RANLIB"; then
-  ac_ct_RANLIB=$RANLIB
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_RANLIB"; then
-  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RANLIB="ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
-$as_echo "$ac_ct_RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_RANLIB" = x; then
-    RANLIB=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    RANLIB=$ac_ct_RANLIB
-  fi
-else
-  RANLIB="$ac_cv_prog_RANLIB"
-fi
-
-# Extract the first word of "doxygen", so it can be a program name with args.
-set dummy doxygen; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_DOXYGEN+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $DOXYGEN in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_path_DOXYGEN" && ac_cv_path_DOXYGEN=":"
-  ;;
-esac
-fi
-DOXYGEN=$ac_cv_path_DOXYGEN
-if test -n "$DOXYGEN"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5
-$as_echo "$DOXYGEN" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-# Extract the first word of "etags", so it can be a program name with args.
-set dummy etags; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_ETAGS+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $ETAGS in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_ETAGS="$ETAGS" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_ETAGS="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_path_ETAGS" && ac_cv_path_ETAGS="/bin/false"
-  ;;
-esac
-fi
-ETAGS=$ac_cv_path_ETAGS
-if test -n "$ETAGS"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ETAGS" >&5
-$as_echo "$ETAGS" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
-$as_echo_n "checking how to run the C preprocessor... " >&6; }
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-  if ${ac_cv_prog_CPP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
-    do
-      ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-                    Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-  break
-fi
-
-    done
-    ac_cv_prog_CPP=$CPP
-
-fi
-  CPP=$ac_cv_prog_CPP
-else
-  ac_cv_prog_CPP=$CPP
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
-$as_echo "$CPP" >&6; }
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-                    Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
-$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if ${ac_cv_path_GREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -z "$GREP"; then
-  ac_path_GREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in grep ggrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_GREP" || continue
-# Check for GNU ac_path_GREP and select it if it is found.
-  # Check for GNU $ac_path_GREP
-case `"$ac_path_GREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'GREP' >> "conftest.nl"
-    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_GREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_GREP="$ac_path_GREP"
-      ac_path_GREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_GREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_GREP"; then
-    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_GREP=$GREP
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
-$as_echo "$ac_cv_path_GREP" >&6; }
- GREP="$ac_cv_path_GREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
-$as_echo_n "checking for egrep... " >&6; }
-if ${ac_cv_path_EGREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
-   then ac_cv_path_EGREP="$GREP -E"
-   else
-     if test -z "$EGREP"; then
-  ac_path_EGREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in egrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_EGREP" || continue
-# Check for GNU ac_path_EGREP and select it if it is found.
-  # Check for GNU $ac_path_EGREP
-case `"$ac_path_EGREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'EGREP' >> "conftest.nl"
-    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_EGREP="$ac_path_EGREP"
-      ac_path_EGREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_EGREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_EGREP"; then
-    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_EGREP=$EGREP
-fi
-
-   fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
-$as_echo "$ac_cv_path_EGREP" >&6; }
- EGREP="$ac_cv_path_EGREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
-$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_header_stdc=yes
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" = yes; then :
-  :
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ctype.h>
-#include <stdlib.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
-                  (('a' <= (c) && (c) <= 'i') \
-                    || ('j' <= (c) && (c) <= 'r') \
-                    || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
-
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
-  int i;
-  for (i = 0; i < 256; i++)
-    if (XOR (islower (i), ISLOWER (i))
-       || toupper (i) != TOUPPER (i))
-      return 2;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
-$as_echo "$ac_cv_header_stdc" >&6; }
-if test $ac_cv_header_stdc = yes; then
-
-$as_echo "#define STDC_HEADERS 1" >>confdefs.h
-
-fi
-
-# On IRIX 5.3, sys/types and inttypes.h are conflicting.
-for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
-                 inttypes.h stdint.h unistd.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
-"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
-$as_echo_n "checking whether byte ordering is bigendian... " >&6; }
-if ${ac_cv_c_bigendian+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_c_bigendian=unknown
-    # See if we're dealing with a universal compiler.
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifndef __APPLE_CC__
-              not a universal capable compiler
-            #endif
-            typedef int dummy;
-
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-       # Check for potential -arch flags.  It is not universal unless
-       # there are at least two -arch flags with different values.
-       ac_arch=
-       ac_prev=
-       for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do
-        if test -n "$ac_prev"; then
-          case $ac_word in
-            i?86 | x86_64 | ppc | ppc64)
-              if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then
-                ac_arch=$ac_word
-              else
-                ac_cv_c_bigendian=universal
-                break
-              fi
-              ;;
-          esac
-          ac_prev=
-        elif test "x$ac_word" = "x-arch"; then
-          ac_prev=arch
-        fi
-       done
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    if test $ac_cv_c_bigendian = unknown; then
-      # See if sys/param.h defines the BYTE_ORDER macro.
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
-            #include <sys/param.h>
-
-int
-main ()
-{
-#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \
-                    && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \
-                    && LITTLE_ENDIAN)
-             bogus endian macros
-            #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  # It does; now see whether it defined to BIG_ENDIAN or not.
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
-               #include <sys/param.h>
-
-int
-main ()
-{
-#if BYTE_ORDER != BIG_ENDIAN
-                not big endian
-               #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_bigendian=yes
-else
-  ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    fi
-    if test $ac_cv_c_bigendian = unknown; then
-      # See if <limits.h> defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris).
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <limits.h>
-
-int
-main ()
-{
-#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN)
-             bogus endian macros
-            #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  # It does; now see whether it defined to _BIG_ENDIAN or not.
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <limits.h>
-
-int
-main ()
-{
-#ifndef _BIG_ENDIAN
-                not big endian
-               #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_bigendian=yes
-else
-  ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    fi
-    if test $ac_cv_c_bigendian = unknown; then
-      # Compile a test program.
-      if test "$cross_compiling" = yes; then :
-  # Try to guess by grepping values from an object file.
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-short int ascii_mm[] =
-                 { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
-               short int ascii_ii[] =
-                 { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
-               int use_ascii (int i) {
-                 return ascii_mm[i] + ascii_ii[i];
-               }
-               short int ebcdic_ii[] =
-                 { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
-               short int ebcdic_mm[] =
-                 { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
-               int use_ebcdic (int i) {
-                 return ebcdic_mm[i] + ebcdic_ii[i];
-               }
-               extern int foo;
-
-int
-main ()
-{
-return use_ascii (foo) == use_ebcdic (foo);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then
-             ac_cv_c_bigendian=yes
-           fi
-           if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then
-             if test "$ac_cv_c_bigendian" = unknown; then
-               ac_cv_c_bigendian=no
-             else
-               # finding both strings is unlikely to happen, but who knows?
-               ac_cv_c_bigendian=unknown
-             fi
-           fi
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-
-            /* Are we little or big endian?  From Harbison&Steele.  */
-            union
-            {
-              long int l;
-              char c[sizeof (long int)];
-            } u;
-            u.l = 1;
-            return u.c[sizeof (long int) - 1] == 1;
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-  ac_cv_c_bigendian=no
-else
-  ac_cv_c_bigendian=yes
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-    fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5
-$as_echo "$ac_cv_c_bigendian" >&6; }
- case $ac_cv_c_bigendian in #(
-   yes)
-     $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h
-;; #(
-   no)
-      ;; #(
-   universal)
-
-$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
-
-     ;; #(
-   *)
-     as_fn_error $? "unknown endianness
- presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;;
- esac
-
-
-# Checks for libraries.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for coap_new_pdu in -lcoap" >&5
-$as_echo_n "checking for coap_new_pdu in -lcoap... " >&6; }
-if ${ac_cv_lib_coap_coap_new_pdu+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lcoap  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char coap_new_pdu ();
-int
-main ()
-{
-return coap_new_pdu ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_coap_coap_new_pdu=yes
-else
-  ac_cv_lib_coap_coap_new_pdu=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_coap_coap_new_pdu" >&5
-$as_echo "$ac_cv_lib_coap_coap_new_pdu" >&6; }
-if test "x$ac_cv_lib_coap_coap_new_pdu" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBCOAP 1
-_ACEOF
-
-  LIBS="-lcoap $LIBS"
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gethostbyname" >&5
-$as_echo_n "checking for library containing gethostbyname... " >&6; }
-if ${ac_cv_search_gethostbyname+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gethostbyname ();
-int
-main ()
-{
-return gethostbyname ();
-  ;
-  return 0;
-}
-_ACEOF
-for ac_lib in '' nsl; do
-  if test -z "$ac_lib"; then
-    ac_res="none required"
-  else
-    ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
-  fi
-  if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_search_gethostbyname=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext
-  if ${ac_cv_search_gethostbyname+:} false; then :
-  break
-fi
-done
-if ${ac_cv_search_gethostbyname+:} false; then :
-
-else
-  ac_cv_search_gethostbyname=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gethostbyname" >&5
-$as_echo "$ac_cv_search_gethostbyname" >&6; }
-ac_res=$ac_cv_search_gethostbyname
-if test "$ac_res" != no; then :
-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing socket" >&5
-$as_echo_n "checking for library containing socket... " >&6; }
-if ${ac_cv_search_socket+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char socket ();
-int
-main ()
-{
-return socket ();
-  ;
-  return 0;
-}
-_ACEOF
-for ac_lib in '' socket; do
-  if test -z "$ac_lib"; then
-    ac_res="none required"
-  else
-    ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
-  fi
-  if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_search_socket=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext
-  if ${ac_cv_search_socket+:} false; then :
-  break
-fi
-done
-if ${ac_cv_search_socket+:} false; then :
-
-else
-  ac_cv_search_socket=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_socket" >&5
-$as_echo "$ac_cv_search_socket" >&6; }
-ac_res=$ac_cv_search_socket
-if test "$ac_res" != no; then :
-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-
-# configuration options that may change compile flags
-
-# Check whether --with-debug was given.
-if test "${with_debug+set}" = set; then :
-  withval=$with_debug; CPPFLAGS="${CPPFLAGS} -DNDEBUG"
-fi
-
-
-
-# Check whether --with-async was given.
-if test "${with_async+set}" = set; then :
-  withval=$with_async; CPPFLAGS="${CPPFLAGS} -DWITHOUT_ASYNC"
-fi
-
-
-
-# Check whether --with-block was given.
-if test "${with_block+set}" = set; then :
-  withval=$with_block; CPPFLAGS="${CPPFLAGS} -DWITHOUT_BLOCK"
-fi
-
-
-
-# Check whether --with-observe was given.
-if test "${with_observe+set}" = set; then :
-  withval=$with_observe; CPPFLAGS="${CPPFLAGS} -DWITHOUT_OBSERVE"
-fi
-
-
-
-# Check whether --with-query-filter was given.
-if test "${with_query_filter+set}" = set; then :
-  withval=$with_query_filter; CPPFLAGS="${CPPFLAGS} -DWITHOUT_QUERY_FILTER"
-fi
-
-
-
-# Check whether --with-tests was given.
-if test "${with_tests+set}" = set; then :
-  withval=$with_tests; TESTS="tests"
-fi
-
-
-
-# Check whether --with-shared was given.
-if test "${with_shared+set}" = set; then :
-  withval=$with_shared; BUILD_SO="BUILD_SO=1"
-fi
-
-
-# disambiguate between autoconf generated setups and contiki / lwip setups
-# which use explicit config.h.* files
-CPPFLAGS="${CPPFLAGS} -DWITH_POSIX"
-
-# Checks for header files.
-for ac_header in assert.h arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h strings.h sys/socket.h sys/time.h time.h unistd.h sys/unistd.h syslog.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-# Checks for typedefs, structures, and compiler characteristics.
-ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default"
-if test "x$ac_cv_type_size_t" = xyes; then :
-
-else
-
-cat >>confdefs.h <<_ACEOF
-#define size_t unsigned int
-_ACEOF
-
-fi
-
-ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default"
-if test "x$ac_cv_type_ssize_t" = xyes; then :
-
-else
-
-cat >>confdefs.h <<_ACEOF
-#define ssize_t int
-_ACEOF
-
-fi
-
-
-# Checks for library functions.
-for ac_header in stdlib.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default"
-if test "x$ac_cv_header_stdlib_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_STDLIB_H 1
-_ACEOF
-
-fi
-
-done
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5
-$as_echo_n "checking for GNU libc compatible malloc... " >&6; }
-if ${ac_cv_func_malloc_0_nonnull+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test "$cross_compiling" = yes; then :
-  ac_cv_func_malloc_0_nonnull=no
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#if defined STDC_HEADERS || defined HAVE_STDLIB_H
-# include <stdlib.h>
-#else
-char *malloc ();
-#endif
-
-int
-main ()
-{
-return ! malloc (0);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-  ac_cv_func_malloc_0_nonnull=yes
-else
-  ac_cv_func_malloc_0_nonnull=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5
-$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; }
-if test $ac_cv_func_malloc_0_nonnull = yes; then :
-
-$as_echo "#define HAVE_MALLOC 1" >>confdefs.h
-
-else
-  $as_echo "#define HAVE_MALLOC 0" >>confdefs.h
-
-   case " $LIBOBJS " in
-  *" malloc.$ac_objext "* ) ;;
-  *) LIBOBJS="$LIBOBJS malloc.$ac_objext"
- ;;
-esac
-
-
-$as_echo "#define malloc rpl_malloc" >>confdefs.h
-
-fi
-
-
-for ac_func in memset select socket strcasecmp strrchr getaddrinfo strnlen
-do :
-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-
-
-
-
-ac_config_headers="$ac_config_headers config.h"
-
-
-ac_config_files="$ac_config_files Makefile doc/Makefile doc/Doxyfile examples/Makefile tests/Makefile"
-
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems.  If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
-
-_ACEOF
-
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, we kill variables containing newlines.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(
-  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
-      *) { eval $ac_var=; unset $ac_var;} ;;
-      esac ;;
-    esac
-  done
-
-  (set) 2>&1 |
-    case $as_nl`(ac_space=' '; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      # `set' does not quote correctly, so add quotes: double-quote
-      # substitution turns \\\\ into \\, and sed turns \\ into \.
-      sed -n \
-       "s/'/'\\\\''/g;
-         s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
-      ;; #(
-    *)
-      # `set' quotes correctly as required by POSIX, so do not add quotes.
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-) |
-  sed '
-     /^ac_cv_env_/b end
-     t clear
-     :clear
-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
-     t end
-     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
-     :end' >>confcache
-if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
-  if test -w "$cache_file"; then
-    if test "x$cache_file" != "x/dev/null"; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
-$as_echo "$as_me: updating cache $cache_file" >&6;}
-      if test ! -f "$cache_file" || test -h "$cache_file"; then
-       cat confcache >"$cache_file"
-      else
-        case $cache_file in #(
-        */* | ?:*)
-         mv -f confcache "$cache_file"$$ &&
-         mv -f "$cache_file"$$ "$cache_file" ;; #(
-        *)
-         mv -f confcache "$cache_file" ;;
-       esac
-      fi
-    fi
-  else
-    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
-$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
-  fi
-fi
-rm -f confcache
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-DEFS=-DHAVE_CONFIG_H
-
-ac_libobjs=
-ac_ltlibobjs=
-U=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
-  # 1. Remove the extension, and $U if already installed.
-  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
-  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
-  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
-  #    will be set to the directory where LIBOBJS objects are built.
-  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
-  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
-
-LTLIBOBJS=$ac_ltlibobjs
-
-
-
-
-: "${CONFIG_STATUS=./config.status}"
-ac_write_fail=0
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
-$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
-as_write_fail=0
-cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-
-SHELL=\${CONFIG_SHELL-$SHELL}
-export SHELL
-_ASEOF
-cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-       expr "X$arg" : "X\\(.*\\)$as_nl";
-       arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
-      PATH_SEPARATOR=';'
-  }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""       $as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-  done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
-  as_status=$1; test $as_status -eq 0 && as_status=1
-  if test "$4"; then
-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
-  fi
-  $as_echo "$as_me: error: $2" >&2
-  as_fn_exit $as_status
-} # as_fn_error
-
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
-  return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
-  set +e
-  as_fn_set_status $1
-  exit $1
-} # as_fn_exit
-
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
-  { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
-  eval 'as_fn_append ()
-  {
-    eval $1+=\$2
-  }'
-else
-  as_fn_append ()
-  {
-    eval $1=\$$1\$2
-  }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
-  eval 'as_fn_arith ()
-  {
-    as_val=$(( $* ))
-  }'
-else
-  as_fn_arith ()
-  {
-    as_val=`expr "$@" || test $? -eq 1`
-  }
-fi # as_fn_arith
-
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-        X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
-  case `echo 'xy\c'` in
-  *c*) ECHO_T='        ';;     # ECHO_T is single tab character.
-  xy)  ECHO_C='\c';;
-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
-       ECHO_T='        ';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
-  if ln -s conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s='ln -s'
-    # ... but there are two gotchas:
-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -pR'.
-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -pR'
-  elif ln conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s=ln
-  else
-    as_ln_s='cp -pR'
-  fi
-else
-  as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || eval $as_mkdir_p || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_dir" : 'X\(//\)[^/]' \| \
-        X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p='mkdir -p "$as_dir"'
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
-  test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-## ----------------------------------- ##
-## Main body of $CONFIG_STATUS script. ##
-## ----------------------------------- ##
-_ASEOF
-test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# Save the log message, to keep $0 and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by libcoap $as_me 4.1.1, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
-
-  CONFIG_FILES    = $CONFIG_FILES
-  CONFIG_HEADERS  = $CONFIG_HEADERS
-  CONFIG_LINKS    = $CONFIG_LINKS
-  CONFIG_COMMANDS = $CONFIG_COMMANDS
-  $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-_ACEOF
-
-case $ac_config_files in *"
-"*) set x $ac_config_files; shift; ac_config_files=$*;;
-esac
-
-case $ac_config_headers in *"
-"*) set x $ac_config_headers; shift; ac_config_headers=$*;;
-esac
-
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-# Files that config.status was made for.
-config_files="$ac_config_files"
-config_headers="$ac_config_headers"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-ac_cs_usage="\
-\`$as_me' instantiates files and other configuration actions
-from templates according to the current configuration.  Unless the files
-and actions are specified as TAGs, all are instantiated by default.
-
-Usage: $0 [OPTION]... [TAG]...
-
-  -h, --help       print this help, then exit
-  -V, --version    print version number and configuration settings, then exit
-      --config     print configuration, then exit
-  -q, --quiet, --silent
-                   do not print progress messages
-  -d, --debug      don't remove temporary files
-      --recheck    update $as_me by reconfiguring in the same conditions
-      --file=FILE[:TEMPLATE]
-                   instantiate the configuration file FILE
-      --header=FILE[:TEMPLATE]
-                   instantiate the configuration header FILE
-
-Configuration files:
-$config_files
-
-Configuration headers:
-$config_headers
-
-Report bugs to the package provider."
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
-ac_cs_version="\\
-libcoap config.status 4.1.1
-configured by $0, generated by GNU Autoconf 2.69,
-  with options \\"\$ac_cs_config\\"
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='$ac_pwd'
-srcdir='$srcdir'
-test -n "\$AWK" || AWK=awk
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# The default lists apply if the user does not specify any file.
-ac_need_defaults=:
-while test $# != 0
-do
-  case $1 in
-  --*=?*)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
-    ac_shift=:
-    ;;
-  --*=)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=
-    ac_shift=:
-    ;;
-  *)
-    ac_option=$1
-    ac_optarg=$2
-    ac_shift=shift
-    ;;
-  esac
-
-  case $ac_option in
-  # Handling of the options.
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    ac_cs_recheck=: ;;
-  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    $as_echo "$ac_cs_version"; exit ;;
-  --config | --confi | --conf | --con | --co | --c )
-    $as_echo "$ac_cs_config"; exit ;;
-  --debug | --debu | --deb | --de | --d | -d )
-    debug=: ;;
-  --file | --fil | --fi | --f )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    '') as_fn_error $? "missing file argument" ;;
-    esac
-    as_fn_append CONFIG_FILES " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --header | --heade | --head | --hea )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --he | --h)
-    # Conflict between --help and --header
-    as_fn_error $? "ambiguous option: \`$1'
-Try \`$0 --help' for more information.";;
-  --help | --hel | -h )
-    $as_echo "$ac_cs_usage"; exit ;;
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil | --si | --s)
-    ac_cs_silent=: ;;
-
-  # This is an error.
-  -*) as_fn_error $? "unrecognized option: \`$1'
-Try \`$0 --help' for more information." ;;
-
-  *) as_fn_append ac_config_targets " $1"
-     ac_need_defaults=false ;;
-
-  esac
-  shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
-  exec 6>/dev/null
-  ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-if \$ac_cs_recheck; then
-  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
-  shift
-  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
-  CONFIG_SHELL='$SHELL'
-  export CONFIG_SHELL
-  exec "\$@"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-  $as_echo "$ac_log"
-} >&5
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
-  case $ac_config_target in
-    "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
-    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-    "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;;
-    "doc/Doxyfile") CONFIG_FILES="$CONFIG_FILES doc/Doxyfile" ;;
-    "examples/Makefile") CONFIG_FILES="$CONFIG_FILES examples/Makefile" ;;
-    "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;;
-
-  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
-  esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used.  Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
-fi
-
-# Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
-  tmp= ac_tmp=
-  trap 'exit_status=$?
-  : "${ac_tmp:=$tmp}"
-  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
-' 0
-  trap 'as_fn_exit 1' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
-  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
-  test -d "$tmp"
-}  ||
-{
-  tmp=./conf$$-$RANDOM
-  (umask 077 && mkdir "$tmp")
-} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
-ac_tmp=$tmp
-
-# Set up the scripts for CONFIG_FILES section.
-# No need to generate them if there are no CONFIG_FILES.
-# This happens for instance with `./config.status config.h'.
-if test -n "$CONFIG_FILES"; then
-
-
-ac_cr=`echo X | tr X '\015'`
-# On cygwin, bash can eat \r inside `` if the user requested igncr.
-# But we know of no other shell where ac_cr would be empty at this
-# point, so we can use a bashism as a fallback.
-if test "x$ac_cr" = x; then
-  eval ac_cr=\$\'\\r\'
-fi
-ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
-if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
-  ac_cs_awk_cr='\\r'
-else
-  ac_cs_awk_cr=$ac_cr
-fi
-
-echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
-_ACEOF
-
-
-{
-  echo "cat >conf$$subs.awk <<_ACEOF" &&
-  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
-  echo "_ACEOF"
-} >conf$$subs.sh ||
-  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
-ac_delim='%!_!# '
-for ac_last_try in false false false false false :; do
-  . ./conf$$subs.sh ||
-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-
-  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
-  if test $ac_delim_n = $ac_delim_num; then
-    break
-  elif $ac_last_try; then
-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-rm -f conf$$subs.sh
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
-_ACEOF
-sed -n '
-h
-s/^/S["/; s/!.*/"]=/
-p
-g
-s/^[^!]*!//
-:repl
-t repl
-s/'"$ac_delim"'$//
-t delim
-:nl
-h
-s/\(.\{148\}\)..*/\1/
-t more1
-s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
-p
-n
-b repl
-:more1
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t nl
-:delim
-h
-s/\(.\{148\}\)..*/\1/
-t more2
-s/["\\]/\\&/g; s/^/"/; s/$/"/
-p
-b
-:more2
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t delim
-' <conf$$subs.awk | sed '
-/^[^""]/{
-  N
-  s/\n//
-}
-' >>$CONFIG_STATUS || ac_write_fail=1
-rm -f conf$$subs.awk
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACAWK
-cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
-  for (key in S) S_is_set[key] = 1
-  FS = "\a"
-
-}
-{
-  line = $ 0
-  nfields = split(line, field, "@")
-  substed = 0
-  len = length(field[1])
-  for (i = 2; i < nfields; i++) {
-    key = field[i]
-    keylen = length(key)
-    if (S_is_set[key]) {
-      value = S[key]
-      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
-      len += length(value) + length(field[++i])
-      substed = 1
-    } else
-      len += 1 + keylen
-  }
-
-  print line
-}
-
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
-  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
-else
-  cat
-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
-  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
-_ACEOF
-
-# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
-# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[         ]*VPATH[        ]*=[    ]*/{
-h
-s///
-s/^/:/
-s/[     ]*$/:/
-s/:\$(srcdir):/:/g
-s/:\${srcdir}:/:/g
-s/:@srcdir@:/:/g
-s/^:*//
-s/:*$//
-x
-s/\(=[  ]*\).*/\1/
-G
-s/\n//
-s/^[^=]*=[      ]*$//
-}'
-fi
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-fi # test -n "$CONFIG_FILES"
-
-# Set up the scripts for CONFIG_HEADERS section.
-# No need to generate them if there are no CONFIG_HEADERS.
-# This happens for instance with `./config.status Makefile'.
-if test -n "$CONFIG_HEADERS"; then
-cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
-BEGIN {
-_ACEOF
-
-# Transform confdefs.h into an awk script `defines.awk', embedded as
-# here-document in config.status, that substitutes the proper values into
-# config.h.in to produce config.h.
-
-# Create a delimiter string that does not exist in confdefs.h, to ease
-# handling of long lines.
-ac_delim='%!_!# '
-for ac_last_try in false false :; do
-  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
-  if test -z "$ac_tt"; then
-    break
-  elif $ac_last_try; then
-    as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-
-# For the awk script, D is an array of macro values keyed by name,
-# likewise P contains macro parameters if any.  Preserve backslash
-# newline sequences.
-
-ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
-sed -n '
-s/.\{148\}/&'"$ac_delim"'/g
-t rset
-:rset
-s/^[    ]*#[    ]*define[       ][      ]*/ /
-t def
-d
-:def
-s/\\$//
-t bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[    ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3"/p
-s/^ \('"$ac_word_re"'\)[        ]*\(.*\)/D["\1"]=" \2"/p
-d
-:bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[    ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3\\\\\\n"\\/p
-t cont
-s/^ \('"$ac_word_re"'\)[        ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p
-t cont
-d
-:cont
-n
-s/.\{148\}/&'"$ac_delim"'/g
-t clear
-:clear
-s/\\$//
-t bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/"/p
-d
-:bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
-b cont
-' <confdefs.h | sed '
-s/'"$ac_delim"'/"\\\
-"/g' >>$CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-  for (key in D) D_is_set[key] = 1
-  FS = "\a"
-}
-/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
-  line = \$ 0
-  split(line, arg, " ")
-  if (arg[1] == "#") {
-    defundef = arg[2]
-    mac1 = arg[3]
-  } else {
-    defundef = substr(arg[1], 2)
-    mac1 = arg[2]
-  }
-  split(mac1, mac2, "(") #)
-  macro = mac2[1]
-  prefix = substr(line, 1, index(line, defundef) - 1)
-  if (D_is_set[macro]) {
-    # Preserve the white space surrounding the "#".
-    print prefix "define", macro P[macro] D[macro]
-    next
-  } else {
-    # Replace #undef with comments.  This is necessary, for example,
-    # in the case of _POSIX_SOURCE, which is predefined and required
-    # on some systems where configure will not decide to define it.
-    if (defundef == "undef") {
-      print "/*", prefix defundef, macro, "*/"
-      next
-    }
-  }
-}
-{ print }
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
-fi # test -n "$CONFIG_HEADERS"
-
-
-eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "
-shift
-for ac_tag
-do
-  case $ac_tag in
-  :[FHLC]) ac_mode=$ac_tag; continue;;
-  esac
-  case $ac_mode$ac_tag in
-  :[FHL]*:*);;
-  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
-  :[FH]-) ac_tag=-:-;;
-  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
-  esac
-  ac_save_IFS=$IFS
-  IFS=:
-  set x $ac_tag
-  IFS=$ac_save_IFS
-  shift
-  ac_file=$1
-  shift
-
-  case $ac_mode in
-  :L) ac_source=$1;;
-  :[FH])
-    ac_file_inputs=
-    for ac_f
-    do
-      case $ac_f in
-      -) ac_f="$ac_tmp/stdin";;
-      *) # Look for the file first in the build tree, then in the source tree
-        # (if the path is not absolute).  The absolute path cannot be DOS-style,
-        # because $ac_f cannot contain `:'.
-        test -f "$ac_f" ||
-          case $ac_f in
-          [\\/$]*) false;;
-          *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
-          esac ||
-          as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
-      esac
-      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
-      as_fn_append ac_file_inputs " '$ac_f'"
-    done
-
-    # Let's still pretend it is `configure' which instantiates (i.e., don't
-    # use $as_me), people would be surprised to read:
-    #    /* config.h.  Generated by config.status.  */
-    configure_input='Generated from '`
-         $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
-       `' by configure.'
-    if test x"$ac_file" != x-; then
-      configure_input="$ac_file.  $configure_input"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
-$as_echo "$as_me: creating $ac_file" >&6;}
-    fi
-    # Neutralize special characters interpreted by sed in replacement strings.
-    case $configure_input in #(
-    *\&* | *\|* | *\\* )
-       ac_sed_conf_input=`$as_echo "$configure_input" |
-       sed 's/[\\\\&|]/\\\\&/g'`;; #(
-    *) ac_sed_conf_input=$configure_input;;
-    esac
-
-    case $ac_tag in
-    *:-:* | *:-) cat >"$ac_tmp/stdin" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
-    esac
-    ;;
-  esac
-
-  ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$ac_file" : 'X\(//\)[^/]' \| \
-        X"$ac_file" : 'X\(//\)$' \| \
-        X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-  as_dir="$ac_dir"; as_fn_mkdir_p
-  ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
-  case $ac_mode in
-  :F)
-  #
-  # CONFIG_FILE
-  #
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-ac_sed_dataroot='
-/datarootdir/ {
-  p
-  q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p'
-case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-  ac_datarootdir_hack='
-  s&@datadir@&$datadir&g
-  s&@docdir@&$docdir&g
-  s&@infodir@&$infodir&g
-  s&@localedir@&$localedir&g
-  s&@mandir@&$mandir&g
-  s&\\\${datarootdir}&$datarootdir&g' ;;
-esac
-_ACEOF
-
-# Neutralize VPATH when `$srcdir' = `.'.
-# Shell code in configure.ac might set extrasub.
-# FIXME: do we really want to maintain this feature?
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_sed_extra="$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s|@configure_input@|$ac_sed_conf_input|;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@top_build_prefix@&$ac_top_build_prefix&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-$ac_datarootdir_hack
-"
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
-  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
-  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
-  { ac_out=`sed -n '/^[         ]*datarootdir[  ]*:*=/p' \
-      "$ac_tmp/out"`; test -z "$ac_out"; } &&
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&5
-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&2;}
-
-  rm -f "$ac_tmp/stdin"
-  case $ac_file in
-  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
-  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
-  esac \
-  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- ;;
-  :H)
-  #
-  # CONFIG_HEADER
-  #
-  if test x"$ac_file" != x-; then
-    {
-      $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
-    } >"$ac_tmp/config.h" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
-$as_echo "$as_me: $ac_file is unchanged" >&6;}
-    else
-      rm -f "$ac_file"
-      mv "$ac_tmp/config.h" "$ac_file" \
-       || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    fi
-  else
-    $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
-      || as_fn_error $? "could not create -" "$LINENO" 5
-  fi
- ;;
-
-
-  esac
-
-done # for ac_tag
-
-
-as_fn_exit 0
-_ACEOF
-ac_clean_files=$ac_clean_files_save
-
-test $ac_write_fail = 0 ||
-  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
-
-
-# configure is writing to config.log, and then calls config.status.
-# config.status does its own redirection, appending to config.log.
-# Unfortunately, on DOS this fails, as config.log is still kept open
-# by configure, so config.status won't be able to write to it; its
-# output is simply discarded.  So we exec the FD to /dev/null,
-# effectively closing config.log, so it can be properly (re)opened and
-# appended to by config.status.  When coming back to configure, we
-# need to make the FD available again.
-if test "$no_create" != yes; then
-  ac_cs_success=:
-  ac_config_status_args=
-  test "$silent" = yes &&
-    ac_config_status_args="$ac_config_status_args --quiet"
-  exec 5>/dev/null
-  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
-  exec 5>>config.log
-  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
-  # would make configure fail if this is the last instruction.
-  $ac_cs_success || as_fn_exit 1
-fi
-if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
-$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
-fi
-
index 77f6c8f..86881ab 100644 (file)
@@ -96,3 +96,4 @@ AC_CONFIG_FILES([Makefile
                  examples/Makefile
                  tests/Makefile])
 AC_OUTPUT
+
index eedf247..df9ae7b 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
@@ -81,12 +81,12 @@ print_timestamp(char *s, size_t len, coap_tick_t t)
 #ifndef NDEBUG
 
 #ifndef HAVE_STRNLEN
-/** 
- * A length-safe strlen() fake. 
- * 
+/**
+ * A length-safe strlen() fake.
+ *
  * @param s      The string to count characters != 0.
  * @param maxlen The maximum length of @p s.
- * 
+ *
  * @return The length of @p s.
  */
 static inline size_t
@@ -148,7 +148,11 @@ size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, si
 {
 #ifdef HAVE_ARPA_INET_H
     const void *addrptr = NULL;
+#if defined(__ANDROID__)
+    __uint16_t port;
+#else
     in_port_t port;
+#endif
     unsigned char *p = buf;
 
     switch (addr->addr.sa.sa_family)
@@ -341,6 +345,14 @@ coap_show_pdu(const coap_pdu_t *pdu)
 
 #endif /* NDEBUG */
 
+#ifdef WITH_ARDUINO
+void coap_log_impl(coap_log_t level, const char *format, ...)
+{
+    //TODO: Implement logging functionalities for Arduino
+}
+#endif
+
+#ifndef WITH_ARDUINO
 #ifndef WITH_CONTIKI
 void coap_log_impl(coap_log_t level, const char *format, ...)
 {
@@ -389,3 +401,4 @@ coap_log_impl(coap_log_t level, const char *format, ...)
     va_end(ap);
 }
 #endif /* WITH_CONTIKI */
+#endif
index 708ffc2..4c55054 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_DEBUG_H_
@@ -36,7 +36,7 @@ coap_log_t coap_get_log_level();
 /** Sets the log level to the specified value. */
 void coap_set_log_level(coap_log_t level);
 
-/** 
+/**
  * Writes the given text to @c COAP_ERR_FD (for @p level <= @c
  * LOG_CRIT) or @c COAP_DEBUG_FD (for @p level >= @c LOG_WARNING). The
  * text is output only when @p level is below or equal to the log
@@ -59,6 +59,8 @@ void coap_log_impl(coap_log_t level, const char *format, ...);
 void coap_show_pdu(const coap_pdu_t *);
 
 struct coap_address_t;
+unsigned int print_readable(const unsigned char *data, unsigned int len, unsigned char *result,
+        unsigned int buflen, int encode_always);
 size_t coap_print_addr(const struct coap_address_t *, unsigned char *, size_t);
 
 #else
index 9e70ea8..86a5b89 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef NDEBUG
index e58cad6..b9b304e 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_ENCODE_H_
 #if (BSD >= 199103) || defined(WITH_CONTIKI)
 # include <string.h>
 #else
+#ifndef WITH_ARDUINO
 # include <strings.h>
 #endif
+#endif
 
 #define Nn 8  /* duplicate definition of N if built on sky motes */
 #define E 4
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile
deleted file mode 100644 (file)
index 9f93ca3..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-# Makefile for libcoap
-#
-# Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
-#
-# This file is part of the CoAP library libcoap. Please see
-# README for terms of use. 
-
-# the library's version
-VERSION:=4.1.1
-
-# tools
-
-SHELL = /bin/sh
-MKDIR = mkdir
-
-abs_builddir = /connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1/examples
-top_builddir = ..
-top_srcdir = ..
-# files and flags
-PROGRAMS:=coap-server coap-client rd etsi_iot_01 #tiny
-SOURCES:= tiny.c client.c server.c rd.c etsi_iot_01.c
-OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
-#CFLAGS:=-g -Wall -ansi -pedantic -I..
-CFLAGS:=-g -Wall -g -O2
-CPPFLAGS:=-I$(top_srcdir)  -DWITH_POSIX
-DISTDIR?=$(top_builddir)/libcoap-4.1.1
-FILES:=Makefile.in $(SOURCES)
-LDFLAGS:=-L$(top_builddir)
-LDLIBS:=-lcoap 
-libcoap =$(top_builddir)/libcoap.a
-
-.PHONY: clean distclean
-
-.SUFFIXES:
-.SUFFIXES:      .c .o
-
-all:   $(PROGRAMS)
-
-check: 
-       echo DISTDIR: $(DISTDIR)
-       echo top_builddir: $(top_builddir)
-
-tiny:  tiny.o $(libcoap)
-       $(CC) -o $@ $< $(LDFLAGS)
-
-coap-client: client.o $(libcoap)
-       $(CC) -o $@ $< $(LDFLAGS) $(LDLIBS)
-
-coap-server:   server.o $(libcoap)
-       $(CC) -o $@ $< $(LDFLAGS) $(LDLIBS)
-
-clean:
-       @rm -f $(PROGRAMS) $(OBJECTS)
-
-distclean:     clean
-       @rm -rf $(DISTDIR)
-       @rm -f *~ 
-
-dist:  $(FILES)
-       test -d $(DISTDIR)/examples || mkdir $(DISTDIR)/examples
-       cp $(FILES) $(DISTDIR)/examples
index 80445ad..a2dfb14 100644 (file)
@@ -59,3 +59,4 @@ distclean:    clean
 dist:  $(FILES)
        test -d $(DISTDIR)/examples || mkdir $(DISTDIR)/examples
        cp $(FILES) $(DISTDIR)/examples
+
index 72a0908..89d27ff 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
@@ -284,10 +284,10 @@ get_block(coap_pdu_t *pdu, coap_opt_iterator_t *opt_iter)
     return coap_option_next(opt_iter);
 }
 
-#define HANDLE_BLOCK1(Pdu)                                             \
-  ((method == COAP_REQUEST_PUT || method == COAP_REQUEST_POST) &&      \
-   ((flags & FLAGS_BLOCK) == 0) &&                                     \
-   ((Pdu)->hdr->code == COAP_RESPONSE_CODE(201) ||                     \
+#define HANDLE_BLOCK1(Pdu)                      \
+  ((method == COAP_REQUEST_PUT || method == COAP_REQUEST_POST) &&   \
+   ((flags & FLAGS_BLOCK) == 0) &&                  \
+   ((Pdu)->hdr->code == COAP_RESPONSE_CODE(201) ||          \
     (Pdu)->hdr->code == COAP_RESPONSE_CODE(204)))
 
 inline int check_token(coap_pdu_t *received)
@@ -761,7 +761,7 @@ int cmdline_blocksize(char *arg)
     return 1;
 }
 
-/* Called after processing the options from the commandline to set 
+/* Called after processing the options from the commandline to set
  * Block1 or Block2 depending on method. */
 void set_blocksize()
 {
index 83f582e..ba68c0e 100644 (file)
@@ -37,7 +37,7 @@ static int quit = 0;
 
 #define COAP_OPT_BLOCK_SZX_MAX 6 /**< allowed maximum for block szx value */
 
-#define REQUIRE_ETAG 0x01      /* flag for coap_payload_t: require ETag option  */
+#define REQUIRE_ETAG 0x01   /* flag for coap_payload_t: require ETag option  */
 typedef struct
 {
     UT_hash_handle hh;
@@ -76,7 +76,7 @@ void handle_sigint(int signum)
 }
 
 #define INDEX "libcoap server for ETSI CoAP Plugtest, March 2012, Paris\n" \
-             "Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>\n\n"
+          "Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>\n\n"
 
 coap_payload_t *
 coap_new_payload(size_t size)
index 0cc97d2..11e01ca 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 /**
index 0d3e055..09b2fdc 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <string.h>
@@ -54,7 +54,7 @@ void handle_sigint(int signum)
 }
 
 #define INDEX "This is a test server made with libcoap (see http://libcoap.sf.net)\n" \
-             "Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>\n\n"
+          "Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>\n\n"
 
 void hnd_get_index(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer,
         coap_pdu_t *request, str *token, coap_pdu_t *response)
index 9ccee12..7b7d437 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <string.h>
index a794292..30447e6 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "hashkey.h"
index 4732a70..5ed5e03 100644 (file)
@@ -3,10 +3,10 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
-/** 
+/**
  * @file hashkey.h
  * @brief definition of hash key type and helper functions
  */
 typedef unsigned char coap_key_t[4];
 
 #ifndef coap_hash
-/** 
+/**
  * Calculates a fast hash over the given string @p s of length @p len
  * and stores the result into @p h. Depending on the exact
  * implementation, this function cannot be used as one-way function to
  * check message integrity or simlar.
- * 
+ *
  * @param s   The string used for hash calculation.
  * @param len The length of @p s.
  * @param h   The result buffer to store the calculated hash key.
@@ -40,18 +40,18 @@ void coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h);
 #undef __COAP_DEFAULT_HASH
 #endif /* coap_hash */
 
-/** 
+/**
  * Calls coap_hash() with given @c str object as parameter.
- * 
+ *
  * @param Str Must contain a pointer to a coap string object.
  * @param H   A coap_key_t object to store the result.
- * 
+ *
  * @hideinitializer
  */
-#define coap_str_hash(Str,H) {                 \
-    assert(Str);                               \
-    memset((H), 0, sizeof(coap_key_t));                \
-    coap_hash((H), (Str)->s, (Str)->length);   \
+#define coap_str_hash(Str,H) {          \
+    assert(Str);                \
+    memset((H), 0, sizeof(coap_key_t));     \
+    coap_hash((H), (Str)->s, (Str)->length);    \
   }
 
 #endif /* _COAP_HASHKEY_H_ */
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/makefile_arduino.mak b/resource/csdk/connectivity/lib/libcoap-4.1.1/makefile_arduino.mak
new file mode 100644 (file)
index 0000000..e12a01e
--- /dev/null
@@ -0,0 +1,72 @@
+# override with `make BUILD=debug`
+# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
+# default to release build
+# default to build for linux
+BUILD   := release
+#other options are android, arduino
+PLATFORM=linux
+# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
+ARDUINOWIFI := 0
+
+OUT_DIR          := ./$(BUILD)
+OBJ_DIR          := $(OUT_DIR)/obj
+
+ROOT_DIR = ..
+
+# Note for Arduino: The CC flag is set to the C++ compiler since Arduino build 
+# includes Time.h header file which has C++ style definitions.
+ifeq ($(PLATFORM),arduinomega)
+    include $(ROOT_DIR)/arduino/local.properties
+    include $(ROOT_DIR)/arduino/$(PLATFORM).properties
+       CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
+else ifeq ($(PLATFORM),arduinodue)
+    include $(ROOT_DIR)/local.properties
+    include $(ROOT_DIR)/$(PLATFORM).properties
+       CC=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-g++
+else
+   $(error Wrong value for PLATFORM !!)
+endif
+
+CC_FLAGS.debug := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions -pedantic \
+-DTB_LOG
+CC_FLAGS.release := -Os -Wall -ffunction-sections -fdata-sections -fno-exceptions
+
+SOURCES:= pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \
+          str.c option.c async.c subscribe.c block.c
+#VPATH := $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src:$(RANDOM_DIR)/src
+ifeq (arduino, $(findstring arduino,$(PLATFORM)))
+       SOURCESCPP:= Time.cpp
+       OBJECTSCPP:= $(patsubst %.cpp, %.o, $(SOURCESCPP))
+       VPATH += $(SDIR_ARD_TIME)
+endif
+
+OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
+
+all: prep_dirs libcoap.a
+
+prep_dirs:
+       -mkdir $(OUT_DIR)
+       -mkdir $(OBJ_DIR)
+
+%.o: %.c
+       $(CC) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+%.o: %.cpp
+       $(CCPLUS) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+libcoap.a: $(OBJECTS) $(OBJECTSCPP)
+       $(AR) rcs $(OUT_DIR)/$@ $(addprefix $(OBJ_DIR)/,$^)
+       $(RANLIB) $(OUT_DIR)/$@
+
+.PHONY: clean
+
+clean: legacy_clean
+       -rm -rf release
+       -rm -rf debug
+       
+#There is no installation in LibCoap.
+install: all
+       
+legacy_clean:
+       rm -f *.o libcoap.a
+
index a84405e..475df6a 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_MEM_H_
index 7138f4a..02bc6ec 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
@@ -18,7 +18,9 @@
 #elif HAVE_SYS_UNISTD_H
 #include <sys/unistd.h>
 #endif
+#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
+#endif
 #ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
@@ -45,9 +47,9 @@
 #include "block.h"
 #include "net.h"
 
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
 
-time_t clock_offset;
+time_t clock_offset=0;
 
 static inline coap_queue_t *
 coap_malloc_node()
@@ -60,7 +62,7 @@ coap_free_node(coap_queue_t *node)
 {
     coap_free(node);
 }
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_LWIP
 
 #include <lwip/memp.h>
@@ -135,8 +137,7 @@ static void received_package(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip
     context->pending_address.addr = addr->addr; /* FIXME: this has to become address-type independent, probably there'll be an lwip function for that */
     context->pending_port = port;
 
-    char* data;
-    coap_read(context, data);
+    coap_read(context);
 }
 
 #endif /* WITH_LWIP */
@@ -296,7 +297,7 @@ coap_pop_next(coap_context_t *context)
 
 #ifdef COAP_DEFAULT_WKC_HASHKEY
 /** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */
-#define is_wkc(Key)                                                    \
+#define is_wkc(Key)                         \
   (memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0)
 #else
 /* Implements a singleton to store a hash key for the .wellknown/core
@@ -315,10 +316,12 @@ is_wkc(coap_key_t k)
 }
 #endif
 
+
+#ifndef WITH_ARDUINO
 coap_context_t *
 coap_new_context(const coap_address_t *listen_addr)
 {
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX)
     coap_context_t *c = coap_malloc( sizeof( coap_context_t ) );
     int reuse = 1;
 #endif /* WITH_POSIX */
@@ -380,7 +383,7 @@ coap_new_context(const coap_address_t *listen_addr)
     coap_register_option(c, COAP_OPTION_BLOCK2);
     coap_register_option(c, COAP_OPTION_BLOCK1);
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
     if ( c->sockfd < 0 )
     {
@@ -413,7 +416,7 @@ coap_new_context(const coap_address_t *listen_addr)
     coap_free( c );
     return NULL;
 
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
     c->conn = udp_new(NULL, 0, NULL);
     udp_bind(c->conn, listen_addr->port);
@@ -462,7 +465,7 @@ void coap_free_context(coap_context_t *context)
     coap_retransmittimer_restart(context);
 #endif
 
-#if defined(WITH_POSIX) || defined(WITH_LWIP)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
 #ifdef COAP_RESOURCES_NOHASH
     LL_FOREACH(context->resources, res)
     {
@@ -488,7 +491,7 @@ void coap_free_context(coap_context_t *context)
     initialized = 0;
 #endif /* WITH_CONTIKI */
 }
-
+#endif //ifndef WITH_ARDUINO
 int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, coap_opt_filter_t unknown)
 {
 
@@ -548,6 +551,11 @@ void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap
         return;
     }
 #endif
+
+#ifdef WITH_ARDUINO
+    coap_hash((const unsigned char *)peer->addr, peer->size, h);
+#endif /* WITH_ARDUINO */
+
 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
     /* FIXME: with lwip, we can do better */
     coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h);
@@ -576,16 +584,23 @@ coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst, coa
     return result;
 }
 
-#ifdef WITH_POSIX
+#if defined(WITH_ARDUINO)
+coap_tid_t
+coap_send_impl(coap_context_t *context,
+               const coap_address_t *dst,
+               coap_pdu_t *pdu)
+{
+    return 0;
+}
+#endif
+
+#if defined(WITH_POSIX)
 /* releases space allocated by PDU if free_pdu is set */
 coap_tid_t
 coap_send_impl(coap_context_t *context,
         const coap_address_t *dst,
         coap_pdu_t *pdu)
 {
-
-    char* z = inet_ntoa(*(struct in_addr *)&(dst->addr));
-
     ssize_t bytes_written;
     coap_tid_t id = COAP_INVALID_TID;
 
@@ -606,7 +621,7 @@ coap_send_impl(coap_context_t *context,
 
     return id;
 }
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
 /* releases space allocated by PDU if free_pdu is set */
 coap_tid_t
@@ -688,7 +703,9 @@ coap_send_impl(coap_context_t *context,
 
 coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu)
 {
+#ifndef WITH_ARDUINO
     return coap_send_impl(context, dst, pdu);
+#endif
 }
 
 coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request, const coap_address_t *dst,
@@ -826,7 +843,7 @@ coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
 
     /* no more retransmissions, remove node from system */
 
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(WITH_ARDUINO)
     debug("** removed transaction %d\n", ntohs(node->id));
 #endif
 
@@ -865,9 +882,10 @@ static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
     return 0;
 }
 
-int coap_read(coap_context_t *ctx, char* data)
+#ifndef WITH_ARDUINO
+int coap_read(coap_context_t *ctx)
 {
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX)
     static char buf[COAP_MAX_PDU_SIZE];
 #endif
 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
@@ -891,10 +909,10 @@ int coap_read(coap_context_t *ctx, char* data)
 
     coap_address_init(&src);
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX)
     bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0, &src.addr.sa, &src.size);
 
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
     if(uip_newdata())
     {
@@ -991,6 +1009,7 @@ int coap_read(coap_context_t *ctx, char* data)
 #endif
     return -1;
 }
+#endif //#ifndef WITH_ARDUINO
 
 int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node)
 {
@@ -1050,7 +1069,7 @@ static inline int token_match(const unsigned char *a, size_t alen, const unsigne
 void coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst,
         const unsigned char *token, size_t token_length)
 {
-    /* cancel all messages in sendqueue that are for dst 
+    /* cancel all messages in sendqueue that are for dst
      * and use the specified token */
     coap_queue_t *p, *q;
 
@@ -1269,7 +1288,7 @@ wellknown_response(coap_context_t *context, coap_pdu_t *request)
         need_block2 = 1;
     }
 
-    /* Check if there is sufficient space to add Content-Format option 
+    /* Check if there is sufficient space to add Content-Format option
      * and data. We do this before adding the Content-Format option to
      * avoid sending error responses with that option but no actual
      * content. */
@@ -1346,7 +1365,7 @@ wellknown_response(coap_context_t *context, coap_pdu_t *request)
     return resp;
 }
 
-#define WANT_WKC(Pdu,Key)                                      \
+#define WANT_WKC(Pdu,Key)                   \
   (((Pdu)->hdr->code == COAP_REQUEST_GET) && is_wkc(Key))
 
 void handle_request(coap_context_t *context, coap_queue_t *node, const char* responseData)
@@ -1429,8 +1448,7 @@ void handle_request(coap_context_t *context, coap_queue_t *node, const char* res
             str token =
             { node->pdu->hdr->token_length, node->pdu->hdr->token };
 
-            //h(context, resource, &node->remote, 
-            //node->pdu, &token, response);
+            h(context, resource, &node->remote, node->pdu, &token, response);
 
             unsigned char buf[3];
             response->hdr->code = COAP_RESPONSE_CODE(205);
@@ -1519,7 +1537,7 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
         str token =
         { 0, NULL };
 
-        /* remove observer for this resource, if any 
+        /* remove observer for this resource, if any
          * get token from sent and try to find a matching resource. Uh!
          */
 
@@ -1547,7 +1565,7 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
             }
         }
 #endif /* WITH_CONTIKI */
-#endif /* WITOUT_OBSERVE */  
+#endif /* WITOUT_OBSERVE */
     }
 
     void coap_dispatch(coap_context_t *context, const char* responseData)
@@ -1584,7 +1602,7 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
                     if (rcvd->pdu->hdr->code == 0)
                         goto cleanup;
 
-                    /* FIXME: if sent code was >= 64 the message might have been a 
+                    /* FIXME: if sent code was >= 64 the message might have been a
                      * notification. Then, we must flag the observer to be alive
                      * by setting obs->fail_cnt = 0. */
                     if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->code) == 2)
@@ -1618,7 +1636,7 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
                     if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0)
                     {
 
-                        /* FIXME: send response only if we have received a request. Otherwise, 
+                        /* FIXME: send response only if we have received a request. Otherwise,
                          * send RST. */
                         response = coap_new_error_response(rcvd->pdu, COAP_RESPONSE_CODE(402),
                                 opt_filter);
index 254b2b4..725bbc4 100644 (file)
@@ -3,12 +3,16 @@
  * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_NET_H_
 #define _COAP_NET_H_
 
+#ifdef WITH_ARDUINO
+#include "Time.h"
+#endif /* WITH_ARDUINO */
+
 #ifdef __cplusplus
 extern "C"
 {
@@ -104,14 +108,14 @@ extern "C"
         /** list of asynchronous transactions */
         struct coap_async_state_t *async_state;
 #endif /* WITHOUT_ASYNC */
-        /**
-         * The time stamp in the first element of the sendqeue is relative
-         * to sendqueue_basetime. */
-        coap_tick_t sendqueue_basetime;
-        coap_queue_t *sendqueue, *recvqueue;
-#if WITH_POSIX
-        int sockfd; /**< send/receive socket */
-#endif /* WITH_POSIX */
+    /**
+     * The time stamp in the first element of the sendqeue is relative
+     * to sendqueue_basetime. */
+    coap_tick_t sendqueue_basetime;
+    coap_queue_t *sendqueue, *recvqueue;
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+    int sockfd; /**< send/receive socket */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
         struct uip_udp_conn *conn; /**< uIP connection object */
 
@@ -146,8 +150,8 @@ extern "C"
 
     /**
      * Registers a new message handler that is called whenever a response
-     * was received that matches an ongoing transaction. 
-     * 
+     * was received that matches an ongoing transaction.
+     *
      * @param context The context to register the handler for.
      * @param handler The response handler to register.
      */
@@ -157,10 +161,10 @@ extern "C"
         context->response_handler = handler;
     }
 
-    /** 
+    /**
      * Registers the option type @p type with the given context object @p
      * ctx.
-     * 
+     *
      * @param ctx  The context to use.
      * @param type The option type to register.
      */
@@ -185,20 +189,23 @@ extern "C"
     /** Creates a new coap_context_t object that will hold the CoAP stack status.  */
     coap_context_t *coap_new_context(const coap_address_t *listen_addr);
 
-    /** 
-     * Returns a new message id and updates @p context->message_id
-     * accordingly. The message id is returned in network byte order
-     * to make it easier to read in tracing tools. 
-     *
-     * @param context the current coap_context_t object
-     * @return incremented message id in network byte order
-     */
-    static inline unsigned short coap_new_message_id(coap_context_t *context)
-    {
-#ifndef WITH_CONTIKI
-        return htons(++(context->message_id));
+/**
+ * Returns a new message id and updates @p context->message_id
+ * accordingly. The message id is returned in network byte order
+ * to make it easier to read in tracing tools.
+ *
+ * @param context the current coap_context_t object
+ * @return incremented message id in network byte order
+ */
+static inline unsigned short coap_new_message_id(coap_context_t *context)
+{
+    ++(context->message_id);
+#if defined(WITH_ARDUINO)
+    return ((context->message_id << 8) | ((context->message_id >> 8) & (0xFF)));
+#elif defined(WITH_CONTIKI)
+    return uip_htons(context->message_id);
 #else /* WITH_CONTIKI */
-        return uip_htons(++context->message_id);
+    return htons(context->message_id);
 #endif
     }
 
@@ -218,7 +225,7 @@ extern "C"
     coap_tid_t coap_send_confirmed(coap_context_t *context, const coap_address_t *dst,
             coap_pdu_t *pdu);
 
-    /** 
+    /**
      * Creates a new ACK PDU with specified error @p code. The options
      * specified by the filter expression @p opts will be copied from the
      * original request contained in @p request.  Unless @c
@@ -227,12 +234,12 @@ extern "C"
      * 0.  This function returns a pointer to the new response message, or
      * @c NULL on error. The storage allocated for the new message must be
      * relased with coap_free().
-     * 
+     *
      * @param request Specification of the received (confirmable) request.
      * @param code The error code to set.
      * @param opts An option filter that specifies which options to copy
      *             from the original request in @p node.
-     * 
+     *
      * @return A pointer to the new message or @c NULL on error.
      */
     coap_pdu_t *coap_new_error_response(coap_pdu_t *request, unsigned char code,
@@ -249,27 +256,27 @@ extern "C"
      */
     coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu);
 
-    /** 
+    /**
      * Sends an error response with code @p code for request @p request to
      * @p dst.  @p opts will be passed to coap_new_error_response() to
      * copy marked options from the request. This function returns the
      * transaction id if the message was sent, or @c COAP_INVALID_TID
      * otherwise.
-     * 
+     *
      * @param context The context to use.
      * @param request The original request to respond to.
      * @param dst     The remote peer that sent the request.
      * @param code    The reponse code.
-     * @param opts    A filter that specifies the options to copy from the 
+     * @param opts    A filter that specifies the options to copy from the
      *                @p request.
-     * 
+     *
      * @return The transaction id if the message was sent, or @c
      * COAP_INVALID_TID otherwise.
      */
     coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request,
             const coap_address_t *dst, unsigned char code, coap_opt_filter_t opts);
 
-    /** 
+    /**
      * Helper funktion to create and send a message with @p type (usually
      * ACK or RST).  This function returns @c COAP_INVALID_TID when the
      * message was not sent, a valid transaction id otherwise.
@@ -283,30 +290,30 @@ extern "C"
     coap_tid_t
     coap_send_message_type(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *request,
             unsigned char type);
-    /** 
+    /**
      * Sends an ACK message with code @c 0 for the specified @p request to
      * @p dst. This function returns the corresponding transaction id if
      * the message was sent or @c COAP_INVALID_TID on error.
-     * 
+     *
      * @param context The context to use.
      * @param dst     The destination address.
      * @param request The request to be acknowledged.
-     * 
+     *
      * @return The transaction id if ACK was sent or @c COAP_INVALID_TID
      * on error.
      */
     coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst,
             coap_pdu_t *request);
 
-    /** 
+    /**
      * Sends an RST message with code @c 0 for the specified @p request to
      * @p dst. This function returns the corresponding transaction id if
      * the message was sent or @c COAP_INVALID_TID on error.
-     * 
+     *
      * @param context The context to use.
      * @param dst     The destination address.
      * @param request The request to be reset.
-     * 
+     *
      * @return The transaction id if RST was sent or @c COAP_INVALID_TID
      * on error.
      */
@@ -324,9 +331,9 @@ extern "C"
      * and a new node with the parsed PDU is added to the receive queue in the specified context
      * object.
      */
-    int coap_read(coap_context_t *context, char* data);
+    int coap_read(coap_context_t *context);
 
-    /** 
+    /**
      * Calculates a unique transaction id from given arguments @p peer and
      * @p pdu. The id is returned in @p id.
      * 
@@ -336,33 +343,33 @@ extern "C"
      */
     void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap_tid_t *id);
 
-    /** 
+    /**
      * This function removes the element with given @p id from the list
      * given list. If @p id was found, @p node is updated to point to the
-     * removed element. Note that the storage allocated by @p node is 
+     * removed element. Note that the storage allocated by @p node is
      * @b not released. The caller must do this manually using
      * coap_delete_node(). This function returns @c 1 if the element with
      * id @p id was found, @c 0 otherwise. For a return value of @c 0,
      * the contents of @p node is undefined.
-     * 
+     *
      * @param queue The queue to search for @p id.
      * @param id    The node id to look for.
-     * @param node  If found, @p node is updated to point to the 
+     * @param node  If found, @p node is updated to point to the
      *   removed node. You must release the storage pointed to by
      *   @p node manually.
-     * 
+     *
      * @return @c 1 if @p id was found, @c 0 otherwise.
      */
     int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node);
 
-    /** 
+    /**
      * Removes the transaction identified by @p id from given @p queue.
      * This is a convenience function for coap_remove_from_queue() with
      * automatic deletion of the removed node.
-     * 
+     *
      * @param queue The queue to search for @p id.
      * @param id    The transaction id.
-     * 
+     *
      * @return @c 1 if node was found, removed and destroyed, @c 0 otherwise.
      */
     inline static int coap_remove_transaction(coap_queue_t **queue, coap_tid_t id)
@@ -384,13 +391,13 @@ extern "C"
     coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_tid_t id);
 
     /**
-     * Cancels all outstanding messages for peer @p dst that have the 
+     * Cancels all outstanding messages for peer @p dst that have the
      * specified token.
      *
      * @param context The context in use
      * @param dst     Destination address of the messages to remove.
      * @param token   Message token
-     * @param token_length Actual length of @p token 
+     * @param token_length Actual length of @p token
      */
     void coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst,
             const unsigned char *token, size_t token_length);
@@ -403,11 +410,11 @@ extern "C"
 
     /**
      * Returns the current value of an internal tick counter. The counter
-     * counts \c COAP_TICKS_PER_SECOND ticks every second. 
+     * counts \c COAP_TICKS_PER_SECOND ticks every second.
      */
     void coap_ticks(coap_tick_t *);
 
-    /** 
+    /**
      * Verifies that @p pdu contains no unknown critical options. Options
      * must be registered at @p ctx, using the function
      * coap_register_option(). A basic set of options is registered
@@ -415,7 +422,7 @@ extern "C"
      * @p pdu is ok, @c 0 otherwise. The given filter object @p unknown
      * will be updated with the unknown options. As only @c COAP_MAX_OPT
      * options can be signalled this way, remaining options must be
-     * examined manually. 
+     * examined manually.
      *
      * @code
      coap_opt_filter_t f = COAP_OPT_NONE;
@@ -430,13 +437,13 @@ extern "C"
      }
      }
      }
-     * @endcode 
+     * @endcode
      *
      * @param ctx      The context where all known options are registered.
      * @param pdu      The PDU to check.
      * @param unknown  The output filter that will be updated to indicate the
      *                 unknown critical options found in @p pdu.
-     * 
+     *
      * @return @c 1 if everything was ok, @c 0 otherwise.
      */
     int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, coap_opt_filter_t unknown);
index c8c8496..3255020 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010-2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
@@ -42,12 +42,12 @@ size_t coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *resul
     assert(opt);
     assert(result);
 
-#define ADVANCE_OPT(o,e,step) if ((e) < step) {                        \
-    debug("cannot advance opt past end\n");                    \
-    return 0;                                                  \
-  } else {                                                     \
-    (e) -= step;                                               \
-    (o) = ((unsigned char *)(o)) + step;                       \
+#define ADVANCE_OPT(o,e,step) if ((e) < step) {         \
+    debug("cannot advance opt past end\n");         \
+    return 0;                           \
+  } else {                          \
+    (e) -= step;                        \
+    (o) = ((unsigned char *)(o)) + step;            \
   }
 
     if (length < 1)
@@ -201,7 +201,7 @@ coap_option_next(coap_opt_iterator_t *oi)
         /* Exit the while loop when:
          *   - no filtering is done at all
          *   - the filter matches for the current option
-         *   - the filter is too small for the current option number 
+         *   - the filter is too small for the current option number
          */
         if (!oi->filtered || (b = coap_option_getb(oi->filter, oi->type)) > 0)
             break;
index 78b2a03..13a97f0 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010-2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 /**
@@ -18,7 +18,7 @@
 #include "bits.h"
 #include "pdu.h"
 
-/** 
+/**
  * Use byte-oriented access methods here because sliding a complex
  * struct coap_opt_t over the data buffer may cause bus error on
  * certain platforms.
@@ -39,7 +39,7 @@ typedef struct
  * function returns the number of bytes that have been parsed, or @c 0
  * on error. An error is signaled when illegal delta or length values
  * are encountered or when option parsing would result in reading past
- * the option (i.e. beyond opt + length). 
+ * the option (i.e. beyond opt + length).
  *
  * @param opt    The beginning of the option to parse.
  * @param length The maximum length of @p opt.
@@ -66,7 +66,7 @@ size_t coap_opt_size(const coap_opt_t *opt);
 
 /**
  * Calculates the beginning of the PDU's option section.
- * 
+ *
  * @param pdu The PDU containing the options.
  * @return A pointer to the first option if available, or @c NULL otherwise.
  */
@@ -85,7 +85,7 @@ coap_opt_t *options_start(coap_pdu_t *pdu);
  * @{
  */
 
-/** 
+/**
  * Fixed-size bit-vector we use for option filtering. It is large
  * enough to hold the highest option number known at build time (20 in
  * the core spec).
@@ -95,9 +95,9 @@ typedef unsigned char coap_opt_filter_t[(COAP_MAX_OPT >> 3) + 1];
 /** Pre-defined filter that includes all options. */
 #define COAP_OPT_ALL NULL
 
-/** 
+/**
  * Clears filter @p f.
- * 
+ *
  * @param f The filter to clear.
  */
 static inline void coap_option_filter_clear(coap_opt_filter_t f)
@@ -105,14 +105,14 @@ static inline void coap_option_filter_clear(coap_opt_filter_t f)
     memset(f, 0, sizeof(coap_opt_filter_t));
 }
 
-/** 
+/**
  * Sets the corresponding bit for @p type in @p filter. This function
  * returns @c 1 if bit was set or @c -1 on error (i.e. when the given
  * type does not fit in the filter).
- * 
+ *
  * @param filter The filter object to change.
- * @param type   The type for which the bit should be set. 
- * 
+ * @param type   The type for which the bit should be set.
+ *
  * @return @c 1 if bit was set, @c -1 otherwise.
  */
 inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short type)
@@ -120,14 +120,14 @@ inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short type
     return bits_setb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
 }
 
-/** 
+/**
  * Clears the corresponding bit for @p type in @p filter. This function
  * returns @c 1 if bit was cleared or @c -1 on error (i.e. when the given
  * type does not fit in the filter).
- * 
+ *
  * @param filter The filter object to change.
- * @param type   The type for which the bit should be cleared. 
- * 
+ * @param type   The type for which the bit should be cleared.
+ *
  * @return @c 1 if bit was set, @c -1 otherwise.
  */
 inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short type)
@@ -135,14 +135,14 @@ inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short type
     return bits_clrb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
 }
 
-/** 
+/**
  * Gets the corresponding bit for @p type in @p filter. This function
  * returns @c 1 if the bit is set @c 0 if not, or @c -1 on error (i.e.
  * when the given type does not fit in the filter).
- * 
+ *
  * @param filter The filter object to read bit from..
  * @param type   The type for which the bit should be read.
- * 
+ *
  * @return @c 1 if bit was set, @c 0 if not, @c -1 on error.
  */
 inline static int coap_option_getb(const coap_opt_filter_t filter, unsigned short type)
@@ -150,7 +150,7 @@ inline static int coap_option_getb(const coap_opt_filter_t filter, unsigned shor
     return bits_getb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
 }
 
-/** 
+/**
  * Iterator to run through PDU options. This object must be
  * initialized with coap_option_iterator_init(). Call
  * coap_option_next() to walk through the list of options until
@@ -176,27 +176,27 @@ typedef struct
     coap_opt_filter_t filter; /**< option filter */
 } coap_opt_iterator_t;
 
-/** 
+/**
  * Initializes the given option iterator @p oi to point to the
  * beginning of the @p pdu's option list. This function returns @p oi
  * on success, @c NULL otherwise (i.e. when no options exist).
  * Note that a length check on the option list must be performed before
  * coap_option_iterator_init() is called.
- * 
+ *
  * @param pdu  The PDU the options of which should be walked through.
  * @param oi   An iterator object that will be initilized.
- * @param filter An optional option type filter. 
- *               With @p type != @c COAP_OPT_ALL, coap_option_next() 
- *               will return only options matching this bitmask. 
+ * @param filter An optional option type filter.
+ *               With @p type != @c COAP_OPT_ALL, coap_option_next()
+ *               will return only options matching this bitmask.
  *               Fence-post options @c 14, @c 28, @c 42, ... are always
  *               skipped.
- * 
+ *
  * @return The iterator object @p oi on success, @c NULL otherwise.
  */
 coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
         const coap_opt_filter_t filter);
 
-/** 
+/**
  * Updates the iterator @p oi to point to the next option. This
  * function returns a pointer to that option or @c NULL if no more
  * options exist. The contents of @p oi will be updated. In
@@ -205,30 +205,30 @@ coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterato
  * oi->option points to the beginning of the current option
  * itself. When advanced past the last option, @c oi->option will be
  * @c NULL.
- * 
+ *
  * Note that options are skipped whose corresponding bits in the
  * filter specified with coap_option_iterator_init() are @c 0. Options
  * with type codes that do not fit in this filter hence will always be
  * returned.
- * 
+ *
  * @param oi The option iterator to update.
- * 
+ *
  * @return The next option or @c NULL if no more options exist.
  */
 coap_opt_t *coap_option_next(coap_opt_iterator_t *oi);
 
-/** 
+/**
  * Retrieves the first option of type @p type from @p pdu. @p oi must
  * point to a coap_opt_iterator_t object that will be initialized by
  * this function to filter only options with code @p type. This
  * function returns the first option with this type, or @c NULL if not
  * found.
- * 
+ *
  * @param pdu  The PDU to parse for options.
  * @param type The option type code to search for.
  * @param oi   An iterator object to use.
- * 
- * @return A pointer to the first option of type @p type, or @c NULL 
+ *
+ * @return A pointer to the first option of type @p type, or @c NULL
  *         if not found.
  */
 coap_opt_t *coap_check_option(coap_pdu_t *pdu, unsigned char type, coap_opt_iterator_t *oi);
@@ -281,7 +281,7 @@ unsigned short coap_opt_delta(const coap_opt_t *opt);
 #define COAP_OPT_DELTA(opt) coap_opt_delta(opt)
 
 /** @deprecated { Use coap_opt_encode() instead. } */
-#define COAP_OPT_SETDELTA(opt,val)                     \
+#define COAP_OPT_SETDELTA(opt,val)          \
   coap_opt_encode((opt), COAP_MAX_PDU_SIZE, (val), NULL, 0)
 
 /**
@@ -304,7 +304,7 @@ unsigned short coap_opt_length(const coap_opt_t *opt);
 
 /**
  * Returns a pointer to the value of the given option. @p opt must
- * point to an option jump or the beginning of the option. This 
+ * point to an option jump or the beginning of the option. This
  * function returns @c NULL if @p opt is not a valid option.
  *
  * @param opt  The option whose value should be returned.
index b8aaaad..5762007 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
 #include "option.h"
 #include "encode.h"
 
+#ifdef WITH_ARDUINO
+#include "util.h"
+#endif
+
 #ifdef WITH_CONTIKI
 #include "memb.h"
 
@@ -93,8 +97,8 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id, size_t
         return NULL;
 
     /* size must be large enough for hdr */
-#ifdef WITH_POSIX
-    pdu = coap_malloc(sizeof(coap_pdu_t) + size);
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+    pdu = (coap_pdu_t *) coap_malloc(sizeof(coap_pdu_t) + size);
 #endif
 #ifdef WITH_CONTIKI
     pdu = (coap_pdu_t *)memb_alloc(&pdu_storage);
@@ -147,12 +151,12 @@ coap_new_pdu()
 
 void coap_delete_pdu(coap_pdu_t *pdu)
 {
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     coap_free( pdu );
 #endif
 #ifdef WITH_LWIP
     if (pdu != NULL) /* accepting double free as the other implementation accept that too */
-    pbuf_free(pdu->pbuf);
+        pbuf_free(pdu->pbuf);
 #endif
 #ifdef WITH_CONTIKI
     memb_free(&pdu_storage, pdu);
@@ -299,7 +303,7 @@ typedef struct
     char *phrase;
 } error_desc_t;
 
-/* if you change anything here, make sure, that the longest string does not 
+/* if you change anything here, make sure, that the longest string does not
  * exceed COAP_ERROR_PHRASE_LENGTH. */
 error_desc_t coap_error[] =
 {
@@ -340,7 +344,7 @@ coap_response_phrase(unsigned char code)
 #endif
 
 /**
- * Advances *optp to next option if still in PDU. This function 
+ * Advances *optp to next option if still in PDU. This function
  * returns the number of bytes opt has been advanced or @c 0
  * on error.
  */
@@ -368,9 +372,6 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu)
 {
     coap_opt_t *opt;
 
-    char optionResult[256] =
-    { 0, };
-
     assert(data);
     assert(pdu);
 
index e01d851..c469b24 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _PDU_H_
 #define COAP_DEFAULT_PORT           5683 /* CoAP default UDP port */
 #define COAP_DEFAULT_MAX_AGE          60 /* default maximum object lifetime in seconds */
 #ifndef COAP_MAX_PDU_SIZE
-#define COAP_MAX_PDU_SIZE           1400 /* maximum size of a CoAP PDU */
+#ifdef WITH_ARDUINO
+#define COAP_MAX_PDU_SIZE           320 /* maximum size of a CoAP PDU for embedded platforms*/
+#else
+#define COAP_MAX_PDU_SIZE           1400 /* maximum size of a CoAP PDU for big platforms*/
+#endif
 #endif /* COAP_MAX_PDU_SIZE */
 
 #define COAP_DEFAULT_VERSION           1 /* version of CoAP supported */
 #define COAP_RESPONSE_CLASS(C) (((C) >> 5) & 0xFF)
 
 #ifndef SHORT_ERROR_RESPONSE
-/** 
+/**
  * Returns a human-readable response phrase for the specified CoAP
  * response @p code. This function returns @c NULL if not found.
- * 
+ *
  * @param code The response code for which the literal phrase should
  * be retrieved.
- * 
+ *
  * @return A zero-terminated string describing the error, or @c NULL
  * if not found.
  */
@@ -178,16 +182,16 @@ typedef struct
 #endif
 
 #define COAP_MESSAGE_IS_EMPTY(MSG)    ((MSG)->code == 0)
-#define COAP_MESSAGE_IS_REQUEST(MSG)  (!COAP_MESSAGE_IS_EMPTY(MSG)     \
-                                      && ((MSG)->code < 32))
+#define COAP_MESSAGE_IS_REQUEST(MSG)  (!COAP_MESSAGE_IS_EMPTY(MSG)  \
+                       && ((MSG)->code < 32))
 #define COAP_MESSAGE_IS_RESPONSE(MSG) ((MSG)->code >= 64 && (MSG)->code <= 191)
 
-#define COAP_OPT_LONG 0x0F     /* OC == 0b1111 indicates that the option list in a
-                                * CoAP message is limited by 0b11110000 marker */
+#define COAP_OPT_LONG 0x0F  /* OC == 0b1111 indicates that the option list in a
+                 * CoAP message is limited by 0b11110000 marker */
 
-#define COAP_OPT_END 0xF0      /* end marker */
+#define COAP_OPT_END 0xF0   /* end marker */
 
-#define COAP_PAYLOAD_START 0xFF        /* payload marker */
+#define COAP_PAYLOAD_START 0xFF /* payload marker */
 
 /**
  * Structures for more convenient handling of options. (To be used with ordered
@@ -216,7 +220,8 @@ typedef struct
     unsigned char *data; /**< payload */
 
 #ifdef WITH_LWIP
-    struct pbuf *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */
+    struct pbuf
+            *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */
 #endif
 
 } coap_pdu_t;
@@ -245,24 +250,24 @@ typedef struct
 coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf);
 #endif
 
-/** 
- * Creates a new CoAP PDU of given @p size (must be large enough to hold the 
+/**
+ * Creates a new CoAP PDU of given @p size (must be large enough to hold the
  * basic CoAP message header (coap_hdr_t). The function returns a pointer to
  * the node coap_pdu_t object on success, or @c NULL on error. The storage
  * allocated for the result must be released with coap_delete_pdu().
- * 
+ *
  * @param type The type of the PDU (one of COAP_MESSAGE_CON,
- *             COAP_MESSAGE_NON, COAP_MESSAGE_ACK, COAP_MESSAGE_RST). 
+ *             COAP_MESSAGE_NON, COAP_MESSAGE_ACK, COAP_MESSAGE_RST).
  * @param code The message code.
  * @param id   The message id to set or COAP_INVALID_TID if unknown.
  * @param size The number of bytes to allocate for the actual message.
- * 
+ *
  * @return A pointer to the new PDU object or @c NULL on error.
  */
 coap_pdu_t *
 coap_pdu_init(unsigned char type, unsigned char code, unsigned short id, size_t size);
 
-/** 
+/**
  * Clears any contents from @p pdu and resets @c version field, @c
  * length and @c data pointers. @c max_size is set to @p size, any
  * other field is set to @c 0. Note that @p pdu must be a valid
@@ -273,9 +278,9 @@ void coap_pdu_clear(coap_pdu_t *pdu, size_t size);
 /**
  * Creates a new CoAP PDU. The object is created on the heap and must be released
  * using coap_delete_pdu();
- * 
+ *
  * @deprecated This function allocates the maximum storage for each
- * PDU. Use coap_pdu_init() instead. 
+ * PDU. Use coap_pdu_init() instead.
  */
 coap_pdu_t *coap_new_pdu();
 
index ca86e72..25e7720 100644 (file)
@@ -3,10 +3,10 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
-/** 
+/**
  * @file prng.h
  * @brief Pseudo Random Numbers
  */
@@ -16,7 +16,7 @@
 
 #include "config.h"
 
-/** 
+/**
  * @defgroup prng Pseudo Random Numbers
  * @{
  */
@@ -64,16 +64,16 @@ contiki_prng_impl(unsigned char *buf, size_t len)
 #endif /* WITH_CONTIKI */
 
 #ifndef prng
-/** 
- * Fills \p Buf with \p Length bytes of random data. 
- * 
+/**
+ * Fills \p Buf with \p Length bytes of random data.
+ *
  * @hideinitializer
  */
 #define prng(Buf,Length) coap_prng_impl((Buf), (Length))
 #endif
 
 #ifndef prng_init
-/** 
+/**
  * Called to set the PRNG seed. You may want to re-define this to
  * allow for a better PRNG.
  *
index d6ae50f..8c3a3ec 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
@@ -27,7 +27,7 @@
 #define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
 
 #endif
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
 #include "utlist.h"
 #include "mem.h"
 
@@ -74,21 +74,21 @@ coap_free_subscription(coap_subscription_t *subscription)
  * Adds Char to Buf if Offset is zero. Otherwise, Char is not written
  * and Offset is decremented.
  */
-#define PRINT_WITH_OFFSET(Buf,Offset,Char)             \
-  if ((Offset) == 0) {                                 \
-    (*(Buf)++) = (Char);                               \
-  } else {                                             \
-    (Offset)--;                                                \
-  }                                                    \
+#define PRINT_WITH_OFFSET(Buf,Offset,Char)      \
+  if ((Offset) == 0) {                  \
+    (*(Buf)++) = (Char);                \
+  } else {                      \
+    (Offset)--;                     \
+  }                         \
 
 /**
  * Adds Char to Buf if Offset is zero and Buf is less than Bufend.
  */
-#define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) {                \
-    if ((Buf) < (Bufend)) {                                            \
-      PRINT_WITH_OFFSET(Buf,Offset,Char);                              \
-    }                                                                  \
-    (Result)++;                                                                \
+#define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) {     \
+    if ((Buf) < (Bufend)) {                     \
+      PRINT_WITH_OFFSET(Buf,Offset,Char);               \
+    }                                   \
+    (Result)++;                             \
   }
 
 /**
@@ -96,11 +96,11 @@ coap_free_subscription(coap_subscription_t *subscription)
  * characters are skipped. Output may be truncated to Bufend - Buf
  * characters.
  */
-#define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) {   \
-    size_t i;                                                          \
-    for (i = 0; i < (Length); i++) {                                   \
+#define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) {    \
+    size_t i;                               \
+    for (i = 0; i < (Length); i++) {                    \
       PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \
-    }                                                                  \
+    }                                   \
   }
 
 int match(const str *text, const str *pattern, int match_prefix, int match_substring)
@@ -119,7 +119,7 @@ int match(const str *text, const str *pattern, int match_prefix, int match_subst
         {
             size_t token_length;
             unsigned char *token = next_token;
-            next_token = memchr(token, ' ', remaining_length);
+            next_token = (unsigned char *) memchr(token, ' ', remaining_length);
 
             if (next_token)
             {
@@ -144,22 +144,22 @@ int match(const str *text, const str *pattern, int match_prefix, int match_subst
             && memcmp(text->s, pattern->s, pattern->length) == 0;
 }
 
-/** 
+/**
  * Prints the names of all known resources to @p buf. This function
  * sets @p buflen to the number of bytes actually written and returns
  * @c 1 on succes. On error, the value in @p buflen is undefined and
  * the return value will be @c 0.
- * 
+ *
  * @param context The context with the resource map.
  * @param buf     The buffer to write the result.
  * @param buflen  Must be initialized to the maximum length of @p buf and will be
  *                set to the length of the well-known response on return.
  * @param offset  The offset in bytes where the output shall start and is
  *                shifted accordingly with the characters that have been
- *                processed. This parameter is used to support the block 
- *                option. 
+ *                processed. This parameter is used to support the block
+ *                option.
  * @param query_filter A filter query according to <a href="http://tools.ietf.org/html/draft-ietf-core-link-format-11#section-4.1">Link Format</a>
- * 
+ *
  * @return COAP_PRINT_STATUS_ERROR on error. Otherwise, the lower 28 bits are
  *         set to the number of bytes that have actually been written to
  *         @p buf. COAP_PRINT_STATUS_TRUNC is set when the output has been
@@ -339,7 +339,7 @@ coap_resource_init(const unsigned char *uri, size_t len, int flags)
 {
     coap_resource_t *r;
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
 #endif
 #ifdef WITH_LWIP
@@ -381,7 +381,7 @@ coap_add_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen,
     if (!resource || !name)
         return NULL;
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
 #endif
 #ifdef WITH_LWIP
@@ -431,7 +431,7 @@ coap_find_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen
         for (attr = list_head(resource->link_attr); attr;
                 attr = list_item_next(attr))
         {
-#endif /* WITH_CONTIKI */    
+#endif /* WITH_CONTIKI */
         if (attr->name.length == nlen && memcmp(attr->name.s, name, nlen) == 0)
             return attr;
     }
@@ -501,7 +501,7 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     if (!resource)
         return 0;
 
-#if defined(WITH_POSIX) || defined(WITH_LWIP)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
 #ifdef COAP_RESOURCES_NOHASH
     LL_DELETE(context->resources, resource);
 #else
@@ -512,15 +512,15 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
 
     if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
-    coap_free(resource->uri.s);
+        coap_free(resource->uri.s);
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     coap_free(resource);
 #endif
 #ifdef WITH_LWIP
     memp_free(MEMP_COAP_RESOURCE, resource);
 #endif
-#else /* not (WITH_POSIX || WITH_LWIP) */
+#else /* not (WITH_POSIX || WITH_LWIP || WITH_ARDUINO) */
     /* delete registered attributes */
     while ((attr = list_pop(resource->link_attr)))
         memb_free(&attribute_storage, attr);
@@ -637,7 +637,8 @@ coap_find_observer(coap_resource_t *resource, const coap_address_t *peer, const
     assert(resource);
     assert(peer);
 
-    for (s = list_head(resource->subscribers); s; s = list_item_next(s))
+    for (s = (coap_subscription_t *) list_head(resource->subscribers);
+            s; s = (coap_subscription_t *) list_item_next((void *) s))
     {
         if (coap_address_equals(&s->subscriber, peer)
                 && (!token
@@ -752,7 +753,8 @@ static void coap_notify_observers(coap_context_t *context, coap_resource_t *r)
         assert(h); /* we do not allow subscriptions if no
          * GET handler is defined */
 
-        for (obs = list_head(r->subscribers); obs; obs = list_item_next(obs))
+        for (obs = (coap_subscription_t *) list_head(r->subscribers);
+                obs; obs = (coap_subscription_t *) list_item_next((void *) obs))
         {
             if (r->dirty == 0 && obs->dirty == 0)
                 /* running this resource due to partiallydirty, but this observation's notification was already enqueued */
@@ -866,7 +868,8 @@ static void coap_remove_failed_observers(coap_context_t *context, coap_resource_
 {
     coap_subscription_t *obs;
 
-    for (obs = list_head(resource->subscribers); obs; obs = list_item_next(obs))
+    for (obs = (coap_subscription_t *) list_head(resource->subscribers);
+            obs; obs = (coap_subscription_t *) list_item_next((void *) obs))
     {
         if (coap_address_equals(peer, &obs->subscriber) && token->length == obs->token_length
                 && memcmp(token->s, obs->token, token->length) == 0)
index 5ed3583..ae3d37a 100644 (file)
@@ -3,10 +3,10 @@
  * Copyright (C) 2010,2011,2014 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
-/** 
+/**
  * @file resource.h
  * @brief generic resource handling
  */
@@ -65,7 +65,7 @@ typedef struct coap_resource_t
     unsigned int observable :1; /**< can be observed */
     unsigned int cacheable :1; /**< can be cached */
 
-    /** 
+    /**
      * Used to store handlers for the four coap methods @c GET, @c POST,
      * @c PUT, and @c DELETE. coap_dispatch() will pass incoming
      * requests to the handler that corresponds to its request method or
@@ -98,15 +98,15 @@ typedef struct coap_resource_t
 
 } coap_resource_t;
 
-/** 
+/**
  * Creates a new resource object and initializes the link field to the
  * string of length @p len.  This function returns the
  * new coap_resource_t object.
- * 
+ *
  * @param uri    The URI path of the new resource.
  * @param len    The length of @p uri.
  * @param flags  Flags for memory management (in particular release of memory)
- * 
+ *
  * @return A pointer to the new object or @c NULL on error.
  */
 coap_resource_t *coap_resource_init(const unsigned char *uri, size_t len, int flags);
@@ -115,29 +115,29 @@ coap_resource_t *coap_resource_init(const unsigned char *uri, size_t len, int fl
  * Registers the given @p resource for @p context. The resource must
  * have been created by coap_resource_init(), the storage allocated
  * for the resource will be released by coap_delete_resource().
- * 
+ *
  * @param context  The context to use.
  * @param resource The resource to store.
  */
 void coap_add_resource(coap_context_t *context, coap_resource_t *resource);
 
-/** 
+/**
  * Deletes a resource identified by @p key. The storage allocated for
  * that resource is freed.
- * 
+ *
  * @param context  The context where the resources are stored.
  * @param key      The unique key for the resource to delete.
- * 
+ *
  * @return @c 1 if the resource was found (and destroyed), @c 0 otherwise.
  */
 int coap_delete_resource(coap_context_t *context, coap_key_t key);
 
-/** 
+/**
  * Registers a new attribute with the given @p resource. As the
- * attributes str fields will point to @p name and @p val the 
+ * attributes str fields will point to @p name and @p val the
  * caller must ensure that these pointers are valid during the
  * attribute's lifetime.
- * 
+ *
  * @param resource  The resource to register the attribute with.
  * @param name      The attribute's name.
  * @param nlen      Length of @p name.
@@ -162,11 +162,11 @@ coap_attr_t *coap_add_attr(coap_resource_t *resource, const unsigned char *name,
  */
 coap_attr_t *coap_find_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen);
 
-/** 
+/**
  * Deletes an attribute
- * 
+ *
  * @param attr  Pointer to a previously created attribute
- * 
+ *
  */
 void coap_delete_attr(coap_attr_t *attr);
 
@@ -187,22 +187,22 @@ typedef unsigned int coap_print_status_t;
 #define COAP_PRINT_STATUS_ERROR 0x80000000u
 #define COAP_PRINT_STATUS_TRUNC 0x40000000u
 
-/** 
+/**
  * Writes a description of this resource in link-format to given text
  * buffer. @p len must be initialized to the maximum length of @p buf
  * and will be set to the number of characters actually written if
  * successful.  This function returns @c 1 on success or @c 0 on
  * error.
- * 
+ *
  * @param resource The resource to describe.
  * @param buf      The output buffer to write the description to.
- * @param len      Must be initialized to the length of @p buf and 
+ * @param len      Must be initialized to the length of @p buf and
  *                 will be set to the length of the printed link description.
  * @param offset   The offset within the resource description where to
  *                 start writing into @p buf. This is useful for dealing
  *                 with the Block2 option. @p offset is updated during
  *                 output as it is consumed.
- * 
+ *
  * @return If COAP_PRINT_STATUS_ERROR is set, an error occured. Otherwise,
  *         the lower 28 bits will indicate the number of characters that
  *         have actually been output into @p buffer. The flag
@@ -212,12 +212,12 @@ typedef unsigned int coap_print_status_t;
 coap_print_status_t coap_print_link(const coap_resource_t *resource, unsigned char *buf,
         size_t *len, size_t *offset);
 
-/** 
+/**
  * Registers the specified @p handler as message handler for the request type
  * @p method 
- * 
+ *
  * @param resource The resource for which the handler shall be registered.
- * @param method   The CoAP request method to handle. 
+ * @param method   The CoAP request method to handle.
  * @param handler  The handler to register with @p resource.
  */
 static inline void coap_register_handler(coap_resource_t *resource, unsigned char method,
@@ -231,28 +231,28 @@ static inline void coap_register_handler(coap_resource_t *resource, unsigned cha
     resource->handler[method - 1] = handler;
 }
 
-/** 
+/**
  * Returns the resource identified by the unique string @p key. If no
  * resource was found, this function returns @c NULL.
- * 
+ *
  * @param context  The context to look for this resource.
  * @param key      The unique key of the resource.
- * 
+ *
  * @return A pointer to the resource or @c NULL if not found.
  */
 coap_resource_t *coap_get_resource_from_key(coap_context_t *context, coap_key_t key);
 
-/** 
+/**
  * Calculates the hash key for the resource requested by the
  * Uri-Options of @p request.  This function calls coap_hash() for
  * every path segment. 
- * 
+ *
  * @param request The requesting pdu.
  * @param key     The resulting hash is stored in @p key
  */
 void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key);
 
-/** 
+/**
  * @addtogroup observe 
  */
 
@@ -267,7 +267,7 @@ void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key);
  * @param token The token that identifies this subscription.
  * @param token_length The actual length of @p token. Must be @c 0 when
  *        @p token is @c NULL.
- * @return A pointer to the added/updated subscription information or 
+ * @return A pointer to the added/updated subscription information or
  *        @c NULL on error.
  */
 coap_subscription_t *coap_add_observer(coap_resource_t *resource, const coap_address_t *observer,
@@ -290,7 +290,7 @@ coap_subscription_t *coap_find_observer(coap_resource_t *resource, const coap_ad
  *
  * @param context  The CoAP context to use
  * @param observer The transport address of the observer
- * @param token    The corresponding token that has been used for 
+ * @param token    The corresponding token that has been used for
  *   the subscription
  */
 void coap_touch_observer(coap_context_t *context, const coap_address_t *observer, const str *token);
@@ -307,7 +307,7 @@ void coap_touch_observer(coap_context_t *context, const coap_address_t *observer
 void coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer,
         const str *token);
 
-/** 
+/**
  * Checks for all known resources, if they are dirty and notifies
  * subscribed observers.
  */
index 8b275e3..950803d 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
@@ -16,7 +16,7 @@
 
 str *coap_new_string(size_t size)
 {
-    str *s = coap_malloc(sizeof(str) + size + 1);
+    str *s = (str *) coap_malloc(sizeof(str) + size + 1);
     if (!s)
     {
 #ifndef NDEBUG
index 6405298..0a96686 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_STR_H_
index 295f5c5..e5c3d24 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
index 7b7dc05..eb76151 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_SUBSCRIBE_H_
@@ -13,7 +13,7 @@
 #include "config.h"
 #include "address.h"
 
-/** 
+/**
  * @defgroup observe Resource observation
  * @{
  */
index 47653d1..5f25f96 100644 (file)
@@ -82,13 +82,13 @@ struct list
 
 #define LIST_CONCAT(s1, s2) s1##s2
 
-#define LIST_STRUCT(name)                      \
-  void *LIST_CONCAT(name, _list);              \
+#define LIST_STRUCT(name)           \
+  void *LIST_CONCAT(name, _list);       \
   list_t name
 
-#define LIST_STRUCT_INIT(struct_ptr, name)  {                          \
-    (struct_ptr)->name = &((struct_ptr)->LIST_CONCAT(name,_list));     \
-    (struct_ptr)->LIST_CONCAT(name,_list) = NULL;                      \
+#define LIST_STRUCT_INIT(struct_ptr, name)  {               \
+    (struct_ptr)->name = &((struct_ptr)->LIST_CONCAT(name,_list));  \
+    (struct_ptr)->LIST_CONCAT(name,_list) = NULL;           \
   }
 
 static inline void *
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile
deleted file mode 100644 (file)
index 6397552..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-# Makefile for libcoap
-#
-# Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
-#
-# This file is part of the CoAP library libcoap. Please see
-# README for terms of use. 
-
-# the library's version
-VERSION:=4.1.1
-
-# tools
-
-SHELL = /bin/sh
-MKDIR = mkdir
-
-abs_builddir = /connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1/tests
-top_builddir = ..
-top_srcdir = ..
-# files and flags
-ifneq (,)
-  PROGRAMS:=testdriver
-endif
-SOURCES:= test_uri.c test_options.c test_pdu.c test_error_response.c \
-  test_sendqueue.c test_wellknown.c
-HEADERS:=$(SOURCES:.c=.h)
-OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
-CFLAGS:=-g -Wall -g -O2
-CPPFLAGS:=-I$(top_srcdir)  -DWITH_POSIX
-DISTDIR?=$(top_builddir)/libcoap-4.1.1
-FILES:=Makefile.in testdriver.c $(HEADERS) $(SOURCES)
-LDFLAGS:=-L$(top_builddir) 
-LDLIBS:=-lcunit 
-libcoap =$(top_builddir)/libcoap.a
-
-.PHONY: clean distclean
-
-.SUFFIXES:
-.SUFFIXES:      .c .o
-
-all:   $(PROGRAMS)
-
-check: 
-       echo DISTDIR: $(DISTDIR)
-       echo top_builddir: $(top_builddir)
-
-testdriver:    $(OBJECTS) $(libcoap)
-
-clean:
-       @rm -f $(PROGRAMS) $(OBJECTS)
-
-distclean:     clean
-       @rm -rf $(DISTDIR)
-       @rm -f *~ 
-
-dist:  $(FILES)
-       test -d $(DISTDIR)/tests || mkdir $(DISTDIR)/tests
-       cp $(FILES) $(DISTDIR)/tests
index 95da5c0..f065c1e 100644 (file)
@@ -55,3 +55,4 @@ distclean:    clean
 dist:  $(FILES)
        test -d $(DISTDIR)/tests || mkdir $(DISTDIR)/tests
        cp $(FILES) $(DISTDIR)/tests
+
index fad0941..69c62bd 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <assert.h>
@@ -310,10 +310,10 @@ CU_pSuite t_init_error_response_tests(void)
         return NULL;
     }
 
-#define ERROR_RESPONSE_TEST(s,t)                                       \
-  if (!CU_ADD_TEST(s,t)) {                                             \
+#define ERROR_RESPONSE_TEST(s,t)                    \
+  if (!CU_ADD_TEST(s,t)) {                      \
     fprintf(stderr, "W: cannot add error response generator test (%s)\n", \
-           CU_get_error_msg());                                        \
+        CU_get_error_msg());                    \
   }
 
     ERROR_RESPONSE_TEST(suite[0], t_error_response1);
index 2bab63c..5ae3cea 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <CUnit/CUnit.h>
index de5b3a6..27c12ad 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <stdio.h>
@@ -756,10 +756,10 @@ CU_pSuite t_init_option_tests(void)
         return NULL;
     }
 
-#define OPTION_TEST(n,s)                                                     \
-  if (!CU_add_test(suite[0], s, t_parse_option##n)) {        \
-    fprintf(stderr, "W: cannot add option parser test (%s)\n",       \
-           CU_get_error_msg());                                      \
+#define OPTION_TEST(n,s)                              \
+  if (!CU_add_test(suite[0], s, t_parse_option##n)) {         \
+    fprintf(stderr, "W: cannot add option parser test (%s)\n",        \
+        CU_get_error_msg());                      \
   }
 
     OPTION_TEST(1, "parse option #1");
@@ -779,10 +779,10 @@ CU_pSuite t_init_option_tests(void)
 
     if ((suite[1] = CU_add_suite("option encoder", NULL, NULL)))
     {
-#define OPTION_ENCODER_TEST(n,s)                             \
-    if (!CU_add_test(suite[1], s, t_encode_option##n)) {                     \
+#define OPTION_ENCODER_TEST(n,s)                  \
+    if (!CU_add_test(suite[1], s, t_encode_option##n)) {              \
       fprintf(stderr, "W: cannot add option encoder test (%s)\n",     \
-             CU_get_error_msg());                                    \
+          CU_get_error_msg());                    \
     }
 
         OPTION_ENCODER_TEST(1, "encode option #1");
@@ -802,10 +802,10 @@ CU_pSuite t_init_option_tests(void)
 
     if ((suite[2] = CU_add_suite("option accessors", NULL, NULL)))
     {
-#define OPTION_ACCESSOR_TEST(n,s)                            \
-    if (!CU_add_test(suite[2], s, t_access_option##n)) {                     \
+#define OPTION_ACCESSOR_TEST(n,s)                 \
+    if (!CU_add_test(suite[2], s, t_access_option##n)) {              \
       fprintf(stderr, "W: cannot add option accessor function test (%s)\n",     \
-             CU_get_error_msg());                                    \
+          CU_get_error_msg());                    \
     }
 
         OPTION_ACCESSOR_TEST(1, "access option #1");
@@ -825,10 +825,10 @@ CU_pSuite t_init_option_tests(void)
 
     if ((suite[3] = CU_add_suite("option iterator", NULL, NULL)))
     {
-#define OPTION_ITERATOR_TEST(n,s)                            \
-    if (!CU_add_test(suite[3], s, t_iterate_option##n)) {                    \
+#define OPTION_ITERATOR_TEST(n,s)                 \
+    if (!CU_add_test(suite[3], s, t_iterate_option##n)) {             \
       fprintf(stderr, "W: cannot add option iterator test (%s)\n",     \
-             CU_get_error_msg());                                    \
+          CU_get_error_msg());                    \
     }
 
         OPTION_ITERATOR_TEST(1, "option iterator #1");
index 3ffcefe..8c2be65 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <CUnit/CUnit.h>
index 2592a32..8d004d8 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <assert.h>
@@ -609,10 +609,10 @@ CU_pSuite t_init_pdu_tests(void)
         return NULL;
     }
 
-#define PDU_TEST(s,t)                                                \
-  if (!CU_ADD_TEST(s,t)) {                                           \
-    fprintf(stderr, "W: cannot add pdu parser test (%s)\n",          \
-           CU_get_error_msg());                                      \
+#define PDU_TEST(s,t)                             \
+  if (!CU_ADD_TEST(s,t)) {                        \
+    fprintf(stderr, "W: cannot add pdu parser test (%s)\n",       \
+        CU_get_error_msg());                      \
   }
 
     PDU_TEST(suite[0], t_parse_pdu1);
@@ -633,10 +633,10 @@ CU_pSuite t_init_pdu_tests(void)
     suite[1] = CU_add_suite("pdu encoder", t_pdu_tests_create, t_pdu_tests_remove);
     if (suite[1])
     {
-#define PDU_ENCODER_TEST(s,t)                                                \
-  if (!CU_ADD_TEST(s,t)) {                                           \
-    fprintf(stderr, "W: cannot add pdu encoder test (%s)\n",         \
-           CU_get_error_msg());                                      \
+#define PDU_ENCODER_TEST(s,t)                             \
+  if (!CU_ADD_TEST(s,t)) {                        \
+    fprintf(stderr, "W: cannot add pdu encoder test (%s)\n",          \
+        CU_get_error_msg());                      \
   }
         PDU_ENCODER_TEST(suite[1], t_encode_pdu1);
         PDU_ENCODER_TEST(suite[1], t_encode_pdu2);
index 992b377..a052240 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <CUnit/CUnit.h>
index 1b6c076..5207039 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <stdio.h>
@@ -291,7 +291,7 @@ void t_sendqueue10(void)
 
 /* This function creates a set of nodes for testing. These nodes
  * will exist for all tests and are modified by coap_insert_node()
- * and 
+ * and
  */
 int t_sendqueue_tests_create(void)
 {
@@ -357,10 +357,10 @@ CU_pSuite t_init_sendqueue_tests(void)
         return NULL;
     }
 
-#define SENDQUEUE_TEST(s,t)                                          \
-  if (!CU_ADD_TEST(s,t)) {                                           \
-    fprintf(stderr, "W: cannot add sendqueue test (%s)\n",           \
-           CU_get_error_msg());                                      \
+#define SENDQUEUE_TEST(s,t)                       \
+  if (!CU_ADD_TEST(s,t)) {                        \
+    fprintf(stderr, "W: cannot add sendqueue test (%s)\n",        \
+        CU_get_error_msg());                      \
   }
 
     SENDQUEUE_TEST(suite, t_sendqueue1);
index 56f3c1e..694072b 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <CUnit/CUnit.h>
index d5dafc5..04a3d14 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <stdio.h>
@@ -371,10 +371,10 @@ CU_pSuite t_init_uri_tests(void)
         return NULL;
     }
 
-#define URI_TEST(s,t)                                                \
-  if (!CU_ADD_TEST(s,t)) {                                           \
-    fprintf(stderr, "W: cannot add uri parser test (%s)\n",          \
-           CU_get_error_msg());                                      \
+#define URI_TEST(s,t)                             \
+  if (!CU_ADD_TEST(s,t)) {                        \
+    fprintf(stderr, "W: cannot add uri parser test (%s)\n",       \
+        CU_get_error_msg());                      \
   }
 
     URI_TEST(suite, t_parse_uri1);
index 165fad3..ca96090 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <CUnit/CUnit.h>
index 97584d8..843e249 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2013--2014 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <assert.h>
@@ -296,7 +296,7 @@ int t_wkc_tests_create(void)
         }
 
     }
-#endif  
+#endif
     return ctx == NULL || pdu == NULL;
 }
 
@@ -319,10 +319,10 @@ CU_pSuite t_init_wellknown_tests(void)
         return NULL;
     }
 
-#define WKC_TEST(s,t)                                                \
-  if (!CU_ADD_TEST(s,t)) {                                           \
-    fprintf(stderr, "W: cannot add .well-known/core test (%s)\n",            \
-           CU_get_error_msg());                                      \
+#define WKC_TEST(s,t)                             \
+  if (!CU_ADD_TEST(s,t)) {                        \
+    fprintf(stderr, "W: cannot add .well-known/core test (%s)\n",         \
+        CU_get_error_msg());                      \
   }
 
     WKC_TEST(suite, t_wellknown1);
index 47f20b3..8ba1d6d 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2013 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include <CUnit/CUnit.h>
index 1b78686..31ac600 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #include "config.h"
 #include "option.h"
 #include "uri.h"
 
-/** 
+/**
  * A length-safe version of strchr(). This function returns a pointer
  * to the first occurrence of @p c  in @p s, or @c NULL if not found.
- * 
+ *
  * @param s   The string to search for @p c.
  * @param len The length of @p s.
  * @param c   The character to search.
- * 
- * @return A pointer to the first occurence of @p c, or @c NULL 
+ *
+ * @return A pointer to the first occurence of @p c, or @c NULL
  * if not found.
  */
 static inline unsigned char *
@@ -125,7 +125,7 @@ int coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri)
     { /* IPv4 address or FQDN */
         while (len && *q != ':' && *q != '/' && *q != '?')
         {
-            // *q = tolower(*q);
+            *q = tolower(*q);
 
             ++q;
             --len;
@@ -201,23 +201,23 @@ int coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri)
     error: return res;
 }
 
-/** 
+/**
  * Calculates decimal value from hexadecimal ASCII character given in
  * @p c. The caller must ensure that @p c actually represents a valid
- * heaxdecimal character, e.g. with isxdigit(3). 
+ * heaxdecimal character, e.g. with isxdigit(3).
  *
  * @hideinitializer
  */
 #define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F))
 
-/** 
+/**
  * Decodes percent-encoded characters while copying the string @p seg
  * of size @p length to @p buf. The caller of this function must
  * ensure that the percent-encodings are correct (i.e. the character
  * '%' is always followed by two hex digits. and that @p buf provides
  * sufficient space to hold the result. This function is supposed to
  * be called by make_decoded_option() only.
- * 
+ *
  * @param seg     The segment to decode and copy.
  * @param length  Length of @p seg.
  * @param buf     The result buffer.
@@ -274,7 +274,7 @@ int check_segment(const unsigned char *s, size_t length)
     return n;
 }
 
-/** 
+/**
  * Writes a coap option from given string @p s to @p buf. @p s should
  * point to a (percent-encoded) path or query segment of a coap_uri_t
  * object.  The created option will have type @c 0, and the length
@@ -282,12 +282,12 @@ int check_segment(const unsigned char *s, size_t length)
  * On success, this function returns the option's size, or a value
  * less than zero on error. This function must be called from
  * coap_split_path_impl() only.
- * 
+ *
  * @param s       The string to decode.
  * @param length  The size of the percent-encoded string @p s.
  * @param buf     The buffer to store the new coap option.
  * @param buflen  The maximum size of @p buf.
- * 
+ *
  * @return The option's size, or @c -1 on error.
  *
  * @bug This function does not split segments that are bigger than 270
@@ -336,14 +336,14 @@ int make_decoded_option(const unsigned char *s, size_t length, unsigned char *bu
 
 typedef void (*segment_handler_t)(unsigned char *, size_t, void *);
 
-/** 
+/**
  * Splits the given string into segments. You should call one of the
  * macros coap_split_path() or coap_split_query() instead.
- * 
+ *
  * @param parse_iter The iterator used for tokenizing.
  * @param h      A handler that is called with every token.
  * @param data   Opaque data that is passed to @p h when called.
- * 
+ *
  * @return The number of characters that have been parsed from @p s.
  */
 size_t coap_split_path_impl(coap_parse_iterator_t *parse_iter, segment_handler_t h, void *data)
@@ -379,7 +379,7 @@ void write_option(unsigned char *s, size_t len, void *data)
     assert(state);
 
     /* skip empty segments and those that consist of only one or two dots */
-    if (memcmp(s, "..", min(len,2)) == 0)
+    if (memcmp(s, "..", min(len, 2)) == 0)
         return;
 
     res = make_decoded_option(s, len, state->buf.s, state->buf.length);
@@ -427,7 +427,7 @@ coap_new_uri(const unsigned char *uri, unsigned int length)
 {
     unsigned char *result;
 
-    result = coap_malloc(length + 1 + sizeof(coap_uri_t));
+    result = (unsigned char *) coap_malloc(length + 1 + sizeof(coap_uri_t));
 
     if (!result)
         return NULL;
@@ -451,8 +451,8 @@ coap_clone_uri(const coap_uri_t *uri)
     if (!uri)
         return NULL;
 
-    result = (coap_uri_t *) coap_malloc( uri->query.length + uri->host.length +
-            uri->path.length + sizeof(coap_uri_t) + 1);
+    result = (coap_uri_t *) coap_malloc(
+            uri->query.length + uri->host.length + uri->path.length + sizeof(coap_uri_t) + 1);
 
     if (!result)
         return NULL;
@@ -494,7 +494,7 @@ coap_clone_uri(const coap_uri_t *uri)
  * segment_handler_t hence we use this wrapper as safe typecast. */
 static inline void hash_segment(unsigned char *s, size_t len, void *data)
 {
-    coap_hash(s, len, data);
+    coap_hash(s, len, (unsigned char *) data);
 }
 
 int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key)
index 20dd28e..820a045 100644 (file)
@@ -3,7 +3,7 @@
  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
  *
  * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
+ * README for terms of use.
  */
 
 #ifndef _COAP_URI_H_
@@ -19,7 +19,7 @@ typedef struct
 {
     str host; /**< host part of the URI */
     unsigned short port; /**< The port in host byte order */
-    str path; /**< Beginning of the first path segment. 
+    str path; /**< Beginning of the first path segment.
      Use coap_split_path() to create Uri-Path options */
     str query; /**<  The query part if present */
 } coap_uri_t;
@@ -41,14 +41,14 @@ coap_uri_t *coap_new_uri(const unsigned char *uri, unsigned int length);
  * be released with coap_free(). */
 coap_uri_t *coap_clone_uri(const coap_uri_t *uri);
 
-/** 
- * Calculates a hash over the given path and stores the result in 
+/**
+ * Calculates a hash over the given path and stores the result in
  * @p key. This function returns @c 0 on error or @c 1 on success.
- * 
+ *
  * @param path The URI path to generate hash for.
  * @param len  The length of @p path.
  * @param key  The output buffer.
- * 
+ *
  * @return @c 1 if @p key was set, @c 0 otherwise.
  */
 int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key);
@@ -61,7 +61,7 @@ int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key);
  * @{
  */
 
-/** 
+/**
  * Iterator to for tokenizing a URI path or query. This structure must
  * be initialized with coap_parse_iterator_init(). Call
  * coap_parse_next() to walk through the tokens.
@@ -86,43 +86,43 @@ typedef struct
     size_t segment_length; /**< length of current segment */
 } coap_parse_iterator_t;
 
-/** 
- * Initializes the given iterator @p pi. 
- * 
+/**
+ * Initializes the given iterator @p pi.
+ *
  * @param s         The string to tokenize.
  * @param n         The length of @p s.
  * @param separator The separator character that delimits tokens.
  * @param delim     A set of characters that delimit @s.
  * @param dlen      The length of @p delim.
  * @param pi        The iterator object to initialize.
- * 
+ *
  * @return The initialized iterator object @p pi.
  */
 coap_parse_iterator_t *
 coap_parse_iterator_init(unsigned char *s, size_t n, unsigned char separator, unsigned char *delim,
         size_t dlen, coap_parse_iterator_t *pi);
 
-/** 
+/**
  * Updates the iterator @p pi to point to the next token. This
  * function returns a pointer to that token or @c NULL if no more
  * tokens exist. The contents of @p pi will be updated. In particular,
  * @c pi->segment_length specifies the length of the current token, @c
  * pi->pos points to its beginning.
- * 
+ *
  * @param pi The iterator to update.
- * 
+ *
  * @return The next token or @c NULL if no more tokens exist.
  */
 unsigned char *coap_parse_next(coap_parse_iterator_t *pi);
 
-/** 
+/**
  * Parses a given string into URI components. The identified syntactic
  * components are stored in the result parameter @p uri. Optional URI
  * components that are not specified will be set to { 0, 0 }, except
  * for the port which is set to @c COAP_DEFAULT_PORT. This function
  * returns @p 0 if parsing succeeded, a value less than zero
  * otherwise.
- * 
+ *
  * @param str_var The string to split up.
  * @param len     The actual length of @p str_var
  * @param uri     The coap_uri_t object to store the result.
@@ -134,32 +134,32 @@ unsigned char *coap_parse_next(coap_parse_iterator_t *pi);
 int
 coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri);
 
-/** 
+/**
  * Splits the given URI path into segments. Each segment is preceded
  * by an option pseudo-header with delta-value 0 and the actual length
  * of the respective segment after percent-decoding.
- * 
- * @param s      The path string to split. 
+ *
+ * @param s      The path string to split.
  * @param length The actual length of @p s.
- * @param buf    Result buffer for parsed segments. 
+ * @param buf    Result buffer for parsed segments.
  * @param buflen Maximum length of @p buf. Will be set to the actual number
  * of bytes written into buf on success.
- * 
+ *
  * @return The number of segments created or @c -1 on error.
  */
 int coap_split_path(const unsigned char *s, size_t length, unsigned char *buf, size_t *buflen);
 
-/** 
+/**
  * Splits the given URI query into segments. Each segment is preceded
  * by an option pseudo-header with delta-value 0 and the actual length
  * of the respective query term.
- * 
- * @param s      The query string to split. 
+ *
+ * @param s      The query string to split.
  * @param length The actual length of @p s.
- * @param buf    Result buffer for parsed segments. 
+ * @param buf    Result buffer for parsed segments.
  * @param buflen Maximum length of @p buf. Will be set to the actual number
  * of bytes written into buf on success.
- * 
+ *
  * @return The number of segments created or @c -1 on error.
  *
  * @bug This function does not reserve additional space for delta > 12.
index 21e8141..be8f2bd 100644 (file)
@@ -22,7 +22,7 @@
  */
 
 #ifndef UTHASH_H
-#define UTHASH_H 
+#define UTHASH_H
 
 #include <string.h>   /* memcmp,strlen */
 #include <stddef.h>   /* ptrdiff_t */
@@ -48,7 +48,7 @@ do {
   char **_da_dst = (char**)(&(dst));                                             \
   *_da_dst = (char*)(src);                                                       \
 } while(0)
-#else 
+#else
 #define DECLTYPE_ASSIGN(dst,src)                                                 \
 do {                                                                             \
   (dst) = DECLTYPE(dst)(src);                                                    \
@@ -121,9 +121,9 @@ do {
   HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
 
 #else
-#define HASH_BLOOM_MAKE(tbl) 
-#define HASH_BLOOM_FREE(tbl) 
-#define HASH_BLOOM_ADD(tbl,hashv) 
+#define HASH_BLOOM_MAKE(tbl)
+#define HASH_BLOOM_FREE(tbl)
+#define HASH_BLOOM_ADD(tbl,hashv)
 #define HASH_BLOOM_TEST(tbl,hashv) (1)
 #endif
 
@@ -299,10 +299,10 @@ do {
     }                                                                            \
 } while (0)
 #else
-#define HASH_FSCK(hh,head) 
+#define HASH_FSCK(hh,head)
 #endif
 
-/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to 
+/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to
  * the descriptor to which this macro is defined for tuning the hash function.
  * The app can #include <unistd.h> to get the prototype for write(2). */
 #ifdef HASH_EMIT_KEYS
@@ -312,12 +312,12 @@ do {
     write(HASH_EMIT_KEYS, &_klen, sizeof(_klen));                                \
     write(HASH_EMIT_KEYS, keyptr, fieldlen);                                     \
 } while (0)
-#else 
-#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                    
+#else
+#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)
 #endif
 
 /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */
-#ifdef HASH_FUNCTION 
+#ifdef HASH_FUNCTION
 #define HASH_FCN HASH_FUNCTION
 #else
 #define HASH_FCN HASH_JEN
@@ -333,7 +333,7 @@ do {
   bkt = (hashv) & (num_bkts-1);                                                  \
 } while (0)
 
-/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at 
+/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at
  * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */
 #define HASH_SAX(key,keylen,num_bkts,hashv,bkt)                                  \
 do {                                                                             \
@@ -484,14 +484,14 @@ do {
 /* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads.
  * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error.
  * So MurmurHash comes in two versions, the faster unaligned one and the slower
- * aligned one. We only use the faster one on CPU's where we know it's safe. 
+ * aligned one. We only use the faster one on CPU's where we know it's safe.
  *
  * Note the preprocessor built-in defines can be emitted using:
  *
  *   gcc -m64 -dM -E - < /dev/null                  (on gcc)
  *   cc -## a.c (where a.c is a simple test file)   (Sun Studio)
  */
-#if (defined(__i386__) || defined(__x86_64__)) 
+#if (defined(__i386__) || defined(__x86_64__))
 #define HASH_MUR HASH_MUR_UNALIGNED
 #else
 #define HASH_MUR HASH_MUR_ALIGNED
@@ -630,7 +630,7 @@ do {
 #endif  /* HASH_USING_NO_STRICT_ALIASING */
 
 /* key comparison function; return 0 if keys equal */
-#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) 
+#define HASH_KEYCMP(a,b,len) memcmp(a,b,len)
 
 /* iterate over items in a known bucket to find desired item */
 #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out)                       \
@@ -671,36 +671,36 @@ do {
     }                                                                            \
     if (hh_del->hh_next) {                                                       \
         hh_del->hh_next->hh_prev = hh_del->hh_prev;                              \
-    }                                                                
+    }
 
 /* Bucket expansion has the effect of doubling the number of buckets
  * and redistributing the items into the new buckets. Ideally the
  * items will distribute more or less evenly into the new buckets
  * (the extent to which this is true is a measure of the quality of
- * the hash function as it applies to the key domain). 
- * 
+ * the hash function as it applies to the key domain).
+ *
  * With the items distributed into more buckets, the chain length
  * (item count) in each bucket is reduced. Thus by expanding buckets
- * the hash keeps a bound on the chain length. This bounded chain 
+ * the hash keeps a bound on the chain length. This bounded chain
  * length is the essence of how a hash provides constant time lookup.
- * 
+ *
  * The calculation of tbl->ideal_chain_maxlen below deserves some
  * explanation. First, keep in mind that we're calculating the ideal
  * maximum chain length based on the *new* (doubled) bucket count.
  * In fractions this is just n/b (n=number of items,b=new num buckets).
- * Since the ideal chain length is an integer, we want to calculate 
+ * Since the ideal chain length is an integer, we want to calculate
  * ceil(n/b). We don't depend on floating point arithmetic in this
  * hash, so to calculate ceil(n/b) with integers we could write
- * 
+ *
  *      ceil(n/b) = (n/b) + ((n%b)?1:0)
- * 
+ *
  * and in fact a previous version of this hash did just that.
  * But now we have improved things a bit by recognizing that b is
  * always a power of two. We keep its base 2 log handy (call it lb),
  * so now we can write this with a bit shift and logical AND:
- * 
+ *
  *      ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)
- * 
+ *
  */
 #define HASH_EXPAND_BUCKETS(tbl)                                                 \
 do {                                                                             \
@@ -751,7 +751,7 @@ do {
 } while(0)
 
 /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */
-/* Note that HASH_SORT assumes the hash handle name to be hh. 
+/* Note that HASH_SORT assumes the hash handle name to be hh.
  * HASH_SRT was added to allow the hash handle name to be passed in. */
 #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)
 #define HASH_SRT(hh,head,cmpfcn)                                                 \
@@ -833,10 +833,10 @@ do {
  }                                                                               \
 } while (0)
 
-/* This function selects items from one hash into another hash. 
- * The end result is that the selected items have dual presence 
- * in both hashes. There is no copy of the items made; rather 
- * they are added into the new hash through a secondary hash 
+/* This function selects items from one hash into another hash.
+ * The end result is that the selected items have dual presence
+ * in both hashes. There is no copy of the items made; rather
+ * they are added into the new hash through a secondary hash
  * hash handle that must be present in the structure. */
 #define HASH_SELECT(hh_dst, dst, hh_src, src, cond)                              \
 do {                                                                             \
@@ -889,7 +889,7 @@ do {
 #ifdef NO_DECLTYPE
 #define HASH_ITER(hh,head,el,tmp)                                                \
 for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL);       \
-  el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) 
+  el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL))
 #else
 #define HASH_ITER(hh,head,el,tmp)                                                \
 for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL);                 \
@@ -897,7 +897,7 @@ for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL);
 #endif
 
 /* obtain a count of items in the hash */
-#define HASH_COUNT(head) HASH_CNT(hh,head) 
+#define HASH_COUNT(head) HASH_CNT(hh,head)
 #define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0)
 
 typedef struct UT_hash_bucket
@@ -907,7 +907,7 @@ typedef struct UT_hash_bucket
 
     /* expand_mult is normally set to 0. In this situation, the max chain length
      * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
-     * the bucket's chain exceeds this length, bucket expansion is triggered). 
+     * the bucket's chain exceeds this length, bucket expansion is triggered).
      * However, setting expand_mult to a non-zero value delays bucket expansion
      * (that would be triggered by additions to this particular bucket)
      * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.
@@ -915,7 +915,7 @@ typedef struct UT_hash_bucket
      * multiplier is to reduce bucket expansions, since they are expensive, in
      * situations where we know that a particular bucket tends to be overused.
      * It is better to let its chain length grow to a longer yet-still-bounded
-     * value, than to do an O(n) bucket expansion too often. 
+     * value, than to do an O(n) bucket expansion too often.
      */
     unsigned expand_mult;
 
@@ -942,7 +942,7 @@ typedef struct UT_hash_table
      * hash distribution; reaching them in a chain traversal takes >ideal steps */
     unsigned nonideal_items;
 
-    /* ineffective expands occur when a bucket doubling was performed, but 
+    /* ineffective expands occur when a bucket doubling was performed, but
      * afterward, more than half the items in the hash had nonideal chain
      * positions. If this happens on two consecutive expansions we inhibit any
      * further expansion, as it's not helping; this happens when the hash
index 4073e04..a1c739c 100644 (file)
@@ -26,7 +26,7 @@
 
 #define UTLIST_VERSION 1.9.1
 
-/* 
+/*
  * This file contains macros to manipulate singly and doubly-linked lists.
  *
  * 1. LL_ macros:  singly-linked lists.
@@ -36,7 +36,7 @@
  * To use singly-linked lists, your structure must have a "next" pointer.
  * To use doubly-linked lists, your structure must "prev" and "next" pointers.
  * Either way, the pointer to the head of the list must be initialized to NULL.
- * 
+ *
  * ----------------.EXAMPLE -------------------------
  * struct item {
  *      int id;
@@ -83,7 +83,7 @@
 #define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); }
 #define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; }
 #define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); }
-#else 
+#else
 #define _SV(elt,list)
 #define _NEXT(elt,list) ((elt)->next)
 #define _NEXTASGN(elt,list,to) ((elt)->next)=(to)
@@ -369,14 +369,14 @@ do {
     LL_FOREACH(head,out) {                                                                     \
       if ((out)->field == (val)) break;                                                        \
     }                                                                                          \
-} while(0) 
+} while(0)
 
 #define LL_SEARCH(head,out,elt,cmp)                                                            \
 do {                                                                                           \
     LL_FOREACH(head,out) {                                                                     \
       if ((cmp(out,elt))==0) break;                                                            \
     }                                                                                          \
-} while(0) 
+} while(0)
 
 /******************************************************************************
  * doubly linked list macros (non-circular)                                   *
@@ -464,7 +464,7 @@ do {
 } while (0);
 
 #define CDL_FOREACH(head,el)                                                                   \
-    for(el=head;el;el=(el->next==head ? 0L : el->next)) 
+    for(el=head;el;el=(el->next==head ? 0L : el->next))
 
 #define CDL_FOREACH_SAFE(head,el,tmp1,tmp2)                                                    \
   for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL);                                        \
@@ -476,14 +476,14 @@ do {
     CDL_FOREACH(head,out) {                                                                    \
       if ((out)->field == (val)) break;                                                        \
     }                                                                                          \
-} while(0) 
+} while(0)
 
 #define CDL_SEARCH(head,out,elt,cmp)                                                           \
 do {                                                                                           \
     CDL_FOREACH(head,out) {                                                                    \
       if ((cmp(out,elt))==0) break;                                                            \
     }                                                                                          \
-} while(0) 
+} while(0)
 
 #endif /* UTLIST_H */
 
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth.h b/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth.h
new file mode 100644 (file)
index 0000000..a6574c7
--- /dev/null
@@ -0,0 +1,4474 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_H__
+#define __TIZEN_NETWORK_BLUETOOTH_H__
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdbool.h>
+#include <tizen_error.h>
+
+#include "bluetooth_type.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @file        bluetooth.h
+ * @brief       API to control the Bluetooth adapter and devices and communications.
+ * @ingroup     CAPI_NETWORK_BLUETOOTH_MODULE
+ */
+
+
+/**
+ * @addtogroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @{
+ */
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @brief Initializes the Bluetooth API.
+ * @since_tizen 2.3
+ *
+ * @remarks This function must be called before Bluetooth API starts. \n
+ * You must free all resources of the Bluetooth service by calling bt_deinitialize() if Bluetooth service is no longer needed.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @see  bt_deinitialize()
+ */
+int bt_initialize(void);
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @brief Releases all resources of the Bluetooth API.
+ * @since_tizen 2.3
+ *
+ * @remarks This function must be called if Bluetooth API is no longer needed.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre Bluetooth API must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ */
+int bt_deinitialize(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Enables the local Bluetooth adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function enables Bluetooth protocol stack and hardware.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_ALREADY_DONE  Already enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_DISABLED
+ * @post This function invokes bt_adapter_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ * @see bt_adapter_state_changed_cb()
+ *
+ */
+int bt_adapter_enable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Disables the local Bluetooth adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function disables Bluetooth protocol stack and hardware.
+ *
+ * @remarks You should disable Bluetooth adapter, which is helpful for saving power.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
+ * @post This function invokes bt_adapter_state_changed_cb().
+ *
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_state_changed_cb()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb ()
+ *
+ */
+int bt_adapter_disable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Recover the local Bluetooth adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function does recovery logic, disables Bluetooth protocol stack and hardware, then enables after a few seconds.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
+ * @post This function invokes bt_adapter_state_changed_cb().
+ *
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_state_changed_cb()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb ()
+ *
+ */
+int bt_adapter_recover(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Reset the local Bluetooth adapter, synchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function resets Bluetooth protocol and values.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_state_changed_cb() will be invoked if The state of local Bluetooth was #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ * @see bt_adapter_state_changed_cb()
+ *
+ */
+int bt_adapter_reset(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the current state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @param[out] adapter_state The current adapter state
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ */
+int bt_adapter_get_state(bt_adapter_state_e *adapter_state);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the address of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @remarks The @a local_address must be released with free() by you.
+ *
+ * @param[out] local_address The device address of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_get_name()
+ */
+int bt_adapter_get_address(char **local_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the version of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @remarks The @a local_version must be released with free() by you.
+ *
+ * @param[out] local_version The version of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_adapter_get_version(char **local_version);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the information regarding local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @remarks The @a all parameters must be released with free() by you.
+ *
+ * @param[out] chipset Chipset name of local Bluetooth adapter
+ * @param[out] firmware Firmware info. of local Bluetooth adapter
+ * @param[out] stack_version Bluetooth stack version
+ * @param[out] profiles The profile list of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_adapter_get_local_info(char **chipset, char **firmware, char **stack_version, char **profiles);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the name of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @details Use this function to get the friendly name associated with Bluetooth
+ * device, retrieved by the remote Bluetooth devices.
+ *
+ * @remarks The @a local_name must be released with free() by you.
+ *
+ * @param[out] local_name  The local device name
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_set_name()
+ */
+int bt_adapter_get_name(char **local_name);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the name of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] local_name The name of the Bluetooth device. \n
+ *                             The maximum length is 248 characters.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_name_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_get_name()
+ * @see bt_adapter_name_changed_cb()
+ * @see bt_adapter_set_name_changed_cb()
+ * @see bt_adapter_unset_name_changed_cb()
+ */
+int bt_adapter_set_name(const char *local_name);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Gets the visibility mode of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @param[out] mode  The visibility mode of the Bluetooth device
+ * @param[out] duration  The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds).
+ * @a duration is valid only if @a mode is #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE. This value can be NULL.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_adapter_get_visibility(bt_adapter_visibility_mode_e *mode, int *duration);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the visibility mode.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE will change to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE
+ * after the given @a duration goes.
+ *
+ * @param[in] discoverable_mode The Bluetooth visibility mode to set
+ * @param[in] duration The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds).
+ * @a duration is used only for #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE mode.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_visibility_mode_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_get_visibility()
+ * @see bt_adapter_visibility_mode_changed_cb()
+ * @see bt_adapter_set_visibility_mode_changed_cb()
+ * @see bt_adapter_unset_visibility_mode_changed_cb()
+ */
+int bt_adapter_set_visibility(bt_adapter_visibility_mode_e discoverable_mode, int duration);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Starts the device discovery, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @details If a device is discovered, bt_adapter_device_discovery_state_changed_cb() will be invoked
+ * with #BT_ADAPTER_DEVICE_DISCOVERY_FOUND, and then bt_adapter_device_discovery_state_changed_cb()
+ * will be called with #BT_ADAPTER_DEVICE_DISCOVERY_FINISHED in case of the completion or cancellation of the discovery.
+ *
+ * @remarks To connect to peer Bluetooth device, you need to know its Bluetooth address. \n
+ * The device discovery can be stopped by bt_adapter_stop_device_discovery().
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation is now in progress
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post This function invokes bt_adapter_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_is_discovering()
+ * @see bt_adapter_stop_device_discovery()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_start_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Stops the device discovery, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks The device discovery process will take 10 ~ 20 seconds to get all the devices in vicinity.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation is not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The device discovery must be in progress with bt_adapter_start_device_discovery().
+ * @post This function invokes bt_adapter_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_is_discovering()
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ */
+int bt_adapter_stop_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Checks for the device discovery is in progress or not.
+ * @since_tizen 2.3
+ *
+ * @remarks If Bluetooth discovery is in progress, other operations are not allowed and
+ * you have to either stop the discovery operation, or wait for it to be finished,
+ * before performing other operations.
+
+ * @param[out] is_discovering The discovering status: (@c true = in progress , @c  false = not in progress )
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_adapter_stop_device_discovery()
+ */
+int bt_adapter_is_discovering(bool *is_discovering);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Get the service mask from the uuid list.
+ * @since_tizen 2.3
+ *
+ * @param[in] uuids The UUID list of the device.
+ * @param[in] no_of_service The number of the UUID list count.
+ * @param[out] service_mask_list Service mask list converted from the given UUID list.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @see bt_service_class_t
+ */
+int bt_device_get_service_mask_from_uuid_list(char **uuids,
+                                     int no_of_service,
+                                     bt_service_class_t *service_mask_list);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Retrieves the device information of all bonded devices.
+ * @since_tizen 2.3
+ *
+ * @param [in] callback The callback function to invoke
+ * @param [in] user_data The user data passed from the foreach function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post This function invokes bt_adapter_bonded_device_cb().
+ *
+ * @see bt_adapter_bonded_device_cb()
+ */
+int bt_adapter_foreach_bonded_device(bt_adapter_bonded_device_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the device information of a bonded device.
+ * @since_tizen 2.3
+ * @remarks The @a device_info must be released with bt_adapter_free_device_info() by you .
+ *
+ * @param [in] remote_address The address of remote device
+ * @param [out] device_info The bonded device information
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post This function invokes bt_adapter_bonded_device_cb().
+ *
+ * @see bt_adapter_bonded_device_cb()
+ */
+int bt_adapter_get_bonded_device_info(const char *remote_address, bt_device_info_s **device_info);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Frees device info.
+ * @since_tizen 2.3
+ *
+ * @param [in] device_info The bonded device information
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @see bt_adapter_get_bonded_device_info()
+ */
+int bt_adapter_free_device_info(bt_device_info_s *device_info);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Checks whether the UUID of service is used or not
+ * @since_tizen 2.3
+ * @param[in] service_uuid The UUID of service
+ * @param[out] used Indicates whether the service is used or not
+ * @return true on success, otherwise false.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ */
+int bt_adapter_is_service_used(const char *service_uuid, bool *used);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Registers a callback function to be invoked when the Bluetooth adapter state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data        The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_state_changed_cb()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ */
+int bt_adapter_set_state_changed_cb(bt_adapter_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_state_changed_cb()
+ */
+int bt_adapter_unset_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Registers a callback function to be invoked when the name of Bluetooth adapter changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post  bt_adapter_name_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_name_changed_cb()
+ * @see bt_adapter_unset_name_changed_cb()
+ */
+int bt_adapter_set_name_changed_cb(bt_adapter_name_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_name_changed_cb()
+ */
+int bt_adapter_unset_name_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Registers a callback function to be invoked when the visibility mode changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_visibility_mode_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_visibility_mode_changed_cb()
+ * @see bt_adapter_unset_visibility_mode_changed_cb()
+ */
+int bt_adapter_set_visibility_mode_changed_cb(bt_adapter_visibility_mode_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre  The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see  bt_initialize()
+ * @see  bt_adapter_set_visibility_mode_changed_cb()
+ */
+int bt_adapter_unset_visibility_mode_changed_cb(void);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Registers a callback function to be invoked every second
+ * @since_tizen 2.3
+ * until the visibility mode is changed from #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE
+ * to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
+ * @details  When you set visibility mode as #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE,
+ * @a callback will be called every second until visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
+ * @param[in]  callback  The callback function to register
+ * @param[in]  user_data  The user data to be passed to the callback function
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre  The Bluetooth service must be initialized by bt_initialize().
+ * @post  bt_adapter_visibility_duration_changed_cb() will be invoked.
+ * @see  bt_initialize()
+ * @see  bt_adapter_visibility_duration_changed_cb()
+ * @see  bt_adapter_unset_visibility_duration_changed_cb()
+ */
+int bt_adapter_set_visibility_duration_changed_cb(bt_adapter_visibility_duration_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief       Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre  The Bluetooth service must be initialized with bt_initialize().
+ * @see  bt_initialize()
+ * @see  bt_adapter_set_visibility_duration_changed_cb()
+ */
+int bt_adapter_unset_visibility_duration_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Registers a callback function to be invoked when the device discovery state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_device_discovery_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_set_device_discovery_state_changed_cb(bt_adapter_device_discovery_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ */
+int bt_adapter_unset_device_discovery_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Get the Hash and Randmoizer value, synchronously.
+ * @since_tizen 2.3
+ *
+ * @param[out] hash The hash value recieved from the controller
+ * @param[out] randomizer The hash value recieved from the controller
+ * @param[out] hash_len The length of the hash value
+ * @param[out] randomizer_len The length of the randomizer value
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_get_local_oob_data(unsigned char **hash, unsigned char **randomizer,
+                                       int *hash_len, int *randomizer_len);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the Hash and Randmoizer value, synchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address Remote device address
+ * @param[in] hash The hash value recieved from the controller
+ * @param[in] randomizer The hash value recieved from the controller
+ * @param[in] hash_len The length of the hash value. Allowed value is 16
+ * @param[in] randomizer_len The length of the randomizer value. Allowed value is 16
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_set_remote_oob_data(const char *remote_address,
+                               unsigned char *hash, unsigned char *randomizer,
+                               int hash_len, int randomizer_len);
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Deletes the Hash and Randomizer value, synchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address Remote device address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_remove_remote_oob_data(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Registers a callback function to be invoked when the connectable state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_connectable_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_connectable_changed_cb()
+ * @see bt_adapter_unset_connectable_changed_cb()
+ */
+int bt_adapter_set_connectable_changed_cb(bt_adapter_connectable_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre  The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see  bt_initialize()
+ * @see  bt_adapter_set_connectable_changed_cb()
+ */
+int bt_adapter_unset_connectable_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Gets the connectable state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @remarks When connectable state is false, no device can connect to this device and visibility mode cannot be changed.
+ *
+ * @param[out] connectable The connectable state of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_set_connectable()
+ */
+int bt_adapter_get_connectable(bool *connectable);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Sets the connectable state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks When connectable state is false, no device can connect to this device and visibility mode cannot be changed.
+ *
+ * @param[in] connectable The connectable state to set
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_connectable_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_get_connectable()
+ * @see bt_adapter_connectable_changed_cb()
+ * @see bt_adapter_set_connectable_changed_cb()
+ * @see bt_adapter_unset_connectable_changed_cb()
+ */
+int bt_adapter_set_connectable(bool connectable);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enables the local Bluetooth le adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function enables Bluetooth protocol stack and hardware.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_ALREADY_DONE  Already enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ * @post This function invokes bt_adapter_le_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_get_state()
+ * @see bt_adapter_le_set_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb()
+ * @see bt_adapter_le_state_changed_cb()
+ *
+ */
+int bt_adapter_le_enable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Disables the local Bluetooth le adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function disables Bluetooth le protocol stack and hardware.
+ *
+ * @remarks
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_LE_ENABLED
+ * @post This function invokes bt_adapter_le_state_changed_cb().
+ *
+ * @see bt_adapter_le_get_state()
+ * @see bt_adapter_le_state_changed_cb()
+ * @see bt_adapter_le_set_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb ()
+ *
+ */
+int bt_adapter_le_disable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Gets the current state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @param[out] adapter_le_state The current adapter le state
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ */
+int bt_adapter_le_get_state(bt_adapter_le_state_e *adapter_le_state);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Starts the LE device discovery for a BT_ADAPTER_DEVICE_DISCOVERY_LE type.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @details If a LE device is discovered, bt_adapter_le_device_discovery_state_changed_cb()
+*  will be invoked with #BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND, and then bt_adapter_le_device_discovery_state_changed_cb()
+ * will be called with #BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED in case of the completion or cancellation of the discovery.
+ *
+ * @remarks To connect to peer Bluetooth device, you need to know its Bluetooth address. \n
+ * The device discovery can be stopped by bt_adapter_le_stop_device_discovery().
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation is now in progress
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * or must be #BT_ADAPTER_LE_ENABLED.
+ * @post This function invokes bt_adapter_le_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_le_is_discovering()
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_start_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Stops the LE device discovery, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation is not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The device discovery must be in progress with bt_adapter_le_start_device_discovery().
+ * @post This function invokes bt_adapter_le_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_le_is_discovering()
+ * @see bt_adapter_le_start_device_discovery()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_stop_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Checks for the LE device discovery is in progress or not.
+ * @since_tizen 2.3
+ *
+ * @remarks If Bluetooth LE discovery is in progress, other operations are not allowed and
+ * you have to either stop the LE discovery operation, or wait for it to be finished,
+ * before performing other operations.
+
+ * @param[out] is_discovering The discovering status: (@c true = in progress , @c  false = not in progress )
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * or must be #BT_ADAPTER_LE_ENABLED.
+ *
+ * @see bt_adapter_le_start_device_discovery()
+ * @see bt_adapter_le_stop_device_discovery()
+ */
+int bt_adapter_le_is_discovering(bool *is_discovering);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Registers a callback function to be invoked when the LE device discovery state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_le_device_discovery_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_set_device_discovery_state_changed_cb(bt_adapter_le_device_discovery_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_unset_device_discovery_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Registers a callback function to be invoked when the Bluetooth adapter le state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data        The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_le_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb()
+ */
+int bt_adapter_le_set_state_changed_cb(bt_adapter_le_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_set_state_changed_cb()
+ */
+int bt_adapter_le_unset_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief add address to whitelist for accepting scanning request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks If the adress is in the whitelist then other LE devices are able to
+ * search this device. Before calling this API, make sure that the adapter is
+ * enabled. There is no callback event for this API.
+
+ * @param[in] address The other device's address
+ * @param[in] address_type The other device's address type
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Adapter is not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_stop_advertising()
+ */
+int bt_adapter_le_add_white_list(const char *address, bt_device_address_type_e address_type);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief remove address from the whitelist for not accepting scanning request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks If the adress is in the whitelist then other LE devices are able to
+ * search this device. Before calling this API, make sure that the adapter is
+ * enabled. There is no callback event for this API.
+ *
+ * @param[in] address The other device's address
+ * @param[in] address_type The other device's address type
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Adapter is not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_stop_advertising()
+ */
+int bt_adapter_le_remove_white_list(const char *address, bt_device_address_type_e address_type);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief clear address from the whitelist for not accepting scanning request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks If the adress is in the whitelist then other LE devices are able to
+ * search this device. Before calling this API, make sure that the adapter is
+ * enabled. There is no callback event for this API.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Adapter is not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_stop_advertising()
+ */
+int bt_adapter_le_clear_white_list(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Create advertiser to advertise device's existence or respond to LE scanning reqeust.
+ * @since_tizen 2.3
+ *
+ * @param[out] advertiser The handle of advertiser
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_destroy_advertiser()
+ */
+int bt_adapter_le_create_advertiser(bt_advertiser_h *advertiser);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Destroy advertiser.
+ * @since_tizen 2.3
+ *
+ * @param[out] advertiser The handle of advertiser
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_create_advertiser()
+ */
+int bt_adapter_le_destroy_advertiser(bt_advertiser_h advertiser);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Set the data to be advertised or responded to scan request from LE scanning device.
+ *        The maximum advertised or responded data size is 31 bytes
+ *        including data type and system wide data.
+ * @since_tizen 2.3
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] pkt_type The packet type
+ * @param[in] data_type The data type that is included in packet
+ * @param[in] data The data to be advertised or be responded to scan request from LE scanning device
+ * @param[in] data_size The size of data to be set.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_QUOTA_EXCEEDED  Quota exceeded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_remove_advertising_data()
+ * @see bt_adapter_le_clear_advertising_data()
+ */
+int bt_adapter_le_add_advertising_data(bt_advertiser_h advertiser,
+               bt_adapter_le_packet_type_e pkt_type, bt_adapter_le_packet_data_type_e data_type,
+               void *data, unsigned int data_size);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Unset the data to be advertised or responded to scan request from LE scanning device.
+ * @since_tizen 2.3
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] pkt_type The packet type
+ * @param[in] data_type The data type to be removed from selected packet
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_add_advertising_data()
+ * @see bt_adapter_le_clear_advertising_data()
+ */
+int bt_adapter_le_remove_advertising_data(bt_advertiser_h advertiser,
+               bt_adapter_le_packet_type_e pkt_type, bt_adapter_le_packet_data_type_e data_type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Clear all data to be advertised or responded to scan request from LE scanning device.
+ * @since_tizen 2.3
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] pkt_type The packet type to be cleared
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_add_advertising_data()
+ * @see bt_adapter_le_remove_advertising_data()
+ */
+int bt_adapter_le_clear_advertising_data(bt_advertiser_h advertiser, bt_adapter_le_packet_type_e pkt_type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Start advertising with passed advertiser and advertising parameters.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @details Once Bluetooth advertising is started, nearby Bluetooth LE(Low Energy) supported
+ * devices can know this device's existence. And one of them can make a connection reqeust,
+ * if it is allowed.
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] adv_params The parameters of advertising \n
+ * If NULL is passed, default values which are defined in driver / controller are used.
+ * @param[in] cb The callback to report the result of this function
+ * @param[in] user_data The user data to be passed when callback is called
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation is now in progress
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post This function invokes bt_adapter_le_advertising_state_changed_cb().
+ *
+ * @see bt_adapter_le_stop_advertising()
+ * @see bt_adapter_le_advertising_state_changed_cb()
+ */
+int bt_adapter_le_start_advertising(bt_advertiser_h advertiser, bt_adapter_le_advertising_params_s *adv_params,
+               bt_adapter_le_advertising_state_changed_cb cb, void *user_data);
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Stops the advertising.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] advertiser The handle of advertiser
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation is not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The advertising must be going on with bt_adapter_le_start_advertising().
+ * @post This function invokes bt_adapter_le_advertising_state_changed_cb().
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_advertising_state_changed_cb()
+ */
+int bt_adapter_le_stop_advertising(bt_advertiser_h advertiser);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Sets the Privacy feature state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] enable_privacy The privacy feature to set/unset.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_LE_ENABLED.
+ *
+ */
+int bt_adapter_le_enable_privacy(bool enable_privacy);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Creates a bond with a remote Bluetooth device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A bond can be destroyed by bt_device_destroy_bond().\n
+ * The bonding request can be cancelled by bt_device_cancel_bonding().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device with which the bond should be created
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @post This function invokes bt_device_bond_created_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_cancel_bonding()
+ * @see bt_device_destroy_bond()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_create_bond(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Creates a bond with a remote Bluetooth device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks A bond can be destroyed by bt_device_destroy_bond().\n
+ * The bonding request can be cancelled by bt_device_cancel_bonding().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device with which the bond should be created
+ * @param[in] conn_type The connection type(LE or BREDR) to create bond with remote device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY     Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @post This function invokes bt_device_bond_created_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_cancel_bonding()
+ * @see bt_device_destroy_bond()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_create_bond_by_type(const char *remote_address,
+                                 bt_device_connection_link_type_e conn_type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Cancels the bonding process.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks Use this function when the remote Bluetooth device is not responding to the
+ * bond request or you wish to cancel the bonding request.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation not in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The creating a bond must be in progress by bt_device_create_bond().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_cancel_bonding(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Destroys the bond, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device to remove bonding
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post This function invokes bt_device_bond_destroyed_cb().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_destroyed_cb()
+ * @see bt_device_set_bond_destroyed_cb()
+ * @see bt_device_unset_bond_destroyed_cb()
+ */
+int bt_device_destroy_bond(const char *remote_address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Sets an alias for the bonded device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device
+ * @param[in] alias The alias of the remote Bluetooth device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ *
+ * @see bt_device_create_bond()
+ */
+int bt_device_set_alias(const char *remote_address, const char *alias);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Sets the authorization of a bonded device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks Once a device is authorized, you don't need to receive a confirmation.
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device to authorize
+ * @param[in] authorization_state The Bluetooth authorization state
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post bt_device_authorization_changed_cb() will be invoked.
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_authorization_changed_cb()
+ * @see bt_device_set_authorization_changed_cb()
+ * @see bt_device_unset_authorization_changed_cb()
+ */
+int bt_device_set_authorization(const char *remote_address, bt_device_authorization_e authorization_state);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Starts the search for services supported by the specified device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks If creating a bond succeeds, which means bt_device_bond_created_cb() is called with result #BT_ERROR_NONE,
+ * then you don't need to run this function.\n
+ * The service search takes a couple of seconds to complete normally. \n
+ * The service search can be canceled by bt_device_cancel_service_search().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device whose services need to be checked
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ * @retval #BT_ERROR_SERVICE_SEARCH_FAILED  Service search failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post This function invokes bt_device_service_searched_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_service_searched_cb()
+ * @see bt_device_cancel_service_search()
+ * @see bt_device_set_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ */
+int bt_device_start_service_search(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Cancels service search process.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ * @retval #BT_ERROR_NOT_IN_PROGRESS  Operation not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The service search must be in progress by bt_device_start_service_search().
+ *
+ * @see bt_device_start_service_search()
+ * @see bt_device_service_searched_cb()
+ * @see bt_device_set_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ */
+int bt_device_cancel_service_search(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Gets the connected profiles.
+ * @since_tizen 2.3
+ * @param[in] remote_address The address of the remote device
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_device_connected_profile() will be invoked.
+ * @see bt_device_connected_profile()
+ */
+int bt_device_foreach_connected_profiles(const char *remote_address, bt_device_connected_profile callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Gets the profile connected status.
+ * @since_tizen 2.3
+ * @param[in] remote_address The address of the remote device
+ * @param[in] bt_profile wish to know bt_profile
+ * @param[out] connected_status the connected status
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_device_is_profile_connected(const char *remote_address, bt_profile_e bt_profile,
+                                       bool *connected_status);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Registers a callback function to be invoked when the bond creates.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post  bt_device_bond_created_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_set_bond_created_cb(bt_device_bond_created_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_bond_created_cb()
+ */
+int bt_device_unset_bond_created_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Registers a callback function to be invoked when the bond destroys.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post  bt_device_bond_destroyed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_bond_destroyed_cb()
+ * @see bt_device_unset_bond_destroyed_cb()
+ */
+int bt_device_set_bond_destroyed_cb(bt_device_bond_destroyed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_bond_destroyed_cb()
+ */
+int bt_device_unset_bond_destroyed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Registers a callback function to be invoked when the authorization of device changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post  bt_device_authorization_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_authorization_changed_cb()
+ * @see bt_device_set_authorization_changed_cb()
+ * @see bt_device_unset_authorization_changed_cb()
+ */
+int bt_device_set_authorization_changed_cb(bt_device_authorization_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_authorization_changed_cb()
+ */
+int bt_device_unset_authorization_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Registers a callback function to be invoked when the process of service search finishes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post  bt_device_service_searched_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ */
+int bt_device_set_service_searched_cb(bt_device_service_searched_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_service_searched_cb()
+ */
+int bt_device_unset_service_searched_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Registers a callback function to be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_device_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_connection_state_changed_cb()
+ * @see bt_device_unset_connection_state_changed_cb()
+ */
+int bt_device_set_connection_state_changed_cb(bt_device_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief      Unregisters the callback function to be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_connection_state_changed_cb()
+ */
+int bt_device_unset_connection_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Registers a rfcomm server socket with a specific UUID.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A socket can be destroyed by bt_socket_destroy_rfcomm().
+ *
+ * @param[in] service_uuid The UUID of service to provide
+ * @param[out] socket_fd The file descriptor of socket to listen
+ * @return 0 on success, otherwise a negative error value.
+ *
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_socket_listen_and_accept_rfcomm()
+ * @see bt_socket_destroy_rfcomm()
+ */
+int bt_socket_create_rfcomm(const char *service_uuid, int *socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Removes the rfcomm server socket which was created using bt_socket_create_rfcomm().
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks If callback function bt_socket_connection_state_changed_cb() is set and the remote Bluetooth device is connected,
+ * then bt_socket_connection_state_changed_cb() will be called when this function is finished successfully.
+ *
+ * @param[in] socket_fd The file descriptor of socket (which was created using bt_socket_create_rfcomm()) to destroy
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The socket must be created with bt_socket_create_rfcomm().
+ * @post If callback function bt_socket_connection_state_changed_cb() is set and the remote Bluetooth device is connected,
+ * then bt_socket_connection_state_changed_cb() will be called.
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_destroy_rfcomm(int socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Starts listening on passed rfcomm socket and accepts connection requests.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details Pop-up is shown automatically when a RFCOMM connection is requested.
+ * bt_socket_connection_state_changed_cb() will be called with
+ * #BT_SOCKET_CONNECTED if you click "yes" and connection is finished successfully.
+ * @param[in] socket_fd The file descriptor of socket on which start to listen
+ * @param[in] max_pending_connections The maximum number of pending connections
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The socket must be created with bt_socket_create_rfcomm().
+ * @post If callback function bt_socket_connection_state_changed_cb() is set,
+ * then bt_socket_connection_state_changed_cb() will be called when the remote Bluetooth device is connected.
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_listen_and_accept_rfcomm(int socket_fd, int max_pending_connections);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Starts listening on passed rfcomm socket.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @details bt_socket_connection_requested_cb() will be called when a RFCOMM connection is requested.
+ *
+ * @param[in] socket_fd  The file descriptor socket on which start to listen
+ * @param[in] max_pending_connections  The number of pending connections
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The socket must be created with bt_socket_create_rfcomm().
+ * @post This function invokes bt_socket_connection_state_changed_cb().
+ *
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_set_connection_requested_cb()
+ * @see bt_socket_unset_connection_requested_cb()
+ * @see bt_socket_connection_requested_cb()
+ */
+int bt_socket_listen(int socket_fd, int max_pending_connections);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Accepts a connection request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] requested_socket_fd  The file descriptor of socket on which a connection is requested
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The connection is requested by bt_socket_connection_requested_cb().
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_requested_cb()
+ * @see bt_socket_listen()
+ * @see bt_socket_reject()
+*/
+int bt_socket_accept(int requested_socket_fd);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Rejects a connection request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] socket_fd  The file descriptor of socket on which a connection is requested
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The connection is requested by bt_socket_connection_requested_cb().
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_requested_cb()
+ * @see bt_socket_listen()
+ * @see bt_socket_accept()
+ */
+int bt_socket_reject(int socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Connects to a specific RFCOMM based service on a remote Bluetooth device UUID, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A connection can be disconnected by bt_socket_disconnect_rfcomm().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device
+ * @param[in] service_uuid The UUID of service provided by the remote Bluetooth device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post This function invokes bt_socket_connection_state_changed_cb().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_start_service_search()
+ * @see bt_socket_disconnect_rfcomm()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_connect_rfcomm(const char *remote_address, const char *service_uuid);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Disconnects the RFCOMM connection with the given file descriptor of conneted socket.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] socket_fd  The file descriptor of socket to close which was received using bt_socket_connection_state_changed_cb().
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The connection must be established.
+ *
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_disconnect_rfcomm(int socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Sends data to the connected device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remark The specific error code can be obtained using the get_last_result() method. Error codes are described in Exception section.
+ *
+ * @param[in] socket_fd The file descriptor of connected socket which was received using bt_socket_connection_state_changed_cb()
+ * @param[in] data The data to be sent
+ * @param[in] length The length of data to be sent
+ *
+ * @return the number of bytes written (zero indicates nothing was written).
+ * @retval On error, -1 is returned, and errno is set appropriately. See write 2 man page.
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @exception BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @exception BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @exception BT_ERROR_AGAIN  Resource temporarily unavailable
+ *
+ * @pre The connection must be established.
+ *
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_send_data(int socket_fd, const char *data, int length);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Register a callback function that will be invoked when you receive data.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post  bt_socket_data_received_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_socket_data_received_cb()
+ * @see bt_socket_set_data_received_cb()
+ * @see bt_socket_unset_data_received_cb()
+ */
+int bt_socket_set_data_received_cb(bt_socket_data_received_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_socket_data_received_cb()
+ * @see bt_socket_set_data_received_cb()
+ */
+int bt_socket_unset_data_received_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Register a callback function that will be invoked when a RFCOMM connection is requested.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post If you listen a socket by bt_socket_listen(), bt_socket_connection_requested_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_socket_unset_connection_requested_cb()
+ */
+int bt_socket_set_connection_requested_cb(bt_socket_connection_requested_cb callback, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre  The Bluetooth service must be initialized with bt_initialize().
+ * @see  bt_initialize()
+ * @see  bt_socket_set_connection_requested_cb()
+ * @see  bt_socket_connection_requested_cb()
+ */
+int bt_socket_unset_connection_requested_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Register a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_socket_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_set_connection_state_changed_cb(bt_socket_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ */
+int bt_socket_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Initializes the Bluetooth OPP server requested by bt_opp_server_push_requested_cb().
+ * @since_tizen 2.3
+ * @details The popup appears when an OPP connection is requested from a remote device.
+ * If you accept the request, then connection will be established and bt_opp_server_push_requested_cb() will be called.
+ * At that time, you can call either bt_opp_server_accept() or bt_opp_server_reject().
+ * @remarks This function must be called to start Bluetooth OPP server. You must free all resources of the Bluetooth service
+ * by calling bt_opp_server_deinitialize() if Bluetooth OPP service is no longer needed.
+ * @param[in] destination  The destination path
+ * @param[in] push_requested_cb  The callback called when a push is requested
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @see  bt_opp_server_push_requested_cb()
+ * @see  bt_opp_server_deinitialize()
+ * @see  bt_opp_server_accept()
+ * @see  bt_opp_server_reject()
+ */
+int bt_opp_server_initialize(const char *destination, bt_opp_server_push_requested_cb push_requested_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Initializes the Bluetooth OPP server requested by bt_opp_server_connection_requested_cb().
+ * @since_tizen 2.3
+ * @details No popup appears when an OPP connection is requested from a remote device.
+ * Instead, @a connection_requested_cb() will be called.
+ * At that time, you can call either bt_opp_server_accept() or bt_opp_server_reject().
+ * @remarks This function must be called to start Bluetooth OPP server. \n
+ * You must free all resources of the Bluetooth service by calling bt_opp_server_deinitialize() if Bluetooth OPP service is no longer needed.
+ * @param[in] destination  The destination path
+ * @param[in] connection_requested_cb  The callback called when an OPP connection is requested
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @see  bt_opp_server_connection_requested_cb()
+ * @see  bt_opp_server_deinitialize()
+ * @see  bt_opp_server_accept_connection()
+ * @see  bt_opp_server_reject_connection()
+ */
+int bt_opp_server_initialize_by_connection_request(const char *destination, bt_opp_server_connection_requested_cb connection_requested_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Denitializes the Bluetooth OPP server.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @see  bt_opp_server_initialize()
+ * @see  bt_opp_server_deinitialize()
+ */
+int bt_opp_server_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Accepts the push request from the remote device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks If you initialize OPP server by bt_opp_server_initialize_by_connection_request(), then name is ignored.
+ * You can cancel the pushes by bt_opp_server_cancel_transfer() with transfer_id.
+ * @param[in] progress_cb  The callback called when a file is being transfered
+ * @param[in] finished_cb  The callback called when a transfer is finished
+ * @param[in] name  The name to store. This can be NULL if you initialize OPP server by bt_opp_server_initialize_by_connection_request().
+ * @param[in] user_data The user data to be passed to the callback function
+ * @param[out]  transfer_id  The ID of transfer
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see  bt_opp_server_reject()
+ */
+int bt_opp_server_accept(bt_opp_server_transfer_progress_cb progress_cb, bt_opp_server_transfer_finished_cb finished_cb, const char *name,
+ void *user_data, int *transfer_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Rejects the push request from the remote device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see  bt_opp_server_accept()
+ */
+int bt_opp_server_reject(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Cancels the transfer.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] transfer_id  The ID of transfer
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see  bt_opp_server_accept_connection()
+ * @see  bt_opp_server_accept()
+ */
+int bt_opp_server_cancel_transfer(int transfer_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Sets the destination path of file to be pushed.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] destination  The destination path of file to be pushed
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see  bt_opp_server_initialize()
+ */
+int bt_opp_server_set_destination(const char *destination);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Initializes the Bluetooth OPP client.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth OPP client starts. \n
+ * You must free all resources of the Bluetooth service by calling bt_opp_client_deinitialize()
+ * if Bluetooth OPP service is no longer needed.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @see  bt_opp_client_deinitialize()
+ */
+int bt_opp_client_initialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Denitializes the Bluetooth OPP client.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @see  bt_opp_client_initialize()
+ */
+int bt_opp_client_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Adds file to be pushed.
+ * @since_tizen 2.3
+ * @param[in] file  The path of file to be pushed
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see  bt_opp_client_clear_files()
+ * @see  bt_opp_client_push_files()
+ */
+int bt_opp_client_add_file(const char *file);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Adds file to be pushed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @see  bt_opp_client_add_file()
+ * @see  bt_opp_client_push_files()
+ */
+int bt_opp_client_clear_files(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Pushes the file to the remote device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details At first, bt_opp_client_push_responded_cb() will be called when OPP server responds to the push request.
+ * After connection is established, bt_opp_client_push_progress_cb() will be called repeatedly until a file is tranfered completely.
+ * If you send several files, then bt_opp_client_push_progress_cb() with another file will be called repeatedly until the file is tranfered completely.
+ * bt_opp_client_push_finished_cb() will be called when the push request is finished.
+ * @param[in] remote_address The remote address
+ * @param[in] responded_cb  The callback called when OPP server responds to the push request
+ * @param[in] progress_cb  The callback called when each file is being transfered
+ * @param[in] finished_cb  The callback called when the push request is finished
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_NOW_IN_PROGRESS  Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see bt_opp_client_initialize()
+ * @see bt_opp_client_cancel_push
+ */
+int bt_opp_client_push_files(const char *remote_address, bt_opp_client_push_responded_cb responded_cb,
+ bt_opp_client_push_progress_cb progress_cb, bt_opp_client_push_finished_cb finished_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Cancels the push request in progress, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre bt_opp_client_push_files() must be called.
+ * @post bt_opp_client_push_finished_cb() will be invoked with result #BT_ERROR_CANCELLED,
+ * which is a parameter of bt_opp_client_push_files().
+ * @see bt_opp_client_initialize()
+ * @see bt_opp_client_push_files()
+ */
+int bt_opp_client_cancel_push(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Initializes the Bluetooth HID(Human Interface Device) Host.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth HID Host starts. \n
+ * You must free all resources of the Bluetooth service by calling bt_hid_host_deinitialize()
+ * if Bluetooth HID Host service is no longer needed.
+ * @param[in] connection_cb  The callback called when the connection state is changed
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see  bt_hid_host_deinitialize()
+ */
+int bt_hid_host_initialize(bt_hid_host_connection_state_changed_cb connection_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Deinitializes the Bluetooth HID(Human Interface Device) Host.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @pre The Bluetooth HID service must be initialized with bt_hid_host_initialize().
+ * @see  bt_hid_host_initialize()
+ */
+int bt_hid_host_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Connects the remote device with the HID(Human Interface Device) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address  The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @pre The Bluetooth HID service must be initialized with bt_hid_host_initialize().
+ * @post bt_hid_host_connection_state_changed_cb() will be invoked.
+ * @see bt_hid_host_disconnect()
+ * @see bt_hid_host_connection_state_changed_cb()
+ */
+int bt_hid_host_connect(const char *remote_address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Disconnects the remote device with the HID(Human Interface Device) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address  The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected by bt_hid_host_connect().
+ * @post bt_hid_host_connection_state_changed_cb() will be invoked.
+ * @see bt_hid_host_connect()
+ * @see bt_hid_host_connection_state_changed_cb()
+ */
+int bt_hid_host_disconnect(const char *remote_address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Initializes the Bluetooth profiles related with audio.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth profiles related with audio starts. \n
+ * You must free all resources of the this service by calling bt_audio_deinitialize()
+ * if Bluetooth profiles related with audio service is no longer needed.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_audio_deinitialize()
+ */
+int bt_audio_initialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Deinitializes the Bluetooth profiles related with audio.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ */
+int bt_audio_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Connects the remote device with the given audio profile, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details If you input type as #BT_AUDIO_PROFILE_TYPE_ALL and connection request succeeds, then bt_audio_connection_state_changed_cb() will be called twice
+ * when #BT_AUDIO_PROFILE_TYPE_HSP_HFP is connected and #BT_AUDIO_PROFILE_TYPE_A2DP is connected.
+ * @param[in] remote_address  The remote address
+ * @param[in] type  The type of audio profile
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @post bt_audio_connection_state_changed_cb() will be invoked.
+ * @see bt_audio_disconnect()
+ * @see bt_audio_connection_state_changed_cb()
+ */
+int bt_audio_connect(const char *remote_address, bt_audio_profile_type_e type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Disconnects the remote device with the given audio profile, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details If you input type as #BT_AUDIO_PROFILE_TYPE_ALL and disconnection request succeeds, then bt_audio_connection_state_changed_cb() will be called twice
+ * when #BT_AUDIO_PROFILE_TYPE_HSP_HFP is disconnected and #BT_AUDIO_PROFILE_TYPE_A2DP is disconnected.
+ * @param[in] remote_address  The remote address
+ * @param[in] type  The type of audio profile
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The remote device must be connected by bt_audio_connect().
+ * @post bt_audio_connection_state_changed_cb() will be invoked.
+ * @see bt_audio_connect()
+ * @see bt_audio_connection_state_changed_cb()
+ */
+int bt_audio_disconnect(const char *remote_address, bt_audio_profile_type_e type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief  Registers a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_audio_connection_state_changed_cb()
+ * @see bt_panu_unset_connection_state_changed_cb()
+ */
+int bt_audio_set_connection_state_changed_cb(bt_audio_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_audio_connection_state_changed_cb()
+ * @see bt_audio_set_connection_state_changed_cb()
+ */
+int bt_audio_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Opens a SCO(Synchronous Connection Oriented link) to connected remote device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_ALREADY_DONE  Operation is already done
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @post bt_ag_sco_state_changed_cb() will be invoked.
+ * @see bt_ag_close_sco()
+ * @see bt_ag_sco_state_changed_cb()
+ * @see bt_audio_connect()
+ */
+int bt_ag_open_sco(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Closes an opened SCO(Synchronous Connection Oriented link), asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The SCO must be opened with bt_ag_open_sco().
+ * @post bt_ag_sco_state_changed_cb() will be invoked.
+ * @see bt_ag_open_sco()
+ * @see bt_ag_sco_state_changed_cb()
+ */
+int bt_ag_close_sco(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Checks whether an opened SCO(Synchronous Connection Oriented link) exists or not.
+ * @since_tizen 2.3
+ * @param[out] opened The SCO status: (@c true = opened, @c  false = not opened)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_ag_open_sco()
+ * @see bt_ag_close_sco()
+ */
+int bt_ag_is_sco_opened(bool *opened);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Registers a callback function that will be invoked when the SCO(Synchronous Connection Oriented link) state is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_sco_state_changed_cb()
+ * @see bt_ag_unset_sco_state_changed_cb()
+ */
+int bt_ag_set_sco_state_changed_cb(bt_ag_sco_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the SCO(Synchronous Connection Oriented link) state is changed.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_sco_state_changed_cb()
+ * @see bt_ag_set_sco_state_changed_cb()
+ */
+int bt_ag_unset_sco_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the call event to the remote bluetooth device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @remarks Before notifying #BT_AG_CALL_EVENT_ANSWERED or #BT_AG_CALL_EVENT_DIALING, you should open SCO(Synchronous Connection Oriented link)
+ * if Bluetooth Hands-Free need SCO connection.
+ * @param[in] event  The call event
+ * @param[in] call_id  The call ID
+ * @param[in] phone_number  The phone number. You must set this value in case of #BT_AG_CALL_EVENT_DIALING and #BT_AG_CALL_EVENT_INCOMING.
+ * In other cases, this value can be NULL.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_call_event(bt_ag_call_event_e event, unsigned int call_id, const char *phone_number);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the call list to the remote bluetooth device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] list  The call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_call_list(bt_call_list_h list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the state of voice recognition.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state  The state of voice recognition: (@c true = enabled, @c  false = disabled)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_voice_recognition_state(bool state);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Registers a callback function that will be invoked when a call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_call_handling_event_cb()
+ * @see bt_ag_unset_call_handling_event_cb()
+ */
+int bt_ag_set_call_handling_event_cb(bt_ag_call_handling_event_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Unregisters a callback function that will be invoked when a call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_call_handling_event_cb()
+ * @see bt_ag_set_call_handling_event_cb()
+ */
+int bt_ag_unset_call_handling_event_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Registers a callback function that will be invoked when a multi call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_multi_call_handling_event_cb()
+ * @see bt_ag_unset_multi_call_handling_event_cb()
+ */
+int bt_ag_set_multi_call_handling_event_cb(bt_ag_multi_call_handling_event_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Unregisters a callback function that will be invoked when a multi call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_multi_call_handling_event_cb()
+ * @see bt_ag_set_multi_call_handling_event_cb()
+ */
+int bt_ag_unset_multi_call_handling_event_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Registers a callback function that will be invoked when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_dtmf_transmitted_cb()
+ * @see bt_ag_unset_dtmf_transmitted_cb()
+ */
+int bt_ag_set_dtmf_transmitted_cb(bt_ag_dtmf_transmitted_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Unregisters a callback function that will be invoked when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_dtmf_transmitted_cb()
+ * @see bt_ag_set_dtmf_transmitted_cb()
+ */
+int bt_ag_unset_dtmf_transmitted_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Notifies the speaker gain to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @details This function sends a signal to the remote device. This signal has the gain value.
+ * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
+ * When the speaker gain of remote device is changed to the requested gain, bt_audio_speaker_gain_changed_cb() will be called.
+ * @param[in] gain The gain of speaker (0 ~ 15)
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_ag_get_speaker_gain()
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+int bt_ag_notify_speaker_gain(int gain);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Gets the current speaker gain of the remote device.
+ * @since_tizen 2.3
+ * @details This function gets the value of speaker gain of the remote device.
+ * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
+ * @param[out] gain The gain of speaker (0 ~ 15)
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_ag_notify_speaker_gain()
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+int bt_ag_get_speaker_gain(int *gain);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Checks whether the remoted device enables NREC(Noise Reduction and Echo Canceling) or not.
+ * @since_tizen 2.3
+ * @param[out] enabled The NREC status: (@c true = enabled, @c  false = not enabled)
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_audio_connect()
+ */
+int bt_ag_is_nrec_enabled(bool *enabled);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Registers a callback function that will be invoked when the speaker gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @details This function let you know the change of the speaker gain of the remote device.
+ * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+int bt_ag_set_speaker_gain_changed_cb(bt_ag_speaker_gain_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the speaker gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ */
+int bt_ag_unset_speaker_gain_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Registers a callback function that will be invoked when the microphone gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_unset_microphone_gain_changed_cb()
+ */
+int bt_ag_set_microphone_gain_changed_cb(bt_ag_microphone_gain_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the microphone gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED  Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_set_microphone_gain_changed_cb()
+ */
+int bt_ag_unset_microphone_gain_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Creates a handle of call list.
+ * @since_tizen 2.3
+ * @param[out] list  The handle of call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see bt_call_list_destroy()
+ */
+int bt_call_list_create(bt_call_list_h *list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Destroys the handle of call list.
+ * @since_tizen 2.3
+ * @param[in] list  The handle of call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @see bt_call_list_create()
+ */
+int bt_call_list_destroy(bt_call_list_h list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Resets the handle of call list.
+ * @since_tizen 2.3
+ * @param[in] list  The handle of call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @see bt_call_list_create()
+ */
+int bt_call_list_reset(bt_call_list_h list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Adds a call to the handle of call list.
+ * @since_tizen 2.3
+ * @param[in] list  The handle of call list
+ * @param[in] call_id  The call ID
+ * @param[in] state  The state of audio gate call
+ * @param[in] phone_number The phone number. You must set this value in case of #BT_AG_CALL_EVENT_DIALING and      #BT_AG_CALL_EVENT_INCOMING.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @see bt_call_list_create()
+ */
+int bt_call_list_add(bt_call_list_h list, unsigned int call_id, bt_ag_call_state_e state, const char *phone_number);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Initializes the Bluetooth AVRCP(Audio/Video Remote Control Profile) service.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth AVRCP service. \n
+ * You must free all resources of the this service by calling bt_avrcp_target_deinitialize()
+ * if Bluetooth AVRCP service is no longer needed.
+ * @param[in] callback The callback function called when the connection state is changed
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_target_deinitialize()
+ */
+int bt_avrcp_target_initialize(bt_avrcp_target_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Deinitializes the Bluetooth AVRCP(Audio/Video Remote Control Profile) service.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth audio service must be initialized with bt_avrcp_target_initialize().
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_deinitialize(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Notifies the equalize state to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state The state of equalizer
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_equalizer_state(bt_avrcp_equalizer_state_e state);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Notifies the repeat mode to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] mode The repeat mode
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_repeat_mode(bt_avrcp_repeat_mode_e mode);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Notifies the shuffle mode to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] mode The repeat mode
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_shuffle_mode(bt_avrcp_shuffle_mode_e mode);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Notifies the scan mode to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] mode The scan mode
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_scan_mode(bt_avrcp_scan_mode_e mode);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Notifies the player state to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state The player state
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_player_state(bt_avrcp_player_state_e state);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Notifies the current position of song to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] position The current position in milliseconds
+ * @return  0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_position(unsigned int position);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Notifies the track to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] title The title of track
+ * @param[in] artist The artist of track
+ * @param[in] album The album of track
+ * @param[in] genre The genre of track
+ * @param[in] track_num The track number
+ * @param[in] total_tracks The number of all tracks
+ * @param[in] duration The duration of track in milliseconds
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_track(const char *title, const char *artist, const char *album, const char *genre, unsigned int track_num, unsigned int total_tracks, unsigned int duration);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Registers a callback function that will be invoked when the equalizer state is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_equalizer_state_changed_cb()
+ */
+int bt_avrcp_set_equalizer_state_changed_cb(bt_avrcp_equalizer_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the equalizer state is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_equalizer_state_changed_cb()
+ */
+int bt_avrcp_unset_equalizer_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Registers a callback function that will be invoked when the repeat mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_repeat_mode_changed_cb()
+ */
+int bt_avrcp_set_repeat_mode_changed_cb(bt_avrcp_repeat_mode_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the repeat mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_repeat_mode_changed_cb()
+ */
+int bt_avrcp_unset_repeat_mode_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Registers a callback function that will be invoked when the shuffle mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_shuffle_mode_changed_cb()
+ */
+int bt_avrcp_set_shuffle_mode_changed_cb(bt_avrcp_shuffle_mode_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the shuffle mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_shuffle_mode_changed_cb()
+ */
+int bt_avrcp_unset_shuffle_mode_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Registers a callback function that will be invoked when the scan mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_scan_mode_changed_cb()
+ */
+int bt_avrcp_set_scan_mode_changed_cb(bt_avrcp_scan_mode_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the scan mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_scan_mode_changed_cb()
+ */
+int bt_avrcp_unset_scan_mode_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Registers an application that acts as the @a Sink role of HDP(Health Device Profile).
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks The @a app_id must be released with free() by you.
+ * @param[in] data_type  The data type of MDEP. This value is defined in ISO/IEEE 11073-20601 spec.
+ * For example, pulse oximeter is 0x1004 and blood pressure monitor is 0x1007.
+ * @param[out] app_id  The ID of application
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_hdp_deactivate_sink()
+ */
+int bt_hdp_register_sink_app(unsigned short data_type, char **app_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Unregisters the given application that acts as the @a Sink role of HDP(Health Device Profile).
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] app_id  The ID of application
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @see bt_hdp_register_sink_app()
+ */
+int bt_hdp_unregister_sink_app(const char *app_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Connects the remote device which acts as @a Source role, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address  The remote address
+ * @param[in] app_id  The ID of application
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Sink role of HDP must be registered with bt_hdp_register_sink_app().
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @post bt_hdp_connected_cb() will be invoked.
+ * @see bt_hdp_disconnect()
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+int bt_hdp_connect_to_source(const char *remote_address, const char *app_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Disconnects the remote device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address  The remote address
+ * @param[in] channel  The connected data channel
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @post bt_hdp_disconnected_cb() will be invoked.
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+int bt_hdp_disconnect(const char *remote_address, unsigned int channel);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Sends the data to the remote device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] channel  The connected data channel
+ * @param[in] data  The data to send
+ * @param[in] size  The size of data to send (byte)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_hdp_data_received_cb()
+ * @see bt_hdp_set_data_received_cb()
+ * @see bt_hdp_unset_data_received_cb()
+ */
+int bt_hdp_send_data(unsigned int channel, const char *data, unsigned int size);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Registers a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @param[in] connected_cb The callback function called when a connection is established
+ * @param[in] disconnected_cb The callback function called when a connection is disconnected
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+int bt_hdp_set_connection_state_changed_cb(bt_hdp_connected_cb connected_cb, bt_hdp_disconnected_cb disconnected_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_set_connection_state_changed_cb()
+ */
+int bt_hdp_unset_connection_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Registers a callback function that will be invoked when you receive the data.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_unset_data_received_cb()
+ */
+int bt_hdp_set_data_received_cb(bt_hdp_data_received_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Unregisters a callback function that will be invoked when you receive the data.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_set_data_received_cb()
+ */
+int bt_hdp_unset_data_received_cb(void);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Gets the primary services of GATT(Generic Attribute Profile).
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  remote_address  The address of the remote device
+ * @param[in]  callback  The callback function to invoke
+ * @param[in]  user_data  The user data to be passed to the callback function
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post  @a callback will be called if there are primary services.
+ * @see  bt_gatt_primary_service_cb()
+ */
+int bt_gatt_foreach_primary_services(const char *remote_address, bt_gatt_primary_service_cb callback, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Discovers the characteristics in service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  service  The attribute handle of service
+ * @param[in]  callback  The result callback
+ * @param[in]  user_data  The user data to be passed to the callback function
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post  @a callback will be called.
+ * @see  bt_gatt_characteristics_discovered_cb()
+ */
+int bt_gatt_discover_characteristics(bt_gatt_attribute_h service, bt_gatt_characteristics_discovered_cb callback, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Gets the UUID of service.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks  @a uuid must be released with free() by you.
+ * @param[in]  service  The attribute handle of service
+ * @param[out]  uuid  The UUID of service
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval  #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_gatt_get_service_uuid(bt_gatt_attribute_h service, char **uuid);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Gets the included services in service.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  service  The attribute handle of service
+ * @param[in]  callback  The callback function to invoke
+ * @param[in]  user_data  The user data to be passed to the callback function
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post  @a callback will be called if there are included services.
+ * @see  bt_gatt_included_service_cb()
+ */
+int bt_gatt_foreach_included_services(bt_gatt_attribute_h service, bt_gatt_included_service_cb callback, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Registers a callback function that will be invoked when a characteristic value is changed.
+ * @since_tizen 2.3
+ * @param[in]  callback  The callback function to register
+ * @param[in]  user_data  The user data to be passed to the callback function
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre  The Bluetooth service must be initialized with bt_initialize().
+ * @see  bt_gatt_unset_characteristic_changed_cb()
+ */
+int bt_gatt_set_characteristic_changed_cb(bt_gatt_characteristic_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Unregisters a callback function that will be invoked when a characteristic is changed.
+ * @since_tizen 2.3
+ * @return  0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_gatt_set_characteristic_changed_cb()
+ */
+int bt_gatt_unset_characteristic_changed_cb(void);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Watches all the characteristic value changes of the service
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  service  The attribute handle of service
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The Bluetooth service must be initialized with bt_initialize().
+ * @see  bt_gatt_unset_characteristic_changed_cb()
+ */
+int bt_gatt_watch_characteristic_changes(bt_gatt_attribute_h service);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Remove watching of all the characteristic value changes of the service
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  service  The attribute handle of service
+ * @return  0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_gatt_set_characteristic_changed_cb()
+ */
+int bt_gatt_unwatch_characteristic_changes(bt_gatt_attribute_h service);
+
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Gets the characteristic declaration.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks  @a uuid and @a value must be released with free() by you.
+ * @param[in]  characteristic  The attribute handle of characteristic
+ * @param[out]  uuid  The UUID of service
+ * @param[out]  value  The value of characteristic (byte array)
+ * @param[out]  value_length  The length of value
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval  #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_gatt_set_characteristic_value()
+ */
+int bt_gatt_get_characteristic_declaration(bt_gatt_attribute_h characteristic, char **uuid, unsigned char **value, int *value_length);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Sets the value of characteristic.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  characteristic  The attribute handle of characteristic
+ * @param[in]  value  The value of characteristic (byte array)
+ * @param[in]  value_length  The length of value
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_set_characteristic_value(bt_gatt_attribute_h characteristic, const unsigned char *value, int value_length);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Sets the value of characteristic request.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  characteristic  The attribute handle of characteristic
+ * @param[in]  value  The value of characteristic (byte array)
+ * @param[in]  value_length  The length of value
+  * @param[in]  callback  The result callback
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_set_characteristic_value_request(bt_gatt_attribute_h characteristic, const unsigned char *value,
+                               int value_length, bt_gatt_characteristic_write_cb callback);
+
+/**
+* @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+* @brief  Clones the attribute handle.
+* @since_tizen 2.3
+* @remarks  @a clone must be released with bt_gatt_destroy_attribute_handle().
+* @param[out]  clone  The cloned attribute handle
+* @param[in]  origin  The origin attribute handle
+* @return  0 on success, otherwise negative error value.
+* @retval  #BT_ERROR_NONE  Successful
+* @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+* @retval  #BT_ERROR_OUT_OF_MEMORY  Out of memory
+* @see  bt_gatt_destroy_attribute_handle()
+*/
+int bt_gatt_clone_attribute_handle(bt_gatt_attribute_h* clone, bt_gatt_attribute_h origin);
+
+/**
+* @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+* @brief  Destroys the attribute handle.
+* @since_tizen 2.3
+* @param[in]  handle  The attribute handle
+* @return  0 on success, otherwise negative error value.
+* @retval  #BT_ERROR_NONE  Successful
+* @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+* @see  bt_gatt_clone_attribute_handle()
+*/
+int bt_gatt_destroy_attribute_handle(bt_gatt_attribute_h handle);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Reads the value of characteristic from remote device
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  char_handle  The attribute handle of characteristic
+ * @param[in]  callback  The result callback
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE      Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_read_characteristic_value(bt_gatt_attribute_h char_handle,
+               bt_gatt_characteristic_read_cb callback);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Discovers the characteristic descriptors of a characteristic within its definition, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  characteristic_handle  The attribute handle of characteristic
+ * @param[in]  callback  The result callback
+ * @param[in]  user_data  The user data to be passed to the callback function
+ * @return  0 on success, otherwise a negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval  #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval  #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval  #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post  @a callback will be called.
+ * @see  bt_gatt_characteristic_descriptor_discovered_cb()
+ */
+int bt_gatt_discover_characteristic_descriptor(bt_gatt_attribute_h characteristic_handle,
+               bt_gatt_characteristic_descriptor_discovered_cb callback,
+               void *user_data);
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Sets the value of characteristic descriptor request.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in]  characteristic  The attribute handle of characteristic
+ * @param[in]  value  The value of characteristic (byte array), desc handle, desc value
+ * @param[in]  value_length  The length of value
+  * @param[in] callback  The result callback
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_set_characteristic_desc_value_request(bt_gatt_attribute_h characteristic,
+                               const unsigned char *value, int value_length,
+                               bt_gatt_characteristic_write_cb callback);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Connect to a specific LE based service on a remote bluetooth dievice address, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A connection can be disconnected by bt_gatt_disconnect().
+ *
+ * @param[in] address The address of the remote Bluetooth device.
+ * @param[in] auto_connect The flag of the auto connection.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @pre The remote device must support le connection.
+ * @post This function invokes bt_gatt_connection_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_set_connection_state_changed_cb()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ * @see bt_gatt_connection_state_changed_cb()
+ */
+int bt_gatt_connect(const char *address, bool auto_connect);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Disconnect to LE connection with the given remote Bluetooth dievice address, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] address The address of the remote Bluetooth device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre The connection must be established.
+ * @post This function invokes bt_gatt_connection_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_gatt_connect()
+ * @see bt_gatt_set_connection_state_changed_cb()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ * @see bt_gatt_connection_state_changed_cb()
+ */
+int bt_gatt_disconnect(const char *address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Registers a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register.
+ * @param[in] user_data The user data to be passed  to the callback function.
+ *
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
+ *
+ * @see bt_gatt_connect()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ */
+int bt_gatt_set_connection_state_changed_cb(bt_gatt_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Unregisters a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ *
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @see bt_gatt_connect()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_connection_state_changed_cb()
+ */
+int bt_gatt_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Initializes the Gatt Service.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_adapter_enable()
+ */
+int _bt_gatt_init_service(void);
+
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  DeInitializes the Gatt Service.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_adapter_enable()
+ * @see _bt_gatt_init_service(void)
+ */
+int _bt_gatt_deinit_service(void);
+
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Adds Gatt Service to the service interface.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in]  svc_uuid                Gatt service uuid.
+ * @param[out] svc_path        Object path of the GATT service.
+ * @remarks svc_path must be released with free() by you.
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_adapter_enable()
+ */
+int bt_gatt_add_service(const char *svc_uuid,
+                               char **svc_path);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Deletes a Gatt Service from the Gatt Server Database.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in]  svc_path  Service path of the gatt service to remove.
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_adapter_enable()
+ */
+int bt_gatt_remove_service(const char *svc_path);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Adds Gatt characteristic to the Characteristics interface.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in]  char_uuid Gatt characteristic uuid.
+ * @param[in]  char_value      Gatt characteristic value.
+ * @param[in]  value_length Caracteristic value length.
+ * @param[in]  char_flags    Characteristic flags.
+ * @param[in]  flags_length Caracteristic flags length.
+ * @param[in]  svc_path        service path to which this characteristic belongs to.
+ * @param[out]  char_path      characteristic path registered on the interface.
+ * @remarks char_path must be released with free() by you.
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_adapter_enable()
+ */
+int bt_gatt_add_characteristic(const char *char_uuid,
+                       const char *char_value, int value_length,
+                       const char *char_flags[], int flags_length,
+                       const char *svc_path, char **char_path);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Adds Gatt descriptor to the descriptor interface.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in]  desc_uuid Gatt descriptor uuid.
+ * @param[in]  desc_value      Gatt descriptor value.
+ * @param[in]  desc_length     Gatt descriptor value.
+ * @param[in]  permissions     Permissions for the descriptor.
+ * @param[in]  char_path       Characteristic path to which this descriptor should belong to.
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_adapter_enable()
+ */
+int bt_gatt_add_descriptor(const char *desc_uuid,
+                       const char *desc_value, int value_length,
+                       const char *permissions, const char *char_path,
+                       char **desc_path);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Registers the given service path (including characteristics and descriptor) with the Bluez.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in]  svc_path Gatt service path obtained from the add_service.
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre  bt_gatt_add_service, bt_gatt_add_characteristic and bt_gatt_add_descriptor
+ *          must be called before calling bt_gatt_register_service
+ *
+ * @see  bt_adapter_enable()
+ * @see  bt_gatt_add_service()
+ * @see  bt_gatt_add_characteristic()
+ * @see  bt_gatt_add_descriptor()
+ */
+int bt_gatt_register_service(const char *svc_path,
+               bt_gatt_remote_characteristic_write_cb callback,
+               void *user_data);
+
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Updates the existing characteristic value.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in]  char_path       characteristic path registered on the interface.
+ * @param[in]  char_value      Gatt characteristic value.
+ * @param[in]  value_length    Characteristic value length.
+ * @param[in]  address Remote device address, for which
+ *                       Notification/Indication need to be sent.
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see  bt_adapter_enable()
+ */
+int bt_gatt_update_characteristic(const char *char_path,
+                       const char *char_value, int value_length,
+                       const char *address);
+/**
+ * @internal
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Delete Gatt Services from the Gatt Server Database.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval     #BT_ERROR_NONE  Successful
+ * @retval     #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval     #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval     #BT_ERROR_OPERATION_FAILED      Operation failed
+ * @retval     #BT_ERROR_PERMISSION_DENIED  Permission denied
+ *
+ * @pre  The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post  @a callback will be called.
+ * @see  bt_adapter_enable()
+ */
+int bt_gatt_delete_services(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Activates the NAP(Network Access Point).
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_ALREADY_DONE  Operation is already done
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
+ * @see bt_nap_deactivate()
+ */
+int bt_nap_activate(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Deactivates the NAP(Network Access Point).
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_ALREADY_DONE  Operation is already done
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
+ * @see bt_nap_activate()
+ */
+int bt_nap_deactivate(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Disconnects the all PANUs(Personal Area Networking User) which are connected to you.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
+ * @see bt_nap_activate()
+ */
+int bt_nap_disconnect_all(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Disconnects the specified PANU(Personal Area Networking User) which is connected to you.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] remote_address  The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
+ * @see bt_nap_activate()
+ */
+int bt_nap_disconnect(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief  Registers a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_nap_connection_state_changed_cb()
+ * @see bt_nap_unset_connection_state_changed_cb()
+ */
+int bt_nap_set_connection_state_changed_cb(bt_nap_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_nap_connection_state_changed_cb()
+ * @see bt_nap_set_connection_state_changed_cb()
+ */
+int bt_nap_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief  Registers a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_panu_connection_state_changed_cb()
+ * @see bt_panu_unset_connection_state_changed_cb()
+ */
+int bt_panu_set_connection_state_changed_cb(bt_panu_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief  Unregisters a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_panu_connection_state_changed_cb()
+ * @see bt_panu_set_connection_state_changed_cb()
+ */
+int bt_panu_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Connects the remote device with the PAN(Personal Area Networking) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] remote_address  The remote address
+ * @param[in] type  The type of PAN service
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @post bt_panu_connection_state_changed_cb() will be invoked.
+ * @see bt_panu_disconnect()
+ * @see bt_panu_connection_state_changed_cb()
+ */
+int bt_panu_connect(const char *remote_address, bt_panu_service_type_e type);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Disconnects the remote device with the PAN(Personal Area Networking) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] remote_address  The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_OUT_OF_MEMORY  Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The remote device must be connected by bt_panu_connect().
+ * @post bt_panu_connection_state_changed_cb() will be invoked.
+ * @see bt_panu_connect()
+ * @see bt_panu_connection_state_changed_cb()
+ */
+int bt_panu_disconnect(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief   update LE connection.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_PERMISSION_DENIED  Permission denied
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @pre The remote device must be connected with bt_gatt_connect().
+ */
+int bt_device_le_conn_update(const char *device_address,
+                            const bt_le_conn_update_s *parameters);
+
+
+/**
+ * @}
+ */
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_H__
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_private.h b/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_private.h
new file mode 100644 (file)
index 0000000..dbb8e44
--- /dev/null
@@ -0,0 +1,284 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__
+#define __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__
+
+#include <dlog.h>
+#include <stdbool.h>
+#include <bluetooth-api.h>
+#include <bluetooth-audio-api.h>
+#include <bluetooth-telephony-api.h>
+#include <bluetooth-media-control.h>
+#include <bluetooth-hid-api.h>
+
+#include "bluetooth.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#undef LOG_TAG
+#define LOG_TAG "CAPI_NETWORK_BLUETOOTH"
+
+#define BT_INFO(fmt, args...) SLOGI(fmt, ##args)
+#define BT_DBG(fmt, args...) SLOGD(fmt, ##args)
+#define BT_ERR(fmt, args...) SLOGE(fmt, ##args)
+
+#define OPP_UUID "00001105-0000-1000-8000-00805f9b34fb"
+
+/**
+ * @internal
+ * @brief Bluetooth callback.
+ */
+typedef enum
+{
+       BT_EVENT_STATE_CHANGED = 0x00, /**< Adapter state is changed */
+       BT_EVENT_LE_STATE_CHANGED, /**< Adapter le state is changed */
+       BT_EVENT_NAME_CHANGED, /**< Adapter name is changed */
+       BT_EVENT_VISIBILITY_MODE_CHANGED, /**< Adapter visibility mode is changed */
+       BT_EVENT_VISIBILITY_DURATION_CHANGED, /**< Adapter visibility duration is changed */
+       BT_EVENT_DEVICE_DISCOVERY_STATE_CHANGED, /**< Device discovery state is changed */
+       BT_EVENT_LE_DEVICE_DISCOVERY_STATE_CHANGED, /**< LE Device discovery state is changed */
+       BT_EVENT_BOND_CREATED, /**< A bond is created */
+       BT_EVENT_BOND_DESTROYED, /**< A bond is destroyed */
+       BT_EVENT_AUTHORIZATION_CHANGED, /**< Authorization is changed */
+       BT_EVENT_SERVICE_SEARCHED, /**< Service search finish */
+       BT_EVENT_DATA_RECEIVED, /**< Data is received */
+       BT_EVENT_CONNECTION_STATE_CHANGED, /**< Connection state is changed */
+       BT_EVENT_RFCOMM_CONNECTION_REQUESTED, /**< RFCOMM connection is requested */
+       BT_EVENT_OPP_CONNECTION_REQUESTED, /**< OPP connection is requested */
+       BT_EVENT_OPP_PUSH_REQUESTED, /**< OPP push is requested */
+       BT_EVENT_OPP_SERVER_TRANSFER_PROGRESS, /**< OPP transfer progress */
+       BT_EVENT_OPP_SERVER_TRANSFER_FINISHED, /**< OPP transfer is completed */
+       BT_EVENT_OPP_CLIENT_PUSH_RESPONSED, /**< OPP client connection is reponsed */
+       BT_EVENT_OPP_CLIENT_PUSH_PROGRESS, /**< OPP client push progress */
+       BT_EVENT_OPP_CLIENT_PUSH_FINISHED, /**< OPP client push is finished */
+       BT_EVENT_PAN_CONNECTION_STATE_CHANGED, /**< PAN connection change */
+       BT_EVENT_NAP_CONNECTION_STATE_CHANGED, /**< NAP connection change */
+       BT_EVENT_HDP_CONNECTED, /**< HDP connection change */
+       BT_EVENT_HDP_DISCONNECTED, /**< HDP disconnection change */
+       BT_EVENT_HDP_DATA_RECEIVED, /**< HDP Data receive Callabck */
+       BT_EVENT_AUDIO_CONNECTION_STATUS, /**< Audio Connection change callback */
+       BT_EVENT_AG_SCO_CONNECTION_STATUS, /**< Audio - AG SCO Connection state change callback */
+       BT_EVENT_AG_CALL_HANDLING_EVENT, /**< Audio - AG call event callback */
+       BT_EVENT_AG_MULTI_CALL_HANDLING_EVENT, /**< Audio - AG 3-way call event callback */
+       BT_EVENT_AG_DTMF_TRANSMITTED, /**< Audio - DTMF tone sending request */
+       BT_EVENT_AG_MICROPHONE_GAIN_CHANGE, /**< Audio Microphone change callback */
+       BT_EVENT_AG_SPEAKER_GAIN_CHANGE, /**< Audio Speaker gain change callback */
+       BT_EVENT_AG_VENDOR_CMD, /**< Audio - XSAT Vendor cmd */
+       BT_EVENT_AVRCP_CONNECTION_STATUS, /**< AVRCP connection change callback */
+       BT_EVENT_AVRCP_EQUALIZER_STATE_CHANGED, /**< AVRCP equalizer state change callback */
+       BT_EVENT_AVRCP_REPEAT_MODE_CHANGED, /**< AVRCP repeat mode change callback */
+       BT_EVENT_AVRCP_SHUFFLE_MODE_CHANGED, /**< AVRCP equalizer mode change callback */
+       BT_EVENT_AVRCP_SCAN_MODE_CHANGED, /**< AVRCP scan mode change callback */
+       BT_EVENT_HID_CONNECTION_STATUS, /**< HID connection status callback */
+       BT_EVENT_DEVICE_CONNECTION_STATUS, /**< Device connection status callback */
+       BT_EVENT_GATT_CONNECTION_STATUS, /** < GATT connection status callback */
+       BT_EVENT_GATT_PRIM_SVC_DISCOVERED, /**< GATT Primary Service discovered callback */
+       BT_EVENT_GATT_CHARACTERISTIC_DISCOVERED, /**< GATT characteristic discovered callback */
+       BT_EVENT_GATT_CHARACTERISTIC_DESCRIPTOR_DISCOVERED, /**< GATT characteristic descriptor discovered callback */
+       BT_EVENT_GATT_VALUE_CHANGED, /**< GATT characteristic value changed callback */
+       BT_EVENT_GATT_READ_CHARACTERISTIC, /**< GATT characteristic value read callback */
+       BT_EVENT_GATT_WRITE_CHARACTERISTIC, /**< GATT characteristic value write callback */
+       BT_EVENT_GATT_SERVER_ON_WRITE_CHAR, /**< GATT characteristic value write callback */
+       BT_EVENT_ADVERTISING_STATE_CHANGED, /**< Advertising state changed callback */
+       BT_EVENT_MANUFACTURER_DATA_CHANGED, /**< Manufacturer data changed callback */
+       BT_EVENT_CONNECTABLE_CHANGED_EVENT, /**< Adapter connectable changed callback */
+       BT_EVENT_RSSI_ENABLED_EVENT, /**< RSSI Enabled callback */
+       BT_EVENT_RSSI_ALERT_EVENT, /**< RSSI Alert callback */
+       BT_EVENT_GET_RSSI_EVENT, /**< Get RSSI Strength callback */
+#ifdef TIZEN_WEARABLE
+       BT_EVENT_PBAP_CONNECTION_STATUS, /**< PBAP connection status callback */
+       BT_EVENT_PBAP_PHONEBOOK_SIZE, /**< PBAP Phonebook Size status callback */
+       BT_EVENT_PBAP_PHONEBOOK_PULL, /**< PBAP Phonebook Pull status callback */
+       BT_EVENT_PBAP_VCARD_LIST, /**< PBAP vCard List status callback */
+       BT_EVENT_PBAP_VCARD_PULL, /**< PBAP vCard Pull status callback */
+       BT_EVENT_PBAP_PHONEBOOK_SEARCH, /**< PBAP Phonebook Search status callback */
+       BT_EVENT_HF_SCO_CONNECTION_STATUS, /**< Audio - HF SCO Connection state change callback */
+       BT_EVENT_HF_SPEAKER_GAIN_CHANGE, /**< Audio - HF Speaker gain change callback */
+       BT_EVENT_HF_CALL_HANDLING_EVENT, /**< Audio - HF call event callback */
+       BT_EVENT_HF_VENDOR_DEP_CMD_EVENT, /**< Audio - HF Vendor Command callback */
+       BT_EVENT_HF_MULTI_CALL_HANDLING_EVENT, /**< Audio - HF 3-way call event callback */
+#endif
+} bt_event_e;
+
+/**
+ * @internal
+ */
+typedef struct {
+       int handle;
+
+       bt_adapter_le_advertising_state_changed_cb cb;
+       void *cb_data;
+
+       bt_adapter_le_advertising_params_s adv_params;
+
+       unsigned int adv_data_len;
+       char *adv_data;
+
+       unsigned int scan_rsp_data_len;
+       char *scan_rsp_data;
+
+       void *user_data;
+} bt_advertiser_s;
+
+/**
+ * @internal
+ */
+typedef struct bt_event_sig_event_slot_s
+{
+    int event_type;
+    const void *callback;
+    void *user_data;
+} bt_event_sig_event_slot_s;
+
+
+#define BT_CHECK_INPUT_PARAMETER(arg) \
+       if (arg == NULL) \
+       { \
+               LOGE("[%s] INVALID_PARAMETER(0x%08x)", __FUNCTION__, BT_ERROR_INVALID_PARAMETER); \
+               return BT_ERROR_INVALID_PARAMETER; \
+       }
+
+/**
+ * @internal
+ * @brief Check the initialzating status
+ */
+int _bt_check_init_status(void);
+
+#define BT_CHECK_INIT_STATUS() \
+       if (_bt_check_init_status() == BT_ERROR_NOT_INITIALIZED) \
+       { \
+               LOGE("[%s] NOT_INITIALIZED(0x%08x)", __FUNCTION__, BT_ERROR_NOT_INITIALIZED); \
+               return BT_ERROR_NOT_INITIALIZED; \
+       }
+
+/**
+ * @internal
+ * @brief Initialize Bluetooth LE adapter
+ */
+int _bt_le_adapter_init(void);
+
+/**
+ * @internal
+ * @brief Deinitialize Bluetooth LE adapter
+ */
+int _bt_le_adapter_deinit(void);
+
+/**
+ * @internal
+ * @brief Set the event callback.
+ */
+void _bt_set_cb(int events, void *callback, void *user_data);
+
+/**
+ * @internal
+ * @brief Unset the event callback.
+ */
+void _bt_unset_cb(int events);
+
+/**
+ * @internal
+ * @brief Check if the event callback exist or not.
+ */
+bool _bt_check_cb(int events);
+
+/**
+ * @internal
+ * @brief Convert Bluetooth F/W error codes to capi Bluetooth error codes.
+ */
+int _bt_get_error_code(int origin_error);
+
+
+/**
+ * @internal
+ * @brief Convert Bluetooth F/W bluetooth_device_info_t to capi bt_device_info_s.
+ */
+int _bt_get_bt_device_info_s(bt_device_info_s **dest_dev, bluetooth_device_info_t *source_dev);
+
+
+/**
+ * @internal
+ * @brief Free bt_device_info_s.
+ */
+void _bt_free_bt_device_info_s(bt_device_info_s *device_info);
+
+/**
+ * @internal
+ * @brief Convert Bluetooth F/W bluetooth_device_address_t to string.
+ */
+int _bt_convert_address_to_string(char **addr_str, bluetooth_device_address_t *addr_hex);
+
+
+/**
+ * @internal
+ * @brief Convert string to Bluetooth F/W bluetooth_device_address_t.
+ */
+void _bt_convert_address_to_hex(bluetooth_device_address_t *addr_hex, const char *addr_str);
+
+
+/**
+ * @internal
+ * @brief Convert error code to string.
+ */
+char* _bt_convert_error_to_string(int error);
+
+/**
+ * @internal
+ * @brief Convert the visibility mode
+ */
+bt_adapter_visibility_mode_e _bt_get_bt_visibility_mode_e(bluetooth_discoverable_mode_t mode);
+
+/**
+ * @internal
+ * @brief Since the Audio call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_audio_event_proxy(int event, bt_audio_event_param_t *param, void *user_data);
+
+#ifdef TIZEN_WEARABLE
+/**
+ * @internal
+ * @brief Since the HF call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_hf_event_proxy(int event, bt_hf_event_param_t *param, void *user_data);
+#endif
+
+/**
+ * @internal
+ * @brief Since the Telephony call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_telephony_event_proxy(int event, telephony_event_param_t *param, void *user_data);
+
+/**
+ * @internal
+ * @brief Since the AVRCP call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_avrcp_event_proxy(int event, media_event_param_t *param, void *user_data);
+
+/**
+ * @internal
+ * @brief Since the HID call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_hid_event_proxy(int event, hid_event_param_t *param, void *user_data);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__ */
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_type.h b/resource/csdk/connectivity/lib/tizen/ble/inc/bluetooth_type.h
new file mode 100644 (file)
index 0000000..95d195d
--- /dev/null
@@ -0,0 +1,1495 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
+#define __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
+
+ #ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @file bluetooth_type.h
+ * @brief API to control the Bluetooth adapter, devices and communications.
+ * @ingroup     CAPI_NETWORK_BLUETOOTH_TYPE_MODULE
+ */
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @brief Enumerations of Bluetooth error codes.
+ */
+typedef enum
+{
+       BT_ERROR_NONE = TIZEN_ERROR_NONE, /**< Successful*/
+       BT_ERROR_CANCELLED = TIZEN_ERROR_CANCELED, /**< Operation cancelled */
+       BT_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER, /**< Invalid parameter */
+       BT_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY, /**< Out of memory */
+       BT_ERROR_RESOURCE_BUSY = TIZEN_ERROR_RESOURCE_BUSY, /**< Device or resource busy */
+       BT_ERROR_TIMED_OUT = TIZEN_ERROR_TIMED_OUT, /**< Timeout error */
+       BT_ERROR_NOW_IN_PROGRESS = TIZEN_ERROR_NOW_IN_PROGRESS, /**< Operation now in progress */
+       BT_ERROR_NOT_SUPPORTED = TIZEN_ERROR_NOT_SUPPORTED,
+       BT_ERROR_PERMISSION_DENIED = TIZEN_ERROR_PERMISSION_DENIED, /**< Permission denied */
+       BT_ERROR_QUOTA_EXCEEDED = TIZEN_ERROR_QUOTA_EXCEEDED, /**< Quota exceeded */
+       BT_ERROR_NOT_INITIALIZED = TIZEN_ERROR_BLUETOOTH|0x0101, /**< Local adapter not initialized */
+       BT_ERROR_NOT_ENABLED = TIZEN_ERROR_BLUETOOTH|0x0102, /**< Local adapter not enabled */
+       BT_ERROR_ALREADY_DONE = TIZEN_ERROR_BLUETOOTH|0x0103, /**< Operation already done  */
+       BT_ERROR_OPERATION_FAILED = TIZEN_ERROR_BLUETOOTH|0x0104, /**< Operation failed */
+       BT_ERROR_NOT_IN_PROGRESS = TIZEN_ERROR_BLUETOOTH|0x0105, /**< Operation not in progress */
+       BT_ERROR_REMOTE_DEVICE_NOT_BONDED = TIZEN_ERROR_BLUETOOTH|0x0106, /**< Remote device not bonded */
+       BT_ERROR_AUTH_REJECTED = TIZEN_ERROR_BLUETOOTH|0x0107, /**< Authentication rejected */
+       BT_ERROR_AUTH_FAILED = TIZEN_ERROR_BLUETOOTH|0x0108, /**< Authentication failed */
+       BT_ERROR_REMOTE_DEVICE_NOT_FOUND = TIZEN_ERROR_BLUETOOTH|0x0109, /**< Remote device not found */
+       BT_ERROR_SERVICE_SEARCH_FAILED = TIZEN_ERROR_BLUETOOTH|0x010A, /**< Service search failed */
+       BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED = TIZEN_ERROR_BLUETOOTH|0x010B, /**< Remote device is not connected */
+       BT_ERROR_AGAIN = TIZEN_ERROR_BLUETOOTH|0x010C, /**< Resource temporarily unavailable */
+       BT_ERROR_SERVICE_NOT_FOUND = TIZEN_ERROR_BLUETOOTH|0x010D, /**< Service Not Found */
+} bt_error_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Enumerations of the Bluetooth adapter state.
+ */
+typedef enum
+{
+       BT_ADAPTER_DISABLED = 0x00, /**< Bluetooth adapter is disabled */
+       BT_ADAPTER_ENABLED, /**< Bluetooth adapter is enabled */
+} bt_adapter_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Enumerations of the Bluetooth adapter le state.
+ */
+typedef enum
+{
+       BT_ADAPTER_LE_DISABLED = 0x00, /**< Bluetooth le is disabled */
+       BT_ADAPTER_LE_ENABLED, /**< Bluetooth le is enabled */
+} bt_adapter_le_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Enumerations of the Bluetooth visibility mode.
+ */
+typedef enum
+{
+       BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE = 0x00,  /**< Other devices cannot find your device via discovery */
+       BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE,  /**< Discoverable mode */
+       BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE,  /**< Discoverable mode with time limit. After specific period,
+                                                           it is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.*/
+} bt_adapter_visibility_mode_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Enumerations of the discovery state of Bluetooth device.
+ *
+ */
+typedef enum
+{
+       BT_ADAPTER_DEVICE_DISCOVERY_STARTED, /**< Device discovery is started */
+       BT_ADAPTER_DEVICE_DISCOVERY_FINISHED, /**< Device discovery is finished */
+       BT_ADAPTER_DEVICE_DISCOVERY_FOUND, /**< The remote Bluetooth device is found */
+} bt_adapter_device_discovery_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the discovery state of Bluetooth LE device.
+ *
+ */
+typedef enum
+{
+       BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED, /**< LE device discovery is started */
+       BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED, /**< LE device discovery is finished */
+       BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND, /**< The remote Bluetooth LE device is found */
+} bt_adapter_le_device_discovery_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Enumerations of the Bluetooth advertising state.
+ */
+typedef enum {
+       BT_ADAPTER_LE_ADVERTISING_STOPPED = 0x00, /**< Bluetooth advertising is stopped */
+       BT_ADAPTER_LE_ADVERTISING_STARTED, /**< Bluetooth advertising is started */
+} bt_adapter_le_advertising_state_e;
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Enumerations of the Bluetooth advertising filter policy.
+ */
+typedef enum {
+       BT_ADAPTER_LE_ADVERTISING_FILTER_DEFAULT = 0x00, /**< White list is not in use */
+       BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_SCAN_WL = 0x01, /**< Allow the scan
+                                       request that in the White list */
+       BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_CONN_WL = 0x02, /**< Allow the connectoin
+                                       request that in the White list */
+       BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_SCAN_CONN_WL = 0x03, /**< Allow the
+                                       scan and connectoin request that in the White list */
+} bt_adapter_le_advertising_filter_policy_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Enumerations of the Bluetooth advertising type.
+ */
+typedef enum {
+       BT_ADAPTER_LE_ADVERTISING_CONNECTABLE = 0x00, /**< Connectable undirected advertising (ADV_IND) */
+       BT_ADAPTER_LE_ADVERTISING_CONNECTABLE_DIRECT_HIGH = 0x01, /**< Connectable high duty cycle directed advertising (ADV_DIRECT_IND) */
+       BT_ADAPTER_LE_ADVERTISING_SCANNABLE = 0x02, /**< Scannable undirected advertising (ADV_SCAN_IND) */
+       BT_ADAPTER_LE_ADVERTISING_NON_CONNECTABLE = 0x03, /**< Non connectable undirected advertising (ADV_NONCOND_IND) */
+       BT_ADAPTER_LE_ADVERTISING_CONNECTABLE_DIRECT_LOW = 0x04, /**< Connectable low duty cycle directed advertising (ADV_DIRECT_IND) */
+} bt_adapter_le_advertising_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Enumerations of the Bluetooth LE packet type.
+ */
+typedef enum {
+       BT_ADAPTER_LE_PACKET_ADVERTISING, /**< Advertising packet */
+       BT_ADAPTER_LE_PACKET_SCAN_RESPONSE, /**< Sacn response packet */
+} bt_adapter_le_packet_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Enumerations of the Bluetooth LE data type
+ *         that can be included in LE packets.
+ */
+typedef enum {
+       BT_ADAPTER_LE_PACKET_DATA_COMP_LIST_16_BIT_SERVICE_CLASS_UUIDS = 0x03, /**< 16 bit UUID */
+       BT_ADAPTER_LE_PACKET_DATA_MANUFACTURER_SPECIFIC_DATA = 0xff, /**< Manufacturer data */
+} bt_adapter_le_packet_data_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of device disconnect reason.
+ */
+typedef enum
+{
+       BT_DEVICE_DISCONNECT_REASON_UNKNOWN, /**< Disconnected by unknown reason */
+       BT_DEVICE_DISCONNECT_REASON_TIMEOUT, /**< Disconnected by timeout */
+       BT_DEVICE_DISCONNECT_REASON_LOCAL_HOST, /**< Disconnected by local host */
+       BT_DEVICE_DISCONNECT_REASON_REMOTE, /**< Disconnected by remote */
+} bt_device_disconnect_reason_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of connection link type.
+ */
+typedef enum
+{
+       BT_DEVICE_CONNECTION_LINK_BREDR, /**< BR/EDR link */
+       BT_DEVICE_CONNECTION_LINK_LE, /**< LE link */
+       BT_DEVICE_CONNECTION_LINK_DEFAULT = 0xFF, /**< The connection type defualt */
+} bt_device_connection_link_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of device authorization state.
+ */
+typedef enum
+{
+       BT_DEVICE_AUTHORIZED, /**< The remote Bluetooth device is authorized */
+       BT_DEVICE_UNAUTHORIZED, /**< The remote Bluetooth device is unauthorized */
+} bt_device_authorization_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of Bluetooth profile.
+ */
+typedef enum
+{
+    BT_PROFILE_RFCOMM = 0x01, /**< RFCOMM Profile */
+    BT_PROFILE_A2DP = 0x02, /**< Advanced Audio Distribution Profile */
+    BT_PROFILE_HSP = 0x04, /**< Headset Profile */
+    BT_PROFILE_HID = 0x08, /**< Human Interface Device Profile */
+    BT_PROFILE_NAP = 0x10, /**< Network Access Point Profile */
+    BT_PROFILE_AG = 0x20, /**< Audio Gateway Profile */
+    BT_PROFILE_GATT = 0x40, /**< Generic Attribute Profile */
+    BT_PROFILE_NAP_SERVER = 0x80, /**< NAP server Profile */
+} bt_profile_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of device address type.
+ */
+typedef enum
+{
+       BT_DEVICE_PUBLIC_ADDRESS = 0x00, /**< Public address */
+       BT_DEVICE_RANDOM_ADDRESS, /**< Random address */
+} bt_device_address_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Enumerations of service class.
+ */
+typedef enum {
+       BT_SC_NONE = 0, /**< No service class */
+       BT_SC_RES_SERVICE_MASK = 0x00000001, /**< RES service class */
+       BT_SC_SPP_SERVICE_MASK = 0x00000002, /**< SPP service class */
+       BT_SC_DUN_SERVICE_MASK = 0x00000004, /**< DUN service class */
+       BT_SC_FAX_SERVICE_MASK = 0x00000008, /**< FAX service class */
+       BT_SC_LAP_SERVICE_MASK = 0x00000010, /**< LAP service class */
+       BT_SC_HSP_SERVICE_MASK = 0x00000020, /**< HSP service class */
+       BT_SC_HFP_SERVICE_MASK = 0x00000040, /**< HFP service class */
+       BT_SC_OPP_SERVICE_MASK = 0x00000080, /**< OPP service class */
+       BT_SC_FTP_SERVICE_MASK = 0x00000100, /**< FTP service class */
+       BT_SC_CTP_SERVICE_MASK = 0x00000200, /**< CTP service class */
+       BT_SC_ICP_SERVICE_MASK = 0x00000400, /**< ICP service class */
+       BT_SC_SYNC_SERVICE_MASK = 0x00000800, /**< SYNC service class */
+       BT_SC_BPP_SERVICE_MASK = 0x00001000, /**< BPP service class */
+       BT_SC_BIP_SERVICE_MASK = 0x00002000, /**< BIP service class */
+       BT_SC_PANU_SERVICE_MASK = 0x00004000, /**< PANU service class */
+       BT_SC_NAP_SERVICE_MASK = 0x00008000, /**< NAP service class */
+       BT_SC_GN_SERVICE_MASK = 0x00010000, /**< GN service class */
+       BT_SC_SAP_SERVICE_MASK = 0x00020000, /**< SAP service class */
+       BT_SC_A2DP_SERVICE_MASK = 0x00040000, /**< A2DP service class */
+       BT_SC_AVRCP_SERVICE_MASK = 0x00080000, /**< AVRCP service class */
+       BT_SC_PBAP_SERVICE_MASK = 0x00100000, /**< PBAP service class */
+       BT_SC_HID_SERVICE_MASK = 0x00200000, /**< HID service class */
+       BT_SC_ALL_SERVICE_MASK = 0x00FFFFFF, /**< ALL service class */
+       BT_SC_MAX /**< MAX service class */
+} bt_service_class_t;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Enumerations of major service class.
+ */
+typedef enum
+{
+       BT_MAJOR_SERVICE_CLASS_LIMITED_DISCOVERABLE_MODE  = 0x002000, /**< Limited discoverable mode */
+       BT_MAJOR_SERVICE_CLASS_POSITIONING                = 0x010000, /**< Positioning class */
+       BT_MAJOR_SERVICE_CLASS_NETWORKING                 = 0x020000, /**< Networking class */
+       BT_MAJOR_SERVICE_CLASS_RENDERING                  = 0x040000, /**< Rendering class */
+       BT_MAJOR_SERVICE_CLASS_CAPTURING                  = 0x080000, /**< Capturing class */
+       BT_MAJOR_SERVICE_CLASS_OBJECT_TRANSFER            = 0x100000, /**< Object transferring class */
+       BT_MAJOR_SERVICE_CLASS_AUDIO                      = 0x200000, /**< Audio class*/
+       BT_MAJOR_SERVICE_CLASS_TELEPHONY                  = 0x400000, /**< Telephony class */
+       BT_MAJOR_SERVICE_CLASS_INFORMATION                = 0x800000, /**< Information class */
+} bt_major_service_class_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Enumerations of major device class.
+ */
+typedef enum
+{
+       BT_MAJOR_DEVICE_CLASS_MISC = 0x00, /**< Miscellaneous major device class*/
+       BT_MAJOR_DEVICE_CLASS_COMPUTER = 0x01, /**< Computer major device class */
+       BT_MAJOR_DEVICE_CLASS_PHONE = 0x02, /**< Phone major device class */
+       BT_MAJOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT = 0x03, /**< LAN/Network access point major device class */
+       BT_MAJOR_DEVICE_CLASS_AUDIO_VIDEO = 0x04, /**< Audio/Video major device class */
+       BT_MAJOR_DEVICE_CLASS_PERIPHERAL = 0x05, /**< Peripheral major device class */
+       BT_MAJOR_DEVICE_CLASS_IMAGING = 0x06, /**< Imaging major device class */
+       BT_MAJOR_DEVICE_CLASS_WEARABLE = 0x07, /**< Wearable device class */
+       BT_MAJOR_DEVICE_CLASS_TOY = 0x08, /**< Toy device class */
+       BT_MAJOR_DEVICE_CLASS_HEALTH = 0x09, /**< Health device class */
+       BT_MAJOR_DEVICE_CLASS_UNCATEGORIZED = 0x1F, /**< Uncategorized major device class */
+} bt_major_device_class_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Enumerations of minor device class.
+ */
+typedef enum
+{
+       BT_MINOR_DEVICE_CLASS_COMPUTER_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of computer */
+       BT_MINOR_DEVICE_CLASS_COMPUTER_DESKTOP_WORKSTATION = 0x04, /**< Desktop workstation minor device class of computer */
+       BT_MINOR_DEVICE_CLASS_COMPUTER_SERVER_CLASS = 0x08, /**< Server minor device class of computer */
+       BT_MINOR_DEVICE_CLASS_COMPUTER_LAPTOP = 0x0C, /**< Laptop minor device class of computer */
+       BT_MINOR_DEVICE_CLASS_COMPUTER_HANDHELD_PC_OR_PDA = 0x10, /**< Handheld PC/PDA minor device class of computer */
+       BT_MINOR_DEVICE_CLASS_COMPUTER_PALM_SIZED_PC_OR_PDA = 0x14, /**< Palm sized PC/PDA minor device class of computer */
+       BT_MINOR_DEVICE_CLASS_COMPUTER_WEARABLE_COMPUTER = 0x18, /**< Wearable(watch sized) minor device class of computer */
+
+       BT_MINOR_DEVICE_CLASS_PHONE_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of phone */
+       BT_MINOR_DEVICE_CLASS_PHONE_CELLULAR = 0x04, /**< Cellular minor device class of phone */
+       BT_MINOR_DEVICE_CLASS_PHONE_CORDLESS = 0x08, /**< Cordless minor device class of phone */
+       BT_MINOR_DEVICE_CLASS_PHONE_SMART_PHONE = 0x0C, /**< Smart phone minor device class of phone */
+       BT_MINOR_DEVICE_CLASS_PHONE_WIRED_MODEM_OR_VOICE_GATEWAY = 0x10, /**< Wired modem or voice gateway minor device class of phone */
+       BT_MINOR_DEVICE_CLASS_PHONE_COMMON_ISDN_ACCESS = 0x14, /**< Common ISDN minor device class of phone */
+
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_FULLY_AVAILABLE = 0x04, /**< Fully available minor device class of LAN/Network access point */
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_1_TO_17_PERCENT_UTILIZED = 0x20, /**< 1-17% utilized minor device class of LAN/Network access point */
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_17_TO_33_PERCENT_UTILIZED = 0x40, /**< 17-33% utilized minor device class of LAN/Network access point */
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_33_TO_50_PERCENT_UTILIZED = 0x60, /**< 33-50% utilized minor device class of LAN/Network access point */
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_50_to_67_PERCENT_UTILIZED = 0x80, /**< 50-67% utilized minor device class of LAN/Network access point */
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_67_TO_83_PERCENT_UTILIZED = 0xA0, /**< 67-83% utilized minor device class of LAN/Network access point */
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_83_TO_99_PERCENT_UTILIZED = 0xC0, /**< 83-99% utilized minor device class of LAN/Network access point */
+       BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_NO_SERVICE_AVAILABLE = 0xE0, /**< No service available minor device class of LAN/Network access point */
+
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_WEARABLE_HEADSET = 0x04, /**< Wearable headset minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HANDS_FREE = 0x08, /**< Hands-free minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_MICROPHONE = 0x10, /**< Microphone minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_LOUDSPEAKER = 0x14, /**< Loudspeaker minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HEADPHONES = 0x18, /**< Headphones minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_PORTABLE_AUDIO = 0x1C, /**< Portable audio minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAR_AUDIO = 0x20, /**< Car audio minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_SET_TOP_BOX = 0x24, /**< Set-top box minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HIFI_AUDIO_DEVICE = 0x28, /**< Hifi audio minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VCR = 0x2C, /**< VCR minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CAMERA = 0x30, /**< Video camera minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAMCORDER = 0x34, /**< Camcorder minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_MONITOR = 0x38, /**< Video monitor minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_DISPLAY_LOUDSPEAKER = 0x3C, /**< Video display and loudspeaker minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CONFERENCING = 0x40, /**< Video conferencing minor device class of audio/video */
+       BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_GAMING_TOY = 0x48, /**< Gaming/toy minor device class of audio/video */
+
+       BT_MINOR_DEVICE_CLASS_PERIPHERA_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_KEY_BOARD = 0x40, /**< Key board minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_POINTING_DEVICE = 0x80, /**< Pointing device minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_COMBO_KEYBOARD_POINTING_DEVICE = 0xC0, /**< Combo keyboard or pointing device minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_JOYSTICK = 0x04, /**< Joystick minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_GAME_PAD = 0x08, /**< Game pad minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_REMOTE_CONTROL = 0x0C, /**< Remote control minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_SENSING_DEVICE = 0x10, /**< Sensing device minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITIZER_TABLET = 0x14, /**< Digitizer minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_CARD_READER = 0x18, /**< Card reader minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITAL_PEN = 0x1C, /**< Digital pen minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_SCANNER = 0x20, /**< Handheld scanner minor device class of peripheral */
+       BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_GESTURAL_INPUT_DEVICE = 0x24, /**< Handheld gestural input device minor device class of peripheral */
+
+       BT_MINOR_DEVICE_CLASS_IMAGING_DISPLAY = 0x10, /**< Display minor device class of imaging */
+       BT_MINOR_DEVICE_CLASS_IMAGING_CAMERA = 0x20, /**< Camera minor device class of imaging */
+       BT_MINOR_DEVICE_CLASS_IMAGING_SCANNER = 0x40, /**< Scanner minor device class of imaging */
+       BT_MINOR_DEVICE_CLASS_IMAGING_PRINTER = 0x80, /**< Printer minor device class of imaging */
+
+       BT_MINOR_DEVICE_CLASS_WEARABLE_WRIST_WATCH = 0x04, /**< Wrist watch minor device class of wearable */
+       BT_MINOR_DEVICE_CLASS_WEARABLE_PAGER = 0x08, /**< Pager minor device class of wearable */
+       BT_MINOR_DEVICE_CLASS_WEARABLE_JACKET = 0x0C, /**< Jacket minor device class of wearable */
+       BT_MINOR_DEVICE_CLASS_WEARABLE_HELMET = 0x10, /**< Helmet minor device class of wearable */
+       BT_MINOR_DEVICE_CLASS_WEARABLE_GLASSES = 0x14, /**< Glasses minor device class of wearable */
+
+       BT_MINOR_DEVICE_CLASS_TOY_ROBOT = 0x04, /**< Robot minor device class of toy */
+       BT_MINOR_DEVICE_CLASS_TOY_VEHICLE = 0x08, /**< Vehicle minor device class of toy */
+       BT_MINOR_DEVICE_CLASS_TOY_DOLL_ACTION = 0x0C, /**< Doll/Action minor device class of toy */
+       BT_MINOR_DEVICE_CLASS_TOY_CONTROLLER = 0x10, /**< Controller minor device class of toy */
+       BT_MINOR_DEVICE_CLASS_TOY_GAME = 0x14, /**< Game minor device class of toy */
+
+       BT_MINOR_DEVICE_CLASS_HEALTH_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_BLOOD_PRESSURE_MONITOR = 0x04, /**< Blood pressure monitor minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_THERMOMETER = 0x08, /**< Thermometer minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_WEIGHING_SCALE = 0x0C, /**< Weighing scale minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_GLUCOSE_METER = 0x10, /**< Glucose minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_PULSE_OXIMETER = 0x14, /**< Pulse oximeter minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_HEART_PULSE_RATE_MONITOR = 0x18, /**< Heart/Pulse rate monitor minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_DATA_DISPLAY = 0x1C, /**< Health data display minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_STEP_COUNTER = 0x20, /**< Step counter minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_BODY_COMPOSITION_ANALYZER = 0x24, /**< Body composition analyzer minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_PEAK_FLOW_MONITOR = 0x28, /**< Peak flow monitor minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_MEDICATION_MONITOR = 0x2C, /**< Medication monitor minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_KNEE_PROSTHESIS = 0x30, /**< Knee prosthesis minor device class of health */
+       BT_MINOR_DEVICE_CLASS_HEALTH_ANKLE_PROSTHESIS = 0x34, /**< Ankle prosthesis minor device class of health */
+} bt_minor_device_class_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Enumerations of gap appearance type.
+ */
+typedef enum
+{
+       BT_APPEARANCE_TYPE_UNKNOWN = 0x00, /**< Unknown appearance type */
+       BT_APPEARANCE_TYPE_GENERIC_PHONE = 0x40, /**< Generic Phone type - Generic category */
+       BT_APPEARANCE_TYPE_GENERIC_COMPUTER = 0x80, /**< Generic Computer type - Generic category */
+       BT_APPEARANCE_TYPE_GENERIC_WATCH = 0xC0, /**< Generic Watch type - Generic category */
+} bt_appearance_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Enumerations of connected Bluetooth device event role.
+ */
+typedef enum
+{
+       BT_SOCKET_UNKNOWN = 0x00, /**< Unknown role*/
+       BT_SOCKET_SERVER , /**< Server role*/
+       BT_SOCKET_CLIENT, /**< Client role*/
+} bt_socket_role_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Enumerations of Bluetooth socket connection state.
+ */
+typedef enum
+{
+       BT_SOCKET_CONNECTED, /**< RFCOMM is connected */
+       BT_SOCKET_DISCONNECTED, /**< RFCOMM is disconnected */
+} bt_socket_connection_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief  Enumerations for the types of profiles related with audio
+ */
+typedef enum {
+    BT_AUDIO_PROFILE_TYPE_ALL = 0,  /**< All supported profiles related with audio */
+    BT_AUDIO_PROFILE_TYPE_HSP_HFP,  /**< HSP(Headset Profile) and HFP(Hands-Free Profile) */
+    BT_AUDIO_PROFILE_TYPE_A2DP,  /**< A2DP(Advanced Audio Distribution Profile) */
+    BT_AUDIO_PROFILE_TYPE_AG,  /**< AG(Audio Gateway) */
+} bt_audio_profile_type_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Enumerations for the call handling event
+ */
+typedef enum {
+    BT_AG_CALL_HANDLING_EVENT_ANSWER = 0x00,  /**< Request to answer an incoming call */
+    BT_AG_CALL_HANDLING_EVENT_RELEASE,  /**< Request to release a call */
+    BT_AG_CALL_HANDLING_EVENT_REJECT,  /**< Request to reject an incoming call */
+} bt_ag_call_handling_event_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Enumerations for the multi call handling event
+ */
+typedef enum {
+    BT_AG_MULTI_CALL_HANDLING_EVENT_RELEASE_HELD_CALLS = 0x00,  /**< Request to release held calls */
+    BT_AG_MULTI_CALL_HANDLING_EVENT_RELEASE_ACTIVE_CALLS,  /**< Request to release active calls */
+    BT_AG_MULTI_CALL_HANDLING_EVENT_ACTIVATE_HELD_CALL,  /**< Request to put active calls into hold state and activate another (held or waiting) call */
+    BT_AG_MULTI_CALL_HANDLING_EVENT_MERGE_CALLS,  /**< Request to add a held call to the conversation */
+    BT_AG_MULTI_CALL_HANDLING_EVENT_EXPLICIT_CALL_TRANSFER,  /**< Request to let a user who has two calls to connect these two calls together and release its connections to both other parties */
+} bt_ag_multi_call_handling_event_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Enumerations for the call state
+ */
+typedef enum {
+    BT_AG_CALL_EVENT_IDLE = 0x00,  /**< Idle */
+    BT_AG_CALL_EVENT_ANSWERED,  /**< Answered */
+    BT_AG_CALL_EVENT_HELD,  /**< Held */
+    BT_AG_CALL_EVENT_RETRIEVED,  /**< Retrieved */
+    BT_AG_CALL_EVENT_DIALING,  /**< Dialing */
+    BT_AG_CALL_EVENT_ALERTING,  /**< Alerting */
+    BT_AG_CALL_EVENT_INCOMING,  /**< Incoming */
+} bt_ag_call_event_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Enumerations for the call state
+ */
+typedef enum {
+    BT_AG_CALL_STATE_IDLE = 0x00,  /**< Idle state */
+    BT_AG_CALL_STATE_ACTIVE,  /**< Active state */
+    BT_AG_CALL_STATE_HELD,  /**< Held state */
+    BT_AG_CALL_STATE_DIALING,  /**< Dialing state */
+    BT_AG_CALL_STATE_ALERTING,  /**< Alerting state */
+    BT_AG_CALL_STATE_INCOMING,  /**< Incoming state */
+    BT_AG_CALL_STATE_WAITING,  /**< Waiting for connected indication event after answering an incoming call*/
+} bt_ag_call_state_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Enumerations for the equalizer state
+ */
+typedef enum {
+    BT_AVRCP_EQUALIZER_STATE_OFF = 0x01,  /**< Equalizer Off */
+    BT_AVRCP_EQUALIZER_STATE_ON,  /**< Equalizer On */
+} bt_avrcp_equalizer_state_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Enumerations for the repeat mode
+ */
+typedef enum {
+    BT_AVRCP_REPEAT_MODE_OFF = 0x01,  /**< Repeat Off */
+    BT_AVRCP_REPEAT_MODE_SINGLE_TRACK,  /**< Single track repeat */
+    BT_AVRCP_REPEAT_MODE_ALL_TRACK,  /**< All track repeat */
+    BT_AVRCP_REPEAT_MODE_GROUP,  /**< Group repeat */
+} bt_avrcp_repeat_mode_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Enumerations for the shuffle mode
+ */
+typedef enum {
+    BT_AVRCP_SHUFFLE_MODE_OFF = 0x01,  /**< Shuffle Off */
+    BT_AVRCP_SHUFFLE_MODE_ALL_TRACK,  /**< All tracks shuffle */
+    BT_AVRCP_SHUFFLE_MODE_GROUP,  /**< Group shuffle */
+} bt_avrcp_shuffle_mode_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Enumerations for the scan mode
+ */
+typedef enum {
+    BT_AVRCP_SCAN_MODE_OFF = 0x01,  /**< Scan Off */
+    BT_AVRCP_SCAN_MODE_ALL_TRACK,  /**< All tracks scan */
+    BT_AVRCP_SCAN_MODE_GROUP,  /**< Group scan */
+} bt_avrcp_scan_mode_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Enumerations for the player state
+ */
+typedef enum {
+    BT_AVRCP_PLAYER_STATE_STOPPED = 0x00,  /**< Stopped */
+    BT_AVRCP_PLAYER_STATE_PLAYING,  /**< Playing */
+    BT_AVRCP_PLAYER_STATE_PAUSED,  /**< Paused */
+    BT_AVRCP_PLAYER_STATE_FORWARD_SEEK,  /**< Seek Forward */
+    BT_AVRCP_PLAYER_STATE_REWIND_SEEK,  /**< Seek Rewind */
+} bt_avrcp_player_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Enumerations for the data channel type
+ */
+typedef enum {
+    BT_HDP_CHANNEL_TYPE_RELIABLE  = 0x01,  /**< Reliable Data Channel */
+    BT_HDP_CHANNEL_TYPE_STREAMING,  /**< Streaming Data Channel */
+} bt_hdp_channel_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief  Enumerations for the types of PAN(Personal Area Networking) service
+ */
+typedef enum {
+    BT_PANU_SERVICE_TYPE_NAP = 0,  /**< Network Access Point */
+} bt_panu_service_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief The handle to control Bluetooth LE advertising
+ */
+typedef void* bt_advertiser_h;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  The attribute handle of GATT(Generic Attribute Profile)
+ */
+typedef void* bt_gatt_attribute_h;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  The handle of calls state
+ */
+typedef void* bt_call_list_h;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Class structure of device and service.
+ *
+ * @see #bt_device_info_s
+ * @see #bt_adapter_device_discovery_info_s
+ * @see bt_device_bond_created_cb()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ */
+typedef struct
+{
+       bt_major_device_class_e major_device_class;     /**< Major device class. */
+       bt_minor_device_class_e minor_device_class;     /**< Minor device class. */
+       int major_service_class_mask;   /**< Major service class mask.
+       This value can be a combination of #bt_major_service_class_e like #BT_MAJOR_SERVICE_CLASS_RENDERING | #BT_MAJOR_SERVICE_CLASS_AUDIO */
+} bt_class_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Structure of device discovery information.
+ *
+ * @see #bt_class_s
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ */
+typedef struct
+{
+       char *remote_address;   /**< The address of remote device */
+       char *remote_name;      /**< The name of remote device */
+       bt_class_s bt_class;    /**< The Bluetooth classes */
+       int rssi;       /**< The strength indicator of received signal  */
+       bool is_bonded; /**< The bonding state */
+       char **service_uuid;  /**< The UUID list of service */
+       int service_count;      /**< The number of services */
+       bt_appearance_type_e appearance;        /**< The Bluetooth appearance */
+       int manufacturer_data_len;      /**< manufacturer specific data length */
+       char *manufacturer_data;                /**< manufacturer specific data */
+} bt_adapter_device_discovery_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Structure of le device discovery information.
+ *
+ * @see #bt_class_s
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ */
+typedef struct
+{
+       char *remote_address;   /**< The address of remote device */
+       int address_type;       /**< The address type of remote device */
+       int rssi;       /**< The strength indicator of received signal  */
+       char **service_uuid;  /**< The UUID list of service */
+       int service_count;      /**< The number of services */
+       int adv_data_len;               /**< advertising indication data length */
+       char *adv_data;                 /**< advertising indication data */
+       int scan_data_len;              /**< scan response data length */
+       char *scan_data;                /**< scan response data */
+} bt_adapter_le_device_discovery_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Structure of advertising parameters
+ *
+ * @see #bt_class_s
+ * @see bt_adapter_le_advertising_state_changed_cb()
+ * @see bt_adapter_le_start_advertising()
+ */
+typedef struct {
+       float interval_min; /**< Minimum advertising interval for non-directed advertising.
+                             A multiple of 0.625ms is only allowed (Time range : 20ms to 10.24sec). */
+       float interval_max; /**< Maximum advertising interval for non-directed advertising.
+                             A multiple of 0.625ms is only allowed (Time range : 20ms to 10.24sec). */
+       char filter_policy; /* Advertising filter policy */
+       char type; /* Advertising type */
+} bt_adapter_le_advertising_params_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Device information structure used for identifying pear device.
+ *
+ * @see #bt_class_s
+ * @see bt_device_bond_created_cb()
+ */
+typedef struct
+{
+       char *remote_address;   /**< The address of remote device */
+       char *remote_name;      /**< The name of remote device */
+       bt_class_s bt_class;    /**< The Bluetooth classes */
+       char **service_uuid;  /**< The UUID list of service */
+       int service_count;      /**< The number of services */
+       bool is_bonded; /**< The bonding state */
+       bool is_connected;      /**< The connection state */
+       bool is_authorized;     /**< The authorization state */
+       int manufacturer_data_len;      /**< manufacturer specific data length */
+       char *manufacturer_data;                /**< manufacturer specific data */
+} bt_device_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Service Discovery Protocol (SDP) data structure.
+ *
+ * @details This protocol is used for discovering available services or pear device,
+ * and finding one to connect with.
+ *
+ * @see bt_device_service_searched_cb()
+ */
+typedef struct
+{
+       char *remote_address;   /**< The address of remote device */
+       char **service_uuid;  /**< The UUID list of service */
+       int service_count;    /**< The number of services. */
+} bt_device_sdp_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Device connection information structure.
+ *
+ * @see bt_device_connection_state_changed_cb()
+ */
+typedef struct
+{
+       char *remote_address;   /**< The address of remote device */
+       bt_device_connection_link_type_e link;  /**< Link type */
+       bt_device_disconnect_reason_e disconn_reason;  /**< Disconnection reason */
+} bt_device_connection_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Device LE connection update structure.
+ *
+ * @see bt_device_le_conn_update()
+ */
+typedef struct
+{
+       unsigned int interval_min;   /**< Minimum value for the connection event interval (msec) */
+       unsigned int interval_max;   /**< Maximum value for the connection event interval (msec) */
+       unsigned int latency;   /**< Slave latency (msec) */
+       unsigned int time_out;   /**< Supervision timeout (msec) */
+} bt_le_conn_update_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ *
+ * @brief Rfcomm connection data used for exchanging data between Bluetooth devices.
+ *
+ * @see bt_socket_connection_state_changed_cb()
+ */
+typedef struct
+{
+       int socket_fd;  /**< The file descriptor of connected socket */
+       int server_fd;  /**< The file descriptor of the server socket or -1 for client connection */
+       bt_socket_role_e local_role;    /**< The local device role in this connection */
+       char *remote_address;   /**< The remote device address */
+       char *service_uuid;     /**< The service UUId */
+} bt_socket_connection_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ *
+ * @brief Structure of RFCOMM received data.
+ *
+ * @remarks User can use standard linux functions for reading/writing
+ * data from/to sockets.
+ *
+ * @see bt_socket_data_received_cb()
+ */
+typedef struct
+{
+       int socket_fd;  /**< The socket fd */
+       int data_size;  /**< The length of the received data */
+       char *data;     /**< The received data */
+} bt_socket_received_data_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called when the Bluetooth adapter state changes.
+ * @param[in]   result  The result of the adapter state changing
+ * @param[in]   adapter_state  The adapter state to be changed
+ * @param[in]   user_data  The user data passed from the callback registration function
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ */
+typedef void (*bt_adapter_state_changed_cb)(int result, bt_adapter_state_e adapter_state, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called when adapter name changes.
+ * @param[in]   device_name    The name of the Bluetooth device to be changed
+ * @param[in]   user_data      The user data passed from the callback registration function
+ * @pre This function will be invoked when the name of Bluetooth adapter changes
+ * if you register this callback using bt_adapter_set_name_changed_cb().
+ * @see bt_adapter_set_name()
+ * @see bt_adapter_set_name_changed_cb()
+ * @see bt_adapter_unset_name_changed_cb()
+ */
+typedef void (*bt_adapter_name_changed_cb)(char *device_name, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called when the visibility mode changes.
+ * @param[in] result The result of the visibility mode changing
+ * @param[in] visibility_mode The visibility mode to be changed
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre This function will be invoked when the visibility of Bluetooth adapter changes
+ * if you register this callback using bt_adapter_set_visibility_mode_changed_cb().
+ *
+ * @see bt_adapter_set_visibility_mode_changed_cb()
+ * @see bt_adapter_unset_visibility_mode_changed_cb()
+ */
+typedef void (*bt_adapter_visibility_mode_changed_cb)
+       (int result, bt_adapter_visibility_mode_e visibility_mode, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called every second until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
+ * @remarks  This callback function is called only if visibility mode is #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE.
+ * @param[in]  duration  The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds)
+ * @param[in]  user_data  The user data passed from the callback registration function
+ * @pre  This function will be invoked if you register this callback using bt_adapter_set_visibility_duration_changed_cb().
+ * @see  bt_adapter_set_visibility_duration_changed_cb()
+ * @see  bt_adapter_unset_visibility_duration_changed_cb()
+ */
+typedef void (*bt_adapter_visibility_duration_changed_cb)(int duration, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called when the state of device discovery changes.
+ *
+ * @remarks If \a discovery_state is #BT_ADAPTER_DEVICE_DISCOVERY_FOUND,
+ * then you can get some information, such as remote device address, remote device name, rssi, and bonding state.
+ *
+ * @param[in] result The result of the device discovery
+ * @param[in] discovery_state The discovery state to be changed
+ * @param[in] discovery_info The information of the discovered device \n
+ *                                     If \a discovery_state is #BT_ADAPTER_DEVICE_DISCOVERY_STARTED or
+ * #BT_ADAPTER_DEVICE_DISCOVERY_FINISHED, then \a discovery_info is NULL.
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre Either bt_adapter_start_device_discovery() or bt_adapter_stop_device_discovery() will invoke this function
+ * if you register this callback using bt_adapter_set_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_adapter_stop_device_discovery()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ *
+ */
+typedef void (*bt_adapter_device_discovery_state_changed_cb)
+       (int result, bt_adapter_device_discovery_state_e discovery_state, bt_adapter_device_discovery_info_s *discovery_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called when you get bonded devices repeatedly.
+ *
+ * @param[in] device_info The bonded device information
+ * @param[in] user_data The user data passed from the foreach function
+ * @return @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre bt_adapter_foreach_bonded_device() will invoke this function.
+ *
+ * @see bt_adapter_foreach_bonded_device()
+ *
+ */
+typedef bool (*bt_adapter_bonded_device_cb)(bt_device_info_s *device_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called when the connectable state changes.
+ * @param[in] result The result of the connectable state changing
+ * @param[in] connectable The connectable to be changed
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre This function will be invoked when the connectable state of local Bluetooth adapter changes
+ * if you register this callback using bt_adapter_set_connectable_changed_cb().
+ *
+ * @see bt_adapter_set_connectable()
+ * @see bt_adapter_set_connectable_changed_cb()
+ * @see bt_adapter_unset_connectable_changed_cb()
+ */
+typedef void (*bt_adapter_connectable_changed_cb)
+       (int result, bool connectable, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Called when the state of LE device discovery changes.
+ *
+ * @remarks If \a discovery_state is #BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND,
+ * then you can get some information, such as remote LE device address, remote device name, rssi, and bonding state.
+ *
+ * @param[in] result The result of the LE device discovery
+ * @param[in] discovery_state The discovery state to be changed
+ * @param[in] discovery_info The information of the discovered LE device \n
+ *                                     If \a discovery_state is #BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED or
+ * #BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED, then \a discovery_info is NULL.
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre Either bt_adapter_start_device_discovery() or bt_adapter_stop_device_discovery() will invoke this function
+ * if you register this callback using bt_adapter_set_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_le_start_device_discovery()
+ * @see bt_adapter_le_stop_device_discovery()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ *
+ */
+typedef void (*bt_adapter_le_device_discovery_state_changed_cb)
+       (int result, bt_adapter_le_device_discovery_state_e discovery_state, bt_adapter_le_device_discovery_info_s *discovery_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Called when the state of advertiser changes.
+ *
+ * @param[out] result The result of the requested state change of advertiser
+ * @param[out] advertiser The handle of the state changed advertiser
+ * @param[out] adv_state The advertiser state to be changed
+ * @param[out] user_data The user data passed from the start function
+ *
+ * @see bt_adapter_le_start_advertiser()
+ * @see bt_adapter_le_stop_advertiser()
+ */
+typedef void (*bt_adapter_le_advertising_state_changed_cb)(int result,
+               bt_advertiser_h advertiser, bt_adapter_le_advertising_state_e adv_state, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Called when the Bluetooth adapter le state changes.
+ * @param[in]   result  The result of the adapter state changing
+ * @param[in]   adapter_le_state  The adapter le state to be changed
+ * @param[in]   user_data  The user data passed from the callback registration function
+ * @pre Either bt_adapter_le_enable() or bt_adapter_le_disable() will invoke this callback if you register this callback using bt_adapter_le_set_state_changed_cb().
+ * @see bt_adapter_le_enable()
+ * @see bt_adapter_le_disable()
+ * @see bt_adapter_le_set_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb()
+ */
+typedef void (*bt_adapter_le_state_changed_cb)(int result, bt_adapter_le_state_e adapter_le_state, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when the process of creating bond finishes.
+ * @remarks If the remote user does not respond within 60 seconds, a time out will happen with #BT_ERROR_TIMED_OUT result code.\n
+ * If bt_device_cancel_bonding() is called and it returns #BT_ERROR_NONE, then this callback function will be called
+ * with #BT_ERROR_CANCELLED result. \n
+ * If creating a bond succeeds but service search fails, then this callback will be called with #BT_ERROR_SERVICE_SEARCH_FAILED.
+ * In this case, you should try service search again by bt_device_start_service_search() to get the supported service list.
+ *
+ * @param[in] result The result of the bonding device
+ * @param[in] device_info The device information which you creates bond with
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre Either bt_device_create_bond() will invoke this function
+ * if you register this callback using bt_device_set_bond_created_cb().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_cancel_bonding()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+typedef void (*bt_device_bond_created_cb)(int result, bt_device_info_s *device_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when you get connected profiles repeatedly.
+ * @param[in] profile The connected Bluetooth profile
+ * @param[in] user_data The user data passed from the foreach function
+ * @return @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre bt_device_foreach_connected_profiles() will invoke this function.
+ * @see bt_device_foreach_connected_profiles()
+ */
+typedef bool (*bt_device_connected_profile)(bt_profile_e profile, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when the bond destroys.
+ * @param[in] result The result that a bond is destroyed
+ * @param[in] remote_address The address of the remote Bluetooth device to destroy bond with
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre bt_device_destroy_bond() will invoke this function
+ * if you register this callback using bt_device_set_bond_destroyed_cb().
+ *
+ * @see bt_device_destroy_bond()
+ * @see bt_device_set_bond_destroyed_cb()
+ * @see bt_device_unset_bond_destroyed_cb()
+ */
+typedef void (*bt_device_bond_destroyed_cb)(int result, char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when the authorization of device changes.
+ * @param[in] authorization The authorization of device
+ * @param[in] remote_address The address of the remote Bluetooth device which is (un)authorized
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre bt_device_set_authorization() will invoke this function if you register this callback using bt_device_set_authorization_changed_cb().
+ *
+ * @see bt_device_set_authorization()
+ * @see #bt_device_set_authorization_changed_cb()
+ * @see #bt_device_unset_authorization_changed_cb()
+ */
+typedef void (*bt_device_authorization_changed_cb)
+       (bt_device_authorization_e authorization, char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when the process of service search finishes.
+ * @remark If bt_device_cancel_service_search() is called and it returns #BT_ERROR_NONE,
+ * then this callback function will be called with #BT_ERROR_CANCELLED result.
+ *
+ * @param[in] result The result of the service searching
+ * @param[in] sdp_info The structure of service lists found on a device
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre Either bt_device_start_service_search() will invoke this function
+ * if you register this callback using  bt_device_set_service_searched_cb().
+ *
+ * @see bt_device_start_service_search()
+ * @see bt_device_cancel_service_search()
+ * @see bt_device_set_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ *
+ */
+typedef void (*bt_device_service_searched_cb)(int result, bt_device_sdp_info_s *sdp_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when the connection state is changed.
+ * @param[in] connected The connection status: (@c true = connected, @c false = disconnected)
+ * @param[in] conn_info The connection information
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_set_connection_state_changed_cb()
+ * @see bt_device_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_device_connection_state_changed_cb)(bool connected, bt_device_connection_info_s *conn_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Called when you receive data.
+ *
+ * @param[in] data The received data from the remote device
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre When the connected remote Bluetooth device invokes bt_socket_send_data(),
+ *             this function will be invoked if you register this function using bt_socket_set_data_received_cb().
+ *
+ * @see bt_socket_set_data_received_cb()
+ * @see bt_socket_unset_data_received_cb()
+ * @see bt_socket_send_data()
+ */
+typedef void (*bt_socket_data_received_cb)(bt_socket_received_data_s *data, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Called when the socket connection state changes.
+ * @param[in] result The result of connection state changing
+ * @param[in] connection_state The connection state
+ * @param[in] connection The connection information which is established or disconnected
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre Either bt_socket_connect_rfcomm() will invoke this function.
+ * In addtion, bt_socket_connection_state_changed_cb() will be invoked when the socket connection state is changed.
+ * @see bt_socket_listen_and_accept_rfcomm()
+ * @see bt_socket_connect_rfcomm()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_socket_connection_state_changed_cb)
+       (int result, bt_socket_connection_state_e connection_state, bt_socket_connection_s *connection, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief  Called when a RFCOMM connection is requested.
+ * @details You must call bt_socket_accept() if you want to accept. Otherwise, you must call bt_socket_reject().
+ * @param[in] socket_fd  The file descriptor of socket on which a connection is requested
+ * @param[in] remote_address  The address of remote device
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre If you register this callback function by bt_socket_set_connection_requested_cb() and listen a socket by bt_socket_listen(),
+ * bt_socket_connection_requested_cb() will be invoked.
+ * @see bt_socket_listen()
+ * @see bt_socket_accept()
+ * @see bt_socket_reject()
+ */
+typedef void (*bt_socket_connection_requested_cb) (int socket_fd, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief  Called when the push is requested.
+ * @details You must call bt_opp_server_accept() if you want to accept.
+ * Otherwise, you must call bt_opp_server_reject().
+ * @param[in] file  The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_initialize()
+ */
+typedef void (*bt_opp_server_push_requested_cb)(const char *file, int size, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief  Called when an OPP connection is requested.
+ * @details You must call bt_opp_server_accept_connection() if you want to accept.
+ * Otherwise, you must call bt_opp_server_reject_connection().
+ * @param[in] remote_address  The address of remote device
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_initialize()
+ * @see bt_opp_server_accept_connection()
+ * @see bt_opp_server_reject_connection()
+ */
+typedef void (*bt_opp_server_connection_requested_cb)(const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief  Called when a file is being transfered.
+ * @param[in] file  The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] percent The progress in percentage (1 ~ 100)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_accept()
+ * @see bt_opp_server_accept_connection()
+ */
+typedef void (*bt_opp_server_transfer_progress_cb) (const char *file, long long size, int percent, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief  Called when a transfer is finished.
+ * @param[in] error_code  The result of push
+ * @param[in] file  The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_accept()
+ * @see bt_opp_server_accept_connection()
+ */
+typedef void (*bt_opp_server_transfer_finished_cb) (int result, const char *file, long long size, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief  Called when OPP server responds to the push request.
+ * @param[in] result  The result of OPP server response
+ * @param[in] remote_address  The remote address
+ * @param[in] user_data  The user data passed from the callback registration function
+ * @pre bt_opp_client_push_files() will invoke this function.
+ * @see bt_opp_client_push_files()
+ */
+typedef void (*bt_opp_client_push_responded_cb)(int result, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief  Called when each file is being transfered.
+ * @param[in] file  The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] percent The progress in percentage (1 ~ 100). 100 means that a file is transfered completely.
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre bt_opp_client_push_files() will invoke this function.
+ * @see bt_opp_client_push_files()
+ */
+typedef void (*bt_opp_client_push_progress_cb)(const char *file, long long size, int percent, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief  Called when the push request is finished.
+ * @param[in] result  The result of the push request
+ * @param[in] remote_address  The remote address
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_client_push_files()
+ */
+typedef void (*bt_opp_client_push_finished_cb)(int result, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief  Called when the connection state is changed.
+ * @details  This callback is called when the connection state is changed.
+ * When you call bt_audio_connect() or bt_audio_disconnect(), this callback is also called with error result even though these functions fail.
+ * @param[in] result  The result of changing the connection state
+ * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address  The remote address
+ * @param[in] type  The type of audio profile except #BT_AUDIO_PROFILE_TYPE_ALL
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_audio_set_connection_state_changed_cb()
+ * @see bt_audio_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_audio_connection_state_changed_cb) (int result, bool connected, const char *remote_address, bt_audio_profile_type_e type, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Called when the SCO(Synchronous Connection Oriented link) state is changed.
+ * @details  This callback is called when the SCO state is changed.
+ * When you call bt_ag_open_sco() or bt_ag_close_sco(), this callback is also called with error result even though these functions failed.
+ * @param[in] result  The result of changing the connection state
+ * @param[in] opened  The state to be changed: (@c true = opened, @c  false = not opened)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_sco_state_changed_cb()
+ * @see bt_ag_unset_sco_state_changed_cb()
+ * @see bt_ag_open_sco()
+ * @see bt_ag_close_sco()
+ */
+typedef void (*bt_ag_sco_state_changed_cb) (int result, bool opened, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Called when a call handling event happened from Hands-Free.
+ * @param[in] event  The call handling event happened from Hands-Free
+ * @param[in] call_id  The call ID
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_call_handling_event_cb()
+ * @see bt_ag_unset_call_handling_event_cb()
+ */
+typedef void (*bt_ag_call_handling_event_cb) (bt_ag_call_handling_event_e event, unsigned int call_id, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Called when a multi call handling event happened from Hands-Free.
+ * @param[in] event  The call handling event happened from Hands-Free
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_multi_call_handling_event_cb()
+ * @see bt_ag_unset_multi_call_handling_event_cb()
+ */
+typedef void (*bt_ag_multi_call_handling_event_cb) (bt_ag_multi_call_handling_event_e event, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Called when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
+ * @param[in] dtmf  The DTMF transmitted from Hands-Free
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_dtmf_transmitted_cb()
+ * @see bt_ag_unset_dtmf_transmitted_cb()
+ */
+typedef void (*bt_ag_dtmf_transmitted_cb) (const char *dtmf, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Called when the speaker gain of the remote device is changed.
+ * @param[in] gain The gain of speaker (0 ~ 15)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+typedef void (*bt_ag_speaker_gain_changed_cb) (int gain, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Called when the microphone gain of the remote device is changed.
+ * @param[in] gain The gain of microphone (0 ~ 15)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_microphone_gain_changed_cb()
+ * @see bt_ag_unset_microphone_gain_changed_cb()
+ */
+typedef void (*bt_ag_microphone_gain_changed_cb) (int gain, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Called when the connection state is changed.
+ * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address  The remote address
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_target_initialize()
+ * @see bt_avrcp_target_deinitialize()
+ */
+typedef void (*bt_avrcp_target_connection_state_changed_cb) (bool connected, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Called when the equalizer state is changed by the remote control device.
+ * @param[in] equalizer The equalizer state
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_equalizer_state_changed_cb()
+ * @see bt_avrcp_unset_equalizer_state_changed_cb()
+ */
+typedef void (*bt_avrcp_equalizer_state_changed_cb) (bt_avrcp_equalizer_state_e equalizer, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Called when the repeat mode is changed by the remote control device.
+ * @param[in] repeat The repeat mode
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_repeat_mode_changed_cb()
+ * @see bt_avrcp_unset_repeat_mode_changed_cb()
+ */
+typedef void (*bt_avrcp_repeat_mode_changed_cb) (bt_avrcp_repeat_mode_e repeat, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Called when the shuffle mode is changed by the remote control device.
+ * @param[in] shuffle The shuffle mode
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_shuffle_mode_changed_cb()
+ * @see bt_avrcp_unset_shuffle_mode_changed_cb()
+ */
+typedef void (*bt_avrcp_shuffle_mode_changed_cb) (bt_avrcp_shuffle_mode_e shuffle, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief  Called when the scan mode is changed by the remote control device.
+ * @param[in] shuffle The shuffle mode
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_scan_mode_changed_cb()
+ * @see bt_avrcp_unset_scan_mode_changed_cb()
+ */
+typedef void (*bt_avrcp_scan_mode_changed_cb) (bt_avrcp_scan_mode_e scan, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief  Called when the connection state is changed.
+ * @details  This callback is called when the connection state is changed.
+ * When you call bt_hid_host_connect() or bt_hid_host_disconnect(), this callback is also called with error result even though these functions fail.
+ * @param[in] result  The result of changing the connection state
+ * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address  The remote address
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_hid_host_connect()
+ * @see bt_hid_host_disconnect()
+ */
+typedef void (*bt_hid_host_connection_state_changed_cb) (int result, bool connected, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Called when the connection is established.
+ * @param[in] result  The result of connecting to the remote device
+ * @param[in] remote_address  The address of connected remote device
+ * @param[in] app_id  The ID of application
+ * @param[in] type  The type of HDP(Health Device Profile) channel
+ * @param[in] channel  The connected data channel
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see  bt_hdp_disconnected_cb
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_hdp_connected_cb) (int result, const char *remote_address, const char *app_id,
+    bt_hdp_channel_type_e type, unsigned int channel, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Called when the connection is disconnected.
+ * @param[in] result  The result of disconnecting from the remote device
+ * @param[in] remote_address  The address of disconnected remote device
+ * @param[in] channel  The connected data channel
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see  bt_hdp_connected_cb
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_hdp_disconnected_cb) (int result, const char *remote_address, unsigned int channel, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief  Called when the you receive the data.
+ * @param[in] channel  The connected data channel
+ * @param[in] data  The received data
+ * @param[in] size  The size of received data (byte)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_hdp_set_data_received_cb()
+ * @see bt_hdp_unset_data_received_cb()
+ */
+typedef void (*bt_hdp_data_received_cb) (unsigned int channel, const char *data, unsigned int size, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Called when you get the primary services repeatedly.
+ * @param[in]  service  The attribute handle of service
+ * @param[in]  index  The index of a service, starts from 0
+ * @param[in]  total  The total number of services
+ * @param[in]  user_data  The user data passed from the foreach function
+ * @return  @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre  bt_gatt_foreach_primary_services() will invoke this function.
+ * @see  bt_gatt_foreach_primary_services()
+ */
+typedef bool (*bt_gatt_primary_service_cb) (bt_gatt_attribute_h service, int index, int total, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Called after the characteristics are discovered by bt_gatt_discover_characteristics().
+ * @remarks  If bt_gatt_discover_characteristics() failed, then this callback function is called only once with 0 totla and NULL characteristic_handle.
+ * @param[in]  result  The result of discovering
+ * @param[in]  index  The index of characteristics in a service, starts from 0
+ * @param[in]  total  The total number of characteristics in a service
+ * @param[in]  characteristic  The attribute handle of characteristic
+ * @param[in]  user_data  The user data passed from the request function
+ * @return  @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre  bt_gatt_discover_characteristics() will invoke this callback.
+ * @see  bt_gatt_discover_characteristics()
+ */
+typedef bool (*bt_gatt_characteristics_discovered_cb) (int result, int index, int total, bt_gatt_attribute_h characteristic, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Called when you get the included services repeatedly.
+ * @param[in]  service  The attribute handle of service
+ * @param[in]  user_data  The user data passed from the foreach function
+ * @return  @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre  bt_gatt_foreach_included_services() will invoke this function.
+ * @see  bt_gatt_foreach_included_services()
+ */
+typedef bool (*bt_gatt_included_service_cb) (bt_gatt_attribute_h service, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Called when a characteristic in service is changed.
+ * @param[in]  characteristic  The attribute handle of characteristic
+ * @param[in]  value  The value of characteristic (byte array)
+ * @param[in]  value_length  The length of value
+ * @param[in]  user_data  The user data passed from the callback registration function
+ * @see bt_gatt_set_characteristic_changed_cb()
+ * @see bt_gatt_unset_characteristic_changed_cb()
+ */
+typedef void (*bt_gatt_characteristic_changed_cb) (bt_gatt_attribute_h characteristic, unsigned char *value, int value_length, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Called when a characteristic value is written.
+ * @see bt_gatt_set_characteristic_value()
+ */
+typedef void (*bt_gatt_characteristic_write_cb) (int result, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Called when a characteristic value is read.
+ * @param[in]  value  The value of characteristic (byte array)
+ * @param[in]  value_length  The length of value
+ * @param[in]  user_data  The user data passed from the foreach function
+ * @see bt_gatt_read_characteristic_value()
+ */
+typedef void (*bt_gatt_characteristic_read_cb) (unsigned char *value,
+                       int value_length, void *user_data);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief  Called after the characteristics descriptors are discovered by bt_gatt_discover_characteristic_descriptor().
+ * @param[in]  result  The result of discovering
+ * @param[in]  characteristic_format  The format of the information data.
+ *                        characteristic_format = 0x01 indicates UUIDs are 16-bits
+ *                        characteristic_format = 0x02 indicates UUIDs are 128-bits
+ * @param[in]  total  The total number of elements in characteristic_descriptor
+ * @param[in]  characteristic descriptor  The attribute handle and the UUID of characteristic descriptor
+ * @param[in]  characteristic  The attribute handle and the UUID of characteristic
+ * @param[in]  user_data  The user data passed from the request function
+ * @see  bt_gatt_discover_characteristic_descriptor()
+ */
+typedef void (*bt_gatt_characteristic_descriptor_discovered_cb) (int result,
+               unsigned char characteristic_format, int total,
+               bt_gatt_attribute_h characteristic_descriptor,
+               bt_gatt_attribute_h characteristic, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when the connection state is changed.
+ * @details This callback is called when the connection state is changed.
+ * When you called bt_gatt_connect() or bt_gatt_disconnect(), this callback is also called with error result even though these functions fail.
+ *
+ * @param[in] result The result of changing the connection state.
+ * @param[in] connected The state to be changed, @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address The remote_address
+ * @param[in] user_data The user data passed from the callback registration function.
+ *
+ * @see bt_gatt_connect()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_set_connection_state_changed_cb()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_gatt_connection_state_changed_cb)(int result, bool connected, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when the remote devices writes a characteristic to the server db.
+ * @details This callback is called when the remote client device writes a characteristics
+ *                     to the server attribute database.
+ *
+ * @param[in] char_path Characteristic path for which the value is writtten.
+ * @param[in] char_value The characteristic value
+ * @param[in] value_length The length of the characteristic value written.
+ * @param[in] remote_address remote client device bd address.
+ *
+ * @see bt_gatt_connect()
+ */
+typedef void (*bt_gatt_remote_characteristic_write_cb) (char *char_path,
+                                       unsigned char* char_value, int value_length,
+                                       const char *remote_address,
+                                       void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief  Called when the connection state is changed.
+ * @param[in] connected  Indicates whether a client is connected or disconnected
+ * @param[in] remote_address  The remote address
+ * @param[in] interface_name  The interface name. For example, bnep0, bnep1.
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_nap_set_connection_state_changed_cb()
+ * @see bt_nap_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_nap_connection_state_changed_cb) (bool connected, const char *remote_address, const char *interface_name, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief  Called when the connection state is changed.
+ * @details  This callback is called when the connection state is changed.
+ * When you call bt_panu_connect() or bt_panu_disconnect(), this callback is also called with error result even though these functions fail.
+ * @param[in] result  The result of changing the connection state
+ * @param[in] connected  The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address  The remote address
+ * @param[in] type  The type of PAN service
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_nap_set_connection_state_changed_cb()
+ * @see bt_nap_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_panu_connection_state_changed_cb) (int result, bool connected, const char *remote_address, bt_panu_service_type_e type, void *user_data);
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_product.h b/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_product.h
new file mode 100644 (file)
index 0000000..74f2b55
--- /dev/null
@@ -0,0 +1,315 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file
+ *
+ *
+ */
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
+#define __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
+
+#include "bluetooth_type.h"
+#include "bluetooth_type_product.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the manufacturer data of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in]   data   The manufacturer specific data of the Bluetooth device.
+ * @param[in]   len    The length of @a data.Maximaum length is 240 bytes.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_manufacturer_data_changed_cb() will be invoked
+ * if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_manufacturer_data_changed_cb
+ * @see bt_adapter_set_manufacturer_data_changed_cb()
+ * @see bt_adapter_unset_manufacturer_data_changed_cb()
+ */
+int bt_adapter_set_manufacturer_data(char *data, int len);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Registers a callback function to be invoked
+ * when the manufacturer data of Bluetooth adapter changes.
+ * @since_tizen 2.3
+ *
+ * @param[in]   callback       The callback function to invoke
+ * @param[in]   user_data      The user data to be passed to the callback function
+ *
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post  bt_adapter_manufacturer_data_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_unset_manufacturer_data_changed_cb()
+ */
+int bt_adapter_set_manufacturer_data_changed_cb(
+               bt_adapter_manufacturer_data_changed_cb callback,
+               void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief      Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return     0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_manufacturer_data_changed_cb()
+ */
+int bt_adapter_unset_manufacturer_data_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Sets the scan interval and widow, synchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in]  scan_params  The parameters of le scanning \n
+ *                             If NULL is passed, default values which are defined in driver / controller are used.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_ENABLED Adapter is not enabled
+ * @retval #BT_ERROR_INVALID_PARAM Parameter is invalid
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_le_set_scan_parameter(bt_adapter_le_scan_params_s *scan_params);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enables RSSI monitoring and sets threshold for LE/ACL link present with the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device for which RSSI is to be monitored
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] low_threshold Lower threshold value for the LE Link in dBm.
+ * @param[in] in_range_threshold In-Range threshold value for the LE Link in dBm.
+ * @param[in] cb_enable Callback to be called when RSSI monitoring is enabled.
+ * @param[in] user_data_enable Data to be passed to RSSI enable callback.
+ * @param[in] cb_alert Callback to receive RSSI Alert values.
+ * @param[in] user_data_alert Data to be passed to RSSI Alert callback.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @remarks High Threshold value is set to 127.
+ *
+ * @see bt_device_unset_rssi_alert_cb()
+ * @see bt_device_disable_rssi_monitor()
+ */
+int bt_device_enable_rssi_monitor(const char *remote_address,
+               bt_device_connection_link_type_e link_type,
+               int low_threshold, int in_range_threshold,
+               bt_rssi_monitor_enabled_cb cb_enable, void *user_data_enable,
+               bt_rssi_alert_cb cb_alert, void *user_data_alert);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Disables RSSI monitoring for LE/ACL link present with the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device for which RSSI monitoring is to be disabled
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] cb_disable Callback to be called when RSSI monitoring is disabled.
+ * @param[in] user_data_enable Data to be passed to RSSI enable callback.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @remarks Low Threshold, In-range Threshold and High Threshold value are set to 0 to disable RSSI monitoring.
+ * @remarks This also calls bt_device_unset_rssi_alert_cb()
+ *
+ * @see bt_device_unset_rssi_alert_cb()
+ * @see bt_device_enable_rssi_monitor()
+ */
+int bt_device_disable_rssi_monitor(const char *remote_address,
+               bt_device_connection_link_type_e link_type,
+               bt_rssi_monitor_enabled_cb cb_disable, void *user_data_disable);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Get Raw RSSI for LE link present with the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device for which RSSI is to be monitored
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] callback Callback to receive Raw RSSI values.
+ * @param[in] user_data Data to be passed to Raw RSSI callback.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY  Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ *
+ * @see bt_device_le_unset_rssi_strength_cb()
+ */
+int bt_device_get_rssi_strength(const char *remote_address,
+               bt_device_connection_link_type_e link_type,
+               bt_rssi_strength_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Unset the callback to receive RSSI Alert values.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ *
+ * @see bt_device_le_enable_rssi()
+ */
+int bt_device_unset_rssi_alert_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the XSAT vendor command to the remote.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state  The XSAT vendor dependent command string. Ex: "AT+SAT= 00,TY,WA"
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED  Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED  Operation failed
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_vendor_cmd(const char *command);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Registers a callback function that will be invoked when a XSATvendor AT command is transmitted from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_vendor_cmd_cb()
+ * @see bt_ag_unset_vendor_cmd_cb()
+ */
+int bt_ag_set_vendor_cmd_cb(bt_ag_vendor_cmd_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Unregisters a callback function that will be invoked when a XSATvendor AT command is transmitted from Hands-Free
+ * @since_tizen 2.3
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_vendor_cmd_cb()
+ * @see bt_ag_set_vendor_cmd_cb()
+ */
+int bt_ag_unset_vendor_cmd_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Checks whether the remoted device is wbs (Wide Band Speech) mode or not.
+ * @since_tizen 2.3
+ * @param[out] wbs_mode The wbs status: (@c true = wide band speech, @c  false = narrow band speech)
+ * @return   0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE  Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED  Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER  Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED  Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED  Remote device is not connected
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_audio_connect()
+ */
+int bt_ag_is_wbs_mode(bool *wbs_mode);
+
+/**
+ * @ingroup  CAPI_NETWORK_BLUETOOTH_AUDIO_A2DP_MODULE
+ * @brief  Sets copy protection. streaming application that needs to have the copy protection for the streaming data, shall invoke this API.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] status - TRUE/FALSE
+ * @return  0 on success, otherwise negative error value.
+ * @retval  #BT_ERROR_NONE  Successful
+ * @retval  #BT_ERROR_OPERATION_FAILED  on failure
+ */
+int bt_a2dp_set_content_protection(bool status);
+
+
+/**
+ * @}
+ */
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
diff --git a/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_type_product.h b/resource/csdk/connectivity/lib/tizen/ble/inc/mobile/bluetooth_type_product.h
new file mode 100644 (file)
index 0000000..999b847
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file
+ *
+ *
+ */
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
+#define __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
+
+ #ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief  Enumerations of the Bluetooth adapter le scan type.
+ */
+typedef enum
+{
+       BT_ADAPTER_LE_PASSIVE_SCAN = 0x00,
+       BT_ADAPTER_LE_ACTIVE_SCAN
+} bt_adapter_le_scan_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Structure of le scan parameters
+ *
+ * @see bt_adapter_le_set_scan_parameter()
+ * @see bt_adapter_le_start_device_discovery()
+ */
+typedef struct {
+       bt_adapter_le_scan_type_e type;  /**< LE scan type */
+       float interval;  /**< LE scan interval */
+       float window;  /**< LE scan window */
+} bt_adapter_le_scan_params_s;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief  Called when the manufacturer dat changes.
+ * @param[in]   data           The manufacurer data of the Bluetooth device to be changed
+ * @param[in]   len                    The length of @a data
+ * @param[in]   user_data      The user data passed from the callback registration function
+ * @pre This function will be invoked when the manufacturer data of Bluetooth adapter changes
+ * if callback is registered using bt_adapter_set_manufacturer_data_changed_cb().
+ * @see bt_adapter_set_manufacturer_data()
+ * @see bt_adapter_set_manufacturer_data_changed_cb()
+ * @see bt_adapter_unset_manufacturer_data_changed_cb()
+ */
+typedef void (*bt_adapter_manufacturer_data_changed_cb) (char *data,
+               int len, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when RSSI monitoring is enabled.
+ * @param[in] remote_address Remote Device address
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] rssi_enabled RSSI monitoring status (@c 1 = enabled, @c 0 = disabled)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_enable_rssi_monitor()
+ * @see bt_device_disable_rssi_monitor()
+ */
+typedef void (*bt_rssi_monitor_enabled_cb)(const char *remote_address,
+               bt_device_connection_link_type_e link_type,
+               int rssi_enabled, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when RSSI Alert is received.
+ * @param[in] remote_address Remote Device address
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] rssi_alert_type RSSI Alert type (@c 1 = High Alert (In-Range Alert), @c 2 = Low Alert)
+ * @param[in] rssi_alert_dbm RSSI Alert signal strength value
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_enable_rssi_monitor()
+ * @see bt_device_disable_rssi_monitor()
+ */
+typedef void (*bt_rssi_alert_cb)(char *bt_address,
+               bt_device_connection_link_type_e link_type,
+               int rssi_alert_type, int rssi_alert_dbm, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief  Called when Raw RSSI signal strength is received.
+ * @param[in] remote_address Remote Device address
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] rssi_dbm Raw RSSI signal strength value
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_get_rssi_strength()
+ */
+typedef void (*bt_rssi_strength_cb)(char *bt_address,
+               bt_device_connection_link_type_e link_type,
+               int rssi_dbm, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief  Called when a XSAT vendor command is transmitted from Hands-Free.
+ * @param[in] command  The XSAT vendor command transmitted from Hands-Free
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_vendor_cmd_cb()
+ * @see bt_ag_unset_vendor_cmd_cb()
+ */
+typedef void (*bt_ag_vendor_cmd_cb) (char *command, void *user_data);
+
+
+/**
+ * @}
+ */
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
diff --git a/resource/csdk/connectivity/samples/android/SConscript b/resource/csdk/connectivity/samples/android/SConscript
new file mode 100644 (file)
index 0000000..e3a4f18
--- /dev/null
@@ -0,0 +1,51 @@
+##\r
+# Building sample application\r
+##\r
+\r
+Import('env')\r
+\r
+app_env = env.Clone()\r
+\r
+ca_os = app_env.get('TARGET_OS')\r
+ca_transport = app_env.get('TARGET_TRANSPORT')\r
+secured = app_env.get('SECURED')\r
+\r
+root_dir = './../../'\r
+main_dir  = Dir('.').srcnode().abspath\r
+jni_dir = main_dir + '/sample_serivce/android/jni'\r
+env.PrependUnique(CPPPATH = ['jni_dir'])\r
+app_env.PrependUnique(CPPDEFINES = ['__ANDROID__'])\r
+\r
+#####################################################################\r
+# Source files and Target(s)\r
+######################################################################\r
+\r
+print"Reading ca script %s"%ca_transport\r
+\r
+app_env.AppendUnique(CPPPATH = [root_dir + '/api/'])\r
+\r
+print "Reading sample application build script"\r
+\r
+build_dir = app_env.get('BUILD_DIR')\r
+secured = app_env.get('SECURED')\r
+\r
+print "Sample secured flag is %s" % secured\r
+\r
+sample_dir = 'sample_service/jni/'\r
+sample_src = [sample_dir + 'ResourceModel.c',]\r
+\r
+print " sample src %s" % sample_src\r
+\r
+app_env.AppendUnique(LIBPATH = [app_env.get('BUILD_DIR'), '.',])\r
+app_env.AppendUnique(CPPPATH = ['lib/android'])\r
+app_env.PrependUnique(LIBS = ['connectivity_abstraction'])\r
+\r
+\r
+if secured == '1':\r
+       app_env.AppendUnique(CPPPATH = [root_dir + 'external/inc/'])\r
+       app_env.PrependUnique(CPPDEFINES = ['__WITH_DTLS__'])\r
+\r
+libRMInterface = app_env.SharedLibrary('RMInterface', sample_src, OBJPREFIX='libRMInterface_')\r
+app_env.InstallTarget(libRMInterface, 'RMInterface')\r
+\r
+\r
diff --git a/resource/csdk/connectivity/samples/android/sample_service/AndroidManifest.xml b/resource/csdk/connectivity/samples/android/sample_service/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..91fcef9
--- /dev/null
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.iotivity.sample_service"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="19"
+        android:targetSdkVersion="21" />
+
+    <application
+        android:allowBackup="true"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name="org.iotivity.service.MainActivity"
+            android:label="@string/app_name"
+            android:windowSoftInputMode="stateHidden" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+    <uses-permission android:name="android.permission.BLUETOOTH" />
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
+    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+
+</manifest>
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/jni/Android.mk b/resource/csdk/connectivity/samples/android/sample_service/jni/Android.mk
new file mode 100644 (file)
index 0000000..55ac16d
--- /dev/null
@@ -0,0 +1,27 @@
+APP_PATH := $(call my-dir)
+#specify project root path here wrt make file directory
+PROJECT_ROOT_PATH      = ../../..
+
+include $(CLEAR_VARS)
+LOCAL_PATH := $(APP_PATH)
+LOCAL_MODULE := CAInterface
+LOCAL_STATIC_LIBRARIES = CA
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_PATH := $(APP_PATH)
+LOCAL_MODULE := RMInterface
+LOCAL_SRC_FILES := ResourceModel.c
+LOCAL_STATIC_LIBRARIES := CA
+LOCAL_LDLIBS := -llog
+LOCAL_C_INCLUDES := ../../../api
+include $(BUILD_SHARED_LIBRARY)
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#Build CACommon CACoap CA
+include $(CLEAR_VARS)
+PROJECT_ROOT_PATH                      = ../../..
+CA_LIB_PATH                            = $(PROJECT_ROOT_PATH)/build/android
+include $(CA_LIB_PATH)/jni/Android.mk
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/jni/Application.mk b/resource/csdk/connectivity/samples/android/sample_service/jni/Application.mk
new file mode 100644 (file)
index 0000000..a0e5d81
--- /dev/null
@@ -0,0 +1,6 @@
+APP_STL := gnustl_shared
+
+APP_PLATFORM = android-21
+APP_CPPFLAGS += -fexceptions
+APP_CPPFLAGS += -frtti
+APP_CFLAGS = -Wno-error=format-security
diff --git a/resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c b/resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c
new file mode 100644 (file)
index 0000000..acca05d
--- /dev/null
@@ -0,0 +1,1322 @@
+#include <jni.h>
+#include <android/log.h>
+#include <stdio.h>
+#include <dlfcn.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "cainterface.h"
+#include "cacommon.h"
+
+#include "org_iotivity_service_RMInterface.h"
+
+#define  LOG_TAG   "JNI_INTERFACE_SAMPLE"
+#define  LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
+#define  LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
+
+/**
+ * @def RS_IDENTITY
+ * @brief
+ */
+#define IDENTITY     ("1111111111111111")
+/* @def RS_CLIENT_PSK
+ * @brief
+ */
+#define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
+
+#define PORT_LENGTH 5
+#define SECURE_DEFAULT_PORT 5684
+#define RESOURCE_URI_LENGTH 14
+#define OPTION_INFO_LENGTH 1024
+#define NETWORK_INFO_LENGTH 1024
+
+uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
+
+void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo);
+void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo);
+void get_resource_uri(const char *URI, char *resourceURI, uint32_t length);
+uint32_t get_secure_information(CAPayload_t payLoad);
+CAResult_t get_network_type(uint32_t selectedNetwork);
+void callback(char *subject, char *receivedData);
+CAResult_t get_remote_address(CATransportType_t transportType, CAAddress_t addressInfo);
+
+CATransportType_t g_selectedNwType = CA_IPV4;
+static CAToken_t g_lastRequestToken = NULL;
+static uint8_t g_lastRequestTokenLength;
+
+static const char SECURE_COAPS_PREFIX[] = "coaps://";
+
+static const char SECURE_INFO_DATA[]
+                                   = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[]
+                                   = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
+
+
+static jobject g_responseListenerObject = NULL;
+static JavaVM *g_jvm;
+
+static CARemoteEndpoint_t *g_clientEndpoint = NULL;
+static CAToken_t g_clientToken;
+static uint8_t g_clientTokenLength = NULL;
+
+static uint16_t g_clientMsgId;
+static char *g_remoteAddress = NULL;
+
+// init
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
+                                                                jobject listener)
+{
+    LOGI("setNativeResponseListener");
+    g_responseListenerObject = (*env)->NewGlobalRef(env, obj);
+}
+
+#ifdef __WITH_DTLS__
+static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
+
+void clearDtlsCredentialInfo()
+{
+    LOGI("clearDtlsCredentialInfo IN");
+    if (pskCredsBlob)
+    {
+        // Initialize sensitive data to zeroes before freeing.
+        if (NULL != pskCredsBlob->creds)
+        {
+            memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds)*(pskCredsBlob->num));
+            free(pskCredsBlob->creds);
+        }
+
+        memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
+        free(pskCredsBlob);
+        pskCredsBlob = NULL;
+    }
+    LOGI("clearDtlsCredentialInfo OUT");
+}
+
+// Internal API. Invoked by OC stack to retrieve credentials from this module
+void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+{
+    LOGI("CAGetDtlsPskCredentials IN");
+    *credInfo = (CADtlsPskCredsBlob_t *) malloc(sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == *credInfo)
+    {
+        LOGE("Failed to allocate credential blob.");
+        return;
+    }
+
+    int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
+    (*credInfo)->creds = (OCDtlsPskCreds *) malloc(credLen);
+    if (NULL == (*credInfo)->creds)
+    {
+        LOGE("Failed to allocate crentials.");
+        free(*credInfo);
+        *credInfo = NULL;
+        return;
+    }
+
+    memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
+    (*credInfo)->num = pskCredsBlob->num;
+    memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
+
+    LOGI("CAGetDtlsPskCredentials OUT");
+}
+
+CAResult_t SetCredentials()
+{
+    LOGI("SetCredentials IN");
+    pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == pskCredsBlob)
+    {
+        LOGE("Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+
+    pskCredsBlob->num = 1;
+
+    pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) *(pskCredsBlob->num));
+    if (NULL == pskCredsBlob->creds)
+    {
+        LOGE("Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
+    memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
+
+    LOGI("SetCredentials OUT");
+    return CA_STATUS_OK;
+}
+#endif
+
+JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
+{
+    LOGI("JNI_OnLoad");
+
+    JNIEnv* env;
+    if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
+    {
+        return -1;
+    }
+    g_jvm = jvm; /* cache the JavaVM pointer */
+
+    CANativeJNISetJavaVM(g_jvm);
+
+    return JNI_VERSION_1_6;
+}
+
+void JNI_OnUnload(JavaVM *jvm, void *reserved)
+{
+    LOGI("JNI_OnUnload");
+
+    JNIEnv* env;
+    if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
+    {
+        return;
+    }
+    g_jvm = 0;
+    return;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
+{
+    LOGI("RMInitialize");
+
+    //Currently set context for Android Platform
+    CANativeJNISetContext(env, context);
+
+    CAResult_t res = CAInitialize();
+
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not Initialize");
+    }
+
+#ifdef __WITH_DTLS__
+    if (CA_STATUS_OK != SetCredentials())
+    {
+        LOGE("SetCredentials failed");
+        return;
+    }
+
+    res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
+    if(CA_STATUS_OK != res)
+    {
+        LOGE("Set credential handler fail");
+        return;
+    }
+#endif
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
+{
+    LOGI("RMTerminate");
+    CADestroyToken(g_lastRequestToken);
+    CATerminate();
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
+{
+    LOGI("RMStartListeningServer");
+
+    if (CA_STATUS_OK != CAStartListeningServer())
+    {
+        LOGE("Could not start Listening server");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
+{
+    LOGI("RMStartDiscoveryServer");
+
+    if (CA_STATUS_OK != CAStartDiscoveryServer())
+    {
+        LOGE("Could not start discovery server");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
+{
+    LOGI("RMRegisterHandler");
+
+    CARegisterHandler(request_handler, response_handler);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMFindResource(JNIEnv *env, jobject obj, jstring uri)
+{
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        LOGE("token generate error!!");
+        return;
+    }
+
+    printf("Generated token %s\n", token);
+
+    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
+    LOGI("RMFindResource - %s", strUri);
+
+    res = CAFindResource((const CAURI_t) strUri, token, tokenLength);
+
+    //ReleseStringUTFCharss for strUri
+    (*env)->ReleaseStringUTFChars(env, uri, strUri);
+
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not find resource");
+        //destroy token
+        CADestroyToken(token);
+    }
+    else
+    {
+        LOGI("find resource to %s URI", strUri);
+        CADestroyToken(g_lastRequestToken);
+        g_lastRequestToken = token;
+        g_lastRequestTokenLength = tokenLength;
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
+                                                    jstring payload, jint selectedNetwork,
+                                                    jint isSecured, jint msgType)
+{
+    LOGI("selectedNetwork - %d", selectedNetwork);
+    CAResult_t res = get_network_type(selectedNetwork);
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
+    LOGI("RMSendRequest - %s", strUri);
+
+    //create remote endpoint
+    CARemoteEndpoint_t* endpoint = NULL;
+    res = CACreateRemoteEndpoint((const CAURI_t) strUri, g_selectedNwType, &endpoint);
+
+    //ReleaseStringUTFChars for strUri
+    (*env)->ReleaseStringUTFChars(env, uri, strUri);
+
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not create remote end point");
+        return;
+    }
+
+    CAMessageType_t messageType = msgType;
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        LOGE("token generate error!!");
+        // destroy remote endpoint
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
+
+    get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
+
+    CAInfo_t requestData = { 0 };
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+
+    if (1 == isSecured)
+    {
+        uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) malloc(length);
+        if (NULL == requestData.payload)
+        {
+            LOGE("Memory allocation failed!");
+            // destroy token
+            CADestroyToken(token);
+            // destroy remote endpoint
+            CADestroyRemoteEndpoint(endpoint);
+            return;
+        }
+        snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
+    }
+    else
+    {
+        uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) malloc(length);
+        if (NULL == requestData.payload)
+        {
+            LOGE("Memory allocation failed!");
+            // destroy token
+            CADestroyToken(token);
+            // destroy remote endpoint
+            CADestroyRemoteEndpoint(endpoint);
+            return;
+        }
+        snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
+    }
+
+    requestData.type = messageType;
+
+    CARequestInfo_t requestInfo = { 0 };
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    // send request
+    if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
+    {
+        LOGE("Could not send request");
+    }
+
+    // destroy token
+    CADestroyToken(token);
+
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+
+    free(requestData.payload);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
+                                                        jint selectedNetwork)
+{
+    LOGI("selectedNetwork - %d", selectedNetwork);
+    CAResult_t res = get_network_type(selectedNetwork);
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
+    LOGI("RMSendReqestToAll - %s", strUri);
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    res = CACreateRemoteEndpoint((const CAURI_t) strUri, g_selectedNwType, &endpoint);
+
+    //ReleaseStringUTFChars for strUri
+    (*env)->ReleaseStringUTFChars(env, uri, strUri);
+
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("create remote endpoint error, error code: %d", res);
+        return;
+    }
+
+    CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+    if (NULL == group)
+    {
+        LOGE("Memory allocation failed!");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+    group->transportType = endpoint->transportType;
+    group->resourceUri = endpoint->resourceUri;
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        LOGE("token generate error!!");
+        // destroy remote endpoint
+        CADestroyRemoteEndpoint(endpoint);
+        free(group);
+        return;
+    }
+
+    LOGI("generated token %s", token);
+
+    CAInfo_t requestData = { 0 };
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+    requestData.payload = "Temp Json Payload";
+    requestData.type = CA_MSG_NONCONFIRM;
+
+    CARequestInfo_t requestInfo = { 0 };
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    // send request to all
+    res = CASendRequestToAll(group, &requestInfo);
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not send request to all");
+        //destroy token
+        CADestroyToken(token);
+    }
+    else
+    {
+        CADestroyToken(g_lastRequestToken);
+        g_lastRequestToken = token;
+        g_lastRequestTokenLength = tokenLength;
+    }
+
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+    free(group);
+
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
+                                                     jint selectedNetwork,
+                                                     jint isSecured, jint msgType,
+                                                     jint responseValue)
+{
+    LOGI("RMSendResponse");
+
+    LOGI("selectedNetwork - %d", selectedNetwork);
+
+    CAResult_t res = get_network_type(selectedNetwork);
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Not supported network type");
+        return;
+    }
+
+    if (NULL == g_clientEndpoint)
+    {
+        LOGE("No Request received");
+        return;
+    }
+
+    CAMessageType_t messageType = msgType;
+
+    CAInfo_t responseData = { 0 };
+    responseData.type = messageType;
+    responseData.messageId = g_clientMsgId;
+
+    CAResponseInfo_t responseInfo = { 0 };
+
+    if (msgType != CA_MSG_RESET)
+    {
+        responseData.token = g_clientToken;
+        responseData.tokenLength = g_clientTokenLength;
+        responseInfo.result = responseValue;
+
+        if (1 == isSecured)
+        {
+            uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_clientEndpoint->resourceUri) + 1;
+            responseData.payload = (CAPayload_t) malloc(length);
+            sprintf(responseData.payload, SECURE_INFO_DATA, g_clientEndpoint->resourceUri,
+                    g_localSecurePort);
+        }
+        else
+        {
+            uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_clientEndpoint->resourceUri) + 1;
+            responseData.payload = (CAPayload_t) malloc(length);
+            sprintf(responseData.payload, NORMAL_INFO_DATA, g_clientEndpoint->resourceUri);
+        }
+    }
+    //msgType is RESET
+    else
+    {
+        responseInfo.result = CA_EMPTY;
+    }
+
+    responseInfo.info = responseData;
+
+    // send response
+    res = CASendResponse(g_clientEndpoint, &responseInfo);
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not send response");
+    }
+
+    // destroy token
+    CADestroyToken(g_clientToken);
+    g_clientToken = NULL;
+    g_clientTokenLength = 0;
+
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(g_clientEndpoint);
+    g_clientEndpoint = NULL;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMAdvertiseResource(JNIEnv *env, jobject obj, jstring uri)
+{
+    LOGI("RMAdvertiseResource");
+
+    uint32_t optionNum = 2;
+
+    CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
+                                                             sizeof(CAHeaderOption_t) * optionNum);
+    if (NULL == headerOpt)
+    {
+        LOGE("Memory allocation failed!");
+        return;
+    }
+
+    char* tmpOptionData1 = "Hello";
+    headerOpt[0].optionID = 3000;
+    memcpy(headerOpt[0].optionData, tmpOptionData1, strlen(tmpOptionData1));
+    headerOpt[0].optionLength = (uint16_t) strlen(tmpOptionData1);
+
+    char* tmpOptionData2 = "World";
+    headerOpt[1].optionID = 3001;
+    memcpy(headerOpt[1].optionData, tmpOptionData2, strlen(tmpOptionData2));
+    headerOpt[1].optionLength = (uint16_t) strlen(tmpOptionData2);
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        LOGE("token generate error!");
+        free(headerOpt);
+        return;
+    }
+
+    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
+
+    res = CAAdvertiseResource((const CAURI_t) strUri, token, tokenLength,
+                              headerOpt, (uint8_t) optionNum);
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not start advertise resource");
+        CADestroyToken(token);
+    }
+    else
+    {
+        CADestroyToken(g_lastRequestToken);
+        g_lastRequestToken = token;
+        g_lastRequestTokenLength = tokenLength;
+    }
+
+    free(headerOpt);
+
+    //ReleaseStringUTFChars for strUri
+    (*env)->ReleaseStringUTFChars(env, uri, strUri);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
+                                                         jstring payload, jint selectedNetwork,
+                                                         jint isSecured, jint msgType,
+                                                         jint responseValue)
+{
+    LOGI("selectedNetwork - %d", selectedNetwork);
+
+    CAResult_t res = get_network_type(selectedNetwork);
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Not supported network type");
+        return;
+    }
+
+    const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
+    LOGI("RMSendNotification - %s", strUri);
+
+    //create remote endpoint
+    CARemoteEndpoint_t* endpoint = NULL;
+    if (CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t) strUri,
+                                               g_selectedNwType, &endpoint))
+    {
+        //ReleaseStringUTFChars for strUri
+        (*env)->ReleaseStringUTFChars(env, uri, strUri);
+        LOGE("Could not create remote end point");
+        return;
+    }
+
+    char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
+    get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
+
+    //ReleaseStringUTFChars for strUri
+    (*env)->ReleaseStringUTFChars(env, uri, strUri);
+
+    CAMessageType_t messageType = msgType;
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        LOGE("token generate error!");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    CAInfo_t responseData = { 0 };
+    responseData.token = token;
+    responseData.tokenLength = tokenLength;
+
+    if (1 == isSecured)
+    {
+        uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+        responseData.payload = (CAPayload_t) malloc(length);
+        if (NULL == responseData.payload)
+        {
+            LOGE("Memory allocation failed!");
+            // destroy token
+            CADestroyToken(token);
+            // destroy remote endpoint
+            CADestroyRemoteEndpoint(endpoint);
+            return;
+        }
+        snprintf(responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
+    }
+    else
+    {
+        uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+        responseData.payload = (CAPayload_t) malloc(length);
+        if (NULL == responseData.payload)
+        {
+            LOGE("Memory allocation failed!");
+            // destroy token
+            CADestroyToken(token);
+            // destroy remote endpoint
+            CADestroyRemoteEndpoint(endpoint);
+            return;
+        }
+        snprintf(responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
+    }
+
+    responseData.type = messageType;
+
+    CAResponseInfo_t responseInfo = { 0 };
+    responseInfo.result = responseValue;
+    responseInfo.info = responseData;
+
+    // send notification
+    if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
+    {
+        LOGE("Could not send notification");
+    }
+
+    LOGI("Send Notification");
+
+    // destroy token
+    CADestroyToken(token);
+
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+
+    free(responseData.payload);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj, jint networkType)
+{
+    LOGI("RMSelectNetwork Type : %d", networkType);
+
+    if (CA_STATUS_OK != CASelectNetwork(networkType))
+    {
+        LOGE("Could not select network");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj, jint networkType)
+{
+    LOGI("RMUnSelectNetwork Type : %d", networkType);
+
+    if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
+    {
+        LOGE("Could not unselect network");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
+{
+    LOGI("RMGetNetworkInfomation");
+
+    CALocalConnectivity_t *tempInfo = NULL;
+    uint32_t tempSize = 0;
+
+    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+    if (CA_STATUS_OK != res)
+    {
+        LOGE("Could not start get network information");
+        OICFree(tempInfo);
+        return;
+    }
+
+    LOGI("################## Network Information #######################");
+    callback("######## Network Information", "#######");
+    LOGI("Network info total size is %d", tempSize);
+
+    uint32_t index;
+    for (index = 0; index < tempSize; index++)
+    {
+        res = get_remote_address(tempInfo[index].type, tempInfo[index].addressInfo);
+        if (CA_STATUS_OK != res)
+        {
+            OICFree(tempInfo);
+            return;
+        }
+        if (NULL != g_responseListenerObject)
+        {
+            char networkInfo[NETWORK_INFO_LENGTH];
+            LOGI("Type: %d", tempInfo[index].type);
+            sprintf(networkInfo, "%d",tempInfo[index].type);
+            callback("Type :", networkInfo);
+            if (CA_IPV4 == tempInfo[index].type)
+            {
+                LOGI("Port: %d", tempInfo[index].addressInfo.IP.port);
+                sprintf(networkInfo, "%d",tempInfo[index].addressInfo.IP.port);
+                callback("Port: ", networkInfo);
+            }
+            LOGI("Secured: %d", tempInfo[index].isSecured);
+            LOGI("Address: %s", g_remoteAddress);
+            callback("Address: ", g_remoteAddress);
+            free(g_remoteAddress);
+        }
+        if (true == tempInfo[index].isSecured)
+        {
+            g_localSecurePort = tempInfo[index].addressInfo.IP.port;
+        }
+    }
+
+    // free
+    OICFree(tempInfo);
+
+    LOGI("##############################################################");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
+{
+    LOGI("RMHandleRequestResponse");
+
+    if (CA_STATUS_OK != CAHandleRequestResponse())
+    {
+        LOGE("Could not handle request and response");
+    }
+}
+
+void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
+{
+
+    if (!object)
+    {
+        LOGE("Remote endpoint is NULL!");
+        return;
+    }
+
+    if (!requestInfo)
+    {
+        LOGE("Request info is NULL!");
+        return;
+    }
+
+    if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
+            (strncmp(g_lastRequestToken, requestInfo->info.token,
+                     requestInfo->info.tokenLength) == 0))
+    {
+        LOGI("token is same. received request of it's own. skip.. ");
+        return;
+    }
+
+    CAResult_t res = get_remote_address(object->transportType, object->addressInfo);
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    LOGI("##########received request from remote device #############");
+    if (object->resourceUri)
+    {
+        LOGI("Uri: %s", object->resourceUri);
+    }
+    LOGI("Remote Address: %s", g_remoteAddress);
+    LOGI("Data: %s", requestInfo->info.payload);
+    LOGI("Token: %s", requestInfo->info.token);
+    LOGI("Code: %d", requestInfo->method);
+    LOGI("MessageType: %d", requestInfo->info.type);
+
+    if (NULL != g_responseListenerObject)
+    {
+        callback("received request from remote device", "#######");
+        char *cloneUri = NULL;
+        uint32_t len = 0;
+
+        if (NULL != object->resourceUri)
+        {
+            len = strlen(object->resourceUri);
+            cloneUri = (char *) malloc(sizeof(char) * (len + 1));
+
+            if (NULL == cloneUri)
+            {
+                LOGE("cloneUri Out of memory");
+                free(g_remoteAddress);
+                return;
+            }
+
+            memcpy(cloneUri, object->resourceUri, len + 1);
+            callback("Uri: ", cloneUri);
+        }
+
+        len = strlen(g_remoteAddress);
+        char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
+
+        if (NULL == cloneRemoteAddress)
+        {
+            LOGE("cloneRemoteAddress Out of memory");
+            free(g_remoteAddress);
+            free(cloneUri);
+            return;
+        }
+
+        memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
+
+        callback("Remote Address: ", cloneRemoteAddress);
+        free(cloneRemoteAddress);
+        free(g_remoteAddress);
+
+        //clone g_clientEndpoint
+        g_clientEndpoint = (CARemoteEndpoint_t *) malloc(sizeof(CARemoteEndpoint_t));
+        if (NULL == g_clientEndpoint)
+        {
+            LOGE("g_clientEndpoint Out of memory");
+            free(cloneUri);
+            return;
+        }
+        memcpy(g_clientEndpoint, object, sizeof(CARemoteEndpoint_t));
+
+        if (NULL != cloneUri)
+        {
+            len = strlen(cloneUri);
+            g_clientEndpoint->resourceUri = (char *) malloc(sizeof(char) * (len + 1));
+            if (NULL == g_clientEndpoint)
+            {
+                LOGE("g_clientEndpoint->resourceUri Out of memory");
+                free(g_clientEndpoint);
+                free(cloneUri);
+                return;
+            }
+            memcpy(g_clientEndpoint->resourceUri, cloneUri, len + 1);
+            free(cloneUri);
+        }
+        //clone g_clientToken
+        len = requestInfo->info.tokenLength;
+
+        g_clientToken = (char *) malloc(sizeof(char) * len);
+        if (NULL == g_clientToken)
+        {
+            LOGE("g_clientToken Out of memory");
+            free(g_clientEndpoint->resourceUri);
+            free(g_clientEndpoint);
+            return;
+        }
+
+        if (NULL != requestInfo->info.token)
+        {
+            memcpy(g_clientToken, requestInfo->info.token, len);
+            g_clientTokenLength = len;
+
+        }
+
+        //clone g_clientMsgId
+        g_clientMsgId = requestInfo->info.messageId;
+
+        if (NULL != requestInfo->info.payload)
+        {
+            len = strlen(requestInfo->info.payload);
+            char *clonePayload = (char *) malloc(sizeof(char) * (len + 1));
+
+            if (NULL == clonePayload)
+            {
+                LOGE("clonePayload Out of memory");
+                free(g_clientEndpoint->resourceUri);
+                free(g_clientEndpoint);
+                return;
+            }
+
+            memcpy(clonePayload, requestInfo->info.payload, len + 1);
+
+            callback("Data: ", clonePayload);
+            free(clonePayload);
+        }
+    }
+
+    if (requestInfo->info.options)
+    {
+        uint32_t len = requestInfo->info.numOptions;
+        uint32_t i;
+
+        LOGI("Option count: %d", requestInfo->info.numOptions);
+
+        for (i = 0; i < len; i++)
+        {
+            LOGI("Option %d", i + 1);
+            LOGI("ID : %d", requestInfo->info.options[i].optionID);
+            LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
+                 requestInfo->info.options[i].optionData);
+
+            if (NULL != g_responseListenerObject)
+            {
+                char optionInfo[OPTION_INFO_LENGTH] = { 0, };
+                sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
+                        requestInfo->info.options[i].optionID,
+                        requestInfo->info.options[i].optionLength);
+
+                callback("Option info: ", optionInfo);
+
+                uint32_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
+                char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
+                if (NULL == cloneOptionData)
+                {
+                    LOGE("cloneOptionData Out of memory");
+                    free(g_clientEndpoint->resourceUri);
+                    free(g_clientEndpoint);
+                    return;
+                }
+
+                memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
+                       optionDataLen + 1);
+
+                callback("Option Data: ", cloneOptionData);
+                free(cloneOptionData);
+            }
+        }
+    }
+    LOGI("############################################################");
+
+    //Check if this has secure communication information
+    if (requestInfo->info.payload && CA_IPV4 == object->transportType)
+    {
+        uint32_t securePort = get_secure_information(requestInfo->info.payload);
+        if (0 < securePort) //Set the remote endpoint secure details and send response
+        {
+            LOGI("This is secure resource...");
+            char *uri = NULL;
+            uint32_t length = 0;
+
+            length = sizeof(SECURE_COAPS_PREFIX) - 1; //length of "coaps://"
+            // length of "ipaddress:port"
+            length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
+            length += strlen(object->resourceUri) + 1;
+
+            uri = calloc(1, sizeof(char) * length);
+            if (!uri)
+            {
+                LOGE("Failed to create new uri");
+                free(uri);
+                return;
+            }
+            sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
+                    securePort, object->resourceUri);
+
+            CARemoteEndpoint_t *endpoint = NULL;
+            if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
+            {
+                LOGE("Failed to create duplicate of remote endpoint!");
+                free(uri);
+                return;
+            }
+            endpoint->isSecured = true;
+            object = endpoint;
+
+            free(uri);
+        }
+    }
+}
+
+void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo)
+{
+
+    CAResult_t res = get_remote_address(object->transportType, object->addressInfo);
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    LOGI("##########Received response from remote device #############");
+    LOGI("Uri: %s", object->resourceUri);
+    LOGI("Remote Address: %s", g_remoteAddress);
+    LOGI("response result: %d", responseInfo->result);
+    LOGI("Data: %s", responseInfo->info.payload);
+    LOGI("Token: %s", responseInfo->info.token);
+    LOGI("MessageType: %d", responseInfo->info.type);
+
+    if (NULL != g_responseListenerObject)
+    {
+        uint32_t len = 0;
+
+        if (NULL != object->resourceUri)
+        {
+            len = strlen(object->resourceUri);
+            char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
+
+            if (NULL == cloneUri)
+            {
+                LOGE("cloneUri Out of memory");
+                free(g_remoteAddress);
+                return;
+            }
+
+            memcpy(cloneUri, object->resourceUri, len + 1);
+
+            callback("Uri: ", cloneUri);
+            free(cloneUri);
+        }
+
+        len = strlen(g_remoteAddress);
+        char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
+
+        if (NULL == cloneRemoteAddress)
+        {
+            LOGE("cloneRemoteAddress Out of memory");
+            free(g_remoteAddress);
+            return;
+        }
+
+        memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
+
+        callback("Remote Address: ", cloneRemoteAddress);
+        free(cloneRemoteAddress);
+        free(g_remoteAddress);
+
+        if (NULL != responseInfo->info.payload)
+        {
+            len = strlen(responseInfo->info.payload);
+            char *clonePayload = (char *) malloc(sizeof(char) * (len + 1));
+
+            if (NULL == clonePayload)
+            {
+                LOGE("clonePayload Out of memory");
+                return;
+            }
+
+            memcpy(clonePayload, responseInfo->info.payload, len + 1);
+
+            callback("Data: ", clonePayload);
+            free(clonePayload);
+        }
+    }
+
+    if (responseInfo->info.options)
+    {
+        uint32_t len = responseInfo->info.numOptions;
+        uint32_t i;
+        for (i = 0; i < len; i++)
+        {
+            LOGI("Option %d", i + 1);
+            LOGI("ID : %d", responseInfo->info.options[i].optionID);
+            LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
+                 responseInfo->info.options[i].optionData);
+
+            if (NULL != g_responseListenerObject)
+            {
+                char optionInfo[OPTION_INFO_LENGTH] = { 0, };
+                sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
+                        responseInfo->info.options[i].optionID,
+                        responseInfo->info.options[i].optionLength);
+
+                callback("Option info: ", optionInfo);
+
+                uint32_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
+                char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
+                if (NULL == cloneOptionData)
+                {
+                    LOGE("cloneOptionData Out of memory");
+                    return;
+                }
+                memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
+                       optionDataLen + 1);
+                callback("Option Data: ", cloneOptionData);
+                free(cloneOptionData);
+            }
+        }
+    }
+    LOGI("############################################################");
+
+    //Check if this has secure communication information
+    if (responseInfo->info.payload && CA_IPV4 == object->transportType)
+    {
+        uint32_t securePort = get_secure_information(responseInfo->info.payload);
+        if (0 < securePort) //Set the remote endpoint secure details and send response
+        {
+            LOGI("This is secure resource...");
+        }
+    }
+}
+
+void get_resource_uri(const char *URI, char *resourceURI, uint32_t length)
+{
+    const char *startPos = URI;
+    const char *temp = NULL;
+    if (NULL != (temp = strstr(URI, "://")))
+    {
+        startPos = strchr(temp + 3, '/');
+        if (!startPos)
+        {
+            LOGE("Resource URI is missing");
+            return;
+        }
+    }
+
+    const char *endPos = strchr(startPos, '?');
+    if (!endPos)
+    {
+        endPos = URI + strlen(URI);
+    }
+    --endPos;
+
+    if (endPos - startPos <= length)
+    {
+        memcpy(resourceURI, startPos + 1, endPos - startPos);
+    }
+
+    LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
+}
+
+uint32_t get_secure_information(CAPayload_t payLoad)
+{
+    LOGI("entering get_secure_information");
+
+    if (!payLoad)
+    {
+        LOGE("Payload is NULL");
+        return -1;
+    }
+
+    const char *subString = NULL;
+    if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
+    {
+        LOGE("This is not secure resource");
+        return -1;
+    }
+
+    if (NULL == (subString = strstr(payLoad, "\"port\":")))
+    {
+        LOGE("This secure resource does not have port information");
+        return -1;
+    }
+
+    const char *startPos = strstr(subString, ":");
+    if (!startPos)
+    {
+        LOGE("Parsing failed !");
+        return -1;
+    }
+
+    const char *endPos = strstr(startPos, "}");
+    if (!endPos)
+    {
+        LOGE("Parsing failed !");
+        return -1;
+    }
+
+    char portStr[6] = { 0 };
+    memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
+
+    LOGI("secured port is: %s", portStr);
+    return atoi(portStr);
+}
+
+CAResult_t get_network_type(uint32_t selectedNetwork)
+{
+
+    uint32_t number = selectedNetwork;
+
+    if (!(number & 0xf))
+    {
+        return CA_NOT_SUPPORTED;
+    }
+    if (number & CA_IPV4)
+    {
+        g_selectedNwType = CA_IPV4;
+        return CA_STATUS_OK;
+    }
+    if (number & CA_EDR)
+    {
+        g_selectedNwType = CA_EDR;
+        return CA_STATUS_OK;
+    }
+    if (number & CA_LE)
+    {
+        g_selectedNwType = CA_LE;
+        return CA_STATUS_OK;
+    }
+
+    return CA_NOT_SUPPORTED;
+}
+
+void callback(char *subject, char *receivedData)
+{
+    JNIEnv* env = NULL;
+    uint32_t status = (*g_jvm)->GetEnv(g_jvm, (void **) &env, JNI_VERSION_1_6);
+    uint32_t res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+    jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
+    jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
+                                        "(Ljava/lang/String;Ljava/lang/String;)V");
+
+    jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
+    jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
+    (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
+
+}
+
+CAResult_t get_remote_address(CATransportType_t transportType, CAAddress_t addressInfo)
+{
+
+    uint32_t len = 0;
+    if (CA_IPV4 == transportType)
+    {
+        len = strlen(addressInfo.IP.ipAddress);
+        g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
+
+        if (NULL == g_remoteAddress)
+        {
+            LOGE("g_remoteAddress Out of memory");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        memcpy(g_remoteAddress, addressInfo.IP.ipAddress, len + 1);
+    }
+
+    else if (CA_EDR == transportType)
+    {
+        len = strlen(addressInfo.BT.btMacAddress);
+        g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
+
+        if (NULL == g_remoteAddress)
+        {
+            LOGE("g_remoteAddress Out of memory");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        memcpy(g_remoteAddress, addressInfo.BT.btMacAddress, len + 1);
+    }
+
+    else if (CA_LE == transportType)
+    {
+        len = strlen(addressInfo.LE.leMacAddress);
+        g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
+
+        if (NULL == g_remoteAddress)
+        {
+            LOGE("g_remoteAddress Out of memory");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        memcpy(g_remoteAddress, addressInfo.LE.leMacAddress, len + 1);
+    }
+
+    return CA_STATUS_OK;
+}
diff --git a/resource/csdk/connectivity/samples/android/sample_service/jni/org_iotivity_service_RMInterface.h b/resource/csdk/connectivity/samples/android/sample_service/jni/org_iotivity_service_RMInterface.h
new file mode 100644 (file)
index 0000000..8c6b61f
--- /dev/null
@@ -0,0 +1,134 @@
+#include <jni.h>
+/* Header for class org_iotivity_service_RMInterface */
+
+#ifndef _Included_org_iotivity_service_RMInterface
+#define _Included_org_iotivity_service_RMInterface
+#ifdef __cplusplus
+extern "C" {
+#endif
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_setNativeResponseListener
+  (JNIEnv *, jobject, jobject);
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMInitialize
+ * Signature: (Landroid/content/Context;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMInitialize
+  (JNIEnv *, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMTerminate
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMTerminate
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMStartListeningServer
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMStartListeningServer
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMStartDiscoveryServer
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMStartDiscoveryServer
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMRegisterHandler
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMRegisterHandler
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMFindResource
+ * Signature: (Ljava/lang/String;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMFindResource
+  (JNIEnv *, jobject, jstring);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMSendRequest
+ * Signature: (Ljava/lang/String;Ljava/lang/String;III)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMSendRequest
+  (JNIEnv *, jobject, jstring, jstring, jint, jint, jint);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMSendReqestToAll
+ * Signature: (Ljava/lang/String;I)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMSendReqestToAll
+  (JNIEnv *, jobject, jstring, jint);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMSendResponse
+ * Signature: (IIII)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMSendResponse
+  (JNIEnv *, jobject, jint, jint, jint, jint);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMAdvertiseResource
+ * Signature: (Ljava/lang/String)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMAdvertiseResource
+  (JNIEnv *, jobject, jstring);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMSendNotification
+ * Signature: (Ljava/lang/String;Ljava/lang/String;IIII)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMSendNotification
+  (JNIEnv *, jobject, jstring, jstring, jint, jint, jint, jint);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMSelectNetwork
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMSelectNetwork
+  (JNIEnv *, jobject, jint);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMUnSelectNetwork
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMUnSelectNetwork
+  (JNIEnv *, jobject, jint);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMGetNetworkInfomation
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMGetNetworkInfomation
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_RMInterface
+ * Method:    RMHandleRequestResponse
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_service_RMInterface_RMHandleRequestResponse
+  (JNIEnv *, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/resource/csdk/connectivity/samples/android/sample_service/proguard-project.txt b/resource/csdk/connectivity/samples/android/sample_service/proguard-project.txt
new file mode 100644 (file)
index 0000000..c1ff32f
--- /dev/null
@@ -0,0 +1,21 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/project.properties b/resource/csdk/connectivity/samples/android/sample_service/project.properties
new file mode 100644 (file)
index 0000000..6e18427
--- /dev/null
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-21
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/layout/activity_main.xml b/resource/csdk/connectivity/samples/android/sample_service/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..25ce793
--- /dev/null
@@ -0,0 +1,364 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    tools:context="org.iotivity.service.MainActivity" >
+
+    <RelativeLayout
+        android:id="@+id/sample_service_layout"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:layout_alignParentTop="true"
+        android:background="#cccccc" >
+
+        <LinearLayout
+            android:id="@+id/layout_mode"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_alignParentTop="true"
+            android:orientation="horizontal" >
+
+            <TextView
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content" />
+
+            <TextView
+                android:id="@+id/tv_mode"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content" />
+        </LinearLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_network"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_mode"
+            android:orientation="horizontal" >
+
+            <TextView
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content" />
+
+            <TextView
+                android:id="@+id/tv_network"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_find_title"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_mode" >
+                        
+            <TextView
+                android:id="@+id/tv_find"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="[Find Resource]"
+                />
+
+         </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_find"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_find_title" >
+
+            <Button
+                android:id="@+id/btn_find_resource"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/find" />
+
+            <EditText
+                android:id="@+id/et_uri"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_centerVertical="true"
+                android:layout_toLeftOf="@id/btn_find_resource"
+                android:text="@string/uri" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_Response_Noti_title"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_mode" >
+
+            <TextView
+                android:id="@+id/tv_Response_Noti"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="[Send Response / Send Notification]"
+                />
+
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_request_setting_for_server"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_Response_Noti_title" >
+
+            <Button
+                android:id="@+id/btn_Request_setting_for_server"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/request_setting" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_notify"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_request_setting_for_server" >
+
+            <EditText
+                android:id="@+id/et_notification"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/notification" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_payload_server_ed"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_notify" >
+
+            <EditText
+                android:id="@+id/et_payload_data_for_server"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_centerVertical="true"
+                android:text="@string/payload_data_server" />
+
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_server_bt"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_payload_server_ed" >
+
+            <Button
+                android:id="@+id/btn_notify"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/notify" />
+
+            <Button
+                android:id="@+id/btn_sendresponse"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_toLeftOf="@id/btn_notify"
+                android:text="@string/sendresponse" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_advertise_title"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_server_bt" >
+
+            <TextView
+                android:id="@+id/tv_advertise"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="[Advertise Resource]"
+                />
+
+         </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_advertise_resource"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_advertise_title" >
+
+            <Button
+                android:id="@+id/btn_advertise"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/advertise" />
+
+            <EditText
+                android:id="@+id/et_uri_advertise"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_toLeftOf="@id/btn_advertise"
+                android:text="@string/uri" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_request_title"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_find" >
+
+            <TextView
+                android:id="@+id/tv_request"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="[Send Request]" />
+
+         </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_request"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_request_title" >
+
+            <EditText
+                android:id="@+id/et_req_data"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_centerVertical="true"
+                android:text="@string/req_data" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_payload_client_ed"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_request" >
+
+            <EditText
+                android:id="@+id/et_payload_data"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_centerVertical="true"
+                android:text="@string/payload_data_client" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_request_setting_for_client"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_payload_client_ed" >
+
+            <Button
+                android:id="@+id/btn_Request"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/request" />
+
+            <Button
+                android:id="@+id/btn_Request_setting_for_client"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_toLeftOf="@id/btn_Request"
+                android:text="@string/request_setting" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_request_to_all_title"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_request_setting_for_client" >
+
+            <TextView
+                android:id="@+id/tv_request_to_all"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content" 
+                android:text="[Send Request to All]"
+                />
+
+         </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_request_to_all"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_request_to_all_title" >
+
+            <EditText
+                android:id="@+id/et_req_to_all_data"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_centerVertical="true"
+                android:text="@string/uri" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_request_to_all_setting_for_client"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_request_to_all" >
+
+            <Button
+                android:id="@+id/btn_request_to_all"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/request_to_all" />
+
+            <Button
+                android:id="@+id/btn_request_to_all_setting_for_client"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_toLeftOf="@id/btn_request_to_all"
+                android:text="@string/request_setting" />
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_handle_title"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_request_to_all_setting_for_client" >
+
+            <TextView
+                android:id="@+id/tv_handle"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="[Handle Reqeust,Response data / Get NetworkInfo]"/>
+        </RelativeLayout>
+
+        <RelativeLayout
+            android:id="@+id/layout_receive"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_below="@id/layout_handle_title" >
+
+            <Button
+                android:id="@+id/btn_get_network_info"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentRight="true"
+                android:text="@string/get_network_info" />
+            <Button
+                android:id="@+id/btn_receive"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:layout_toLeftOf="@id/btn_get_network_info"
+                android:text="@string/receive" />
+        </RelativeLayout>
+    </RelativeLayout>
+
+    <ScrollView
+        android:id="@+id/sv_result_scoll"
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:layout_below="@id/sample_service_layout"
+        android:layout_marginTop="10pt" >
+
+        <TextView
+            android:id="@+id/tv_result"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content" />
+    </ScrollView>
+
+</RelativeLayout>
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/menu/main.xml b/resource/csdk/connectivity/samples/android/sample_service/res/menu/main.xml
new file mode 100644 (file)
index 0000000..ae3d56a
--- /dev/null
@@ -0,0 +1,12 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    tools:context="org.iotivity.sample_service.MainActivity" >
+
+    <item
+        android:id="@+id/action_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never"
+        android:title="@string/action_settings"/>
+
+</menu>
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/values-v11/styles.xml b/resource/csdk/connectivity/samples/android/sample_service/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..3df0c14
--- /dev/null
@@ -0,0 +1,12 @@
+<resources>
+
+    <!--
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+        <!-- API 11 theme customizations can go here. -->
+    </style>
+
+</resources>
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/values-v14/styles.xml b/resource/csdk/connectivity/samples/android/sample_service/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..13d7045
--- /dev/null
@@ -0,0 +1,13 @@
+<resources>
+
+    <!--
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+        <!-- API 14 theme customizations can go here. -->
+    </style>
+
+</resources>
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/values-w820dp/dimens.xml b/resource/csdk/connectivity/samples/android/sample_service/res/values-w820dp/dimens.xml
new file mode 100644 (file)
index 0000000..efaa062
--- /dev/null
@@ -0,0 +1,11 @@
+<resources>
+
+    <!--
+         Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
+    -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+
+</resources>
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/values/dimens.xml b/resource/csdk/connectivity/samples/android/sample_service/res/values/dimens.xml
new file mode 100644 (file)
index 0000000..6ed10f5
--- /dev/null
@@ -0,0 +1,8 @@
+<resources>
+
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/values/strings.xml b/resource/csdk/connectivity/samples/android/sample_service/res/values/strings.xml
new file mode 100644 (file)
index 0000000..f75b6be
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">CA Android Sample</string>
+    <string name="find">Find</string>
+    <string name="sendresponse">Send Response</string>
+    <string name="notify">Send Notification</string>
+    <string name="advertise">Advertise</string>
+    <string name="request_setting">Request Setting</string>
+    <string name="request">Request</string>
+    <string name="request_to_all">Request to All</string>
+    <string name="response">Response</string>
+    <string name="uri">/a/light</string>
+    <string name="notification"></string>
+    <string name="req_data"></string>
+    <string name="resp_data">resourceUri/response</string>
+    <string name="get_network_info">Network Info</string>
+    <string name="receive">Receive</string>
+    <string name="received">Received Message</string>
+    <string name="action_settings">Settings</string>
+    <string name="payload_data_client">PayloadData</string>
+    <string name="payload_data_server">PayloadData</string>
+</resources>
\ No newline at end of file
diff --git a/resource/csdk/connectivity/samples/android/sample_service/res/values/styles.xml b/resource/csdk/connectivity/samples/android/sample_service/res/values/styles.xml
new file mode 100644 (file)
index 0000000..d77df4e
--- /dev/null
@@ -0,0 +1,21 @@
+<resources>
+
+    <!--
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!--
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        -->
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+    </style>
+
+</resources>
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/ca/CaIpInterface.java b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/ca/CaIpInterface.java
new file mode 100644 (file)
index 0000000..43d0ace
--- /dev/null
@@ -0,0 +1,70 @@
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * //      http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+package org.iotivity.ca;\r
+\r
+import android.content.BroadcastReceiver;\r
+import android.content.Context;\r
+import android.content.Intent;\r
+import android.content.IntentFilter;\r
+import android.net.ConnectivityManager;\r
+import android.net.NetworkInfo;\r
+import android.net.wifi.WifiManager;\r
+\r
+public class CaIpInterface {\r
+    private static Context mContext;\r
+\r
+    private CaIpInterface(Context context) {\r
+        mContext = context;\r
+        registerIpStateReceiver();\r
+    }\r
+\r
+    private void registerIpStateReceiver() {\r
+        IntentFilter intentFilter = new IntentFilter();\r
+        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);\r
+        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\r
+\r
+        mContext.registerReceiver(mReceiver, intentFilter);\r
+    }\r
+\r
+    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,\r
+                    WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {\r
+                stateDisabled();\r
+            } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {\r
+                ConnectivityManager manager = (ConnectivityManager)\r
+                        mContext.getSystemService(Context.CONNECTIVITY_SERVICE);\r
+                NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\r
+\r
+                if(nwInfo.isConnected()) {\r
+                    stateEnabled();\r
+                }\r
+            }\r
+        }\r
+    };\r
+\r
+    private native static void stateEnabled();\r
+\r
+    private native static void stateDisabled();\r
+}
\ No newline at end of file
diff --git a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/CALeInterface.java b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/CALeInterface.java
new file mode 100644 (file)
index 0000000..ccc24cb
--- /dev/null
@@ -0,0 +1,343 @@
+package org.iotivity.jar;
+
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGatt;
+import android.bluetooth.BluetoothGattCallback;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattDescriptor;
+import android.bluetooth.BluetoothGattServerCallback;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.le.AdvertiseCallback;
+import android.bluetooth.le.AdvertiseSettings;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.util.Log;
+
+public class CALeInterface {
+
+    public CALeInterface(Context context) {
+
+        CARegisterLeScanCallback(mLeScanCallback);
+        CARegisterLeGattCallback(mGattCallback);
+        CARegisterLeGattServerCallback(mGattServerCallback);
+        CARegisterBluetoothLeAdvertiseCallback(mAdvertiseCallback);
+
+        registerIntentFilter(context);
+    }
+
+    public static void getLeScanCallback() {
+        CARegisterLeScanCallback(mLeScanCallback);
+    }
+
+    public static void getLeGattCallback() {
+        CARegisterLeGattCallback(mGattCallback);
+    }
+
+    public static void getLeGattServerCallback() {
+        CARegisterLeGattServerCallback(mGattServerCallback);
+    }
+
+    public static void getBluetoothLeAdvertiseCallback() {
+        CARegisterBluetoothLeAdvertiseCallback(mAdvertiseCallback);
+    }
+
+    public static IntentFilter registerIntentFilter(Context context) {
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
+        context.registerReceiver(mReceiver, filter);
+        return filter;
+    }
+
+    public native static void CARegisterLeScanCallback(
+            BluetoothAdapter.LeScanCallback callback);
+
+    public native static void CARegisterLeGattCallback(
+            BluetoothGattCallback callback);
+
+    public native static void CARegisterLeGattServerCallback(
+            BluetoothGattServerCallback callback);
+
+    public native static void CARegisterBluetoothLeAdvertiseCallback(
+            AdvertiseCallback callback);
+
+    // BluetoothAdapter.LeScanCallback
+    public native static void CALeScanCallback(BluetoothDevice device,
+            int rssi, byte[] scanRecord);
+
+    // BluetoothGattCallback
+    public native static void CALeGattConnectionStateChangeCallback(
+            BluetoothGatt gatt, int status, int newState);
+
+    public native static void CALeGattServicesDiscoveredCallback(
+            BluetoothGatt gatt, int status);
+
+    public native static void CALeGattCharacteristicReadCallback(
+            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
+            byte[] data, int status);
+
+    public native static void CALeGattCharacteristicWriteCallback(
+            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
+            byte[] data, int status);
+
+    public native static void CALeGattCharacteristicChangedCallback(
+            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
+            byte[] data);
+
+    public native static void CALeGattDescriptorReadCallback(
+            BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status);
+
+    public native static void CALeGattDescriptorWriteCallback(
+            BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status);
+
+    public native static void CALeGattReliableWriteCompletedCallback(
+            BluetoothGatt gatt, int status);
+
+    public native static void CALeGattReadRemoteRssiCallback(
+            BluetoothGatt gatt, int rssi, int status);
+
+    // BluetoothGattServerCallback
+    public native static void CALeGattServerConnectionStateChangeCallback(
+            BluetoothDevice device, int status, int newState);
+
+    public native static void CALeGattServerServiceAddedCallback(int status,
+            BluetoothGattService service);
+
+    public native static void CALeGattServerCharacteristicReadRequestCallback(
+            BluetoothDevice device, int requestId, int offset,
+            BluetoothGattCharacteristic characteristic, byte[] data);
+
+    public native static void CALeGattServerCharacteristicWriteRequestCallback(
+            BluetoothDevice device, int requestId,
+            BluetoothGattCharacteristic characteristic, byte[] data,
+            boolean preparedWrite, boolean responseNeeded, int offset,
+            byte[] value);
+
+    public native static void CALeGattServerDescriptorReadRequestCallback(
+            BluetoothDevice device, int requestId, int offset,
+            BluetoothGattDescriptor descriptor);
+
+    public native static void CALeGattServerDescriptorWriteRequestCallback(
+            BluetoothDevice device, int requestId,
+            BluetoothGattDescriptor descriptor, boolean preparedWrite,
+            boolean responseNeeded, int offset, byte[] value);
+
+    public native static void CALeGattServerExecuteWriteCallback(
+            BluetoothDevice device, int requestId, boolean execute);
+
+    public native static void CALeGattServerNotificationSentCallback(
+            BluetoothDevice device, int status);
+
+    // AdvertiseCallback
+    public native static void CALeAdvertiseStartSuccessCallback(
+            AdvertiseSettings settingsInEffect);
+
+    public native static void CALeAdvertiseStartFailureCallback(int errorCode);
+
+    // Network Monitor
+    public native static void CALeStateChangedCallback(int state);
+
+    // Callback
+    private static BluetoothAdapter.LeScanCallback mLeScanCallback
+        = new BluetoothAdapter.LeScanCallback() {
+
+        @Override
+        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
+
+            try {
+                CALeScanCallback(device, rssi, scanRecord);
+            } catch(UnsatisfiedLinkError e) {
+
+            }
+        }
+    };
+
+    private static final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
+
+        @Override
+        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
+            super.onConnectionStateChange(gatt, status, newState);
+
+            CALeGattConnectionStateChangeCallback(gatt, status, newState);
+        }
+
+        @Override
+        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+            super.onServicesDiscovered(gatt, status);
+
+            CALeGattServicesDiscoveredCallback(gatt, status);
+        }
+
+        @Override
+        public void onCharacteristicRead(BluetoothGatt gatt,
+                BluetoothGattCharacteristic characteristic, int status) {
+            super.onCharacteristicRead(gatt, characteristic, status);
+
+            CALeGattCharacteristicReadCallback(gatt, characteristic,
+                    characteristic.getValue(), status);
+        }
+
+        @Override
+        public void onCharacteristicWrite(BluetoothGatt gatt,
+                BluetoothGattCharacteristic characteristic, int status) {
+            super.onCharacteristicWrite(gatt, characteristic, status);
+
+            CALeGattCharacteristicWriteCallback(gatt, characteristic,
+                    characteristic.getValue(), status);
+        }
+
+        @Override
+        public void onCharacteristicChanged(BluetoothGatt gatt,
+                BluetoothGattCharacteristic characteristic) {
+            super.onCharacteristicChanged(gatt, characteristic);
+
+            CALeGattCharacteristicChangedCallback(gatt, characteristic,
+                    characteristic.getValue());
+        }
+
+        @Override
+        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
+                int status) {
+            super.onDescriptorRead(gatt, descriptor, status);
+
+            CALeGattDescriptorReadCallback(gatt, descriptor, status);
+        }
+
+        @Override
+        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
+                int status) {
+            super.onDescriptorWrite(gatt, descriptor, status);
+
+            CALeGattDescriptorWriteCallback(gatt, descriptor, status);
+        }
+
+        @Override
+        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
+            super.onReliableWriteCompleted(gatt, status);
+
+            CALeGattReliableWriteCompletedCallback(gatt, status);
+        }
+
+        @Override
+        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
+            super.onReadRemoteRssi(gatt, rssi, status);
+
+            CALeGattReadRemoteRssiCallback(gatt, rssi, status);
+        }
+    };
+
+    private static final BluetoothGattServerCallback mGattServerCallback
+        = new BluetoothGattServerCallback() {
+
+        @Override
+        public void onConnectionStateChange(BluetoothDevice device, int status,
+                int newState) {
+            super.onConnectionStateChange(device, status, newState);
+
+            CALeGattServerConnectionStateChangeCallback(device, status, newState);
+        }
+
+        @Override
+        public void onServiceAdded(int status, BluetoothGattService service) {
+            super.onServiceAdded(status, service);
+
+            CALeGattServerServiceAddedCallback(status, service);
+        }
+
+        @Override
+        public void onCharacteristicReadRequest(BluetoothDevice device,
+                int requestId, int offset,
+                BluetoothGattCharacteristic characteristic) {
+            super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
+
+            CALeGattServerCharacteristicReadRequestCallback(device, requestId, offset,
+                    characteristic, characteristic.getValue());
+        }
+
+        @Override
+        public void onCharacteristicWriteRequest(BluetoothDevice device,
+                int requestId, BluetoothGattCharacteristic characteristic,
+                boolean preparedWrite, boolean responseNeeded, int offset,
+                byte[] value) {
+            super.onCharacteristicWriteRequest(device, requestId, characteristic,
+                    preparedWrite, responseNeeded, offset, value);
+
+            CALeGattServerCharacteristicWriteRequestCallback(device, requestId, characteristic,
+                    value, preparedWrite, responseNeeded, offset, value);
+        }
+
+        @Override
+        public void onDescriptorReadRequest(BluetoothDevice device,
+                int requestId, int offset, BluetoothGattDescriptor descriptor) {
+            super.onDescriptorReadRequest(device, requestId, offset, descriptor);
+
+            CALeGattServerDescriptorReadRequestCallback(device, requestId, offset, descriptor);
+        }
+
+        @Override
+        public void onDescriptorWriteRequest(BluetoothDevice device,
+                int requestId, BluetoothGattDescriptor descriptor,
+                boolean preparedWrite, boolean responseNeeded, int offset,
+                byte[] value) {
+            super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite,
+                    responseNeeded, offset, value);
+
+            CALeGattServerDescriptorWriteRequestCallback(device, requestId, descriptor,
+                    preparedWrite, responseNeeded, offset, value);
+        }
+
+        @Override
+        public void onExecuteWrite(BluetoothDevice device, int requestId,
+                boolean execute) {
+            super.onExecuteWrite(device, requestId, execute);
+
+            CALeGattServerExecuteWriteCallback(device, requestId, execute);
+        }
+
+        @Override
+        public void onNotificationSent(BluetoothDevice device, int status) {
+            super.onNotificationSent(device, status);
+
+            CALeGattServerNotificationSentCallback(device, status);
+        }
+    };
+
+    private static final AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
+
+        @Override
+        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
+            super.onStartSuccess(settingsInEffect);
+
+            CALeAdvertiseStartSuccessCallback(settingsInEffect);
+        }
+
+        @Override
+        public void onStartFailure(int errorCode) {
+            super.onStartFailure(errorCode);
+
+            CALeAdvertiseStartFailureCallback(errorCode);
+        }
+    };
+
+    private static final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+
+            String action = intent.getAction();
+
+            if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
+
+                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
+                        BluetoothAdapter.ERROR);
+                // STATE_ON:12, STATE_OFF:10
+                if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF) {
+                    CALeStateChangedCallback(state);
+                }
+            }
+        }
+    };
+}
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/caipinterface.java b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/caipinterface.java
new file mode 100644 (file)
index 0000000..c6e5e78
--- /dev/null
@@ -0,0 +1,55 @@
+package org.iotivity.jar;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.net.wifi.WifiManager;
+import android.util.Log;
+
+public class caipinterface {
+
+    private static String TAG = "caipinterface";
+    private static Context mContext = null;
+
+    public caipinterface(Context context) {
+        Log.d(TAG, "caipinterface");
+        mContext = context;
+        registerIpStateReceiver();
+    }
+
+    private void registerIpStateReceiver() {
+
+        IntentFilter intentFilter = new IntentFilter();
+        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
+        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
+
+        mContext.registerReceiver(mReceiver, intentFilter);
+    }
+
+    private static BroadcastReceiver mReceiver = new BroadcastReceiver() {
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
+                WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {
+                CAIPStateDisabled();
+            } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
+                ConnectivityManager manager = (ConnectivityManager)
+                        mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
+                NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+
+                if(nwInfo.isConnected()) {
+                    CAIPStateEnabled();
+                }
+            }
+        }
+    };
+
+    public native static void CAIPStateEnabled();
+
+    public native static void CAIPStateDisabled();
+}
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/DLog.java b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/DLog.java
new file mode 100644 (file)
index 0000000..b8b3b34
--- /dev/null
@@ -0,0 +1,90 @@
+
+package org.iotivity.service;
+
+import android.os.Handler;
+import android.widget.TextView;
+
+public final class DLog {
+
+    private final static String MAIN_TAG = "Sample_Service";
+
+    private static TextView mLogView = null;
+
+    private static Handler mHandler = null;
+
+    public static void setTextView(Handler handler, TextView logView) {
+        mHandler = handler;
+        mLogView = logView;
+    }
+
+    private static void addLogText(final String msg) {
+
+        mHandler.post(new Runnable() {
+
+            @Override
+            public void run() {
+
+                if (mLogView == null)
+                    return;
+
+                StringBuilder builder = new StringBuilder(mLogView.getText());
+                // add front
+                builder.append(msg + "\n");
+
+                mLogView.setText(builder.toString());
+            }
+
+        });
+
+    }
+
+    public static final void v(String className, String msg) {
+        android.util.Log.v(MAIN_TAG, className + "." + msg);
+
+        if (mLogView != null) {
+            addLogText(msg);
+        }
+    }
+
+    public static final void d(String className, String msg) {
+        android.util.Log.d(MAIN_TAG, className + "." + msg);
+
+        if (mLogView != null) {
+            addLogText(msg);
+        }
+    }
+
+    public static final void i(String className, String msg) {
+        android.util.Log.i(MAIN_TAG, className + "." + msg);
+
+        if (mLogView != null) {
+            addLogText(msg);
+        }
+    }
+
+    public static final void w(String className, String msg) {
+        android.util.Log.w(MAIN_TAG, className + "." + msg);
+
+        if (mLogView != null) {
+            addLogText(msg);
+        }
+    }
+
+    public static final void w(String className, String msg, Exception ex) {
+        android.util.Log.w(MAIN_TAG, className + "." + msg + ":" + ex.getMessage());
+
+        if (mLogView != null) {
+            addLogText(msg);
+        }
+    }
+
+    public static final void w(String className, String msg, Error e) {
+        android.util.Log.w(MAIN_TAG, className + "." + msg + ":" + e.getMessage());
+
+        if (mLogView != null) {
+            addLogText(msg);
+        }
+    }
+
+}
+
diff --git a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/MainActivity.java b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/MainActivity.java
new file mode 100644 (file)
index 0000000..fc321cb
--- /dev/null
@@ -0,0 +1,806 @@
+package org.iotivity.service;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+
+import org.iotivity.sample_service.R;
+
+public class MainActivity extends Activity {
+
+    static RMInterface RM = new RMInterface();
+
+    private final static String TAG = "MainActivity";
+
+    private final CharSequence[] mNetworkCheckBoxItems = { Network.IPV4.name(),
+            Network.IPV6.name(), Network.EDR.name(), Network.LE.name()};
+
+    private final CharSequence[] mDTLSCheckBoxItems = { DTLS.UNSECURED.name(),
+            DTLS.SECURED.name() };
+
+    private final CharSequence[] mMsgTyleCheckBoxItems = { MsgType.CON.name(),
+            MsgType.NON.name(), MsgType.ACK.name(), MsgType.RESET.name() };
+
+    private final CharSequence[] mResponseResultCheckBoxItems = {
+            ResponseResult.CA_SUCCESS.name(), ResponseResult.CA_CREATED.name(),
+            ResponseResult.CA_DELETED.name(), ResponseResult.CA_EMPTY.name(),
+            ResponseResult.CA_BAD_REQ.name(), ResponseResult.CA_BAD_OPT.name(),
+            ResponseResult.CA_NOT_FOUND.name(),
+            ResponseResult.CA_INTERNAL_SERVER_ERROR.name(),
+            ResponseResult.CA_RETRANSMIT_TIMEOUT.name() };
+
+    private enum Mode {
+        SERVER, CLIENT, BOTH, UNKNOWN
+    };
+
+    private enum Network {
+        IPV4, IPV6, EDR, LE
+    };
+
+    private enum DTLS {
+        UNSECURED, SECURED
+    };
+
+    private enum MsgType {
+        CON, NON, ACK, RESET
+    };
+
+    private enum ResponseResult {
+        CA_SUCCESS, CA_CREATED, CA_DELETED, CA_EMPTY, CA_BAD_REQ, CA_BAD_OPT,
+        CA_NOT_FOUND, CA_INTERNAL_SERVER_ERROR, CA_RETRANSMIT_TIMEOUT
+    }
+
+    private boolean mCheckedItems[] = {
+            false, false, false, false
+    };
+
+    private int mSelectedItems[] = { 0, 0, 0, 0 };
+
+    private int mUnSelectedItems[] = { 0, 0, 0, 0 };
+
+    private Mode mCurrentMode = Mode.UNKNOWN;
+
+    private RelativeLayout mFindResourceLayout = null;
+
+    private RelativeLayout mSendNotificationLayout = null;
+
+    private RelativeLayout mSendRequestLayout = null;
+
+    private RelativeLayout mSendRequestToAllLayout = null;
+
+    private RelativeLayout mSendRequestSettingLayout = null;
+
+    private RelativeLayout mSendRequestToAllSettingLayout = null;
+
+    private RelativeLayout mSendResponseNotiSettingLayout = null;
+
+    private RelativeLayout mReceiveLayout = null;
+
+    private RelativeLayout mFindTitleLayout = null;
+
+    private RelativeLayout mRequestTitleLayout = null;
+
+    private RelativeLayout mRequestToAllTitleLayout = null;
+
+    private RelativeLayout mResponseNotificationTitleLayout = null;
+
+    private RelativeLayout mAdvertiseTitleLayout = null;
+
+    private RelativeLayout mHandleTitleLayout = null;
+
+    private RelativeLayout mPayLoadClientEditLayout = null;
+
+    private RelativeLayout mPayLoadServerEditLayout = null;
+
+    private RelativeLayout mAdvertiseResourceLayout = null;
+
+    private RelativeLayout mServerButtonLayout = null;
+
+    private TextView mMode_tv = null;
+
+    private TextView mNetwork_tv = null;
+
+    private EditText mUri_ed = null;
+
+    private EditText mNotification_ed = null;
+
+    private EditText mReqData_ed = null;
+
+    private EditText mReqToAllData_ed = null;
+
+    private EditText mPayload_ed = null;
+
+    private EditText mAdvertise_ed = null;
+
+    private Button mFind_btn = null;
+
+    private Button mNotify_btn = null;
+
+    private Button mAdvertiseResource_btn = null;
+
+    private Button mReqeust_btn = null;
+
+    private Button mReqeust_setting_btn = null;
+
+    private Button mReqeustToAll_btn = null;
+
+    private Button mReqeustToAll_setting_btn = null;
+
+    private Button mResponse_Notify_setting_btn = null;
+
+    private Button mResponse_btn = null;
+
+    private Button mGetNetworkInfo_btn = null;
+
+    private Button mRecv_btn = null;
+
+    private Handler mLogHandler = null;
+
+    /**
+     * Defined ConnectivityType in cacommon.c
+     *
+     * CA_IPV4 = (1 << 0) CA_IPV6 = (1 << 1) CA_EDR = (1 << 2) CA_LE = (1 << 3)
+     */
+    private int CA_IPV4 = (1 << 0);
+    private int CA_IPV6 = (1 << 1);
+    private int CA_EDR = (1 << 2);
+    private int CA_LE = (1 << 3);
+    private int isSecured = 0;
+    private int msgType = 1;
+    private int responseValue = 0;
+    private int selectedNetworkType = -1;
+    private int selectedMsgType = 1;
+    private int selectedMsgSecured = 0;
+    private int selectedResponseValue = 0;
+    int selectedNetwork = -1;
+    int interestedNetwork = 0;
+    int uninterestedNetwork = 0;
+    private boolean isSendResponseSetting = false;
+    private boolean isSendRequestToAllSetting = false;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+
+        RM.setResponseListener(this);
+
+        mLogHandler = new Handler();
+        TextView logView = (TextView) findViewById(R.id.tv_result);
+        DLog.setTextView(mLogHandler, logView);
+
+        // Initialize UI
+        // common
+        mReceiveLayout = (RelativeLayout) findViewById(R.id.layout_receive);
+
+        // client
+        mSendRequestLayout = (RelativeLayout) findViewById(R.id.layout_request);
+        mSendRequestToAllLayout = (RelativeLayout) findViewById(R.id.layout_request_to_all);
+        mSendRequestSettingLayout = (RelativeLayout)
+                findViewById(R.id.layout_request_setting_for_client);
+        mSendRequestToAllSettingLayout = (RelativeLayout)
+                findViewById(R.id.layout_request_to_all_setting_for_client);
+        mFindResourceLayout = (RelativeLayout) findViewById(R.id.layout_find);
+        mFindTitleLayout = (RelativeLayout) findViewById(R.id.layout_find_title);
+        mRequestTitleLayout = (RelativeLayout) findViewById(R.id.layout_request_title);
+        mRequestToAllTitleLayout = (RelativeLayout) findViewById(R.id.layout_request_to_all_title);
+        mHandleTitleLayout = (RelativeLayout) findViewById(R.id.layout_handle_title);
+        mPayLoadClientEditLayout = (RelativeLayout) findViewById(R.id.layout_payload_client_ed);
+
+        // server
+        mSendNotificationLayout = (RelativeLayout) findViewById(R.id.layout_notify);
+        mPayLoadServerEditLayout = (RelativeLayout)
+                findViewById(R.id.layout_payload_server_ed);
+        mSendResponseNotiSettingLayout = (RelativeLayout)
+                findViewById(R.id.layout_request_setting_for_server);
+        mServerButtonLayout = (RelativeLayout) findViewById(R.id.layout_server_bt);
+        mResponseNotificationTitleLayout = (RelativeLayout)
+                findViewById(R.id.layout_Response_Noti_title);
+        mAdvertiseTitleLayout = (RelativeLayout) findViewById(R.id.layout_advertise_title);
+        mAdvertiseResourceLayout = (RelativeLayout) findViewById(R.id.layout_advertise_resource);
+
+        mMode_tv = (TextView) findViewById(R.id.tv_mode);
+        mNetwork_tv = (TextView) findViewById(R.id.tv_network);
+
+        mUri_ed = (EditText) findViewById(R.id.et_uri);
+        mNotification_ed = (EditText) findViewById(R.id.et_notification);
+        mReqData_ed = (EditText) findViewById(R.id.et_req_data);
+        mReqToAllData_ed = (EditText) findViewById(R.id.et_req_to_all_data);
+        mPayload_ed = (EditText) findViewById(R.id.et_payload_data_for_server);
+        mAdvertise_ed = (EditText) findViewById(R.id.et_uri_advertise);
+
+        mFind_btn = (Button) findViewById(R.id.btn_find_resource);
+        mResponse_btn = (Button) findViewById(R.id.btn_sendresponse);
+        mNotify_btn = (Button) findViewById(R.id.btn_notify);
+        mAdvertiseResource_btn = (Button) findViewById(R.id.btn_advertise);
+        mReqeust_btn = (Button) findViewById(R.id.btn_Request);
+        mReqeust_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_client);
+        mReqeustToAll_btn = (Button) findViewById(R.id.btn_request_to_all);
+        mReqeustToAll_setting_btn = (Button)
+                findViewById(R.id.btn_request_to_all_setting_for_client);
+        mResponse_Notify_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_server);
+        mGetNetworkInfo_btn = (Button) findViewById(R.id.btn_get_network_info);
+        mRecv_btn = (Button) findViewById(R.id.btn_receive);
+
+        mFind_btn.setOnClickListener(mFindResourceHandler);
+        mResponse_btn.setOnClickListener(mSendResponseHandler);
+        mNotify_btn.setOnClickListener(mNotifyHandler);
+        mAdvertiseResource_btn.setOnClickListener(mAdvertiseResourceHandler);
+        mReqeust_btn.setOnClickListener(mSendRequestHandler);
+        mReqeust_setting_btn.setOnClickListener(mSendRequestSettingHandler);
+        mReqeustToAll_btn.setOnClickListener(mSendRequestToAllHandler);
+        mReqeustToAll_setting_btn.setOnClickListener(mSendRequestToAllSettingHandler);
+        mResponse_Notify_setting_btn
+                .setOnClickListener(mSendResponseNotiSettingHandler);
+        mRecv_btn.setOnClickListener(mResponseHandler);
+        mGetNetworkInfo_btn.setOnClickListener(mGetNetworkInfoHandler);
+
+        showSelectModeView();
+
+        // Initialize Connectivity Abstraction
+        RM.RMInitialize(getApplicationContext());
+
+        // set handler
+        RM.RMRegisterHandler();
+    }
+
+    private void showSelectModeView() {
+
+        mFindResourceLayout.setVisibility(View.INVISIBLE);
+        mSendNotificationLayout.setVisibility(View.INVISIBLE);
+        mSendRequestLayout.setVisibility(View.INVISIBLE);
+        mSendRequestToAllLayout.setVisibility(View.INVISIBLE);
+        mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
+        mSendRequestToAllSettingLayout.setVisibility(View.INVISIBLE);
+        mReceiveLayout.setVisibility(View.INVISIBLE);
+        mFindTitleLayout.setVisibility(View.INVISIBLE);
+        mRequestTitleLayout.setVisibility(View.INVISIBLE);
+        mRequestToAllTitleLayout.setVisibility(View.INVISIBLE);
+        mHandleTitleLayout.setVisibility(View.INVISIBLE);
+        mPayLoadClientEditLayout.setVisibility(View.INVISIBLE);
+        mPayLoadServerEditLayout.setVisibility(View.INVISIBLE);
+        mServerButtonLayout.setVisibility(View.INVISIBLE);
+        mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
+        mAdvertiseTitleLayout.setVisibility(View.INVISIBLE);
+        mAdvertiseResourceLayout.setVisibility(View.INVISIBLE);
+        mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
+
+        mMode_tv.setText("Select Mode (Server or Client)");
+    }
+
+    private void showNetworkView() {
+
+        mNetwork_tv.setText("Select Network Type");
+    }
+
+    private void showModeView() {
+
+        if (mCurrentMode == Mode.SERVER) {
+
+            mFindResourceLayout.setVisibility(View.INVISIBLE);
+            mSendNotificationLayout.setVisibility(View.VISIBLE);
+            mSendRequestLayout.setVisibility(View.INVISIBLE);
+            mSendRequestToAllLayout.setVisibility(View.INVISIBLE);
+            mSendRequestSettingLayout.setVisibility(View.INVISIBLE);
+            mSendRequestToAllSettingLayout.setVisibility(View.INVISIBLE);
+            mReceiveLayout.setVisibility(View.VISIBLE);
+
+            mFindTitleLayout.setVisibility(View.INVISIBLE);
+            mRequestTitleLayout.setVisibility(View.INVISIBLE);
+            mRequestToAllTitleLayout.setVisibility(View.INVISIBLE);
+            mHandleTitleLayout.setVisibility(View.VISIBLE);
+            mPayLoadClientEditLayout.setVisibility(View.INVISIBLE);
+
+            mPayLoadServerEditLayout.setVisibility(View.VISIBLE);
+            mServerButtonLayout.setVisibility(View.VISIBLE);
+
+            mResponseNotificationTitleLayout.setVisibility(View.VISIBLE);
+            mAdvertiseTitleLayout.setVisibility(View.VISIBLE);
+            mAdvertiseResourceLayout.setVisibility(View.VISIBLE);
+
+            mSendResponseNotiSettingLayout.setVisibility(View.VISIBLE);
+
+            mNetwork_tv.setText("");
+
+        } else if (mCurrentMode == Mode.CLIENT) {
+
+            mFindResourceLayout.setVisibility(View.VISIBLE);
+            mSendNotificationLayout.setVisibility(View.INVISIBLE);
+            mSendRequestLayout.setVisibility(View.VISIBLE);
+            mSendRequestToAllLayout.setVisibility(View.VISIBLE);
+            mSendRequestSettingLayout.setVisibility(View.VISIBLE);
+            mSendRequestToAllSettingLayout.setVisibility(View.VISIBLE);
+            mReceiveLayout.setVisibility(View.VISIBLE);
+
+            mFindTitleLayout.setVisibility(View.VISIBLE);
+            mRequestTitleLayout.setVisibility(View.VISIBLE);
+            mRequestToAllTitleLayout.setVisibility(View.VISIBLE);
+            mHandleTitleLayout.setVisibility(View.VISIBLE);
+            mPayLoadClientEditLayout.setVisibility(View.VISIBLE);
+
+            mPayLoadServerEditLayout.setVisibility(View.INVISIBLE);
+            mServerButtonLayout.setVisibility(View.INVISIBLE);
+
+            mResponseNotificationTitleLayout.setVisibility(View.INVISIBLE);
+            mAdvertiseTitleLayout.setVisibility(View.INVISIBLE);
+            mAdvertiseResourceLayout.setVisibility(View.INVISIBLE);
+
+            mSendResponseNotiSettingLayout.setVisibility(View.INVISIBLE);
+
+            mNetwork_tv.setText("");
+        }
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+
+        // Terminate Connectivity Abstraction
+        RM.RMTerminate();
+        android.os.Process.killProcess(android.os.Process.myPid());
+    }
+
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+
+        menu.add(0, 1, Menu.NONE, "Start Server");
+        menu.add(0, 2, Menu.NONE, "Start Client");
+        menu.add(0, 3, Menu.NONE, "Select Network");
+
+        return true;
+    }
+
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+
+        switch (item.getItemId()) {
+
+        case 1:
+
+            RM.RMStartListeningServer();
+
+            if (interestedNetwork == 0) {
+                mCurrentMode = Mode.SERVER;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showNetworkView();
+
+            } else {
+                mCurrentMode = Mode.SERVER;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showModeView();
+            }
+
+            break;
+
+        case 2:
+
+            RM.RMStartDiscoveryServer();
+
+            if (interestedNetwork == 0) {
+                mCurrentMode = Mode.CLIENT;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showNetworkView();
+
+            } else {
+                mCurrentMode = Mode.CLIENT;
+                mMode_tv.setText("MODE: " + mCurrentMode.toString());
+                showModeView();
+            }
+
+            break;
+
+        case 3:
+
+            checkInterestedNetwork("Select Network");
+
+            break;
+        }
+
+        return super.onOptionsItemSelected(item);
+    }
+
+    private OnClickListener mFindResourceHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+
+            DLog.v(TAG, "FindResource click");
+            RM.RMFindResource(mUri_ed.getText().toString());
+
+        }
+    };
+
+    private OnClickListener mSendResponseHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+
+            DLog.v(TAG, "SendResponse click");
+            if ( selectedNetwork != -1) {
+                RM.RMSendResponse(selectedNetwork, isSecured, msgType, responseValue);
+            }
+            else {
+                DLog.v(TAG, "Please Select Network Type");
+            }
+        }
+    };
+
+    private OnClickListener mNotifyHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+
+            DLog.v(TAG, "SendNotification click");
+            if ( selectedNetwork != -1) {
+                RM.RMSendNotification(mNotification_ed.getText().toString(),
+                    mPayload_ed.getText().toString(), selectedNetwork,
+                    isSecured, msgType, responseValue);
+            }
+            else {
+                DLog.v(TAG, "Please Select Network Type");
+            }
+        }
+    };
+
+    private OnClickListener mAdvertiseResourceHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+
+            DLog.v(TAG, "AdvertiseResource click");
+            RM.RMAdvertiseResource(mAdvertise_ed.getText().toString());
+        }
+    };
+
+    private OnClickListener mSendRequestHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+
+            DLog.v(TAG, "SendRequest click");
+            if ( selectedNetwork != -1) {
+                RM.RMSendRequest(mReqData_ed.getText().toString(), mPayload_ed
+                    .getText().toString(), selectedNetwork, isSecured, msgType);
+            }
+            else {
+                DLog.v(TAG, "Please Select Network Type");
+            }
+        }
+    };
+
+    private OnClickListener mSendRequestSettingHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+            checkSendNetworkType("Select Send Network Type");
+        }
+    };
+
+    private OnClickListener mSendRequestToAllHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+
+            DLog.v(TAG, "SendRequestToAll click");
+            if ( selectedNetwork != -1) {
+                RM.RMSendReqestToAll(mReqToAllData_ed.getText().toString(), selectedNetwork);
+            }
+            else {
+                DLog.v(TAG, "Please Select Network Type");
+            }
+        }
+    };
+
+    private OnClickListener mSendRequestToAllSettingHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+            isSendRequestToAllSetting = true;
+            checkSendNetworkType("Select Send Network Type");
+        }
+    };
+
+    private OnClickListener mSendResponseNotiSettingHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+            isSendResponseSetting = true;
+            checkSendNetworkType("Select Send Network Type");
+        }
+    };
+
+    private OnClickListener mGetNetworkInfoHandler = new OnClickListener() {
+        @Override
+        public void onClick(View v) {
+
+            RM.RMGetNetworkInfomation();
+        }
+    };
+
+    private OnClickListener mResponseHandler = new OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+
+            RM.RMHandleRequestResponse();
+        }
+    };
+
+    private void checkInterestedNetwork(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+        builder.setTitle(title)
+                .setMultiChoiceItems(mNetworkCheckBoxItems, mCheckedItems,
+                        new DialogInterface.OnMultiChoiceClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which, boolean isChecked) {
+
+                                if (isChecked) {
+
+                                    mSelectedItems[which] = 1;
+                                    mUnSelectedItems[which] = 0;
+
+                                } else if (mSelectedItems[which] == 1) {
+
+                                    mSelectedItems[which] = 0;
+                                    mUnSelectedItems[which] = 1;
+                                }
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        interestedNetwork = 0;
+
+                        for (int i = 0; i < mSelectedItems.length; i++) {
+                            if (mSelectedItems[i] == 1) {
+                                if(i != 1)
+                                    interestedNetwork |= (1 << i);
+                                else
+                                    checkNotSupportedTransport("Not Supported Transport");
+                            }
+                        }
+                        if(0 != interestedNetwork)
+                            RM.RMSelectNetwork(interestedNetwork);
+
+                        uninterestedNetwork = 0;
+
+                        for (int i = 0; i < mUnSelectedItems.length; i++) {
+                            if (mUnSelectedItems[i] == 1) {
+                                if (i != 1)
+                                    uninterestedNetwork |= (1 << i);
+                                else
+                                    checkNotSupportedTransport("Not Supported Transport");
+                                mUnSelectedItems[i] = 0;
+                            }
+                        }
+                        if(0 != uninterestedNetwork)
+                            RM.RMUnSelectNetwork(uninterestedNetwork);
+
+                    }
+                }).show();
+    }
+
+    private void checkNotSupportedTransport(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+        builder.setTitle(title).
+        setMessage("Selected Transport Not Supported")
+        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+            @Override
+            public void onClick(DialogInterface dialog, int which) {
+
+            }
+        }).show();
+    }
+
+    private void checkMsgSecured(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+
+        builder.setTitle(title)
+                .setSingleChoiceItems(mDTLSCheckBoxItems, selectedMsgSecured,
+                        new DialogInterface.OnClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which) {
+                                selectedMsgSecured = which;
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        if (selectedMsgSecured == DTLS.SECURED.ordinal()) {
+                            isSecured = 1;
+                            DLog.v(TAG, "Send secured message");
+
+                            mPayLoadClientEditLayout
+                                    .setVisibility(View.INVISIBLE);
+
+                            mPayLoadServerEditLayout
+                                    .setVisibility(View.INVISIBLE);
+
+                        } else if (selectedMsgSecured == DTLS.UNSECURED.ordinal()) {
+                            isSecured = 0;
+                            DLog.v(TAG, "Send unsecured message");
+
+                            if (mCurrentMode == Mode.SERVER) {
+                                mPayLoadServerEditLayout
+                                        .setVisibility(View.VISIBLE);
+                            } else if (mCurrentMode == Mode.CLIENT) {
+                                mPayLoadClientEditLayout
+                                        .setVisibility(View.VISIBLE);
+                            }
+                        }
+                        checkMsgType("Select Msg Type");
+                    }
+
+                }).show();
+    }
+
+    private void checkMsgType(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+        builder.setTitle(title)
+                .setSingleChoiceItems(mMsgTyleCheckBoxItems, selectedMsgType,
+                        new DialogInterface.OnClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which) {
+                                selectedMsgType = which;
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        if (selectedMsgType == MsgType.CON.ordinal()) {
+                            msgType = 0;
+                            DLog.v(TAG, "Message Type is CON");
+
+                        } else if (selectedMsgType == MsgType.NON.ordinal()) {
+                            msgType = 1;
+                            DLog.v(TAG, "Message Type is NON");
+                        } else if (selectedMsgType == MsgType.ACK.ordinal()) {
+                            msgType = 2;
+                            DLog.v(TAG, "Message Type is ACK");
+                        } else if (selectedMsgType == MsgType.RESET.ordinal()) {
+                            msgType = 3;
+                            DLog.v(TAG, "Message Type is RESET");
+                            }
+
+                        if (isSendResponseSetting == true && msgType != 3) {
+                            checkResponseResult("Select Value of Response Result");
+                            isSendResponseSetting = false;
+                        }
+                    }
+                }).show();
+    }
+
+    private void checkResponseResult(String title) {
+
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+        builder.setTitle(title)
+                .setSingleChoiceItems(mResponseResultCheckBoxItems, selectedResponseValue,
+                        new DialogInterface.OnClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which) {
+                                selectedResponseValue = which;
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        if (selectedResponseValue == ResponseResult.CA_SUCCESS.ordinal()) {
+                            responseValue = 200;
+                            DLog.v(TAG, "Response Value is CA_SUCCESS");
+                        } else if (selectedResponseValue == ResponseResult.CA_CREATED
+                                .ordinal()) {
+                            responseValue = 201;
+                            DLog.v(TAG, "Response Value is CA_CREATED");
+                        } else if (selectedResponseValue == ResponseResult.CA_DELETED
+                                .ordinal()) {
+                            responseValue = 202;
+                            DLog.v(TAG, "Response Value is CA_DELETED");
+                        } else if (selectedResponseValue == ResponseResult.CA_EMPTY
+                                .ordinal()) {
+                            responseValue = 0;
+                            DLog.v(TAG, "Response Value is CA_EMPTY");
+                        } else if (selectedResponseValue == ResponseResult.CA_BAD_REQ
+                                .ordinal()) {
+                            responseValue = 400;
+                            DLog.v(TAG, "Response Value is CA_BAD_REQ");
+                        } else if (selectedResponseValue == ResponseResult.CA_BAD_OPT
+                                .ordinal()) {
+                            responseValue = 402;
+                            DLog.v(TAG, "Response Value is CA_BAD_OPT");
+                        } else if (selectedResponseValue == ResponseResult.CA_NOT_FOUND
+                                .ordinal()) {
+                            responseValue = 404;
+                            DLog.v(TAG, "Response Value is CA_NOT_FOUND");
+                        } else if (selectedResponseValue ==
+                                ResponseResult.CA_INTERNAL_SERVER_ERROR
+                                .ordinal()) {
+                            responseValue = 500;
+                            DLog.v(TAG, "Response Value is CA_INTERNAL_SERVER_ERROR");
+                        } else if (selectedResponseValue == ResponseResult.CA_RETRANSMIT_TIMEOUT
+                                .ordinal()) {
+                            responseValue = 504;
+                            DLog.v(TAG, "Response Value is CA_RETRANSMIT_TIMEOUT");
+                        }
+                    }
+                }).show();
+    }
+
+    private void checkSendNetworkType(String title) {
+        selectedNetworkType = -1;
+        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
+
+        builder.setTitle(title)
+                .setSingleChoiceItems(mNetworkCheckBoxItems, -1,
+                        new DialogInterface.OnClickListener() {
+
+                            @Override
+                            public void onClick(DialogInterface dialog,
+                                    int which) {
+                                selectedNetworkType = which;
+                            }
+                        })
+                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+
+                        if (selectedNetworkType == Network.IPV4.ordinal()) {
+                            selectedNetwork = CA_IPV4;
+                            DLog.v(TAG, "Selected Network is CA_IPV4");
+                        } else if (selectedNetworkType == Network.EDR.ordinal()) {
+                            selectedNetwork = CA_EDR;
+                            DLog.v(TAG, "Selected Network is EDR");
+                        } else if (selectedNetworkType == Network.LE.ordinal()) {
+                            selectedNetwork = CA_LE;
+                            DLog.v(TAG, "Selected Network is LE");
+                        }
+                        else {
+                            DLog.v(TAG, "Selected Network is NULL");
+                            selectedNetwork = -1;
+                        }
+
+                        if (isSendRequestToAllSetting != true) {
+                            checkMsgSecured("Select DTLS Type");
+                        }
+                        isSendRequestToAllSetting = false;
+                    }
+                }).show();
+    }
+
+    public void OnResponseReceived(String subject, String receivedData) {
+        String callbackData = subject + receivedData;
+        DLog.v(TAG, callbackData);
+
+    }
+}
diff --git a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/RMInterface.java b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/service/RMInterface.java
new file mode 100644 (file)
index 0000000..b70c066
--- /dev/null
@@ -0,0 +1,60 @@
+package org.iotivity.service;
+
+import android.content.Context;
+
+public class RMInterface {
+
+    static {
+        // Load RI JNI interface
+        System.loadLibrary("RMInterface");
+    }
+
+    private org.iotivity.service.MainActivity mResponseListener = null;
+
+    public native void setNativeResponseListener(Object listener);
+
+    public native void RMInitialize(Context context);
+
+    public native void RMTerminate();
+
+    public native void RMStartListeningServer();
+
+    public native void RMStartDiscoveryServer();
+
+    public native void RMRegisterHandler();
+
+    public native void RMFindResource(String uri);
+
+    public native void RMSendRequest(String uri, String payload,
+            int selectedNetwork, int isSecured, int msgType);
+
+    public native void RMSendReqestToAll(String uri, int selectedNetwork);
+
+    public native void RMSendResponse(int selectedNetwork, int isSecured,
+            int msgType, int responseValue);
+
+    public native void RMAdvertiseResource(String advertiseResource);
+
+    public native void RMSendNotification(String uri, String payload,
+            int selectedNetwork, int isSecured, int msgType, int responseValue);
+
+    public native void RMSelectNetwork(int interestedNetwork);
+
+    public native void RMUnSelectNetwork(int uninterestedNetwork);
+
+    public native void RMGetNetworkInfomation();
+
+    public native void RMHandleRequestResponse();
+
+    public void setResponseListener(org.iotivity.service.MainActivity listener) {
+        mResponseListener = listener;
+        setNativeResponseListener(this);
+    }
+
+    private void OnResponseReceived(String subject, String receivedData) {
+        if (null != mResponseListener) {
+            mResponseListener.OnResponseReceived(subject, receivedData);
+        }
+    }
+
+}
diff --git a/resource/csdk/connectivity/samples/arduino/SConscript b/resource/csdk/connectivity/samples/arduino/SConscript
new file mode 100644 (file)
index 0000000..660cd72
--- /dev/null
@@ -0,0 +1,30 @@
+Import('env')
+
+sample_env= env.Clone()
+root_dir = './../../'
+
+sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+sample_env.PrependUnique(LIBS = ['connectivity_abstraction', 'coap'])
+
+sample_env.PrependUnique(CPPPATH = [root_dir + '/api/'])
+sample_env.AppendUnique(CPPPATH = [root_dir + '/inc/'])
+sample_env.AppendUnique(CPPPATH = [root_dir + '/lib/libcoap-4.1.1/'])
+sample_env.AppendUnique(CPPPATH = [root_dir + 'common/inc/'])
+
+if env.get('SHIELD') == 'WIFI':
+       sample_env.AppendUnique(CPPDEFINES = ['ARDUINOWIFI'])
+elif env.get('SHIELD') == 'ETH':
+       sample_env.AppendUnique(CPPDEFINES = ['ARDUINOETH'])
+
+sample_dir = './samples/arduino/'
+arduino_simplecs = sample_env.Program('CASample', 'casample.cpp')
+env.CreateBin('CASample')
+
+i_arduino_simplecs = sample_env.Install(env.get('BUILD_DIR'), arduino_simplecs)
+
+Alias('arduino_simplecs', i_arduino_simplecs)
+sample_env.Default('CASample.hex')
+
+if(sample_env['UPLOAD'] == True):
+       sample_env.Upload(env.get('BUILD_DIR') + '/samples/arduino/' + 'CASample.hex')
+
diff --git a/resource/csdk/connectivity/samples/arduino/casample.cpp b/resource/csdk/connectivity/samples/arduino/casample.cpp
new file mode 100644 (file)
index 0000000..f22eb1c
--- /dev/null
@@ -0,0 +1,841 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <ctype.h>
+#include <errno.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "cacommon.h"
+#include "cainterface.h"
+#include "Arduino.h"
+
+#ifdef ARDUINOWIFI
+#include "WiFi.h"
+#elif defined ARDUINOETH
+#include "Ethernet.h"
+#endif
+
+#include "oic_malloc.h"
+
+#define MAX_BUF_LEN 100 //1024
+#define MAX_OPT_LEN 16
+
+static bool g_isLeSelected = false;
+
+static void PrintMenu();
+static void Process();
+static void Initialize();
+static void StartListeningServer();
+static void StartDiscoveryServer();
+static void FindResource();
+static void SendRequest();
+static void SendRequestAll();
+static void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info);
+static void AdvertiseResource();
+static void SendNotification();
+static void SelectNetwork();
+static void UnselectNetwork();
+static void HandleRequestResponse();
+
+static void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
+static void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+static void Terminate();
+
+void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
+{
+    if (!readInput || bufferLength == 0 || !dataLength)
+    {
+        Serial.println("Invalid buffer");
+        return;
+    }
+
+    while (!Serial.available())
+    {
+        delay(500);
+    }
+    int len = 0;
+    while (Serial.available())
+    {
+        delay(100);
+        char c = Serial.read();
+        if ('\n' != c && '\r' != c && len < bufferLength - 1)
+        {
+            readInput[len++] = c;
+        }
+        else
+        {
+            break;
+        }
+    }
+
+    readInput[len] = '\0';
+    Serial.flush();
+    Serial.print("PD:");
+    Serial.println(readInput);
+    (*dataLength) = len;
+}
+
+CATransportType_t GetConnectivityType()
+{
+    char type[2] = {0};
+    Serial.println("Select network");
+    Serial.println("IPv4: 0");
+    Serial.println("EDR: 2");
+    Serial.println("LE: 3");
+
+    size_t typeLen = 0;
+    GetData(type, sizeof(type), &typeLen);
+    if (0 >= typeLen)
+    {
+        Serial.println("i/p err,default ethernet");
+        return CA_IPV4;
+    }
+    switch (type[0])
+    {
+        case '0':
+            return CA_IPV4;
+        case '2':
+            return CA_EDR;
+        case '3':
+            return CA_LE;
+    }
+    return CA_IPV4;
+}
+
+void setup()
+{
+    Serial.begin (115200);
+
+    Serial.println("============");
+    Serial.println("CA SAMPLE");
+    Serial.println("============");
+    PrintMenu();
+}
+
+void loop()
+{
+    char buffer[5] = {0};
+    size_t len;
+    if (Serial.available() > 0)
+    {
+        GetData(buffer, sizeof(buffer), &len);
+        if (0 >= len)
+        {
+            Serial.println("i/p err");
+            return;
+        }
+        switch (toupper(buffer[0]))
+        {
+            case 'M': // menu
+                PrintMenu();
+                break;
+
+            case 'Q': // quit
+                Serial.println("quit");
+                return;
+
+            case 'I': // Initialize interface
+                Initialize();
+                break;
+
+            case 'S': // start listening server
+                StartListeningServer();
+                break;
+
+            case 'D': // start discovery server
+                StartDiscoveryServer();
+                break;
+
+            case 'F': // find resource
+                FindResource();
+                break;
+
+            case 'R': // send request
+                SendRequest();
+                break;
+            case 'E': //send request to all
+                SendRequestAll();
+                break;
+            case 'A': // advertise resource
+                AdvertiseResource();
+                break;
+
+            case 'B': // send notification
+                SendNotification();
+                break;
+
+            case 'N': // select network
+                SelectNetwork();
+                break;
+
+            case 'X': // unselect network
+                UnselectNetwork();
+                break;
+
+            case 'H': // handle request response
+                HandleRequestResponse();
+                break;
+
+            case 'T': // handle request response
+                Terminate();
+                break;
+
+            default:
+                Serial.println("wrong menu");
+                break;
+        }
+    }
+    //1:Add check for startserver before calling below api
+    if (g_isLeSelected)
+    {
+        HandleRequestResponse();
+    }
+    delay(1000);
+}
+
+void Initialize()
+{
+    if(CAInitialize() != CA_STATUS_OK)
+    {
+        Serial.println("Initialize failed");
+        return;
+    }
+    SelectNetwork();
+    // set handler.
+    CARegisterHandler(RequestHandler, ResponseHandler);
+}
+
+void StartListeningServer()
+{
+    Serial.println("listening server");
+    CAResult_t ret = CAStartListeningServer();
+    if(ret != CA_STATUS_OK)
+    {
+        Serial.print("listening failed: ");
+        Serial.println(ret);
+        return;
+    }
+}
+
+void StartDiscoveryServer()
+{
+    Serial.println("discovery server");
+    CAResult_t ret = CAStartDiscoveryServer();
+    if(ret != CA_STATUS_OK)
+    {
+        Serial.print("discovery failed: ");
+        Serial.println(ret);
+        return;
+    }
+}
+
+void FindResource()
+{
+    char buf[MAX_BUF_LEN] = {0};
+    Serial.println("============");
+    Serial.println("ex) /a/light");
+    Serial.println("uri: ");
+    size_t len = 0;
+    GetData(buf, sizeof(buf), &len);
+    if (0 >= len)
+    {
+        Serial.println("i/p err");
+        return;
+    }
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if (res != CA_STATUS_OK || (!token))
+    {
+        Serial.println("token error");
+        return;
+    }
+
+    Serial.print("token:");
+    Serial.println(token);
+
+    res = CAFindResource(buf, token, tokenLength);
+    if (res != CA_STATUS_OK)
+    {
+        Serial.print("find error: ");
+        Serial.println(res);
+    }
+    else
+    {
+        Serial.println("success: ");
+        Serial.println(buf);
+    }
+    CADestroyToken(token);
+}
+
+void SendRequest()
+{
+    char buf[MAX_BUF_LEN] = {0};
+    CATransportType_t selectedNetwork;
+    selectedNetwork = GetConnectivityType();
+
+    Serial.println("============");
+    Serial.println("10.11.12.13:4545/res_uri (for IP)");
+    Serial.println("10:11:12:13:45:45/res_uri (for BT)");
+    Serial.println("uri: ");
+
+    size_t len = 0;
+    GetData(buf, sizeof(buf), &len);
+    if (0 >= len)
+    {
+        Serial.println("i/p err");
+        return;
+    }
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
+    if (res != CA_STATUS_OK)
+    {
+        Serial.println("Out of memory");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    memset(buf, 0, sizeof(buf));
+
+    Serial.println("\n=============================================\n");
+    Serial.println("0:CON, 1:NON\n");
+    Serial.println("select message type : ");
+    GetData(buf, sizeof(buf), &len);
+    CAMessageType_t msgType = CA_MSG_CONFIRM;
+
+    if (0 >= len)
+    {
+        Serial.println("i/p err,default: 0");
+    }
+    else if(buf[0] == '1')
+    {
+        msgType = CA_MSG_NONCONFIRM;
+    }
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if (res != CA_STATUS_OK || (!token))
+    {
+        Serial.println("token error");
+        return;
+    }
+
+    Serial.println(token);
+    CAInfo_t requestData = {CA_MSG_RESET};
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+    requestData.payload = (CAPayload_t)"Json Payload";
+
+    requestData.type = msgType;
+
+    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    // send request
+    CASendRequest(endpoint, &requestInfo);
+    if (NULL != token)
+    {
+        CADestroyToken(token);
+    }
+
+    // destroy remote endpoint
+    if (endpoint != NULL)
+    {
+        CADestroyRemoteEndpoint(endpoint);
+    }
+
+    CADestroyToken(token);
+    Serial.println("============");
+}
+
+void SendRequestAll()
+{
+    char buf[MAX_BUF_LEN] = {0};
+
+    CATransportType_t selectedNetwork;
+    selectedNetwork = GetConnectivityType();
+
+    Serial.println("=========");
+    Serial.println("10.11.12.13:4545/resource_uri ( for IP )");
+    Serial.println("10:11:12:13:45:45/resource_uri ( for BT )");
+    Serial.println("uri : ");
+
+    size_t len = 0;
+    GetData(buf, sizeof(buf), &len);
+    if (0 >= len)
+    {
+        Serial.println("i/p err");
+        return;
+    }
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    CAResult_t res = CACreateRemoteEndpoint(buf, selectedNetwork, &endpoint);
+
+    if (res != CA_STATUS_OK)
+    {
+        Serial.println("create remote endpoint error");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    CAGroupEndpoint_t *group = NULL;
+    group = (CAGroupEndpoint_t *)OICMalloc(sizeof(CAGroupEndpoint_t));
+    group->transportType = endpoint->transportType;
+    group->resourceUri = endpoint->resourceUri;
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if (res != CA_STATUS_OK || (!token))
+    {
+        Serial.println("token error");
+        return;
+    }
+
+    Serial.println(token);
+
+    CAInfo_t requestData = {CA_MSG_RESET};
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+    requestData.payload = "Temp Json Payload";
+    requestData.type = CA_MSG_NONCONFIRM;
+
+    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    // send request
+    // CASendRequest(endpoint, &requestInfo);
+    CASendRequestToAll(group, &requestInfo);
+
+    if (NULL != token)
+    {
+        CADestroyToken(token);
+    }
+
+    // destroy remote endpoint
+    if (endpoint != NULL)
+    {
+        CADestroyRemoteEndpoint(endpoint);
+    }
+
+    OICFree(group);
+    Serial.println("==========");
+}
+
+void AdvertiseResource()
+{
+    char buf[MAX_BUF_LEN] = {0};
+
+    Serial.println("============");
+    Serial.println("uri: ");
+
+    size_t len = 0;
+    GetData(buf, sizeof(buf), &len);
+    if (0 >= len)
+    {
+        Serial.println("no i/p");
+        return;
+    }
+
+    int16_t optionNum = 0;
+    char optionData[MAX_OPT_LEN] = {0};
+    char optionNumBuf[2] = {0};
+
+    Serial.println("Option Num: ");
+    GetData(optionNumBuf, sizeof(optionNumBuf), &len);
+    if (0 >= len)
+    {
+        Serial.println("no i/p,0 option");
+    }
+    else
+    {
+        optionNum = atoi(optionNumBuf);
+        Serial.println(optionNum);
+    }
+
+    CAHeaderOption_t *headerOpt = NULL;
+    if (optionNum > 0)
+    {
+        headerOpt = (CAHeaderOption_t *) OICCalloc(optionNum, sizeof(CAHeaderOption_t));
+        if (NULL == headerOpt)
+        {
+            Serial.println("Out of memory");
+            return;
+        }
+    }
+
+    int i;
+    for (i = 0 ; i < optionNum ; i++)
+    {
+        int optionID = 0;
+        char getOptionID[4];
+        Serial.println("Opt ID:");
+        GetData(getOptionID, sizeof(getOptionID), &len);
+        if (0 >= len)
+        {
+            Serial.println("no i/p");
+            continue;
+        }
+        else
+        {
+            optionID = atoi(getOptionID);
+        }
+
+        memset(optionData, 0, sizeof(optionData));
+        Serial.println("Opt Data:");
+        GetData(optionData, sizeof(optionData), &len);
+        if (0 >= len)
+        {
+            Serial.println("no i/p");
+            continue;
+        }
+
+        headerOpt[i].optionID = optionID;
+        memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
+        Serial.println("ID:");
+        Serial.println(optionID);
+        Serial.println("Data:");
+        Serial.println(optionData);
+
+        headerOpt[i].optionLength = (uint16_t)strlen(optionData);
+    }
+
+    Serial.println("============");
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if (res != CA_STATUS_OK || (!token))
+    {
+        Serial.println("token error");
+        return;
+    }
+
+    Serial.println("token");
+    Serial.println(token);
+
+    CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t)optionNum);
+    OICFree(headerOpt);
+    CADestroyToken(token);
+}
+
+void SendNotification()
+{
+    char buf[MAX_BUF_LEN] = {0};
+    CATransportType_t selectedNetwork;
+    selectedNetwork = GetConnectivityType();
+
+    Serial.println("============");
+    Serial.println("10.11.12.13:4545/res_uri (for IP)");
+    Serial.println("10:11:12:13:45:45/res_uri (for BT)");
+    Serial.println("uri: ");
+
+    size_t len = 0;
+    GetData(buf, sizeof(buf), &len);
+    if (0 >= len)
+    {
+        Serial.println("i/p err");
+        return;
+    }
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        Serial.println("Out of memory");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if (res != CA_STATUS_OK || (!token))
+    {
+        Serial.println("token error");
+        return;
+    }
+
+    CAInfo_t respondData = {CA_MSG_NONCONFIRM};
+    respondData.token = token;
+    respondData.tokenLength = tokenLength;
+    respondData.payload = (CAPayload_t)"Notification Data";
+
+    CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
+    responseInfo.result = CA_SUCCESS;
+    responseInfo.info = respondData;
+
+    // send request
+    CASendNotification(endpoint, &responseInfo);
+    // destroy remote endpoint
+    if (NULL != endpoint)
+    {
+        CADestroyRemoteEndpoint(endpoint);
+    }
+
+    CADestroyToken(token);
+    Serial.println("============");
+}
+
+void SelectNetwork()
+{
+    char buf[MAX_BUF_LEN] = {0};
+
+    Serial.println("============");
+    Serial.println("Select network");
+    Serial.println("IPv4: 0");
+    Serial.println("EDR: 2");
+    Serial.println("LE: 3\n");
+
+    size_t len = 0;
+    GetData(buf, sizeof(buf), &len);
+    int number = buf[0] - '0';
+    if (0 >= len || number < 0 || number > 3)
+    {
+        Serial.println("Wrong i/p. WIFI selected");
+        number = 1;
+    }
+
+    switch (number)
+    {
+        case 0:
+            {
+#ifdef ARDUINOWIFI
+                const char ssid[] = "SSID";              // your network SSID (name)
+                const char pass[] = "SSID_Password";     // your network password
+                int16_t status = WL_IDLE_STATUS;         // the Wifi radio's status
+
+                if (WiFi.status() == WL_NO_SHIELD)
+                {
+                    Serial.println("ERROR:No Shield");
+                    return;
+                }
+
+                while (status != WL_CONNECTED)
+                {
+                    Serial.print("connecting: ");
+                    Serial.println(ssid);
+                    // WiFi.begin api is weird. ssid should also be taken as const char *
+                    // Connect to WPA/WPA2 network:
+                    status = WiFi.begin((char *)ssid, pass);
+                }
+#elif defined ARDUINOETH
+                // Note: ****Update the MAC address here with your shield's MAC address****
+                uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
+                uint8_t error = Ethernet.begin(ETHERNET_MAC);
+                if (error  == 0)
+                {
+                    Serial.print("Failed: ");
+                    Serial.println(error);
+                    return;
+                }
+#endif
+            }
+            break;
+        case 2:
+            // Nothing TBD here
+            break;
+        case 3:
+            g_isLeSelected = true;
+            break;
+    }
+
+    CASelectNetwork(CATransportType_t(1<<number));
+    Serial.println("============");
+}
+
+void UnselectNetwork()
+{
+    char buf[MAX_BUF_LEN] = {0};
+
+    Serial.println("============");
+    Serial.println("Unselect network");
+    Serial.println("IPv4: 0");
+    Serial.println("EDR: 2");
+    Serial.println("LE: 3\n");
+
+    size_t len = 0;
+    GetData(buf, sizeof(buf), &len);
+    int number = buf[0] - '0';
+    Serial.println(number);
+    if (0 >= len || number < 0 || number > 3)
+    {
+        Serial.println("Wrong i/p. WIFI selected");
+        number = 1;
+    }
+    if (number == 3)
+    {
+        g_isLeSelected = false;
+    }
+    CAUnSelectNetwork(1 << number);
+    Serial.println("Terminate");
+    CATerminate();
+    Serial.println("============");
+}
+
+void PrintMenu()
+{
+
+    Serial.println("============");
+    Serial.println("i: Initialize");
+    Serial.println("s: start listening server");
+    Serial.println("d: start discovery server");
+    Serial.println("f: find resource");
+    Serial.println("r: send request");
+    Serial.println("e: send request to all");
+    Serial.println("a: advertise resource");
+    Serial.println("b: send notification");
+    Serial.println("n: select network");
+    Serial.println("x: unselect network");
+    Serial.println("h: handle request response");
+    Serial.println("t: terminate");
+    Serial.println("q: quit");
+    Serial.println("============");
+}
+
+void HandleRequestResponse()
+{
+    CAHandleRequestResponse();
+}
+
+void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+{
+    if (!object)
+    {
+        Serial.println("Remote endpoint is NULL!");
+        return;
+    }
+
+    if (!requestInfo)
+    {
+        Serial.println("Request info is NULL!");
+        return;
+    }
+
+    Serial.println("uri: ");
+    Serial.println(object->resourceUri);
+    Serial.println("RAddr: ");
+    Serial.println(object->addressInfo.IP.ipAddress);
+    Serial.println("Port: ");
+    Serial.println(object->addressInfo.IP.port);
+    Serial.println("data: ");
+    Serial.println(requestInfo->info.payload);
+    Serial.println("Type: ");
+    Serial.println(requestInfo->info.type);
+
+    if (requestInfo->info.options)
+    {
+        uint32_t len = requestInfo->info.numOptions;
+        uint32_t i;
+        for (i = 0; i < len; i++)
+        {
+            Serial.println("Option:");
+            Serial.println(i+1);
+            Serial.println("ID:");
+            Serial.println(requestInfo->info.options[i].optionID);
+            Serial.println("Data:");
+            Serial.println((char*)requestInfo->info.options[i].optionData);
+        }
+    }
+    Serial.println("send response");
+    SendResponse((CARemoteEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
+}
+
+void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+{
+    if (object && object->resourceUri)
+    {
+        Serial.print("uri: ");
+        Serial.println(object->resourceUri);
+    }
+
+    if (responseInfo)
+    {
+        Serial.print("data: ");
+        Serial.println(responseInfo->info.payload);
+        Serial.print("Type: ");
+        Serial.println(responseInfo->info.type);
+        Serial.print("res result=");
+        Serial.println(responseInfo->result);
+    }
+}
+
+void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info)
+{
+    char buf[MAX_BUF_LEN] = {0};
+
+    Serial.println("============");
+    CAInfo_t responseData = {CA_MSG_RESET};
+    if(info && info->type == CA_MSG_CONFIRM)
+    {
+        responseData.type = CA_MSG_ACKNOWLEDGE;
+    }
+    else
+    {
+        responseData.type = CA_MSG_NONCONFIRM;
+    }
+
+    responseData.messageId = (info != NULL) ? info->messageId : 0;
+    responseData.token = (info != NULL) ? (CAToken_t)info->token : NULL;
+    responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
+    responseData.payload = (CAPayload_t)"response payload";
+
+    CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
+    responseInfo.result = (CAResponseResult_t)203;
+    responseInfo.info = responseData;
+
+    // send request (connectivityType from remoteEndpoint of request Info)
+    CAResult_t res = CASendResponse(endpoint, &responseInfo);
+    if(res != CA_STATUS_OK)
+    {
+        Serial.println("Snd Resp error");
+    }
+    else
+    {
+        Serial.println("Snd Resp success");
+    }
+
+    Serial.println("============");
+}
+
+void Terminate()
+{
+    UnselectNetwork();
+}
+
diff --git a/resource/csdk/connectivity/samples/linux/.gitignore b/resource/csdk/connectivity/samples/linux/.gitignore
deleted file mode 100644 (file)
index 1ec70a5..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-/.objs/
-/out/
diff --git a/resource/csdk/connectivity/samples/linux/Makefile b/resource/csdk/connectivity/samples/linux/Makefile
deleted file mode 100644 (file)
index 74197a0..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-#/******************************************************************
-# *
-# * Copyright 2014 Samsung Electronics All Rights Reserved.
-# *
-# *
-# *
-# * Licensed under the Apache License, Version 2.0 (the "License");
-# * you may not use this file except in compliance with the License.
-# * You may obtain a copy of the License at
-# *
-# *      http://www.apache.org/licenses/LICENSE-2.0
-# *
-# * Unless required by applicable law or agreed to in writing, software
-# * distributed under the License is distributed on an "AS IS" BASIS,
-# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# * See the License for the specific language governing permissions and
-# * limitations under the License.
-# *
-#******************************************************************/
-
-##
-##     Definitions
-##
-SHELL                                          = /bin/bash
-PROJECT_NAME                           = connectivity_abstraction
-PROJECT_ROOT_PATH                      = ../..
-PROJECT_API_PATH                       = $(PROJECT_ROOT_PATH)/api
-PROJECT_INC_PATH                       = $(PROJECT_ROOT_PATH)/inc
-PROJECT_SRC_PATH                       = $(PROJECT_ROOT_PATH)/src
-PROJECT_COMMON_PATH            = $(PROJECT_ROOT_PATH)/common
-PROJECT_OUT_PATH                       = $(PROJECT_ROOT_PATH)/build/out
-COMPONENT_OUT_PATH             = ./out
-COMPONENT_OBJ_PATH             = ./.objs
-
-TARGET = sample_main
-
-##
-##     Commands
-##
-CC                     = gcc
-CXX                    = g++
-RM                     = rm -rf
-CP                     = cp
-MV                     = mv
-AR                     = ar
-LD                     = ld
-LN                     = ln
-CD                     = cd
-RANLIB         = ranlib
-
-##
-##     file declaration
-##
-COMPONENT_SRCS                 =  sample_main.c        \
-
-COMPONENT_OBJS                 = $(COMPONENT_SRCS:%.c=$(COMPONENT_OBJ_PATH)/%.o)
-
-##
-##     compiler flags
-##
-LIBS                           = -L$(PROJECT_OUT_PATH) -lconnectivity_abstraction
-
-CFLAGS                         = -g -c -Wall -fPIC
-
-LFLAGS                         = -ldl -lpthread
-
-IFLAGS                         = -I$(PROJECT_API_PATH) \
-
-DFLAGS                         = -DLINUX -DTB_LOG
-
-##
-##     compile and link rules
-##
-vpath %.c ./
-
-$(COMPONENT_OBJ_PATH)/%.o: %.c
-       @$(MAKE_OBJ_PATH)
-       $(CC) -o $@ $(CFLAGS) $(DFLAGS) $(IFLAGS) $<
-
-all : $(TARGET)
-       @echo   " "
-       @echo   "======================"
-       @echo   "       Success!!"
-       @echo   "======================"
-
-$(TARGET) : $(COMPONENT_OBJS)
-       @$(MAKE_COMPONENT_OUT_PATH)
-       $(CC) -o $@ $(COMPONENT_OBJS) $(LIBS) $(LFLAGS)
-       @$(MV) $(TARGET) $(COMPONENT_OUT_PATH)/.
-
-clean :        
-       @$(RM) $(COMPONENT_OBJ_PATH) \
-                       $(COMPONENT_OUT_PATH)
-
-install :
-       @$(MAKE_COMPONENT_OUT_PATH)
-       @$(CP) $(PROJECT_OUT_PATH)/* $(COMPONENT_OUT_PATH)/.
-
-##
-##     macros
-##
-define MAKE_OBJ_PATH
-       @if [ ! -d $(COMPONENT_OBJ_PATH) ]; then \
-       mkdir $(COMPONENT_OBJ_PATH); \
-       fi
-endef
-
-
-##
-##     macro
-##
-define MAKE_COMPONENT_OUT_PATH
-       @if     [ ! -d $(COMPONENT_OUT_PATH) ]; then    \
-       mkdir $(COMPONENT_OUT_PATH);    \
-       fi
-endef
-
-.PHONY:        all clean install
-
-
index 239ddbc..99f365d 100644 (file)
@@ -24,3 +24,8 @@ in auto_build.sh which is also in the the repository root directory.
 #4     execute sample.sh in "connectivity/samples/linux/" folder
  ex.    $./sample.sh (This will make a clean build and execute application)
 
+#4     execute sample.sh in if you want to build with DTLS
+ ex.    $./sample.sh  WITH_DTLS (This will make a clean build and execute application)
+
+
+
diff --git a/resource/csdk/connectivity/samples/linux/SConscript b/resource/csdk/connectivity/samples/linux/SConscript
new file mode 100644 (file)
index 0000000..9c0a0a3
--- /dev/null
@@ -0,0 +1,53 @@
+##
+# Building sample application
+##
+
+Import('env')
+
+sample_env = env.Clone()
+
+ca_os = sample_env.get('TARGET_OS')
+ca_transport = sample_env.get('TARGET_TRANSPORT')
+secured = sample_env.get('SECURED')
+root_dir = './../../'
+
+
+#####################################################################
+# Source files and Target(s)
+######################################################################
+
+print"Reading ca script %s"%ca_transport
+
+sample_env.PrependUnique(CPPPATH = [root_dir + '/api/'])
+sample_env.AppendUnique(CPPPATH = [root_dir + '/inc/'])
+sample_env.AppendUnique(CPPPATH = [root_dir + '/lib/libcoap-4.1.1/'])
+sample_env.AppendUnique(CPPPATH = [root_dir + 'common/inc/'])
+
+print "Reading sample application build script"
+
+build_dir = sample_env.get('BUILD_DIR')
+sample_dir = './samples/linux/'
+
+secured = sample_env.get('SECURED')
+
+print "Sample secured flag is %s" % secured
+
+sample_src = ['./sample_main.c',]
+print " sample src %s" % sample_src
+#env.StaticLibrary('casample', sample_src)
+
+sample_env.PrependUnique(LIBPATH = [sample_env.get('BUILD_DIR'), '.',])
+sample_env.PrependUnique(RPATH = [sample_env.get('BUILD_DIR'), '.',])
+sample_env.PrependUnique(LIBS = ['connectivity_abstraction', 'coap', 'pthread', 'rt'])
+
+if secured == '1':
+       sample_env.AppendUnique(CPPPATH = [root_dir + 'external/inc/'])
+       sample_env.AppendUnique(LIBS = ['tinydtls'])
+       casample =sample_env.Program('casample', [sample_src])
+else:
+       casample =sample_env.Program('casample', [sample_src])
+env.InstallTarget(casample, 'casample')
+
+
+
+
old mode 100644 (file)
new mode 100755 (executable)
index 3d85b40..bebc545
 # *
 #******************************************************************/
 
-cd ../../lib/libcoap-4.1.1
+cd ../../build/linux
 make clean
+if echo $1 | grep -q -i "WITH_DTLS"
+then
+make DTLS=1
+else
 make
-
-cd ../../build/linux 
-make clean
-make
-
+fi
 
 cd ../../samples/linux
 make clean
@@ -33,3 +33,4 @@ make
 
 cd out
 LD_LIBRARY_PATH=../../../build/out ./sample_main
+
index 17992e2..d7c2354 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <stdbool.h>
+
 #include "cacommon.h"
 #include "cainterface.h"
+#include "oic_malloc.h"
+#ifdef __WITH_DTLS__
+#include "ocsecurityconfig.h"
+#endif
 
 #define MAX_BUF_LEN 1024
+#define MAX_OPT_LEN 16
+
+#define PORT_LENGTH 5
+
+#define SECURE_DEFAULT_PORT 5684
+
+#define RESOURCE_URI_LENGTH 14
+
+#define SYSTEM_INVOKE_ERROR 127
+#define SYSTEM_ERROR -1
+
+/**
+ * @def RS_IDENTITY
+ * @brief
+ */
+#define IDENTITY     ("1111111111111111")
+/* @def RS_CLIENT_PSK
+ * @brief
+ */
+#define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
+
+int g_received;
+uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
+CATransportType_t g_selected_nw_type = CA_IPV4;
+const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
 
 char get_menu();
 void process();
+CAResult_t get_network_type();
+CAResult_t get_input_data(char *buf, int32_t length);
 
 void start_listening_server();
 void start_discovery_server();
 void find_resource();
 void send_request();
-void send_response();
+void send_request_all();
 void advertise_resource();
+void send_notification();
 void select_network();
 void unselect_network();
 void handle_request_response();
+void find_fixed_resource();
+void get_network_info();
+void send_secure_request();
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
+void get_resource_uri(char *URI, char *resourceURI, int length);
+int get_secure_information(CAPayload_t payLoad);
+
+static CAToken_t g_last_request_token = NULL;
+static const char SECURE_COAPS_PREFIX[] = "coaps://";
+static const char SECURE_INFO_DATA[] =
+                                    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[] =
+                                    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
+
+#ifdef __WITH_DTLS__
+static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
+
+void clearDtlsCredentialInfo()
+{
+    printf("clearDtlsCredentialInfo IN\n");
+    if (pskCredsBlob)
+    {
+        // Initialize sensitive data to zeroes before freeing.
+        if (pskCredsBlob->creds)
+        {
+            memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+            free(pskCredsBlob->creds);
+        }
+
+        memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
+        free(pskCredsBlob);
+        pskCredsBlob = NULL;
+    }
+    printf("clearDtlsCredentialInfo OUT\n");
+}
+
+// Internal API. Invoked by CA stack to retrieve credentials from this module
+void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+{
+    printf("CAGetDtlsPskCredentials IN\n");
+    if(!credInfo)
+    {
+        printf("Invalid credential container");
+        return;
+    }
+
+    *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == *credInfo)
+    {
+        printf("Failed to allocate credential blob.");
+        return;
+    }
+
+    size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
+    (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
+    if (NULL == (*credInfo)->creds)
+    {
+        printf("Failed to allocate credentials.");
+        free(*credInfo);
+        *credInfo = NULL;
+        return;
+    }
+
+    memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
+    (*credInfo)->num = pskCredsBlob->num;
+    memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
+
+    printf("CAGetDtlsPskCredentials OUT\n");
+}
+
+
+CAResult_t SetCredentials()
+{
+    printf("SetCredentials IN\n");
+    pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == pskCredsBlob)
+    {
+        printf("Memory allocation failed!\n");
+        return CA_MEMORY_ALLOC_FAILED;
+     }
+    memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+
+
+    pskCredsBlob->num = 1;
+
+    pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+    if (NULL == pskCredsBlob->creds)
+    {
+        printf("Memory allocation failed!\n");
+        free(pskCredsBlob);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
+    memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
 
-void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
-void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
-void send_request_tmp(CARemoteEndpoint_t* endpoint, CAToken_t token);
+    printf("SetCredentials OUT\n");
+    return CA_STATUS_OK;
+}
+#endif
 
 int main()
 {
-    system("clear");
+    int ret = system("clear");
+    // shell invoke error: 127, others: -1
+    if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
+    {
+        printf("Terminal Clear Error: %d\n", ret);
+        return -1;
+    }
 
     printf("=============================================\n");
     printf("\t\tsample main\n");
     printf("=============================================\n");
 
-    CAInitialize();
+    CAResult_t res = CAInitialize();
+    if (CA_STATUS_OK != res)
+    {
+        printf("CAInitialize fail\n");
+        return -1;
+    }
+
+    /*
+    * Read DTLS PSK credentials from persistent storage and
+    * set in the OC stack.
+    */
+#ifdef __WITH_DTLS__
+    res = SetCredentials();
+    if (CA_STATUS_OK != res)
+    {
+        printf("SetCredentials failed\n");
+        return -1;
+    }
 
-    // network enable
-    // default
-    printf("select default network(WIFI)\n");
-    CASelectNetwork(CA_WIFI);
+    res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Set credential handler fail\n");
+        return -1;
+    }
+#endif
 
     // set handler.
     CARegisterHandler(request_handler, response_handler);
 
     process();
 
-    CATerminate();
+    CADestroyToken(g_last_request_token);
+
+    g_last_request_token = NULL;
 
+    CATerminate();
+#ifdef __WITH_DTLS__
+    clearDtlsCredentialInfo();
+#endif
     return 0;
 }
 
@@ -78,20 +247,25 @@ void process()
         {
             case 'm': // menu
             case 'M':
-                continue;
+                break;
 
             case 'q': // quit
             case 'Q':
                 printf("quit..!!\n");
                 return;
 
-            case 's': // start listening server
+            case 's': // start server
             case 'S':
                 start_listening_server();
                 break;
 
-            case 'd': // start discovery server
-            case 'D':
+            case 't': // send request
+            case 'T':
+                send_request_all();
+                break;
+
+            case 'c': // start client
+            case 'C':
                 start_discovery_server();
                 break;
 
@@ -110,6 +284,11 @@ void process()
                 advertise_resource();
                 break;
 
+            case 'b': // send notification
+            case 'B':
+                send_notification();
+                break;
+
             case 'n': // select network
             case 'N':
                 select_network();
@@ -125,271 +304,1146 @@ void process()
                 handle_request_response();
                 break;
 
+            case 'y':
+            case 'Y':
+                while (1)
+                {
+                    g_received = 0;
+                    find_fixed_resource();
+                    while (g_received == 0)
+                    {
+                        sleep(1);
+                        handle_request_response();
+
+                    }
+                }
+                break;
+
+            case 'w':
+            case 'W':
+                g_received = 0;
+                start_discovery_server();
+                send_secure_request();
+                while (g_received == 0)
+                {
+                    sleep(1);
+                    handle_request_response();
+                }
+                break;
+
+            case 'z':
+            case 'Z':
+                start_listening_server();
+                while (1)
+                {
+                    sleep(1);
+                    handle_request_response();
+                }
+                break;
+
+            case 'g': // get network information
+            case 'G':
+                get_network_info();
+                break;
+
             default:
                 printf("not supported menu!!\n");
                 break;
         }
     }
-
 }
 
 void start_listening_server()
 {
     printf("start listening server!!\n");
 
-    CAStartListeningServer();
+    CAResult_t res = CAStartListeningServer();
+    if (CA_STATUS_OK != res)
+    {
+        printf("start listening server fail, error code : %d\n", res);
+    }
+    else
+    {
+        printf("start listening server success\n");
+    }
 }
 
 void start_discovery_server()
 {
-    printf("start discovery server!!\n");
+    printf("start discovery client!!\n");
 
-    CAStartDiscoveryServer();
+    CAResult_t res = CAStartDiscoveryServer();
+    if (CA_STATUS_OK != res)
+    {
+        printf("start discovery client fail, error code : %d\n", res);
+    }
+    else
+    {
+        printf("start discovery client success\n");
+    }
 }
 
-void find_resource()
+void find_fixed_resource()
 {
-    char buf[MAX_BUF_LEN];
-
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
-    printf("\n=============================================\n");
-    printf("ex) a/light\n");
-    printf("reference uri : ");
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
 
-    gets(buf);
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!");
+        return;
+    }
+    printf("Generated token %s\n", token);
 
-    CAResult_t res = CAFindResource(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    strcpy(buf, "/a/light");
 
-    if (res != CA_STATUS_OK)
+    res = CAFindResource(buf, token, tokenLength);
+    if (CA_STATUS_OK != res)
     {
-        printf("find resource error!!\n");
+        printf("Find resource error : %d\n", res);
     }
     else
     {
-        printf("find resource fo %s URI\n", buf);
+        printf("Find resource to %s URI\n", buf);
     }
 
+    // delete token
+    CADestroyToken(token);
+
     printf("=============================================\n");
 }
 
-void send_request()
+void find_resource()
 {
-    char buf[MAX_BUF_LEN];
-
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
     printf("\n=============================================\n");
-    printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
-    printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
-    printf("uri : ");
-
-    gets(buf);
-
-    // create remote endpoint
-    CARemoteEndpoint_t* endpoint = NULL;
-    CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint);
-    endpoint->connectivityType = CA_WIFI; //
+    printf("ex) /a/light\n");
+    printf("reference uri : ");
 
-    if (res != CA_STATUS_OK)
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
     {
-        printf("create remote endpoint error!!");
         return;
     }
 
     // create token
     CAToken_t token = NULL;
-    res = CAGenerateToken(&token);
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
 
-    if (res != CA_STATUS_OK)
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
     {
-        printf("token generate error!!");
-        token = NULL;
+        printf("Token generate error!!\n");
+        return;
     }
 
-    printf("generated token %s\n", (token != NULL) ? token : "");
-
-    CAInfo_t requestData;
-    memset(&requestData, 0, sizeof(CAInfo_t));
-    requestData.token = token;
-    requestData.payload = "Temp Json Payload";
-
-    CARequestInfo_t requestInfo;
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
-
-    // send request
-    CASendRequest(endpoint, &requestInfo);
+    printf("Generated token %s\n", token);
 
-    if (token != NULL)
+    res = CAFindResource(buf, token, tokenLength);
+    if (CA_STATUS_OK != res)
     {
+        printf("Find resource error : %d\n", res);
         CADestroyToken(token);
     }
-
-    // destroy remote endpoint
-    if (endpoint != NULL)
+    else
     {
-        CADestroyRemoteEndpoint(endpoint);
+        printf("Find resource to %s URI\n", buf);
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
     }
 
     printf("=============================================\n");
 }
 
-void advertise_resource()
+void send_request()
 {
-    printf("\n=============================================\n");
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
 
-    printf("not implemented yet.\n");
+    printf("Do you want to send secure request ?.... enter (0/1): ");
 
-    printf("=============================================\n");
-}
+    char secureRequest[MAX_BUF_LEN] = {0};
+    if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
+    {
+        return;
+    }
 
-void select_network()
-{
-    char buf[MAX_BUF_LEN];
+    if (strcmp(secureRequest, "1") == 0)
+    {
+        printf("Enter the URI like below....\n");
+        printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
+    }
+    else if (strcmp(secureRequest, "0") == 0)
+    {
+        printf("Enter the URI like below....\n");
+        printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
+        printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
+    }
+    else
+    {
+        printf("Input data is wrong value\n");
+        return;
+    }
+
+    char uri[MAX_BUF_LEN] = {'\0'};
+    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res || !endpoint)
+    {
+        printf("Failed to create remote endpoint, error code : %d\n", res);
+        return;
+    }
 
     printf("\n=============================================\n");
-    printf("\tselect network\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
-    printf("EDR : 2\n");
-    printf("LE : 3\n");
-    printf("select : ");
+    printf("0:CON, 1:NON\n");
+    printf("select message type : ");
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-    gets(buf);
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
 
-    int number = buf[0] - '0';
+    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
 
-    number = (number < 0 || number > 3) ? 1 : number;
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
 
-    CASelectNetwork(1 << number);
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error, error code : %d\n", res);
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
 
-    printf("=============================================\n");
-}
+    printf("Generated token %s\n", token);
 
-void unselect_network()
-{
-    char buf[MAX_BUF_LEN];
+    // extract relative resourceuri from give uri
+    printf("URI : %s\n", uri);
 
-    printf("\n=============================================\n");
-    printf("\tunselect enabled network\n");
-    printf("ETHERNET : 0\n");
-    printf("WIFI : 1\n");
-    printf("EDR : 2\n");
-    printf("LE : 3\n");
-    printf("select : ");
+    char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
+    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-    gets(buf);
+    // create request data
+    CAInfo_t requestData = { 0 };
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
 
-    int number = buf[0] - '0';
+    if (strcmp(secureRequest, "1") == 0)
+    {
+        size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+        if (NULL == requestData.payload)
+        {
+            printf("Memory allocation fail\n");
+            CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
+            return;
+        }
+        snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
+    }
+    else
+    {
+        size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+        if (NULL == requestData.payload)
+        {
+            printf("Memory allocation fail\n");
+            CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
+            return;
+        }
+        snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
+    }
+    requestData.type = msgType;
+
+    CARequestInfo_t requestInfo = { 0 };
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    // send request
+    res = CASendRequest(endpoint, &requestInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not send request : %d\n", res);
+    }
 
-    number = (number < 0 || number > 3) ? 1 : number;
+    //destroy token
+    CADestroyToken(token);
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+    free(requestData.payload);
 
-    CAUnSelectNetwork(1 << number);
 
     printf("=============================================\n");
 }
 
-char get_menu()
+void send_secure_request()
 {
-    char buf[MAX_BUF_LEN];
+    char uri[MAX_BUF_LEN];
+    char ipv4addr[CA_IPADDR_SIZE];
 
     printf("\n=============================================\n");
-    printf("\t\tMenu\n");
-    printf("\ts : start listening server\n");
-    printf("\td : start discovery server\n");
-    printf("\tf : find resource\n");
-    printf("\tr : send request\n");
-    printf("\ta : advertise resource\n");
-    printf("\tn : select network\n");
-    printf("\tx : unselect network\n");
-    printf("\th : handle request response\n");
-    printf("\tq : quit\n");
-    printf("=============================================\n");
-    printf("select : ");
-
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+    printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
 
-    gets(buf);
-
-    return buf[0];
-}
+    if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
+    {
+        return;
+    }
+    snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
 
-void handle_request_response()
-{
-    printf("handle_request_response\n");
-    CAHandleRequestResponse();
-}
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    CAResult_t res = CACreateRemoteEndpoint(uri, CA_IPV4, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Failed to create remote endpoint, error code: %d\n", res);
+        goto exit;
+    }
 
-void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo)
-{
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
 
-    printf("request_handler, uri : %s, data : %s\n", (object != NULL) ? object->resourceUri : "",
-            (requestInfo != NULL) ? requestInfo->info.payload : "");
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error, error code : %d\n", res);
+        goto exit;
+    }
 
-    printf("send response with URI\n");
-    send_response(object, (requestInfo != NULL) ? requestInfo->info.token : "");
+    printf("Generated token %s\n", token);
 
-}
+    // create request data
+    CAMessageType_t msgType = CA_MSG_NONCONFIRM;
+    CAInfo_t requestData = { 0 };
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+    requestData.type = msgType;
 
-void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo)
-{
+    CARequestInfo_t requestInfo = { 0 };
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
 
-    printf("response_handler, uri : %s, data : %s\n", (object != NULL) ? object->resourceUri : "",
-            (responseInfo != NULL) ? responseInfo->info.payload : "");
+    // send request
+    CASendRequest(endpoint, &requestInfo);
 
-    printf("send request after receivce response data\n");
-    send_request_tmp(object, (responseInfo != NULL) ? responseInfo->info.token : "");
+exit:
+    // cleanup
+    CADestroyToken(token);
+    CADestroyRemoteEndpoint(endpoint);
+    printf("=============================================\n");
 }
 
-void send_response(CARemoteEndpoint_t* endpoint, CAToken_t request_token)
+
+void send_request_all()
 {
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
 
     printf("\n=============================================\n");
+    printf("ex) /a/light\n");
+    printf("resource uri : ");
 
-    CAInfo_t responseData;
-    //responseData = (CAInfo*) malloc(sizeof(CAInfo));
-    memset(&responseData, 0, sizeof(CAInfo_t));
-    responseData.token = request_token;
-    responseData.payload = "response payload";
-
-    CAResponseInfo_t responseInfo;
-    //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo));
-    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
-    responseInfo.result = 203;
-    responseInfo.info = responseData;
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
 
-    // send request
-    endpoint->connectivityType = CA_WIFI;
-    CASendResponse(endpoint, &responseInfo);
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Create remote endpoint error, error code: %d\n", res);
+        return;
+    }
 
-    printf("=============================================\n");
+    CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+    if (NULL == group)
+    {
+        printf("Memory allocation failed!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+    group->transportType = endpoint->transportType;
+    group->resourceUri = endpoint->resourceUri;
 
-}
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
 
-void send_request_tmp(CARemoteEndpoint_t* endpoint, CAToken_t token)
-{
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        free(group);
+        return;
+    }
 
-    printf("\n=============================================\n");
+    printf("generated token %s\n", token);
 
-    CAInfo_t requestData;
-    memset(&requestData, 0, sizeof(CAInfo_t));
+    CAInfo_t requestData = { 0 };
     requestData.token = token;
+    requestData.tokenLength = tokenLength;
     requestData.payload = "Temp Json Payload";
+    requestData.type = CA_MSG_NONCONFIRM;
 
-    CARequestInfo_t requestInfo;
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+    CARequestInfo_t requestInfo = { 0 };
     requestInfo.method = CA_GET;
     requestInfo.info = requestData;
 
     // send request
-    endpoint->connectivityType = CA_WIFI;
-    CASendRequest(endpoint, &requestInfo);
-
-    printf("=============================================\n");
-
-}
+    res = CASendRequestToAll(group, &requestInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not send request to all\n");
+        CADestroyToken(token);
+    }
+    else
+    {
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
+    }
+
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+    free(group);
+
+    printf("=============================================\n");
+}
+
+void advertise_resource()
+{
+    printf("\n=============================================\n");
+    printf("uri : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    char optionNumBuf[MAX_BUF_LEN] = { 0 };
+    char optionData[MAX_OPT_LEN] = { 0 } ;
+
+    printf("Option Num : ");
+    if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
+    {
+        return;
+    }
+    int optionNum = atoi(optionNumBuf);
+
+    CAHeaderOption_t * headerOpt = (CAHeaderOption_t *)
+            calloc(1, optionNum * sizeof(CAHeaderOption_t));
+    if (NULL == headerOpt)
+    {
+        printf("Memory allocation failed!\n");
+        return;
+    }
+
+    int i;
+    for (i = 0; i < optionNum; i++)
+    {
+        char getOptionID[MAX_BUF_LEN] = { 0 } ;
+
+        printf("[%d] Option ID : ", i + 1);
+        if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
+        {
+            free(headerOpt);
+            return;
+        }
+        int optionID = atoi(getOptionID);
+
+        headerOpt[i].optionID = optionID;
+
+        printf("[%d] Option Data : ", i + 1);
+        if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
+        {
+            free(headerOpt);
+            return;
+        }
+
+        memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
+        printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
+
+        headerOpt[i].optionLength = (uint16_t) strlen(optionData);
+    }
+    printf("\n=============================================\n");
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!\n");
+        free(headerOpt);
+        return;
+    }
+
+    printf("Generated token %s\n", token);
+
+    res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not start advertise resource\n");
+        CADestroyToken(token);
+    }
+    else
+    {
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
+    }
+
+    free(headerOpt);
+}
+
+void send_notification()
+{
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    printf("\n=============================================\n");
+    printf("Enter the URI like below....\n");
+    printf("10.11.12.13:4545/resource_uri ( for IP )\n");
+    printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
+    printf("uri : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CON     : 0\n");
+    printf("NON     : 1\n");
+    printf("ACK     : 2\n");
+    printf("RESET   : 3\n");
+    printf("select : ");
+
+    char messageTypeBuf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int messageType = messageTypeBuf[0] - '0';
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Create remote endpoint error, error code: %d\n", res);
+        return;
+    }
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    printf("Generated token %s\n", token);
 
+    CAInfo_t respondData = { 0 };
+    respondData.token = token;
+    respondData.payload = "Temp Notification Data";
+    respondData.type = messageType;
+
+    CAResponseInfo_t responseInfo = { 0 };
+    responseInfo.result = CA_SUCCESS;
+    responseInfo.info = respondData;
+
+    // send request
+    res = CASendNotification(endpoint, &responseInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Send notification error, error code: %d\n", res);
+    }
+    else
+    {
+        printf("Send notification success\n");
+    }
+
+    // destroy token
+    CADestroyToken(token);
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+
+    printf("\n=============================================\n");
+}
+
+void select_network()
+{
+    printf("\n=============================================\n");
+    printf("\tselect network\n");
+    printf("IPv4 : 0\n");
+    printf("EDR  : 2\n");
+    printf("LE   : 3\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int number = buf[0] - '0';
+
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
+
+    CAResult_t res = CASelectNetwork(1 << number);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Select network error\n");
+    }
+    else
+    {
+        printf("Select network success\n");
+    }
+
+    printf("=============================================\n");
+}
+
+void unselect_network()
+{
+    printf("\n=============================================\n");
+    printf("\tunselect enabled network\n");
+    printf("IPv4 : 0\n");
+    printf("EDR : 2\n");
+    printf("LE : 3\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int number = buf[0] - '0';
+
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
+
+    CAResult_t res = CAUnSelectNetwork(1 << number);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Unselect network error\n");
+    }
+    else
+    {
+        printf("Unselect network success\n");
+    }
+
+    printf("=============================================\n");
+}
+
+char get_menu()
+{
+    printf("\n=============================================\n");
+    printf("\t\tMenu\n");
+    printf("\ts : start server\n");
+    printf("\tc : start client\n");
+    printf("\tf : find resource\n");
+    printf("\tr : send request\n");
+    printf("\tt : send request to all\n");
+    printf("\ta : advertise resource\n");
+    printf("\tb : send notification\n");
+    printf("\tn : select network\n");
+    printf("\tx : unselect network\n");
+    printf("\tg : get network information\n");
+    printf("\th : handle request response\n");
+    printf("\ty : run static client\n");
+    printf("\tz : run static server\n");
+    printf("\tw : send secure request\n");
+    printf("\tq : quit\n");
+    printf("=============================================\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        printf("Failed to get input data\n");
+    }
+
+    return buf[0];
+}
+
+void handle_request_response()
+{
+    printf("Handle_request_response\n");
+
+    CAResult_t res = CAHandleRequestResponse();
+    if (CA_STATUS_OK != res)
+    {
+        printf("Handle request error, error code: %d\n", res);
+    }
+    else
+    {
+        printf("Handle request success\n");
+    }
+}
+
+void get_network_info()
+{
+    CALocalConnectivity_t *tempInfo = NULL;
+    uint32_t tempSize = 0;
+
+    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+    if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
+    {
+        printf("Network not connected\n");
+        free(tempInfo);
+        return;
+    }
+
+    printf("################## Network Information #######################\n");
+    printf("Network info total size is %d\n\n", tempSize);
+
+    int index;
+    for (index = 0; index < tempSize; index++)
+    {
+        printf("Type: %d\n", tempInfo[index].type);
+        if (CA_IPV4 == tempInfo[index].type)
+        {
+            printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
+            printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
+        }
+        else if (CA_EDR == tempInfo[index].type)
+        {
+            printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
+        }
+        else if (CA_LE == tempInfo[index].type)
+        {
+            printf("Address: %s\n", tempInfo[index].addressInfo.LE.leMacAddress);
+        }
+        printf("Secured: %s\n\n", tempInfo[index].isSecured ? "true" : "false");
+
+        if (tempInfo[index].isSecured)
+        {
+            g_local_secure_port = tempInfo[index].addressInfo.IP.port;
+            printf("Secured: in global %d\n\n", g_local_secure_port);
+        }
+    }
+
+    free(tempInfo);
+    printf("##############################################################");
+}
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+{
+    if (NULL == object || NULL == requestInfo)
+    {
+        printf("Input parameter is NULL\n");
+        return;
+    }
+
+    if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
+        && (memcmp(g_last_request_token, requestInfo->info.token,
+                   CA_MAX_TOKEN_LEN) == 0))
+    {
+        printf("token is same. received request of it's own. skip.. \n");
+        return;
+    }
+
+    printf("##########received request from remote device #############\n");
+    printf("Uri: %s\n", object->resourceUri);
+    if (CA_IPV4 == object->transportType)
+    {
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
+    }
+    else if (CA_EDR == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+    }
+    else if (CA_LE == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.LE.leMacAddress);
+    }
+    printf("Data: %s\n", requestInfo->info.payload);
+    printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
+
+    if (requestInfo->info.options)
+    {
+        uint32_t len = requestInfo->info.numOptions;
+        uint32_t i;
+        for (i = 0; i < len; i++)
+        {
+            printf("Option %d\n", i + 1);
+            printf("ID : %d\n", requestInfo->info.options[i].optionID);
+            printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
+                   requestInfo->info.options[i].optionData);
+        }
+    }
+    printf("############################################################\n");
+
+    //Check if this has secure communication information
+    if (requestInfo->info.payload &&
+            (CA_IPV4 == object->transportType))
+    {
+        int securePort = get_secure_information(requestInfo->info.payload);
+        if (0 < securePort) //Set the remote endpoint secure details and send response
+        {
+            printf("This is secure resource...\n");
+
+            //length of "coaps://"
+            size_t length = sizeof(SECURE_COAPS_PREFIX) - 1;
+
+            // length of "ipaddress:port"
+            length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
+            length += strlen(object->resourceUri) + 1;
+
+            char *uri = calloc(1, sizeof(char) * length);
+            if (!uri)
+            {
+                printf("Failed to create new uri\n");
+                return;
+            }
+            sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
+                    object->addressInfo.IP.port, object->resourceUri);
+
+            CARemoteEndpoint_t *endpoint = NULL;
+            if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
+            {
+                printf("Failed to create duplicate of remote endpoint!\n");
+                return;
+            }
+            endpoint->isSecured = true;
+            object = endpoint;
+
+            free(uri);
+        }
+    }
+
+    printf("Send response with URI\n");
+    send_response(object, &requestInfo->info);
+
+    g_received = 1;
+}
+
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+{
+    printf("##########Received response from remote device #############\n");
+    printf("Uri: %s\n", object->resourceUri);
+    if (CA_IPV4 == object->transportType)
+    {
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
+    }
+    else if (CA_EDR == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+    }
+    else if (CA_LE == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.LE.leMacAddress);
+    }
+    printf("response result : %d\n", responseInfo->result);
+    printf("Data: %s\n", responseInfo->info.payload);
+    printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
+    printf("Token: %s\n", responseInfo->info.token);
+    if (responseInfo->info.options)
+    {
+        uint32_t len = responseInfo->info.numOptions;
+        uint32_t i;
+        for (i = 0; i < len; i++)
+        {
+            printf("Option %d\n", i + 1);
+            printf("ID : %d\n", responseInfo->info.options[i].optionID);
+            printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
+                   responseInfo->info.options[i].optionData);
+        }
+    }
+    printf("############################################################\n");
+    g_received = 1;
+
+    //Check if this has secure communication information
+    if (responseInfo->info.payload)
+    {
+        int securePort = get_secure_information(responseInfo->info.payload);
+        if (0 < securePort) //Set the remote endpoint secure details and send response
+        {
+            printf("This is secure resource...\n");
+        }
+    }
+}
+
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
+{
+    printf("entering send_response\n");
+
+    printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CON     : 0\n");
+    printf("NON     : 1\n");
+    printf("ACK     : 2\n");
+    printf("RESET   : 3\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int messageType = buf[0] - '0';
+    if (0 > messageType || 3 < messageType)
+    {
+        printf("Invalid message type\n");
+        return;
+    }
+
+    int responseCode = 0 ;
+    char responseCodeBuf[MAX_BUF_LEN] = { 0 };
+    if (CA_MSG_RESET != messageType)
+    {
+        printf("\n=============================================\n");
+        printf("\tselect response code\n");
+        printf("EMPTY                    :   0\n");
+        printf("SUCCESS                  : 200\n");
+        printf("CREATED                  : 201\n");
+        printf("DELETED                  : 202\n");
+        printf("BAD_REQ                  : 400\n");
+        printf("BAD_OPT                  : 402\n");
+        printf("NOT_FOUND                : 404\n");
+        printf("INTERNAL_SERVER_ERROR    : 500\n");
+        printf("RETRANSMIT_TIMEOUT       : 504\n");
+        printf("select : ");
+
+        if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
+        {
+            return;
+        }
+        responseCode = atoi(responseCodeBuf);
+    }
+    CAInfo_t responseData = { 0 };
+    responseData.type = messageType;
+    responseData.messageId = (info != NULL) ? info->messageId : 0;
+
+    if(CA_MSG_RESET != messageType)
+    {
+        responseData.token = (info != NULL) ? info->token : NULL;
+        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
+
+        if (endpoint->isSecured)
+        {
+            printf("Sending response on secure communication\n");
+
+            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
+                     g_local_secure_port);
+        }
+        else
+        {
+            printf("Sending response on non-secure communication\n");
+
+            uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
+        }
+    }
+
+    CAResponseInfo_t responseInfo = { 0 };
+    responseInfo.result = responseCode;
+    responseInfo.info = responseData;
+
+    // send response (transportType from remoteEndpoint of request Info)
+    CAResult_t res = CASendResponse(endpoint, &responseInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Send response error\n");
+    }
+    else
+    {
+        printf("Send response success\n");
+    }
+
+    printf("=============================================\n");
+}
+
+int get_secure_information(CAPayload_t payLoad)
+{
+    printf("Entering get_secure_information\n");
+
+    if (!payLoad)
+    {
+        printf("Payload is NULL\n");
+        return -1;
+    }
+
+    char *subString = NULL;
+    if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
+    {
+        printf("This is not secure resource\n");
+        return -1;
+    }
+
+    if (NULL == (subString = strstr(payLoad, "\"port\":")))
+    {
+        printf("This secure resource does not have port information\n");
+        return -1;
+    }
+
+    char *startPos = strstr(subString, ":");
+    if (!startPos)
+    {
+        printf("Parsing failed !\n");
+        return -1;
+    }
+
+    char *endPos = strstr(startPos, "}");
+    if (!endPos)
+    {
+        printf("Parsing failed !\n");
+        return -1;
+    }
+
+    char portStr[4] = {0};
+    memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
+
+    printf("secured port is: %s\n", portStr);
+    return atoi(portStr);
+}
+
+void get_resource_uri(char *URI, char *resourceURI, int length)
+{
+    char *startPos = URI;
+    char *temp = NULL;
+    if (NULL != (temp = strstr(URI, "://")))
+    {
+        startPos = strchr(temp + 3, '/');
+        if (!startPos)
+        {
+            printf("Resource URI is missing\n");
+            return;
+        }
+    }
+
+    char *endPos = strchr(startPos, '?');
+    if (!endPos)
+    {
+        endPos = URI + strlen(URI);
+    }
+    endPos -= 1;
+
+    if (endPos - startPos <= length)
+    {
+        memcpy(resourceURI, startPos + 1, endPos - startPos);
+    }
+
+    printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
+}
+
+CAResult_t get_network_type()
+{
+    char buf[MAX_BUF_LEN] = { 0 };
+
+    printf("\n=============================================\n");
+    printf("\tselect network type\n");
+    printf("IPv4 : 0\n");
+    printf("BT : 2\n");
+    printf("LE : 3\n");
+    printf("select : ");
+
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return CA_NOT_SUPPORTED ;
+    }
+
+    int number = buf[0] - '0';
+
+    number = (number < 0 || number > 3) ? 0 : 1 << number;
+
+    if (!(number & 0xf))
+    {
+        return CA_NOT_SUPPORTED;
+    }
+    if (number & CA_IPV4)
+    {
+        g_selected_nw_type = CA_IPV4;
+        return CA_STATUS_OK;
+    }
+    if (number & CA_EDR)
+    {
+        g_selected_nw_type = CA_EDR;
+        return CA_STATUS_OK;
+    }
+    if (number & CA_LE)
+    {
+        g_selected_nw_type = CA_LE;
+        return CA_STATUS_OK;
+    }
+
+    printf("\n=============================================\n");
+
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t get_input_data(char *buf, int32_t length)
+{
+    if (!fgets(buf, length, stdin))
+    {
+        printf("fgets error\n");
+        return CA_STATUS_FAILED;
+    }
+
+    char *p = NULL;
+    if ( (p = strchr(buf, '\n')) != NULL )
+    {
+        *p = '\0';
+    }
+
+    return CA_STATUS_OK;
+}
diff --git a/resource/csdk/connectivity/samples/linux/threadpool/Makefile b/resource/csdk/connectivity/samples/linux/threadpool/Makefile
deleted file mode 100644 (file)
index 74abc3d..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-CC=gcc
-ROOT_DIR = ../../..
-INC_DIR := -I$(ROOT_DIR)/api -I$(ROOT_DIR)/inc -I$(ROOT_DIR)/common/inc
-SRC_DIR := $(ROOT_DIR)/common/src/
-CFLAGS = -Wall
-COMPILEFLAGS = `pkg-config --cflags glib-2.0`
-LDFLAGS = `pkg-config --libs glib-2.0` 
-
-OUT = threadpool
-
-all: 
-       $(CC) $(CFLAGS) $(INC_DIR) $(COMPILEFLAGS) $(SRC_DIR)uthreadpool.c $(SRC_DIR)umutex.c $(SRC_DIR)/../logger.c main.c -o $(OUT) $(LDFLAGS)
-clean:
-       rm -f $(OUT)
index 3b83fa0..2e90d8c 100644 (file)
@@ -1,13 +1,34 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
 #include <stdio.h>
 #include <stdlib.h>
 
-#include "uthreadpool.h"
-#include "umutex.h"
+#include "cathreadpool.h"
+#include "camutex.h"
 
-u_thread_pool_t gThreadPoolHandle = NULL;
+ca_thread_pool_t g_threadPoolHandle = NULL;
 
-u_mutex gMutex = NULL;
-u_cond gCond = NULL;
+ca_mutex g_mutex = NULL;
+ca_cond g_cond = NULL;
+bool g_condFlag = false;
 
 void task(void *data)
 {
@@ -15,20 +36,22 @@ void task(void *data)
 
     //Signal the condition that task has been completed
     printf("[TASK] Signaling the condition\n");
-    u_cond_signal(gCond);
+    ca_mutex_lock(g_mutex);
+    g_condFlag = true;
+    ca_cond_signal(g_cond);
+    ca_mutex_unlock(g_mutex);
 }
 
 void testThreadPool(void)
 {
-    char *string = "Test glib thread pool";
+    char *string = "Test thread pool";
 
     //Initialize the mutex
     printf("[testThreadPool] Initializing mutex\n");
-    u_mutex_init();
 
     //Initialize the thread pool
     printf("[testThreadPool] Initializing thread pool\n");
-    if (CA_STATUS_OK != u_thread_pool_init(2, &gThreadPoolHandle))
+    if (CA_STATUS_OK != ca_thread_pool_init(2, &g_threadPoolHandle))
     {
         printf("thread_pool_init failed!\n");
         return;
@@ -36,52 +59,58 @@ void testThreadPool(void)
 
     //Create the mutex
     printf("[testThreadPool] Creating mutex\n");
-    gMutex = u_mutex_new();
-    if (NULL == gMutex)
+    g_mutex = ca_mutex_new();
+    if (NULL == g_mutex)
     {
         printf("[testThreadPool] Failed to create mutex!\n");
+        ca_thread_pool_free(g_threadPoolHandle);
         return;
     }
 
     //Create the condition
     printf("[testThreadPool] Creating Condition\n");
-    gCond = u_cond_new();
-    if (NULL == gCond)
+    g_cond = ca_cond_new();
+    if (NULL == g_cond)
     {
         printf("[testThreadPool] Failed to create condition!\n");
-
-        u_mutex_free(gMutex);
+        ca_mutex_free(g_mutex);
+        ca_thread_pool_free(g_threadPoolHandle);
         return;
     }
 
     //Lock the mutex
     printf("[testThreadPool] Locking the mutex\n");
-    u_mutex_lock(gMutex);
+    ca_mutex_lock(g_mutex);
 
+    g_condFlag = false;
     //Add task to thread pool
     printf("[testThreadPool] Adding the task to thread pool\n");
-    if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPoolHandle, task, (void *) string))
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, task, (void *) string))
     {
         printf("[testThreadPool] thread_pool_add_task failed!\n");
-
-        u_mutex_unlock(gMutex);
-        u_mutex_free(gMutex);
-        u_cond_free(gCond);
+        ca_thread_pool_free(g_threadPoolHandle);
+        ca_mutex_unlock(g_mutex);
+        ca_mutex_free(g_mutex);
+        ca_cond_free(g_cond);
         return;
     }
 
     //Wait for the task to be executed
     printf("[testThreadPool] Waiting for the task to be completed\n");
-    u_cond_wait(gCond, gMutex);
+
+    while (!g_condFlag)
+    {
+        ca_cond_wait(g_cond, g_mutex);
+    }
 
     //Unlock the mutex
     printf("[testThreadPool] Got the signal and unlock the mutex\n");
-    u_mutex_unlock(gMutex);
+    ca_mutex_unlock(g_mutex);
 
     printf("[testThreadPool] Task is completed and terminating threadpool\n");
-    u_mutex_free(gMutex);
-    u_cond_free(gCond);
-    u_thread_pool_free(gThreadPoolHandle);
+    ca_cond_free(g_cond);
+    ca_mutex_free(g_mutex);
+    ca_thread_pool_free(g_threadPoolHandle);
 
     printf("Exiting from testThreadPool\n");
 }
@@ -101,21 +130,30 @@ static void startTesting(void)
     while (1)
     {
         int choice = -1;
-        scanf("%d", &choice);
-
-        switch (choice)
+        if(scanf("%d", &choice) == 1)
+        {
+            switch (choice)
+            {
+                case 0:
+                    printf("Terminating test.\n");
+                    return;
+                case 1:
+                    testThreadPool();
+                    break;
+                default:
+                    printf("Invalid input.\n");
+                    menu();
+                    break;
+            }
+        }
+        else
         {
-            case 0:
-                printf("Terminating test.....\n");
-                return;
-            case 1:
-                testThreadPool();
-                break;
-            default:
-                printf("Invalid input...\n");
-                menu();
-                break;
+            printf("Invalid input.\n");
+            menu();
         }
+
+        // clear input buffer
+        while (getchar() != '\n');
     }
 }
 
@@ -125,3 +163,4 @@ int main()
     startTesting();
     return 0;
 }
+
diff --git a/resource/csdk/connectivity/samples/tizen/README.txt b/resource/csdk/connectivity/samples/tizen/README.txt
new file mode 100644 (file)
index 0000000..a5e4283
--- /dev/null
@@ -0,0 +1,53 @@
+Procedure to Execute Sample App:
+================================
+    1) Copy the generated rpm(com-oic-ca-sample-0.1-1.armv7l.rpm) to Tizen Device
+       (say /opt/usr/media/xxx/)
+    2) sdb shell
+    3) su
+    4) cd  /opt/usr/media/xxx/
+
+    5) change-booting-mode.sh --update
+
+    6) Install casample(console app). It contains Interface API libs and OIC-CORE Libs
+        i) rpm -Uvh com-oic-ca-sample-0.1-1.armv7l.rpm --force --nodeps
+
+    7) RPM will be installed in "/usr/apps/"
+       Execute the sample app by below commands
+        i) cd /usr/apps/com.oic.ca.sample/bin
+        ii) ./ca_sample (for CA Sample)
+
+Apply smack rule[ONLY for WIFI]
+===============================
+
+    1) After installing the RPMs, apply the following smack rule
+        a) chsmack -a "net-config" /usr/apps/com.oic.ca.sample/bin/ca_sample
+        b) chsmack -e "net-config" /usr/apps/com.oic.ca.sample/bin/ca_sample
+
+    Note: EDR adapter will give permission issues if these rules are applied.
+          So to test EDR adapter, delete the "/usr/apps/com.oic.ca.sample" folder
+          and again install the RPMs.
+
+Install Dependent RPMS(Only for EDR Adapter Testing)
+====================================================
+
+    1) In su(super user) mode, install Bluetooth related RPMs present in
+    "connectivity/lib/tizen/edr/rpms" on Tizen v2.3 mobile device
+    (Currently only SM Z910F Device is supported).
+    2) Install the Sample as given above in "Procedure to Execute Sample App"
+
+Install Dependent RPMS(Only for BLE Adapter Testing)
+====================================================
+
+    1) Flash the system image present in connectivity/lib/tizen/ble/image/ folder on SM Z910F Tizen v2.3
+    2) In su(super user) mode, Install Bluetooth related rpms Present in connectivity/lib/tizen/ble/rpms on
+    Tizen v2.3 mobile device (Currently only SM Z910F Device is supported)
+    3) Install the Sample as given above in "Procedure to Execute Sample App" [ Till Step 6 ]
+    4) Open another sdb shell, in su (super user) mode follow the below steps:
+            (i)   cd /var/lib/bluetooth
+            (ii)  Turn off Bluetooth in the device
+            (iii) rm -rf *
+            (iv)  Run the command ./usr/lib/bluetooth/bluetoothd -ndE &. for OIC Server device and
+            run the command ./usr/lib/bluetooth/bluetoothd -nd &. for OIC Client device.
+            (v)   Turn on the Bluetooth.
+    5) Run the sample as given in Step 8 of "Procedure to Execute Sample App"
+
diff --git a/resource/csdk/connectivity/samples/tizen/SConscript b/resource/csdk/connectivity/samples/tizen/SConscript
new file mode 100644 (file)
index 0000000..be3619b
--- /dev/null
@@ -0,0 +1,240 @@
+##
+# This script includes generic build options:
+#    release/debug, target os, target arch, cross toolchain, build environment etc
+##
+import os
+import platform
+
+# Map of host os and allowed target os (host: allowed target os)
+host_target_map = {
+               'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
+               'windows': ['windows', 'winrt', 'android', 'arduino', 'tizen'],
+               'darwin': ['darwin', 'ios', 'android', 'arduino'],
+               }
+
+# Map of os and allowed archs (os: allowed archs)
+os_arch_map = {
+               'linux': ['x86', 'x86_64', 'arm', 'arm64'],
+               'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
+               'windows': ['x86', 'amd64', 'arm'],
+               'winrt': ['arm'],
+               'darwin': ['i386', 'x86_64'],
+               'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
+               'arduino': ['avr', 'arm'],
+                'yocto': ['x86', 'x86_64'],
+               'tizen': ['armv7'],
+               }
+
+host = platform.system().lower()
+
+if not host_target_map.has_key(host):
+       print "\nError: Current system (%s) isn't supported\n" % host
+       Exit(1)
+
+######################################################################
+# Get build options (the optins from command line)
+######################################################################
+target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
+
+if target_os not in host_target_map[host]:
+       print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
+       Exit(1)
+
+default_arch = platform.machine()
+if default_arch not in os_arch_map[target_os]:
+       default_arch = os_arch_map[target_os][0].lower()
+
+target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
+
+######################################################################
+# Common build options (release, target os, target arch)
+######################################################################
+help_vars = Variables()
+help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
+help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
+help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'IP', 'BT', 'BLE']))
+help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
+help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
+
+######################################################################
+# Platform(build target) specific options: SDK/NDK & toolchain
+######################################################################
+targets_support_cc = ['linux', 'arduino', 'tizen']
+
+if target_os in targets_support_cc:
+       # Set cross compile toolchain
+       help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
+       help_vars.Add(PathVariable('TC_PATH',
+                       'Toolchain path (Generally only be required for cross-compiling)',
+                       os.environ.get('TC_PATH')))
+
+if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
+       env = Environment(variables = help_vars,
+                       tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
+                       )
+else:
+       env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os)
+
+Help(help_vars.GenerateHelpText(env))
+
+tc_set_msg = '''
+************************************ Warning **********************************
+*   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
+* toolchain, if it isn't what you expect you should unset it, otherwise it may*
+* cause inexplicable errors.                                                  *
+*******************************************************************************
+'''
+
+if target_os in targets_support_cc:
+       prefix = env.get('TC_PREFIX')
+       tc_path = env.get('TC_PATH')
+       if prefix:
+               env.Replace(CC = prefix + 'gcc')
+               env.Replace(CXX = prefix + 'g++')
+               env.Replace(AR = prefix + 'ar')
+               env.Replace(AS = prefix + 'as')
+               env.Replace(LINK = prefix + 'ld')
+               env.Replace(RANLIB = prefix + 'ranlib')
+
+       if tc_path:
+               env.PrependENVPath('PATH', tc_path)
+               sys_root = os.path.abspath(tc_path + '/../')
+               env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
+               env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
+
+       if prefix or tc_path:
+               print tc_set_msg
+
+# Ensure scons be able to change its working directory
+env.SConscriptChdir(1)
+
+# Set the source directory and build directory
+#   Source directory: 'dir'
+#   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
+#
+# You can get the directory as following:
+#   env.get('SRC_DIR')
+#   env.get('BUILD_DIR')
+
+def __set_dir(env, dir):
+       if not os.path.exists(dir + '/SConstruct'):
+               print '''
+*************************************** Error *********************************
+* The directory(%s) seems isn't a source code directory, no SConstruct file is
+* found. *
+*******************************************************************************
+''' % dir
+               Exit(1)
+
+       if env.get('RELEASE'):
+               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
+       else:
+               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
+       env.VariantDir(build_dir, dir, duplicate=0)
+
+       env.Replace(BUILD_DIR = build_dir)
+       env.Replace(SRC_DIR = dir)
+
+def __src_to_obj(env, src, home = ''):
+       obj = env.get('BUILD_DIR') + src.replace(home, '')
+       if env.get('OBJSUFFIX'):
+               obj += env.get('OBJSUFFIX')
+       return env.Object(obj, src)
+
+def __install(ienv, targets, name):
+       i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+       Alias(name, i_n)
+       env.AppendUnique(TS = [name])
+
+def __append_target(ienv, target):
+       env.AppendUnique(TS = [target])
+
+def __print_targets(env):
+       Help('''
+===============================================================================
+Targets:\n    ''')
+       for t in env.get('TS'):
+               Help(t + ' ')
+       Help('''
+\nDefault all targets will be built. You can specify the target to build:
+
+    $ scons [options] [target]
+===============================================================================
+''')
+
+env.AddMethod(__set_dir, 'SetDir')
+env.AddMethod(__print_targets, 'PrintTargets')
+env.AddMethod(__src_to_obj, 'SrcToObj')
+env.AddMethod(__append_target, 'AppendTarget')
+env.AddMethod(__install, 'InstallTarget')
+env.SetDir(env.GetLaunchDir())
+env['ROOT_DIR']=env.GetLaunchDir()
+
+Export('env')
+
+######################################################################
+# Link scons to Yocto cross-toolchain ONLY when target_os is yocto
+######################################################################
+if target_os == "yocto":
+    '''
+    This code injects Yocto cross-compilation tools+flags into scons'
+    build environment in order to invoke the relevant tools while
+    performing a build.
+    '''
+    import os.path
+    try:
+        CC = os.environ['CC']
+        target_prefix = CC.split()[0]
+        target_prefix = target_prefix[:len(target_prefix)-3]
+        tools = {"CC" : target_prefix+"gcc",
+                "CXX" : target_prefix+"g++",
+                "AS" : target_prefix+"as",
+                "LD" : target_prefix+"ld",
+                "GDB" : target_prefix+"gdb",
+                "STRIP" : target_prefix+"strip",
+                "RANLIB" : target_prefix+"ranlib",
+                "OBJCOPY" : target_prefix+"objcopy",
+                "OBJDUMP" : target_prefix+"objdump",
+                "AR" : target_prefix+"ar",
+                "NM" : target_prefix+"nm",
+                "M4" : "m4",
+                "STRINGS": target_prefix+"strings"}
+        PATH = os.environ['PATH'].split(os.pathsep)
+        for tool in tools:
+            if tool in os.environ:
+                for path in PATH:
+                    if os.path.isfile(os.path.join(path, tools[tool])):
+                        env[tool] = os.path.join(path, os.environ[tool])
+                        break
+    except:
+        print "ERROR in Yocto cross-toolchain environment"
+        Exit(1)
+    '''
+    Now reset TARGET_OS to linux so that all linux specific build configurations
+    hereupon apply for the entirety of the build process.
+    '''
+    env['TARGET_OS'] = 'linux'
+    '''
+    We want to preserve debug symbols to allow BitBake to generate both DEBUG and
+    RELEASE packages for OIC.
+    '''
+    env['CCFLAGS'].append('-g')
+    Export('env')
+else:
+    '''
+    If target_os is not Yocto, continue with the regular build process
+    '''
+    # Load config of target os
+    env.SConscript(target_os + '/SConscript')
+
+# Delete the temp files of configuration
+if env.GetOption('clean'):
+       dir = env.get('SRC_DIR')
+
+       if os.path.exists(dir + '/config.log'):
+               Execute(Delete(dir + '/config.log'))
+               Execute(Delete(dir + '/.sconsign.dblite'))
+               Execute(Delete(dir + '/.sconf_temp'))
+
+Return('env')
+
diff --git a/resource/csdk/connectivity/samples/tizen/SConstruct b/resource/csdk/connectivity/samples/tizen/SConstruct
new file mode 100644 (file)
index 0000000..bc860fb
--- /dev/null
@@ -0,0 +1,23 @@
+##
+# The main build script
+#
+##
+
+# Load common build config
+# Load common build config
+SConscript('SConscript')
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+
+print "Given Transport is %s" % transport
+print "Given OS is %s" % target_os
+print "Secured %s" % env.get('SECURED')
+
+if target_os == 'tizen':
+        SConscript('scons/SConscript')
+else:
+       print "Given platform is not supported"
+
diff --git a/resource/csdk/connectivity/samples/tizen/casample.c b/resource/csdk/connectivity/samples/tizen/casample.c
new file mode 100644 (file)
index 0000000..3052feb
--- /dev/null
@@ -0,0 +1,1432 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <glib.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdbool.h>
+#include <pthread.h>
+#include "cacommon.h"
+#include "cainterface.h"
+
+#ifdef __WITH_DTLS__
+#include "ocsecurityconfig.h"
+#endif
+/**
+ * @def MAX_BUF_LEN
+ * @brief maximum buffer length
+ */
+#define MAX_BUF_LEN 1024
+
+/**
+ * @def MAX_OPT_LEN
+ * @brief maximum option length
+ */
+#define MAX_OPT_LEN 16
+
+/**
+ * @def PORT_LENGTH
+ * @brief maximum port length
+ */
+#define PORT_LENGTH 5
+
+/**
+ * @def SECURE_DEFAULT_PORT
+ * @brief default secured port
+ */
+#define SECURE_DEFAULT_PORT 5684
+
+#define RESOURCE_URI_LENGTH 14
+
+/**
+ * @def RS_IDENTITY
+ * @brief
+ */
+#define IDENTITY     ("1111111111111111")
+/* @def RS_CLIENT_PSK
+ * @brief
+ */
+#define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
+
+static GMainLoop *g_mainloop = NULL;
+pthread_t thread;
+
+int g_received;
+uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
+CATransportType_t g_selected_nw_type = CA_IPV4;
+const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
+
+char get_menu();
+void process();
+CAResult_t get_network_type();
+CAResult_t get_input_data(char *buf, int32_t length);
+
+void start_listening_server();
+void start_discovery_server();
+void find_resource();
+void send_request();
+void send_request_all();
+void advertise_resource();
+void send_notification();
+void select_network();
+void unselect_network();
+void handle_request_response();
+void find_fixed_resource();
+void get_network_info();
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
+void get_resource_uri(char *URI, char *resourceURI, int length);
+int get_secure_information(CAPayload_t payLoad);
+
+static CAToken_t g_last_request_token = NULL;
+static const char SECURE_COAPS_PREFIX[] = "coaps://";
+static const char SECURE_INFO_DATA[] =
+    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+    "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[] =
+    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+    "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
+
+#ifdef __WITH_DTLS__
+static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
+
+void clearDtlsCredentialInfo()
+{
+    printf("clearDtlsCredentialInfo IN\n");
+    if (pskCredsBlob)
+    {
+        // Initialize sensitive data to zeroes before freeing.
+        if (pskCredsBlob->creds)
+        {
+            memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+            free(pskCredsBlob->creds);
+        }
+
+        memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
+        free(pskCredsBlob);
+        pskCredsBlob = NULL;
+    }
+    printf("clearDtlsCredentialInfo OUT\n");
+}
+
+// Internal API. Invoked by CA stack to retrieve credentials from this module.
+void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+{
+    printf("CAGetDtlsPskCredentials IN\n");
+
+    if(NULL == credInfo)
+    {
+        printf("Invalid credential container");
+        return;
+    }
+
+    *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == *credInfo)
+    {
+        printf("Failed to allocate credential blob.");
+        return;
+    }
+
+    int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
+    (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
+    if (NULL == (*credInfo)->creds)
+    {
+        printf("Failed to allocate credentials.");
+        free(*credInfo);
+        *credInfo = NULL;
+        return;
+    }
+
+    memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
+    (*credInfo)->num = pskCredsBlob->num;
+    memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
+
+    printf("CAGetDtlsPskCredentials OUT\n");
+}
+
+CAResult_t SetCredentials()
+{
+    printf("SetCredentials IN\n");
+    pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+    if (NULL == pskCredsBlob)
+    {
+        printf("Memory allocation failed!\n");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+
+    pskCredsBlob->num = 1;
+
+    pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+    if (NULL == pskCredsBlob->creds)
+    {
+        printf("Memory allocation failed!\n");
+        free(pskCredsBlob);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
+    memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
+
+    printf("SetCredentials OUT\n");
+    return CA_STATUS_OK;
+}
+#endif
+
+void GMainLoopThread()
+{
+    g_main_loop_run(g_mainloop);
+}
+
+CAResult_t Initialize()
+{
+    g_mainloop = g_main_loop_new(NULL, FALSE);
+    if(!g_mainloop)
+    {
+        printf("g_main_loop_new failed\n");
+        return CA_STATUS_FAILED;
+    }
+
+    int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
+    if (result < 0)
+    {
+        printf("pthread_create failed in initialize\n");
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t res = CAInitialize();
+    if (res != CA_STATUS_OK)
+    {
+        printf("CAInitialize fail\n");
+    }
+    return res;
+}
+
+int main()
+{
+    int ret = system("clear");
+    // shell invoke error: 127, others: -1
+    if (127 == ret || -1 == ret)
+    {
+        printf("Terminal Clear Error: %d\n", ret);
+    }
+
+    printf("=============================================\n");
+    printf("\t\tsample main\n");
+    printf("=============================================\n");
+
+    CAResult_t res = Initialize();
+    if (CA_STATUS_OK != res)
+    {
+        printf("Initialization is  failed\n");
+        return -1;
+    }
+
+    /*
+     * Read DTLS PSK credentials from persistent storage and
+     * set in the OC stack.
+     */
+#ifdef __WITH_DTLS__
+    res = SetCredentials();
+    if (CA_STATUS_OK != res)
+    {
+        printf("SetCredentials failed\n");
+        return -1;
+    }
+
+    res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Set credential handler fail\n");
+        return -1;
+    }
+#endif
+
+    // set handler.
+    CARegisterHandler(request_handler, response_handler);
+
+    process();
+
+    CADestroyToken(g_last_request_token);
+
+    CATerminate();
+#ifdef __WITH_DTLS__
+    clearDtlsCredentialInfo();
+#endif
+    return 0;
+}
+
+void process()
+{
+    while (1)
+    {
+        char menu = get_menu();
+
+        switch (menu)
+        {
+            case 'm': // menu
+            case 'M':
+                break;
+
+            case 'q': // quit
+            case 'Q':
+                printf("quit..!!\n");
+                return;
+
+            case 's': // start server
+            case 'S':
+                start_listening_server();
+                break;
+
+            case 't': // send request
+            case 'T':
+                send_request_all();
+                break;
+
+            case 'c': // start client
+            case 'C':
+                start_discovery_server();
+                break;
+
+            case 'f': // find resource
+            case 'F':
+                find_resource();
+                break;
+
+            case 'r': // send request
+            case 'R':
+                send_request();
+                break;
+
+            case 'a': // advertise resource
+            case 'A':
+                advertise_resource();
+                break;
+
+            case 'b': // send notification
+            case 'B':
+                send_notification();
+                break;
+
+            case 'n': // select network
+            case 'N':
+                select_network();
+                break;
+
+            case 'x': // unselect network
+            case 'X':
+                unselect_network();
+                break;
+
+            case 'h': // handle request response
+            case 'H':
+                handle_request_response();
+                break;
+
+            case 'y':
+            case 'Y':
+                while (1)
+                {
+                    g_received = 0;
+                    find_fixed_resource();
+                    while (g_received == 0)
+                    {
+                        sleep(1);
+                        handle_request_response();
+
+                    }
+                }
+                break;
+
+            case 'w':
+            case 'W':
+                g_received = 0;
+                start_discovery_server();
+                //send_secure_request();
+                while (g_received == 0)
+                {
+                    sleep(1);
+                    handle_request_response();
+                }
+                break;
+
+            case 'z':
+            case 'Z':
+                start_listening_server();
+                while (1)
+                {
+                    sleep(1);
+                    handle_request_response();
+                }
+                break;
+
+            case 'g': // get network information
+            case 'G':
+                get_network_info();
+                break;
+
+            default:
+                printf("Not supported menu!!\n");
+                break;
+        }
+    }
+
+}
+
+void start_listening_server()
+{
+    printf("Start listening server!!\n");
+
+    CAResult_t res = CAStartListeningServer();
+    if (CA_STATUS_OK != res)
+    {
+        printf("Start listening server fail, error code : %d\n", res);
+    }
+    else
+    {
+        printf("Start listening server success\n");
+    }
+}
+
+void start_discovery_server()
+{
+    printf("Start discovery client!!\n");
+
+    CAResult_t res = CAStartDiscoveryServer();
+    if (CA_STATUS_OK != res)
+    {
+        printf("Start discovery client fail, error code : %d\n", res);
+    }
+    else
+    {
+        printf("Start discovery client success\n");
+    }
+}
+
+void find_fixed_resource()
+{
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!");
+        return;
+    }
+
+    printf("Generated token %s\n", token);
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    strcpy(buf, "/a/light");
+
+    res = CAFindResource(buf, token, tokenLength);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Find resource error : %d\n", res);
+    }
+    else
+    {
+        printf("Find resource to %s URI\n", buf);
+    }
+
+    // delete token
+    CADestroyToken(token);
+
+    printf("=============================================\n");
+}
+
+void find_resource()
+{
+    printf("\n=============================================\n");
+    printf("ex) /a/light\n");
+    printf("reference uri : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!\n");
+        return;
+    }
+
+    printf("Generated token %s\n", token);
+
+    res = CAFindResource(buf, token, tokenLength);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Find resource error : %d\n", res);
+        CADestroyToken(token);
+    }
+    else
+    {
+        printf("Find resource to %s URI\n", buf);
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
+    }
+
+    printf("=============================================\n");
+}
+
+void send_request()
+{
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    printf("Do you want to send secure request ?.... enter (0/1): ");
+
+    char secureRequest[MAX_BUF_LEN] = {0};
+    if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    if (strcmp(secureRequest, "1") == 0)
+    {
+        printf("Enter the URI like below....\n");
+        printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
+    }
+    else if (strcmp(secureRequest, "0") == 0)
+    {
+        printf("Enter the URI like below....\n");
+        printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
+        printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
+    }
+    else
+    {
+        printf("Input data is wrong value\n");
+        return;
+    }
+
+    char uri[MAX_BUF_LEN] = {'\0'};
+    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res || !endpoint)
+    {
+        printf("Failed to create remote endpoint, error code : %d\n", res);
+        return;
+    }
+
+    printf("\n=============================================\n");
+    printf("0:CON, 1:NON\n");
+    printf("select message type : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error, error code : %d\n", res);
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    printf("Generated token %s\n", token);
+
+    // extract relative resourceuri from give uri
+    printf("URI : %s\n", uri);
+
+    char resourceURI[15] = {0};
+    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
+
+    // create request data
+    CAInfo_t requestData = { 0 };
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+
+    if (strcmp(secureRequest, "1") == 0)
+    {
+        uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+        if (NULL == requestData.payload)
+        {
+            printf("Memory allocation fail\n");
+            CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
+            return;
+        }
+        snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
+    }
+    else
+    {
+        uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+        requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+        if (NULL == requestData.payload)
+        {
+            printf("Memory allocation fail\n");
+            CADestroyRemoteEndpoint(endpoint);
+            CADestroyToken(token);
+            return;
+        }
+        snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
+    }
+    requestData.type = msgType;
+
+    CARequestInfo_t requestInfo = { 0 };
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    // send request
+    res = CASendRequest(endpoint, &requestInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not send request : %d\n", res);
+    }
+
+    //destroy token
+    CADestroyToken(token);
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+    free(requestData.payload);
+
+
+    printf("=============================================\n");
+}
+
+void send_request_all()
+{
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    printf("\n=============================================\n");
+    printf("ex) /a/light\n");
+    printf("resource uri : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Create remote endpoint error, error code: %d\n", res);
+        return;
+    }
+
+    CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+    if (NULL == group)
+    {
+        printf("Memory allocation failed!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+    group->transportType = endpoint->transportType;
+    group->resourceUri = endpoint->resourceUri;
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        free(group);
+        return;
+    }
+
+    printf("generated token %s\n", token);
+
+    CAInfo_t requestData = {CA_MSG_RESET};
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+    requestData.payload = "Temp Json Payload";
+    requestData.type = CA_MSG_NONCONFIRM;
+
+    CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    // send request all
+    res = CASendRequestToAll(group, &requestInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not send request to all\n");
+        CADestroyToken(token);
+    }
+    else
+    {
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
+    }
+
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+    free(group);
+
+    printf("=============================================\n");
+}
+
+void advertise_resource()
+{
+    printf("\n=============================================\n");
+    printf("uri : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    char optionNumBuf[MAX_BUF_LEN] = { 0 };
+    char optionData[MAX_OPT_LEN] = { 0 } ;
+
+    printf("Option Num : ");
+    if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
+    {
+        return;
+    }
+    int optionNum = atoi(optionNumBuf);
+
+    CAHeaderOption_t * headerOpt = (CAHeaderOption_t *)
+            calloc(1, optionNum * sizeof(CAHeaderOption_t));
+    if (NULL == headerOpt)
+    {
+        printf("Memory allocation failed!\n");
+        return;
+    }
+
+    int i;
+    for (i = 0; i < optionNum; i++)
+    {
+        char getOptionID[MAX_BUF_LEN] = { 0 } ;
+
+        printf("[%d] Option ID : ", i + 1);
+        if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
+        {
+            free(headerOpt);
+            return;
+        }
+        int optionID = atoi(getOptionID);
+
+        headerOpt[i].optionID = optionID;
+
+        printf("[%d] Option Data : ", i + 1);
+        if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
+        {
+            free(headerOpt);
+            return;
+        }
+
+        memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
+        printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
+
+        headerOpt[i].optionLength = (uint16_t) strlen(optionData);
+    }
+    printf("\n=============================================\n");
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    CAResult_t res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!\n");
+        free(headerOpt);
+        return;
+    }
+
+    printf("Generated token %s\n", token);
+
+    res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Could not start advertise resource\n");
+        CADestroyToken(token);
+    }
+    else
+    {
+        CADestroyToken(g_last_request_token);
+        g_last_request_token = token;
+    }
+
+    free(headerOpt);
+}
+
+void send_notification()
+{
+    CAResult_t res = get_network_type();
+    if (CA_STATUS_OK != res)
+    {
+        return;
+    }
+
+    printf("\n=============================================\n");
+    printf("Enter the URI like below....\n");
+    printf("10.11.12.13:4545/resource_uri ( for IP )\n");
+    printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
+    printf("uri : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CON     : 0\n");
+    printf("NON     : 1\n");
+    printf("select : ");
+
+    char messageTypeBuf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int messageType = messageTypeBuf[0] - '0';
+
+    switch(messageType)
+    {
+        case 0:
+                printf("CONFIRM messagetype is selected\n");
+                break;
+        case 1:
+                printf("NONCONFIRM messagetype is selected\n");
+                break;
+        default:
+                printf("Invalid Selection\n");
+                return;
+    }
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Create remote endpoint error, error code: %d\n", res);
+        return;
+    }
+
+    // create token
+    CAToken_t token = NULL;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+
+    res = CAGenerateToken(&token, tokenLength);
+    if ((CA_STATUS_OK != res) || (!token))
+    {
+        printf("Token generate error!!\n");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+
+    printf("Generated token %s\n", token);
+
+    CAInfo_t respondData = { 0 };
+    respondData.token = token;
+    respondData.tokenLength = tokenLength;
+    respondData.payload = "Temp Notification Data";
+    respondData.type = messageType;
+
+    CAResponseInfo_t responseInfo = { 0 };
+    responseInfo.result = CA_SUCCESS;
+    responseInfo.info = respondData;
+
+    // send notification
+    res = CASendNotification(endpoint, &responseInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Send notification error, error code: %d\n", res);
+    }
+    else
+    {
+        printf("Send notification success\n");
+    }
+
+    // destroy token
+    CADestroyToken(token);
+    // destroy remote endpoint
+    CADestroyRemoteEndpoint(endpoint);
+
+    printf("\n=============================================\n");
+}
+
+void select_network()
+{
+    printf("\n=============================================\n");
+    printf("\tselect network\n");
+    printf("IPv4 : 0\n");
+    printf("EDR : 2\n");
+    printf("LE : 3\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int number = buf[0] - '0';
+
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
+
+    CAResult_t res = CASelectNetwork(1 << number);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Select network error\n");
+        g_selected_nw_type = 1 << number;
+    }
+    else
+    {
+        printf("Select network success\n");
+    }
+
+    printf("=============================================\n");
+}
+
+void unselect_network()
+{
+    printf("\n=============================================\n");
+    printf("\tunselect enabled network\n");
+    printf("IPv4 : 0\n");
+    printf("EDR : 2\n");
+    printf("LE : 3\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int number = buf[0] - '0';
+
+    if (number < 0 || number > 3)
+    {
+        printf("Invalid network type\n");
+        return;
+    }
+
+    CAResult_t res = CAUnSelectNetwork(1 << number);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Unselect network error\n");
+    }
+    else
+    {
+        printf("Unselect network success\n");
+    }
+
+    printf("=============================================\n");
+}
+
+char get_menu()
+{
+    printf("\n=============================================\n");
+    printf("\t\tMenu\n");
+    printf("\ts : start server\n");
+    printf("\tc : start client\n");
+    printf("\tf : find resource\n");
+    printf("\tr : send request\n");
+    printf("\tt : send request to all\n");
+    printf("\ta : advertise resource\n");
+    printf("\tb : send notification\n");
+    printf("\tn : select network\n");
+    printf("\tx : unselect network\n");
+    printf("\tg : get network information\n");
+    printf("\th : handle request response\n");
+    printf("\ty : run static client\n");
+    printf("\tz : run static server\n");
+    printf("\tw : send secure request\n");
+    printf("\tq : quit\n");
+    printf("=============================================\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        printf("Failed to get input data\n");
+    }
+
+    return buf[0];
+}
+
+void handle_request_response()
+{
+    printf("Handle_request_response\n");
+
+    CAResult_t res = CAHandleRequestResponse();
+    if (CA_STATUS_OK != res)
+    {
+        printf("Handle request error, error code: %d\n", res);
+    }
+    else
+    {
+        printf("Handle request success\n");
+    }
+}
+
+void get_network_info()
+{
+    CALocalConnectivity_t *tempInfo = NULL;
+    uint32_t tempSize = 0;
+
+    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+    if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
+    {
+        printf("Network not connected\n");
+        free(tempInfo);
+        return;
+    }
+
+    printf("################## Network Information #######################\n");
+    printf("Network info total size is %d\n\n", tempSize);
+
+    int index;
+    for (index = 0; index < tempSize; index++)
+    {
+        printf("Type: %d\n", tempInfo[index].type);
+        if (CA_IPV4 == tempInfo[index].type)
+        {
+            printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
+            printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
+        }
+        else if (CA_EDR == tempInfo[index].type)
+        {
+            printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
+        }
+        printf("Secured: %d\n\n", tempInfo[index].isSecured);
+
+        if (tempInfo[index].isSecured)
+        {
+            g_local_secure_port = tempInfo[index].addressInfo.IP.port;
+            printf("Secured: in global %d\n\n", g_local_secure_port);
+        }
+    }
+
+    free(tempInfo);
+    printf("##############################################################");
+}
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+{
+    if (NULL == object || NULL == requestInfo)
+    {
+        printf("Input parameter is NULL\n");
+        return;
+    }
+
+    if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
+        && (strncmp(g_last_request_token, requestInfo->info.token,
+                    requestInfo->info.tokenLength) == 0))
+    {
+        printf("Token is same. received request of it's own. skip.. \n");
+        return;
+    }
+
+    printf("##########received request from remote device #############\n");
+    printf("Uri: %s\n", object->resourceUri);
+    if (CA_IPV4 == object->transportType)
+    {
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
+    }
+    else if (CA_EDR == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+    }
+    printf("Data: %s\n", requestInfo->info.payload);
+    printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
+
+    if (requestInfo->info.options)
+    {
+        uint32_t len = requestInfo->info.numOptions;
+        uint32_t i;
+        for (i = 0; i < len; i++)
+        {
+            printf("Option %d\n", i + 1);
+            printf("ID : %d\n", requestInfo->info.options[i].optionID);
+            printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
+                   requestInfo->info.options[i].optionData);
+        }
+    }
+    printf("############################################################\n");
+
+    //Check if this has secure communication information
+    if (requestInfo->info.payload &&
+            (CA_IPV4 == object->transportType))
+    {
+        int securePort = get_secure_information(requestInfo->info.payload);
+        if (0 < securePort) //Set the remote endpoint secure details and send response
+        {
+            printf("This is secure resource...\n");
+
+            //length of "coaps://"
+            int length = sizeof(SECURE_COAPS_PREFIX) - 1;
+
+            // length of "ipaddress:port"
+            length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
+            length += strlen(object->resourceUri) + 1;
+
+            char *uri = calloc(1, sizeof(char) * length);
+            if (!uri)
+            {
+                printf("Failed to create new uri\n");
+                return;
+            }
+            sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
+                    object->addressInfo.IP.port, object->resourceUri);
+
+            CARemoteEndpoint_t *endpoint = NULL;
+            if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
+            {
+                printf("Failed to create duplicate of remote endpoint!\n");
+                return;
+            }
+            endpoint->isSecured = true;
+            object = endpoint;
+
+            free(uri);
+        }
+    }
+
+    printf("Send response with URI\n");
+    send_response(object, &requestInfo->info);
+
+    g_received = 1;
+}
+
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+{
+    printf("##########Received response from remote device #############\n");
+    printf("Uri: %s\n", object->resourceUri);
+    if (CA_IPV4 == object->transportType)
+    {
+        printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
+               object->addressInfo.IP.port, object->isSecured);
+    }
+    else if (CA_EDR == object->transportType)
+    {
+        printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+    }
+    printf("response result : %d\n", responseInfo->result);
+    printf("Data: %s\n", responseInfo->info.payload);
+    printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
+    printf("Token: %s\n", responseInfo->info.token);
+    if (responseInfo->info.options)
+    {
+        uint32_t len = responseInfo->info.numOptions;
+        uint32_t i;
+        for (i = 0; i < len; i++)
+        {
+            printf("Option %d\n", i + 1);
+            printf("ID : %d\n", responseInfo->info.options[i].optionID);
+            printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
+                   responseInfo->info.options[i].optionData);
+        }
+    }
+    printf("############################################################\n");
+    g_received = 1;
+
+    //Check if this has secure communication information
+    if (responseInfo->info.payload)
+    {
+        int securePort = get_secure_information(responseInfo->info.payload);
+        if (0 < securePort) //Set the remote endpoint secure details and send response
+        {
+            printf("This is secure resource...\n");
+        }
+    }
+}
+
+void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
+{
+    printf("entering send_response\n");
+
+    printf("\n=============================================\n");
+    printf("\tselect message type\n");
+    printf("CON     : 0\n");
+    printf("NON     : 1\n");
+    printf("ACK     : 2\n");
+    printf("RESET   : 3\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return;
+    }
+
+    int messageType = buf[0] - '0';
+    int responseCode = 0 ;
+    char responseCodeBuf[MAX_BUF_LEN] = { 0 };
+    if (CA_MSG_RESET != messageType)
+    {
+        printf("\n=============================================\n");
+        printf("\tselect response code\n");
+        printf("EMPTY                    :   0\n");
+        printf("SUCCESS                  : 200\n");
+        printf("CREATED                  : 201\n");
+        printf("DELETED                  : 202\n");
+        printf("BAD_REQ                  : 400\n");
+        printf("BAD_OPT                  : 402\n");
+        printf("NOT_FOUND                : 404\n");
+        printf("INTERNAL_SERVER_ERROR    : 500\n");
+        printf("RETRANSMIT_TIMEOUT       : 504\n");
+        printf("select : ");
+
+        if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
+        {
+            return;
+        }
+        responseCode = atoi(responseCodeBuf);
+    }
+    CAInfo_t responseData = { 0 };
+    responseData.type = messageType;
+
+    responseData.messageId = (info != NULL) ? info->messageId : 0;
+    if(CA_MSG_RESET != messageType)
+    {
+        responseData.token = (info != NULL) ? info->token : NULL;
+        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
+
+        if (endpoint->isSecured)
+        {
+            printf("Sending response on secure communication\n");
+
+            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
+                     g_local_secure_port);
+        }
+        else
+        {
+            printf("Sending response on non-secure communication\n");
+
+            uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
+            responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
+            if (NULL == responseData.payload)
+            {
+                printf("Memory allocation fail\n");
+                return;
+            }
+            snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
+        }
+    }
+
+    CAResponseInfo_t responseInfo = { 0 };
+    responseInfo.result = responseCode;
+    responseInfo.info = responseData;
+
+    // send response (transportType from remoteEndpoint of request Info)
+    CAResult_t res = CASendResponse(endpoint, &responseInfo);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Send response error\n");
+    }
+    else
+    {
+        printf("Send response success\n");
+    }
+
+    printf("=============================================\n");
+}
+
+int get_secure_information(CAPayload_t payLoad)
+{
+    printf("Entering get_secure_information\n");
+
+    if (!payLoad)
+    {
+        printf("Payload is NULL\n");
+        return -1;
+    }
+
+    char *subString = NULL;
+    if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
+    {
+        printf("This is not secure resource\n");
+        return -1;
+    }
+
+    if (NULL == (subString = strstr(payLoad, "\"port\":")))
+    {
+        printf("This secure resource does not have port information\n");
+        return -1;
+    }
+
+    char *startPos = strstr(subString, ":");
+    if (!startPos)
+    {
+        printf("Parsing failed !\n");
+        return -1;
+    }
+
+    char *endPos = strstr(startPos, "}");
+    if (!endPos)
+    {
+        printf("Parsing failed !\n");
+        return -1;
+    }
+
+    if(((endPos - 1) - startPos) > 4)
+    {
+        printf("port length is not proper.Exceeding length 4\n");
+        return -1;
+    }
+
+    char portStr[4] = {0};
+    memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
+
+    printf("secured port is: %s\n", portStr);
+    return atoi(portStr);
+}
+
+void get_resource_uri(char *URI, char *resourceURI, int length)
+{
+    char *startPos = URI;
+    char *temp = NULL;
+    if (NULL != (temp = strstr(URI, "://")))
+    {
+        startPos = strchr(temp + 3, '/');
+        if (!startPos)
+        {
+            printf("Resource URI is missing\n");
+            return;
+        }
+    }
+
+    char *endPos = strchr(startPos, '?');
+    if (!endPos)
+    {
+        endPos = URI + strlen(URI);
+    }
+    endPos -= 1;
+
+    if (endPos - startPos <= length)
+    {
+        memcpy(resourceURI, startPos + 1, endPos - startPos);
+    }
+
+    printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
+}
+
+CAResult_t get_network_type()
+{
+    printf("\n=============================================\n");
+    printf("\tselect network type\n");
+    printf("IPv4 : 0\n");
+    printf("BT : 2\n");
+    printf("LE : 3\n");
+    printf("select : ");
+
+    char buf[MAX_BUF_LEN] = { 0 };
+    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+    {
+        return CA_NOT_SUPPORTED ;
+    }
+
+    int number = buf[0] - '0';
+    number = (number < 0 || number > 3) ? 0 : 1 << number;
+
+    if (!(number & 0xf))
+    {
+        return CA_NOT_SUPPORTED;
+    }
+    if (number & CA_IPV4)
+    {
+        g_selected_nw_type = CA_IPV4;
+        return CA_STATUS_OK;
+    }
+    if (number & CA_EDR)
+    {
+        g_selected_nw_type = CA_EDR;
+        return CA_STATUS_OK;
+    }
+    if (number & CA_LE)
+    {
+        g_selected_nw_type = CA_LE;
+        return CA_STATUS_OK;
+    }
+
+    printf("\n=============================================\n");
+
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t get_input_data(char *buf, int32_t length)
+{
+    if (!fgets(buf, length, stdin))
+    {
+        printf("fgets error\n");
+        return CA_STATUS_FAILED;
+    }
+
+    char *p = NULL;
+    if ((p = strchr(buf, '\n')) != NULL)
+    {
+        *p = '\0';
+    }
+
+    return CA_STATUS_OK;
+}
diff --git a/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.manifest b/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.manifest
new file mode 100644 (file)
index 0000000..50868ad
--- /dev/null
@@ -0,0 +1,26 @@
+<manifest>
+       <define>
+         <domain name="casample" />
+         <permit>
+               <smack permit="system::use_internet" type="rwx"/>
+         </permit>
+         <request>
+                <smack request="system::use_internet" type="rwx"/>
+                <smack request="bt-service" type="rwx"/>
+               <smack request="sap" type="rwx"/>
+                <smack request="bt-service::spp" type="rwx"/>
+                <smack request="bt-service::gap" type="rwx"/>
+                <smack request="bt-service::admin" type="rwx"/>
+                <smack request="bt-service::manager" type="rwx"/>
+                <smack request="bt-service::public" type="rwx"/>
+                 <smack request="bt-service::platform" type="rwx"/>
+         </request>
+       </define>
+       <assign>
+               <filesystem path="/opt/apps/com.oic.ca.sample/bin/sample" exec_label="sample" />
+       </assign>
+       <request>
+               <domain name="casample" />
+       </request>
+</manifest>
+
diff --git a/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.xml b/resource/csdk/connectivity/samples/tizen/com.oic.ca.sample.xml
new file mode 100644 (file)
index 0000000..7ee7fbb
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns="http://tizen.org/ns/packages" package="com.oic.ca.sample" version="0.1.12" install-location="internal-only">
+       <label>casample</label>
+       <author email="oic" href="www.iotivity.org">OIC</author>
+       <description>casample</description>
+       <ui-application appid="com.oic.ca.sample" exec="/usr/apps/com.oic.ca.sample/bin/sample" nodisplay="false" multiple="false" type="capp" taskmanage="true">
+               <icon>com.oic.ca.sample.png</icon>
+               <label>casample</label>
+               <label xml:lang="en-us">casample</label>
+               <label xml:lang="nl-nl">casample</label>
+       </ui-application>
+       <privileges>
+               <privilege>http://tizen.org/privilege/socket</privilege>
+       </privileges>
+
+</manifest>
+
diff --git a/resource/csdk/connectivity/samples/tizen/gbsbuild.sh b/resource/csdk/connectivity/samples/tizen/gbsbuild.sh
new file mode 100644 (file)
index 0000000..6c60044
--- /dev/null
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+git init
+gbs build -A armv7l --include-all -B ~/GBS-ROOT-NEW
+
+
+
diff --git a/resource/csdk/connectivity/samples/tizen/packaging/com.oic.ca.sample.spec b/resource/csdk/connectivity/samples/tizen/packaging/com.oic.ca.sample.spec
new file mode 100644 (file)
index 0000000..cc32466
--- /dev/null
@@ -0,0 +1,51 @@
+%define PREFIX /usr/apps/com.oic.ca.sample
+%define ROOTDIR  %{_builddir}/%{name}-%{version}
+
+Name: com-oic-ca-sample
+Version:    0.1
+Release:    1
+Summary: Tizen adapter interfacesample application
+URL: http://slp-source.sec.samsung.net
+Source: %{name}-%{version}.tar.gz
+License: Apache-2.0
+Group: Applications/OICSample
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(glib-2.0)
+BuildRequires: boost-devel
+BuildRequires: boost-thread
+BuildRequires: boost-system
+BuildRequires: boost-filesystem
+BuildRequires: pkgconfig(capi-network-wifi)
+BuildRequires: pkgconfig(capi-network-bluetooth)
+BuildRequires: scons
+BuildRequires: com-oic-ca
+
+
+%description
+OIC interfacesample application
+
+%prep
+%setup -q
+
+%build
+
+scons TARGET_OS=tizen -c
+scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT}
+
+%install
+
+mkdir -p %{buildroot}%{_datadir}/packages
+mkdir -p %{buildroot}/%{_sysconfdir}/smack/accesses2.d
+mkdir -p %{buildroot}/usr/apps/com.oic.ca.sample/bin/
+mkdir -p %{buildroot}/usr/apps/com.oic.ca.sample/bin/internal
+
+cp -rf %{ROOTDIR}/com.oic.ca.sample.xml %{buildroot}/%{_datadir}/packages
+cp -rf %{ROOTDIR}/scons/ca_sample %{buildroot}/usr/apps/com.oic.ca.sample/bin/
+
+%files
+%manifest com.oic.ca.sample.manifest
+%defattr(-,root,root,-)
+/usr/apps/com.oic.ca.sample/bin/ca_sample
+/%{_datadir}/packages/com.oic.ca.sample.xml
+
+
diff --git a/resource/csdk/connectivity/samples/tizen/scons/SConscript b/resource/csdk/connectivity/samples/tizen/scons/SConscript
new file mode 100644 (file)
index 0000000..301a366
--- /dev/null
@@ -0,0 +1,55 @@
+##
+# 'resource' sub-project main build script
+#
+##
+
+Import('env')
+
+target_os = env.get('TARGET_OS')
+transport = env.get('TARGET_TRANSPORT')
+
+OIC_LIB = 'oic'
+root_dir = env.get('ROOT_DIR')
+build_dir = env.get('BUILD_DIR')
+sample_dir = build_dir
+
+env.AppendUnique(CFLAGS = ['-std=c99', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall', '-DSLP_SDK_LOG', '-g','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE', '-DTB_LOG','`pkg-config', '--cflags', '--libs','dlog', 'com.oic.ca', 'capi-network-wifi',
+                               'gobject-2.0','glib-2.0`'])
+
+env.Append(LIBPATH=[root_dir +'/lib/tizen/ble/libs/',])
+env.Append(LIBS=[
+  '-lm', '-lpthread', '-lrt', '-ldl', '-lstdc++', '-lgobject-2.0', '-lgio-2.0', '-lglib-2.0', '-lcapi-network-wifi', '-ldlog', '-lcapi-network-bluetooth', '-lconnectivity_abstraction', 'coap',
+])
+
+env.Prepend(RPATH=[root_dir +'/lib/tizen/ble/libs/',])
+if 'ALL' in transport:
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER','BT_ADAPTER_TEST','BLE_ADAPTER_TEST'])
+               print "CA Transport is ALL"
+else:
+       if 'BT' in transport:
+               env.AppendUnique(CPPDEFINES = ['EDR_ADAPTER','BT_ADAPTER_TEST'])
+               print "CA Transport is BT"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_EDR_ADAPTER'])
+               
+       if 'BLE' in transport:
+               env.AppendUnique(CPPDEFINES = ['LE_ADAPTER','BLE_ADAPTER_TEST'])
+               print "CA Transport is BLE"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_LE_ADAPTER'])
+
+       if 'IP' in transport:
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER'])
+               print "CA Transport is IP"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
+               
+
+ca_sample_src = [sample_dir + '/casample.c']
+
+print " ca sample src %s" % ca_sample_src
+
+env.Program('ca_sample', [ca_sample_src,])
+
+
+
diff --git a/resource/csdk/connectivity/src/SConscript b/resource/csdk/connectivity/src/SConscript
new file mode 100644 (file)
index 0000000..45db09b
--- /dev/null
@@ -0,0 +1,106 @@
+##
+# CA build script
+##
+
+Import('env')
+
+ca_os = env.get('TARGET_OS')
+ca_transport = env.get('TARGET_TRANSPORT')
+secured = env.get('SECURED')
+root_dir = './../'
+ca_path = './'
+current_dir=env.get('SRC_DIR')
+
+# The tinydtls library location is ~/iotivity/extlibs. When scons run from connectivity folder,
+# the build folder is ~/iotivity/resource/csdk/connectivity/out/linux/x86_64/release/.
+# To include  ~/iotivity/extlibs/tinyDTLS, it should go seven level up from the build folder.
+extlib_dir ='../../../../../../../../'
+
+#####################################################################
+# Source files and Target(s)
+######################################################################
+
+print"Reading ca script %s"%ca_transport
+
+env.PrependUnique(CPPPATH = [root_dir + '/api/'])
+env.AppendUnique(CPPPATH = [root_dir + '/inc/'])
+env.AppendUnique(CPPPATH = [root_dir + '/lib/libcoap-4.1.1/'])
+env.AppendUnique(CPPPATH = [root_dir + '/common/inc/'])
+
+if ca_os not in ['arduino', 'windows', 'winrt']:
+       env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
+
+if ca_os in ['darwin']:
+       env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+
+#Getting common source files
+env.SConscript('./../common/SConscript')
+
+if env.get('SECURED') == '1':
+       if current_dir.find('connectivity') == -1:
+               env.SConscript(current_dir +'/extlibs/tinydtls/SConscript')
+       else:
+               env.SConscript(extlib_dir + '/extlibs/tinydtls/SConscript')
+
+
+env.AppendUnique(CA_SRC=[ca_path+'adapter_util/caadapterutils.c'])
+env.AppendUnique(CA_SRC=[ca_path+'adapter_util/camsgparser.c'])
+if env.get('SECURED') == '1':
+       env.AppendUnique(CA_SRC=[ca_path+'adapter_util/caadapternetdtls.c'])
+       env.AppendUnique(CPPPATH = [root_dir + '/external/inc/'])
+
+if ca_os == 'arduino':
+       env.AppendUnique(CPPDEFINES = ['SINGLE_THREAD'])
+       ca_common_src = [
+               ca_path + 'caconnectivitymanager_singlethread.c',
+               ca_path + 'cainterfacecontroller_singlethread.c',
+               ca_path + 'camessagehandler_singlethread.c',
+               ca_path + 'canetworkconfigurator.c',
+               ca_path + 'caprotocolmessage.c',
+               ca_path + 'caremotehandler.c',
+               ca_path + 'caretransmission_singlethread.c',
+               ]
+else:
+       env.AppendUnique(CPPDEFINES = ['MULTI_THREAD'])
+       ca_common_src = [
+               ca_path + 'caconnectivitymanager.c',
+               ca_path + 'cainterfacecontroller.c',
+               ca_path + 'camessagehandler.c',
+               ca_path + 'canetworkconfigurator.c',
+               ca_path + 'caprotocolmessage.c',
+               ca_path + 'caqueueingthread.c',
+               ca_path + 'caremotehandler.c',
+               ca_path + 'caretransmission.c',
+               ]
+       if secured == '1':
+               env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
+               if current_dir.find('connectivity') == -1:
+                       env.AppendUnique(CPPPATH = [current_dir + '/extlibs/tinydtls'])
+               else:
+                       env.AppendUnique(CPPPATH = [extlib_dir + '/extlibs/tinydtls'])
+env.AppendUnique(CA_SRC = ca_common_src)
+
+
+
+if 'ALL' in ca_transport:
+       env.SConscript(ca_path + 'ip_adapter/SConscript')
+       env.SConscript(ca_path + 'bt_edr_adapter/SConscript')
+       env.SConscript(ca_path + 'bt_le_adapter/SConscript')
+
+if 'IP' in ca_transport:
+       env.SConscript(ca_path + 'ip_adapter/SConscript')
+
+if 'BT' in ca_transport:
+       env.SConscript(ca_path + 'bt_edr_adapter/SConscript')
+
+if 'BLE' in ca_transport:
+       env.SConscript(ca_path + 'bt_le_adapter/SConscript')
+
+print "Include path is %s" %env.get('CPPPATH')
+print "Files path is %s" %env.get('CA_SRC')
+if ca_os in ['android', 'tizen']:
+       calib = env.SharedLibrary('connectivity_abstraction', env.get('CA_SRC'))
+else:
+       calib = env.StaticLibrary('connectivity_abstraction', env.get('CA_SRC'))
+env.InstallTarget(calib, 'libconnectivity_abstraction')
+
diff --git a/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c b/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
new file mode 100644 (file)
index 0000000..562a5fa
--- /dev/null
@@ -0,0 +1,670 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "caadapternetdtls.h"
+#include "cacommon.h"
+#include "caipinterface.h"
+#include "dtls.h"
+#include "oic_malloc.h"
+
+/**
+ * @def NET_DTLS_TAG
+ * @brief Logging tag for module name
+ */
+#define NET_DTLS_TAG "NET_DTLS"
+
+/**
+ * @var g_caDtlsContext
+ * @brief global context which holds dtls context and cache list information.
+ */
+static stCADtlsContext_t *g_caDtlsContext = NULL;
+
+/**
+ * @var g_dtlsContextMutex
+ * @brief Mutex to synchronize access to g_caDtlsContext.
+ */
+static ca_mutex g_dtlsContextMutex = NULL;
+
+/**
+ * @var g_dtlsListMutex
+ * @brief Mutex to synchronize access to DTLS Cache.
+ */
+static ca_mutex g_dtlsListMutex = NULL;
+
+/**
+ * @var g_getCredentialsCallback
+ * @brief callback to get DTLS credentials
+ */
+static CAGetDTLSCredentialsHandler g_getCredentialsCallback = NULL;
+
+static eDtlsRet_t CAAdapterNetDtlsEncryptInternal(const stCADtlsAddrInfo_t *dstSession,
+        uint8_t *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(dstSession, NET_DTLS_TAG, "Param dstSession is NULL" , DTLS_FAIL);
+    VERIFY_NON_NULL_RET(data, NET_DTLS_TAG, "Param data is NULL" , DTLS_FAIL);
+
+    if (0 == dataLen)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Given Packet length is equal to zero.");
+        return DTLS_FAIL;
+    }
+
+    ca_mutex_lock(g_dtlsContextMutex);
+    if (NULL == g_caDtlsContext)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
+        ca_mutex_unlock(g_dtlsContextMutex);
+        return DTLS_FAIL;
+    }
+
+    int retLen = dtls_write(g_caDtlsContext->dtlsContext, (session_t *)dstSession, data,
+                                dataLen);
+    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "dtls_write retun len [%d]", retLen);
+    ca_mutex_unlock(g_dtlsContextMutex);
+
+    if (0 == retLen)
+    {
+        // A new DTLS session was initiated by tinyDTLS library and wait for callback.
+        return DTLS_SESSION_INITIATED;
+    }
+    else if (dataLen == retLen)
+    {
+        OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+        return DTLS_OK;
+    }
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT FAILURE");
+    return DTLS_FAIL;
+}
+
+static eDtlsRet_t CAAdapterNetDtlsDecryptInternal(const stCADtlsAddrInfo_t *srcSession,
+        uint8_t *buf, uint32_t bufLen)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(srcSession, NET_DTLS_TAG, "Param srcSession is NULL", DTLS_FAIL);
+    VERIFY_NON_NULL_RET(buf, NET_DTLS_TAG, "Param buf is NULL", DTLS_FAIL);
+
+    if (0 == bufLen)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Given Packet length is equal to zero.");
+        return DTLS_FAIL;
+    }
+
+    eDtlsRet_t ret = DTLS_FAIL;
+
+    ///  TODO: how to protect g_caDtlsContext as dtls_handle_message is blocking call
+    if (dtls_handle_message(g_caDtlsContext->dtlsContext, (session_t *)srcSession, buf, bufLen) == 0)
+    {
+        OIC_LOG(DEBUG, NET_DTLS_TAG, "dtls_handle_message success");
+        ret = DTLS_OK;
+    }
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+    return ret;
+}
+
+static void CAFreeCacheMsg(stCACacheMessage_t *msg)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+    VERIFY_NON_NULL_VOID(msg, NET_DTLS_TAG, "msg");
+
+    OICFree(msg->destSession);
+    OICFree(msg->data);
+    OICFree(msg);
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+}
+
+static void CAClearCacheList()
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+    uint32_t list_index = 0;
+    uint32_t list_length = 0;
+    ca_mutex_lock(g_dtlsListMutex);
+    if (NULL == g_caDtlsContext)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Dtls Context is NULL");
+        ca_mutex_unlock(g_dtlsListMutex);
+        return;
+    }
+    list_length = u_arraylist_length(g_caDtlsContext->cacheList);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        stCACacheMessage_t *msg = (stCACacheMessage_t *)u_arraylist_get(g_caDtlsContext->cacheList,
+                                  list_index);
+        if (msg != NULL)
+        {
+            CAFreeCacheMsg(msg);
+        }
+    }
+    u_arraylist_free(&g_caDtlsContext->cacheList);
+    g_caDtlsContext->cacheList = NULL;
+    ca_mutex_unlock(g_dtlsListMutex);
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+}
+
+static CAResult_t CADtlsCacheMsg(stCACacheMessage_t *msg)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    ca_mutex_lock(g_dtlsListMutex);
+    if (NULL == g_caDtlsContext)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Dtls Context is NULL");
+        ca_mutex_unlock(g_dtlsListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t result = u_arraylist_add(g_caDtlsContext->cacheList, (void *)msg);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "u_arraylist_add failed!");
+    }
+    ca_mutex_unlock(g_dtlsListMutex);
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+    return result;
+}
+
+
+static bool CAIsAddressMatching(const stCADtlsAddrInfo_t *a,  const stCADtlsAddrInfo_t *b)
+{
+    return (a->size == b->size) &&
+           (a->addr.sa.sa_family == b->addr.sa.sa_family) &&
+           (a->addr.sin.sin_port == b->addr.sin.sin_port) &&
+           memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr, sizeof(struct in_addr)) == 0;
+}
+
+static void CASendCachedMsg(const stCADtlsAddrInfo_t *dstSession)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+    VERIFY_NON_NULL_VOID(dstSession, NET_DTLS_TAG, "Param dstSession is NULL");
+
+    uint32_t list_index = 0;
+    uint32_t list_length = 0;
+    ca_mutex_lock(g_dtlsListMutex);
+    list_length = u_arraylist_length(g_caDtlsContext->cacheList);
+    for (list_index = 0; list_index < list_length;)
+    {
+        stCACacheMessage_t *msg = (stCACacheMessage_t *)u_arraylist_get(g_caDtlsContext->cacheList,
+                                  list_index);
+        if ((NULL != msg) && (true == CAIsAddressMatching(msg->destSession, dstSession)))
+        {
+            eDtlsRet_t ret = CAAdapterNetDtlsEncryptInternal(msg->destSession,
+                             msg->data, msg->dataLen);
+            if (ret == DTLS_OK)
+            {
+                OIC_LOG(DEBUG, NET_DTLS_TAG, "CAAdapterNetDtlsEncryptInternal success");
+            }
+            else
+            {
+                OIC_LOG(ERROR, NET_DTLS_TAG, "CAAdapterNetDtlsEncryptInternal failed.");
+            }
+
+            if (u_arraylist_remove(g_caDtlsContext->cacheList, list_index))
+            {
+                CAFreeCacheMsg(msg);
+                // Reduce list length by 1 as we removed one element.
+                list_length--;
+            }
+            else
+            {
+                OIC_LOG(ERROR, NET_DTLS_TAG, "u_arraylist_remove failed.");
+                break;
+            }
+        }
+        else
+        {
+            // Move to the next element
+            ++list_index;
+        }
+    }
+    ca_mutex_unlock(g_dtlsListMutex);
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+}
+
+static int32_t CAReadDecryptedPayload(dtls_context_t *dtlsContext,
+                                      session_t *session,
+                                      uint8_t *buf,
+                                      size_t bufLen )
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", 0);
+    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Decrypted buf len [%d]", bufLen);
+
+    stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
+
+    char *remoteAddress = inet_ntoa(addrInfo->addr.sin.sin_addr);
+    uint32_t port = ntohs(addrInfo->addr.sin.sin_port);
+    eDtlsAdapterType_t type = (eDtlsAdapterType_t)addrInfo->ifIndex;
+
+    ca_mutex_lock(g_dtlsContextMutex);
+    if (NULL == g_caDtlsContext)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
+        ca_mutex_unlock(g_dtlsContextMutex);
+        return 0;
+    }
+
+    if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type) &&
+        (NULL != g_caDtlsContext->adapterCallbacks[type].recvCallback))
+    {
+        g_caDtlsContext->adapterCallbacks[type].recvCallback(remoteAddress, port,
+                buf,  bufLen, true);
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, NET_DTLS_TAG, "recvCallback Callback or adapter type is wrong [%d]", type);
+    }
+    ca_mutex_unlock(g_dtlsContextMutex);
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+    return 0;
+}
+
+static int32_t CASendSecureData(dtls_context_t *dtlsContext,
+                                session_t *session,
+                                uint8_t *buf,
+                                size_t bufLen)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", -1);
+    VERIFY_NON_NULL_RET(buf, NET_DTLS_TAG, "Param buf is NULL", -1);
+
+    if (0 == bufLen)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Encrypted Buffer length is equal to zero");
+        return 0;
+    }
+
+    stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
+
+    char *remoteAddress = inet_ntoa(addrInfo->addr.sin.sin_addr);
+    uint16_t port = ntohs(addrInfo->addr.sin.sin_port);
+    eDtlsAdapterType_t type = (eDtlsAdapterType_t)addrInfo->ifIndex;
+
+    //Mutex is not required for g_caDtlsContext. It will be called in same thread.
+    int32_t sentLen = 0;
+    if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type) &&
+        (NULL != g_caDtlsContext->adapterCallbacks[type].sendCallback))
+    {
+        sentLen = g_caDtlsContext->adapterCallbacks[type].sendCallback(remoteAddress, port,
+                  buf,  bufLen);
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, NET_DTLS_TAG, "send Callback or adapter type is wrong [%d]", type );
+    }
+
+    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "sent buffer length [%d]", sentLen);
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+    return sentLen;
+}
+
+
+static int32_t CAHandleSecureEvent(dtls_context_t *dtlsContext,
+                                   session_t *session,
+                                   dtls_alert_level_t level,
+                                   unsigned short code)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", 0);
+
+    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "level [%d] code [%u]", level, code);
+
+    if (!level && (code == DTLS_EVENT_CONNECTED))
+    {
+        OIC_LOG(DEBUG, NET_DTLS_TAG, "Received DTLS_EVENT_CONNECTED. Sending Cached data");
+        CASendCachedMsg((stCADtlsAddrInfo_t *)session);
+    }
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+    return 0;
+}
+
+
+static int32_t CAGetPskCredentials(dtls_context_t *ctx,
+                                   const session_t *session,
+                                   dtls_credentials_type_t type,
+                                   const unsigned char *desc, size_t descLen,
+                                   unsigned char *result, size_t resultLen)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    int32_t ret  = -1;
+
+    VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_DTLS_TAG, "GetCredential callback", -1);
+    VERIFY_NON_NULL_RET(result, NET_DTLS_TAG, "result", -1);
+
+    CADtlsPskCredsBlob_t *credInfo = NULL;
+
+    // Retrieve the credentials blob from security module
+    g_getCredentialsCallback(&credInfo);
+
+    VERIFY_NON_NULL_RET(credInfo, NET_DTLS_TAG, "credInfo is NULL", -1);
+    if(NULL == credInfo->creds)
+    {
+        OIC_LOG(DEBUG, NET_DTLS_TAG, "credentials are NULL");
+        memset(credInfo, 0, sizeof(CADtlsPskCredsBlob_t));
+        OICFree(credInfo);
+        return -1;
+    }
+
+    if ((type == DTLS_PSK_HINT) || (type == DTLS_PSK_IDENTITY))
+    {
+        if (DTLS_PSK_ID_LEN <= resultLen)
+        {
+            memcpy(result, credInfo->identity, DTLS_PSK_ID_LEN);
+            ret = DTLS_PSK_ID_LEN;
+        }
+    }
+
+    if ((type == DTLS_PSK_KEY) && (desc) && (descLen == DTLS_PSK_PSK_LEN))
+    {
+        // Check if we have the credentials for the device with which we
+        // are trying to perform a handshake
+        int index = 0;
+        for (index = 0; index < credInfo->num; index++)
+        {
+            if (memcmp(desc, credInfo->creds[index].id, DTLS_PSK_ID_LEN) == 0)
+            {
+                memcpy(result, credInfo->creds[index].psk, DTLS_PSK_PSK_LEN);
+                ret = DTLS_PSK_PSK_LEN;
+            }
+        }
+    }
+
+    // Erase sensitive data before freeing.
+    memset(credInfo->creds, 0, sizeof(OCDtlsPskCreds) * (credInfo->num));
+    OICFree(credInfo->creds);
+
+    memset(credInfo, 0, sizeof(CADtlsPskCredsBlob_t));
+    OICFree(credInfo);
+    credInfo = NULL;
+
+    return ret;
+}
+
+void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
+                               CAPacketSendCallback sendCallback, eDtlsAdapterType_t type)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+    ca_mutex_lock(g_dtlsContextMutex);
+    if (NULL == g_caDtlsContext)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
+        ca_mutex_unlock(g_dtlsContextMutex);
+        return;
+    }
+
+    if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type))
+    {
+        g_caDtlsContext->adapterCallbacks[type].recvCallback = recvCallback;
+        g_caDtlsContext->adapterCallbacks[type].sendCallback = sendCallback;
+    }
+
+    ca_mutex_unlock(g_dtlsContextMutex);
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+}
+
+void CADTLSSetCredentialsCallback(CAGetDTLSCredentialsHandler credCallback)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+    g_getCredentialsCallback = credCallback;
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+}
+
+CAResult_t CAAdapterNetDtlsInit()
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    if (NULL == g_dtlsContextMutex)
+    {
+        g_dtlsContextMutex = ca_mutex_new();
+        VERIFY_NON_NULL_RET(g_dtlsContextMutex, NET_DTLS_TAG, "malloc failed",
+            CA_MEMORY_ALLOC_FAILED);
+    }
+    else
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "CAAdapterNetDtlsInit done already!");
+        return CA_STATUS_OK;
+    }
+
+    if (NULL == g_dtlsListMutex)
+    {
+        g_dtlsListMutex = ca_mutex_new();
+        if (NULL == g_dtlsListMutex)
+        {
+            OIC_LOG(ERROR, NET_DTLS_TAG, "g_dtlsListMutex malloc failed");
+            ca_mutex_free(g_dtlsContextMutex);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+
+    ca_mutex_lock(g_dtlsContextMutex);
+    g_caDtlsContext = (stCADtlsContext_t *)OICCalloc(1, sizeof(stCADtlsContext_t));
+
+    if (NULL == g_caDtlsContext)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Context malloc failed");
+        ca_mutex_free(g_dtlsListMutex);
+        ca_mutex_unlock(g_dtlsContextMutex);
+        ca_mutex_free(g_dtlsContextMutex);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    ca_mutex_lock(g_dtlsListMutex);
+    g_caDtlsContext->cacheList = u_arraylist_create();
+
+    if (NULL == g_caDtlsContext->cacheList)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "cacheList initialization failed!");
+        ca_mutex_unlock(g_dtlsListMutex);
+        ca_mutex_free(g_dtlsListMutex);
+        ca_mutex_unlock(g_dtlsContextMutex);
+        ca_mutex_free(g_dtlsContextMutex);
+        OICFree(g_caDtlsContext);
+        g_caDtlsContext = NULL;
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_dtlsListMutex);
+    // Initialize clock, crypto and other global vars in tinyDTLS library
+    dtls_init();
+
+    g_caDtlsContext->dtlsContext = dtls_new_context(g_caDtlsContext);
+
+    if (NULL ==  g_caDtlsContext->dtlsContext)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "dtls_new_context failed");
+        ca_mutex_unlock(g_dtlsContextMutex);
+        CAAdapterNetDtlsDeInit();
+        return CA_STATUS_FAILED;
+    }
+
+    g_caDtlsContext->callbacks.write = CASendSecureData;
+    g_caDtlsContext->callbacks.read  = CAReadDecryptedPayload;
+    g_caDtlsContext->callbacks.event = CAHandleSecureEvent;
+    g_caDtlsContext->callbacks.get_psk_info = CAGetPskCredentials;
+
+    dtls_set_handler(g_caDtlsContext->dtlsContext, &(g_caDtlsContext->callbacks));
+    ca_mutex_unlock(g_dtlsContextMutex);
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAAdapterNetDtlsDeInit()
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(g_caDtlsContext, NET_DTLS_TAG, "context is NULL");
+
+    ca_mutex_lock(g_dtlsContextMutex);
+    CAClearCacheList();
+    dtls_free_context(g_caDtlsContext->dtlsContext);
+    g_caDtlsContext->dtlsContext = NULL;
+    OICFree(g_caDtlsContext);
+    g_caDtlsContext = NULL;
+    ca_mutex_unlock(g_dtlsContextMutex);
+
+    ca_mutex_free(g_dtlsContextMutex);
+    g_dtlsContextMutex = NULL;
+    ca_mutex_free(g_dtlsListMutex);
+    g_dtlsListMutex = NULL;
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+}
+
+CAResult_t CAAdapterNetDtlsEncrypt(const char *remoteAddress,
+                                   const uint16_t port,
+                                   void *data,
+                                   uint32_t dataLen,
+                                   uint8_t *cacheFlag,
+                                   eDtlsAdapterType_t adapterType)
+{
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, NET_DTLS_TAG,"Param remoteAddress is NULL",CA_STATUS_FAILED);
+
+    VERIFY_NON_NULL_RET(data, NET_DTLS_TAG, "Param data is NULL" , CA_STATUS_FAILED);
+
+    if (0 == dataLen)
+    {
+        OIC_LOG_V(ERROR, NET_DTLS_TAG, "dataLen is less than or equal zero [%d]", dataLen);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Data to be encrypted dataLen [%d]", dataLen);
+
+    stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)OICCalloc(1, sizeof(stCADtlsAddrInfo_t));
+
+    VERIFY_NON_NULL_RET(addrInfo, NET_DTLS_TAG, "malloc failed" , CA_MEMORY_ALLOC_FAILED);
+
+    addrInfo->addr.sin.sin_family = AF_INET;
+    addrInfo->addr.sin.sin_port = htons(port);
+    // Conversion from ASCII format to Network format
+    if (inet_aton(remoteAddress, &addrInfo->addr.sin.sin_addr) == 0)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to convert from ASCII to Network Address");
+        OICFree(addrInfo);
+        return CA_STATUS_FAILED;
+    }
+    addrInfo->size = sizeof(addrInfo->addr);
+    addrInfo->ifIndex = adapterType;
+
+    eDtlsRet_t ret = CAAdapterNetDtlsEncryptInternal(addrInfo, data, dataLen);
+    if (ret == DTLS_SESSION_INITIATED)
+    {
+        stCACacheMessage_t *message = (stCACacheMessage_t *)OICCalloc(1, sizeof(stCACacheMessage_t));
+        if (NULL == message)
+        {
+            OIC_LOG(ERROR, NET_DTLS_TAG, "calloc failed!");
+            OICFree(addrInfo);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        message->data = (uint8_t *)OICCalloc(dataLen + 1, sizeof(uint8_t));
+        if (NULL == message->data)
+        {
+            OIC_LOG(ERROR, NET_DTLS_TAG, "calloc failed!");
+            OICFree(addrInfo);
+            OICFree(message);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+        memcpy(message->data, data, dataLen);
+        message->dataLen = dataLen;
+        message->destSession = addrInfo;
+
+        CAResult_t result = CADtlsCacheMsg(message);
+        if (CA_STATUS_OK == result)
+        {
+            if (cacheFlag)
+            {
+                *cacheFlag = 1;
+            }
+        }
+        else
+        {
+            OIC_LOG(DEBUG, NET_DTLS_TAG, "CADtlsCacheMsg failed!");
+            CAFreeCacheMsg(message);
+        }
+        OIC_LOG_V(DEBUG, NET_DTLS_TAG, "OUT Initiating Dtls session [%d]", result);
+        return result;
+    }
+
+    OICFree(addrInfo);
+
+    if (ret == DTLS_OK)
+    {
+        OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+        return CA_STATUS_OK;
+    }
+
+    OIC_LOG(ERROR, NET_DTLS_TAG, "OUT FAILURE");
+    return CA_STATUS_FAILED;
+}
+
+
+CAResult_t CAAdapterNetDtlsDecrypt(const char *remoteAddress,
+                                   const uint16_t port,
+                                   uint8_t *data,
+                                   uint32_t dataLen,
+                                   eDtlsAdapterType_t adapterType)
+{
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+
+    stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)OICCalloc(1, sizeof(stCADtlsAddrInfo_t));
+
+    VERIFY_NON_NULL_RET(addrInfo, NET_DTLS_TAG, "calloc failed" , CA_MEMORY_ALLOC_FAILED);
+
+    addrInfo->addr.sin.sin_family = AF_INET;
+    addrInfo->addr.sin.sin_port = htons(port);
+
+    // Conversion from ASCII format to Network format
+    if (inet_aton(remoteAddress, &addrInfo->addr.sin.sin_addr) == 0)
+    {
+        OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to convert from ASCII to Network Address");
+        OICFree(addrInfo);
+        return CA_STATUS_FAILED;
+    }
+    addrInfo->size = sizeof(addrInfo->addr);
+    addrInfo->ifIndex = adapterType;
+
+    eDtlsRet_t ret = CAAdapterNetDtlsDecryptInternal(addrInfo, data, dataLen);
+
+    OICFree(addrInfo);
+    if (DTLS_OK == ret || DTLS_HS_MSG == ret)
+    {
+        OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Successfully Decrypted or Handshake msg recvd [%d]", ret);
+        OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+        return CA_STATUS_OK;
+    }
+
+    OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT FAILURE");
+    return CA_STATUS_FAILED;
+}
+
+
diff --git a/resource/csdk/connectivity/src/adapter_util/caadapterutils.c b/resource/csdk/connectivity/src/adapter_util/caadapterutils.c
new file mode 100644 (file)
index 0000000..c073b62
--- /dev/null
@@ -0,0 +1,605 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "caadapterutils.h"
+
+#include <string.h>
+#include <ctype.h>
+
+#ifdef __ANDROID__
+#include <jni.h>
+#endif
+
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#define CA_ADAPTER_UTILS_TAG "CA_ADAPTER_UTILS"
+
+#ifdef __ANDROID__
+/**
+ * @var g_jvm
+ * @brief pointer to store JavaVM
+ */
+static JavaVM *g_jvm = NULL;
+
+/**
+ * @var gContext
+ * @brief pointer to store context for android callback interface
+ */
+static jobject g_Context = NULL;
+#endif
+
+void CALogPDUData(coap_pdu_t *pdu)
+{
+    VERIFY_NON_NULL_VOID(pdu, CA_ADAPTER_UTILS_TAG, "pdu");
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - payload : %s", pdu->data);
+
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - type : %d", pdu->hdr->type);
+
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - code : %d", pdu->hdr->code);
+
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - id : %d", pdu->hdr->id);
+
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - token : %s", pdu->hdr->token);
+}
+
+CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CATransportType_t type, const char *address)
+{
+    CALocalConnectivity_t *info = (CALocalConnectivity_t *)
+                                  OICCalloc(1, sizeof(CALocalConnectivity_t));
+    if (NULL == info)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
+        return NULL;
+    }
+
+    info->type = type;
+    if (address && strlen(address))
+    {
+        if (CA_EDR == type)
+        {
+            strncpy(info->addressInfo.BT.btMacAddress, address, CA_MACADDR_SIZE - 1);
+            info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        }
+        else if (CA_LE == type)
+        {
+            strncpy(info->addressInfo.LE.leMacAddress, address, CA_MACADDR_SIZE - 1);
+            info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        }
+        else if (CA_IPV4 == type)
+        {
+            strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1);
+            info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+        }
+        else if (CA_IPV6 == type)
+        {
+            OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
+            OICFree(info);
+            return NULL;
+        }
+        else
+        {
+            OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
+            OICFree(info);
+            return NULL;
+        }
+    }
+
+    return info;
+}
+
+CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *connectivity)
+{
+    VERIFY_NON_NULL_RET(connectivity, CA_ADAPTER_UTILS_TAG, "connectivity is NULL", NULL);
+
+    CALocalConnectivity_t *info = (CALocalConnectivity_t *)
+                                  OICCalloc(1, sizeof(CALocalConnectivity_t));
+    if (NULL == info)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
+        return NULL;
+    }
+
+    info->type = connectivity->type;
+    if (CA_EDR == info->type && strlen(connectivity->addressInfo.BT.btMacAddress))
+    {
+        strncpy(info->addressInfo.BT.btMacAddress, connectivity->addressInfo.BT.btMacAddress,
+                CA_MACADDR_SIZE - 1);
+        info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+    }
+    else if (CA_LE == info->type && strlen(connectivity->addressInfo.LE.leMacAddress))
+    {
+        strncpy(info->addressInfo.LE.leMacAddress, connectivity->addressInfo.LE.leMacAddress,
+                CA_MACADDR_SIZE - 1);
+        info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+    }
+    else if ((CA_IPV4 == info->type)
+
+            && strlen(connectivity->addressInfo.IP.ipAddress))
+    {
+        strncpy(info->addressInfo.IP.ipAddress, connectivity->addressInfo.IP.ipAddress,
+                CA_IPADDR_SIZE - 1);
+        info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+        info->addressInfo.IP.port = connectivity->addressInfo.IP.port;
+    }
+    else if (CA_IPV6 == info->type)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
+        OICFree(info);
+        return NULL;
+    }
+    else
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
+        OICFree(info);
+        return NULL;
+    }
+
+    info->isSecured = connectivity->isSecured;
+    return info;
+}
+
+void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndpoint)
+{
+    OICFree(localEndpoint);
+}
+
+CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CATransportType_t type, const char *address,
+                                                  const char *resourceUri)
+{
+    CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
+                               OICCalloc(1, sizeof(CARemoteEndpoint_t));
+    if (NULL == info)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
+        return NULL;
+    }
+
+    info->transportType = type;
+    if (address && strlen(address))
+    {
+        if (CA_EDR == type)
+        {
+            strncpy(info->addressInfo.BT.btMacAddress, address, CA_MACADDR_SIZE - 1);
+            info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        }
+        else if (CA_LE == type)
+        {
+            strncpy(info->addressInfo.LE.leMacAddress, address, CA_MACADDR_SIZE - 1);
+            info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        }
+        else if (CA_IPV4 == type)
+        {
+            strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1);
+            info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+        }
+        else if (CA_IPV6 == type)
+        {
+            OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
+            OICFree(info);
+            return NULL;
+        }
+        else
+        {
+            OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
+            OICFree(info);
+            return NULL;
+        }
+    }
+
+    if (resourceUri && strlen(resourceUri))
+    {
+        info->resourceUri = OICStrdup(resourceUri);
+    }
+
+    return info;
+}
+
+CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(const CARemoteEndpoint_t *remoteEndpoint)
+{
+    VERIFY_NON_NULL_RET(remoteEndpoint, CA_ADAPTER_UTILS_TAG, "Remote endpoint is NULL", NULL);
+
+    CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
+                               OICCalloc(1, sizeof(CARemoteEndpoint_t));
+    if (NULL == info)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
+        return NULL;
+    }
+
+    info->transportType = remoteEndpoint->transportType;
+    if (CA_EDR == info->transportType && ('\0' != remoteEndpoint->addressInfo.BT.btMacAddress[0]))
+    {
+        strncpy(info->addressInfo.BT.btMacAddress, remoteEndpoint->addressInfo.BT.btMacAddress,
+                CA_MACADDR_SIZE - 1);
+        info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+    }
+    else if (CA_LE == info->transportType
+             && ('\0' != remoteEndpoint->addressInfo.LE.leMacAddress[0]))
+    {
+        strncpy(info->addressInfo.LE.leMacAddress, remoteEndpoint->addressInfo.LE.leMacAddress,
+                CA_MACADDR_SIZE - 1);
+        info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+    }
+    else if ((CA_IPV4 == info->transportType)
+            && ('\0' != remoteEndpoint->addressInfo.IP.ipAddress[0]))
+    {
+        strncpy(info->addressInfo.IP.ipAddress, remoteEndpoint->addressInfo.IP.ipAddress,
+                CA_IPADDR_SIZE - 1);
+        info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+        info->addressInfo.IP.port = remoteEndpoint->addressInfo.IP.port;
+    }
+    else if (CA_IPV6 == info->transportType)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
+    }
+    else
+    {
+        OIC_LOG(DEBUG, CA_ADAPTER_UTILS_TAG, "Its not matching. May be multicast.");
+    }
+
+    //For Multicast, remote address will be null while resourceUri will have the service UUID
+
+    if (remoteEndpoint->resourceUri && strlen(remoteEndpoint->resourceUri))
+    {
+        info->resourceUri = OICStrdup(remoteEndpoint->resourceUri);
+    }
+
+    info->isSecured = remoteEndpoint->isSecured;
+    return info;
+}
+
+void CAAdapterFreeRemoteEndpoint(CARemoteEndpoint_t *remoteEndpoint)
+{
+    if (remoteEndpoint)
+    {
+        OICFree(remoteEndpoint->resourceUri);
+        OICFree(remoteEndpoint);
+    }
+}
+
+CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
+                                   size_t ipAddrLen, uint16_t *port)
+{
+    if (!ipAddr || !isdigit(ipAddrStr[0]) || !port)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "invalid param");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    size_t index = 0;
+    uint8_t dotCount = 0;
+
+    ipAddr[index] = 0;
+    *port = 0;
+    while (*ipAddrStr)
+    {
+        if (isdigit(*ipAddrStr))
+        {
+            if(index >= ipAddrLen)
+            {
+                OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "invalid param");
+                return CA_STATUS_INVALID_PARAM;
+            }
+            ipAddr[index] *= 10;
+            ipAddr[index] += *ipAddrStr - '0';
+        }
+        else if (*ipAddrStr == '.')
+        {
+            index++;
+            dotCount++;
+            ipAddr[index] = 0;
+        }
+        else
+        {
+            break;
+        }
+        ipAddrStr++;
+    }
+
+    if (*ipAddrStr == ':')
+    {
+        ipAddrStr++;
+        while (*ipAddrStr)
+        {
+            if (isdigit(*ipAddrStr))
+            {
+                *port *= 10;
+                *port += *ipAddrStr - '0';
+            }
+            else
+            {
+                break;
+            }
+            ipAddrStr++;
+        }
+    }
+
+    if (dotCount == 3)
+    {
+        return CA_STATUS_OK;
+    }
+    return CA_STATUS_FAILED;
+}
+
+bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2, const char *netMask)
+{
+    VERIFY_NON_NULL_RET(ipAddress1, CA_ADAPTER_UTILS_TAG, "First address", false);
+    VERIFY_NON_NULL_RET(ipAddress2, CA_ADAPTER_UTILS_TAG, "Second address", false);
+    VERIFY_NON_NULL_RET(netMask, CA_ADAPTER_UTILS_TAG, "netMask", false);
+
+    uint8_t ipList1[IPV4_ADDR_ONE_OCTECT_LEN] = { 0 };
+    uint8_t ipList2[IPV4_ADDR_ONE_OCTECT_LEN] = { 0 };
+    uint8_t maskList[IPV4_ADDR_ONE_OCTECT_LEN] = { 0 };
+    CAResult_t ret = CA_STATUS_OK;
+
+    /* Local Loopback Address */
+    if (0 == strncmp(ipAddress1, "127.", 4) || 0 == strncmp(ipAddress2, "127.", 4))
+    {
+        return true;
+    }
+
+    uint16_t parsedPort = 0;
+    ret = CAParseIPv4AddressInternal(ipAddress1, ipList1, sizeof(ipList1), &parsedPort);
+    if (ret != CA_STATUS_OK)
+    {
+        OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "First ip address parse fail %d", ret);
+        return false;
+    }
+
+    ret = CAParseIPv4AddressInternal(ipAddress2, ipList2, sizeof(ipList2), &parsedPort);
+    if (ret != CA_STATUS_OK)
+    {
+        OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Second ip address parse fail %d", ret);
+        return false;
+    }
+
+    ret = CAParseIPv4AddressInternal(netMask, maskList, sizeof(maskList), &parsedPort);
+    if (ret != CA_STATUS_OK)
+    {
+        OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Net mask parse fail %d", ret);
+        return false;
+    }
+
+    return ((ipList1[0] & maskList[0]) == (ipList2[0] & maskList[0])) && ((ipList1[1] & maskList[1])
+            == (ipList2[1] & maskList[1]))
+           && ((ipList1[2] & maskList[2]) == (ipList2[2] & maskList[2]))
+           && ((ipList1[3] & maskList[3]) == (ipList2[3] & maskList[3]));
+}
+
+
+bool CAIsMulticastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress,
+                                const char *multicastAddress, uint16_t port)
+{
+    VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", false);
+    VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", false);
+    VERIFY_NON_NULL_RET(multicastAddress, CA_ADAPTER_UTILS_TAG, "multicastAddress is null", false);
+
+    uint32_t listLength = u_arraylist_length(serverInfoList);
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex);
+        if (!info)
+        {
+            OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Info is NULL");
+            return false;
+        }
+
+        if (info->isMulticastServer && (strncmp(info->ipAddress, multicastAddress,
+                                                strlen(multicastAddress) == 0))
+            && (info->port == port) && (strncmp(info->ifAddr, ipAddress, strlen(ipAddress)) == 0))
+        {
+            return info->isServerStarted;
+        }
+    }
+    return false;
+}
+
+bool CAIsUnicastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress,
+                              uint16_t port)
+{
+    VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", false);
+    VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", false);
+
+    uint32_t listLength = u_arraylist_length(serverInfoList);
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex);
+        if (!info)
+        {
+            continue;
+        }
+
+        if (!info->isMulticastServer && (strncmp(info->ipAddress, ipAddress,
+                                                 strlen(ipAddress)) == 0)
+            && (info->port == port))
+        {
+            return info->isServerStarted;
+        }
+    }
+    return false;
+}
+
+uint16_t CAGetServerPort(const u_arraylist_t *serverInfoList, const char *ipAddress, bool isSecured)
+{
+    VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", 0);
+    VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", 0);
+
+    uint32_t listLength = u_arraylist_length(serverInfoList);
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex);
+        if (!info)
+        {
+            continue;
+        }
+        if ((strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0) &&
+                    (info->isSecured == isSecured))
+        {
+            return info->port;
+        }
+    }
+
+    return 0;
+}
+
+int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList, const char *ipAddress,
+                                  bool isSecured, bool isMulticast, CATransportType_t type)
+{
+    VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", -1);
+    VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", -1);
+
+    uint32_t listLength = u_arraylist_length(serverInfoList);
+
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex);
+        if (!info)
+        {
+            continue;
+        }
+
+        if (!CAAdapterIsSameSubnet(info->ipAddress, ipAddress, info->subNetMask))
+        {
+            continue;
+        }
+
+        if (!info->isMulticastServer && (info->isSecured == isSecured))
+        {
+            OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG,
+                      "CAGetSocketFdForServer found socket [%d]", info->socketFd);
+            return info->socketFd;
+        }
+
+    }
+
+    OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG,
+            "CAGetSocketFdForServer socket fd is not found");
+    return -1;
+}
+
+CAResult_t CAAddServerInfo(u_arraylist_t *serverInfoList, CAServerInfo_t *info)
+{
+    VERIFY_NON_NULL(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null");
+    VERIFY_NON_NULL(info, CA_ADAPTER_UTILS_TAG, "info is null");
+
+    CAResult_t result = u_arraylist_add(serverInfoList, (void *) info);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "u_arraylist_add failed!");
+    }
+    return result;
+}
+
+void CARemoveServerInfo(u_arraylist_t *serverInfoList, int sockFd)
+{
+    VERIFY_NON_NULL_VOID(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null");
+
+    uint32_t listLength = u_arraylist_length(serverInfoList);
+    for (uint32_t listIndex = 0; listIndex < listLength;)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex);
+        if (!info)
+        {
+            listIndex++;
+            continue;
+        }
+
+        if (info->socketFd == sockFd)
+        {
+            if (u_arraylist_remove(serverInfoList, listIndex))
+            {
+                OICFree(info);
+                listLength--;
+            }
+            else
+            {
+                OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "u_arraylist_remove failed!");
+                break;
+            }
+        }
+        else
+        {
+            listIndex++;
+        }
+    }
+}
+
+void CAClearNetInterfaceInfoList(u_arraylist_t *infoList)
+{
+    uint32_t listLength = u_arraylist_length(infoList);
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(infoList, listIndex);
+        if (!netInfo)
+        {
+            continue;
+        }
+        OICFree(netInfo);
+    }
+    u_arraylist_free(&infoList);
+}
+
+void CAClearServerInfoList(u_arraylist_t *serverInfoList)
+{
+    uint32_t listLength = u_arraylist_length(serverInfoList);
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CAServerInfo_t *serverInfo = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex);
+        if (!serverInfo)
+        {
+            continue;
+        }
+        OICFree(serverInfo);
+    }
+    u_arraylist_free(&serverInfoList);
+}
+
+#ifdef __ANDROID__
+void CANativeJNISetContext(JNIEnv *env, jobject context)
+{
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeJNISetContext");
+
+    if (!context)
+    {
+        OIC_LOG(DEBUG, CA_ADAPTER_UTILS_TAG, "context is null");
+
+    }
+
+    g_Context = (*env)->NewGlobalRef(env, context);
+}
+
+void CANativeJNISetJavaVM(JavaVM *jvm)
+{
+    OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeJNISetJavaVM");
+    g_jvm = jvm;
+}
+
+jobject CANativeJNIGetContext()
+{
+    return g_Context;
+}
+
+JavaVM *CANativeJNIGetJavaVM()
+{
+    return g_jvm;
+}
+#endif
+
diff --git a/resource/csdk/connectivity/src/adapter_util/camsgparser.c b/resource/csdk/connectivity/src/adapter_util/camsgparser.c
new file mode 100644 (file)
index 0000000..16e8bde
--- /dev/null
@@ -0,0 +1,68 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "camsgparser.h"
+
+#include <string.h>
+#include <math.h>
+
+#include "cacommon.h"
+#include "caadapterutils.h"
+
+/**
+ * @var CA_MSG_PARSER_TAG
+ * @brief debugging tag for parser module
+ */
+#define CA_MSG_PARSER_TAG "CA_MSG_PARSER"
+
+CAResult_t CAGenerateHeader(char *header, uint32_t length)
+{
+    OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
+
+    VERIFY_NON_NULL(header, CA_MSG_PARSER_TAG, "header is NULL");
+    memset(header, 0x0, sizeof(char) * CA_HEADER_LENGTH);
+
+    if(length > MAX_DATA_LENGTH_SUPPORTED)
+    {
+        OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "Given length is more than 4095.It will be truncated");
+    }
+    //if length is more than 4095 then it will be truncated.
+    header[1] = length & 0xFF;
+    length >>= 8;
+    header[0] = length & 0x0F;
+    header[0] = header[0] | 0x40; // Adding version 0100.(Not used. Future use)
+
+    OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+uint32_t CAParseHeader(const char *header)
+{
+    OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
+
+    VERIFY_NON_NULL(header, CA_MSG_PARSER_TAG, "header is NULL");
+
+    uint32_t dataLen = ((header[0] & 0x0F) << 8) | (header[1] & 0xFF);
+
+    OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
+    return dataLen;
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/SConscript b/resource/csdk/connectivity/src/bt_edr_adapter/SConscript
new file mode 100644 (file)
index 0000000..4e2fa34
--- /dev/null
@@ -0,0 +1,44 @@
+#######################################################
+#      Building BT adapter
+#######################################################
+
+Import('env')
+
+print"Reading bt adapter script"
+
+target_os = env.get('TARGET_OS')
+
+if target_os == 'tizen':
+    env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
+
+src_dir = './bt_edr_adapter/'
+
+#Source files to build common for all platforms
+if target_os != 'arduino':
+       env.AppendUnique(CA_SRC=[src_dir+'caedradapter.c'])
+
+#Source files to build in Linux platform
+if target_os == 'linux':
+       env.AppendUnique(CA_SRC=[src_dir+'linux/caedradapter.c',
+                       ])
+
+#Source files to build in Tizen platform
+if target_os == 'tizen':
+       env.PrependUnique(CPPPATH = [src_dir + 'tizen'])
+       env.AppendUnique(CA_SRC=[src_dir+'tizen/caedrclient.c',
+                       src_dir+'tizen/caedrdevicelist.c',
+                       src_dir+'tizen/caedrendpoint.c',
+                       src_dir+'tizen/caedrnwmonitor.c',
+                       src_dir+'tizen/caedrserver.c',
+                       src_dir+'tizen/caedrutils.c',
+                       ])
+
+#Source files to build in Android platform
+if target_os == 'android':
+       env.AppendUnique(CA_SRC=[src_dir+'caedradapter.c',
+                       src_dir+'android/caedrclient.c',
+                       src_dir+'android/caedrutils.c',
+                       src_dir+'android/caedrnwmonitor.c',
+                       src_dir+'android/caedrserver.c',
+                       ])
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c
new file mode 100644 (file)
index 0000000..0065fbe
--- /dev/null
@@ -0,0 +1,1075 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include <jni.h>
+
+#include "caedrinterface.h"
+#include "caedrutils.h"
+#include "caedrclient.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "cathreadpool.h" /* for thread pool */
+#include "camutex.h"
+#include "uarraylist.h"
+#include "caadapterutils.h"
+
+//#define DEBUG_MODE
+#define TAG PCF("CA_EDR_CLIENT")
+
+static const char METHODID_CONTEXTNONPARAM[] = "()Landroid/content/Context;";
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char METHODID_OUTPUTNONPARAM[] = "()Ljava/io/OutputStream;";
+static const char METHODID_STRINGNONPARAM[] = "()Ljava/lang/String;";
+static const char METHODID_BT_DEVICEPARAM[] =
+        "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;";
+static const char CLASSPATH_BT_ADPATER[] = "android/bluetooth/BluetoothAdapter";
+static const char CLASSPATH_BT_DEVICE[] = "android/bluetooth/BluetoothDevice";
+static const char CLASSPATH_BT_INTERFACE[] = "org/iotivity/jar/caedrinterface";
+static const char CLASSPATH_BT_SOCKET[] = "android/bluetooth/BluetoothSocket";
+static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
+static const char CLASSPATH_CONTEXT[] = "android/content/Context";
+static const char CLASSPATH_OUTPUT[] = "java/io/OutputStream";
+
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+
+static JavaVM *g_jvm;
+static jobject g_context;
+
+/**
+ * @var g_mutexUnicastServer
+ * @brief Mutex to synchronize unicast server
+ */
+static ca_mutex g_mutexUnicastServer = NULL;
+
+/**
+ * @var g_stopUnicast
+ * @brief Flag to control the Receive Unicast Data Thread
+ */
+static bool g_stopUnicast = false;
+
+/**
+ * @var g_mutexMulticastServer
+ * @brief Mutex to synchronize secure multicast server
+ */
+static ca_mutex g_mutexMulticastServer = NULL;
+
+/**
+ * @var g_stopMulticast
+ * @brief Flag to control the Receive Multicast Data Thread
+ */
+static bool g_stopMulticast = false;
+
+/**
+ * @var g_stopAccept
+ * @brief Flag to control the Accept Thread
+ */
+static bool g_stopAccept = false;
+
+/**
+ * @var g_mutexStateList
+ * @brief Mutex to synchronize device state list
+ */
+static ca_mutex g_mutexStateList = NULL;
+
+/**
+ * @var g_mutexObjectList
+ * @brief Mutex to synchronize device object list
+ */
+static ca_mutex g_mutexObjectList = NULL;
+
+typedef struct send_data
+{
+    char* address;
+    char* data;
+    uint32_t id;
+} data_t;
+
+/**
+ @brief Thread context information for unicast, multicast and secured unicast server
+ */
+typedef struct
+{
+    bool *stopFlag;
+    CAAdapterServerType_t type;
+} CAAdapterReceiveThreadContext_t;
+
+typedef struct
+{
+    bool *stopFlag;
+} CAAdapterAcceptThreadContext_t;
+
+/**
+ * implement for BT-EDR adapter common method
+ */
+CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAEDRGetInterfaceInformation");
+
+    if (!info)
+    {
+        OIC_LOG(ERROR, TAG, "LocalConnectivity info is null");
+        return CA_STATUS_FAILED;
+    }
+
+    int32_t netInfoSize = 1;
+
+    char *macAddress = NULL;
+    CAResult_t ret = CAEDRGetInterfaceInfo(&macAddress);
+    OIC_LOG_V(ERROR, TAG, "address : %s", macAddress);
+    if (NULL == macAddress)
+    {
+        OIC_LOG(ERROR, TAG, "mac address is null");
+
+        return CA_STATUS_FAILED;
+    }
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to get interface info [%d]", ret);
+
+        OICFree(macAddress);
+        return ret;
+    }
+
+    // Create local endpoint using util function
+    CALocalConnectivity_t *endpoint = CAAdapterCreateLocalEndpoint(CA_EDR, macAddress);
+    if (NULL == endpoint)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create Local Endpoint!");
+        OICFree(macAddress);
+        return CA_STATUS_FAILED;
+    }
+
+    // copy unicast server information
+    endpoint->isSecured = false;
+    CALocalConnectivity_t *netInfo = (CALocalConnectivity_t *) OICMalloc(
+            sizeof(CALocalConnectivity_t) * netInfoSize);
+    if (NULL == netInfo)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid input..");
+        OICFree(macAddress);
+        CAAdapterFreeLocalEndpoint(endpoint);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memcpy(netInfo, endpoint, sizeof(CALocalConnectivity_t));
+    *info = netInfo;
+
+    OICFree(macAddress);
+    CAAdapterFreeLocalEndpoint(endpoint);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CAEDRGetInterfaceInformation");
+    return CA_STATUS_OK;
+}
+
+void CAEDRClientTerminate()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAEDRTerminate();
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAEDRManagerReadData(void)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress, const char *serviceUUID,
+                                      const void *data, uint32_t dataLength, uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAEDRSendUnicastMessage(remoteAddress, (const char*) data, dataLength);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, const void *data,
+                                        uint32_t dataLength, uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAEDRSendMulticastMessage((const char*) data, dataLength);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+// It will be updated when android EDR support is added
+void CAEDRClientUnsetCallbacks(void)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+// It will be updated when android EDR support is added
+void CAEDRClientDisconnectAll(void)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAEDRGetAdapterEnableState(bool *state)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRGetAdapterEnableState - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return CA_STATUS_INVALID_PARAM;
+        }
+        isAttached = true;
+    }
+    jboolean ret = CAEDRNativeIsEnableBTAdapter(env);
+    if (ret)
+    {
+        *state = true;
+    }
+    else
+    {
+        *state = false;
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRJniInitContext()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRJniInitContext");
+
+    g_context = (jobject) CANativeJNIGetContext();
+}
+
+CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
+{
+    JNIEnv* env;
+    OIC_LOG(DEBUG, TAG, "[EDRCore] CAEDRCreateJNIInterfaceObject");
+
+    if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
+    {
+        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get JNIEnv pointer");
+        return CA_STATUS_FAILED;
+    }
+
+    //getApplicationContext
+    jclass contextClass = (*env)->FindClass(env, CLASSPATH_CONTEXT);
+    if (!contextClass)
+    {
+        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get context object class");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID getApplicationContextMethod = (*env)->GetMethodID(env, contextClass,
+                                                                "getApplicationContext",
+                                                                METHODID_CONTEXTNONPARAM);
+    if (!getApplicationContextMethod)
+    {
+        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get getApplicationContext method");
+        return CA_STATUS_FAILED;
+    }
+
+    //Create EDRJniInterface instance
+    jclass EDRJniInterface = (*env)->FindClass(env, CLASSPATH_BT_INTERFACE);
+    if (!EDRJniInterface)
+    {
+        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get caedrinterface class");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID EDRInterfaceConstructorMethod = (*env)->GetMethodID(env, EDRJniInterface, "<init>",
+                                                                  "(Landroid/content/Context;)V");
+    if (!EDRInterfaceConstructorMethod)
+    {
+        OIC_LOG(ERROR, TAG, "[EDRCore] Could not get caedrinterface constructor method");
+        return CA_STATUS_FAILED;
+    }
+
+    (*env)->NewObject(env, EDRJniInterface, EDRInterfaceConstructorMethod, context);
+    OIC_LOG(DEBUG, TAG, "[EDRCore] NewObject Success");
+
+    return CA_STATUS_OK;
+
+}
+
+static void CAEDRDestroyMutex()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (g_mutexUnicastServer)
+    {
+        ca_mutex_free(g_mutexUnicastServer);
+        g_mutexUnicastServer = NULL;
+    }
+
+    if (g_mutexMulticastServer)
+    {
+        ca_mutex_free(g_mutexMulticastServer);
+        g_mutexMulticastServer = NULL;
+    }
+
+    if (g_mutexStateList)
+    {
+        ca_mutex_free(g_mutexStateList);
+        g_mutexStateList = NULL;
+    }
+
+    if (g_mutexObjectList)
+    {
+        ca_mutex_free(g_mutexObjectList);
+        g_mutexObjectList = NULL;
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static CAResult_t CAEDRCreateMutex()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    g_mutexUnicastServer = ca_mutex_new();
+    if (!g_mutexUnicastServer)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexMulticastServer = ca_mutex_new();
+    if (!g_mutexMulticastServer)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexStateList = ca_mutex_new();
+    if (!g_mutexStateList)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexObjectList = ca_mutex_new();
+    if (!g_mutexObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRInitialize(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRInitialize");
+
+    g_threadPoolHandle = handle;
+
+    CAEDRCoreJniInit();
+
+    CAEDRJniInitContext();
+
+    // init mutex
+    CAEDRCreateMutex();
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRInitialize - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return;
+        }
+        isAttached = true;
+    }
+    jstring jni_address = CAEDRNativeGetLocalDeviceAddress(env);
+    if (jni_address)
+    {
+        const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        OIC_LOG_V(DEBUG, TAG, "My BT Address is %s", localAddress);
+        (*env)->ReleaseStringUTFChars(env, jni_address, localAddress);
+    }
+
+    ca_mutex_lock(g_mutexStateList);
+    CAEDRNativeCreateDeviceStateList();
+    ca_mutex_unlock(g_mutexStateList);
+
+    ca_mutex_lock(g_mutexObjectList);
+    CAEDRNativeCreateDeviceSocketList();
+    ca_mutex_unlock(g_mutexObjectList);
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    if (g_context)
+    {
+        CAEDRCreateJNIInterfaceObject(g_context); /* create java caedrinterface instance*/
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAEDRTerminate()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRTerminate");
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRTerminate - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    g_stopAccept = true;
+    g_stopMulticast = true;
+    g_stopUnicast = true;
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    if (g_context)
+    {
+        (*env)->DeleteGlobalRef(env, g_context);
+    }
+
+    CAEDRNativeSocketCloseToAll(env);
+
+    // delete mutex
+    CAEDRDestroyMutex();
+
+    CAEDRNativeRemoveAllDeviceState();
+    CAEDRNativeRemoveAllDeviceSocket(env);
+}
+
+void CAEDRCoreJniInit()
+{
+    OIC_LOG(DEBUG, TAG, "CAEdrClientJniInit");
+    g_jvm = (JavaVM*) CANativeJNIGetJavaVM();
+}
+
+CAResult_t CAEDRSendUnicastMessage(const char* address, const char* data, uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CAEDRSendUnicastMessage(%s, %s)", address, data);
+
+    CAEDRSendUnicastMessageImpl(address, data, dataLen);
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRSendMulticastMessage(const char* data, uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CAEDRSendMulticastMessage(%s)", data);
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRSendMulticastMessage - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return CA_STATUS_INVALID_PARAM;
+        }
+        isAttached = true;
+    }
+
+    CAEDRSendMulticastMessageImpl(env, data, dataLen);
+
+    OIC_LOG(DEBUG, TAG, "sent data");
+
+    if (isAttached)
+    {
+        OIC_LOG(DEBUG, TAG, "DetachCurrentThread");
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CAEDRSendMulticastMessage");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRGetInterfaceInfo(char **address)
+{
+    CAEDRGetLocalAddress(address);
+    return CA_STATUS_OK;
+}
+
+void CAEDRGetLocalAddress(char **address)
+{
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRGetLocalAddress - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    jstring jni_address = CAEDRNativeGetLocalDeviceAddress(env);
+    if (jni_address)
+    {
+        const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        *address = (char*) OICMalloc(strlen(localAddress) + 1);
+        if (*address == NULL)
+        {
+            if (isAttached)
+            {
+                (*g_jvm)->DetachCurrentThread(g_jvm);
+            }
+            return;
+        }
+        memcpy(*address, localAddress, strlen(localAddress));
+        (*env)->ReleaseStringUTFChars(env, jni_address, localAddress);
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "Local Address : %s", *address);
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+}
+
+CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const char* data, uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CAEDRSendUnicastMessageImpl, address: %s, data: %s", address, data);
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRSendUnicastMessageImpl - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return CA_STATUS_INVALID_PARAM;
+        }
+        isAttached = true;
+    }
+
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] set byteArray for data");
+
+    // get bonded device list
+    jobjectArray jni_arrayPairedDevices = CAEDRNativeGetBondedDevices(env);
+    if (!jni_arrayPairedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_arrayPairedDevices is empty");
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return CA_STATUS_INVALID_PARAM;
+    }
+    // Get information from array of devices
+    jclass jni_cid_BTDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
+    jmethodID j_mid_getName = (*env)->GetMethodID(env, jni_cid_BTDevice, "getName",
+                                                  METHODID_STRINGNONPARAM);
+    jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice, "getAddress",
+                                                     METHODID_STRINGNONPARAM);
+
+    jsize length = (*env)->GetArrayLength(env, jni_arrayPairedDevices);
+    jsize i;
+    for (i = 0; i < length; i++)
+    {
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] start to check device");
+        // get name, address from BT device
+        jobject j_obj_device = (*env)->GetObjectArrayElement(env, jni_arrayPairedDevices, i);
+        jstring j_str_name = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getName);
+
+        if (j_str_name)
+        {
+            const char * name = (*env)->GetStringUTFChars(env, j_str_name, NULL);
+            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] getBondedDevices: ~~device name is %s", name);
+            (*env)->ReleaseStringUTFChars(env, j_str_name, name);
+        }
+
+        jstring j_str_address = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getAddress);
+        const char * remoteAddress = (*env)->GetStringUTFChars(env, j_str_address, NULL);
+        OIC_LOG_V(DEBUG, TAG,
+                  "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
+
+        if (!remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+            if (isAttached)
+            {
+                (*g_jvm)->DetachCurrentThread(g_jvm);
+            }
+            return CA_STATUS_INVALID_PARAM;
+        }
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] address is null");
+            if (isAttached)
+            {
+                (*g_jvm)->DetachCurrentThread(g_jvm);
+            }
+            (*env)->ReleaseStringUTFChars(env, j_str_address, remoteAddress);
+            return CA_STATUS_INVALID_PARAM;
+        }
+        // find address
+        if (!strcmp(remoteAddress, address))
+        {
+            CAResult_t res = CAEDRNativeSendData(env, remoteAddress, data, dataLen, i);
+            if (CA_STATUS_OK != res)
+            {
+                (*env)->ReleaseStringUTFChars(env, j_str_address, remoteAddress);
+                return res;
+            }
+        }
+        (*env)->ReleaseStringUTFChars(env, j_str_address, remoteAddress);
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const char* data, uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, send to, data: %s, %d", data, dataLen);
+
+    // get bonded device list
+    jobjectArray jni_arrayPairedDevices = CAEDRNativeGetBondedDevices(env);
+    if (!jni_arrayPairedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_arrayPairedDevices is empty");
+        return CA_STATUS_INVALID_PARAM;
+    }
+    // Get information from array of devices
+    jclass jni_cid_BTDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
+    jmethodID j_mid_getName = (*env)->GetMethodID(env, jni_cid_BTDevice, "getName",
+                                                  METHODID_STRINGNONPARAM);
+    jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice, "getAddress",
+                                                     METHODID_STRINGNONPARAM);
+
+    jsize length = (*env)->GetArrayLength(env, jni_arrayPairedDevices);
+    jsize i;
+    for (i = 0; i < length; i++)
+    {
+        // get name, address from BT device
+        jobject j_obj_device = (*env)->GetObjectArrayElement(env, jni_arrayPairedDevices, i);
+        jstring j_str_name = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getName);
+
+        if (j_str_name)
+        {
+            const char * name = (*env)->GetStringUTFChars(env, j_str_name, NULL);
+            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] getBondedDevices: ~~device name is %s", name);
+            (*env)->ReleaseStringUTFChars(env, j_str_name, name);
+        }
+
+        jstring j_str_address = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getAddress);
+        const char * remoteAddress = (*env)->GetStringUTFChars(env, j_str_address, NULL);
+        OIC_LOG_V(DEBUG, TAG,
+                  "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
+
+        // find address
+        CAResult_t res = CAEDRNativeSendData(env, remoteAddress, data, dataLen, i);
+        (*env)->ReleaseStringUTFChars(env, j_str_address, remoteAddress);
+        if (CA_STATUS_OK != res)
+        {
+            return res;
+        }
+    }
+
+    return CA_STATUS_OK;
+}
+
+/**
+ * EDR Method
+ */
+CAResult_t CAEDRNativeSendData(JNIEnv *env, const char *address, const char *data,
+                               uint32_t dataLength, uint32_t id)
+{
+    OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btSendData logic start : %s, %d", data, dataLength);
+
+    if (!CAEDRNativeIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (STATE_DISCONNECTED == CAEDRIsConnectedDevice(address))
+    {
+        // connect before send data
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] connect before send data");
+
+        if (NULL == address)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] remote address is empty");
+            return CA_STATUS_INVALID_PARAM;
+        }
+        else
+        {
+            CAResult_t res = CAEDRNativeConnect(env, address, id);
+            if (CA_STATUS_OK != res)
+            {
+                return res;
+            }
+        }
+    }
+
+    if (STATE_CONNECTED == CAEDRIsConnectedDevice(address))
+    {
+        if (!((*env)->ExceptionCheck(env)))
+        {
+            jclass jni_cid_BTsocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
+            if (!jni_cid_BTsocket)
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_cid_BTsocket is null");
+                return CA_STATUS_FAILED;
+            }
+
+            jmethodID jni_mid_getOutputStream = (*env)->GetMethodID(env, jni_cid_BTsocket,
+                                                                    "getOutputStream",
+                                                                    METHODID_OUTPUTNONPARAM);
+            if (!jni_mid_getOutputStream)
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_mid_getOutputStream is null");
+                return CA_STATUS_FAILED;
+            }
+
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: Get MethodID for i/o stream");
+
+            jobject jni_obj_socket = CAEDRNativeGetDeviceSocketBaseAddr(env, address);
+            if (!jni_obj_socket)
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_socket is not available");
+                return CA_STATUS_FAILED;
+            }
+
+            jobject jni_obj_outputStream = (*env)->CallObjectMethod(env, jni_obj_socket,
+                                                                    jni_mid_getOutputStream);
+            if (!jni_obj_outputStream)
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_obj_outputStream is null");
+                return CA_STATUS_FAILED;
+            }
+
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: ready outputStream..");
+
+            jclass jni_cid_OutputStream = (*env)->FindClass(env, CLASSPATH_OUTPUT);
+            if (!jni_cid_OutputStream)
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_cid_OutputStream is null");
+                return CA_STATUS_FAILED;
+            }
+
+            jmethodID jni_mid_write = (*env)->GetMethodID(env, jni_cid_OutputStream, "write",
+                                                          "([BII)V");
+            if (!jni_mid_write)
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_mid_write is null");
+                return CA_STATUS_FAILED;
+            }
+
+            jbyteArray jbuf;
+            jbuf = (*env)->NewByteArray(env, dataLength);
+            (*env)->SetByteArrayRegion(env, jbuf, 0, dataLength, (jbyte*) data);
+
+            (*env)->CallVoidMethod(env, jni_obj_outputStream, jni_mid_write, jbuf, (jint) 0,
+                                   (jint) dataLength);
+
+            if ((*env)->ExceptionCheck(env))
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: Write Error!!!");
+                (*env)->ExceptionDescribe(env);
+                (*env)->ExceptionClear(env);
+                return CA_STATUS_FAILED;
+            }
+
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: Write Success");
+        }
+        else
+        {
+            (*env)->ExceptionDescribe(env);
+            (*env)->ExceptionClear(env);
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: error!!");
+            return CA_STATUS_FAILED;
+        }
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: BT connection is not completed!!");
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address, uint32_t id)
+{
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect..");
+
+    if (!CAEDRNativeIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get BTadpater
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_getDefaultAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get remote bluetooth device
+    jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                            "getRemoteDevice",
+                                                            METHODID_BT_DEVICEPARAM);
+    if (!jni_mid_getRemoteDevice)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_getRemoteDevice is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jstring jni_address = (*env)->NewStringUTF(env, address);
+    jobject jni_obj_remoteBTDevice = (*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+                                                              jni_mid_getRemoteDevice, jni_address);
+    if (!jni_obj_remoteBTDevice)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_remoteBTDevice is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get create Rfcomm Socket method ID
+    jclass jni_cid_BluetoothDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
+    if (!jni_cid_BluetoothDevice)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_BluetoothDevice is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_createSocket = (*env)->GetMethodID(
+            env, jni_cid_BluetoothDevice, "createInsecureRfcommSocketToServiceRecord",
+            "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;");
+    if (!jni_mid_createSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_createSocket is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // setting UUID
+    jclass jni_cid_uuid = (*env)->FindClass(env, CLASSPATH_BT_UUID);
+    if (!jni_cid_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_uuid is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(
+            env, jni_cid_uuid, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
+    if (!jni_mid_fromString)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_fromString is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jstring jni_uuid = (*env)->NewStringUTF(env, OIC_EDR_SERVICE_ID);
+    if (!jni_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_uuid is null");
+        return CA_STATUS_FAILED;
+    }
+    jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString,
+                                                          jni_uuid);
+    if (!jni_obj_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_uuid is null");
+        return CA_STATUS_FAILED;
+    }
+    // create socket
+    jobject jni_obj_BTSocket = (*env)->CallObjectMethod(env, jni_obj_remoteBTDevice,
+                                                        jni_mid_createSocket, jni_obj_uuid);
+    if (!jni_obj_BTSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_obj_BTSocket is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // connect
+    jclass jni_cid_BTSocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
+    if (!jni_cid_BTSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_cid_BTSocket is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_connect = (*env)->GetMethodID(env, jni_cid_BTSocket, "connect", "()V");
+    if (!jni_mid_connect)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_mid_connect is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: initiating connection...");
+    (*env)->CallVoidMethod(env, jni_obj_BTSocket, jni_mid_connect);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: Connect is Failed!!!");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    // set socket to list
+    jobject jni_socket = (*env)->NewGlobalRef(env, jni_obj_BTSocket);
+    if (!jni_socket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btConnect: jni_socket is null");
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_lock(g_mutexObjectList);
+    CAEDRNativeAddDeviceSocketToList(env, jni_socket);
+    ca_mutex_unlock(g_mutexObjectList);
+
+    // update state
+    ca_mutex_lock(g_mutexStateList);
+    CAEDRUpdateDeviceState(STATE_CONNECTED, address);
+    ca_mutex_unlock(g_mutexStateList);
+
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: connected");
+
+    return CA_STATUS_OK;
+}
+
+void CAEDRNativeSocketClose(JNIEnv *env, const char *address, uint32_t id)
+{
+
+    jclass jni_cid_BTSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
+    if (!jni_cid_BTSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
+        return;
+    }
+
+    jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_BTSocket, "close", "()V");
+    if (!jni_mid_close)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_mid_close is null");
+        return;
+    }
+
+    jobject jni_obj_socket = CAEDRNativeGetDeviceSocketBaseAddr(env, address);
+    if (!jni_obj_socket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_obj_socket is not available");
+        return;
+    }
+
+    (*env)->CallVoidMethod(env, jni_obj_socket, jni_mid_close);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] close: close is Failed!!!");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return;
+    }
+
+    // remove socket to list
+    CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
+
+    // update state
+    ca_mutex_lock(g_mutexStateList);
+    CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
+    ca_mutex_unlock(g_mutexStateList);
+
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] close: disconnected");
+}
+
+void CAEDRInitializeClient(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAEDRInitialize(handle);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.h b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.h
new file mode 100644 (file)
index 0000000..e655193
--- /dev/null
@@ -0,0 +1,169 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * @brief This file contains the APIs for BT EDR communications.
+ */
+#ifndef CA_EDR_CLIENT_H_
+#define CA_EDR_CLIENT_H_
+
+#include <stdbool.h>
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "jni.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   Initialize context of application
+ * @return  None
+ */
+void CAEDRJniInitContext();
+
+/**
+ * @brief   Create JNI Object
+ * @param   context          [IN] context of application
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRCreateJNIInterfaceObject(jobject context);
+
+/**
+ * @brief   Initialize client for EDR
+ * @param   handle           [IN] thread pool handle object
+ * @return  None
+ */
+void CAEDRInitialize(ca_thread_pool_t handle);
+
+/**
+ * @brief   Terminate server for EDR
+ * @return  None
+ */
+void CAEDRTerminate();
+
+/**
+ * @brief   Initialize JNI object
+ * @return  None
+ */
+void CAEDRCoreJniInit();
+
+/**
+ * @brief   Send data for unicast
+ * @param   address         [IN] remote address
+ * @param   data            [IN] data for transmission
+ * @param   dataLen         [IN] data length
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendUnicastMessage(const char *address, const char *data, uint32_t dataLen);
+
+/**
+ * @brief   Send data for multicast
+ * @param   data            [IN] data for transmission
+ * @param   dataLen         [IN] data length
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendMulticastMessage(const char *data, uint32_t dataLen);
+
+/**
+ * @brief   Get Local EDR Address
+ * @param   address         [OUT] local address
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRGetInterfaceInfo(char **address);
+
+/**
+ * @brief   Get address from a local device
+ * @param   address         [OUT] local address
+ * @return  None
+ */
+void CAEDRGetLocalAddress(char **address);
+
+/**
+ * @brief   Send data for unicast (implement)
+ * @param   address         [IN] remote address
+ * @param   data            [IN] data for transmission
+ * @param   dataLen         [IN] data length
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendUnicastMessageImpl(const char *address, const char *data, uint32_t dataLen);
+
+/**
+ * @brief   Send data for multicast (implement)
+ * @param   env             [IN] JNI interface pointer
+ * @param   data            [IN] data for transmission
+ * @param   dataLen         [IN] data length
+ * @return  #CA_STATUS_OK or Appropriate error code
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const char *data, uint32_t dataLen);
+
+/**
+ * EDR Method
+ */
+
+/**
+ * @brief  This function will send the data to remote device.
+ * @param  env              [IN] JNI interface pointer
+ * @param  address          [IN] Remote Address
+ * @param  data             [IN] Data to be transmitted from EDR
+ * @param  dataLength       [IN] Length of data
+ * @param  id               [IN] index of remote address
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRNativeSendData(JNIEnv *env, const char* address, const char* data,
+                               uint32_t dataLength, uint32_t id);
+
+/**
+ * @brief  This function will connect to remote device.
+ * @param  env              [IN] JNI interface pointer
+ * @param  address          [IN] Remote Address
+ * @param  id               [IN] index of remote address
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address, uint32_t id);
+
+/**
+ * @brief  This function will close socket.
+ * @param  env              [IN] JNI interface pointer
+ * @param  address          [IN] Remote Address
+ * @param  id               [IN] index of remote address
+ * @return None
+ */
+void CAEDRNativeSocketClose(JNIEnv *env, const char *address, uint32_t id);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_CLIENT_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.c b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.c
new file mode 100644 (file)
index 0000000..e91e415
--- /dev/null
@@ -0,0 +1,170 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include <jni.h>
+
+#include "caedrinterface.h"
+#include "caedrnwmonitor.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "cathreadpool.h" /* for thread pool */
+#include "camutex.h"
+#include "uarraylist.h"
+#include "caadapterutils.h"
+#include "caedrserver.h"
+#include "caedrutils.h"
+
+#include "org_iotivity_jar_caedrinterface.h"
+
+//#define DEBUG_MODE
+#define TAG PCF("CA_EDR_MONITOR")
+
+static JavaVM *g_jvm;
+static jobject g_context;
+static CAEDRNetworkStatusCallback g_networkChangeCb = NULL;
+
+static const char CLASSPATH_BT_ADPATER[] = "android/bluetooth/BluetoothAdapter";
+
+void CAEDRNetworkMonitorJNISetContext()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNetworkMonitorJNISetContext");
+    g_context = (jobject) CANativeJNIGetContext();
+}
+
+//getting jvm
+void CAEDRNetworkMonitorJniInit()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNetworkMonitorJniInit");
+    g_jvm = (JavaVM*) CANativeJNIGetJavaVM();
+}
+
+CAResult_t CAEDRInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAEDRNetworkMonitorJniInit();
+    CANativeJNIGetJavaVM();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRSetNetworkChangeCallback(CAEDRNetworkStatusCallback networkChangeCallback)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRSetNetworkChangeCallback");
+    g_networkChangeCb = networkChangeCallback;
+}
+
+void CAEDRTerminateNetworkMonitor(void)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAEDRStartNetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStopNetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRClientSetCallbacks(void)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caedrinterface_CAEDRStateChangedCallback(JNIEnv *env, jobject obj,
+                                                               jint status)
+{
+    // STATE_ON:12, STATE_OFF:10
+    OIC_LOG(DEBUG, TAG, "caedrinterface - Network State Changed");
+
+    if (NULL == g_networkChangeCb)
+    {
+        OIC_LOG_V(DEBUG, TAG, "gNetworkChangeCb is null", status);
+    }
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_BTAdapter is null");
+        return;
+    }
+
+    jfieldID id_state_on = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_ON", "I");
+    if (!id_state_on)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] id_state_on is null");
+        return;
+    }
+
+    jfieldID id_state_off = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_OFF", "I");
+    if (!id_state_off)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] id_state_off is null");
+        return;
+    }
+
+    jint state_on = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, id_state_on);
+    jint state_off = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, id_state_off);
+
+    if (state_on == status)
+    {
+        CANetworkStatus_t newStatus = CA_INTERFACE_UP;
+        CAEDRServerStartAcceptThread();
+        g_networkChangeCb(newStatus);
+    }
+    else if (state_off == status)
+    {
+        CANetworkStatus_t newStatus = CA_INTERFACE_DOWN;
+        CAEDRNativeRemoveAllDeviceSocket(env);
+        CAEDRNativeRemoveAllDeviceState(env);
+        g_networkChangeCb(newStatus);
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caedrinterface_CAEDRBondStateChangedCallback(JNIEnv *env, jobject obj,
+                                                                   jstring addr)
+{
+    OIC_LOG(DEBUG, TAG, "caedrinterface - Bond State Changed");
+
+    if (addr)
+    {
+        CAEDRNativeRemoveDeviceSocketBaseAddr(env, addr);
+        CAEDRNativeRemoveDevice(addr);
+    }
+}
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.h b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.h
new file mode 100644 (file)
index 0000000..947d501
--- /dev/null
@@ -0,0 +1,52 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * @brief This file contains the APIs for BT LE communications.
+ */
+#ifndef CA_EDR_NW_MONITOR_H_
+#define CA_EDR_NW_MONITOR_H_
+
+#include "cacommon.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   Set context of application
+ * @return  None
+ */
+void CAEDRNetworkMonitorJNISetContext();
+
+/**
+ * @brief   Initialize JNI object
+ * @return  None
+ */
+void CAEDRNetworkMonitorJniInit();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_NW_MONITOR_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c
new file mode 100644 (file)
index 0000000..8705898
--- /dev/null
@@ -0,0 +1,1112 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+#include <jni.h>
+
+#include "caedrinterface.h"
+#include "caedrutils.h"
+#include "caedrserver.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "cathreadpool.h" /* for thread pool */
+#include "camutex.h"
+#include "uarraylist.h"
+#include "caadapterutils.h"
+#include "org_iotivity_jar_caedrinterface.h"
+
+//#define DEBUG_MODE
+#define TAG PCF("CA_EDR_SERVER")
+#define MAX_PDU_BUFFER (1024)
+
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char CLASSPATH_BT_ADPATER[] = "android/bluetooth/BluetoothAdapter";
+static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
+
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+
+static JavaVM *g_jvm;
+
+/**
+ * @var g_mMutexSocketListManager
+ * @brief Mutex to synchronize socket list update
+ */
+static ca_mutex g_mutexSocketListManager;
+
+// server socket instance
+static jobject g_serverSocketObject = NULL;
+
+/**
+ * @var g_mutexUnicastServer
+ * @brief Mutex to synchronize unicast server
+ */
+static ca_mutex g_mutexUnicastServer = NULL;
+
+/**
+ * @var g_stopUnicast
+ * @brief Flag to control the Receive Unicast Data Thread
+ */
+static bool g_stopUnicast = false;
+
+/**
+ * @var g_mutexMulticastServer
+ * @brief Mutex to synchronize secure multicast server
+ */
+static ca_mutex g_mutexMulticastServer = NULL;
+
+/**
+ * @var g_stopMulticast
+ * @brief Flag to control the Receive Multicast Data Thread
+ */
+static bool g_stopMulticast = false;
+
+/**
+ * @var g_mutexAcceptServer
+ * @brief Mutex to synchronize accept server
+ */
+static ca_mutex g_mutexAcceptServer = NULL;
+
+/**
+ * @var g_stopAccept
+ * @brief Flag to control the Accept Thread
+ */
+static bool g_stopAccept = false;
+
+static jobject g_inputStream = NULL;
+
+/**
+ * @var g_mutexServerSocket
+ * @brief Mutex to synchronize server socket
+ */
+static ca_mutex g_mutexServerSocket = NULL;
+
+static jobject g_serverSocket = NULL;
+
+/**
+ * @var g_mutexStateList
+ * @brief Mutex to synchronize device state list
+ */
+static ca_mutex g_mutexStateList = NULL;
+
+/**
+ * @var g_mutexObjectList
+ * @brief Mutex to synchronize device object list
+ */
+static ca_mutex g_mutexObjectList = NULL;
+
+typedef struct send_data
+{
+    char* address;
+    char* data;
+    uint32_t id;
+} data_t;
+
+/**
+ @brief Thread context information for unicast, multicast and secured unicast server
+ */
+typedef struct
+{
+    bool *stopFlag;
+    CAAdapterServerType_t type;
+} CAAdapterReceiveThreadContext_t;
+
+typedef struct
+{
+    bool *stopFlag;
+} CAAdapterAcceptThreadContext_t;
+
+/**
+ * @var g_edrPacketReceivedCallback
+ * @brief Maintains the callback to be notified when data received from remote Bluetooth device
+ */
+static CAEDRDataReceivedCallback g_edrPacketReceivedCallback = NULL;
+
+static void CAReceiveHandler(void *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler..");
+    // Input validation
+    VERIFY_NON_NULL_VOID(data, TAG, "Invalid thread context");
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAReceiveHandler - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) data;
+
+    while (true != *(ctx->stopFlag))
+    {
+        // if new socket object is added in socket list after below logic is ran.
+        // new socket will be started to read after next while loop
+        uint32_t length = CAEDRGetSocketListLength();
+        if (0 == length)
+        {
+            OIC_LOG(DEBUG, TAG, "socket list is empty");
+            sleep(1);
+        }
+
+        uint32_t idx;
+        for (idx = 0; idx < length; idx++)
+        {
+            OIC_LOG(DEBUG, TAG, "start CAEDRNativeReadData");
+            CAEDRNativeReadData(env, idx, ctx->type);
+            sleep(1);
+        }
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OICFree(ctx);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
+}
+
+static void CAAcceptHandler(void *data)
+{
+    if (!data)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] CAAcceptHandler: data is null");
+        return;
+    }
+
+    OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread start");
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAAcceptHandler - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    jobject jni_obj_BTServerSocket = CAEDRNativeListen(env);
+    if (!jni_obj_BTServerSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] AcceptThread: jni_obj_BTServerSocket is null");
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+
+        return;
+    }
+
+    ca_mutex_lock(g_mutexServerSocket);
+    g_serverSocket = (*env)->NewGlobalRef(env, jni_obj_BTServerSocket);
+    ca_mutex_unlock(g_mutexServerSocket);
+
+    CAAdapterAcceptThreadContext_t *ctx = (CAAdapterAcceptThreadContext_t *) data;
+
+    if (NULL == ctx)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] AcceptThread: ctx is null");
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return;
+    }
+
+    // it should be initialized for restart accept thread
+    ca_mutex_lock(g_mutexAcceptServer);
+    g_stopAccept = false;
+    ca_mutex_unlock(g_mutexAcceptServer);
+
+    while (true != *(ctx->stopFlag))
+    {
+        OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread running");
+
+        // when BT state is changed with Off. its thread will be stopped
+        if (!CAEDRNativeIsEnableBTAdapter(env))
+        {
+            OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
+            ca_mutex_lock(g_mutexAcceptServer);
+            g_stopAccept = true;
+            ca_mutex_unlock(g_mutexAcceptServer);
+            ca_mutex_lock(g_mutexServerSocket);
+            g_serverSocket = NULL;
+            ca_mutex_unlock(g_mutexServerSocket);
+        }
+        else
+        {
+            CAEDRNativeAccept(env, g_serverSocket);
+        }
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OICFree(ctx);
+
+    OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread finish");
+
+    return;
+}
+
+/**
+ * implement for adapter common method
+ */
+CAResult_t CAEDRServerStart(const char *serviceUUID, int32_t *serverFD, ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAEDRServerInitialize(handle);
+    CAResult_t res = CAEDRStartUnicastServer(false);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CAEDRStartUnicastServer failed");
+        return CA_STATUS_FAILED;
+    }
+
+    *serverFD = 1;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRServerStop(int serverFD)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAEDRStopUnicastServer(-1);
+    CAEDRStopMulticastServer(-1);
+
+    ca_mutex_lock(g_mutexAcceptServer);
+    g_stopAccept = true;
+    ca_mutex_unlock(g_mutexAcceptServer);
+
+    if (!g_jvm)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRServerStop - g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRServerStop - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAEDRNatvieCloseServerTask(env);
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRSetPacketReceivedCallback(CAEDRDataReceivedCallback packetReceivedCallback)
+{
+    g_edrPacketReceivedCallback = packetReceivedCallback;
+}
+
+/**
+ * Destroy Mutex
+ */
+static void CAEDRServerDestroyMutex()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (g_mutexUnicastServer)
+    {
+        ca_mutex_free(g_mutexUnicastServer);
+        g_mutexUnicastServer = NULL;
+    }
+
+    if (g_mutexMulticastServer)
+    {
+        ca_mutex_free(g_mutexMulticastServer);
+        g_mutexMulticastServer = NULL;
+    }
+
+    if (g_mutexSocketListManager)
+    {
+        ca_mutex_free(g_mutexSocketListManager);
+        g_mutexSocketListManager = NULL;
+    }
+
+    if (g_mutexAcceptServer)
+    {
+        ca_mutex_free(g_mutexAcceptServer);
+        g_mutexAcceptServer = NULL;
+    }
+
+    if (g_mutexServerSocket)
+    {
+        ca_mutex_free(g_mutexServerSocket);
+        g_mutexServerSocket = NULL;
+    }
+
+    if (g_mutexStateList)
+    {
+        ca_mutex_free(g_mutexStateList);
+        g_mutexStateList = NULL;
+    }
+
+    if (g_mutexObjectList)
+    {
+        ca_mutex_free(g_mutexObjectList);
+        g_mutexObjectList = NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+/*
+ * Create Mutex
+ */
+static CAResult_t CAEDRServerCreateMutex()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    g_mutexUnicastServer = ca_mutex_new();
+    if (!g_mutexUnicastServer)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexMulticastServer = ca_mutex_new();
+    if (!g_mutexMulticastServer)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRServerDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexSocketListManager = ca_mutex_new();
+    if (!g_mutexSocketListManager)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRServerDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexAcceptServer = ca_mutex_new();
+    if (!g_mutexAcceptServer)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRServerDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexServerSocket = ca_mutex_new();
+    if (!g_mutexServerSocket)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRServerDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexStateList = ca_mutex_new();
+    if (!g_mutexStateList)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRServerDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    g_mutexObjectList = ca_mutex_new();
+    if (!g_mutexObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to created mutex!");
+
+        CAEDRServerDestroyMutex();
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRServerJniInit()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRServerJniInit");
+    g_jvm = CANativeJNIGetJavaVM();
+}
+
+void CAEDRServerInitialize(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRServerInitialize");
+
+    g_threadPoolHandle = handle;
+
+    CAEDRServerStartAcceptThread();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAEDRServerStartAcceptThread()
+{
+    CAEDRServerJniInit();
+
+    // init mutex
+    CAEDRServerCreateMutex();
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRServerInitialize - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    jstring jni_address = CAEDRNativeGetLocalDeviceAddress(env);
+    if (jni_address)
+    {
+        const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        OIC_LOG_V(DEBUG, TAG, "My BT Address is %s", localAddress);
+        (*env)->ReleaseStringUTFChars(env, jni_address, localAddress);
+    }
+
+    ca_mutex_lock(g_mutexStateList);
+    CAEDRNativeCreateDeviceStateList();
+    ca_mutex_unlock(g_mutexStateList);
+
+    ca_mutex_lock(g_mutexObjectList);
+    CAEDRNativeCreateDeviceSocketList();
+    ca_mutex_unlock(g_mutexObjectList);
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) OICMalloc(
+            sizeof(CAAdapterReceiveThreadContext_t));
+    if (!ctx)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory!");
+        return;
+    }
+
+    ctx->stopFlag = &g_stopAccept;
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CAAcceptHandler, (void *) ctx))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create read thread!");
+        OICFree((void *) ctx);
+        return;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAEDRServerTerminate()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRServerTerminate");
+
+    if (!g_jvm)
+    {
+        return;
+    }
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "CAEDRServerTerminate - Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    CAEDRNativeSocketCloseToAll(env);
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    CAEDRNativeRemoveAllDeviceState();
+    CAEDRNativeRemoveAllDeviceSocket(env);
+
+    // delete mutex
+    CAEDRServerDestroyMutex();
+}
+
+CAResult_t CAEDRStartUnicastServer(bool isSecured)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRStartUnicastServer");
+
+    ca_mutex_lock(g_mutexUnicastServer);
+
+    /**
+     * The task to listen for data from unicast is added to the thread pool.
+     * This is a blocking call is made where we try to receive some data..
+     * We will keep waiting until some data is received.
+     * This task will be terminated when thread pool is freed on stopping the adapters.
+     * Thread context will be freed by thread on exit.
+     */
+    CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) OICMalloc(
+            sizeof(CAAdapterReceiveThreadContext_t));
+    if (!ctx)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory!");
+        ca_mutex_unlock(g_mutexUnicastServer);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    ctx->stopFlag = &g_stopUnicast;
+    ctx->type = isSecured ? CA_SECURED_UNICAST_SERVER : CA_UNICAST_SERVER;
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CAReceiveHandler, (void *) ctx))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create read thread!");
+        ca_mutex_unlock(g_mutexUnicastServer);
+        OICFree((void *) ctx);
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_mutexUnicastServer);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStartMulticastServer(bool isSecured)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRStartMulticastServer");
+
+    ca_mutex_lock(g_mutexMulticastServer);
+
+    /**
+     * The task to listen to data from multicast socket is added to the thread pool.
+     * This is a blocking call is made where we try to receive some data.
+     * We will keep waiting until some data is received.
+     * This task will be terminated when thread pool is freed on stopping the adapters.
+     * Thread context will be freed by thread on exit.
+     */
+    CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) OICMalloc(
+            sizeof(CAAdapterReceiveThreadContext_t));
+    if (!ctx)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory!");
+        ca_mutex_unlock(g_mutexMulticastServer);
+
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    ctx->stopFlag = &g_stopMulticast;
+    ctx->type = CA_MULTICAST_SERVER;
+
+    g_stopMulticast = false;
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CAReceiveHandler, (void *) ctx))
+    {
+        OIC_LOG(ERROR, TAG, "thread_pool_add_task failed!");
+
+        g_stopMulticast = true;
+        ca_mutex_unlock(g_mutexMulticastServer);
+        OICFree((void *) ctx);
+
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_mutexMulticastServer);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStopUnicastServer(int32_t serverID)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRStopUnicastServer");
+
+    ca_mutex_lock(g_mutexUnicastServer);
+    g_stopUnicast = true;
+    ca_mutex_unlock(g_mutexUnicastServer);
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStopMulticastServer(int32_t serverID)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRStopMulticastServer");
+
+    ca_mutex_lock(g_mutexMulticastServer);
+    g_stopMulticast = true;
+    ca_mutex_unlock(g_mutexMulticastServer);
+
+    OIC_LOG(INFO, TAG, "Multicast server stopped");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type)
+{
+    if (!CAEDRNativeIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (!((*env)->ExceptionCheck(env)))
+    {
+        // check whether this socket object is connected or not.
+        jobject jni_obj_socket = CAEDRNativeGetDeviceSocket(id);
+        if (!jni_obj_socket)
+        {
+            return CA_STATUS_INVALID_PARAM;
+        }
+
+        jstring jni_str_address = CAEDRNativeGetAddressFromDeviceSocket(env, jni_obj_socket);
+        if (!jni_str_address)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: jni_str_address is null");
+            return CA_STATUS_FAILED;
+        }
+        const char* address = (*env)->GetStringUTFChars(env, jni_str_address, NULL);
+
+        // check it whether is still connected or not through google api
+        jboolean ret = CAEDRIsConnectedForSocket(env, jni_obj_socket);
+        if (!ret)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] this device is not connected now.let close socket");
+        }
+
+        // check it whether is still connected or not through socket state list
+        if (STATE_DISCONNECTED == CAEDRIsConnectedDevice(address))
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: it is not connected yet..");
+
+            // remove socket to list
+            // this code is related to below read fail exception code
+            CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
+            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
+
+            return CA_STATUS_FAILED;
+        }
+
+        // start to read through InputStream
+        jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
+        if (!jni_cid_BTsocket)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: jni_cid_BTsocket is null");
+            return CA_STATUS_FAILED;
+        }
+        jmethodID jni_mid_getInputStream = (*env)->GetMethodID(env, jni_cid_BTsocket,
+                                                               "getInputStream",
+                                                               "()Ljava/io/InputStream;");
+        OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData:  get InputStream..%d, %s", id, address);
+
+        if (!jni_obj_socket)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_obj_socket is not available anymore..");
+            return CA_STATUS_FAILED;
+        }
+
+        jobject jni_obj_inputStream = (*env)->CallObjectMethod(env, jni_obj_socket,
+                                                               jni_mid_getInputStream);
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData:  ready inputStream..");
+
+        g_inputStream = (*env)->NewGlobalRef(env, jni_obj_inputStream);
+
+        jclass jni_cid_InputStream = (*env)->FindClass(env, "java/io/InputStream");
+        if (!jni_cid_InputStream)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: jni_cid_InputStream is null");
+            return CA_STATUS_FAILED;
+        }
+        jmethodID jni_mid_read = (*env)->GetMethodID(env, jni_cid_InputStream, "read", "([BII)I");
+
+        jbyteArray jbuf = (*env)->NewByteArray(env, MAX_PDU_BUFFER);
+
+        if (!jni_obj_socket)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_obj_socket is not available anymore...");
+            return CA_STATUS_FAILED;
+        }
+
+        jint length = (*env)->CallIntMethod(env, g_inputStream, jni_mid_read, jbuf, (jint) 0,
+                                            MAX_PDU_BUFFER);
+
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] read something from InputStream");
+
+        if (-1 == length)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] read buffer is empty...");
+            return CA_STATUS_FAILED;
+        }
+
+        if ((*env)->ExceptionCheck(env))
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: read Error!!!");
+            (*env)->ExceptionDescribe(env);
+            (*env)->ExceptionClear(env);
+
+            // update state to disconnect
+            // the socket will be close next read thread routine
+            ca_mutex_lock(g_mutexStateList);
+            CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
+            ca_mutex_unlock(g_mutexStateList);
+            (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
+            return CA_STATUS_FAILED;
+        }
+
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData: reading");
+        jbyte* buf = (*env)->GetByteArrayElements(env, jbuf, NULL);
+        if (NULL == buf)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: buf is null");
+            return CA_STATUS_FAILED;
+        }
+
+        OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: read %s, %d", buf, length);
+
+        char responseData[MAX_PDU_BUFFER] = { 0 };
+        memcpy(responseData, (const char*) buf, length);
+
+        switch (type)
+        {
+            case CA_UNICAST_SERVER:
+            case CA_MULTICAST_SERVER:
+                // Notify data to upper layer
+                if (g_edrPacketReceivedCallback)
+                {
+                    uint32_t sentLength = 0;
+                    OIC_LOG_V(DEBUG, TAG,"[EDR][Native] data will be sent to callback routine: \
+                              %s, %d", responseData, length);
+                    g_edrPacketReceivedCallback(address, (void*) responseData, length, &sentLength);
+                }
+                break;
+
+            default:
+                // Should never occur
+                OIC_LOG(ERROR, TAG, "Invalid server type");
+                return CA_STATUS_FAILED;
+        }
+        (*env)->ReleaseByteArrayElements(env, jbuf, buf, 0);
+        (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
+    }
+    else
+    {
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: env error!!");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+jboolean CAEDRIsConnectedForSocket(JNIEnv *env, jobject socket)
+{
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRIsConnectedForSocket...");
+
+    if (!CAEDRNativeIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
+        return JNI_FALSE;
+    }
+
+    if (!socket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] CAEDRIsConnectedForSocket - socket is null");
+        return JNI_FALSE;
+    }
+
+    jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
+    if (!jni_cid_BTsocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] CAEDRIsConnectedForSocket - jni_cid_BTsocket is null");
+        return JNI_FALSE;
+    }
+
+    jmethodID jni_mid_isConnected = (*env)->GetMethodID(env, jni_cid_BTsocket, "isConnected",
+                                                        "()Z");
+    if (!jni_mid_isConnected)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] CAEDRIsConnectedForSocket \
+                - jni_mid_isConnected is null.");
+        return JNI_FALSE;
+    }
+
+    jboolean jni_isConnected = (*env)->CallBooleanMethod(env, socket, jni_mid_isConnected);
+
+    return jni_isConnected;
+}
+
+void CANativeStartListenTask(JNIEnv *env)
+{
+    jobject jni_obj_BTServerSocket = CAEDRNativeListen(env);
+    if (!jni_obj_BTServerSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] AcceptThread: jni_obj_BTServerSocket is null");
+        return;
+    }
+
+    ca_mutex_lock(g_mutexServerSocket);
+    g_serverSocket = (*env)->NewGlobalRef(env, jni_obj_BTServerSocket);
+    ca_mutex_unlock(g_mutexServerSocket);
+}
+
+jobject CAEDRNativeListen(JNIEnv *env)
+{
+    if (!CAEDRNativeIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adpater is not enable");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen");
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    // get BTadpater
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_BTAdapter is null");
+        return NULL;
+    }
+
+    // get listen method ID
+    jmethodID jni_mid_listen = (*env)->GetMethodID(
+            env, jni_cid_BTAdapter, "listenUsingInsecureRfcommWithServiceRecord",
+            "(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;");
+    if (!jni_mid_listen)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
+        return NULL;
+    }
+    // listenUsingInsecureRfcommWithServiceRecord  / listenUsingRfcommWithServiceRecord
+    // setting UUID
+    jclass jni_cid_uuid = (*env)->FindClass(env, CLASSPATH_BT_UUID);
+    if (!jni_cid_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(
+            env, jni_cid_uuid, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
+    if (!jni_mid_fromString)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_fromString is null");
+        return NULL;
+    }
+
+    jstring jni_uuid = (*env)->NewStringUTF(env, OIC_EDR_SERVICE_ID);
+    if (!jni_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_uuid is null");
+        return NULL;
+    }
+    jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString,
+                                                          jni_uuid);
+    if (!jni_obj_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_uuid is null");
+        return NULL;
+    }
+
+    // create socket
+    jstring jni_name = (*env)->NewStringUTF(env, "BluetoothTestSecure");
+    if (!jni_name)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_name is null");
+        return NULL;
+    }
+    jobject jni_obj_BTServerSocket = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_listen,
+                                                             jni_name, jni_obj_uuid);
+    if (!jni_obj_BTServerSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_BTServerSocket is null");
+        return NULL;
+    }
+
+    g_serverSocketObject = (*env)->NewGlobalRef(env, jni_obj_BTServerSocket);
+
+    return jni_obj_BTServerSocket;
+}
+
+void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
+{
+    if (NULL != serverSocketObject)
+    {
+        jclass jni_cid_BTServerSocket = (*env)->FindClass(
+                env, "android/bluetooth/BluetoothServerSocket");
+        if (!jni_cid_BTServerSocket)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_cid_BTServerSocket is null");
+            return;
+        }
+
+        jmethodID jni_mid_accept = (*env)->GetMethodID(env, jni_cid_BTServerSocket, "accept",
+                                                       "()Landroid/bluetooth/BluetoothSocket;");
+        if (!jni_mid_accept)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_mid_accept is null");
+            return;
+        }
+
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: initiating accept...");
+
+        jobject jni_obj_BTSocket = (*env)->CallObjectMethod(env, serverSocketObject,
+                                                            jni_mid_accept);
+        if (!jni_obj_BTSocket)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_obj_BTSocket is null");
+
+            if ((*env)->ExceptionCheck(env))
+            {
+                OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: socket might closed or timeout!!!");
+                (*env)->ExceptionDescribe(env);
+                (*env)->ExceptionClear(env);
+                return;
+            }
+        }
+
+        // get remote address
+        jstring j_str_address = CAEDRNativeGetAddressFromDeviceSocket(env, jni_obj_BTSocket);
+        if (!j_str_address)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: j_str_address is null");
+            return;
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, j_str_address, NULL);
+        OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btAccept: address is %s", address);
+
+        // set socket to list
+        jobject jni_socket = (*env)->NewGlobalRef(env, jni_obj_BTSocket);
+        ca_mutex_lock(g_mutexObjectList);
+        CAEDRNativeAddDeviceSocketToList(env, jni_socket);
+        ca_mutex_unlock(g_mutexObjectList);
+
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: Accepted!!");
+
+        // update state
+        ca_mutex_lock(g_mutexStateList);
+        CAEDRUpdateDeviceState(STATE_CONNECTED, address);
+        ca_mutex_unlock(g_mutexStateList);
+        (*env)->ReleaseStringUTFChars(env, j_str_address, address);
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: serverSocket is close previously");
+    }
+}
+
+/**
+ * InputStream & BluetoothServerSocket will be close for Terminating
+ */
+void CAEDRNatvieCloseServerTask(JNIEnv* env)
+{
+    if (g_inputStream)
+    {
+        OIC_LOG(DEBUG, TAG, "InputStream will be close");
+        jclass jni_cid_InputStream = (*env)->FindClass(env, "java/io/InputStream");
+        jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_InputStream, "close", "()V");
+        (*env)->CallVoidMethod(env, g_inputStream, jni_mid_close);
+        (*env)->DeleteGlobalRef(env, g_inputStream);
+    }
+
+    if (g_serverSocket)
+    {
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] Accept Resource will be close");
+
+        jclass jni_cid_BTServerSocket = (*env)->FindClass(
+                env, "android/bluetooth/BluetoothServerSocket");
+        if (!jni_cid_BTServerSocket)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_BTServerSocket is null");
+            return;
+        }
+
+        jmethodID jni_mid_accept = (*env)->GetMethodID(env, jni_cid_BTServerSocket, "close", "()V");
+        if (!jni_mid_accept)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_accept is null");
+            return;
+        }
+        (*env)->CallVoidMethod(env, g_serverSocket, jni_mid_accept);
+        (*env)->DeleteGlobalRef(env, g_serverSocket);
+
+        OIC_LOG(DEBUG, TAG, "[EDR][Native] close accept obj");
+    }
+}
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.h b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.h
new file mode 100644 (file)
index 0000000..faa4a6a
--- /dev/null
@@ -0,0 +1,142 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * @brief This file contains the APIs for BT EDR communications.
+ */
+#ifndef CA_EDR_SERVER_H_
+#define CA_EDR_SERVER_H_
+
+#include <stdbool.h>
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "jni.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+typedef void (*CAPacketReceiveCallback)(const char *address, const char *data);
+
+/**
+ * @brief   Initialize JNI object
+ * @return  None
+ */
+void CAEDRServerJniInit();
+
+/**
+ * @brief   Initialize server for EDR
+ * @param   handle           [IN] thread pool handle object
+ * @return  None
+ */
+void CAEDRServerInitialize(ca_thread_pool_t handle);
+
+/*
+ * @brief   Start Accept Thread
+ * @return  None
+ */
+void CAEDRServerStartAcceptThread();
+/**
+ * @brief   Start unicast server
+ * @param   isSecured       [IN] unicast server type
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRStartUnicastServer(bool isSecured);
+
+/**
+ * @brief   Start multicast server
+ * @param   isSecured       [IN] multicst server type
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRStartMulticastServer(bool isSecured);
+
+/**
+ * @brief   Stop unicast server
+ * @param   serverID        [IN] unicast server id
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRStopUnicastServer(int32_t serverID);
+
+/**
+ * @brief   Stop multicast server
+ * @param   serverID        [IN] multicast server id
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRStopMulticastServer(int32_t serverID);
+
+/**
+ * EDR Method
+ */
+
+/**
+ * @brief  This function will read the data from remote device.
+ * @param  env              [IN] JNI interface pointer
+ * @param  id               [IN] index of remote address
+ * @param  type             [IN] EDR server type
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type);
+
+/*
+ * @brief   Start Listen Task
+ * @param   env             [IN] JNI interface pointer
+ * @return  None
+ */
+void CANativeStartListenTask(JNIEnv *env);
+
+/**
+ * @brief  This function will listen the connection from remote device.
+ * @param  env              [IN] JNI interface pointer
+ * @return server socket object or NULL
+ */
+jobject CAEDRNativeListen(JNIEnv *env);
+
+/**
+ * @brief  This function will listen the connection from remote device.
+ * @param  env              [IN] JNI interface pointer
+ * @param  socket           [IN] server socket object
+ * @return JNI_TRUE or JNI_FALSE
+ */
+jboolean CAEDRIsConnectedForSocket(JNIEnv *env, jobject socket);
+
+/**
+ * @brief  This function will accept the connection from remote device.
+ * @param  env                  [IN] JNI interface pointer
+ * @param  severSocketObject    [IN] server socket object
+ * @return None
+ */
+void CAEDRNativeAccept(JNIEnv *env, jobject severSocketObject);
+
+/**
+ * @brief   Remove all device objects in the list
+ * @param   env    [IN] JNI interface pointer
+ * @return  None
+ */
+void CAEDRNatvieCloseServerTask(JNIEnv* env);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_SERVER_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.c b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.c
new file mode 100644 (file)
index 0000000..5044c58
--- /dev/null
@@ -0,0 +1,889 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <jni.h>
+#include <stdio.h>
+#include <android/log.h>
+#include "caedrutils.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+
+#define ERROR_CODE (-1)
+#define TAG PCF("CA_EDR_UTILS")
+
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char METHODID_STRINGNONPARAM[] = "()Ljava/lang/String;";
+static const char CLASSPATH_BT_ADPATER[] = "android/bluetooth/BluetoothAdapter";
+static const char CLASSPATH_BT_DEVICE[] = "android/bluetooth/BluetoothDevice";
+static const char CLASSPATH_BT_SOCKET[] = "android/bluetooth/BluetoothSocket";
+
+static u_arraylist_t *g_deviceStateList = NULL;
+static u_arraylist_t *g_deviceObjectList = NULL;
+
+// get address from bluetooth socket
+jstring CAEDRNativeGetAddressFromDeviceSocket(JNIEnv *env, jobject bluetoothSocketObj)
+{
+    if (!bluetoothSocketObj)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: bluetoothSocketObj is null");
+        return NULL;
+    }
+
+    jclass jni_cid_BTSocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
+    if (!jni_cid_BTSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_cid_BTSocket is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(
+            env, jni_cid_BTSocket, "getRemoteDevice", "()Landroid/bluetooth/BluetoothDevice;");
+    if (!jni_mid_getRemoteDevice)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_mid_getRemoteDevice is null");
+        return NULL;
+    }
+
+    jobject jni_obj_remoteBTDevice = (*env)->CallObjectMethod(env, bluetoothSocketObj,
+                                                              jni_mid_getRemoteDevice);
+    if (!jni_obj_remoteBTDevice)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_obj_remoteBTDevice is null");
+        return NULL;
+    }
+
+    jclass jni_cid_BTDevice = (*env)->FindClass(env, CLASSPATH_BT_DEVICE);
+    if (!jni_cid_BTDevice)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: jni_cid_BTDevice is null");
+        return NULL;
+    }
+    jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice, "getAddress",
+                                                     METHODID_STRINGNONPARAM);
+    if (!j_mid_getAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: j_mid_getAddress is null");
+        return NULL;
+    }
+
+    jstring j_str_address = (*env)->CallObjectMethod(env, jni_obj_remoteBTDevice, j_mid_getAddress);
+    if (!j_str_address)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR] getRemoteAddress: j_str_address is null");
+        return NULL;
+    }
+
+    return j_str_address;
+}
+
+jstring CAEDRNativeGetLocalDeviceAddress(JNIEnv* env)
+{
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_mid_getDefaultAdapter is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getAddress",
+                                                       METHODID_STRINGNONPARAM);
+    if (!jni_mid_getAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_mid_getAddress is null");
+        return NULL;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_obj_BTAdapter is null");
+        return NULL;
+    }
+
+    jstring jni_str_address = (jstring)(*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+                                                                jni_mid_getAddress);
+    if (!jni_str_address)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_str_address is null");
+        return NULL;
+    }
+
+    return jni_str_address;
+}
+
+jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env)
+{
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: default adapter is null");
+        return NULL;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: bluetooth adapter is null");
+        return NULL;
+    }
+
+    // Get a list of currently paired devices
+    jmethodID jni_mid_getBondedDevices = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                             "getBondedDevices",
+                                                             "()Ljava/util/Set;");
+    if (!jni_mid_getBondedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_mid_getBondedDevicesr is null");
+        return NULL;
+    }
+
+    jobject jni_obj_setPairedDevices = (*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+                                                                jni_mid_getBondedDevices);
+    if (!jni_obj_setPairedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_obj_setPairedDevices is null");
+        return NULL;
+    }
+
+    // Convert the set to an object array
+    // object[] array = Set<BluetoothDevice>.toArray();
+    jclass jni_cid_Set = (*env)->FindClass(env, "java/util/Set");
+    if (!jni_cid_Set)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_cid_Set is null");
+        return NULL;
+    }
+    jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray",
+                                                    "()[Ljava/lang/Object;");
+
+    if (!jni_mid_toArray)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_mid_toArray is null");
+        return NULL;
+    }
+
+    jobjectArray jni_arrayPairedDevices = (jobjectArray)(
+            (*env)->CallObjectMethod(env, jni_obj_setPairedDevices, jni_mid_toArray));
+    if (!jni_arrayPairedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_arrayPairedDevices is null");
+        return NULL;
+    }
+
+    return jni_arrayPairedDevices;
+}
+
+jint CAEDRNativeGetBTStateOnInfo(JNIEnv *env)
+{
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] getBTStateOnInfo: jni_cid_BTAdapter is null");
+        return ERROR_CODE;
+    }
+
+    jfieldID jni_fid_stateon = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_ON", "I");
+    if (jni_fid_stateon == 0)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] get_field_state is 0");
+        return ERROR_CODE;
+    }
+    jint jni_int_val = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, jni_fid_stateon);
+
+    OIC_LOG_V(DEBUG, TAG, "[EDR][Native] bluetooth state integer value : %d", jni_int_val);
+
+    return jni_int_val;
+}
+
+jboolean CAEDRNativeIsEnableBTAdapter(JNIEnv *env)
+{
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_BTAdapter: jni_cid_BTAdapter is null");
+        return JNI_FALSE;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_getDefaultAdapter is null");
+        return JNI_FALSE;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_obj_BTAdapter is null");
+        return JNI_FALSE;
+    }
+
+    // isEnable()
+    jmethodID jni_mid_isEnable = (*env)->GetMethodID(env, jni_cid_BTAdapter, "isEnabled", "()Z");
+    if (!jni_mid_isEnable)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_isEnable is null");
+        return JNI_FALSE;
+    }
+
+    jboolean jni_isEnable = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_isEnable);
+    OIC_LOG_V(DEBUG, TAG, "[EDR][Native] adapter state is %d", jni_isEnable);
+
+    return jni_isEnable;
+}
+
+jstring CAEDRNativeGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
+{
+    if (!bluetoothDevice)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] bluetoothDevice is null");
+        return NULL;
+    }
+    jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
+    if (!jni_cid_device_list)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_device_list is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_device_list, "getAddress",
+                                                       METHODID_STRINGNONPARAM);
+    if (!jni_mid_getAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_getAddress is null");
+        return NULL;
+    }
+
+    jstring jni_address = (jstring)(*env)->CallObjectMethod(env, bluetoothDevice,
+                                                            jni_mid_getAddress);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_address is null");
+        return NULL;
+    }
+    return jni_address;
+}
+
+/**
+ * BT State List
+ */
+void CAEDRNativeCreateDeviceStateList()
+{
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceStateList");
+
+    // create new object array
+    if (NULL == g_deviceStateList)
+    {
+        OIC_LOG(DEBUG, TAG, "Create device list");
+
+        g_deviceStateList = u_arraylist_create();
+    }
+}
+
+void CAEDRUpdateDeviceState(CAConnectedState_t state, const char *address)
+{
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] address is null");
+        return;
+    }
+    state_t *newstate = (state_t*) OICCalloc(1, sizeof(state_t));
+    if (!newstate)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] newstate is null");
+        return;
+    }
+    strcpy(newstate->address, address);
+    newstate->state = state;
+
+    CAEDRNativeAddDeviceStateToList(newstate);
+}
+
+void CAEDRNativeAddDeviceStateToList(state_t *state)
+{
+    if (!state)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] device is null");
+        return;
+    }
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdevice_list is null");
+        return;
+    }
+
+    if (CAEDRNativeIsDeviceInList(state->address))
+    {
+        CAEDRNativeRemoveDevice(state->address); // delete previous state for update new state
+    }
+    u_arraylist_add(g_deviceStateList, state); // update new state
+    OIC_LOG_V(DEBUG, TAG, "Set State Info to List : %d", state->state);
+}
+
+bool CAEDRNativeIsDeviceInList(const char* remoteAddress)
+{
+
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        return false;
+    }
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] state_t object is null");
+            return false;
+        }
+
+        if (!strcmp(remoteAddress, state->address))
+        {
+            OIC_LOG(DEBUG, TAG, "the device is already set");
+            return true;
+        }
+        else
+        {
+            continue;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "there are no the device in list.");
+    return false;
+}
+
+void CAEDRNativeRemoveAllDeviceState()
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeRemoveAllDevices");
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+        return;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            continue;
+        }
+        OICFree(state);
+    }
+
+    OICFree(g_deviceStateList);
+    g_deviceStateList = NULL;
+    return;
+}
+
+void CAEDRNativeRemoveDevice(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeRemoveDeviceforStateList");
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+        return;
+    }
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        return;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+            continue;
+        }
+
+        if (!strcmp(state->address, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove state : %s", remoteAddress);
+            OICFree(state);
+
+            CAEDRReorderingDeviceList(index);
+            break;
+        }
+    }
+    return;
+}
+
+CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRIsConnectedDevice");
+
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        return STATE_DISCONNECTED;
+    }
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+        return STATE_DISCONNECTED;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+            continue;
+        }
+
+        if (!strcmp(state->address, remoteAddress))
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] check whether it is connected or not");
+
+            return state->state;
+        }
+    }
+    return STATE_DISCONNECTED;
+}
+
+void CAEDRReorderingDeviceList(uint32_t index)
+{
+    if (index >= g_deviceStateList->length)
+    {
+        return;
+    }
+
+    if (index < g_deviceStateList->length - 1)
+    {
+        memmove(&g_deviceStateList->data[index], &g_deviceStateList->data[index + 1],
+                (g_deviceStateList->length - index - 1) * sizeof(void *));
+    }
+
+    g_deviceStateList->size--;
+    g_deviceStateList->length--;
+}
+
+/**
+ * Device Socket Object List
+ */
+void CAEDRNativeCreateDeviceSocketList()
+{
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceSocketList");
+
+    // create new object array
+    if (NULL == g_deviceObjectList)
+    {
+        OIC_LOG(DEBUG, TAG, "Create Device object list");
+
+        g_deviceObjectList = u_arraylist_create();
+    }
+}
+
+void CAEDRNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket)
+{
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] CANativeAddDeviceobjToList");
+
+    if (!deviceSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] Device is null");
+        return;
+    }
+
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return;
+    }
+
+    jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
+    if (!jni_remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jni_remoteAddress is null");
+        return;
+    }
+
+    const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+
+    if (!CAEDRNativeIsDeviceSocketInList(env, remoteAddress))
+    {
+        jobject gDeviceSocker = (*env)->NewGlobalRef(env, deviceSocket);
+        u_arraylist_add(g_deviceObjectList, gDeviceSocker);
+        OIC_LOG(DEBUG, TAG, "Set Socket Object to Array");
+    }
+    (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+}
+
+bool CAEDRNativeIsDeviceSocketInList(JNIEnv *env, const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] CANativeIsDeviceObjInList");
+
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+        return false;
+    }
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            return false;
+        }
+
+        jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_setAddress is null");
+            return false;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] setAddress is null");
+            return false;
+        }
+
+        if (!strcmp(remoteAddress, setAddress))
+        {
+            OIC_LOG(DEBUG, TAG, "the device is already set");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            return true;
+        }
+        else
+        {
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            continue;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "there are no the Device obejct in list. we can add");
+    return false;
+}
+
+void CAEDRNativeSocketCloseToAll(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeSocketCloseToAll");
+
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return;
+    }
+
+    jclass jni_cid_BTSocket = (*env)->FindClass(env, CLASSPATH_BT_SOCKET);
+    if (!jni_cid_BTSocket)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
+        return;
+    }
+
+    jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_BTSocket, "close", "()V");
+    if (!jni_mid_close)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_mid_close is null");
+        return;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        jobject jni_obj_socket = (jobject) u_arraylist_get(g_deviceObjectList, index);
+        if (!jni_obj_socket)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] socket obj is null");
+            return;
+        }
+
+        (*env)->CallVoidMethod(env, jni_obj_socket, jni_mid_close);
+
+        if ((*env)->ExceptionCheck(env))
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] close: close is Failed!!!");
+            (*env)->ExceptionDescribe(env);
+            (*env)->ExceptionClear(env);
+            return;
+        }
+    }
+}
+
+void CAEDRNativeRemoveAllDeviceSocket(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CANativeRemoveAllDeviceObjsList");
+
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jarrayObj is null");
+            return;
+        }
+        (*env)->DeleteGlobalRef(env, jarrayObj);
+    }
+
+    OICFree(g_deviceObjectList);
+    g_deviceObjectList = NULL;
+    return;
+}
+
+void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeRemoveDeviceSocket");
+
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            continue;
+        }
+
+        jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_setAddress is null");
+            continue;
+        }
+
+        jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
+        if (!jni_remoteAddress)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_remoteAddress is null");
+            continue;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+
+        if (!strcmp(setAddress, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+            (*env)->DeleteGlobalRef(env, jarrayObj);
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+
+            CAEDRReorderingDeviceSocketList(index);
+            break;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+        (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+    }
+
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] there are no target object");
+    return;
+}
+
+void CAEDRNativeRemoveDeviceSocketBaseAddr(JNIEnv *env, jstring address)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeRemoveDeviceSocket");
+
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+            continue;
+        }
+
+        jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_setAddress is null");
+            continue;
+        }
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        const char* remoteAddress = (*env)->GetStringUTFChars(env, address, NULL);
+
+        if (!strcmp(setAddress, remoteAddress))
+        {
+            OIC_LOG_V(ERROR, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+            (*env)->DeleteGlobalRef(env, jarrayObj);
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
+
+            CAEDRReorderingDeviceSocketList(index);
+            break;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+        (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
+    }
+
+    OIC_LOG(DEBUG, TAG, "[EDR][Native] there are no target object");
+    return;
+}
+
+jobject CAEDRNativeGetDeviceSocket(uint32_t idx)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeGetDeviceSocket");
+
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return NULL;
+    }
+
+    jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, idx);
+    if (!jarrayObj)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] jarrayObj is not available");
+        return NULL;
+    }
+    return jarrayObj;
+}
+
+jobject CAEDRNativeGetDeviceSocketBaseAddr(JNIEnv *env, const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CAEDRNativeGetDeviceSocket");
+
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return NULL;
+    }
+
+    jint index;
+    jint length = u_arraylist_length(g_deviceStateList);
+    for (index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jarrayObj is null");
+            continue;
+        }
+
+        jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "[EDR][Native] jni_setAddress is null");
+            continue;
+        }
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+
+        if (!strcmp(setAddress, remoteAddress))
+        {
+            OIC_LOG_V(ERROR, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            return jarrayObj;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+    }
+
+    return NULL;
+}
+
+uint32_t CAEDRGetSocketListLength()
+{
+    if (!g_deviceObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+        return 0;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceObjectList);
+
+    return length;
+}
+
+void CAEDRReorderingDeviceSocketList(uint32_t index)
+{
+    if (index >= g_deviceObjectList->length)
+    {
+        return;
+    }
+
+    if (index < g_deviceObjectList->length - 1)
+    {
+        memmove(&g_deviceObjectList->data[index], &g_deviceObjectList->data[index + 1],
+                (g_deviceObjectList->length - index - 1) * sizeof(void *));
+    }
+
+    g_deviceObjectList->size--;
+    g_deviceObjectList->length--;
+}
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.h b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.h
new file mode 100644 (file)
index 0000000..1348546
--- /dev/null
@@ -0,0 +1,230 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * @brief This file contains the APIs for BT communications.
+ */
+#ifndef CA_EDR_UTILS_H_
+#define CA_EDR_UTILS_H_
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+#include "caedrinterface.h"
+#include "jni.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   Get address from device socket
+ * @param   env                 [IN] JNI interface pointer
+ * @param   bluetoothSocketObj  [IN] bluetooth socket object
+ * @return  Bluetooth device address
+ */
+jstring CAEDRNativeGetAddressFromDeviceSocket(JNIEnv *env, jobject bluetoothSocketObj);
+
+/**
+ * @brief   Get local device address
+ * @param   env                 [IN] JNI interface pointer
+ * @return  Bluetooth device address
+ */
+jstring CAEDRNativeGetLocalDeviceAddress(JNIEnv *env);
+
+/**
+ * @brief   Get bonded devices list
+ * @param   env                 [IN] JNI interface pointer
+ * @return  Bonded devices list
+ */
+jobjectArray CAEDRNativeGetBondedDevices(JNIEnv *env);
+
+/**
+ * @brief   Get Bluetooth device state
+ * @param   env                 [IN] JNI interface pointer
+ * @return  Bluetooth device state
+ */
+jint CAEDRNativeGetBTStateOnInfo(JNIEnv *env);
+
+/**
+ * @brief   Check the BT Adapter enable
+ * @param   env                 [IN] JNI interface pointer
+ * @return  JNI_TRUE or JNI_FALSE
+ */
+jboolean CAEDRNativeIsEnableBTAdapter(JNIEnv *env);
+
+/**
+ * @brief   Get address from BT device
+ * @param   env                 [IN] JNI interface pointer
+ * @param   bluetoothSocketObj  [IN] bluetooth socket object
+ * @return  Bluetooth device address
+ */
+jstring CAEDRNativeGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice);
+
+/**
+ * BT State Info List
+ */
+
+/**
+ * @brief  This function will create the device state list.
+ * @return None
+ */
+void CAEDRNativeCreateDeviceStateList();
+
+/**
+ * @brief  Update connection state of device
+ * @param  state            [IN] connection state
+ * @param  address          [IN] remote address
+ * @return None
+ */
+void CAEDRUpdateDeviceState(CAConnectedState_t state, const char *address);
+
+/**
+ * @brief  Add device object to the list
+ * @param  state            [IN] connection state object
+ * @return None
+ */
+void CAEDRNativeAddDeviceStateToList(state_t *state);
+
+/**
+ * @brief  Check whether the device exist in the list or not
+ * @param  remoteAddress    [IN] remote address
+ * @return true or false
+ */
+bool CAEDRNativeIsDeviceInList(const char *remoteAddress);
+
+/**
+ * @brief   Close all socket
+ * @param   env       [IN] JNI interface pointer
+ * @return  NONE
+ */
+void CAEDRNativeSocketCloseToAll(JNIEnv *env);
+
+/**
+ * @brief   Remove all device objects in the list
+ * @return  None
+ */
+void CAEDRNativeRemoveAllDeviceState();
+
+/**
+ * @brief   Remove target device in the list
+ * @param   remoteAddress    [IN] remote address
+ * @return  None
+ */
+void CAEDRNativeRemoveDevice(const char *remoteAddress);
+
+/**
+ * @brief   Get current device connection state
+ * @param   remoteAddress    [IN] remote address
+ * @return  STATE_DISCONNECTED or STATE_CONNECTED
+ */
+CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress);
+
+/**
+ * @brief   Reordering for the list
+ * @param   index           [IN] index of device list that want to reordering
+ * @return  None
+ */
+void CAEDRReorderingDeviceList(uint32_t index);
+
+/**
+ * Bluetooth Socket Object List
+ */
+
+/**
+ * @brief  This function will create the device socket list.
+ * @return None
+ */
+void CAEDRNativeCreateDeviceSocketList();
+
+/**
+ * @brief  Add device object to the list
+ * @param  env              [IN] JNI interface pointer
+ * @param  deviceSocket     [IN] device socket object
+ * @return None
+ */
+void CAEDRNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket);
+
+/**
+ * @brief  Add device object to the list
+ * @param  env              [IN] JNI interface pointer
+ * @param  remoteAddress    [IN] remote address
+ * @return true or false
+ */
+bool CAEDRNativeIsDeviceSocketInList(JNIEnv *env, const char *remoteAddress);
+
+/**
+ * @brief  Add device object to the list
+ * @param  env              [IN] JNI interface pointer
+ * @return None
+ */
+void CAEDRNativeRemoveAllDeviceSocket(JNIEnv *env);
+
+/**
+ * @brief  Add device object to the list
+ * @param  env              [IN] JNI interface pointer
+ * @param  deviceSocket     [IN] device socket object
+ * @return None
+ */
+void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket);
+
+/**
+ * @brief   Remove device socket
+ * @param   env             [IN] JNI interface pointer
+ * @param   address         [IN] remote address
+ * @return  NONE
+ */
+void CAEDRNativeRemoveDeviceSocketBaseAddr(JNIEnv *env, jstring address);
+
+/**
+ * @brief  Get device socket object from the list
+ * @param  idx              [IN] index of device list
+ * @return Device socket object or NULL
+ */
+jobject CAEDRNativeGetDeviceSocket(uint32_t idx);
+
+/**
+ * @brief   Get device socket address
+ * @param   env             [IN] JNI interface pointer
+ * @param   remoteAddress   [IN] remote address
+ * @return  Device socket object or NULL
+ */
+jobject CAEDRNativeGetDeviceSocketBaseAddr(JNIEnv *env, const char* remoteAddress);
+
+/**
+ * @brief  Get length of device socket list
+ * @return length of list
+ */
+uint32_t CAEDRGetSocketListLength();
+
+/**
+ * @brief   Reordering for the list
+ * @param   index           [IN] index of device list that want to reordering
+ * @return  None
+ */
+void CAEDRReorderingDeviceSocketList(uint32_t index);
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_UTILS_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/org_iotivity_jar_caedrinterface.h b/resource/csdk/connectivity/src/bt_edr_adapter/android/org_iotivity_jar_caedrinterface.h
new file mode 100644 (file)
index 0000000..fbe3511
--- /dev/null
@@ -0,0 +1,31 @@
+#include <jni.h>
+/* Header for class org_iotivity_jar_caedrinterface */
+
+#ifndef Included_org_iotivity_jar_caedrinterface
+#define Included_org_iotivity_jar_caedrinterface
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class:     org_iotivity_jar_caedrinterface
+ * Method:    CAEDRStateChangedCallback
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caedrinterface_CAEDRStateChangedCallback
+(JNIEnv *, jobject, jint);
+
+/*
+ * Class:     org_iotivity_jar_caedrinterface
+ * Method:    CAEDRStateChangedCallback
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caedrinterface_CAEDRBondStateChangedCallback
+(JNIEnv *, jobject, jstring);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c b/resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c
new file mode 100644 (file)
index 0000000..9425988
--- /dev/null
@@ -0,0 +1,983 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the APIs for EDR adapter.
+ */
+
+#include "caedradapter.h"
+
+#include "caedrinterface.h"
+#include "caadapterutils.h"
+#include "logger.h"
+#include "camsgparser.h"
+#include "caqueueingthread.h"
+#include "oic_malloc.h"
+
+/**
+ * @var EDR_ADAPTER_TAG
+ * @brief Logging tag for module name.
+ */
+#define EDR_ADAPTER_TAG "CA_EDR_ADAPTER"
+
+/**
+ * @var g_edrThreadPool
+ * @brief Reference to threadpool.
+ */
+static ca_thread_pool_t g_edrThreadPool = NULL;
+
+/**
+ * @var g_sendQueueHandle
+ * @brief Queue handle for Send Data
+ */
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
+
+/**
+ * @var g_recvQueueHandle
+ * @brief Queue handle for Receive Data
+ */
+static CAQueueingThread_t *g_recvQueueHandle = NULL;
+
+/**
+ * @var g_isHeaderAvailable
+ * @brief to differentiate btw header and data packet.
+ */
+static bool g_isHeaderAvailable = false;
+
+/**
+ * @var g_adapterState
+ * @brief Storing Adapter state information
+ */
+static bool g_adapterState = true;
+
+/**
+ * @var g_networkPacketReceivedCallback
+ * @brief Maintains the callback to be notified on receival of network packets from other
+ *          Bluetooth devices.
+ */
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
+
+/**
+ * @var g_networkChangeCallback
+ * @brief Maintains the callback to be notified on local bluetooth adapter status change.
+ */
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
+
+/**
+ * @var g_localConnectivity
+ * @brief Information of local Bluetooth adapter.
+ */
+static CALocalConnectivity_t *g_localConnectivity = NULL;
+
+/**
+ * @var g_serverId
+ * @brief Storing RfcommserverUUID
+ */
+static int g_serverId = -1;
+
+/**
+ * @var g_serverState
+ * @brief Storing Rfcommserver state information
+ */
+static bool g_serverState = false;
+
+static CAResult_t CAStartServer();
+static CAResult_t CAEDRInitializeQueueHandlers();
+CAResult_t CAEDRInitializeSendHandler();
+CAResult_t CAEDRInitializeReceiveHandler();
+void CAAdapterTerminateQueues();
+void CAAdapterDataSendHandler(void *context);
+void CAAdapterDataReceiverHandler(void *context);
+CAResult_t CAAdapterStopQueue();
+void CAAdapterRecvData(const char *remoteAddress, const void *data, uint32_t dataLength,
+                       uint32_t *sentLength);
+void CAEDRNotifyNetworkStatus(CANetworkStatus_t status);
+void CAEDROnNetworkStatusChanged(void *context);
+CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID, const void *data,
+                             uint32_t dataLength, uint32_t *sentLength);
+CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CALocalConnectivity_t *connectivity,
+                                           CANetworkStatus_t status);
+CAResult_t CAEDRClientSendData(const char *remoteAddress, const char *serviceUUID,
+                               const void *data, uint32_t dataLength, uint32_t *sentLength);
+/**
+ * @fn CACreateEDRData
+ * @brief Helper function to create CAEDRData
+ */
+static CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                                  uint32_t dataLength);
+
+/**
+ * @fn CAFreeEDRData
+ * @brief Free the Created EDR data
+ */
+static void CAFreeEDRData(CAEDRData *edrData);
+
+/**
+ * @fn CAEDRFreeNetworkEvent
+ * @brief Free the memory associated with @event.
+ */
+void CAEDRFreeNetworkEvent(CAEDRNetworkEvent *event);
+
+static void CAEDRDataDestroyer(void *data, uint32_t size);
+
+CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
+                           CANetworkPacketReceivedCallback packetReceivedCallback,
+                           CANetworkChangeCallback networkStateChangeCallback,
+                           ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(registerCallback, EDR_ADAPTER_TAG, "register callback is NULL");
+    VERIFY_NON_NULL(packetReceivedCallback, EDR_ADAPTER_TAG, "data receive callback is NULL");
+    VERIFY_NON_NULL(networkStateChangeCallback, EDR_ADAPTER_TAG,
+                    "network state change callback is NULL");
+    VERIFY_NON_NULL(handle, EDR_ADAPTER_TAG, "Thread pool handle is NULL");
+
+    // Register the callbacks
+
+    g_edrThreadPool = handle;
+    g_networkPacketReceivedCallback = packetReceivedCallback;
+    g_networkChangeCallback = networkStateChangeCallback;
+
+    // Initialize EDR Network Monitor
+    CAResult_t err = CAEDRInitializeNetworkMonitor(handle);
+    if (CA_STATUS_OK != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDR N/w Monitor Initialize failed!, error number [%d]",
+                  err);
+        return err;
+    }
+
+    CAEDRSetNetworkChangeCallback(CAEDRNotifyNetworkStatus);
+    CAEDRSetPacketReceivedCallback(CAAdapterRecvData);
+    CAEDRInitializeClient(handle);
+
+    CAConnectivityHandler_t handler;
+    handler.startAdapter = CAStartEDR;
+    handler.startListenServer = CAStartEDRListeningServer;
+    handler.startDiscoveryServer = CAStartEDRDiscoveryServer;
+    handler.sendData = CASendEDRUnicastData;
+    handler.sendDataToAll = CASendEDRMulticastData;
+    handler.GetnetInfo = CAGetEDRInterfaceInformation;
+    handler.readData = CAReadEDRData;
+    handler.stopAdapter = CAStopEDR;
+    handler.terminate = CATerminateEDR;
+    registerCallback(handler, CA_EDR);
+
+    // Initialize Send/Receive data message queues
+    if (CA_STATUS_OK != CAEDRInitializeQueueHandlers())
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAAdapterInitializeQueues API failed");
+        CATerminateEDR();
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartEDR()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    //Start Monitoring EDR Network
+    CAResult_t ret = CAEDRStartNetworkMonitor();
+    if (CA_STATUS_OK != ret)
+    {
+       OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start n/w monitor");
+    }
+
+    // Get Bluetooth adapter state
+    bool adapterState = false;
+    if (CA_STATUS_OK != CAEDRGetAdapterEnableState(&adapterState))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get adapter enable state");
+        return CA_STATUS_FAILED;
+    }
+
+    if (false == adapterState)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
+        g_adapterState = false;
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    if (CA_STATUS_OK != (ret = CAEDRClientSetCallbacks()))
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Start Network Monitor failed!, error number [%d] ",
+                  ret);
+    }
+
+    if (CA_STATUS_OK != (ret = CAAdapterStartQueue()))
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "CAAdapterStartQueue failed!, error number [%d] ", ret);
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartEDRListeningServer()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    return CAStartServer();
+}
+
+CAResult_t CAStartEDRDiscoveryServer()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    return CAStartServer();
+}
+
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                             uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL_RET(remoteEndpoint, EDR_ADAPTER_TAG, "Remote endpoint is null", -1);
+    VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", -1);
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
+        return -1;
+    }
+
+    if (0 == strlen(remoteEndpoint->addressInfo.BT.btMacAddress))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: EDR Address is empty!");
+        return -1;
+    }
+
+    uint32_t sentLength = 0;
+    const char *serviceUUID = OIC_EDR_SERVICE_ID;
+    const char *address = remoteEndpoint->addressInfo.BT.btMacAddress;
+    CAResult_t err = CAAdapterSendData(address, serviceUUID, data, dataLength, &sentLength);
+    if (CA_STATUS_OK != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send unicast data failed!, error num [%d]", err);
+        return -1;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return sentLength;
+}
+
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CASendEDRMulticastData");
+
+    // Input validation
+    VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", -1);
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
+        return -1;
+    }
+
+    uint32_t sentLen = 0;
+    const char *serviceUUID = OIC_EDR_SERVICE_ID;
+    CAResult_t err = CAAdapterSendData(NULL, serviceUUID, data, dataLength, &sentLen);
+    if (CA_STATUS_OK != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send multicast data failed!, error num [%d]", err);
+        return -1;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT - CASendEDRMulticastData");
+    return sentLen;
+}
+
+
+CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(info, EDR_ADAPTER_TAG, "LocalConnectivity info is null");
+
+    CAResult_t err = CA_STATUS_OK;
+    *size = 0;
+    if (CA_STATUS_OK != (err = CAEDRGetInterfaceInformation(info)))
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                  "Failed to get local interface information!, error num [%d]", err);
+        return err;
+    }
+
+    *size = 1;
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return err;
+}
+
+CAResult_t CAReadEDRData()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    return CAEDRManagerReadData();
+}
+
+CAResult_t CAStopEDR()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Stop RFComm server if it is running
+    if (-1 != g_serverId)
+    {
+        CAEDRServerStop(g_serverId);
+        g_serverId = -1;
+    }
+
+    // Stop network monitor
+    CAEDRStopNetworkMonitor();
+
+    // Stop the adapter
+    CAEDRClientUnsetCallbacks();
+
+    // Disconnect all the client connections
+    CAEDRClientDisconnectAll();
+
+    // Stop Send and receive Queue
+    CAAdapterStopQueue();
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateEDR()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Stop EDR adapter
+    CAStopEDR();
+    // Terminate EDR Network Monitor
+    CAEDRTerminateNetworkMonitor();
+
+    // Terminate Send/Receive data messages queues
+    CAAdapterTerminateQueues();
+
+    g_networkPacketReceivedCallback = NULL;
+    g_networkChangeCallback = NULL;
+
+    // Terminate thread pool
+    g_edrThreadPool = NULL;
+
+    // Terminate EDR Client
+    CAEDRClientTerminate();
+
+    // Terminate EDR Server
+    CAEDRServerTerminate();
+
+    // Free LocalConnectivity information
+    CAAdapterFreeLocalEndpoint(g_localConnectivity);
+    g_localConnectivity = NULL;
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAStartServer()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    CAResult_t err = CA_STATUS_OK;
+
+    if (false == g_adapterState)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
+        // Setting g_serverState for starting Rfcommserver when adapter starts
+        g_serverState = true;
+        return CA_STATUS_OK;
+    }
+
+    if (-1 < g_serverId)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Server is already in running state.");
+        return CA_SERVER_STARTED_ALREADY;
+    }
+
+    if (CA_STATUS_OK != (err = CAEDRServerStart(OIC_EDR_SERVICE_ID, &g_serverId, g_edrThreadPool)))
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to start RFCOMM server!, error num [%d]",
+                  err);
+        return err;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return err;
+}
+
+CAResult_t CAEDRInitializeQueueHandlers()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (CA_STATUS_OK == CAEDRInitializeSendHandler()
+        && CA_STATUS_OK == CAEDRInitializeReceiveHandler())
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Queue is initialized!");
+        return CA_STATUS_OK;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CAEDRInitializeSendHandler()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    // Check if the message queue is already initialized
+    if (g_sendQueueHandle)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Already queue is initialized!");
+        return CA_STATUS_OK;
+    }
+
+    g_sendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+    if (!g_sendQueueHandle)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_edrThreadPool,
+                                                   CAAdapterDataSendHandler, CAEDRDataDestroyer))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Initialize send queue thread");
+        return CA_STATUS_FAILED;
+    }
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRInitializeReceiveHandler()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    // Check if the message queue is already initialized
+    if (g_recvQueueHandle)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Already queue is initialized!");
+        return CA_STATUS_OK;
+    }
+
+    g_recvQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+    if (!g_recvQueueHandle)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_recvQueueHandle, g_edrThreadPool,
+                                                   CAAdapterDataReceiverHandler,
+                                                   CAEDRDataDestroyer))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Initialize send queue thread");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAAdapterTerminateQueues()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (g_sendQueueHandle)
+    {
+        CAQueueingThreadDestroy(g_sendQueueHandle);
+        g_sendQueueHandle = NULL;
+    }
+    if (g_recvQueueHandle)
+    {
+        CAQueueingThreadDestroy(g_recvQueueHandle);
+        g_recvQueueHandle = NULL;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAAdapterDataSendHandler(void *context)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CAAdapterDataSendHandler");
+
+    CAEDRData *message = (CAEDRData *) context;
+    if (NULL == message)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
+        return;
+    }
+
+    const char *remoteAddress = NULL;
+    const char *serviceUUID = NULL;
+    uint32_t sentLength = 0;
+
+    if (NULL == message->remoteEndpoint)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "remoteEndpoint is not available");
+    }
+    else
+    {
+        remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
+        serviceUUID = message->remoteEndpoint->resourceUri;
+    }
+
+    uint32_t dataSegmentLength = message->dataLen + CA_HEADER_LENGTH;
+    uint32_t dataLen = message->dataLen;
+    OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "checking for fragmentation and the dataLen is %d",
+              message->dataLen);
+
+    char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
+    VERIFY_NON_NULL_VOID(header, EDR_ADAPTER_TAG, "Memory allocation failed");
+
+    char* dataSegment = (char *) OICCalloc(dataSegmentLength, sizeof(char));
+    if (NULL == dataSegment)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed");
+        OICFree(header);
+        return;
+    }
+
+    CAResult_t result = CAGenerateHeader(header, dataLen);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Generate header failed");
+        OICFree(header);
+        OICFree(dataSegment);
+        return ;
+    }
+
+    memcpy(dataSegment, header, CA_HEADER_LENGTH);
+    OICFree(header);
+    uint32_t length = 0;
+    if (CA_SUPPORTED_EDR_MTU_SIZE > dataSegmentLength)
+    {
+        length = dataSegmentLength;
+        memcpy(dataSegment + CA_HEADER_LENGTH, message->data, dataLen);
+    }
+    else
+    {
+        length =  CA_SUPPORTED_EDR_MTU_SIZE;
+        memcpy(dataSegment + CA_HEADER_LENGTH, message->data,
+               CA_SUPPORTED_EDR_MTU_SIZE - CA_HEADER_LENGTH);
+    }
+
+    uint32_t iter = dataSegmentLength / CA_SUPPORTED_EDR_MTU_SIZE;
+    uint32_t index = 0;
+    if (CA_STATUS_OK != CAEDRClientSendData(remoteAddress, serviceUUID, dataSegment, length,
+                                            &sentLength))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
+        OICFree(dataSegment);
+        return;
+    }
+    OICFree(dataSegment);
+
+    for (index = 1; index < iter; index++)
+    {
+        // Send the remaining header.
+        OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Sending the chunk number [%d]", index);
+
+        if (CA_STATUS_OK != CAEDRClientSendData(remoteAddress, serviceUUID,
+                    message->data + ((index * CA_SUPPORTED_EDR_MTU_SIZE) - CA_HEADER_LENGTH),
+                    CA_SUPPORTED_EDR_MTU_SIZE, &sentLength))
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
+            return;
+        }
+    }
+
+    uint32_t remainingLen = dataSegmentLength % CA_SUPPORTED_EDR_MTU_SIZE;
+    if (remainingLen &&  (dataSegmentLength > CA_SUPPORTED_EDR_MTU_SIZE))
+    {
+        // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Sending the last chunk");
+        if (CA_STATUS_OK != CAEDRClientSendData(remoteAddress, serviceUUID,
+                    message->data + (index * CA_SUPPORTED_EDR_MTU_SIZE) - CA_HEADER_LENGTH,
+                    remainingLen, &sentLength))
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "CAEDRClientSendData API failed");
+            return;
+        }
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAEDRClientSendData(const char *remoteAddress, const char *serviceUUID,
+                               const void *data, uint32_t dataLength, uint32_t *sentLength)
+{
+
+    // Send the first segment with the header.
+    if ((NULL != remoteAddress) && (0 < strlen(remoteAddress))) //Unicast data
+    {
+        if (CA_STATUS_OK != CAEDRClientSendUnicastData(remoteAddress, serviceUUID, data,
+                                                       dataLength, sentLength))
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to send unicast data !");
+            return CA_STATUS_FAILED;
+        }
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "sending multicast data : %s", data);
+        if (CA_STATUS_OK != CAEDRClientSendMulticastData(serviceUUID, data, dataLength,
+                                                         sentLength))
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to send multicast data !");
+            return CA_STATUS_FAILED;
+        }
+    }
+    return CA_STATUS_OK;
+}
+
+void CAAdapterDataReceiverHandler(void *context)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN_CAAdapterDataReceiverHandler");
+
+    CAEDRData *message = (CAEDRData *) context;
+    if (NULL == message)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
+        return;
+    }
+
+    static uint32_t recvDataLen = 0;
+    static uint32_t totalDataLen = 0;
+    static char *defragData = NULL;
+    static CARemoteEndpoint_t *remoteEndpoint = NULL;
+
+    if (!g_isHeaderAvailable)
+    {
+        totalDataLen = CAParseHeader((char*)message->data);
+        if (0 == totalDataLen)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "totalDataLen is zero");
+            return;
+        }
+
+        OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Total data to be accumulated [%d] bytes", totalDataLen);
+
+        defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
+        if (!defragData)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "defragData is null");
+            return;
+        }
+
+        const char *remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
+        const char *serviceUUID = message->remoteEndpoint->resourceUri;
+
+        remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress, serviceUUID);
+
+        memcpy(defragData + recvDataLen, message->data + CA_HEADER_LENGTH,
+               message->dataLen - CA_HEADER_LENGTH);
+        recvDataLen += message->dataLen - CA_HEADER_LENGTH;
+        g_isHeaderAvailable = true;
+    }
+    else
+    {
+        memcpy(defragData + recvDataLen, message->data, message->dataLen);
+        recvDataLen += message->dataLen ;
+    }
+
+    if (totalDataLen == recvDataLen)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Sending data up !");
+        g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
+        recvDataLen = 0;
+        totalDataLen = 0;
+        remoteEndpoint = NULL;
+        g_isHeaderAvailable = false;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT_CAAdapterDataReceiverHandler");
+}
+
+CAResult_t CAAdapterStartQueue()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    // Start send queue thread
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start Send Data Thread");
+        CAEDRClientUnsetCallbacks();
+        //Disconnect all the client connections
+        CAEDRClientDisconnectAll();
+        return CA_STATUS_FAILED;
+    }
+
+    // Start receive queue thread
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_recvQueueHandle))
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start Receive Data Thread");
+        CAEDRClientUnsetCallbacks();
+        //Disconnect all the client connections
+        CAEDRClientDisconnectAll();
+        return CA_STATUS_FAILED;
+    }
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAAdapterStopQueue()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    //Stop send queue thread
+    CAQueueingThreadStop(g_sendQueueHandle);
+
+    //Stop receive queue thread
+    CAQueueingThreadStop(g_recvQueueHandle);
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAAdapterRecvData(const char *remoteAddress, const void *data, uint32_t dataLength,
+                       uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (false == g_adapterState)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
+        *sentLength = 0;
+        return;
+    }
+
+    // Input validation
+    VERIFY_NON_NULL_VOID(data, EDR_ADAPTER_TAG, "Data is null");
+    VERIFY_NON_NULL_VOID(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
+
+    static const char serviceUUID[] = OIC_EDR_SERVICE_ID;
+    // Create remote endpoint
+    CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
+                                                                       serviceUUID);
+    if (NULL == remoteEndpoint)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
+        return;
+    }
+
+    // Add message to data queue
+    CAEDRData *edrData =  CACreateEDRData(remoteEndpoint, data, dataLength);
+    CAQueueingThreadAddData(g_recvQueueHandle, edrData, sizeof(CAEDRData));
+    *sentLength = dataLength;
+
+    // Free remote endpoint
+    CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID, const void *data,
+                             uint32_t dataLength, uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CAAdapterSendData");
+
+    if (false == g_adapterState)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
+        *sentLength = 0;
+        return CA_STATUS_OK;
+    }
+    // Input validation
+    VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "service UUID is null");
+    VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
+    VERIFY_NON_NULL(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
+
+    // Create remote endpoint
+    CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
+                                                                       serviceUUID);
+    if (NULL == remoteEndpoint)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
+        return CA_STATUS_FAILED;
+    }
+
+    // Add message to data queue
+    CAEDRData *edrData =  CACreateEDRData(remoteEndpoint, data, dataLength);
+    CAQueueingThreadAddData(g_sendQueueHandle, edrData, sizeof(CAEDRData));
+    *sentLength = dataLength;
+
+    // Free remote endpoint
+    CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT - CAAdapterSendData");
+    return CA_STATUS_OK;
+}
+
+void CAEDRNotifyNetworkStatus(CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Create localconnectivity
+    if (NULL == g_localConnectivity)
+    {
+        CAEDRGetInterfaceInformation(&g_localConnectivity);
+    }
+
+    if (CA_INTERFACE_UP == status)
+    {
+        if (false == g_adapterState)
+        {
+            // Get Bluetooth adapter state
+            bool adapterState = false;
+            if (CA_STATUS_OK != CAEDRGetAdapterEnableState(&adapterState))
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to get adapter enable state");
+                return;
+            }
+
+            if (false== adapterState)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
+                g_adapterState = false;
+                return;
+            }
+            CAEDRClientSetCallbacks();
+            g_adapterState = true;
+            CAAdapterStartQueue();
+            // starting RFCommServer
+            if (true == g_serverState)
+            {
+                CAStartServer();
+                g_serverState = false;
+            }
+        }
+    }
+    else
+    {
+        g_adapterState = false;
+    }
+
+    // Notify to upper layer
+    if (g_networkChangeCallback && g_localConnectivity && g_edrThreadPool)
+    {
+        // Add notification task to thread pool
+        CAEDRNetworkEvent *event = CAEDRCreateNetworkEvent(g_localConnectivity, status);
+        if (NULL != event)
+        {
+            if (CA_STATUS_OK != ca_thread_pool_add_task(g_edrThreadPool,
+                                                        CAEDROnNetworkStatusChanged,event))
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create threadpool!");
+                return;
+            }
+        }
+    }
+
+    OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDROnNetworkStatusChanged(void *context)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "context is NULL!");
+        return;
+    }
+
+    CAEDRNetworkEvent *networkEvent = (CAEDRNetworkEvent *) context;
+
+    // Notify to upper layer
+    if (g_networkChangeCallback)
+    {
+        g_networkChangeCallback(networkEvent->info, networkEvent->status);
+    }
+
+    // Free the created Network event
+    CAEDRFreeNetworkEvent(networkEvent);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CALocalConnectivity_t *connectivity,
+                                           CANetworkStatus_t status)
+{
+    VERIFY_NON_NULL_RET(connectivity, EDR_ADAPTER_TAG, "connectivity is NULL", NULL);
+
+    // Create CAEDRNetworkEvent
+    CAEDRNetworkEvent *event = (CAEDRNetworkEvent *) OICMalloc(sizeof(CAEDRNetworkEvent));
+    if (NULL == event)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to allocate memory to network event!");
+        return NULL;
+    }
+
+    // Create duplicate of Local connectivity
+    event->info = CAAdapterCopyLocalEndpoint(connectivity);
+    event->status = status;
+    return event;
+}
+
+void CAEDRFreeNetworkEvent(CAEDRNetworkEvent *event)
+{
+    if (event)
+    {
+        CAAdapterFreeLocalEndpoint(event->info);
+        OICFree(event);
+    }
+}
+
+CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                           uint32_t dataLength)
+{
+    CAEDRData *edrData = (CAEDRData *) OICMalloc(sizeof(CAEDRData));
+    if (!edrData)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
+        return NULL;
+    }
+
+    edrData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
+    edrData->data = OICMalloc(dataLength);
+    if (NULL == edrData->data)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
+        CAFreeEDRData(edrData);
+        return NULL;
+    }
+    memcpy(edrData->data, data, dataLength);
+    edrData->dataLen = dataLength;
+
+    return edrData;
+}
+
+void CAFreeEDRData(CAEDRData *edrData)
+{
+    VERIFY_NON_NULL_VOID(edrData, EDR_ADAPTER_TAG, "edrData is NULL");
+
+    CAAdapterFreeRemoteEndpoint(edrData->remoteEndpoint);
+    OICFree(edrData->data);
+    OICFree(edrData);
+}
+
+void CAEDRDataDestroyer(void *data, uint32_t size)
+{
+    CAEDRData *edrdata = (CAEDRData *) data;
+
+    CAFreeEDRData(edrdata);
+}
+
index 3a31a81..a33d708 100644 (file)
 
 #define TAG PCF("CA")
 
-static CANetworkPacketReceivedCallback gEDRReceivedCallback = NULL;
+static CANetworkPacketReceivedCallback g_edrReceivedCallback = NULL;
+static ca_thread_pool_t g_threadPoolHandle = NULL;
 
 CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback)
+        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
+        ca_thread_pool_t handle)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAInitializeEDR");
+    OIC_LOG(DEBUG, TAG, "CAInitializeEDR");
 
-    gEDRReceivedCallback = reqRespCallback;
+    g_edrReceivedCallback = reqRespCallback;
+    g_threadPoolHandle = handle;
 
     // register handlers
     CAConnectivityHandler_t handler;
@@ -42,11 +45,9 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
 
     handler.startAdapter = CAStartEDR;
     handler.startListenServer = CAStartEDRListeningServer;
-    handler.startDiscoverServer = CAStartEDRDiscoveryServer;
+    handler.startDiscoveryServer = CAStartEDRDiscoveryServer;
     handler.sendData = CASendEDRUnicastData;
     handler.sendDataToAll = CASendEDRMulticastData;
-    handler.startNotifyServer = CAStartEDRNotifyServer;
-    handler.sendNotification = CASendEDRNotification;
     handler.GetnetInfo = CAGetEDRInterfaceInformation;
     handler.readData = CAReadEDRData;
     handler.stopAdapter = CAStopEDR;
@@ -59,75 +60,63 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
 
 CAResult_t CAStartEDR()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartEDR");
+    OIC_LOG(DEBUG, TAG, "CAStartEDR");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartEDRListeningServer()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartEDRListeningServer");
+    OIC_LOG(DEBUG, TAG, "CAStartEDRListeningServer");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartEDRDiscoveryServer()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartEDRDiscoveryServer");
+    OIC_LOG(DEBUG, TAG, "CAStartEDRDiscoveryServer");
 
     return CA_STATUS_OK;
 }
 
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+    uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "CASendEDRUnicastData");
+    OIC_LOG(DEBUG, TAG, "CASendEDRUnicastData");
 
-    return 0;
+    return -1;
 }
 
-uint32_t CASendEDRMulticastData(void* data, uint32_t dataLen)
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "CASendEDRMulticastData");
+    OIC_LOG(DEBUG, TAG, "CASendEDRMulticastData");
 
-    return 0;
+    return -1;
 }
 
-CAResult_t CAStartEDRNotifyServer()
+CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartEDRNotifyServer");
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendEDRNotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendEDRNotification");
-
-    return 0;
-}
-
-CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size)
-{
-    OIC_LOG_V(DEBUG, TAG, "CAGetEDRInterfaceInformation");
+    OIC_LOG(DEBUG, TAG, "CAGetEDRInterfaceInformation");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAReadEDRData()
 {
-    OIC_LOG_V(DEBUG, TAG, "Read EDR Data");
+    OIC_LOG(DEBUG, TAG, "Read EDR Data");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStopEDR()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStopEDR");
+    OIC_LOG(DEBUG, TAG, "CAStopEDR");
 
     return CA_STATUS_OK;
 }
 
 void CATerminateEDR()
 {
-    OIC_LOG_V(DEBUG, TAG, "CATerminateEDR");
+    OIC_LOG(DEBUG, TAG, "CATerminateEDR");
 }
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrclient.c b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrclient.c
new file mode 100644 (file)
index 0000000..b489dc3
--- /dev/null
@@ -0,0 +1,867 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides the APIs to establish RFCOMM connection with remote
+ * bluetooth device.
+ */
+
+#include <string.h>
+#include <bluetooth.h>
+
+#include "caedrinterface.h"
+#include "camutex.h"
+#include "caedrendpoint.h"
+#include "caadapterutils.h"
+#include "caedrutils.h"
+#include "logger.h"
+#include "cacommon.h"
+#include "caedrdevicelist.h"
+
+/**
+ * @var g_edrDeviceListMutex
+ * @brief Mutex to synchronize the access to Bluetooth device information list.
+ */
+static ca_mutex g_edrDeviceListMutex = NULL;
+
+/**
+ * @var g_edrDeviceList
+ * @brief Peer Bluetooth device information list.
+ */
+static EDRDeviceList *g_edrDeviceList = NULL;
+
+/**
+ * @var gEDRNetworkChangeCallback
+ * @brief Maintains the callback to be notified when data received from remote Bluetooth device
+ */
+static CAEDRDataReceivedCallback g_edrPacketReceivedCallback = NULL;
+
+/**
+ * @fn CAEDRManagerInitializeMutex
+ * @brief This function creates mutex.
+ */
+static void CAEDRManagerInitializeMutex(void);
+
+/**
+ * @fn CAEDRManagerTerminateMutex
+ * @brief This function frees mutex.
+ */
+static void CAEDRManagerTerminateMutex(void);
+
+/**
+ * @fn CAEDRDataRecvCallback
+ * @brief This callback is registered to recieve data on any open RFCOMM connection.
+ */
+static void CAEDRDataRecvCallback(bt_socket_received_data_s *data, void *userData);
+
+/**
+ * @brief This function starts device discovery.
+ * @return NONE
+ */
+static CAResult_t CAEDRStartDeviceDiscovery(void);
+
+/**
+ * @fn CAEDRStopServiceSearch
+ * @brief This function stops any ongoing service sevice search.
+ */
+static CAResult_t CAEDRStopServiceSearch(void);
+
+/**
+ * @fn CAEDRStopDeviceDiscovery
+ * @brief This function stops device discovery.
+ */
+static CAResult_t CAEDRStopDeviceDiscovery(void);
+
+/**
+ * @fn CAEDRStartServiceSearch
+ * @brief This function searches for OIC service for remote Bluetooth device.
+ */
+static CAResult_t CAEDRStartServiceSearch(const char *remoteAddress);
+
+/**
+ * @fn CAEDRDeviceDiscoveryCallback
+ * @brief This callback is registered to recieve all bluetooth nearby devices when device
+ *           scan is initiated.
+ */
+static void CAEDRDeviceDiscoveryCallback(int result,
+                                         bt_adapter_device_discovery_state_e state,
+                                         bt_adapter_device_discovery_info_s *discoveryInfo,
+                                         void *userData);
+
+/**
+ * @fn CAEDRServiceSearchedCallback
+ * @brief This callback is registered to recieve all the services remote bluetooth device supports
+ *           when service search initiated.
+ */
+static void CAEDRServiceSearchedCallback(int result, bt_device_sdp_info_s *sdpInfo,
+                                        void *userData);
+
+/**
+ * @fn CAEDRSocketConnectionStateCallback
+ * @brief This callback is registered to receive bluetooth RFCOMM connection state changes.
+ */
+static void CAEDRSocketConnectionStateCallback(int result,
+                                    bt_socket_connection_state_e state,
+                                              bt_socket_connection_s *connection, void *userData);
+
+/**
+ * @fn CAEDRClientConnect
+ * @brief Establishes RFCOMM connection with remote bluetooth device
+ */
+static CAResult_t CAEDRClientConnect(const char *remoteAddress, const char *serviceUUID);
+
+/**
+ * @fn CAEDRClientDisconnect
+ * @brief  Disconnect RFCOMM client socket connection
+ */
+static CAResult_t CAEDRClientDisconnect(const int32_t clientID);
+
+void CAEDRSetPacketReceivedCallback(CAEDRDataReceivedCallback packetReceivedCallback)
+{
+    g_edrPacketReceivedCallback = packetReceivedCallback;
+}
+
+void CAEDRSocketConnectionStateCallback(int result, bt_socket_connection_state_e state,
+                                       bt_socket_connection_s *connection, void *userData)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    EDRDevice *device = NULL;
+
+    if (BT_ERROR_NONE != result || NULL == connection)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid connection state!, error num [%x]",
+                  result);
+        return;
+    }
+
+    switch (state)
+    {
+        case BT_SOCKET_CONNECTED:
+            {
+                ca_mutex_lock(g_edrDeviceListMutex);
+                CAResult_t res = CAGetEDRDevice(g_edrDeviceList, connection->remote_address,
+                                                   &device);
+                if (CA_STATUS_OK != res)
+                {
+                    // Create the deviceinfo and add to list
+                    res = CACreateAndAddToDeviceList(&g_edrDeviceList,
+                            connection->remote_address, OIC_EDR_SERVICE_ID, &device);
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed add device to list ret[%d]", res);
+                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        return;
+                    }
+
+                    if(!device)
+                    {
+                        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        return;
+                    }
+
+                    device->socketFD = connection->socket_fd;
+                    ca_mutex_unlock(g_edrDeviceListMutex);
+                    return;
+                }
+
+                if(!device)
+                {
+                    OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+                    ca_mutex_unlock(g_edrDeviceListMutex);
+                    return;
+                }
+                device->socketFD = connection->socket_fd;
+                while (device->pendingDataList)
+                {
+                    uint32_t sentData = 0;
+                    EDRData *edrData = device->pendingDataList->data;
+                    res = CAEDRSendData(device->socketFD, edrData->data,
+                                                     edrData->dataLength, &sentData);
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to send pending data [%s]",
+                                  device->remoteAddress);
+
+                        // Remove all the data from pending list
+                        CADestroyEDRDataList(&device->pendingDataList);
+                        break;
+                    }
+
+                    // Remove the data which send from pending list
+                    CARemoveEDRDataFromList(&device->pendingDataList);
+                }
+                ca_mutex_unlock(g_edrDeviceListMutex);
+            }
+            break;
+
+        case BT_SOCKET_DISCONNECTED:
+            {
+                ca_mutex_lock(g_edrDeviceListMutex);
+                CARemoveEDRDeviceFromList(&g_edrDeviceList, connection->remote_address);
+                ca_mutex_unlock(g_edrDeviceListMutex);
+            }
+            break;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+
+void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_e state,
+                                 bt_adapter_device_discovery_info_s *discoveryInfo, void *userData)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    EDRDevice *device = NULL;
+
+    if (BT_ERROR_NONE != result)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Received bad state!, error num [%x]",
+                  result);
+        return;
+    }
+
+    switch (state)
+    {
+        case BT_ADAPTER_DEVICE_DISCOVERY_STARTED:
+            {
+                OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Discovery started!");
+            }
+            break;
+
+        case BT_ADAPTER_DEVICE_DISCOVERY_FINISHED:
+            {
+                OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Discovery finished!");
+            }
+            break;
+
+        case BT_ADAPTER_DEVICE_DISCOVERY_FOUND:
+            {
+                OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Device discovered [%s]!",
+                          discoveryInfo->remote_name);
+                if (true == CAEDRIsServiceSupported((const char **)discoveryInfo->service_uuid,
+                                                        discoveryInfo->service_count,
+                                                        OIC_EDR_SERVICE_ID))
+                {
+                    // Check if the deivce is already in the list
+                    ca_mutex_lock(g_edrDeviceListMutex);
+                    if (CA_STATUS_OK == CAGetEDRDevice(g_edrDeviceList,
+                                                discoveryInfo->remote_address, &device))
+                    {
+                        if(!device)
+                        {
+                            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+                            ca_mutex_unlock(g_edrDeviceListMutex);
+                            return;
+                        }
+                        device->serviceSearched = true;
+                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        return;
+                    }
+
+                    // Create the deviceinfo and add to list
+                    CAResult_t res = CACreateAndAddToDeviceList(&g_edrDeviceList,
+                            discoveryInfo->remote_address, OIC_EDR_SERVICE_ID, &device);
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to add device to list!");
+                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        return;
+                    }
+
+                    if(!device)
+                    {
+                        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        return;
+                    }
+                    device->serviceSearched = true;
+                    ca_mutex_unlock(g_edrDeviceListMutex);
+                }
+                else
+                {
+                    OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Device does not support OIC service!");
+                }
+            }
+            break;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDRServiceSearchedCallback(int32_t result,
+                bt_device_sdp_info_s *sdpInfo,void *userData)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (NULL == sdpInfo)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "SDP info is null!");
+        return;
+    }
+
+    ca_mutex_lock(g_edrDeviceListMutex);
+
+    EDRDevice *device = NULL;
+    CAResult_t res = CAGetEDRDevice(g_edrDeviceList, sdpInfo->remote_address, &device);
+    if (CA_STATUS_OK == res && NULL != device)
+    {
+        if (device->serviceSearched)
+        {
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Service is already searched for this device!");
+            ca_mutex_unlock(g_edrDeviceListMutex);
+            return;
+        }
+
+        if (true == CAEDRIsServiceSupported((const char **)sdpInfo->service_uuid,
+                                           sdpInfo->service_count, OIC_EDR_SERVICE_ID))
+        {
+            device->serviceSearched = true;
+            res = CAEDRClientConnect(sdpInfo->remote_address, OIC_EDR_SERVICE_ID);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to make rfcomm connection!");
+
+                // Remove the device from device list
+                CARemoveEDRDeviceFromList(&g_edrDeviceList, sdpInfo->remote_address);
+            }
+        }
+        else
+        {
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Device does not contain OIC service!");
+
+            // Remove device from list as it does not support OIC service
+            CARemoveEDRDeviceFromList(&g_edrDeviceList, sdpInfo->remote_address);
+        }
+    }
+
+    ca_mutex_unlock(g_edrDeviceListMutex);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAEDRStartDeviceDiscovery(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+
+    bool isDiscoveryStarted = false;
+
+    // Check the device discovery state
+    bt_error_e err = bt_adapter_is_discovering(&isDiscoveryStarted);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    //Start device discovery if its not started
+    if (false == isDiscoveryStarted)
+    {
+        err = bt_adapter_start_device_discovery();
+        if (BT_ERROR_NONE != err)
+        {
+            OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Device discovery failed!, error num [%x]",
+                      err);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStopServiceSearch(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    bt_error_e err = bt_device_cancel_service_search();
+    // Stop ongoing service search
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStopDeviceDiscovery(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    bool isDiscoveryStarted = false;
+    bt_error_e err = bt_adapter_is_discovering(&isDiscoveryStarted);
+    // Check the device discovery state
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    //stop the device discovery process
+    if (true == isDiscoveryStarted)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Stopping the device search process");
+        if (BT_ERROR_NONE != (err = bt_adapter_stop_device_discovery()))
+        {
+            OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to stop discovery!, error num [%x]",
+                      err);
+        }
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStartServiceSearch(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(remoteAddress, EDR_ADAPTER_TAG, "Remote address is null");
+    if (!remoteAddress[0])
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Remote address is empty!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    bt_error_e err = bt_device_start_service_search(remoteAddress);
+    // Start searching for OIC service
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRClientSetCallbacks(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Register for discovery and rfcomm socket connection callbacks
+    bt_adapter_set_device_discovery_state_changed_cb(CAEDRDeviceDiscoveryCallback, NULL);
+    bt_device_set_service_searched_cb(CAEDRServiceSearchedCallback, NULL);
+    bt_socket_set_connection_state_changed_cb(CAEDRSocketConnectionStateCallback, NULL);
+    bt_socket_set_data_received_cb(CAEDRDataRecvCallback, NULL);
+
+    // Start device discovery
+    CAResult_t result = CAEDRStartDeviceDiscovery();
+    if(CA_STATUS_OK != result)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Failed to Start Device discovery");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+
+void CAEDRClientUnsetCallbacks(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Stop service search
+    CAEDRStopServiceSearch();
+
+    // Stop the device discovery process
+    CAEDRStopDeviceDiscovery();
+
+    // reset bluetooth adapter callbacks
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Resetting the callbacks");
+    bt_adapter_unset_device_discovery_state_changed_cb();
+    bt_device_unset_service_searched_cb();
+    bt_socket_unset_connection_state_changed_cb();
+    bt_socket_unset_data_received_cb();
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDRManagerInitializeMutex(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (!g_edrDeviceListMutex)
+    {
+        g_edrDeviceListMutex = ca_mutex_new();
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDRManagerTerminateMutex(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (g_edrDeviceListMutex)
+    {
+        ca_mutex_free(g_edrDeviceListMutex);
+        g_edrDeviceListMutex = NULL;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDRInitializeClient(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    CAEDRManagerInitializeMutex();
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDRClientTerminate()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Free EDRDevices list
+    if (g_edrDeviceListMutex)
+    {
+        ca_mutex_lock(g_edrDeviceListMutex);
+        CADestroyEDRDeviceList(&g_edrDeviceList);
+        ca_mutex_unlock(g_edrDeviceListMutex);
+    }
+
+    // Free the mutex
+    CAEDRManagerTerminateMutex();
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CAEDRClientDisconnectAll(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    ca_mutex_lock(g_edrDeviceListMutex);
+
+    EDRDeviceList *cur = g_edrDeviceList;
+    while (cur != NULL)
+    {
+        EDRDevice *device = cur->device;
+        cur = cur->next;
+
+        if (device && 0 <= device->socketFD)
+        {
+            CAResult_t result = CAEDRClientDisconnect(device->socketFD);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to disconnect with client :%s",
+                          device->remoteAddress);
+            }
+
+            device->socketFD = -1;
+        }
+    }
+
+    ca_mutex_unlock(g_edrDeviceListMutex);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+
+CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress, const char *serviceUUID,
+                                      const void *data, uint32_t dataLength, uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    EDRDevice *device = NULL;
+
+    // Input validation
+    VERIFY_NON_NULL(remoteAddress, EDR_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "service UUID is null");
+    VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
+    VERIFY_NON_NULL(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
+
+    if (0 >= dataLength)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: Negative data length!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // Check the connection existence with remote device
+    ca_mutex_lock(g_edrDeviceListMutex);
+    CAResult_t result = CAGetEDRDevice(g_edrDeviceList, remoteAddress, &device);
+    if (CA_STATUS_OK != result)
+    {
+        // Create new device and add to list
+        result = CACreateAndAddToDeviceList(&g_edrDeviceList, remoteAddress,
+                                            OIC_EDR_SERVICE_ID, &device);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed create device and add to list!");
+
+            ca_mutex_unlock(g_edrDeviceListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        // Start the OIC service search newly created device
+        result = CAEDRStartServiceSearch(remoteAddress);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to initiate service search!");
+
+            // Remove device from list
+            CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
+
+            ca_mutex_unlock(g_edrDeviceListMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if(!device)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+        // Remove device from list
+        CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
+
+        ca_mutex_unlock(g_edrDeviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_unlock(g_edrDeviceListMutex);
+
+    if (-1 == device->socketFD)
+    {
+        // Adding to pending list
+        result = CAAddEDRDataToList(&device->pendingDataList, data,
+                                              dataLength);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to add data to pending list!");
+
+            //Remove device from list
+            CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
+            return CA_STATUS_FAILED;
+        }
+
+        // Make a rfcomm connection with remote BT Device
+        if (device->serviceSearched &&
+            CA_STATUS_OK != CAEDRClientConnect(remoteAddress, serviceUUID))
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to make RFCOMM connection!");
+
+            //Remove device from list
+            CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
+            return CA_STATUS_FAILED;
+        }
+        *sentLength = dataLength;
+    }
+    else
+    {
+        result = CAEDRSendData(device->socketFD, data, dataLength, sentLength);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to send data!");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, const void *data,
+                                        uint32_t dataLength, uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "service UUID is null");
+    VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
+    VERIFY_NON_NULL(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
+
+    if (0 >= dataLength)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: Negative data length!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    *sentLength = dataLength;
+
+    // Send the packet to all OIC devices
+    ca_mutex_lock(g_edrDeviceListMutex);
+    EDRDeviceList *curList = g_edrDeviceList;
+    CAResult_t result = CA_STATUS_FAILED;
+    while (curList != NULL)
+    {
+        EDRDevice *device = curList->device;
+        curList = curList->next;
+
+        if (!device)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "There is no device!");
+            break;
+        }
+
+        if (-1 == device->socketFD)
+        {
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN1");
+            // Check if the device service search is finished
+            if (false == device->serviceSearched)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Device services are still unknown!");
+                continue;
+            }
+
+            // Adding to pendding list
+            result = CAAddEDRDataToList(&device->pendingDataList, data,
+                                                  dataLength);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to add data to pending list !");
+                continue;
+            }
+
+            // Make a rfcomm connection with remote BT Device
+            result = CAEDRClientConnect(device->remoteAddress, device->serviceUUID);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to make RFCOMM connection !");
+
+                //Remove the data which added to pending list
+                CARemoveEDRDataFromList(&device->pendingDataList);
+                continue;
+            }
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN2");
+        }
+        else
+        {
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN3");
+            result = CAEDRSendData(device->socketFD, data, dataLength, sentLength);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to send data to [%s] !",
+                          device->remoteAddress);
+            }
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN4");
+        }
+    }
+    ca_mutex_unlock(g_edrDeviceListMutex);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRClientConnect(const char *remoteAddress, const char *serviceUUID)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(remoteAddress, EDR_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "Service UUID is null");
+
+    size_t addressLen = strlen(remoteAddress);
+    if (0 == addressLen || CA_MACADDR_SIZE - 1 != addressLen)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: Invalid remote address");
+        return  CA_STATUS_INVALID_PARAM;
+    }
+
+    if (!serviceUUID[0])
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: Empty service uuid");
+        return  CA_STATUS_INVALID_PARAM;
+    }
+
+    bt_error_e err = bt_socket_connect_rfcomm(remoteAddress, serviceUUID);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                  "Failed to connect!, address [%s] error num [%x]",
+                  remoteAddress, err);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRClientDisconnect(const int32_t clientID)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Input validation
+    if (0 > clientID)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: negative client id");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    bt_error_e err = bt_socket_disconnect_rfcomm(clientID);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed close rfcomm client socket!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRDataRecvCallback(bt_socket_received_data_s *data, void *userData)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    EDRDevice *device = NULL;
+
+    if (NULL == data || 0 >= data->data_size)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Data is null!");
+        return;
+    }
+
+    // Get EDR device from list
+    ca_mutex_lock(g_edrDeviceListMutex);
+    CAResult_t result = CAGetEDRDeviceBySocketId(g_edrDeviceList, data->socket_fd, &device);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Could not find the device!");
+
+        ca_mutex_unlock(g_edrDeviceListMutex);
+        return;
+    }
+    ca_mutex_unlock(g_edrDeviceListMutex);
+
+    if (!device)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "There is no device!");
+        return;
+    }
+
+    uint32_t sentLength = 0;
+
+    g_edrPacketReceivedCallback(device->remoteAddress, data->data,
+                                (uint32_t)data->data_size, &sentLength);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrdevicelist.c b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrdevicelist.c
new file mode 100644 (file)
index 0000000..cd84528
--- /dev/null
@@ -0,0 +1,407 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs to access the discovered bluetooth device list.
+ */
+
+#include "caedrdevicelist.h"
+#include "caadapterutils.h"
+#include "caedrutils.h"
+#include "logger.h"
+
+
+/**
+ * @fn  CACreateEDRDevice
+ * @brief  Creates #EDRDevice for specified remote address and uuid.
+ *
+ */
+static CAResult_t CACreateEDRDevice(const char *deviceAddress,
+                                const char *uuid,EDRDevice **device);
+
+
+/**
+ * @fn  CADestroyEDRDevice
+ * @brief  Free all the memory associated with specified device.
+ *
+ */
+static void CADestroyEDRDevice(EDRDevice *device);
+
+
+/**
+ * @fn  CADestroyEDRData
+ * @brief  Free all the memory associated with specified data.
+ *
+ */
+static void CADestroyEDRData(EDRData *data);
+
+
+CAResult_t CACreateAndAddToDeviceList(EDRDeviceList **deviceList, const char *deviceAddress,
+                                      const char *uuid, EDRDevice **device)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
+    CAResult_t result = CACreateEDRDevice(deviceAddress, uuid, device);
+    if (CA_STATUS_OK != result || NULL == *device)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid or Not bonded device ret[%d]", result);
+        return CA_STATUS_FAILED;
+    }
+    result = CAAddEDRDeviceToList(deviceList, *device);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to add in list ret[%d]", result);
+
+        //Remove created EDRDevice
+        CADestroyEDRDevice(*device);
+        *device = NULL;
+
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CACreateEDRDevice(const char *deviceAddress, const char *uuid, EDRDevice **device)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(uuid, EDR_ADAPTER_TAG, "uuid is null");
+    VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
+
+    *device = (EDRDevice *) OICMalloc(sizeof(EDRDevice));
+    if (NULL == *device)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Out of memory (device)!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    //Copy bluetooth address
+    if (deviceAddress[0])
+    {
+        (*device)->remoteAddress = strndup(deviceAddress, strlen(deviceAddress));
+        if (NULL == (*device)->remoteAddress)
+        {
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Out of memory (remote address)!");
+
+            OICFree(*device);
+            *device = NULL;
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+
+    //Copy OIC service uuid
+    if (strlen(uuid))
+    {
+        (*device)->serviceUUID = strndup(uuid, strlen(uuid));
+        if (NULL == (*device)->serviceUUID)
+        {
+            OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                      "[createEDRDevice] Out of memory (service uuid)!");
+
+            OICFree((*device)->remoteAddress);
+            OICFree(*device);
+            *device = NULL;
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+
+    (*device)->socketFD = -1;
+    (*device)->pendingDataList = NULL;
+    (*device)->serviceSearched = false;
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAAddEDRDeviceToList(EDRDeviceList **deviceList, EDRDevice *device)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
+
+    EDRDeviceList *node = (EDRDeviceList *) OICMalloc(sizeof(EDRDeviceList));
+    if (NULL == node)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Out of memory (device list)!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    node->device = device;
+    node->next = NULL;
+
+    if (NULL == *deviceList) //Empty list
+    {
+        *deviceList = node;
+    }
+    else //Add at front end
+    {
+        node->next = *deviceList;
+        *deviceList = node;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetEDRDevice(EDRDeviceList *deviceList,
+                            const char *deviceAddress, EDRDevice **device)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
+
+    EDRDeviceList *curNode = deviceList;
+    *device = NULL;
+    while (curNode != NULL)
+    {
+        if (!strcasecmp(curNode->device->remoteAddress, deviceAddress))
+        {
+            *device = curNode->device;
+            return CA_STATUS_OK;
+        }
+
+        curNode = curNode->next;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT [Device not found!]");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CAGetEDRDeviceBySocketId(EDRDeviceList *deviceList,
+                                    int32_t socketID, EDRDevice **device)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
+    EDRDeviceList *curNode = deviceList;
+    *device = NULL;
+    while (curNode != NULL)
+    {
+        if (curNode->device->socketFD == socketID)
+        {
+            *device = curNode->device;
+            return CA_STATUS_OK;
+        }
+
+        curNode = curNode->next;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CARemoveEDRDeviceFromList(EDRDeviceList **deviceList,
+    const char *deviceAddress)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
+
+    EDRDeviceList *curNode = NULL;
+    EDRDeviceList *prevNode = NULL;
+
+    curNode = *deviceList;
+    while (curNode != NULL)
+    {
+        if (!strcasecmp(curNode->device->remoteAddress, deviceAddress))
+        {
+            if (curNode == *deviceList)
+            {
+                *deviceList = curNode->next;
+
+                curNode->next = NULL;
+                CADestroyEDRDeviceList(&curNode);
+                return CA_STATUS_OK;
+            }
+            else
+            {
+                prevNode->next = curNode->next;
+
+                curNode->next = NULL;
+                CADestroyEDRDeviceList(&curNode);
+                return CA_STATUS_OK;
+            }
+        }
+        else
+        {
+            prevNode = curNode;
+            curNode = curNode->next;
+        }
+    }
+
+    OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OUT Device not in the list !");
+    return CA_STATUS_FAILED;
+}
+
+void CADestroyEDRDeviceList(EDRDeviceList **deviceList)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(deviceList, EDR_ADAPTER_TAG, "deviceList is null");
+
+    while (*deviceList)
+    {
+        EDRDeviceList *curNode = *deviceList;
+        *deviceList = (*deviceList)->next;
+
+        CADestroyEDRDevice(curNode->device);
+        OICFree(curNode);
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CADestroyEDRDevice(EDRDevice *device)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    if (device)
+    {
+        OICFree(device->remoteAddress);
+        OICFree(device->serviceUUID);
+        CADestroyEDRDataList(&device->pendingDataList);
+        OICFree(device);
+    }
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAAddEDRDataToList(EDRDataList **dataList, const void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(dataList, EDR_ADAPTER_TAG, "Data list is null");
+    VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    EDRDataList *pending_data = (EDRDataList *) OICMalloc(sizeof(EDRDataList));
+    if (NULL == pending_data)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data list)!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    pending_data->data = (EDRData *) OICMalloc(sizeof(EDRData));
+    if (NULL == pending_data->data)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data node)!");
+
+        OICFree(pending_data);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    pending_data->next = NULL;
+
+    pending_data->data->data = (void *) OICMalloc(dataLength); //data
+    if (NULL == pending_data->data->data)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data)!");
+
+        OICFree(pending_data->data);
+        OICFree(pending_data);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    memcpy(pending_data->data->data, data, dataLength);
+    pending_data->data->dataLength = dataLength;
+
+    if (NULL == *dataList) //Empty list
+    {
+        *dataList = pending_data;
+    }
+    else //Add at rear end
+    {
+        EDRDataList *curNode = *dataList;
+        while (curNode->next != NULL)
+        {
+            curNode = curNode->next;
+        }
+
+        curNode->next = pending_data;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARemoveEDRDataFromList(EDRDataList **dataList)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(dataList, EDR_ADAPTER_TAG, "Data list is null");
+
+    if (*dataList)
+    {
+        EDRDataList *curNode = *dataList;
+        *dataList = (*dataList)->next;
+
+        //Delete the first node
+        CADestroyEDRData(curNode->data);
+        OICFree(curNode);
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CADestroyEDRDataList(EDRDataList **dataList)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(dataList, EDR_ADAPTER_TAG, "Data list is null");
+
+    while (*dataList)
+    {
+        EDRDataList *curNode = *dataList;
+        *dataList = (*dataList)->next;
+
+        CADestroyEDRData(curNode->data);
+        OICFree(curNode);
+    }
+
+    *dataList = NULL;
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+void CADestroyEDRData(EDRData *data)
+{
+    if (data)
+    {
+        OICFree(data->data);
+        OICFree(data);
+    }
+}
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrdevicelist.h b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrdevicelist.h
new file mode 100644 (file)
index 0000000..eec78cd
--- /dev/null
@@ -0,0 +1,197 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs to manage discovered bluetooth device list.
+ */
+
+#ifndef CA_EDR_DEVICE_LIST_H_
+#define CA_EDR_DEVICE_LIST_H_
+
+#include "cacommon.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @struct EDRData
+ * @brief Structure to maintain the data needs to send to peer Bluetooth device.
+ */
+typedef struct
+{
+    void *data;             /**< Data to be sent to peer Bluetooth device. */
+    uint32_t dataLength;    /**< Length of the data. */
+} EDRData;
+
+/**
+ * @struct EDRDataList
+ * @brief Structure to maintain list of data needs to send to peer Bluetooth device.
+ */
+typedef struct _EDRDataList
+{
+    EDRData *data;            /**< Data to be sent to peer Bluetooth device. */
+    struct _EDRDataList *next;/**< Reference to next data in list. */
+} EDRDataList;
+
+/**
+ * @struct EDRDevice
+ * @brief Structure to maintain information of peer Bluetooth device.
+ */
+typedef struct
+{
+    char *remoteAddress;        /**< Address of peer Bluetooth device. */
+    char *serviceUUID;          /**< OIC service UUID running in peer Bluetooth device. */
+    int socketFD;           /**< RfComm connection socket FD. */
+    EDRDataList *pendingDataList;/**< List of data needs to send to peer Bluetooth device. */
+    bool serviceSearched;   /**< Flag to indicate the status of service search. */
+} EDRDevice;
+
+/**
+ * @struct EDRDeviceList
+ * @brief Structure to maintain list of peer Bluetooth device information.
+ */
+typedef struct _EDRDeviceList
+{
+    EDRDevice *device;            /**< Bluetooth device information. */
+    struct _EDRDeviceList *next;  /**< Reference to next device information. */
+} EDRDeviceList;
+
+/**
+ * @brief  Creates #EDRDevice for specified remote address and uuid and to device list.
+ *
+ * @param  deviceList       [IN,OUT] Device list which created device add to.
+ * @param  deviceAddress    [IN]     Bluetooth device address.
+ * @param  uuid             [IN]     Service uuid.
+ * @param  device           [IN]     Created #EDRDevice.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval #CA_STATUS_FAILED Failed to create device and add to list
+ */
+CAResult_t CACreateAndAddToDeviceList(EDRDeviceList **deviceList, const char *deviceAddress,
+                                      const char *uuid, EDRDevice **device);
+
+/**
+ * @brief  Insert device to specified list.
+ *
+ * @param  deviceList [IN,OUT] Device list to which specifed @device to be added.
+ * @param  device     [IN]     Device to be added to list.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval #CA_MEMORY_ALLOC_FAILED Memory allocation failed
+ */
+CAResult_t CAAddEDRDeviceToList(EDRDeviceList **deviceList, EDRDevice *device);
+
+/**
+ * @brief  Get the device from list which matches specified device address.
+ *
+ * @param  deviceList    [IN]  Device list to search for the device.
+ * @param  deviceAddress [IN]  Device address used for matching.
+ * @param  device        [OUT] #EDRDevice which has matching device address.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval #CA_STATUS_FAILED Device is not found in the list
+ */
+CAResult_t CAGetEDRDevice(EDRDeviceList *deviceList,
+                           const char *deviceAddress, EDRDevice **device);
+
+/**
+ * @brief  Get the device from list which matches specified RFCOMM socket id.
+ *
+ * @param  deviceList [IN]  Device list to search for the device.
+ * @param  socketID   [IN]  RFCOMM socket id.
+ * @param  device     [OUT] #EDRDevice which has matching RFCOMM socket id .
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval #CA_STATUS_FAILED Device is not found in the list
+ */
+CAResult_t CAGetEDRDeviceBySocketId(EDRDeviceList *deviceList, int32_t socketID,
+                                    EDRDevice **device);
+
+/**
+ * @brief  Remove and delete the device matching specified device address from list.
+ *
+ * @param  deviceList    [IN,OUT] Device list to search for the device.
+ * @param  deviceAddress [IN]     Bluetooth device address.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval #CA_STATUS_FAILED Device is not found in the list
+ */
+CAResult_t CARemoveEDRDeviceFromList(EDRDeviceList **deviceList,
+                                    const char *deviceAddress);
+
+/**
+ * @brief  Destroy the specified device list. Removes and delete all the devices in the list.
+ * @param  deviceList [IN,OUT] Device list to be destroyed.
+ * @return NONE
+ */
+void CADestroyEDRDeviceList(EDRDeviceList **deviceList);
+
+/**
+ * @brief  Insert data to specified list.
+ *
+ * @param  dataList   [IN,OUT] Data list to which data will be add.
+ * @param  data       [IN]      Data to be stored.
+ * @param  dataLength [IN]      Length of the data.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval #CA_MEMORY_ALLOC_FAILED Memory allocation failed
+ */
+CAResult_t CAAddEDRDataToList(EDRDataList **dataList, const void *data, uint32_t dataLength);
+
+/**
+ * @brief  Remove and delete data from front end of list.
+ * @param  dataList [IN,OUT] Data list from which data will be removed.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
+ */
+CAResult_t CARemoveEDRDataFromList(EDRDataList **dataList);
+
+/**
+ * @brief  Destroy the specified data list. Removes and deletes all the data in the list.
+ * @param  dataList [IN] Data list to be destroyed.
+ * @return NONE
+ */
+void CADestroyEDRDataList(EDRDataList **dataList);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_DEVICE_LIST_H_ */
+
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.c b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.c
new file mode 100644 (file)
index 0000000..26e7402
--- /dev/null
@@ -0,0 +1,58 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides the APIs to send data on established RFCOMM connections.
+ */
+
+#include "caedrendpoint.h"
+#include "caadapterutils.h"
+#include "caedrutils.h"
+#include "logger.h"
+
+CAResult_t CAEDRSendData(int serverFD, const void *data, uint32_t dataLength,
+                         uint32_t *sentDataLen)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
+    VERIFY_NON_NULL(sentDataLen, EDR_ADAPTER_TAG, "Sent data length holder is null");
+
+    if (0 > serverFD)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: Negative socket id");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    int dataLen = bt_socket_send_data(serverFD, (const char *)data, dataLength);
+    if (dataLen == -1)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "sending data failed!, soketid [%d]", serverFD);
+        *sentDataLen = 0;
+        return CA_STATUS_FAILED;
+    }
+
+    *sentDataLen = dataLen;
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.h b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.h
new file mode 100644 (file)
index 0000000..3df03f3
--- /dev/null
@@ -0,0 +1,61 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides the APIs to send data on established RFCOMM connections.
+ */
+
+#ifndef CA_EDR_ENDPOINT_H_
+#define CA_EDR_ENDPOINT_H_
+
+#include <bluetooth.h>
+
+#include "cacommon.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief  Send data over RFCOMM connection.
+ *
+ * @param  serverFD         [IN] The RFCOMM connection socket file descriptor.
+ * @param  data             [IN] The data needs to be sent.
+ * @param  dataLength       [IN] The length of data.
+ * @param  sentDataLength   [IN] The length of data which actually sent successful.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendData(int serverFD, const void *data, uint32_t dataLength,
+                        uint32_t *sentDataLength);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_ENDPOINT_H_ */
+
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c
new file mode 100644 (file)
index 0000000..f123852
--- /dev/null
@@ -0,0 +1,199 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides the APIs for EDR Network Monitor.
+ */
+
+#include <string.h>
+#include <bluetooth.h>
+
+#include "caedrinterface.h"
+#include "caedrdevicelist.h"
+#include "caedrutils.h"
+#include "caadapterutils.h"
+#include "caqueueingthread.h"
+
+/**
+ * @var g_edrNetworkChangeCallback
+ * @brief Maintains the callback to be notified on local bluetooth adapter status change.
+ */
+static CAEDRNetworkStatusCallback g_edrNetworkChangeCallback = NULL;
+
+/**
+ * @fn CAEDRAdapterStateChangeCallback
+ * @brief This callback is registered to receive bluetooth adapter state changes.
+ */
+static void CAEDRAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState,
+                                            void *userData);
+
+CAResult_t CAEDRInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Initialize Bluetooth service
+    int err = bt_initialize();
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRTerminateNetworkMonitor(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    g_edrNetworkChangeCallback = NULL;
+
+    // Terminate Bluetooth service
+    bt_deinitialize();
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAEDRStartNetworkMonitor()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    int ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL);
+    if(BT_ERROR_NONE != ret)
+    {
+       OIC_LOG(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
+       return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRStopNetworkMonitor()
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    // Unset bluetooth adapter callbacks
+    int ret = bt_adapter_unset_state_changed_cb();
+    if(BT_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRSetNetworkChangeCallback(
+    CAEDRNetworkStatusCallback networkChangeCallback)
+{
+    g_edrNetworkChangeCallback = networkChangeCallback;
+}
+
+CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(info, EDR_ADAPTER_TAG, "LocalConnectivity info is null");
+
+    // Get the bluetooth adapter local address
+    char *localAddress = NULL;
+    int err = bt_adapter_get_address(&localAddress);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                  "Getting local adapter address failed!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    // Create network info
+    *info = CAAdapterCreateLocalEndpoint(CA_EDR, localAddress);
+    if (NULL == *info)
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create LocalConnectivity instance!");
+
+        OICFree(localAddress);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    OICFree(localAddress);
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRGetAdapterEnableState(bool *state)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(state, EDR_ADAPTER_TAG, "state holder is NULL!");
+
+
+    bt_adapter_state_e adapterState;
+    int err = bt_adapter_get_state(&adapterState);
+    // Get Bluetooth adapter state
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth get state failed!, error num [%x]",
+                  err);
+
+        return CA_STATUS_FAILED;
+    }
+
+    *state = false;
+    if (BT_ADAPTER_ENABLED == adapterState)
+    {
+        *state = true;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState,
+                                     void *userData)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (BT_ADAPTER_ENABLED == adapterState)
+    {
+        // Notity to upper layer
+        if (g_edrNetworkChangeCallback)
+        {
+            g_edrNetworkChangeCallback(CA_INTERFACE_UP);
+        }
+    }
+    else if (BT_ADAPTER_DISABLED == adapterState)
+    {
+        // Notity to upper layer
+        if (g_edrNetworkChangeCallback)
+        {
+            g_edrNetworkChangeCallback(CA_INTERFACE_DOWN);
+        }
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+}
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrserver.c b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrserver.c
new file mode 100644 (file)
index 0000000..7d8be13
--- /dev/null
@@ -0,0 +1,120 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides the APIs to start and stop RFCOMM server.
+ */
+
+#include <string.h>
+#include <bluetooth.h>
+
+#include "caedrinterface.h"
+#include "caadapterutils.h"
+#include "caedrutils.h"
+#include "logger.h"
+#include "camutex.h"
+#include "cacommon.h"
+#include "caedrdevicelist.h"
+
+static int32_t g_maxPendingConnections = 10;
+
+CAResult_t CAEDRServerStart(const char *serviceUUID, int *serverFD, ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "Service UUID is null");
+    VERIFY_NON_NULL(serverFD, EDR_ADAPTER_TAG, "Server fd holder is null");
+
+    if (!serviceUUID[0])
+    {
+        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: Empty service uuid!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    bool isRunning = false;
+    bt_error_e err = bt_adapter_is_service_used(serviceUUID, &isRunning);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
+                  "Unable to find whether service is already running or not! error num[%x]", err);
+        return CA_STATUS_FAILED;
+    }
+
+    if (isRunning)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Service is already running with this UUID!");
+        return CA_SERVER_STARTED_ALREADY;
+    }
+
+    int socketFD = 0;
+    // Registers a rfcomm socket with a specific service_uuid.
+    err = bt_socket_create_rfcomm(serviceUUID, &socketFD);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to create rfcomm socket!, error num [%x]", err);
+        return CA_STATUS_FAILED;
+    }
+
+    // Start listening and accepting
+    err = bt_socket_listen_and_accept_rfcomm(socketFD, g_maxPendingConnections);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed in listen rfcomm socket!, error num [%x]", err);
+
+        bt_socket_destroy_rfcomm(socketFD);
+        return CA_STATUS_FAILED;
+    }
+
+    *serverFD = socketFD;
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAEDRServerStop(int serverFD)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    bt_error_e err = bt_socket_destroy_rfcomm(serverFD);
+    if (BT_ERROR_NONE != err)
+    {
+        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed close server socket!, error num [%x]", err);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAEDRServerTerminate()
+{
+    // This is just a dummy
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "CAEDRServerTerminate");
+}
+
+CAResult_t CAEDRManagerReadData(void)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return CA_NOT_SUPPORTED;
+}
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.c b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.c
new file mode 100644 (file)
index 0000000..70073ae
--- /dev/null
@@ -0,0 +1,58 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides helper functions for EDR adapter.
+ */
+
+#include "caedrutils.h"
+
+#include <bluetooth.h>
+
+#include "logger.h"
+
+bool CAEDRIsServiceSupported(const char **serviceUUID, int32_t serviceCount,
+                                 const char *matchService)
+{
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+    if (NULL == serviceUUID || 0 == serviceCount || NULL == matchService)
+    {
+        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Invalid input");
+        return false;
+    }
+
+    for (int i = 0; i < serviceCount; i++)
+    {
+        if (!strcasecmp(serviceUUID[i], matchService))
+        {
+            OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Service found !");
+            return true;
+        }
+    }
+
+    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
+    return false;
+}
+
+
+
diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.h b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrutils.h
new file mode 100644 (file)
index 0000000..466ad63
--- /dev/null
@@ -0,0 +1,68 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides helper functions for EDR adapter.
+ */
+
+#ifndef CA_EDR_UTILS_H_
+#define CA_EDR_UTILS_H_
+
+#include <stdbool.h>
+#include <string.h>
+
+#include "cacommon.h"
+#include "oic_malloc.h"
+
+/**
+ * @var EDR_ADAPTER_TAG
+ * @brief Logging tag for module name.
+ */
+#ifndef EDR_ADAPTER_TAG
+#define EDR_ADAPTER_TAG "CA_EDR_ADAPTER"
+#endif //EDR_ADAPTER_TAG
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief  Checks if the specified list of service UUIDs contains OIC service UUID.
+ *
+ * @param  serviceUUID  [IN] Array of service UUIDs
+ * @param  serviceCount [IN] Size of the service UUIDs array.
+ * @param  matchService [IN] Service UUID to be checked in the given array of service UUIDs
+ *
+ * @return  true if match service UUID found otherwise false.
+ *
+ */
+bool CAEDRIsServiceSupported(const char **serviceUUID, int32_t serviceCount,
+                            const char *matchService);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_EDR_UTILS_H_ */
+
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/SConscript b/resource/csdk/connectivity/src/bt_le_adapter/SConscript
new file mode 100644 (file)
index 0000000..62707b7
--- /dev/null
@@ -0,0 +1,53 @@
+#######################################################
+#      Building BLE adapter
+#######################################################
+
+Import('env')
+
+print"Reading ble adapter script"
+
+target_os = env.get('TARGET_OS')
+
+if target_os == 'tizen':
+    env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
+
+src_dir = './bt_le_adapter/'
+
+#Source files to build common for all platforms
+if target_os != 'arduino':
+       env.AppendUnique(CA_SRC=[src_dir+'caleadapter.c'])
+else:
+       env.AppendUnique(CA_SRC=[src_dir+'caleadapter_singlethread.c'])
+
+#Source files to build in Linux platform
+if target_os == 'linux':
+       env.AppendUnique(CA_SRC=[src_dir+'linux/caleadapter.c',
+                       ])
+
+#Source files to build in Tizen platform
+if target_os == 'tizen':
+       env.PrependUnique(CPPPATH = [src_dir + 'tizen'])
+       env.PrependUnique(CFLAGS = ['-I'+ './con/lib/tizen/ble/inc'])
+       env.PrependUnique(CFLAGS = ['-I'+ './con/lib/tizen/ble/inc/mobile'])
+       env.AppendUnique(CA_SRC=[src_dir+'tizen/cableclient.c',
+                       src_dir+'tizen/cableserver.c',
+                       src_dir+'tizen/cableutil.c',
+                       src_dir+'tizen/cablenwmonitor.c',
+                       ])
+
+#Source files to build in Arduino platform
+if target_os == 'arduino':
+       env.PrependUnique(CPPPATH = [src_dir + 'arduino'])
+       env.AppendUnique(CA_SRC=[src_dir+'arduino/cableserver.cpp',
+                       src_dir+'arduino/cablenwmonitor.cpp',
+                       ])
+
+#Source files to build in Android platform
+if target_os == 'android':
+       env.PrependUnique(CPPPATH = [src_dir + 'android'])
+       env.AppendUnique(CA_SRC=[
+                       src_dir+'android/caleclient.c',
+                       src_dir+'android/caleserver.c',
+                       src_dir+'android/calenwmonitor.c',
+                       src_dir+'android/caleutils.c'
+                       ])
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c b/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c
new file mode 100644 (file)
index 0000000..06c1c05
--- /dev/null
@@ -0,0 +1,3770 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include <jni.h>
+#include <unistd.h>
+
+#include "caleclient.h"
+#include "caleserver.h"
+#include "caleutils.h"
+#include "caleinterface.h"
+#include "caadapterutils.h"
+
+#include "logger.h"
+#include "oic_malloc.h"
+#include "cathreadpool.h" /* for thread pool */
+#include "camutex.h"
+#include "uarraylist.h"
+#include "org_iotivity_jar_caleclientinterface.h"
+
+#define TAG PCF("CA_LE_CLIENT")
+
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char CLASSPATH_BT_ADAPTER[] = "android/bluetooth/BluetoothAdapter";
+static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
+static const char CLASSPATH_BT_GATT[] = "android/bluetooth/BluetoothGatt";
+
+JavaVM *g_jvm;
+static u_arraylist_t *g_deviceList = NULL; // device list to have same UUID
+static u_arraylist_t *g_gattObjectList = NULL;
+static u_arraylist_t *g_deviceStateList = NULL;
+
+static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+static jobject g_leScanCallback = NULL;
+static jobject g_leGattCallback = NULL;
+static jobject g_context = NULL;
+static jobjectArray g_uuidList = NULL;
+
+// it will be prevent to start send logic when adapter has stopped.
+static bool g_isStartedLEClient = false;
+static bool g_isStartedMulticastServer = false;
+static bool g_isStartedScan = false;
+
+static jbyteArray g_sendBuffer = NULL;
+static uint32_t g_targetCnt = 0;
+static uint32_t g_currentSentCnt = 0;
+static bool g_isFinishedSendData = false;
+static ca_mutex g_SendFinishMutex = false;
+static ca_mutex g_threadMutex = NULL;
+static ca_cond g_threadCond = NULL;
+
+static bool g_isRequestedSend = false;
+static bool g_isReceivedWriteCB = false;
+static ca_mutex g_writeCharacteristicCBMutex = false;
+static ca_mutex g_theSendRequestMutex = false;
+static ca_mutex g_threadSendCBMutex = NULL;
+static ca_cond g_threadSendCBCond = NULL;
+
+static ca_mutex g_threadSendMutex = NULL;
+static ca_cond g_threadSendCond = NULL;
+
+static ca_mutex g_bleReqRespClientCbMutex = NULL;
+static ca_mutex g_bleServerBDAddressMutex = NULL;
+
+static ca_mutex g_deviceListMutex = NULL;
+static ca_mutex g_gattObjectMutex = NULL;
+static ca_mutex g_deviceStateListMutex = NULL;
+
+static CABLEClientDataReceivedCallback g_CABLEClientDataReceivedCallback = NULL;
+
+//getting jvm
+void CALEClientJniInit()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientJniInit");
+    g_jvm = (JavaVM*) CANativeJNIGetJavaVM();
+}
+
+void CALEClientJNISetContext()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientJNISetContext");
+    g_context = (jobject) CANativeJNIGetContext();
+}
+
+CAResult_t CALECreateJniInterfaceObject()
+{
+    OIC_LOG(DEBUG, TAG, "CALECreateJniInterfaceObject");
+
+    if (!g_context)
+    {
+        OIC_LOG(ERROR, TAG, "g_context is null");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    jclass jni_LEInterface = (*env)->FindClass(env, "org/iotivity/jar/caleclientinterface");
+    if (!jni_LEInterface)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get caleclientinterface class");
+        goto error_exit;
+    }
+
+    jmethodID LeInterfaceConstructorMethod = (*env)->GetMethodID(env, jni_LEInterface, "<init>",
+                                                                 "(Landroid/content/Context;)V");
+    if (!LeInterfaceConstructorMethod)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get caleclientinterface constructor method");
+        goto error_exit;
+    }
+
+    (*env)->NewObject(env, jni_LEInterface, LeInterfaceConstructorMethod, g_context);
+    OIC_LOG(DEBUG, TAG, "Create instance for caleclientinterface");
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+
+error_exit:
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CALEClientInitialize(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientInitialize");
+
+    CALEClientJniInit();
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALECheckPlatformVersion(env, 18);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "it is not supported");
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+
+        return ret;
+    }
+
+    g_threadPoolHandle = handle;
+
+    ret = CALEClientInitGattMutexVaraibles();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientInitGattMutexVaraibles has failed!");
+        CALEClientTerminateGattMutexVariables();
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+
+        return ret;
+    }
+
+    // init mutex for send logic
+    g_threadCond = ca_cond_new();
+    g_threadSendCond = ca_cond_new();
+    g_threadSendCBCond = ca_cond_new();
+
+    CALEClientCreateDeviceList();
+    CALEClientJNISetContext();
+
+    ret = CALEClientCreateUUIDList();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientCreateUUIDList has failed");
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+
+        return ret;
+    }
+
+    ret = CALECreateJniInterfaceObject(); /* create java caleinterface instance*/
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALECreateJniInterfaceObject has failed");
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+
+        return ret;
+    }
+    g_isStartedLEClient = true;
+
+    return CA_STATUS_OK;
+}
+
+void CALEClientTerminate()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientTerminate");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    if (g_leScanCallback)
+    {
+        (*env)->DeleteGlobalRef(env, g_leScanCallback);
+    }
+
+    if (g_leGattCallback)
+    {
+        (*env)->DeleteGlobalRef(env, g_leGattCallback);
+    }
+
+    if (g_sendBuffer)
+    {
+        (*env)->DeleteGlobalRef(env, g_sendBuffer);
+    }
+
+    if (g_uuidList)
+    {
+        (*env)->DeleteGlobalRef(env, g_uuidList);
+    }
+
+    CAResult_t ret = CALEClientRemoveAllDeviceState();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientRemoveAllDeviceState has failed");
+    }
+
+    ret = CALEClientRemoveAllScanDevices(env);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientRemoveAllScanDevices has failed");
+    }
+
+    ret = CALEClientRemoveAllGattObjs(env);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientRemoveAllGattObjs has failed");
+    }
+
+    g_isStartedMulticastServer = false;
+    g_isStartedScan = false;
+    CALEClientSetSendFinishFlag(false);
+    CALEClientSetTheSendRequestFlag(false);
+    CALEClientSetWriteCharacteristicCBFlag(false);
+
+    CALEClientTerminateGattMutexVariables();
+
+    ca_cond_free(g_threadCond);
+    ca_cond_free(g_threadSendCond);
+    ca_cond_free(g_threadSendCBCond);
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+}
+
+void CALEClientSendFinish(JNIEnv *env, jobject gatt)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientSendFinish");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+
+    if (gatt)
+    {
+        CAResult_t res = CALEClientDisconnect(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientDisconnect has failed");
+        }
+    }
+    CALEClientUpdateSendCnt(env);
+}
+
+CAResult_t CALEClientSendUnicastMessage(const char* address, const char* data,
+                                        const uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALEClientSendUnicastMessage(%s, %s)", address, data);
+    VERIFY_NON_NULL(address, TAG, "address is null");
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    return CALEClientSendUnicastMessageImpl(address, data, dataLen);
+}
+
+CAResult_t CALEClientSendMulticastMessage(const char* data, const uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALEClientSendMulticastMessage(%s)", data);
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALEClientSendMulticastMessageImpl(env, data, dataLen);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientSendMulticastMessageImpl has failed");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return ret;
+}
+
+CAResult_t CALEClientStartUnicastServer(const char* address)
+{
+    OIC_LOG_V(DEBUG, TAG, "it is not needed in this platform (%s)", address);
+
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CALEClientStartMulticastServer()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientStartMulticastServer");
+
+    if (g_isStartedMulticastServer)
+    {
+        OIC_LOG(ERROR, TAG, "server is already started..it will be skipped");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    g_isStartedMulticastServer = true;
+    CAResult_t ret = CALEClientStartScan();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return ret;
+}
+
+void CALEClientStopUnicastServer()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientStopUnicastServer");
+}
+
+void CALEClientStopMulticastServer()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientStopMulticastServer");
+    g_isStartedMulticastServer = false;
+    CAResult_t res = CALEClientStopScan();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        return;
+    }
+}
+
+void CALEClientSetCallback(CAPacketReceiveCallback callback)
+{
+    g_packetReceiveCallback = callback;
+}
+
+CAResult_t CALEClientGetInterfaceInfo(char **address)
+{
+    OIC_LOG(INFO, TAG, "CALEClientGetInterfaceInfo is not supported");
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const char* data,
+                                      const uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALEClientSendUnicastMessageImpl, address: %s, data: %s", address,
+              data);
+    VERIFY_NON_NULL(address, TAG, "address is null");
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    ca_mutex_lock(g_threadSendMutex);
+
+    CAResult_t ret = CA_STATUS_OK;
+    if (g_context && g_deviceList)
+    {
+        uint32_t length = u_arraylist_length(g_deviceList);
+        for (uint32_t index = 0; index < length; index++)
+        {
+            jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+            if (!jarrayObj)
+            {
+                OIC_LOG(ERROR, TAG, "jarrayObj is null");
+                goto error_exit;
+            }
+
+            jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
+            if (!jni_setAddress)
+            {
+                OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+                goto error_exit;
+            }
+
+            const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+            if (!setAddress)
+            {
+                OIC_LOG(ERROR, TAG, "setAddress is null");
+                goto error_exit;
+            }
+
+            OIC_LOG_V(DEBUG, TAG, "remote device address is %s", setAddress);
+
+            if (!strcmp(setAddress, address))
+            {
+                (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+
+                // connect to gatt server
+                ret = CALEClientStopScan();
+                if (CA_STATUS_OK != ret)
+                {
+                    OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
+                    goto error_exit;
+                }
+
+                if (g_sendBuffer)
+                {
+                    (*env)->DeleteGlobalRef(env, g_sendBuffer);
+                }
+                jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
+                (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*) data);
+                g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
+
+                ret = CALEClientSendData(env, jarrayObj);
+                if (CA_STATUS_OK != ret)
+                {
+                    OIC_LOG(ERROR, TAG, "CALEClientSendData in unicast is failed");
+                    goto error_exit;
+                }
+                else
+                {
+                    CALEClientSetTheSendRequestFlag(true);
+                    ca_cond_signal(g_threadSendCBCond);
+
+                    if (!g_isReceivedWriteCB)
+                    {
+                        OIC_LOG(INFO, TAG, "wait..(unicast)");
+                        ca_cond_wait(g_threadSendCond, g_threadSendMutex);
+                    }
+                    else
+                    {
+                        CALEClientSetWriteCharacteristicCBFlag(false);
+                    }
+                }
+
+                OIC_LOG(INFO, TAG, "wake up");
+                break;
+            }
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+        }
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    ret = CALECheckSendState(address);
+    if(CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "send has failed");
+        goto error_exit;
+    }
+
+    // start LE Scan again
+    ret = CALEClientStartScan();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        ca_mutex_unlock(g_threadSendMutex);
+        return res;
+    }
+
+    ca_mutex_unlock(g_threadSendMutex);
+    OIC_LOG(INFO, TAG, "unicast - send success");
+    return CA_STATUS_OK;
+
+    // error label.
+error_exit:
+
+    // start LE Scan again
+    ret = CALEClientStartScan();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        ca_mutex_unlock(g_threadSendMutex);
+        return res;
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+    ca_mutex_unlock(g_threadSendMutex);
+    return CA_SEND_FAILED;
+}
+
+CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const char* data,
+                                              const uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, send to, data: %s, %d", data, dataLen);
+    VERIFY_NON_NULL(data, TAG, "data is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    if (!g_deviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceList is null");
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_threadSendMutex);
+
+    CALEClientSetSendFinishFlag(false);
+
+    OIC_LOG(DEBUG, TAG, "set byteArray for data");
+    if (g_sendBuffer)
+    {
+        (*env)->DeleteGlobalRef(env, g_sendBuffer);
+    }
+    jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
+    (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*) data);
+    g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
+
+    // connect to gatt server
+    CAResult_t res = CALEClientStopScan();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
+        ca_mutex_unlock(g_threadSendMutex);
+        return res;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceList);
+    g_targetCnt = length;
+    if (0 == length)
+    {
+        goto error_exit;
+    }
+
+    uint32_t index = 0;
+    while (index < length)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            continue;
+        }
+
+        res = CALEClientSendData(env, jarrayObj);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "BT device[%d] - send has failed");
+        }
+        else
+        {
+            CALEClientSetTheSendRequestFlag(true);
+            ca_cond_signal(g_threadSendCBCond);
+
+            if (!g_isReceivedWriteCB)
+            {
+                OIC_LOG(INFO, TAG, "wait..(multicast)");
+                ca_cond_wait(g_threadSendCond, g_threadSendMutex);
+            }
+            else
+            {
+                CALEClientSetWriteCharacteristicCBFlag(false);
+            }
+        }
+
+        jstring jni_address = CALEGetAddressFromBTDevice(env, jarrayObj);
+        if (!jni_address)
+        {
+            OIC_LOG(ERROR, TAG, "CALEGetAddressFromBTDevice has failed");
+            goto error_exit;
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (!address)
+        {
+            OIC_LOG(ERROR, TAG, "address is not available");
+            goto error_exit;
+        }
+
+        res = CALECheckSendState(address);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "send has failed");
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            goto error_exit;
+        }
+
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
+
+        index++;
+    }
+
+    OIC_LOG(DEBUG, TAG, "connection routine is finished");
+
+    // wait for finish to send data through "CALeGattServicesDiscoveredCallback"
+    if (!g_isFinishedSendData)
+    {
+        ca_mutex_lock(g_threadMutex);
+        ca_cond_wait(g_threadCond, g_threadMutex);
+        OIC_LOG(DEBUG, TAG, "the data was sent for All devices");
+        ca_mutex_unlock(g_threadMutex);
+    }
+
+    // start LE Scan again
+    res = CALEClientStartScan();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        ca_mutex_unlock(g_threadSendMutex);
+        return res;
+    }
+
+    ca_mutex_unlock(g_threadSendMutex);
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientSendMulticastMessageImpl");
+    return CA_STATUS_OK;
+
+error_exit:
+    res = CALEClientStartScan();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        ca_mutex_unlock(g_threadSendMutex);
+        return res;
+    }
+
+    ca_mutex_unlock(g_threadSendMutex);
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientSendMulticastMessageImpl");
+    return CA_SEND_FAILED;
+}
+
+CAResult_t CALECheckSendState(const char* address)
+{
+    VERIFY_NON_NULL(address, TAG, "address is null");
+
+    ca_mutex_lock(g_deviceStateListMutex);
+    CALEState_t* state = CALEClientGetStateInfo(address);
+    if (NULL == state)
+    {
+        OIC_LOG(ERROR, TAG, "state is null");
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return CA_SEND_FAILED;
+    }
+
+    if (STATE_SEND_SUCCESS != state->sendState)
+    {
+        OIC_LOG(ERROR, TAG, "sendstate is not STATE_SEND_SUCCESS");
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return CA_SEND_FAILED;
+    }
+    ca_mutex_unlock(g_deviceStateListMutex);
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientSendData(JNIEnv *env, jobject device)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientSendData");
+    VERIFY_NON_NULL(device, TAG, "device is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    jstring jni_address = CALEGetAddressFromBTDevice(env, device);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "CALEGetAddressFromBTDevice has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is not available");
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_deviceStateListMutex);
+    CALEState_t* state = CALEClientGetStateInfo(address);
+    ca_mutex_unlock(g_deviceStateListMutex);
+    if (!state)
+    {
+        OIC_LOG(DEBUG, TAG, "state is empty..start to connect LE");
+        CAResult_t ret = CALEClientConnect(env, device, JNI_FALSE, g_leGattCallback);
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+            return ret;
+        }
+    }
+    else
+    {
+        if (STATE_CONNECTED == state->connectedState)
+        {
+            OIC_LOG(INFO, TAG, "GATT has already connected");
+            jobject gatt = CALEClientGetGattObjInList(env, address);
+            if (!gatt)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientGetGattObjInList has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                return CA_STATUS_FAILED;
+            }
+
+            CAResult_t ret = CALEClientWriteCharacteristic(env, gatt);
+            if (CA_STATUS_OK != ret)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                return ret;
+            }
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG, "start to connect LE");
+            CAResult_t ret = CALEClientConnect(env, device, JNI_FALSE, g_leGattCallback);
+            if (CA_STATUS_OK != ret)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                return ret;
+            }
+        }
+    }
+
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    return CA_STATUS_OK;
+}
+
+jstring CALEClientGetAddressFromGattObj(JNIEnv *env, jobject gatt)
+{
+    VERIFY_NON_NULL_RET(gatt, TAG, "gatt is null", NULL);
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    jclass jni_cid_gattdevice_list = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_gattdevice_list)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_gattdevice_list is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getDevice = (*env)->GetMethodID(env, jni_cid_gattdevice_list, "getDevice",
+                                                      "()Landroid/bluetooth/BluetoothDevice;");
+    if (!jni_mid_getDevice)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDevice is null");
+        return NULL;
+    }
+
+    jobject jni_obj_device = (*env)->CallObjectMethod(env, gatt, jni_mid_getDevice);
+    if (!jni_obj_device)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_device is null");
+        return NULL;
+    }
+
+    jstring jni_address = CALEGetAddressFromBTDevice(env, jni_obj_device);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "jni_address is null");
+        return NULL;
+    }
+
+    return jni_address;
+}
+
+/**
+ * BLE layer
+ */
+CAResult_t CALEClientGattClose(JNIEnv *env, jobject bluetoothGatt)
+{
+    // GATT CLOSE
+    OIC_LOG(DEBUG, TAG, "Gatt Close");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    // get BluetoothGatt class
+    OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_closeGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "close", "()V");
+    if (!jni_mid_closeGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_closeGatt is null");
+        return CA_STATUS_OK;
+    }
+
+    // call disconnect gatt method
+    OIC_LOG(DEBUG, TAG, "request to close GATT");
+    (*env)->CallVoidMethod(env, bluetoothGatt, jni_mid_closeGatt);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "closeGATT has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientStartScan()
+{
+    if (!g_isStartedMulticastServer)
+    {
+        OIC_LOG(ERROR, TAG, "server is not started yet..scan will be passed");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_isStartedLEClient)
+    {
+        OIC_LOG(ERROR, TAG, "LE client is not started");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    if (g_isStartedScan)
+    {
+        OIC_LOG(INFO, TAG, "scanning is already started");
+        return CA_STATUS_OK;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CALEClientStartScan");
+
+    CAResult_t ret = CA_STATUS_OK;
+    // scan gatt server with UUID
+    if (g_leScanCallback && g_uuidList)
+    {
+#ifndef FULL_SCAN
+        ret = CALEClientStartScanWithUUIDImpl(env, g_uuidList, g_leScanCallback);
+        if(CA_STATUS_OK != ret)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientStartScanWithUUIDImpl has failed");
+        }
+#else
+        ret = CALEClientStartScanImpl(env, g_leScanCallback);
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientStartScanImpl has failed");
+        }
+#endif
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return ret;
+}
+
+CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback)
+{
+    VERIFY_NON_NULL(callback, TAG, "callback is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    // get default bt adapter class
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get remote bt adapter method
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get start le scan method
+    jmethodID jni_mid_startLeScan = (*env)->GetMethodID(env, jni_cid_BTAdapter, "startLeScan",
+                                                        "(Landroid/bluetooth/BluetoothAdapter$"
+                                                        "LeScanCallback;)Z");
+    if (!jni_mid_startLeScan)
+    {
+        OIC_LOG(ERROR, TAG, "startLeScan: jni_mid_startLeScan is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // gat bt adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call start le scan method
+    jboolean jni_obj_startLeScan = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter,
+                                                             jni_mid_startLeScan, callback);
+    if (!jni_obj_startLeScan)
+    {
+        OIC_LOG(ERROR, TAG, "startLeScan is failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "startLeScan is started");
+        g_isStartedScan = true;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobject callback)
+{
+    VERIFY_NON_NULL(callback, TAG, "callback is null");
+    VERIFY_NON_NULL(uuids, TAG, "uuids is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get remote bt adapter method
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get start le scan method
+    jmethodID jni_mid_startLeScan = (*env)->GetMethodID(env, jni_cid_BTAdapter, "startLeScan",
+                                                        "([Ljava/util/UUID;Landroid/bluetooth/"
+                                                        "BluetoothAdapter$LeScanCallback;)Z");
+    if (!jni_mid_startLeScan)
+    {
+        OIC_LOG(ERROR, TAG, "startLeScan: jni_mid_startLeScan is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get bt adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call start le scan method
+    jboolean jni_obj_startLeScan = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter,
+                                                             jni_mid_startLeScan, uuids, callback);
+    if (!jni_obj_startLeScan)
+    {
+        OIC_LOG(ERROR, TAG, "startLeScan With UUID is failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "startLeScan With UUID is started");
+        g_isStartedScan = true;
+    }
+
+    return CA_STATUS_OK;
+}
+
+jobject CALEClientGetUUIDObject(JNIEnv *env, const char* uuid)
+{
+    VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL);
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    // setting UUID
+    jclass jni_cid_uuid = (*env)->FindClass(env, CLASSPATH_BT_UUID);
+    if (!jni_cid_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_uuid is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_uuid, "fromString",
+                                                             "(Ljava/lang/String;)"
+                                                             "Ljava/util/UUID;");
+    if (!jni_mid_fromString)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_fromString is null");
+        return NULL;
+    }
+
+    jstring jni_uuid = (*env)->NewStringUTF(env, uuid);
+    jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString,
+                                                          jni_uuid);
+    if (!jni_obj_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_uuid is null");
+        return NULL;
+    }
+
+    return jni_obj_uuid;
+}
+
+CAResult_t CALEClientStopScan()
+{
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_isStartedScan)
+    {
+        OIC_LOG(INFO, TAG, "scanning is already stopped");
+        return CA_STATUS_OK;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALEClientStopScanImpl(env, g_leScanCallback);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStopScanImpl has failed");
+    }
+    else
+    {
+        g_isStartedScan = false;
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return ret;
+}
+
+CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientStopScanImpl");
+    VERIFY_NON_NULL(callback, TAG, "callback is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    // get default bt adapter class
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get remote bt adapter method
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get start le scan method
+    jmethodID jni_mid_stopLeScan = (*env)->GetMethodID(env, jni_cid_BTAdapter, "stopLeScan",
+                                                       "(Landroid/bluetooth/"
+                                                       "BluetoothAdapter$LeScanCallback;)V");
+    if (!jni_mid_stopLeScan)
+    {
+        OIC_LOG(ERROR, TAG, "stopLeScan: jni_mid_stopLeScan is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // gat bt adapter object
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CALL API - request to stop LE Scan");
+    // call start le scan method
+    (*env)->CallVoidMethod(env, jni_obj_BTAdapter, jni_mid_stopLeScan, callback);
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "stopLeScan has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect,
+                             jobject callback)
+{
+    OIC_LOG(DEBUG, TAG, "GATT CONNECT");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothDevice, TAG, "bluetoothDevice is null");
+    VERIFY_NON_NULL(callback, TAG, "callback is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jstring jni_address = CALEGetAddressFromBTDevice(env, bluetoothDevice);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "bleConnect: CALEGetAddressFromBTDevice is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get BluetoothDevice class
+    OIC_LOG(DEBUG, TAG, "get BluetoothDevice class");
+    jclass jni_cid_BluetoothDevice = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
+    if (!jni_cid_BluetoothDevice)
+    {
+        OIC_LOG(ERROR, TAG, "bleConnect: jni_cid_BluetoothDevice is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // get connectGatt method
+    OIC_LOG(DEBUG, TAG, "get connectGatt method");
+    jmethodID jni_mid_connectGatt = (*env)->GetMethodID(env, jni_cid_BluetoothDevice, "connectGatt",
+                                                        "(Landroid/content/Context;ZLandroid/"
+                                                        "bluetooth/BluetoothGattCallback;)"
+                                                        "Landroid/bluetooth/BluetoothGatt;");
+    if (!jni_mid_connectGatt)
+    {
+        OIC_LOG(ERROR, TAG, "bleConnect: jni_mid_connectGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Call object method - connectGatt");
+    jobject jni_obj_connectGatt = (*env)->CallObjectMethod(env, bluetoothDevice,
+                                                           jni_mid_connectGatt,
+                                                           NULL,
+                                                           autoconnect, callback);
+    if (!jni_obj_connectGatt)
+    {
+        OIC_LOG(ERROR, TAG, "CALL API - connectGatt was failed..it will be removed");
+        CALEClientRemoveDeviceInScanDeviceList(env, jni_address);
+        CALEClientUpdateSendCnt(env);
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "le connecting..please wait..");
+    }
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientDisconnect(JNIEnv *env, jobject bluetoothGatt)
+{
+    OIC_LOG(DEBUG, TAG, "GATT DISCONNECT");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    // get BluetoothGatt class
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "get gatt disconnect method");
+    jmethodID jni_mid_disconnectGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
+                                                           "disconnect", "()V");
+    if (!jni_mid_disconnectGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_disconnectGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call disconnect gatt method
+    (*env)->CallVoidMethod(env, bluetoothGatt, jni_mid_disconnectGatt);
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "disconnect has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "disconnecting Gatt...");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientDisconnectAll(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientDisconnectAll");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    if (!g_gattObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            continue;
+        }
+        CAResult_t res = CALEClientDisconnect(env, jarrayObj);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientDisconnect has failed");
+            continue;
+        }
+    }
+
+    OICFree(g_gattObjectList);
+    g_gattObjectList = NULL;
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientDiscoverServices(JNIEnv *env, jobject bluetoothGatt)
+{
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    // get BluetoothGatt class
+    OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "discovery gatt services method");
+    jmethodID jni_mid_discoverServices = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
+                                                             "discoverServices", "()Z");
+    if (!jni_mid_discoverServices)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_discoverServices is null");
+        return CA_STATUS_FAILED;
+    }
+    // call disconnect gatt method
+    OIC_LOG(DEBUG, TAG, "CALL API - request discovery gatt services");
+    jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_discoverServices);
+    if (!ret)
+    {
+        OIC_LOG(ERROR, TAG, "discoverServices has not been started");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientWriteCharacteristic(JNIEnv *env, jobject gatt)
+{
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(gatt, TAG, "gatt is null");
+
+    // send data
+    jobject jni_obj_character = CALEClientCreateGattCharacteristic(env, gatt, g_sendBuffer);
+    if (!jni_obj_character)
+    {
+        CALEClientSendFinish(env, gatt);
+        ca_cond_signal(g_threadSendCond);
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t ret = CALEClientWriteCharacteristicImpl(env, gatt, jni_obj_character);
+    if (CA_STATUS_OK != ret)
+    {
+        CALEClientSendFinish(env, gatt);
+        ca_cond_signal(g_threadSendCond);
+        return ret;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientWriteCharacteristicImpl(JNIEnv *env, jobject bluetoothGatt,
+                                           jobject gattCharacteristic)
+{
+    OIC_LOG(DEBUG, TAG, "WRITE GATT CHARACTERISTIC");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+    VERIFY_NON_NULL(gattCharacteristic, TAG, "gattCharacteristic is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_STATUS_FAILED;
+    }
+
+    // get BluetoothGatt class
+    OIC_LOG(DEBUG, TAG, "get BluetoothGatt class");
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "write characteristic method");
+    jmethodID jni_mid_writeCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
+                                                                "writeCharacteristic",
+                                                                "(Landroid/bluetooth/"
+                                                                "BluetoothGattCharacteristic;)Z");
+    if (!jni_mid_writeCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_writeCharacteristic is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call disconnect gatt method
+    OIC_LOG(DEBUG, TAG, "CALL API - request to write gatt characteristic");
+    jboolean ret = (jboolean)(*env)->CallBooleanMethod(env, bluetoothGatt,
+                                                       jni_mid_writeCharacteristic,
+                                                       gattCharacteristic);
+    if (ret)
+    {
+        OIC_LOG(DEBUG, TAG, "writeCharacteristic success");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "writeCharacteristic has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientReadCharacteristic(JNIEnv *env, jobject bluetoothGatt)
+{
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jstring jni_uuid = (*env)->NewStringUTF(env, OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
+    if (!jni_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_uuid is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_GattCharacteristic = CALEClientGetGattService(env, bluetoothGatt, jni_uuid);
+    if (!jni_obj_GattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_GattCharacteristic is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "read characteristic method");
+    jmethodID jni_mid_readCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
+                                                               "readCharacteristic",
+                                                               "(Landroid/bluetooth/"
+                                                               "BluetoothGattCharacteristic;)Z");
+    if (!jni_mid_readCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_readCharacteristic is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // call disconnect gatt method
+    OIC_LOG(DEBUG, TAG, "CALL API - request to read gatt characteristic");
+    jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_readCharacteristic,
+                                             jni_obj_GattCharacteristic);
+    if (ret)
+    {
+        OIC_LOG(DEBUG, TAG, "readCharacteristic success");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "readCharacteristic has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientSetCharacteristicNotification(JNIEnv *env, jobject bluetoothGatt,
+                                                   jobject characteristic)
+{
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+    VERIFY_NON_NULL(characteristic, TAG, "characteristic is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    // get BluetoothGatt class
+    OIC_LOG(DEBUG, TAG, "CALEClientSetCharacteristicNotification");
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // set Characteristic Notification
+    jmethodID jni_mid_setNotification = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
+                                                            "setCharacteristicNotification",
+                                                            "(Landroid/bluetooth/"
+                                                            "BluetoothGattCharacteristic;Z)Z");
+    if (!jni_mid_setNotification)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getService is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_setNotification,
+                                             characteristic, JNI_TRUE);
+    if (JNI_TRUE == ret)
+    {
+        OIC_LOG(DEBUG, TAG, "CALL API - setCharacteristicNotification success");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "CALL API - setCharacteristicNotification has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+jobject CALEClientGetGattService(JNIEnv *env, jobject bluetoothGatt, jstring characterUUID)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(bluetoothGatt, TAG, "bluetoothGatt is null", NULL);
+    VERIFY_NON_NULL_RET(characterUUID, TAG, "characterUUID is null", NULL);
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return NULL;
+    }
+
+    // get BluetoothGatt class
+    OIC_LOG(DEBUG, TAG, "CALEClientGetGattService");
+    jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+    if (!jni_cid_BluetoothGatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGatt is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getService = (*env)->GetMethodID(
+            env, jni_cid_BluetoothGatt, "getService",
+            "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattService;");
+    if (!jni_mid_getService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getService is null");
+        return NULL;
+    }
+
+    jobject jni_obj_service_uuid = CALEClientGetUUIDObject(env, OIC_GATT_SERVICE_UUID);
+    if (!jni_obj_service_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_service_uuid is null");
+        return NULL;
+    }
+
+    // get bluetooth gatt service
+    OIC_LOG(DEBUG, TAG, "request to get service");
+    jobject jni_obj_gattService = (*env)->CallObjectMethod(env, bluetoothGatt, jni_mid_getService,
+                                                           jni_obj_service_uuid);
+    if (!jni_obj_gattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_gattService is null");
+        return NULL;
+    }
+
+    // get bluetooth gatt service class
+    jclass jni_cid_BluetoothGattService = (*env)->FindClass(
+            env, "android/bluetooth/BluetoothGattService");
+    if (!jni_cid_BluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BluetoothGattService is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "get gatt getCharacteristic method");
+    jmethodID jni_mid_getCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGattService,
+                                                              "getCharacteristic",
+                                                              "(Ljava/util/UUID;)"
+                                                              "Landroid/bluetooth/"
+                                                              "BluetoothGattCharacteristic;");
+    if (!jni_mid_getCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getCharacteristic is null");
+        return NULL;
+    }
+
+    const char* uuid = (*env)->GetStringUTFChars(env, characterUUID, NULL);
+    if (!uuid)
+    {
+        OIC_LOG(ERROR, TAG, "uuid is null");
+        return NULL;
+    }
+
+    jobject jni_obj_tx_uuid = CALEClientGetUUIDObject(env, uuid);
+    if (!jni_obj_tx_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_tx_uuid is null");
+        (*env)->ReleaseStringUTFChars(env, characterUUID, uuid);
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "request to get Characteristic");
+    jobject jni_obj_GattCharacteristic = (*env)->CallObjectMethod(env, jni_obj_gattService,
+                                                                  jni_mid_getCharacteristic,
+                                                                  jni_obj_tx_uuid);
+
+    (*env)->ReleaseStringUTFChars(env, characterUUID, uuid);
+    return jni_obj_GattCharacteristic;
+}
+
+jobject CALEClientCreateGattCharacteristic(JNIEnv *env, jobject bluetoothGatt, jbyteArray data)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientCreateGattCharacteristic");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(bluetoothGatt, TAG, "bluetoothGatt is null", NULL);
+    VERIFY_NON_NULL_RET(data, TAG, "data is null", NULL);
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return NULL;
+    }
+
+    jstring jni_uuid = (*env)->NewStringUTF(env, OIC_GATT_CHARACTERISTIC_REQUEST_UUID);
+    if (!jni_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_uuid is null");
+        return NULL;
+    }
+
+    jobject jni_obj_GattCharacteristic = CALEClientGetGattService(env, bluetoothGatt, jni_uuid);
+    if (!jni_obj_GattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_GattCharacteristic is null");
+        return NULL;
+    }
+
+    jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(env, "android/bluetooth"
+                                                            "/BluetoothGattCharacteristic");
+    if (!jni_cid_BTGattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTGattCharacteristic is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "set value in Characteristic");
+    jmethodID jni_mid_setValue = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic, "setValue",
+                                                     "([B)Z");
+    if (!jni_mid_setValue)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setValue is null");
+        return NULL;
+    }
+
+    jboolean ret = (*env)->CallBooleanMethod(env, jni_obj_GattCharacteristic, jni_mid_setValue,
+                                             data);
+    if (JNI_TRUE == ret)
+    {
+        OIC_LOG(DEBUG, TAG, "the locally stored value has been set");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "the locally stored value hasn't been set");
+        return NULL;
+    }
+
+    // set Write Type
+    jmethodID jni_mid_setWriteType = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic,
+                                                         "setWriteType", "(I)V");
+    if (!jni_mid_setWriteType)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setWriteType is null");
+        return NULL;
+    }
+
+    jfieldID jni_fid_no_response = (*env)->GetStaticFieldID(env, jni_cid_BTGattCharacteristic,
+                                                            "WRITE_TYPE_NO_RESPONSE", "I");
+    if (!jni_fid_no_response)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_no_response is not available");
+        return NULL;
+    }
+
+    jint jni_int_val = (*env)->GetStaticIntField(env, jni_cid_BTGattCharacteristic,
+                                                 jni_fid_no_response);
+
+    (*env)->CallVoidMethod(env, jni_obj_GattCharacteristic, jni_mid_setWriteType, jni_int_val);
+
+    return jni_obj_GattCharacteristic;
+}
+
+jbyteArray CALEClientGetValueFromCharacteristic(JNIEnv *env, jobject characteristic)
+{
+    VERIFY_NON_NULL_RET(characteristic, TAG, "characteristic is null", NULL);
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return NULL;
+    }
+
+    jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
+                                                            "BluetoothGattCharacteristic");
+    if (!jni_cid_BTGattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTGattCharacteristic is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "get value in Characteristic");
+    jmethodID jni_mid_getValue = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic, "getValue",
+                                                     "()[B");
+    if (!jni_mid_getValue)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getValue is null");
+        return NULL;
+    }
+
+    jbyteArray jni_obj_data_array = (*env)->CallObjectMethod(env, characteristic,
+                                                             jni_mid_getValue);
+    return jni_obj_data_array;
+}
+
+CAResult_t CALEClientCreateUUIDList()
+{
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    // create new object array
+    jclass jni_cid_uuid_list = (*env)->FindClass(env, CLASSPATH_BT_UUID);
+    if (!jni_cid_uuid_list)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_uuid_list is null");
+        goto error_exit;
+    }
+
+    jobjectArray jni_obj_uuid_list = (jobjectArray)(*env)->NewObjectArray(env, 1,
+                                                                          jni_cid_uuid_list, NULL);
+    if (!jni_obj_uuid_list)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_uuid_list is null");
+        goto error_exit;
+    }
+
+    // make uuid list
+    jobject jni_obj_uuid = CALEClientGetUUIDObject(env, OIC_GATT_SERVICE_UUID);
+    if (!jni_obj_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_uuid is null");
+        goto error_exit;
+    }
+    (*env)->SetObjectArrayElement(env, jni_obj_uuid_list, 0, jni_obj_uuid);
+
+    g_uuidList = (jobjectArray)(*env)->NewGlobalRef(env, jni_obj_uuid_list);
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+
+    // error label.
+error_exit:
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CALEClientSetUUIDToDescriptor(JNIEnv *env, jobject bluetoothGatt,
+                                         jobject characteristic)
+{
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGatt, TAG, "bluetoothGatt is null");
+    VERIFY_NON_NULL(characteristic, TAG, "characteristic is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CALEClientSetUUIDToDescriptor");
+    jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
+                                                            "BluetoothGattCharacteristic");
+    if (!jni_cid_BTGattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTGattCharacteristic is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "set value in Characteristic");
+    jmethodID jni_mid_getDescriptor = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic,
+                                                          "getDescriptor",
+                                                          "(Ljava/util/UUID;)Landroid/bluetooth/"
+                                                          "BluetoothGattDescriptor;");
+    if (!jni_mid_getDescriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDescriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_cc_uuid = CALEClientGetUUIDObject(env, OIC_GATT_CHARACTERISTIC_CONFIG_UUID);
+    if (!jni_obj_cc_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_cc_uuid is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "request to get descriptor");
+    jobject jni_obj_descriptor = (*env)->CallObjectMethod(env, characteristic,
+                                                          jni_mid_getDescriptor, jni_obj_cc_uuid);
+    if (!jni_obj_descriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_descriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "set value in descriptor");
+    jclass jni_cid_descriptor = (*env)->FindClass(env,
+                                                  "android/bluetooth/BluetoothGattDescriptor");
+    if (!jni_cid_descriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_descriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_setValue = (*env)->GetMethodID(env, jni_cid_descriptor, "setValue", "([B)Z");
+    if (!jni_mid_setValue)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setValue is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jfieldID jni_fid_NotiValue = (*env)->GetStaticFieldID(env, jni_cid_descriptor,
+                                                          "ENABLE_NOTIFICATION_VALUE", "[B");
+    if (!jni_fid_NotiValue)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_NotiValue is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "get ENABLE_NOTIFICATION_VALUE");
+
+    jboolean jni_setvalue = (*env)->CallBooleanMethod(
+            env, jni_obj_descriptor, jni_mid_setValue,
+            (jbyteArray)(*env)->GetStaticObjectField(env, jni_cid_descriptor, jni_fid_NotiValue));
+    if (jni_setvalue)
+    {
+        OIC_LOG(DEBUG, TAG, "setValue success");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "setValue has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_gatt = (*env)->FindClass(env, "android/bluetooth/BluetoothGatt");
+    if (!jni_cid_gatt)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_gatt is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "write Descriptor in gatt object");
+    jmethodID jni_mid_writeDescriptor = (*env)->GetMethodID(env, jni_cid_gatt, "writeDescriptor",
+                                                            "(Landroid/bluetooth/"
+                                                            "BluetoothGattDescriptor;)Z");
+    if (!jni_mid_writeDescriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_writeDescriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "request to write descriptor");
+    jboolean jni_ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_writeDescriptor,
+                                                 jni_obj_descriptor);
+    if (jni_ret)
+    {
+        OIC_LOG(DEBUG, TAG, "writeDescriptor success");
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "writeDescriptor has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+void CALEClientCreateScanDeviceList(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientCreateScanDeviceList");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+
+    ca_mutex_lock(g_deviceListMutex);
+    // create new object array
+    if (g_deviceList == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "Create device list");
+
+        g_deviceList = u_arraylist_create();
+    }
+    ca_mutex_unlock(g_deviceListMutex);
+}
+
+CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientAddScanDeviceToList");
+    VERIFY_NON_NULL(device, TAG, "device is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_deviceListMutex);
+
+    if (!g_deviceList)
+    {
+        OIC_LOG(ERROR, TAG, "gdevice_list is null");
+        ca_mutex_unlock(g_deviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
+    if (!jni_remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
+        ca_mutex_unlock(g_deviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
+        ca_mutex_unlock(g_deviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    if (!CALEClientIsDeviceInScanDeviceList(env, remoteAddress))
+    {
+        jobject gdevice = (*env)->NewGlobalRef(env, device);
+        u_arraylist_add(g_deviceList, gdevice);
+        OIC_LOG(DEBUG, TAG, "Set Object to Array as Element");
+    }
+    (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+
+    ca_mutex_unlock(g_deviceListMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientAddScanDeviceToList");
+    return CA_STATUS_OK;
+}
+
+bool CALEClientIsDeviceInScanDeviceList(JNIEnv *env, const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientIsDeviceInScanDeviceList");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", true);
+
+    if (!g_deviceList)
+    {
+        OIC_LOG(DEBUG, TAG, "g_deviceList is null");
+        return true;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            return true;
+        }
+
+        jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            return true;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            return true;
+        }
+
+        if (!strcmp(remoteAddress, setAddress))
+        {
+            OIC_LOG(DEBUG, TAG, "the device is already set");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            return true;
+        }
+
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientIsDeviceInScanDeviceList");
+    OIC_LOG(DEBUG, TAG, "there are no the device in list. we can add");
+
+    return false;
+}
+
+CAResult_t CALEClientRemoveAllScanDevices(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientRemoveAllScanDevices");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_deviceListMutex);
+
+    if (!g_deviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceList is null");
+        ca_mutex_unlock(g_deviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            continue;
+        }
+        (*env)->DeleteGlobalRef(env, jarrayObj);
+    }
+
+    OICFree(g_deviceList);
+    g_deviceList = NULL;
+
+    ca_mutex_unlock(g_deviceListMutex);
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientRemoveDeviceInScanDeviceList");
+    VERIFY_NON_NULL(address, TAG, "address is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_deviceListMutex);
+
+    if (!g_deviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceList is null");
+        ca_mutex_unlock(g_deviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            ca_mutex_unlock(g_deviceListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            ca_mutex_unlock(g_deviceListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            ca_mutex_unlock(g_deviceListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* remoteAddress = (*env)->GetStringUTFChars(env, address, NULL);
+        if (!remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "remoteAddress is null");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            ca_mutex_unlock(g_deviceListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (!strcmp(setAddress, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
+            (*env)->DeleteGlobalRef(env, jarrayObj);
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
+
+            CALEClientReorderingList(index, g_deviceList);
+            ca_mutex_unlock(g_deviceListMutex);
+            return CA_STATUS_OK;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+        (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
+    }
+
+    ca_mutex_unlock(g_deviceListMutex);
+    OIC_LOG(DEBUG, TAG, "There are no object in the device list");
+
+    return CA_STATUS_OK;
+}
+
+/**
+ * Gatt Object List
+ */
+
+CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientAddGattobjToList");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(gatt, TAG, "gatt is null");
+
+    ca_mutex_lock(g_gattObjectMutex);
+
+    jstring jni_remoteAddress = CALEClientGetAddressFromGattObj(env, gatt);
+    if (!jni_remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
+        ca_mutex_unlock(g_gattObjectMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
+        ca_mutex_unlock(g_gattObjectMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    if (!CALEClientIsGattObjInList(env, remoteAddress))
+    {
+        jobject newGatt = (*env)->NewGlobalRef(env, gatt);
+        u_arraylist_add(g_gattObjectList, newGatt);
+        OIC_LOG(DEBUG, TAG, "Set GATT Object to Array as Element");
+    }
+
+    (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+    ca_mutex_unlock(g_gattObjectMutex);
+    return CA_STATUS_OK;
+}
+
+bool CALEClientIsGattObjInList(JNIEnv *env, const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientIsGattObjInList");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", true);
+
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            return true;
+        }
+
+        jstring jni_setAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            return true;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            return true;
+        }
+
+        if (!strcmp(remoteAddress, setAddress))
+        {
+            OIC_LOG(DEBUG, TAG, "the device is already set");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            return true;
+        }
+        else
+        {
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            continue;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "There are no GATT object in list. it can be added");
+    return false;
+}
+
+jobject CALEClientGetGattObjInList(JNIEnv *env, const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientGetGattObjInList");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", NULL);
+
+    ca_mutex_lock(g_gattObjectMutex);
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return NULL;
+        }
+
+        jstring jni_setAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return NULL;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return NULL;
+        }
+
+        if (!strcmp(remoteAddress, setAddress))
+        {
+            OIC_LOG(DEBUG, TAG, "the device is already set");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            ca_mutex_unlock(g_gattObjectMutex);
+            return jarrayObj;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+    }
+
+    ca_mutex_unlock(g_gattObjectMutex);
+    OIC_LOG(DEBUG, TAG, "There are no the gatt object in list");
+    return NULL;
+}
+
+CAResult_t CALEClientRemoveAllGattObjs(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientRemoveAllGattObjs");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_gattObjectMutex);
+    if (!g_gattObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
+        ca_mutex_unlock(g_gattObjectMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            continue;
+        }
+        (*env)->DeleteGlobalRef(env, jarrayObj);
+    }
+
+    OICFree(g_gattObjectList);
+    g_gattObjectList = NULL;
+    ca_mutex_unlock(g_gattObjectMutex);
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientRemoveGattObj");
+    VERIFY_NON_NULL(gatt, TAG, "gatt is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_gattObjectMutex);
+    if (!g_gattObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
+        ca_mutex_unlock(g_gattObjectMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        jstring jni_setAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        jstring jni_remoteAddress = CALEClientGetAddressFromGattObj(env, gatt);
+        if (!jni_remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+        if (!remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "remoteAddress is null");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (!strcmp(setAddress, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
+            (*env)->DeleteGlobalRef(env, jarrayObj);
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CALEClientReorderingList(index, g_gattObjectList);
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+        (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+    }
+
+    ca_mutex_unlock(g_gattObjectMutex);
+    OIC_LOG(DEBUG, TAG, "there are no target object");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientRemoveGattObjForAddr");
+    VERIFY_NON_NULL(addr, TAG, "addr is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_gattObjectMutex);
+    if (!g_gattObjectList)
+    {
+        OIC_LOG(ERROR, TAG, "g_gattObjectList is null");
+        ca_mutex_unlock(g_gattObjectMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_gattObjectList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        jstring jni_setAddress = CALEClientGetAddressFromGattObj(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        const char* remoteAddress = (*env)->GetStringUTFChars(env, addr, NULL);
+        if (!remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "remoteAddress is null");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (!strcmp(setAddress, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "remove object : %s", remoteAddress);
+            (*env)->DeleteGlobalRef(env, jarrayObj);
+
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
+            ca_mutex_unlock(g_gattObjectMutex);
+            return CALEClientReorderingList(index, g_gattObjectList);
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+        (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
+    }
+
+    ca_mutex_unlock(g_gattObjectMutex);
+    OIC_LOG(DEBUG, TAG, "there are no target object");
+    return CA_STATUS_FAILED;
+}
+
+/**
+ * BT State List
+ */
+
+CAResult_t CALEClientUpdateDeviceState(const char* address, uint32_t connectedState,
+                                       uint16_t notificationState, uint16_t sendState)
+{
+    VERIFY_NON_NULL(address, TAG, "address is null");
+
+    CALEState_t *newstate = (CALEState_t*) OICMalloc(sizeof(CALEState_t));
+    if (!newstate)
+    {
+        OIC_LOG(ERROR, TAG, "out of memory");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    if (strlen(address) > CA_MACADDR_SIZE)
+    {
+        OIC_LOG(ERROR, TAG, "address is not proper");
+        OICFree(newstate);
+        return CA_STATUS_FAILED;
+    }
+
+    strcpy(newstate->address, address);
+    newstate->connectedState = connectedState;
+    newstate->notificationState = notificationState;
+    newstate->sendState = sendState;
+    return CALEClientAddDeviceStateToList(newstate);
+}
+
+CAResult_t CALEClientAddDeviceStateToList(CALEState_t* state)
+{
+    VERIFY_NON_NULL(state, TAG, "state is null");
+
+    ca_mutex_lock(g_deviceStateListMutex);
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "gdevice_list is null");
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    if (CALEClientIsDeviceInList(state->address))
+    {
+        CALEState_t* curState = CALEClientGetStateInfo(state->address);
+        if(!curState)
+        {
+            OIC_LOG(ERROR, TAG, "curState is null");
+            ca_mutex_unlock(g_deviceStateListMutex);
+            return CA_STATUS_FAILED;
+        }
+
+        if (STATE_CHARACTER_NO_CHANGE == state->notificationState)
+        {
+            state->notificationState = curState->notificationState;
+        }
+
+        // delete previous state for update new state
+        CAResult_t res = CALEClientRemoveDeviceState(state->address);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientRemoveDeviceState has failed");
+            ca_mutex_unlock(g_deviceStateListMutex);
+            return res;
+        }
+    }
+    u_arraylist_add(g_deviceStateList, state); // update new state
+    OIC_LOG_V(DEBUG, TAG, "Set State Info to List : %d, %d",
+              state->connectedState, state->notificationState);
+
+    ca_mutex_unlock(g_deviceStateListMutex);
+    return CA_STATUS_OK;
+}
+
+bool CALEClientIsDeviceInList(const char* remoteAddress)
+{
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false);
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
+        return false;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceStateList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "CALEState_t object is null");
+            return false;
+        }
+
+        if (!strcmp(remoteAddress, state->address))
+        {
+            OIC_LOG(DEBUG, TAG, "the device is already set");
+            return true;
+        }
+        else
+        {
+            continue;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "there are no the device in list.");
+    return false;
+}
+
+CAResult_t CALEClientRemoveAllDeviceState()
+{
+    OIC_LOG(DEBUG, TAG, "CALENativeRemoveAllDevices");
+
+    ca_mutex_lock(g_deviceStateListMutex);
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceStateList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            continue;
+        }
+        OICFree(state);
+    }
+
+    OICFree(g_deviceStateList);
+    g_deviceStateList = NULL;
+    ca_mutex_unlock(g_deviceStateListMutex);
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEClientRemoveDeviceState(const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientRemoveDeviceState");
+    VERIFY_NON_NULL(remoteAddress, TAG, "remoteAddress is null");
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceStateList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "CALEState_t object is null");
+            continue;
+        }
+
+        if (!strcmp(state->address, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "remove state : %s", remoteAddress);
+            OICFree(state);
+
+            CAResult_t res = CALEClientReorderingList(index, g_deviceStateList);
+            if(CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientReorderingList has failed");
+                return res;
+            }
+            return CA_STATUS_OK;
+        }
+    }
+
+    return CA_STATUS_FAILED;
+}
+
+CALEState_t* CALEClientGetStateInfo(const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientGetStateInfo");
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", NULL);
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
+        return NULL;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceStateList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "CALEState_t object is null");
+            continue;
+        }
+
+        if (!strcmp(state->address, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "get state : %s", remoteAddress);
+            return state;
+        }
+    }
+    return NULL;
+}
+
+bool CALEClientIsConnectedDevice(const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientIsConnectedDevice");
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false);
+
+    ca_mutex_lock(g_deviceStateListMutex);
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return false;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceStateList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "CALEState_t object is null");
+            continue;
+        }
+
+        if (!strcmp(state->address, remoteAddress))
+        {
+            OIC_LOG(DEBUG, TAG, "check whether it is connected or not");
+
+            if (STATE_CONNECTED == state->connectedState)
+            {
+                ca_mutex_unlock(g_deviceStateListMutex);
+                return true;
+            }
+            else
+            {
+                ca_mutex_unlock(g_deviceStateListMutex);
+                return false;
+            }
+        }
+    }
+    ca_mutex_unlock(g_deviceStateListMutex);
+    return false;
+}
+
+bool CALEClientIsSetCharacteristic(const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientIsSetCharacteristic");
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false);
+
+    ca_mutex_lock(g_deviceStateListMutex);
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
+        ca_mutex_unlock(g_deviceStateListMutex);
+        return false;
+    }
+
+    uint32_t length = u_arraylist_length(g_deviceStateList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index);
+        if (!state)
+        {
+            OIC_LOG(ERROR, TAG, "CALEState_t object is null");
+            continue;
+        }
+
+        if (!strcmp(state->address, remoteAddress))
+        {
+            OIC_LOG_V(DEBUG, TAG, "check whether it was set or not:%d", state->notificationState);
+
+            if (STATE_CHARACTER_SET == state->notificationState)
+            {
+                ca_mutex_unlock(g_deviceStateListMutex);
+                return true;
+            }
+            else
+            {
+                ca_mutex_unlock(g_deviceStateListMutex);
+                return false;
+            }
+        }
+    }
+
+    ca_mutex_unlock(g_deviceStateListMutex);
+    return false;
+}
+
+void CALEClientCreateDeviceList()
+{
+    OIC_LOG(DEBUG, TAG, "CALEClientCreateDeviceList");
+
+    // create new object array
+    if (!g_gattObjectList)
+    {
+        OIC_LOG(DEBUG, TAG, "Create g_gattObjectList");
+
+        g_gattObjectList = u_arraylist_create();
+    }
+
+    if (!g_deviceStateList)
+    {
+        OIC_LOG(DEBUG, TAG, "Create g_deviceStateList");
+
+        g_deviceStateList = u_arraylist_create();
+    }
+
+    if (!g_deviceList)
+    {
+        OIC_LOG(DEBUG, TAG, "Create g_deviceList");
+
+        g_deviceList = u_arraylist_create();
+    }
+}
+
+CAResult_t CALEClientReorderingList(uint32_t index, u_arraylist_t *list)
+{
+    if (!list)
+    {
+        OIC_LOG(ERROR, TAG, "list is null");
+        return CA_STATUS_FAILED;
+    }
+
+    if (index >= list->length)
+    {
+        OIC_LOG(ERROR, TAG, "index is not available");
+        return CA_STATUS_FAILED;
+    }
+
+    if (index < list->length - 1)
+    {
+        memmove(&list->data[index], &list->data[index + 1],
+                (list->length - index - 1) * sizeof(void *));
+    }
+
+    list->size--;
+    list->length--;
+
+    return CA_STATUS_OK;
+}
+
+/**
+ * Check Sent Count for remove g_sendBuffer
+ */
+void CALEClientUpdateSendCnt(JNIEnv *env)
+{
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    // mutex lock
+    ca_mutex_lock(g_threadMutex);
+
+    g_currentSentCnt++;
+
+    if (g_targetCnt <= g_currentSentCnt)
+    {
+        g_targetCnt = 0;
+        g_currentSentCnt = 0;
+
+        if (g_sendBuffer)
+        {
+            (*env)->DeleteGlobalRef(env, g_sendBuffer);
+            g_sendBuffer = NULL;
+        }
+        // notity the thread
+        ca_cond_signal(g_threadCond);
+        CALEClientSetSendFinishFlag(true);
+        OIC_LOG(DEBUG, TAG, "set signal for send data");
+    }
+    // mutex unlock
+    ca_mutex_unlock(g_threadMutex);
+}
+
+CAResult_t CALEClientInitGattMutexVaraibles()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == g_bleReqRespClientCbMutex)
+    {
+        g_bleReqRespClientCbMutex = ca_mutex_new();
+        if (NULL == g_bleReqRespClientCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleServerBDAddressMutex)
+    {
+        g_bleServerBDAddressMutex = ca_mutex_new();
+        if (NULL == g_bleServerBDAddressMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_threadMutex)
+    {
+        g_threadMutex = ca_mutex_new();
+        if (NULL == g_threadMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_threadSendMutex)
+    {
+        g_threadSendMutex = ca_mutex_new();
+        if (NULL == g_threadSendMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_threadSendCBMutex)
+    {
+        g_threadSendCBMutex = ca_mutex_new();
+        if (NULL == g_threadSendCBMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_deviceListMutex)
+    {
+        g_deviceListMutex = ca_mutex_new();
+        if (NULL == g_deviceListMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_gattObjectMutex)
+    {
+        g_gattObjectMutex = ca_mutex_new();
+        if (NULL == g_gattObjectMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_deviceStateListMutex)
+    {
+        g_deviceStateListMutex = ca_mutex_new();
+        if (NULL == g_deviceStateListMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_SendFinishMutex)
+    {
+        g_SendFinishMutex = ca_mutex_new();
+        if (NULL == g_SendFinishMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_writeCharacteristicCBMutex)
+    {
+        g_writeCharacteristicCBMutex = ca_mutex_new();
+        if (NULL == g_writeCharacteristicCBMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_theSendRequestMutex)
+    {
+        g_theSendRequestMutex = ca_mutex_new();
+        if (NULL == g_theSendRequestMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALEClientTerminateGattMutexVariables()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_free(g_bleReqRespClientCbMutex);
+    g_bleReqRespClientCbMutex = NULL;
+
+    ca_mutex_free(g_bleServerBDAddressMutex);
+    g_bleServerBDAddressMutex = NULL;
+
+    ca_mutex_free(g_threadMutex);
+    g_threadMutex = NULL;
+
+    ca_mutex_free(g_threadSendMutex);
+    g_threadSendMutex = NULL;
+
+    ca_mutex_free(g_threadSendCBMutex);
+    g_threadSendCBMutex = NULL;
+
+    ca_mutex_free(g_deviceListMutex);
+    g_deviceListMutex = NULL;
+
+    ca_mutex_free(g_SendFinishMutex);
+    g_SendFinishMutex = NULL;
+
+    ca_mutex_free(g_writeCharacteristicCBMutex);
+    g_writeCharacteristicCBMutex = NULL;
+
+    ca_mutex_free(g_theSendRequestMutex);
+    g_theSendRequestMutex = NULL;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CALEClientSetSendFinishFlag(bool flag)
+{
+    OIC_LOG_V(DEBUG, TAG, "g_isFinishedSendData is %d", flag);
+
+    ca_mutex_lock(g_SendFinishMutex);
+    g_isFinishedSendData = flag;
+    ca_mutex_unlock(g_SendFinishMutex);
+}
+
+void CALEClientSetWriteCharacteristicCBFlag(bool flag)
+{
+    OIC_LOG_V(DEBUG, TAG, "g_isReceivedWriteCB is %d", flag);
+
+    ca_mutex_lock(g_writeCharacteristicCBMutex);
+    g_isReceivedWriteCB = flag;
+    ca_mutex_unlock(g_writeCharacteristicCBMutex);
+}
+
+void CALEClientSetTheSendRequestFlag(bool flag)
+{
+    OIC_LOG_V(DEBUG, TAG, "g_isRequestedSend is %d", flag);
+
+    ca_mutex_lock(g_theSendRequestMutex);
+    g_isRequestedSend = flag;
+    ca_mutex_unlock(g_theSendRequestMutex);
+}
+
+/**
+ * adapter common
+ */
+
+CAResult_t CAStartBLEGattClient()
+{
+    CAResult_t res = CALEClientStartMulticastServer();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStartMulticastServer has failed");
+    }
+    else
+    {
+        g_isStartedLEClient = true;
+    }
+
+    return res;
+}
+
+void CAStopBLEGattClient()
+{
+    OIC_LOG(DEBUG, TAG, "CAStopBLEGattClient");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALEClientDisconnectAll(env);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientDisconnectAll has failed");
+    }
+
+    ret = CALEClientStopScan();
+    if(CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
+    }
+
+    ca_cond_signal(g_threadCond);
+    ca_cond_signal(g_threadSendCond);
+    g_isStartedLEClient = false;
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+}
+
+void CATerminateBLEGattClient()
+{
+    OIC_LOG(DEBUG, TAG, "Terminate GATT Client");
+    CALEClientTerminate();
+}
+
+CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char  *data,
+                                                const uint32_t dataLen, CALETransferType_t type,
+                                                const int32_t position)
+{
+    OIC_LOG(DEBUG, TAG, "call CALEClientSendUnicastMessage");
+    VERIFY_NON_NULL(data, TAG, "data is null");
+    VERIFY_NON_NULL(remoteAddress, TAG, "remoteAddress is null");
+
+    return CALEClientSendUnicastMessage(remoteAddress, data, dataLen);
+}
+
+CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "call CALEClientSendMulticastMessage");
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    return CALEClientSendMulticastMessage(data, dataLen);
+}
+
+void CASetBLEReqRespClientCallback(CABLEClientDataReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_bleReqRespClientCbMutex);
+    g_CABLEClientDataReceivedCallback = callback;
+    ca_mutex_unlock(g_bleReqRespClientCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetBleClientThreadPoolHandle(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CALEClientInitialize(handle);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAGetLEAddress(char **local_address)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(local_address, TAG, "local_address is null");
+    CAResult_t res = CALEClientGetInterfaceInfo(local_address);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "it didn't get local address");
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CARegisterLeScanCallback(JNIEnv *env, jobject obj,
+                                                                   jobject callback)
+{
+    OIC_LOG(DEBUG, TAG, "CARegisterLeScanCallback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(callback, TAG, "callback is null");
+
+    g_leScanCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CARegisterLeGattCallback(JNIEnv *env, jobject obj,
+                                                                   jobject callback)
+{
+    OIC_LOG(DEBUG, TAG, "CARegisterLeGattCallback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(callback, TAG, "callback is null");
+
+    g_leGattCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeScanCallback(JNIEnv *env, jobject obj,
+                                                           jobject device, jint rssi,
+                                                           jbyteArray scanRecord)
+{
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(device, TAG, "device is null");
+
+    CAResult_t res = CALEClientAddScanDeviceToList(env, device);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "CALEClientAddScanDeviceToList has failed : %d", res);
+    }
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattConnectionStateChangeCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattConnectionStateChangeCallback(JNIEnv *env,
+                                                                                jobject obj,
+                                                                                jobject gatt,
+                                                                                jint status,
+                                                                                jint newstate)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattConnectionStateChangeCallback - status %d, newstate %d", status,
+            newstate);
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
+
+    if (GATT_SUCCESS == status && STATE_CONNECTED == newstate) // le connected
+    {
+        jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
+        if (!jni_address)
+        {
+            goto error_exit;
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (address)
+        {
+            CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED,
+                                                         STATE_CHARACTER_NO_CHANGE,
+                                                         STATE_SEND_NONE);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+                (*env)->ReleaseStringUTFChars(env, jni_address, address);
+                goto error_exit;
+            }
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+        }
+
+        CAResult_t res = CALEClientAddGattobjToList(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientAddGattobjToList has failed");
+            goto error_exit;
+        }
+
+        res = CALEClientDiscoverServices(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientDiscoverServices has failed");
+            goto error_exit;
+        }
+    }
+    else if (GATT_SUCCESS == status && STATE_DISCONNECTED == newstate) // le disconnected
+    {
+        CAResult_t res = CALEClientStartScan();
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        }
+
+        jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
+        if (!jni_address)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientGetAddressFromGattObj has failed");
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (address)
+        {
+            res = CALEClientUpdateDeviceState(address, STATE_DISCONNECTED,
+                                              STATE_CHARACTER_NO_CHANGE,
+                                              STATE_SEND_NONE);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+            }
+            (*env)->ReleaseStringUTFChars(env, jni_address, address);
+        }
+
+        res = CALEClientGattClose(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientGattClose has failed");
+        }
+
+        ca_cond_signal(g_threadSendCond);
+    }
+    else // error
+    {
+        // update state
+        jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
+        if (!jni_address)
+        {
+            OIC_LOG(ERROR, TAG, "jni_address is null");
+            goto error_exit;
+
+        }
+
+        const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+        if (address)
+        {
+            CAResult_t res = CALEClientUpdateDeviceState(address, STATE_DISCONNECTED,
+                                                         STATE_CHARACTER_NO_CHANGE,
+                                                         STATE_SEND_FAILED);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+            }
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_address, address);
+
+        goto error_exit;
+    }
+    return;
+
+    // error label.
+error_exit:
+
+    CALEClientSendFinish(env, gatt);
+    ca_cond_signal(g_threadSendCond);
+    return;
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattServicesDiscoveredCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattServicesDiscoveredCallback(JNIEnv *env,
+                                                                             jobject obj,
+                                                                             jobject gatt,
+                                                                             jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattServicesDiscoveredCallback - status %d: ", status);
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
+
+    if (0 != status) // discovery error
+    {
+        CALEClientSendFinish(env, gatt);
+        ca_cond_signal(g_threadSendCond);
+        return;
+    }
+
+    jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
+    if (!jni_address)
+    {
+        CALEClientSendFinish(env, gatt);
+        ca_cond_signal(g_threadSendCond);
+        return;
+    }
+
+    const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        CALEClientSendFinish(env, gatt);
+        ca_cond_signal(g_threadSendCond);
+        return;
+    }
+
+    if (!CALEClientIsSetCharacteristic(address))
+    {
+        jstring jni_uuid = (*env)->NewStringUTF(env, OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
+        if (!jni_uuid)
+        {
+            OIC_LOG(ERROR, TAG, "jni_uuid is null");
+            goto error_exit;
+        }
+
+        jobject jni_obj_GattCharacteristic = CALEClientGetGattService(env, gatt, jni_uuid);
+        if (!jni_obj_GattCharacteristic)
+        {
+            OIC_LOG(ERROR, TAG, "jni_obj_GattCharacteristic is null");
+            goto error_exit;
+        }
+
+        CAResult_t res = CALEClientSetCharacteristicNotification(env, gatt,
+                                                                 jni_obj_GattCharacteristic);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientSetCharacteristicNotification has failed");
+            goto error_exit;
+        }
+
+        res = CALEClientSetUUIDToDescriptor(env, gatt, jni_obj_GattCharacteristic);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientSetUUIDToDescriptor has failed");
+            goto error_exit;
+        }
+
+        res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, STATE_CHARACTER_SET,
+                                          STATE_SEND_NONE);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+            goto error_exit;
+        }
+    }
+    else
+    {
+        CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
+            goto error_exit;
+        }
+    }
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    return;
+
+    // error label.
+error_exit:
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    CALEClientSendFinish(env, gatt);
+    ca_cond_signal(g_threadSendCond);
+    return;
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattCharacteristicReadCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattCharacteristicReadCallback(JNIEnv *env,
+                                                                             jobject obj,
+                                                                             jobject gatt,
+                                                                             jobject characteristic,
+                                                                             jbyteArray data,
+                                                                             jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicReadCallback - status : %d", status);
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattCharacteristicWritjclasseCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattCharacteristicWriteCallback(
+        JNIEnv *env, jobject obj, jobject gatt, jobject characteristic, jbyteArray data,
+        jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - status : %d", status);
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
+
+    ca_mutex_lock(g_threadSendCBMutex);
+    if (!g_isRequestedSend)
+    {
+        OIC_LOG(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - waiting");
+        ca_cond_wait(g_threadSendCBCond, g_threadSendCBMutex);
+    }
+    ca_mutex_unlock(g_threadSendCBMutex);
+
+    jboolean isCopy;
+    char* wroteData = (char*) (*env)->GetByteArrayElements(env, data, &isCopy);
+
+    OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - write data : %s", wroteData);
+
+    // send success & signal
+    jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
+    if (!jni_address)
+    {
+        goto error_exit;
+    }
+
+    const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        goto error_exit;
+    }
+
+    if (GATT_SUCCESS != status) // error case
+    {
+        OIC_LOG(ERROR, TAG, "send failure");
+        CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, STATE_CHARACTER_SET,
+                                                     STATE_SEND_FAILED);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+        }
+        CALEClientSendFinish(env, gatt);
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "send success");
+        CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, STATE_CHARACTER_SET,
+                                                     STATE_SEND_SUCCESS);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+        }
+        CALEClientUpdateSendCnt(env);
+    }
+
+    CALEClientSetWriteCharacteristicCBFlag(true);
+    CALEClientSetTheSendRequestFlag(false);
+    ca_cond_signal(g_threadSendCond);
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+    return;
+
+    // error label.
+error_exit:
+
+    CALEClientSetWriteCharacteristicCBFlag(true);
+    CALEClientSetTheSendRequestFlag(false);
+    CALEClientSendFinish(env, gatt);
+    ca_cond_signal(g_threadSendCond);
+    return;
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattCharacteristicChangedCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattCharacteristicChangedCallback(
+        JNIEnv *env, jobject obj, jobject gatt, jobject characteristic, jbyteArray data)
+{
+    OIC_LOG(DEBUG, TAG, "CALeGattCharacteristicChangedCallback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
+    VERIFY_NON_NULL_VOID(data, TAG, "data is null");
+
+    // get Byte Array and covert to char*
+    jint length = (*env)->GetArrayLength(env, data);
+
+    jboolean isCopy;
+    jbyte *jni_byte_responseData = (jbyte*) (*env)->GetByteArrayElements(env, data, &isCopy);
+
+    OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicChangedCallback - raw data received : %s",
+            jni_byte_responseData);
+
+    char* receivedData = (char*) OICMalloc(sizeof(char) * length + 1);
+    if (!receivedData)
+    {
+        OIC_LOG(ERROR, TAG, "recevicedData is null");
+        return;
+    }
+
+    memcpy(receivedData, (const char*) jni_byte_responseData, length);
+    receivedData[length] = '\0';
+    (*env)->ReleaseByteArrayElements(env, data, jni_byte_responseData, JNI_ABORT);
+
+    jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "jni_address is null");
+        OICFree(receivedData);
+        return;
+    }
+
+    const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        OICFree(receivedData);
+        return;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicChangedCallback - data. : %s, %d",
+              receivedData, length);
+
+    ca_mutex_lock(g_bleServerBDAddressMutex);
+    uint32_t sentLength = 0;
+    g_CABLEClientDataReceivedCallback(address, OIC_GATT_SERVICE_UUID, receivedData, length,
+                                      &sentLength);
+    ca_mutex_unlock(g_bleServerBDAddressMutex);
+
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattDescriptorReadCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattDescriptorReadCallback(JNIEnv *env, jobject obj,
+                                                                         jobject gatt,
+                                                                         jobject descriptor,
+                                                                         jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattDescriptorReadCallback - status %d: ", status);
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattDescriptorWriteCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattDescriptorWriteCallback(JNIEnv *env, jobject obj,
+                                                                          jobject gatt,
+                                                                          jobject descriptor,
+                                                                          jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattDescriptorWriteCallback - status %d: ", status);
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(gatt, TAG, "gatt is null");
+
+    CAResult_t res = CALEClientWriteCharacteristic(env, gatt);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed");
+        goto error_exit;
+    }
+    return;
+
+// error label.
+error_exit:
+
+    CALEClientSendFinish(env, gatt);
+    ca_cond_signal(g_threadSendCond);
+    return;
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattReliableWriteCompletedCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattReliableWriteCompletedCallback(JNIEnv *env,
+                                                                                 jobject obj,
+                                                                                 jobject gatt,
+                                                                                 jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattReliableWriteCompletedCallback - status %d: ", status);
+}
+
+/*
+ * Class:     org_iotivity_jar_caleinterface
+ * Method:    CALeGattReadRemoteRssiCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattReadRemoteRssiCallback(JNIEnv *env, jobject obj,
+                                                                         jobject gatt, jint rssi,
+                                                                         jint status)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALeGattReadRemoteRssiCallback - rssi %d,  status %d: ", rssi, status);
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h b/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h
new file mode 100644 (file)
index 0000000..edfec61
--- /dev/null
@@ -0,0 +1,597 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caleclient.h
+ * @brief This file contains the APIs for BT LE communications.
+ */
+#ifndef CA_LECLIENT_H_
+#define CA_LECLIENT_H_
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+#include "jni.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+static const uint16_t STATE_CHARACTER_SET = 2;
+static const uint16_t STATE_CHARACTER_UNSET = 1;
+static const uint16_t STATE_CHARACTER_NO_CHANGE = 0;
+
+static const uint16_t STATE_SEND_NONE = 0;
+static const uint16_t STATE_SEND_SUCCESS = 1;
+static const uint16_t STATE_SEND_FAILED = 2;
+
+static const uint32_t STATE_CONNECTED = 2;
+static const uint32_t STATE_DISCONNECTED = 0;
+
+typedef struct le_state_info
+{
+    char address[CA_MACADDR_SIZE];
+    uint32_t connectedState;
+    uint16_t notificationState;
+    uint16_t sendState;
+} CALEState_t;
+
+/**
+ * @brief Callback to be notified on reception of any data from remote devices.
+ * @param  address                [IN] MAC address of remote device.
+ * @param  data                   [IN] Data received from remote device.
+ * @return None
+ * @pre  Callback must be registered using CALESetCallback(CAPacketReceiveCallback callback)
+ */
+typedef void (*CAPacketReceiveCallback)(const char *address, const char *data);
+
+/**
+ * @brief   initialize JNI object
+ * @return  None
+ */
+void CALEClientJniInit();
+
+/**
+ * @brief   set context of application
+ * @return  None
+ */
+void CALEClientJNISetContext();
+
+/**
+ * @brief   create interface object and initialize the object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientCreateJniInterfaceObject();
+
+/**
+ * @brief   initialize client for BLE
+ * @param   handle                [IN] thread pool handle object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientInitialize(ca_thread_pool_t handle);
+
+/**
+ * @brief   terminate client for BLE
+ * @return  None
+ */
+void CALEClientTerminate();
+
+/**
+ * @brief   for destroy sending routine
+ * @param   env                   [IN] JNI interface pointer
+ * @param   gatt                  [IN] Gatt profile object
+ * @return  None
+ */
+void CALEClientSendFinish(JNIEnv *env, jobject gatt);
+
+/**
+ * @brief   send data for unicast (interface)
+ * @param   address               [IN] remote address
+ * @param   data                  [IN] data for transmission
+ * @param   dataLen               [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientSendUnicastMessage(const char *address, const char *data,
+                                        const uint32_t dataLen);
+
+/**
+ * @brief   send data for multicast (interface)
+ * @param   data                  [IN] data for transmission
+ * @param   dataLen               [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientSendMulticastMessage(const char *data, const uint32_t dataLen);
+
+/**
+ * @brief   start unicast server
+ * @param   address               [IN] remote address
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientStartUnicastServer(const char *address);
+
+/**
+ * @brief   start multicast server (start discovery)
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientStartMulticastServer();
+
+/**
+ * @brief   stop unicast server
+ * @return  None
+ */
+void CALEClientStopUnicastServer();
+
+/**
+ * @brief   stop multicast server (stop discovery)
+ * @return  None
+ */
+void CALEClientStopMulticastServer();
+
+/**
+ * @brief   set this callback for receiving data packets from peer devices.
+ * @param   callback              [IN] callback to be notified on reception of
+ *                                unicast/multicast data packets.
+ * @return  None
+ */
+void CALEClientSetCallback(CAPacketReceiveCallback callback);
+
+/**
+ * @brief   get local address (interface)
+ * @param   address               [OUT] local address
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientGetInterfaceInfo(char **address);
+
+/**
+ * @brief   get local address (implement)
+ * @param   address               [OUT] local address
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientGetLocalAddress(char** address);
+
+/**
+ * @brief   send data for unicast (implement)
+ * @param   address               [IN] remote address
+ * @param   data                  [IN] data for transmission
+ * @param   dataLen               [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientSendUnicastMessageImpl(const char *address, const char *data,
+                                            const uint32_t dataLen);
+
+/**
+ * @brief   send data for multicast (implement)
+ * @param   env                   [IN] JNI interface pointer
+ * @param   data                  [IN] data for transmission
+ * @param   dataLen               [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const char *data,
+                                              const uint32_t dataLen);
+
+/**
+ * @brief   check whether it is connected or not with remote address.
+ * @param   address               [IN] remote address
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALECheckSendState(const char* address);
+
+/**
+ * @brief   send data to remote device.
+ *          if it isn't connected yet. connect LE before try to send data
+ * @param   env                   [IN] JNI interface pointer
+ * @param   device                [IN] bluetooth device object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientSendData(JNIEnv *env, jobject device);
+
+/**
+ * @brief   get address from bluetooth gatt object
+ * @param   env                   [IN] JNI interface pointer
+ * @param   gatt                  [IN] Gatt profile object
+ * @return  bluetooth address
+ */
+jstring CALEClientGetAddressFromGattObj(JNIEnv *env, jobject gatt);
+
+/**
+ * @brief   get remote address from bluetooth socket object
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothSocketObj    [IN] bluetooth socket
+ * @return  bluetooth address
+ */
+jstring CALEClientGetRemoteAddress(JNIEnv *env, jobject bluetoothSocketObj);
+
+/**
+ * @brief   close gatt
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientGattClose(JNIEnv *env, jobject bluetoothGatt);
+
+/**
+ * @brief   start to scan whole bluetooth devices (interface)
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientStartScan();
+
+/**
+ * @brief   start to scan whole bluetooth devices (implement)
+ * @param   env                   [IN] JNI interface pointer
+ * @param   callback              [IN] callback to receive device object by scanning
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback);
+
+/**
+ * @brief   start to scan target bluetooth devices for service uuid (implement)
+ * @param   env                   [IN] JNI interface pointer
+ * @param   uuids                 [IN] target UUID
+ * @param   callback              [IN] callback to receive device object by scanning
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids,
+                                           jobject callback);
+
+/**
+ * @brief   get uuid object
+ * @param   env                   [IN] JNI interface pointer
+ * @param   uuid                  [IN] uuid
+ * @return  uuid object
+ */
+jobject CALEClientGetUUIDObject(JNIEnv *env, const char *uuid);
+
+/**
+ * @brief   stop scan (interface)
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientStopScan();
+
+/**
+ * @brief   stop scan (implement)
+ * @param   env                   [IN] JNI interface pointer
+ * @param   callback              [IN] callback to receive device object by scanning
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback);
+
+/**
+ * @brief   connect to gatt server hosted
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothDevice       [IN] bluetooth Device object
+ * @param   autoconnect           [IN] whether to directly connect to the remote device(false) or
+ *                                     to automatically connect as soon as the remote device
+ *                                     becomes available
+ * @param   callback              [IN] callback for connection state change
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect,
+                             jobject callback);
+
+/**
+ * @brief   disconnect to gatt server by a target device
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientDisconnect(JNIEnv *env, jobject bluetoothGatt);
+
+/**
+ * @brief   disconnect to gatt server by whole devices
+ * @param   env                   [IN] JNI interface pointer
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientDisconnectAll(JNIEnv *env);
+
+/**
+ * @brief   start discovery server
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientDiscoverServices(JNIEnv *env, jobject bluetoothGatt);
+
+/**
+ * @brief   create GattCharacteristic and call CALEClientWriteCharacteristicImpl
+ *          for request to write gatt characteristic
+ * @param   env                   [IN] JNI interface pointer
+ * @param   gatt                  [IN] Gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientWriteCharacteristic(JNIEnv *env, jobject gatt);
+
+/**
+ * @brief   request to write gatt characteristic
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @param   gattCharacteristic    [IN] characteristic object that contain data to send
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientWriteCharacteristicImpl(JNIEnv *env, jobject bluetoothGatt,
+                                             jobject gattCharacteristic);
+
+/**
+ * @brief   request to read gatt characteristic
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientReadCharacteristic(JNIEnv *env, jobject bluetoothGatt);
+
+/**
+ * @brief   enable notification for a target device
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @param   characteristic        [IN] Characteristic object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientSetCharacteristicNotification(JNIEnv *env, jobject bluetoothGatt,
+                                                  jobject characteristic);
+
+/**
+ * @brief   create gatt characteristic object
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @param   data                  [IN] for make Characteristic with data
+ * @return  Gatt Characteristic object
+ */
+jobject CALEClientCreateGattCharacteristic(JNIEnv *env, jobject bluetoothGatt, jbyteArray data);
+
+/**
+ * @brief   get gatt service
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @param   characterUUID         [IN] for make BluetoothGattCharacteristic object
+ * @return  Gatt Service
+ */
+jobject CALEClientGetGattService(JNIEnv *env, jobject bluetoothGatt, jstring characterUUID);
+
+/**
+ * @brief   get value from characteristic
+ * @param   env                   [IN] JNI interface pointer
+ * @param   characteristic        [IN] Characteristic object
+ * @return  value in characteristic
+ */
+jbyteArray CALEClientGetValueFromCharacteristic(JNIEnv *env, jobject characteristic);
+
+/**
+ * @brief   create UUID List
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientCreateUUIDList();
+
+/**
+ * @brief   set UUID to descriptor
+ * @param   env                   [IN] JNI interface pointer
+ * @param   bluetoothGatt         [IN] Gatt profile object
+ * @param   characteristic        [IN] Characteristic object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientSetUUIDToDescriptor(JNIEnv *env, jobject bluetoothGatt,
+                                         jobject characteristic);
+
+/**
+ * BluetoothDevice List
+ */
+/**
+ * @brief   add device object to scan device list
+ * @param   env                   [IN] JNI interface pointer
+ * @param   device                [IN] bluetooth device object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device);
+
+/**
+ * @brief   check whether the device exist in list or not
+ * @param   env                   [IN] JNI interface pointer
+ * @param   remoteAddress         [IN] remote address
+ * @return  true or false
+ */
+bool CALEClientIsDeviceInScanDeviceList(JNIEnv *env, const char *remoteAddress);
+
+/**
+ * @brief   remove all devices in scan device list
+ * @param   env                   [IN] JNI interface pointer
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientRemoveAllScanDevices(JNIEnv *env);
+
+/**
+ * @brief   remove target device in scan device list
+ * @param   env                   [IN] JNI interface pointer
+ * @param   remoteAddress         [IN] remote address
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring remoteAddress);
+
+/**
+ * BluetoothGatt List
+ */
+
+/**
+ * @brief   add gatt object to gatt object list
+ * @param   env                   [IN] JNI interface pointer
+ * @param   gatt                  [IN] Gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt);
+
+/**
+ * @brief   check whether the gatt object exist in list or not
+ * @param   env                   [IN] JNI interface pointer
+ * @param   remoteAddress         [IN] remote address
+ * @return  true or false
+ */
+bool CALEClientIsGattObjInList(JNIEnv *env, const char *remoteAddress);
+
+/**
+ * @brief   get the gatt object
+ * @param   env                   [IN] JNI interface pointer
+ * @param   remoteAddress         [IN] remote address
+ * @return  gatt object
+ */
+jobject CALEClientGetGattObjInList(JNIEnv *env, const char* remoteAddress);
+
+/**
+ * @brief   remove all gatt objects in gatt object list
+ * @param   env                   [IN] JNI interface pointer
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientRemoveAllGattObjs(JNIEnv *env);
+
+/**
+ * @brief   remove target device in gatt object list
+ * @param   env                   [IN] JNI interface pointer
+ * @param   gatt                  [IN] Gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt);
+
+/**
+ * @brief   remove gatt object of target device for address in gatt object list
+ * @param   env                   [IN] JNI interface pointer
+ * @param   gatt                  [IN] Gatt profile object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr);
+
+/**
+ * BT State Info List
+ */
+
+/**
+ * @brief   update new state information
+ * @param   address               [IN] remote address
+ * @param   connectedState        [IN] connection state
+ * @param   notificationState     [IN] whether characteristic notification already set or not
+ * @param   sendState             [IN] whether sending was success or not
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientUpdateDeviceState(const char* address, uint32_t connectedState,
+                                       uint16_t notificationState, uint16_t sendState);
+
+/**
+ * @brief   add new state to state list
+ * @param   state                 [IN] new state
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientAddDeviceStateToList(CALEState_t* state);
+
+/**
+ * @brief   check whether the remote address is existed or not.
+ * @param   address               [IN] remote address
+ * @return  true or false
+ */
+bool CALEClientIsDeviceInList(const char *remoteAddress);
+
+/**
+ * @brief   remove all device states
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientRemoveAllDeviceState();
+
+/**
+ * @brief   remove the device state for a remote device
+ * @param   remoteAddress         [IN] remote address
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientRemoveDeviceState(const char* remoteAddress);
+
+/**
+ * @brief   get state information for a remote device
+ * @param   remoteAddress         [IN] remote address
+ * @return  CALEState_t
+ */
+CALEState_t* CALEClientGetStateInfo(const char* remoteAddress);
+
+/**
+ * @brief   check whether the remote address is connected or not.
+ * @param   remoteAddress         [IN] remote address
+ * @return  true or false
+ */
+bool CALEClientIsConnectedDevice(const char* remoteAddress);
+
+/**
+ * @brief   check whether the remote address set CharacteristicNotification or not
+ * @param   remoteAddress         [IN] remote address
+ * @return  true or false
+ */
+bool CALEClientIsSetCharacteristic(const char* remoteAddress);
+
+/**
+ * @brief   create scan device list
+ * @return  None
+ */
+void CALEClientCreateDeviceList();
+
+/**
+ * @brief   Reordering for device state list
+ * @param   index                 [IN] index of device list that want to reordering
+ * @param   list                  [IN] the list to reorder
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientReorderingList(uint32_t index, u_arraylist_t *list);
+
+/**
+ * @brief   update the counter which data is sent to remote device
+ * @param   env                   [IN] JNI interface pointer
+ * @return  None
+ */
+void CALEClientUpdateSendCnt(JNIEnv *env);
+
+/**
+ * @brief   initialize mutex
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEClientInitGattMutexVaraibles();
+
+/**
+ * @brief   terminate mutex
+ * @return  None
+ */
+void CALEClientTerminateGattMutexVariables();
+
+/**
+ * @brief   set send finish flag
+ * @param   flag                  [IN] flag
+ * @return  None
+ */
+void CALEClientSetSendFinishFlag(bool flag);
+
+/**
+ * @brief   set the flag whether WriteCharacteristicCB is called
+ * @param   flag                  [IN] flag
+ * @return  None
+ */
+void CALEClientSetWriteCharacteristicCBFlag(bool flag);
+
+/**
+ * @brief   set the flag whether Send Request is called
+ * @param   flag                  [IN] flag
+ * @return  None
+ */
+void CALEClientSetTheSendRequestFlag(bool flag);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_LECLIENT_H_ */
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c b/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c
new file mode 100644 (file)
index 0000000..d6874fa
--- /dev/null
@@ -0,0 +1,279 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <jni.h>
+#include <stdio.h>
+#include <android/log.h>
+#include "logger.h"
+#include "calenwmonitor.h"
+#include "caleclient.h"
+#include "caleserver.h"
+#include "caleutils.h"
+#include "caleinterface.h"
+#include "caadapterutils.h"
+
+#include "camutex.h"
+
+#include "org_iotivity_jar_caleclientinterface.h"
+
+#define TAG PCF("CA_LE_MONITOR")
+
+#define BT_STATE_ON (12)
+#define BT_STATE_OFF (10)
+
+static JavaVM *g_jvm;
+
+/**
+ * @var gCALEDeviceStateChangedCallback
+ * @brief Maintains the callback to be notified on device state changed.
+ */
+static CALEDeviceStateChangedCallback gCALEDeviceStateChangedCallback = NULL;
+
+/**
+ * @var gCALEDeviceStateChangedCbMutex
+ * @brief Mutex to synchronize access to the deviceStateChanged Callback when the state
+ *           of the LE adapter gets change.
+ */
+static ca_mutex gCALEDeviceStateChangedCbMutex = NULL;
+
+//getting context
+void CALENetworkMonitorJNISetContext()
+{
+    OIC_LOG(DEBUG, TAG, "CALENetworkMonitorJNISetContext - it is not supported");
+}
+
+//getting jvm
+void CALENetworkMonitorJniInit()
+{
+    OIC_LOG(DEBUG, TAG, "CALENetworkMonitorJniInit");
+    g_jvm = CANativeJNIGetJavaVM();
+}
+
+void CALESetNetStateCallback(CALEDeviceStateChangedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "CALESetNetStateCallback");
+    gCALEDeviceStateChangedCallback = callback;
+}
+
+CAResult_t CAInitializeLEAdapter()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CALENetworkMonitorJNISetContext();
+    CALENetworkMonitorJniInit();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitLENwkMonitorMutexVaraibles()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == gCALEDeviceStateChangedCbMutex)
+    {
+        gCALEDeviceStateChangedCbMutex = ca_mutex_new();
+        if (NULL == gCALEDeviceStateChangedCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+
+}
+
+void CATerminateLENwkMonitorMutexVaraibles()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_free(gCALEDeviceStateChangedCbMutex);
+    gCALEDeviceStateChangedCbMutex = NULL;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAGetLEAdapterState()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(DEBUG, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitializeLENetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t res = CAInitLENwkMonitorMutexVaraibles();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CAInitLENwkMonitorMutexVaraibles has failed");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
+
+}
+
+void CATerminateLENetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CATerminateLENwkMonitorMutexVaraibles();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "Setting CALEDeviceStateChangedCallback");
+
+    ca_mutex_lock(gCALEDeviceStateChangedCbMutex);
+    CALESetNetStateCallback(callback);
+    ca_mutex_unlock(gCALEDeviceStateChangedCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUnSetLEAdapterStateChangedCb()
+{
+    OIC_LOG(DEBUG, TAG, "it is not required in this platform");
+    return CA_STATUS_OK;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeStateChangedCallback(JNIEnv *env, jobject obj,
+                                                                   jint status)
+{
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+
+
+    OIC_LOG(DEBUG, TAG, "caleclientinterface - Network State Changed");
+
+    if (!gCALEDeviceStateChangedCallback)
+    {
+        OIC_LOG_V(ERROR, TAG, "gNetworkChangeCb is null", status);
+    }
+
+    if (BT_STATE_ON == status) // STATE_ON:12
+    {
+        CANetworkStatus_t newStatus = CA_INTERFACE_UP;
+        gCALEDeviceStateChangedCallback(newStatus);
+    }
+    else if (BT_STATE_OFF == status) // STATE_OFF:10
+    {
+        // remove obj for client
+        CAResult_t res = CALEClientRemoveAllGattObjs(env);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientRemoveAllGattObjs has failed");
+        }
+
+        res = CALEClientRemoveAllScanDevices(env);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEClientRemoveAllScanDevices has failed");
+        }
+
+        // remove obej for server
+        res = CALEServerRemoveAllDevices(env);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "CALEServerRemoveAllDevices has failed");
+        }
+
+        CANetworkStatus_t newStatus = CA_INTERFACE_DOWN;
+        gCALEDeviceStateChangedCallback(newStatus);
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeBondStateChangedCallback(JNIEnv *env, jobject obj,
+                                                                       jstring addr)
+{
+    OIC_LOG(DEBUG, TAG, "caleclientinterface - Bond State Changed");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(addr, TAG, "addr is null");
+
+    // remove obj for client
+    CAResult_t res = CALEClientRemoveGattObjForAddr(env, addr);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CANativeRemoveGattObjForAddr has failed");
+    }
+
+    res = CALEClientRemoveDeviceInScanDeviceList(env, addr);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEClientRemoveDeviceInScanDeviceList has failed");
+    }
+
+    // remove obej for server
+    res = CALEServerRemoveDevice(env, addr);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerRemoveDevice has failed");
+    }
+
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.h b/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.h
new file mode 100644 (file)
index 0000000..c04a0d6
--- /dev/null
@@ -0,0 +1,63 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+* @file calenwmonitor.h
+* @brief This file contains the APIs for BT LE communications.
+*/
+#ifndef CA_LENWMONITOR_H_
+#define CA_LENWMONITOR_H_
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+#include "caleinterface.h"
+#include "jni.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief   set context of application
+ * @return  None
+ */
+void CALENetworkMonitorJNISetContext();
+
+/**
+ * @brief   initialize JNI object
+ * @return  None
+ */
+void CALENetworkMonitorJniInit();
+
+/**
+ * @brief  Set this callback for receiving network information from BT stack.
+ * @param  callback   [IN] Callback to be notified on reception of BT state information
+ * @return  NONE
+ */
+void CALESetNetStateCallback(CALEDeviceStateChangedCallback callback);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_LENWMONITOR_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c b/resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c
new file mode 100644 (file)
index 0000000..dec1409
--- /dev/null
@@ -0,0 +1,2445 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <jni.h>
+#include <stdio.h>
+#include <string.h>
+#include <android/log.h>
+#include <unistd.h>
+#include "caleserver.h"
+#include "caleutils.h"
+#include "caleinterface.h"
+#include "caadapterutils.h"
+
+#include "logger.h"
+#include "oic_malloc.h"
+#include "cathreadpool.h"
+#include "camutex.h"
+#include "uarraylist.h"
+#include "org_iotivity_jar_caleserverinterface.h"
+
+#define TAG PCF("CA_LE_SERVER")
+
+static JavaVM *g_jvm = NULL;
+static jobject g_context = NULL;
+static jobject g_bluetoothGattServer = NULL;
+static jobject g_bluetoothGattServerCallback = NULL;
+static jobject g_leAdvertiseCallback = NULL;
+
+static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
+static u_arraylist_t *g_connectedDeviceList = NULL;
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+
+static bool g_isStartServer = false;
+static bool g_isInitializedServer = false;
+
+static CABLEServerDataReceivedCallback g_CABLEServerDataReceivedCallback = NULL;
+static ca_mutex g_bleReqRespCbMutex = NULL;
+static ca_mutex g_bleClientBDAddressMutex = NULL;
+static ca_mutex g_connectedDeviceListMutex = NULL;
+
+void CALEServerJNISetContext()
+{
+    OIC_LOG(DEBUG, TAG, "CALEServerJNISetContext");
+    g_context = (jobject) CANativeJNIGetContext();
+}
+
+void CALeServerJniInit()
+{
+    OIC_LOG(DEBUG, TAG, "CALeServerJniInit");
+    g_jvm = (JavaVM*) CANativeJNIGetJavaVM();
+}
+
+CAResult_t CALEServerCreateJniInterfaceObject()
+{
+    OIC_LOG(DEBUG, TAG, "CALEServerCreateJniInterfaceObject");
+
+    if (!g_context)
+    {
+        OIC_LOG(ERROR, TAG, "g_context is null");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    jclass jni_LEInterface = (*env)->FindClass(env, "org/iotivity/jar/caleserverinterface");
+    if (!jni_LEInterface)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get caleserverinterface class");
+        goto exit;
+    }
+
+    jmethodID LeInterfaceConstructorMethod = (*env)->GetMethodID(env, jni_LEInterface, "<init>",
+                                                                 "()V");
+    if (!LeInterfaceConstructorMethod)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get caleserverinterface constructor method");
+        goto exit;
+    }
+
+    (*env)->NewObject(env, jni_LEInterface, LeInterfaceConstructorMethod, g_context);
+    OIC_LOG(DEBUG, TAG, "Create instance for caleserverinterface");
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_OK;
+
+    exit:
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    return CA_STATUS_FAILED;
+}
+
+jobject CALEServerSetResponseData(JNIEnv *env, jbyteArray responseData)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerSetResponseData");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(responseData, TAG, "responseData is null", NULL);
+
+    if (!g_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "Check BluetoothGattServer status");
+        return NULL;
+    }
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CALEServerSetResponseData");
+
+    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
+                                                           "android/bluetooth/BluetoothGattServer");
+    if (!jni_cid_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
+        return NULL;
+    }
+
+    jclass jni_cid_bluetoothGattService = (*env)->FindClass(env, "android/bluetooth/"
+                                                            "BluetoothGattService");
+    if (!jni_cid_bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattService is null");
+        return NULL;
+    }
+
+    jclass jni_cid_bluetoothGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
+                                                                   "BluetoothGattCharacteristic");
+    if (!jni_cid_bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattCharacteristic is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getService = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
+                                                       "getService",
+                                                       "(Ljava/util/UUID;)Landroid/bluetooth/"
+                                                       "BluetoothGattService;");
+    if (!jni_cid_bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getService is null");
+        return NULL;
+    }
+
+    jobject jni_obj_serviceUUID = CALEGetUuidFromString(env, OIC_GATT_SERVICE_UUID);
+    if (!jni_obj_serviceUUID)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_serviceUUID is null");
+        return NULL;
+    }
+
+    jobject jni_obj_bluetoothGattService = (*env)->CallObjectMethod(env, g_bluetoothGattServer,
+                                                                    jni_mid_getService,
+                                                                    jni_obj_serviceUUID);
+    if (!jni_obj_bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_bluetoothGattService is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getCharacteristic = (*env)->GetMethodID(env, jni_cid_bluetoothGattService,
+                                                              "getCharacteristic",
+                                                              "(Ljava/util/UUID;)"
+                                                              "Landroid/bluetooth/"
+                                                              "BluetoothGattCharacteristic;");
+    if (!jni_mid_getCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getCharacteristic is null");
+        return NULL;
+    }
+
+    jobject jni_obj_responseUUID = CALEGetUuidFromString(env,
+                                                         OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
+    if (!jni_obj_responseUUID)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_responseUUID is null");
+        return NULL;
+    }
+
+    jobject jni_obj_bluetoothGattCharacteristic = (*env)->CallObjectMethod(
+            env, jni_obj_bluetoothGattService, jni_mid_getCharacteristic, jni_obj_responseUUID);
+    if (!jni_obj_bluetoothGattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_bluetoothGattCharacteristic is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_setValue = (*env)->GetMethodID(env, jni_cid_bluetoothGattCharacteristic,
+                                                     "setValue", "([B)Z");
+    if (!jni_mid_setValue)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setValue is null");
+        return NULL;
+    }
+
+    jboolean jni_boolean_setValue = (*env)->CallBooleanMethod(env,
+                                                              jni_obj_bluetoothGattCharacteristic,
+                                                              jni_mid_setValue, responseData);
+    if (JNI_FALSE == jni_boolean_setValue)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to set response data");
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSetResponseData");
+    return jni_obj_bluetoothGattCharacteristic;
+}
+
+CAResult_t CALEServerSendResponseData(JNIEnv *env, jobject device, jobject responseData)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerSendResponseData");
+    VERIFY_NON_NULL(responseData, TAG, "responseData is null");
+    VERIFY_NON_NULL(device, TAG, "device is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
+                                                           "android/bluetooth/BluetoothGattServer");
+    if (!jni_cid_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_notifyCharacteristicChanged = (*env)->GetMethodID(
+            env, jni_cid_bluetoothGattServer, "notifyCharacteristicChanged",
+            "(Landroid/bluetooth/BluetoothDevice;"
+            "Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z");
+    if (!jni_mid_notifyCharacteristicChanged)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_notifyCharacteristicChanged is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jboolean jni_boolean_notifyCharacteristicChanged = (*env)->CallBooleanMethod(
+            env, g_bluetoothGattServer, jni_mid_notifyCharacteristicChanged, device, responseData,
+            JNI_FALSE);
+    if (JNI_FALSE == jni_boolean_notifyCharacteristicChanged)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to notify characteristic");
+        return CA_SEND_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendResponseData");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerSendResponse(JNIEnv *env, jobject device, jint requestId, jint status,
+                                        jint offset, jbyteArray value)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerSendResponse");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(device, TAG, "device is null");
+    VERIFY_NON_NULL(value, TAG, "value is null");
+
+    OIC_LOG(DEBUG, TAG, "CALEServerSendResponse");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
+                                                           "android/bluetooth/BluetoothGattServer");
+    if (!jni_cid_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_sendResponse = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
+                                                         "sendResponse",
+                                                         "(Landroid/bluetooth/BluetoothDevice;"
+                                                         "III[B)Z");
+    if (!jni_mid_sendResponse)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_sendResponse is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jboolean jni_boolean_sendResponse = (*env)->CallBooleanMethod(env, g_bluetoothGattServer,
+                                                                  jni_mid_sendResponse, device,
+                                                                  requestId, status, offset,
+                                                                  value);
+    if (JNI_FALSE == jni_boolean_sendResponse)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to send response for gatt characteristic write request");
+        return CA_SEND_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendResponse");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerStartAdvertise");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(advertiseCallback, TAG, "advertiseCallback is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_AdvertiseSettings = (*env)->FindClass(env,
+                                                         "android/bluetooth/le/"
+                                                         "AdvertiseSettings$Builder");
+    if (!jni_cid_AdvertiseSettings)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_AdvertiseSettings is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_AdvertiseSettings = (*env)->GetMethodID(env, jni_cid_AdvertiseSettings,
+                                                              "<init>", "()V");
+    if (!jni_mid_AdvertiseSettings)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_AdvertiseSettings is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_AdvertiseSettings = (*env)->NewObject(env, jni_cid_AdvertiseSettings,
+                                                      jni_mid_AdvertiseSettings);
+    if (!jni_AdvertiseSettings)
+    {
+        OIC_LOG(ERROR, TAG, "jni_AdvertiseSettings is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_setAdvertiseMode = (*env)->GetMethodID(env, jni_cid_AdvertiseSettings,
+                                                             "setAdvertiseMode",
+                                                             "(I)Landroid/bluetooth/le/"
+                                                             "AdvertiseSettings$Builder;");
+    if (!jni_mid_setAdvertiseMode)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setAdvertiseMode is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // 0: Low power, 1: Balanced
+    jobject jni_obj_setAdvertiseMode = (*env)->CallObjectMethod(env, jni_AdvertiseSettings,
+                                                                jni_mid_setAdvertiseMode, 0);
+    if (!jni_obj_setAdvertiseMode)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_setAdvertiseMode is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_setConnectable = (*env)->GetMethodID(env, jni_cid_AdvertiseSettings,
+                                                           "setConnectable",
+                                                           "(Z)Landroid/bluetooth/le/"
+                                                           "AdvertiseSettings$Builder;");
+    if (!jni_mid_setConnectable)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setConnectable is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_setConnectable = (*env)->CallObjectMethod(env, jni_AdvertiseSettings,
+                                                              jni_mid_setConnectable, JNI_TRUE);
+    if (!jni_obj_setConnectable)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_setConnectable is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_setTimeout = (*env)->GetMethodID(env, jni_cid_AdvertiseSettings, "setTimeout",
+                                                       "(I)Landroid/bluetooth/le/"
+                                                       "AdvertiseSettings$Builder;");
+    if (!jni_mid_setTimeout)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_setTimeout is null");
+        return CA_STATUS_FAILED;
+    }
+
+    //A value of 0 will disable the time limit
+    jobject jni_obj_setTimeout = (*env)->CallObjectMethod(env, jni_AdvertiseSettings,
+                                                          jni_mid_setTimeout, 0);
+    if (!jni_obj_setTimeout)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_setTimeout is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_AdvertiseDataBuilder = (*env)->FindClass(env,
+                                                            "android/bluetooth/le/"
+                                                            "AdvertiseData$Builder");
+    if (!jni_cid_AdvertiseDataBuilder)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_AdvertiseDataBuilder is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_AdvertiseDataBuilder = (*env)->GetMethodID(env, jni_cid_AdvertiseDataBuilder,
+                                                                 "<init>", "()V");
+    if (!jni_mid_AdvertiseDataBuilder)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_AdvertiseDataBuilder is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_AdvertiseDataBuilder = (*env)->NewObject(env, jni_cid_AdvertiseDataBuilder,
+                                                         jni_mid_AdvertiseDataBuilder);
+    if (!jni_AdvertiseDataBuilder)
+    {
+        OIC_LOG(ERROR, TAG, "jni_AdvertiseDataBuilder is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_serviceUUID = CALEGetUuidFromString(env, OIC_GATT_SERVICE_UUID);
+    if (!jni_obj_serviceUUID)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_serviceUUID is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_ParcelUuid = CALEGetParcelUuid(env, jni_obj_serviceUUID);
+    if (!jni_ParcelUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_ParcelUuid is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_addServiceUuid = (*env)->GetMethodID(env, jni_cid_AdvertiseDataBuilder,
+                                                           "addServiceUuid",
+                                                           "(Landroid/os/ParcelUuid;)Landroid/"
+                                                           "bluetooth/le/AdvertiseData$Builder;");
+    if (!jni_mid_addServiceUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_addServiceUuid is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_addServiceUuid = (*env)->CallObjectMethod(env, jni_AdvertiseDataBuilder,
+                                                              jni_mid_addServiceUuid,
+                                                              jni_ParcelUuid);
+    if (!jni_obj_addServiceUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_addServiceUuid is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, "android/bluetooth/BluetoothAdapter");
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    "()Landroid/bluetooth/"
+                                                                    "BluetoothAdapter;");
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_getBluetoothLeAdvertiser = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                                     "getBluetoothLeAdvertiser",
+                                                                     "()Landroid/bluetooth/le/"
+                                                                     "BluetoothLeAdvertiser;");
+    if (!jni_mid_getBluetoothLeAdvertiser)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getBluetoothLeAdvertiser is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_getBluetoothLeAdvertiser = (*env)->CallObjectMethod(
+            env, jni_obj_BTAdapter, jni_mid_getBluetoothLeAdvertiser);
+    if (!jni_obj_getBluetoothLeAdvertiser)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_getBluetoothLeAdvertiser is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_build_LeAdvertiseSettings = (*env)->GetMethodID(env,
+                                                                      jni_cid_AdvertiseSettings,
+                                                                      "build",
+                                                                      "()Landroid/bluetooth/le/"
+                                                                      "AdvertiseSettings;");
+    if (!jni_mid_build_LeAdvertiseSettings)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_build_LeAdvertiseSettings is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_build_LeAdvertiseSettings = (*env)->CallObjectMethod(
+            env, jni_AdvertiseSettings, jni_mid_build_LeAdvertiseSettings);
+    if (!jni_obj_build_LeAdvertiseSettings)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_build_LeAdvertiseSettings is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_build_LeAdvertiseData = (*env)->GetMethodID(env, jni_cid_AdvertiseDataBuilder,
+                                                                  "build",
+                                                                  "()Landroid/bluetooth/le/"
+                                                                  "AdvertiseData;");
+    if (!jni_mid_build_LeAdvertiseData)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_build_LeAdvertiseData is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_build_LeAdvertiseData = (*env)->CallObjectMethod(env, jni_AdvertiseDataBuilder,
+                                                                     jni_mid_build_LeAdvertiseData);
+    if (!jni_obj_build_LeAdvertiseData)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_build_LeAdvertiseData is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_leAdvertiser = (*env)->FindClass(env,
+                                                    "android/bluetooth/le/BluetoothLeAdvertiser");
+    if (!jni_cid_leAdvertiser)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_leAdvertiser is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_startAdvertising = (*env)->GetMethodID(env, jni_cid_leAdvertiser,
+                                                             "startAdvertising",
+                                                             "(Landroid/bluetooth/le/"
+                                                             "AdvertiseSettings;Landroid/bluetooth/"
+                                                             "le/AdvertiseData;Landroid/bluetooth/"
+                                                             "le/AdvertiseCallback;)V");
+    if (!jni_mid_startAdvertising)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_startAdvertising is null");
+        return CA_STATUS_FAILED;
+    }
+
+    (*env)->CallVoidMethod(env, jni_obj_getBluetoothLeAdvertiser, jni_mid_startAdvertising,
+                           jni_obj_build_LeAdvertiseSettings, jni_obj_build_LeAdvertiseData,
+                           advertiseCallback);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "StartAdvertising has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Advertising started!!");
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerStartAdvertise");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerStopAdvertise(JNIEnv *env, jobject advertiseCallback)
+{
+    OIC_LOG(DEBUG, TAG, "IN - LEServerStopAdvertise");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(advertiseCallback, TAG, "advertiseCallback is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, "android/bluetooth/BluetoothAdapter");
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_leAdvertiser = (*env)->FindClass(env,
+                                                    "android/bluetooth/le/BluetoothLeAdvertiser");
+    if (!jni_cid_leAdvertiser)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_leAdvertiser is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    "()Landroid/bluetooth/"
+                                                                    "BluetoothAdapter;");
+    if (!jni_cid_leAdvertiser)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_leAdvertiser is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_getBTLeAdvertiser = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                                     "getBluetoothLeAdvertiser",
+                                                                     "()Landroid/bluetooth/le/"
+                                                                     "BluetoothLeAdvertiser;");
+    if (!jni_mid_getBTLeAdvertiser)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getBTLeAdvertiser is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_stopAdvertising = (*env)->GetMethodID(env, jni_cid_leAdvertiser,
+                                                            "stopAdvertising",
+                                                            "(Landroid/bluetooth/le/"
+                                                            "AdvertiseCallback;)V");
+    if (!jni_mid_stopAdvertising)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_stopAdvertising is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_getBluetoothLeAdvertiser = (*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+                                                                        jni_mid_getBTLeAdvertiser);
+    if (!jni_obj_getBluetoothLeAdvertiser)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_getBluetoothLeAdvertiser is null");
+        return CA_STATUS_FAILED;
+    }
+
+    (*env)->CallVoidMethod(env, jni_obj_getBluetoothLeAdvertiser, jni_mid_stopAdvertising,
+                           advertiseCallback);
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "getBluetoothLeAdvertiser has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "Advertising stopped!!");
+
+    OIC_LOG(DEBUG, TAG, "OUT - LEServerStopAdvertise");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerStartGattServer(JNIEnv *env, jobject gattServerCallback)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerStartGattServer");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(gattServerCallback, TAG, "gattServerCallback is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    if (g_isStartServer)
+    {
+        OIC_LOG(DEBUG, TAG, "Gatt server already started");
+    }
+
+    g_bluetoothGattServerCallback = (*env)->NewGlobalRef(env, gattServerCallback);
+
+    // open gatt server
+    jobject bluetoothGattServer = CALEServerOpenGattServer(env);
+    if (!bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "bluetoothGattServer is null");
+        return CA_STATUS_FAILED;
+    }
+
+    g_bluetoothGattServer = (*env)->NewGlobalRef(env, bluetoothGattServer);
+    if (!g_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "g_bluetoothGattServer is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // create gatt service
+    jobject bluetoothGattService = CALEServerCreateGattService(env);
+    if (!bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "bluetoothGattService is null");
+        return CA_STATUS_FAILED;
+    }
+
+    // add gatt service
+    CAResult_t res = CALEServerAddGattService(env, g_bluetoothGattServer,
+                                              bluetoothGattService);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerAddGattService has failed");
+    }
+    return res;
+}
+
+jobject CALEServerOpenGattServer(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerOpenGattServer");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return NULL;
+    }
+
+    jclass jni_cid_context = (*env)->FindClass(env, "android/content/Context");
+    if (!jni_cid_context)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_context is null");
+        return NULL;
+    }
+
+    jclass jni_cid_bluetoothManager = (*env)->FindClass(env, "android/bluetooth/BluetoothManager");
+    if (!jni_cid_bluetoothManager)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothManager is null");
+        return NULL;
+    }
+
+    jfieldID jni_fid_bluetoothService = (*env)->GetStaticFieldID(env, jni_cid_context,
+                                                                 "BLUETOOTH_SERVICE",
+                                                                 "Ljava/lang/String;");
+    if (!jni_fid_bluetoothService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_bluetoothService is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getSystemService = (*env)->GetMethodID(env, jni_cid_context,
+                                                             "getSystemService",
+                                                             "(Ljava/lang/String;)"
+                                                             "Ljava/lang/Object;");
+    if (!jni_mid_getSystemService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getSystemService is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_openGattServer = (*env)->GetMethodID(env, jni_cid_bluetoothManager,
+                                                           "openGattServer",
+                                                           "(Landroid/content/Context;"
+                                                           "Landroid/bluetooth/"
+                                                           "BluetoothGattServerCallback;)"
+                                                           "Landroid/bluetooth/"
+                                                           "BluetoothGattServer;");
+    if (!jni_mid_openGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_openGattServer is null");
+        return NULL;
+    }
+
+    jobject jni_obj_bluetoothService = (*env)->GetStaticObjectField(env, jni_cid_context,
+                                                                    jni_fid_bluetoothService);
+    if (!jni_obj_bluetoothService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_bluetoothService is null");
+        return NULL;
+    }
+
+    jobject jni_obj_bluetoothManager = (*env)->CallObjectMethod(env, g_context,
+                                                                jni_mid_getSystemService,
+                                                                jni_obj_bluetoothService);
+    if (!jni_obj_bluetoothManager)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_bluetoothManager is null");
+        return NULL;
+    }
+
+    jobject jni_obj_bluetoothGattServer = (*env)->CallObjectMethod(env, jni_obj_bluetoothManager,
+                                                                   jni_mid_openGattServer,
+                                                                   g_context,
+                                                                   g_bluetoothGattServerCallback);
+    if (!jni_obj_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_bluetoothGattServer is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerOpenGattServer");
+    return jni_obj_bluetoothGattServer;
+}
+
+jobject CALEServerCreateGattService(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerCreateGattService");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return NULL;
+    }
+
+    jclass jni_cid_bluetoothGattService = (*env)->FindClass(env, "android/bluetooth/"
+                                                            "BluetoothGattService");
+    if (!jni_cid_bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattService is null");
+        return NULL;
+    }
+
+    jclass jni_cid_bluetoothGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
+                                                                   "BluetoothGattCharacteristic");
+    if (!jni_cid_bluetoothGattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattCharacteristic is null");
+        return NULL;
+    }
+
+    jfieldID jni_fid_serviceType = (*env)->GetStaticFieldID(env, jni_cid_bluetoothGattService,
+                                                            "SERVICE_TYPE_PRIMARY", "I");
+    if (!jni_fid_serviceType)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_serviceType is null");
+        return NULL;
+    }
+
+    jfieldID jni_fid_readProperties = (*env)->GetStaticFieldID(env,
+                                                               jni_cid_bluetoothGattCharacteristic,
+                                                               "PROPERTY_READ", "I");
+    if (!jni_fid_readProperties)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_readProperties is null");
+        return NULL;
+    }
+
+#ifdef USE_PROPERTY_WRITE_RESPONSE
+    jfieldID jni_fid_writeProperties = (*env)->GetStaticFieldID(env,
+                                                                jni_cid_bluetoothGattCharacteristic,
+                                                                "PROPERTY_WRITE", "I");
+#else
+    jfieldID jni_fid_writeProperties = (*env)->GetStaticFieldID(env,
+                                                                jni_cid_bluetoothGattCharacteristic,
+                                                                "PROPERTY_WRITE_NO_RESPONSE", "I");
+#endif
+
+    if (!jni_fid_writeProperties)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_writeProperties is null");
+        return NULL;
+    }
+
+    jfieldID jni_fid_readPermissions = (*env)->GetStaticFieldID(env,
+                                                                jni_cid_bluetoothGattCharacteristic,
+                                                                "PERMISSION_READ", "I");
+    if (!jni_fid_readPermissions)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_readPermissions is null");
+        return NULL;
+    }
+
+    jfieldID jni_fid_writePermissions = (*env)->GetStaticFieldID(
+            env, jni_cid_bluetoothGattCharacteristic, "PERMISSION_WRITE", "I");
+    if (!jni_fid_writePermissions)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_writePermissions is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_bluetoothGattService = (*env)->GetMethodID(env, jni_cid_bluetoothGattService,
+                                                                 "<init>", "(Ljava/util/UUID;I)V");
+    if (!jni_mid_bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_bluetoothGattService is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_addCharacteristic = (*env)->GetMethodID(env, jni_cid_bluetoothGattService,
+                                                              "addCharacteristic",
+                                                              "(Landroid/bluetooth/"
+                                                              "BluetoothGattCharacteristic;)Z");
+    if (!jni_mid_addCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_addCharacteristic is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_bluetoothGattCharacteristic = (*env)->GetMethodID(
+            env, jni_cid_bluetoothGattCharacteristic, "<init>", "(Ljava/util/UUID;II)V");
+    if (!jni_mid_bluetoothGattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_bluetoothGattCharacteristic is null");
+        return NULL;
+    }
+
+    jobject jni_obj_serviceUUID = CALEGetUuidFromString(env, OIC_GATT_SERVICE_UUID);
+    if (!jni_obj_serviceUUID)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_serviceUUID is null");
+        return NULL;
+    }
+
+    jint jni_int_serviceType = (*env)->GetStaticIntField(env, jni_cid_bluetoothGattService,
+                                                         jni_fid_serviceType);
+    jobject jni_bluetoothGattService = (*env)->NewObject(env, jni_cid_bluetoothGattService,
+                                                         jni_mid_bluetoothGattService,
+                                                         jni_obj_serviceUUID, jni_int_serviceType);
+    if (!jni_bluetoothGattService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_bluetoothGattService is null");
+        return NULL;
+    }
+
+    jobject jni_obj_readUuid = CALEGetUuidFromString(env, OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
+    if (!jni_obj_readUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_readUuid is null");
+        return NULL;
+    }
+
+    jint jni_int_readProperties = (*env)->GetStaticIntField(env,
+                                                            jni_cid_bluetoothGattCharacteristic,
+                                                            jni_fid_readProperties);
+
+    jint jni_int_readPermissions = (*env)->GetStaticIntField(env,
+                                                             jni_cid_bluetoothGattCharacteristic,
+                                                             jni_fid_readPermissions);
+
+    jobject jni_readCharacteristic = (*env)->NewObject(env, jni_cid_bluetoothGattCharacteristic,
+                                                       jni_mid_bluetoothGattCharacteristic,
+                                                       jni_obj_readUuid, jni_int_readProperties,
+                                                       jni_int_readPermissions);
+    if (!jni_readCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_readCharacteristic is null");
+        return NULL;
+    }
+
+    CAResult_t res = CALEServerAddDescriptor(env, jni_readCharacteristic);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerAddDescriptor has failed");
+        return NULL;
+    }
+
+    jboolean jni_boolean_addReadCharacteristic = (*env)->CallBooleanMethod(
+            env, jni_bluetoothGattService, jni_mid_addCharacteristic, jni_readCharacteristic);
+    if (!jni_boolean_addReadCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_boolean_addReadCharacteristic is null");
+        return NULL;
+    }
+
+    jobject jni_obj_writeUuid = CALEGetUuidFromString(env, OIC_GATT_CHARACTERISTIC_REQUEST_UUID);
+    if (!jni_obj_writeUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_bluetoothGattServer is null");
+        return NULL;
+    }
+
+    jint jni_int_writeProperties = (*env)->GetStaticIntField(env,
+                                                             jni_cid_bluetoothGattCharacteristic,
+                                                             jni_fid_writeProperties);
+
+    jint jni_int_writePermissions = (*env)->GetStaticIntField(env,
+                                                              jni_cid_bluetoothGattCharacteristic,
+                                                              jni_fid_writePermissions);
+
+    jobject jni_writeCharacteristic = (*env)->NewObject(env, jni_cid_bluetoothGattCharacteristic,
+                                                        jni_mid_bluetoothGattCharacteristic,
+                                                        jni_obj_writeUuid, jni_int_writeProperties,
+                                                        jni_int_writePermissions);
+    if (!jni_writeCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_writeCharacteristic is null");
+        return NULL;
+    }
+
+    jboolean jni_boolean_addWriteCharacteristic = (*env)->CallBooleanMethod(
+            env, jni_bluetoothGattService, jni_mid_addCharacteristic, jni_writeCharacteristic);
+    if (JNI_FALSE == jni_boolean_addWriteCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to add jni_boolean_addReadCharacteristic");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerCreateGattService");
+    return jni_bluetoothGattService;
+}
+
+CAResult_t CALEServerAddDescriptor(JNIEnv *env, jobject characteristic)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerAddDescriptor");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(characteristic, TAG, "characteristic is null");
+
+    jclass jni_cid_bluetoothGattDescriptor = (*env)->FindClass(env, "android/bluetooth/"
+                                                               "BluetoothGattDescriptor");
+    if (!jni_cid_bluetoothGattDescriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattDescriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_bluetoothGattDescriptor = (*env)->GetMethodID(env,
+                                                                    jni_cid_bluetoothGattDescriptor,
+                                                                    "<init>",
+                                                                    "(Ljava/util/UUID;I)V");
+    if (!jni_mid_bluetoothGattDescriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_bluetoothGattDescriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jfieldID jni_fid_readPermissions = (*env)->GetStaticFieldID(env,
+                                                                jni_cid_bluetoothGattDescriptor,
+                                                                "PERMISSION_READ", "I");
+    if (!jni_fid_readPermissions)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_readPermissions is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_readUuid = CALEGetUuidFromString(env, OIC_GATT_CHARACTERISTIC_CONFIG_UUID);
+    if (!jni_obj_readUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_readUuid is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jint jni_int_readPermissions = (*env)->GetStaticIntField(env, jni_cid_bluetoothGattDescriptor,
+                                                             jni_fid_readPermissions);
+
+    OIC_LOG(DEBUG, TAG, "initialize new Descriptor");
+
+    jobject jni_readDescriptor = (*env)->NewObject(env, jni_cid_bluetoothGattDescriptor,
+                                                   jni_mid_bluetoothGattDescriptor,
+                                                   jni_obj_readUuid, jni_int_readPermissions);
+    if (!jni_readDescriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_readDescriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass jni_cid_GattCharacteristic = (*env)->FindClass(env, "android/bluetooth/"
+                                                          "BluetoothGattCharacteristic");
+    if (!jni_cid_GattCharacteristic)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_GattCharacteristic is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_addDescriptor = (*env)->GetMethodID(env, jni_cid_GattCharacteristic,
+                                                          "addDescriptor",
+                                                          "(Landroid/bluetooth/"
+                                                          "BluetoothGattDescriptor;)Z");
+    if (!jni_mid_addDescriptor)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_addDescriptor is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jboolean jni_boolean_addDescriptor = (*env)->CallBooleanMethod(env, characteristic,
+                                                                   jni_mid_addDescriptor,
+                                                                   jni_readDescriptor);
+
+    if (JNI_FALSE == jni_boolean_addDescriptor)
+    {
+        OIC_LOG(ERROR, TAG, "addDescriptor has failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "addDescriptor success");
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerAddDescriptor");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerAddGattService(JNIEnv *env, jobject bluetoothGattServer,
+                                          jobject bluetoothGattService)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerAddGattService");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothGattServer, TAG, "bluetoothGattServer is null");
+    VERIFY_NON_NULL(bluetoothGattService, TAG, "bluetoothGattService is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
+                                                           "android/bluetooth/BluetoothGattServer");
+    if (!jni_cid_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_addService = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
+                                                       "addService",
+                                                       "(Landroid/bluetooth/BluetoothGattService;)"
+                                                       "Z");
+    if (!jni_mid_addService)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_addService is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jboolean jni_boolean_addService = (*env)->CallBooleanMethod(env, bluetoothGattServer,
+                                                                jni_mid_addService,
+                                                                bluetoothGattService);
+
+    if (JNI_FALSE == jni_boolean_addService)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to add GATT service");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerAddGattService");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerConnect(JNIEnv *env, jobject bluetoothDevice)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerConnect");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothDevice, TAG, "bluetoothDevice is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
+                                                           "android/bluetooth/BluetoothGattServer");
+    if (!jni_cid_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_connect = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer, "connect",
+                                                    "(Landroid/bluetooth/BluetoothDevice;Z)Z");
+    if (!jni_mid_connect)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_connect is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jboolean jni_boolean_connect = (*env)->CallBooleanMethod(env, g_bluetoothGattServer,
+                                                             jni_mid_connect, bluetoothDevice,
+                                                             JNI_FALSE);
+    if (JNI_FALSE == jni_boolean_connect)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to connect");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerConnect");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerDisconnectAllDevices(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerDisconnectAllDevices");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_connectedDeviceListMutex);
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
+        ca_mutex_unlock(g_connectedDeviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_connectedDeviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG_V(ERROR, TAG, "object[%d] is null", index);
+            continue;
+        }
+
+        // disconnect for device obj
+        CAResult_t res = CALEServerDisconnect(env, jarrayObj);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG_V(ERROR, TAG, "Disconnect for this device[%d] has failed", index);
+            continue;
+        }
+    }
+
+    ca_mutex_unlock(g_connectedDeviceListMutex);
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerDisconnectAllDevices");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerDisconnect(JNIEnv *env, jobject bluetoothDevice)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerDisconnect");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothDevice, TAG, "bluetoothDevice is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
+                                                           "android/bluetooth/BluetoothGattServer");
+    if (!jni_cid_bluetoothGattServer)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothGattServer is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID jni_mid_cancelConnection = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
+                                                             "cancelConnection",
+                                                             "(Landroid/bluetooth/BluetoothDevice;)"
+                                                             "V");
+    if (!jni_mid_cancelConnection)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_cancelConnection is null");
+        return CA_STATUS_FAILED;
+    }
+
+    (*env)->CallVoidMethod(env, g_bluetoothGattServer, jni_mid_cancelConnection, bluetoothDevice);
+
+    if ((*env)->ExceptionCheck(env))
+    {
+        OIC_LOG(ERROR, TAG, "cancelConnection has failed");
+        (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerDisconnect");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jbyteArray responseData)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerSend");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(bluetoothDevice, TAG, "bluetoothDevice is null");
+    VERIFY_NON_NULL(responseData, TAG, "responseData is null");
+
+    if (!CALEIsEnableBTAdapter(env))
+    {
+        OIC_LOG(ERROR, TAG, "BT adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    jobject responseChar = CALEServerSetResponseData(env, responseData);
+    if (!responseChar)
+    {
+        OIC_LOG(ERROR, TAG, "responseChar is null");
+        return CA_STATUS_FAILED;
+    }
+
+    CAResult_t result = CALEServerSendResponseData(env, bluetoothDevice, responseChar);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to send response data");
+        return result;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSend");
+    return result;
+}
+
+CAResult_t CALEServerInitialize(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerInitialize");
+
+    CALeServerJniInit();
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALECheckPlatformVersion(env, 21);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "it is not supported");
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return ret;
+    }
+
+    g_threadPoolHandle = handle;
+
+    ret = CALEServerInitMutexVaraibles();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerInitMutexVaraibles has failed");
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return CA_STATUS_FAILED;
+    }
+
+    CALEServerJNISetContext();
+    CALEServerCreateCachedDeviceList();
+
+    ret = CALEServerCreateJniInterfaceObject();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerCreateJniInterfaceObject has failed");
+
+        if (isAttached)
+        {
+            (*g_jvm)->DetachCurrentThread(g_jvm);
+        }
+        return CA_STATUS_FAILED;
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    g_isInitializedServer = true;
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerInitialize");
+    return CA_STATUS_OK;
+}
+
+void CALEServerTerminate()
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerTerminate");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALEServerStopMulticastServer(0);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerStopMulticastServer has failed");
+    }
+
+    ret = CALEServerDisconnectAllDevices(env);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerDisconnectAllDevices has failed");
+    }
+
+    ret = CALEServerRemoveAllDevices(env);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerRemoveAllDevices has failed");
+    }
+
+    if (g_leAdvertiseCallback)
+    {
+        (*env)->DeleteGlobalRef(env, g_leAdvertiseCallback);
+    }
+
+    if (g_bluetoothGattServer)
+    {
+        (*env)->DeleteGlobalRef(env, g_bluetoothGattServer);
+    }
+
+    if (g_bluetoothGattServerCallback)
+    {
+        (*env)->DeleteGlobalRef(env, g_bluetoothGattServerCallback);
+    }
+
+    CALEServerTerminateMutexVaraibles();
+    CALEServerTerminateConditionVaraibles();
+
+    g_isStartServer = false;
+    g_isInitializedServer = false;
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerTerminate");
+}
+
+CAResult_t CALEServerSendUnicastMessage(const char* address, const char* data, uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendUnicastMessage(%s, %s)", address, data);
+    VERIFY_NON_NULL(address, TAG, "address is null");
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALEServerSendUnicastMessageImpl(env, address, data, dataLen);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerSendUnicastMessageImpl has failed");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendUnicastMessage");
+    return ret;
+}
+
+CAResult_t CALEServerSendMulticastMessage(const char* data, uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendMulticastMessage(%s)", data);
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALEServerSendMulticastMessageImpl(env, data, dataLen);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerSendMulticastMessageImpl has failed");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendMulticastMessage");
+    return ret;
+}
+
+CAResult_t CALEServerStartMulticastServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerStartMulticastServer");
+
+    if (!g_isInitializedServer)
+    {
+        OIC_LOG(INFO, TAG, "server is not initialized");
+        return CA_STATUS_FAILED;
+    }
+
+    if (g_isStartServer)
+    {
+        OIC_LOG(INFO, TAG, "server is already started..it will be skipped");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    g_isStartServer = true;
+
+    // start gatt server
+    CAResult_t ret = CALEServerStartGattServer(env, g_bluetoothGattServerCallback);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to start gatt server");
+        return ret;
+    }
+
+    // start advertise
+    ret = CALEServerStartAdvertise(env, g_leAdvertiseCallback);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerSendMulticastMessageImpl has failed");
+    }
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerStartMulticastServer");
+    return ret;
+}
+
+CAResult_t CALEServerStopMulticastServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerStopMulticastServer");
+
+    if (false == g_isStartServer)
+    {
+        OIC_LOG(INFO, TAG, "server is already stopped..it will be skipped");
+        return CA_STATUS_FAILED;
+    }
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, TAG, "g_jvm is null");
+        return CA_STATUS_FAILED;
+    }
+
+    bool isAttached = false;
+    JNIEnv* env;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return CA_STATUS_FAILED;
+        }
+        isAttached = true;
+    }
+
+    CAResult_t ret = CALEServerStopAdvertise(env, g_leAdvertiseCallback);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerSendMulticastMessageImpl has failed");
+    }
+
+    g_isStartServer = false;
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerStopMulticastServer");
+    return ret;
+}
+
+void CALEServerSetCallback(CAPacketReceiveCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "CALEServerSetCallback");
+    g_packetReceiveCallback = callback;
+}
+
+CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, const char* data,
+                                            uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendUnicastMessageImpl, address: %s, data: %s",
+            address, data);
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(address, TAG, "address is null");
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jni_obj_bluetoothDevice = NULL;
+    uint32_t length = u_arraylist_length(g_connectedDeviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        OIC_LOG(DEBUG, TAG, "check device address");
+        jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            return CA_STATUS_FAILED;
+        }
+
+        jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            return CA_STATUS_FAILED;
+        }
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            return CA_STATUS_FAILED;
+        }
+
+        OIC_LOG_V(DEBUG, TAG, "setAddress : %s", setAddress);
+        OIC_LOG_V(DEBUG, TAG, "address : %s", address);
+
+        if (!strcmp(setAddress, address))
+        {
+            OIC_LOG(DEBUG, TAG, "found the device");
+            jni_obj_bluetoothDevice = jarrayObj;
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            break;
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+    }
+
+    if (jni_obj_bluetoothDevice)
+    {
+        jbyteArray jni_bytearr_data = (*env)->NewByteArray(env, dataLen);
+        (*env)->SetByteArrayRegion(env, jni_bytearr_data, 0, dataLen, (jbyte*) data);
+
+        CAResult_t res = CALEServerSend(env, jni_obj_bluetoothDevice, jni_bytearr_data);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "send has failed");
+            return CA_SEND_FAILED;
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "There are no device to send in the list");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendUnicastMessageImpl");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const char *data, uint32_t dataLen)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN - CALEServerSendMulticastMessageImpl, send to, data: %s", data);
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(data, TAG, "data is null");
+
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_connectedDeviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            return CA_STATUS_FAILED;
+        }
+
+        // send data for all device
+        jbyteArray jni_bytearr_data = (*env)->NewByteArray(env, dataLen);
+        (*env)->SetByteArrayRegion(env, jni_bytearr_data, 0, dataLen, (jbyte*) data);
+        CAResult_t res = CALEServerSend(env, jarrayObj, jni_bytearr_data);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "send has failed");
+            return CA_SEND_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerSendMulticastMessageImpl");
+    return CA_STATUS_OK;
+}
+
+void CALEServerCreateCachedDeviceList()
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerCreateCachedDeviceList");
+
+    ca_mutex_lock(g_connectedDeviceListMutex);
+    // create new object array
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(DEBUG, TAG, "Create device list");
+        g_connectedDeviceList = u_arraylist_create();
+    }
+    ca_mutex_unlock(g_connectedDeviceListMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerCreateCachedDeviceList");
+}
+
+bool CALEServerIsDeviceInList(JNIEnv *env, const char* remoteAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerIsDeviceInList");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", false);
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false);
+
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "list is null");
+        return false;
+    }
+
+    uint32_t length = u_arraylist_length(g_connectedDeviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+
+        if (!jarrayObj)
+        {
+            OIC_LOG(ERROR, TAG, "jarrayObj is null");
+            return false;
+        }
+
+        jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
+        if (!jni_setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+            return false;
+        }
+
+        const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+        if (!setAddress)
+        {
+            OIC_LOG(ERROR, TAG, "setAddress is null");
+            return false;
+        }
+
+        if (!strcmp(remoteAddress, setAddress))
+        {
+            OIC_LOG(ERROR, TAG, "the device is already set");
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            return true;
+        }
+        else
+        {
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            continue;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "there are no device in the list");
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerCreateCachedDeviceList");
+    return false;
+}
+
+CAResult_t CALEServerAddDeviceToList(JNIEnv *env, jobject device)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerAddDeviceToList");
+    VERIFY_NON_NULL(device, TAG, "device is null");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_connectedDeviceListMutex);
+
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "list is null");
+        ca_mutex_unlock(g_connectedDeviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
+    if (!jni_remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
+        ca_mutex_unlock(g_connectedDeviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+    if (!remoteAddress)
+    {
+        OIC_LOG(ERROR, TAG, "remoteAddress is null");
+        ca_mutex_unlock(g_connectedDeviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    if (false == CALEServerIsDeviceInList(env, remoteAddress))
+    {
+        jobject jni_obj_device = (*env)->NewGlobalRef(env, device);
+        u_arraylist_add(g_connectedDeviceList, jni_obj_device);
+        OIC_LOG_V(DEBUG, TAG, "Set the object to ArrayList as Element : %s", remoteAddress);
+    }
+
+    (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+    ca_mutex_unlock(g_connectedDeviceListMutex);
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerAddDeviceToList");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerRemoveAllDevices(JNIEnv *env)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEServerRemoveAllDevices");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+
+    ca_mutex_lock(g_connectedDeviceListMutex);
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
+        ca_mutex_unlock(g_connectedDeviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_connectedDeviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+        if (jarrayObj)
+        {
+            (*env)->DeleteGlobalRef(env, jarrayObj);
+        }
+    }
+
+    OICFree(g_connectedDeviceList);
+    g_connectedDeviceList = NULL;
+    ca_mutex_unlock(g_connectedDeviceListMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEServerRemoveAllDevices");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address)
+{
+    OIC_LOG(DEBUG, TAG, "IN CALEServerRemoveDevice");
+    VERIFY_NON_NULL(env, TAG, "env is null");
+    VERIFY_NON_NULL(address, TAG, "address is null");
+
+    ca_mutex_lock(g_connectedDeviceListMutex);
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "no deviceList");
+        ca_mutex_unlock(g_connectedDeviceListMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint32_t length = u_arraylist_length(g_connectedDeviceList);
+    for (uint32_t index = 0; index < length; index++)
+    {
+        jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+
+        if (jarrayObj)
+        {
+            jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
+            if (!jni_setAddress)
+            {
+                OIC_LOG(ERROR, TAG, "wrong device address");
+                continue;
+            }
+            const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+            if (!setAddress)
+            {
+                OIC_LOG(ERROR, TAG, "setAddress is null");
+                continue;
+            }
+
+            const char* remoteAddress = (*env)->GetStringUTFChars(env, address, NULL);
+            if (!remoteAddress)
+            {
+                OIC_LOG(ERROR, TAG, "remoteAddress is null");
+                (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+                continue;
+            }
+
+            if (!strcmp(setAddress, remoteAddress))
+            {
+                OIC_LOG_V(DEBUG, TAG, "device address : %s", remoteAddress);
+
+                (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+                (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
+                (*env)->DeleteGlobalRef(env, jarrayObj);
+
+                CAResult_t res = CALEServerReorderinglist(index);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "CALEServerReorderinglist has failed");
+                    ca_mutex_unlock(g_connectedDeviceListMutex);
+                    return res;
+                }
+                ca_mutex_unlock(g_connectedDeviceListMutex);
+                return CA_STATUS_OK;
+            }
+            (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+            (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
+        }
+    }
+
+    ca_mutex_unlock(g_connectedDeviceListMutex);
+
+    OIC_LOG(DEBUG, TAG, "there are no device in the device list");
+
+    OIC_LOG(DEBUG, TAG, "IN CALEServerRemoveDevice");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CALEServerReorderinglist(uint32_t index)
+{
+    if (!g_connectedDeviceList)
+    {
+        OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
+        return CA_STATUS_FAILED;
+    }
+
+    if (index >= g_connectedDeviceList->length)
+    {
+        OIC_LOG(ERROR, TAG, "index is not available");
+        return CA_STATUS_FAILED;
+    }
+
+    if (index < g_connectedDeviceList->length - 1)
+    {
+        memmove(&g_connectedDeviceList->data[index], &g_connectedDeviceList->data[index + 1],
+                (g_connectedDeviceList->length - index - 1) * sizeof(void *));
+    }
+
+    g_connectedDeviceList->size--;
+    g_connectedDeviceList->length--;
+
+    return CA_STATUS_OK;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CARegisterLeGattServerCallback(JNIEnv *env, jobject obj,
+                                                                         jobject callback)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface - Register Le Gatt Server Callback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(callback, TAG, "callback is null");
+
+    g_bluetoothGattServerCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CARegisterBluetoothLeAdvertiseCallback(JNIEnv *env,
+                                                                                 jobject obj,
+                                                                                 jobject callback)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface - Register Le Advertise Callback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(callback, TAG, "callback is null");
+
+    g_leAdvertiseCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerConnectionStateChangeCallback(
+        JNIEnv *env, jobject obj, jobject device, jint status, jint newState)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface - Gatt Server ConnectionStateChange Callback");
+    OIC_LOG_V(DEBUG, TAG, "New connection State: %d", newState);
+
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(device, TAG, "device is null");
+
+    jclass jni_cid_bluetoothProfile = (*env)->FindClass(env, "android/bluetooth/BluetoothProfile");
+    if (!jni_cid_bluetoothProfile)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_bluetoothProfile is null");
+        return;
+    }
+
+    jfieldID jni_fid_state_connected = (*env)->GetStaticFieldID(env, jni_cid_bluetoothProfile,
+                                                                "STATE_CONNECTED", "I");
+    if(!jni_fid_state_connected)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_state_connected is null");
+        return;
+    }
+
+    jfieldID jni_fid_state_disconnected = (*env)->GetStaticFieldID(env, jni_cid_bluetoothProfile,
+                                                                   "STATE_DISCONNECTED", "I");
+    if(!jni_fid_state_disconnected)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_state_disconnected is null");
+        return;
+    }
+
+    // STATE_CONNECTED
+    jint jni_int_state_connected = (*env)->GetStaticIntField(env, jni_cid_bluetoothProfile,
+                                                             jni_fid_state_connected);
+
+    // STATE_DISCONNECTED
+    jint jni_int_state_disconnected = (*env)->GetStaticIntField(env, jni_cid_bluetoothProfile,
+                                                                jni_fid_state_disconnected);
+
+    if (newState == jni_int_state_connected)
+    {
+
+        OIC_LOG(DEBUG, TAG, "LE CONNECTED");
+
+        jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
+        if (!jni_remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
+            return;
+        }
+
+        const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+        if (!remoteAddress)
+        {
+            OIC_LOG(ERROR, TAG, "remoteAddress is null");
+            return;
+        }
+
+        if (false == CALEServerIsDeviceInList(env, remoteAddress))
+        {
+            OIC_LOG(DEBUG, TAG, "add connected device to cache");
+            CALEServerAddDeviceToList(env, device);
+        }
+        (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+    }
+    else if (newState == jni_int_state_disconnected)
+    {
+        OIC_LOG(DEBUG, TAG, "LE DISCONNECTED");
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, TAG, "LE Connection state is [newState : %d, status %d]", newState,
+                status);
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerServiceAddedCallback(JNIEnv *env,
+                                                                             jobject obj,
+                                                                             jint status,
+                                                                             jobject gattService)
+{
+    OIC_LOG_V(DEBUG, TAG, "caleserverinterface - Gatt Service Added Callback(%d)", status);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerCharacteristicReadRequestCallback(
+        JNIEnv *env, jobject obj, jobject device, jint requestId, jint offset,
+        jobject characteristic, jbyteArray data)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface - Gatt Server Characteristic Read Request Callback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(device, TAG, "device is null");
+
+#ifdef USE_PROPERTY_WRITE_RESPONSE
+    CALEServerSendResponse(env, device, requestId, 0, offset, NULL);
+#endif
+
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerCharacteristicWriteRequestCallback(
+        JNIEnv *env, jobject obj, jobject device, jint requestId, jobject characteristic,
+        jbyteArray data, jboolean preparedWrite, jboolean responseNeeded, jint offset,
+        jbyteArray value)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface - Gatt Server Characteristic Write Request Callback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(device, TAG, "device is null");
+    VERIFY_NON_NULL_VOID(value, TAG, "value is null");
+    VERIFY_NON_NULL_VOID(data, TAG, "data is null");
+
+#ifdef USE_PROPERTY_WRITE_RESPONSE
+    CALEServerSendResponse(env, device, requestId, 0, offset, value);
+#endif
+
+    // get Byte Array and covert to char*
+    jint length = (*env)->GetArrayLength(env, data);
+
+    jboolean isCopy;
+    jbyte *jni_byte_requestData = (jbyte *) (*env)->GetByteArrayElements(env, data, &isCopy);
+
+    char* requestData = NULL;
+    requestData = (char*) OICMalloc(sizeof(char) * length + 1);
+    if (!requestData)
+    {
+        OIC_LOG(ERROR, TAG, "requestData is null");
+        return;
+    }
+
+    memcpy(requestData, (const char*) jni_byte_requestData, length);
+    requestData[length] = '\0';
+    (*env)->ReleaseByteArrayElements(env, data, jni_byte_requestData, JNI_ABORT);
+
+    jstring jni_address = CALEGetAddressFromBTDevice(env, device);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "jni_address is null");
+        OICFree(requestData);
+        return;
+    }
+
+    const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+    if (!address)
+    {
+        OIC_LOG(ERROR, TAG, "address is null");
+        OICFree(requestData);
+        return;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "remote device address : %s, %s, %d", address, requestData, length);
+
+    ca_mutex_lock(g_bleClientBDAddressMutex);
+    uint32_t sentLength = 0;
+    g_CABLEServerDataReceivedCallback(address, OIC_GATT_SERVICE_UUID, requestData, length,
+                                      &sentLength);
+    ca_mutex_unlock(g_bleClientBDAddressMutex);
+
+    (*env)->ReleaseStringUTFChars(env, jni_address, address);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerDescriptorReadRequestCallback(
+        JNIEnv *env, jobject obj, jobject device, jint requestId, jint offset, jobject descriptor)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface_CALeGattServerDescriptorReadRequestCallback");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerDescriptorWriteRequestCallback(
+        JNIEnv *env, jobject obj, jobject device, jint requestId, jobject descriptor,
+        jboolean preparedWrite, jboolean responseNeeded, jint offset, jbyteArray value)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface_CALeGattServerDescriptorWriteRequestCallback");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerExecuteWriteCallback(JNIEnv *env,
+                                                                             jobject obj,
+                                                                             jobject device,
+                                                                             jint requestId,
+                                                                             jboolean execute)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface_CALeGattServerExecuteWriteCallback");
+    VERIFY_NON_NULL_VOID(env, TAG, "env is null");
+    VERIFY_NON_NULL_VOID(device, TAG, "device is null");
+
+//    CALEServerSendResponse(env, device, requestId, 0, 0, NULL);
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerNotificationSentCallback(JNIEnv *env,
+                                                                                 jobject obj,
+                                                                                 jobject device,
+                                                                                 jint status)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface - Gatt Server Notification Sent Callback");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeAdvertiseStartSuccessCallback(
+        JNIEnv *env, jobject obj, jobject settingsInEffect)
+{
+    OIC_LOG(DEBUG, TAG, "caleserverinterface - LE Advertise Start Success Callback");
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeAdvertiseStartFailureCallback(JNIEnv *env,
+                                                                            jobject obj,
+                                                                            jint errorCode)
+{
+    OIC_LOG_V(ERROR, TAG, "caleserverinterface - LE Advertise Start Failure Callback(%)",
+              errorCode);
+}
+
+/**
+ * adapter common
+ */
+
+CAResult_t CAStartBleGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t ret = CALEServerInitMutexVaraibles();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerInitMutexVaraibles has failed!");
+        CALEServerTerminateMutexVaraibles();
+        return CA_SERVER_NOT_STARTED;
+    }
+
+    ret = CALEServerInitConditionVaraibles();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "CALEServerInitConditionVaraibles has failed!");
+        CALEServerTerminateConditionVaraibles();
+        return CA_SERVER_NOT_STARTED;
+    }
+
+    // start gatt service
+    CALEServerStartMulticastServer();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopBleGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateBleGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "Terminat Gatt Server");
+    CALEServerTerminate();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_lock(g_bleReqRespCbMutex);
+    g_CABLEServerDataReceivedCallback = callback;
+    ca_mutex_unlock(g_bleReqRespCbMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAUpdateCharacteristicsToGattClient(const char* address, const char *charValue,
+                                               const uint32_t charValueLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(address, TAG, "env is null");
+    VERIFY_NON_NULL(charValue, TAG, "device is null");
+
+    if (address)
+    {
+        OIC_LOG(DEBUG, TAG, "CALEServerSendUnicastData");
+        CALEServerSendUnicastMessage(address, charValue, charValueLen);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
+                                                   const uint32_t charValueLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(charValue, TAG, "device is null");
+
+    OIC_LOG(DEBUG, TAG, "CALEServerSendMulticastMessage");
+    CALEServerSendMulticastMessage(charValue, charValueLen);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CASetBleServerThreadPoolHandle(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CALEServerInitialize(handle);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CALEServerInitMutexVaraibles()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == g_bleReqRespCbMutex)
+    {
+        g_bleReqRespCbMutex = ca_mutex_new();
+        if (NULL == g_bleReqRespCbMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleClientBDAddressMutex)
+    {
+        g_bleClientBDAddressMutex = ca_mutex_new();
+        if (NULL == g_bleClientBDAddressMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_connectedDeviceListMutex)
+    {
+        g_connectedDeviceListMutex = ca_mutex_new();
+        if (NULL == g_connectedDeviceListMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CALEServerInitConditionVaraibles()
+{
+    OIC_LOG(DEBUG, TAG, "this method is not supported");
+    return CA_STATUS_OK;
+}
+
+void CALEServerTerminateMutexVaraibles()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    ca_mutex_free(g_bleReqRespCbMutex);
+    g_bleReqRespCbMutex = NULL;
+
+    ca_mutex_free(g_bleClientBDAddressMutex);
+    g_bleClientBDAddressMutex = NULL;
+
+    ca_mutex_free(g_connectedDeviceListMutex);
+    g_connectedDeviceListMutex = NULL;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CALEServerTerminateConditionVaraibles()
+{
+    OIC_LOG(DEBUG, TAG, "this method is not supported");
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.h b/resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.h
new file mode 100644 (file)
index 0000000..99230ed
--- /dev/null
@@ -0,0 +1,330 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caleserver.h
+ * @brief This file contains the APIs for BT LE communications.
+ */
+#ifndef CA_LESERVER_H_
+#define CA_LESERVER_H_
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+#include "jni.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief Callback to be notified on reception of any data from remote devices.
+ * @param  address           [IN] MAC address of remote device.
+ * @param  data              [IN] Data received from remote device.
+ * @return None
+ * @pre  Callback must be registered using CALEServerSetCallback(CAPacketReceiveCallback callback)
+ */
+typedef void (*CAPacketReceiveCallback)(const char *address, const char *data);
+
+/**
+ * @brief   initialize server for BLE
+ * @param   handle           [IN] thread pool handle object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerInitialize(ca_thread_pool_t handle);
+
+/**
+ * @brief   terminate client for BLE
+ * @return  None
+ */
+void CALEServerTerminate();
+
+/**
+ * @brief   send data for unicast (interface)
+ * @param   address          [IN] remote address
+ * @param   data             [IN] data for transmission
+ * @param   dataLen          [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerSendUnicastMessage(const char *address, const char *data, uint32_t dataLen);
+
+/**
+ * @brief   send data for multicast (interface)
+ * @param   data             [IN] data for transmission
+ * @param   dataLen          [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerSendMulticastMessage(const char *data, uint32_t dataLen);
+
+/**
+ * @brief   start multicast server (start advertise)
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerStartMulticastServer();
+
+/**
+ * @brief   stop multicast server (stop discovery)
+ * @return  None
+ */
+CAResult_t CALEServerStopMulticastServer();
+
+/**
+ * @brief   set this callback for receiving data packets from peer devices.
+ * @param   callback         [IN] callback to be notified on reception of
+ *                                unicast/multicast data packets.
+ * @return  None
+ */
+void CALEServerSetCallback(CAPacketReceiveCallback callback);
+
+/**
+ * @brief   send data for unicast (implement)
+ * @param   env              [IN] JNI interface pointer
+ * @param   address          [IN] remote address
+ * @param   data             [IN] data for transmission
+ * @param   dataLen          [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char *address, const char *data,
+                                            uint32_t dataLen);
+
+/**
+ * @brief   send data for multicast (implement)
+ * @param   env              [IN] JNI interface pointer
+ * @param   data             [IN] data for transmission
+ * @param   dataLen          [IN] data length
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const char *data, uint32_t dataLen);
+
+/* Android BLE Server Functions */
+/**
+ * @brief   set context of application
+ * @return  None
+ */
+void CALEServerJNISetContext();
+
+/**
+ * @brief   initialize JNI object
+ * @return  None
+ */
+void CALeServerJniInit();
+
+/**
+ * @brief   create interface object and initialize the object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerCreateJniInterfaceObject();
+
+/**
+ * @brief   start advertise in gatt server
+ * @param   env                [IN] JNI interface pointer
+ * @param   advertiseCallback  [IN] callback to be notified on reception of
+ *                                advertisement result
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback);
+
+/**
+ * @brief   stop advertise in gatt server
+ * @param   env                [IN] JNI interface pointer
+ * @param   advertiseCallback  [IN] callback to be notified on reception of
+ *                                advertisement result
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerStopAdvertise(JNIEnv *env, jobject advertiseCallback);
+
+/**
+ * @brief   open a gatt server
+ * @param   env                [IN] JNI interface pointer
+ * @return  gatt server object
+ */
+jobject CALEServerOpenGattServer(JNIEnv *env);
+
+/**
+ * @brief   create gatt service
+ * @param   env                [IN] JNI interface pointer
+ * @return  gatt service object
+ */
+jobject CALEServerCreateGattService(JNIEnv *env);
+
+/**
+ * @brief   add a descriptor to the characteristic
+ * @param   env                [IN] JNI interface pointer
+ * @param   characteristic     [IN] Characteristic object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerAddDescriptor(JNIEnv *env, jobject characteristic);
+
+/**
+ * @brief   create gatt service
+ * @param   env                  [IN] JNI interface pointer
+ * @param   bluetoothGattServer  [IN] Bluetooth Gatt Server object
+ * @param   bluetoothGattService [IN] Bluetooth Gatt Service object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerAddGattService(JNIEnv *env, jobject bluetoothGattServer,
+                                    jobject bluetoothGattService);
+
+/**
+ * @brief   start gatt server
+ * @param   env                  [IN] JNI interface pointer
+ * @param   gattServerCallback   [IN] callback to be notified on reception of
+ *                                state change of gatt server
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerStartGattServer(JNIEnv *env, jobject gattServerCallback);
+
+/**
+ * @brief   send data
+ * @param   env                  [IN] JNI interface pointer
+ * @param   bluetoothDevice      [IN] bluetooth device object
+ * @param   data                 [IN] data which send
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jstring data);
+
+/**
+ * @brief   set data in BluetoothGattCharacteristic
+ * @param   env                  [IN] JNI interface pointer
+ * @param   responseData         [IN] data to set in characteristic object
+ * @return  BluetoothGattCharacteristic object
+ */
+jobject CALEServerSetResponseData(JNIEnv *env, jbyteArray responseData);
+
+/**
+ * @brief   send data through notifyCharacteristicChanged api of android
+ * @param   env                  [IN] JNI interface pointer
+ * @param   device               [IN] bluetooth device object
+ * @param   responseData         [IN] data which send
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerSendResponseData(JNIEnv *env, jobject device, jobject responseData);
+
+/**
+ * @brief   send a response to a write request to a remote device
+ * @param   env                  [IN] JNI interface pointer
+ * @param   device               [IN] bluetooth device object
+ * @param   requestId            [IN] the id of request
+ * @param   status               [IN] the status of the request to be sent to the remote devices
+ * @param   offset               [IN] value offset for partial write response
+ * @param   value                [IN] the value of the attribute that written (optional)
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerSendResponse(JNIEnv *env, jobject device, jint requestId, jint status,
+                                  jint offset, jbyteArray value);
+
+/**
+ * @brief   connect BLE to remote device form gatt server
+ * @param   env                  [IN] JNI interface pointer
+ * @param   bluetoothDevice      [IN] bluetooth device object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerConnect(JNIEnv *env, jobject bluetoothDevice);
+
+/**
+ * @brief   disconnect LE for all devices
+ * @param   env                  [IN] JNI interface pointer
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerDisconnectAllDevices(JNIEnv *env);
+
+/**
+ * @brief   disconnect LE to remote device form gatt server
+ * @param   env                  [IN] JNI interface pointer
+ * @param   bluetoothDevice      [IN] bluetooth device object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerDisconnect(JNIEnv *env, jobject bluetoothDevice);
+
+/* BLE Server Utils */
+/**
+ * @brief   create connected device list
+ * @return  None
+ */
+void CALEServerCreateCachedDeviceList();
+
+/**
+ * @brief   check whether the device exist in the list or not
+ * @param   env                   [IN] JNI interface pointer
+ * @param   remoteAddress         [IN] remote address
+ * @return  true or false
+ */
+bool CALEServerIsDeviceInList(JNIEnv *env, const char* remoteAddress);
+
+/**
+ * @brief   add device object to the list (connected device list)
+ * @param   env                   [IN] JNI interface pointer
+ * @param   device                [IN] bluetooth device object
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerAddDeviceToList(JNIEnv *env, jobject device);
+
+/**
+ * @brief   remove all devices objects in the list (connected device list)
+ * @param   env                   [IN] JNI interface pointer
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerRemoveAllDevices(JNIEnv *env);
+
+/**
+ * @brief   remove target device in the list (connected device list)
+ * @param   env                   [IN] JNI interface pointer
+ * @param   address               [IN] target address to remove
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address);
+
+/**
+ * @brief   Reordering for the list (connected device list)
+ * @param   index                 [IN] index of device list that want to reordering
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerReorderinglist(uint32_t index);
+
+/**
+ * @brief   initialize mutex
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerInitMutexVaraibles();
+
+/**
+ * @brief   terminate mutex
+ * @return  None
+ */
+void CALEServerTerminateMutexVaraibles();
+
+/**
+ * @brief   initialize condition
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALEServerInitConditionVaraibles();
+
+/**
+ * @brief   terminate condition
+ * @return  None
+ */
+void CALEServerTerminateConditionVaraibles();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_LESERVER_H_ */
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c b/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c
new file mode 100644 (file)
index 0000000..c7f597f
--- /dev/null
@@ -0,0 +1,375 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <jni.h>
+#include <stdio.h>
+#include <android/log.h>
+
+#include "caleutils.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+#include "caadapterutils.h"
+
+#define TAG PCF("CA_LE_UTILS")
+
+#define METHODID_OBJECTNONPARAM   "()Landroid/bluetooth/BluetoothAdapter;"
+#define METHODID_STRINGNONPARAM   "()Ljava/lang/String;"
+#define CLASSPATH_BT_ADPATER "android/bluetooth/BluetoothAdapter"
+
+jobject CALEGetUuidFromString(JNIEnv *env, const char* uuid)
+{
+    VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL);
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    OIC_LOG(DEBUG, TAG, "CALEGetUuidFromString");
+
+    jclass jni_cid_UUID = (*env)->FindClass(env, "java/util/UUID");
+    if (!jni_cid_UUID)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_UUID is not available");
+        return NULL;
+    }
+
+    jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_UUID, "fromString",
+                                                             "(Ljava/lang/String;)"
+                                                             "Ljava/util/UUID;");
+    if (!jni_mid_fromString)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_fromString is not available");
+        return NULL;
+    }
+
+    jstring str_uuid = (*env)->NewStringUTF(env, uuid);
+    if (!str_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "str_uuid is not available");
+        return NULL;
+    }
+
+    jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_UUID, jni_mid_fromString,
+                                                          str_uuid);
+    if (!jni_obj_uuid)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to get jni uuid object");
+        return NULL;
+    }
+
+    return jni_obj_uuid;
+}
+
+jobject CALEGetParcelUuid(JNIEnv *env, jobject uuid)
+{
+    OIC_LOG(DEBUG, TAG, "CALEGetParcelUuid");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL);
+
+    jclass jni_cid_ParcelUuid = (*env)->FindClass(env, "android/os/ParcelUuid");
+    if (!jni_cid_ParcelUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_ParcelUuid is not available");
+        return NULL;
+    }
+
+    jmethodID jni_mid_ParcelUuid = (*env)->GetMethodID(env, jni_cid_ParcelUuid, "<init>",
+                                                       "(Ljava/util/UUID;)V");
+    if (!jni_mid_ParcelUuid)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_ParcelUuid is not available");
+        return NULL;
+    }
+
+    jobject jni_ParcelUuid = (*env)->NewObject(env, jni_cid_ParcelUuid, jni_mid_ParcelUuid, uuid);
+    if (!jni_ParcelUuid)
+    {
+        OIC_LOG(ERROR, TAG, "Fail to get jni ParcelUuid");
+        return NULL;
+    }
+
+    return jni_ParcelUuid;
+}
+
+bool CALEIsBondedDevice(JNIEnv *env, jobject bluetoothDevice)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", false);
+    VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", false);
+
+    jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
+    if (!jni_cid_device_list)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_device_list is null");
+        return false;
+    }
+
+    jmethodID jni_mid_getBondState = (*env)->GetMethodID(env, jni_cid_device_list, "getBondState",
+                                                         "()I");
+    if (!jni_mid_getBondState)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getBondState is null");
+        return false;
+    }
+
+    jint jni_bondState = (jint)(*env)->CallIntMethod(env, bluetoothDevice, jni_mid_getBondState);
+
+    OIC_LOG_V(DEBUG, TAG, "bond state is %d", jni_bondState);
+
+    if (BOND_BONDED == jni_bondState)
+    {
+        OIC_LOG(DEBUG, TAG, "remote device is bonded");
+        return true;
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "remote device is not bonded");
+        return false;
+    }
+
+    return false;
+}
+
+jobjectArray CALEGetBondedDevices(JNIEnv *env)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getBondedDevices: jni_cid_BTAdapter is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getBondedDevices: bluetooth adapter is null");
+        return NULL;
+    }
+
+    // Get a list of currently paired devices
+    jmethodID jni_mid_getBondedDevices = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+                                                             "getBondedDevices",
+                                                             "()Ljava/util/Set;");
+    if (!jni_mid_getBondedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "getBondedDevices: jni_mid_getBondedDevicesr is null");
+        return NULL;
+    }
+
+    jobject jni_obj_setPairedDevices = (*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+                                                                jni_mid_getBondedDevices);
+    if (!jni_obj_setPairedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "getBondedDevices: jni_obj_setPairedDevices is null");
+        return NULL;
+    }
+
+    jclass jni_cid_Set = (*env)->FindClass(env, "java/util/Set");
+    if (!jni_cid_Set)
+    {
+        OIC_LOG(ERROR, TAG, "getBondedDevices : jni_cid_Set is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray",
+                                                    "()[Ljava/lang/Object;");
+    if (!jni_mid_toArray)
+    {
+        OIC_LOG(ERROR, TAG, "getBondedDevices: jni_mid_toArray is null");
+        return NULL;
+    }
+
+    jobjectArray jni_arrayPairedDevices = (jobjectArray)(
+            (*env)->CallObjectMethod(env, jni_obj_setPairedDevices, jni_mid_toArray));
+    if (!jni_arrayPairedDevices)
+    {
+        OIC_LOG(ERROR, TAG, "getBondedDevices: jni_arrayPairedDevices is null");
+        return NULL;
+    }
+
+    return jni_arrayPairedDevices;
+}
+
+jint CALEGetBTStateOnInfo(JNIEnv *env)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", -1);
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "getBTStateOnInfo: jni_cid_BTAdapter is null");
+        return -1;
+    }
+
+    jfieldID jni_fid_stateon = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_ON", "I");
+    if (!jni_fid_stateon)
+    {
+        OIC_LOG(ERROR, TAG, "get_field_state is not available");
+        return -1;
+    }
+
+    jint jni_int_val = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, jni_fid_stateon);
+    OIC_LOG_V(DEBUG, TAG, "bluetooth.STATE_ON state integer value : %d", jni_int_val);
+
+    return jni_int_val;
+}
+
+CAResult_t CALECheckPlatformVersion(JNIEnv *env, uint16_t level)
+{
+    jint jni_int_sdk = CALEGetBuildVersion(env);
+    if (jni_int_sdk < level)
+    {
+        OIC_LOG(ERROR, TAG, "it is not supported");
+        return CA_NOT_SUPPORTED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+jint CALEGetBuildVersion(JNIEnv *env)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", -1);
+
+    // VERSION is a nested class within android.os.Build (hence "$" rather than "/")
+    jclass jni_cls_version = (*env)->FindClass(env, "android/os/Build$VERSION");
+    if (!jni_cls_version)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_version is null");
+        return -1;
+    }
+
+    jfieldID jni_fid_sdk = (*env)->GetStaticFieldID(env, jni_cls_version, "SDK_INT", "I");
+    if (!jni_fid_sdk)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_sdk is null");
+        return -1;
+    }
+
+    jint jni_int_sdk = (*env)->GetStaticIntField(env, jni_cls_version, jni_fid_sdk);
+    OIC_LOG_V(DEBUG, TAG, "sdk version is %d", jni_int_sdk);
+
+    return jni_int_sdk;
+}
+
+jint CALEGetBuildVersionCodeForName(JNIEnv *env, const char* versionName)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", -1);
+    VERIFY_NON_NULL_RET(versionName, TAG, "versionName is null", -1);
+
+    // VERSION is a nested class within android.os.Build (hence "$" rather than "/")
+    jclass jni_cls_version = (*env)->FindClass(env, "android/os/Build$VERSION_CODES");
+    if (!jni_cls_version)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cls_version is null");
+        return -1;
+    }
+
+    jfieldID jni_fid_version = (*env)->GetStaticFieldID(env, jni_cls_version, versionName, "I");
+    if (!jni_fid_version)
+    {
+        OIC_LOG(ERROR, TAG, "jni_fid_version is null");
+        return -1;
+    }
+
+    jint jni_int_version = (*env)->GetStaticIntField(env, jni_cls_version, jni_fid_version);
+    OIC_LOG_V(DEBUG, TAG, "version [%s] is %d",versionName, jni_int_version);
+
+    return jni_int_version;
+}
+
+jboolean CALEIsEnableBTAdapter(JNIEnv *env)
+{
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", JNI_FALSE);
+
+    jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+    if (!jni_cid_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null");
+        return JNI_FALSE;
+    }
+
+    jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+                                                                    "getDefaultAdapter",
+                                                                    METHODID_OBJECTNONPARAM);
+    if (!jni_mid_getDefaultAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        return JNI_FALSE;
+    }
+
+    jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+                                                               jni_mid_getDefaultAdapter);
+    if (!jni_obj_BTAdapter)
+    {
+        OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        return JNI_FALSE;
+    }
+
+    // isEnable()
+    jmethodID jni_mid_isEnable = (*env)->GetMethodID(env, jni_cid_BTAdapter, "isEnabled", "()Z");
+    if (!jni_mid_isEnable)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_isEnable is null");
+        return JNI_FALSE;
+    }
+
+    jboolean jni_isEnable = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_isEnable);
+    OIC_LOG_V(DEBUG, TAG, "adapter state is %d", jni_isEnable);
+
+    return jni_isEnable;
+}
+
+jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEGetAddressFromBTDevice");
+    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
+    VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", NULL);
+
+    jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
+    if (!jni_cid_device_list)
+    {
+        OIC_LOG(ERROR, TAG, "jni_cid_device_list is null");
+        return NULL;
+    }
+
+    jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_device_list, "getAddress",
+                                                       "()Ljava/lang/String;");
+    if (!jni_mid_getAddress)
+    {
+        OIC_LOG(ERROR, TAG, "jni_mid_getAddress is null");
+        return NULL;
+    }
+
+    jstring jni_address = (jstring)(*env)->CallObjectMethod(env, bluetoothDevice,
+                                                            jni_mid_getAddress);
+    if (!jni_address)
+    {
+        OIC_LOG(ERROR, TAG, "jni_address is null");
+        return NULL;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEGetAddressFromBTDevice");
+    return jni_address;
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h b/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h
new file mode 100644 (file)
index 0000000..4e25589
--- /dev/null
@@ -0,0 +1,129 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file caleutils.h
+ * @brief This file contains the APIs for BT LE communications.
+ */
+#ifndef CA_LE_UTILS_H_
+#define CA_LE_UTILS_H_
+
+#include "cacommon.h"
+#include "cathreadpool.h"
+#include "uarraylist.h"
+#include "jni.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* Service UUID */
+static const char OIC_GATT_SERVICE_UUID[] = "713d0000-503e-4c75-ba94-3148f18d941e";
+static const char OIC_GATT_CHARACTERISTIC_RESPONSE_UUID[] = "713d0002-503e-4c75-ba94-3148f18d941e";
+static const char OIC_GATT_CHARACTERISTIC_REQUEST_UUID[] = "713d0003-503e-4c75-ba94-3148f18d941e";
+static const char OIC_GATT_CHARACTERISTIC_CONFIG_UUID[] = "00002902-0000-1000-8000-00805f9b34fb";
+
+static const uint32_t GATT_SUCCESS = 0;
+
+static const uint32_t BOND_BONDED = 12;
+static const uint32_t BOND_BONDING = 11;
+static const uint32_t BOND_NONE = 10;
+
+/**
+ * @brief   get uuid(jni object) from uuid(character)
+ * @param   env              [IN] JNI interface pointer
+ * @param   uuid             [IN] uuid(character)
+ * @return  uuid(jni object)
+ */
+jobject CALEGetUuidFromString(JNIEnv *env, const char* uuid);
+
+/**
+ * @brief   get parcel uuid object
+ * @param   env              [IN] JNI interface pointer
+ * @param   uuid             [IN] uuid (jni object)
+ * @return  parcel uuid object
+ */
+jobject CALEGetParcelUuid(JNIEnv *env, jobject uuid);
+
+/**
+ * @brief   get address from a local device
+ * @param   env              [IN] JNI interface pointer
+ * @return  local address
+ */
+jstring CALEGetLocalDeviceAddress(JNIEnv *env);
+
+/**
+ * @brief   get bonded list
+ * @param   env              [IN] JNI interface pointer
+ * @return  bonded list
+ */
+jobjectArray CALEGetBondedDevices(JNIEnv *env);
+
+/**
+ * @brief   get constants information of bluetooth state-on
+ * @param   env              [IN] JNI interface pointer
+ * @return  constants information of bluetooth state-on
+ */
+jint CALEGetBTStateOnInfo(JNIEnv *env);
+
+/**
+ * @brief   check this device can be supported as BLE client or server
+ * @param   env              [IN] JNI interface pointer
+ * @param   level            [IN] Android API Level to support
+ * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CALECheckPlatformVersion(JNIEnv *env, uint16_t level);
+
+/**
+ * @brief   get constants information of android.os.Build.VERSION.SDK_INT
+ * @param   env              [IN] JNI interface pointer
+ * @return  constants information of android.os.Build.VERSION.SDK_INT
+ */
+jint CALEGetBuildVersion(JNIEnv *env);
+
+/**
+ * @brief   get constants information of android.os.Build.VERSION_CODES.[VersionName]
+ * @param   env              [IN] JNI interface pointer
+ * @param   versionName      [IN] version name (.., KITKAT, LOLLIPOP, ..)
+ * @return  constants information of android.os.Build.VERSION_CODES.[VersionName]
+ */
+jint CALEGetBuildVersionCodeForName(JNIEnv *env, const char* versionName);
+
+/**
+ * @brief   get bluetooth adapter state information
+ * @param   env              [IN] JNI interface pointer
+ * @return  JNI_TRUE if the local adapter is turned on
+ */
+jboolean CALEIsEnableBTAdapter(JNIEnv *env);
+
+/**
+ * @brief   get address from remote device
+ * @param   env              [IN] JNI interface pointer
+ * @param   bluetoothDevice  [IN] bluetooth device object
+ * @return  remote address
+ */
+jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CA_LE_UTILS_H_ */
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_jar_caleclientinterface.h b/resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_jar_caleclientinterface.h
new file mode 100644 (file)
index 0000000..e57b2d1
--- /dev/null
@@ -0,0 +1,141 @@
+#include <jni.h>
+/* Header for class org_iotivity_jar_caleclientinterface */
+
+#ifndef CA_Included_org_iotivity_jar_caleclientinterface_H_
+#define CA_Included_org_iotivity_jar_caleclientinterface_H_
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CARegisterLeScanCallback
+ * Signature: (Landroid/bluetooth/BluetoothAdapter/LeScanCallback;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CARegisterLeScanCallback
+(JNIEnv *, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CARegisterLeGattCallback
+ * Signature: (Landroid/bluetooth/BluetoothGattCallback;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CARegisterLeGattCallback
+(JNIEnv *, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeScanCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;I[B)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeScanCallback
+(JNIEnv *, jobject, jobject, jint, jbyteArray);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattConnectionStateChangeCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattConnectionStateChangeCallback
+(JNIEnv *, jobject, jobject, jint, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattServicesDiscoveredCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattServicesDiscoveredCallback
+(JNIEnv *, jobject, jobject, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattCharacteristicReadCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattCharacteristicReadCallback
+(JNIEnv *, jobject, jobject, jobject, jbyteArray, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattCharacteristicWritjclasseCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattCharacteristicWriteCallback
+(JNIEnv *, jobject, jobject, jobject, jbyteArray, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattCharacteristicChangedCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattCharacteristicChangedCallback
+(JNIEnv *, jobject, jobject, jobject, jbyteArray);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattDescriptorReadCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattDescriptorReadCallback
+(JNIEnv *, jobject, jobject, jobject, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattDescriptorWriteCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattDescriptorWriteCallback
+(JNIEnv *, jobject, jobject, jobject, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattReliableWriteCompletedCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattReliableWriteCompletedCallback
+(JNIEnv *, jobject, jobject, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeGattReadRemoteRssiCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeGattReadRemoteRssiCallback
+(JNIEnv *, jobject, jobject, jint, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeStateChangedCallback
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeStateChangedCallback
+(JNIEnv *, jobject, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleclientinterface
+ * Method:    CALeBondStateChangedCallback
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleclientinterface_CALeBondStateChangedCallback
+(JNIEnv *, jobject, jstring);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_jar_caleserverinterface.h b/resource/csdk/connectivity/src/bt_le_adapter/android/org_iotivity_jar_caleserverinterface.h
new file mode 100644 (file)
index 0000000..2f82092
--- /dev/null
@@ -0,0 +1,129 @@
+#include <jni.h>
+/* Header for class org_iotivity_jar_caleserverinterface */
+
+#ifndef CA_Included_org_iotivity_jar_caleserverinterface_H_
+#define CA_Included_org_iotivity_jar_caleserverinterface_H_
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CARegisterLeGattServerCallback
+ * Signature: (Landroid/bluetooth/BluetoothGattServerCallback;)V
+ */
+JNIEXPORT void JNICALL
+
+Java_org_iotivity_jar_caleserverinterface_CARegisterLeGattServerCallback
+(JNIEnv *, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CARegisterBluetoothLeAdvertiseCallback
+ * Signature: (Landroid/bluetooth/le/AdvertiseCallback;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CARegisterBluetoothLeAdvertiseCallback
+(JNIEnv *, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerConnectionStateChangeCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;II)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerConnectionStateChangeCallback
+(JNIEnv *, jobject, jobject, jint, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerServiceAddedCallback
+ * Signature: (ILandroid/bluetooth/BluetoothGattService;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerServiceAddedCallback
+(JNIEnv *, jobject, jint, jobject);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerCharacteristicReadRequestCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;IILandroid/
+ * bluetooth/BluetoothGattCharacteristic;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerCharacteristicReadRequestCallback
+(JNIEnv *, jobject, jobject, jint, jint, jobject, jbyteArray);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerCharacteristicWriteRequestCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;ILandroid/bluetooth/
+ * BluetoothGattCharacteristic;ZZI[B)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerCharacteristicWriteRequestCallback
+(JNIEnv *, jobject, jobject, jint, jobject, jbyteArray, jboolean, jboolean, jint, jbyteArray);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerDescriptorReadRequestCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;IILandroid/bluetooth/
+ * BluetoothGattDescriptor;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerDescriptorReadRequestCallback
+(JNIEnv *, jobject, jobject, jint, jint, jobject);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerDescriptorWriteRequestCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;ILandroid/bluetooth/
+ * BluetoothGattDescriptor;ZZI[B)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerDescriptorWriteRequestCallback
+(JNIEnv *, jobject, jobject, jint, jobject, jboolean, jboolean, jint, jbyteArray);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerExecuteWriteCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;IZ)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerExecuteWriteCallback
+(JNIEnv *, jobject, jobject, jint, jboolean);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeGattServerNotificationSentCallback
+ * Signature: (Landroid/bluetooth/BluetoothDevice;I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeGattServerNotificationSentCallback
+(JNIEnv *, jobject, jobject, jint);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeAdvertiseStartSuccessCallback
+ * Signature: (Landroid/bluetooth/le/AdvertiseSettings;)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeAdvertiseStartSuccessCallback
+(JNIEnv *, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_jar_caleserverinterface
+ * Method:    CALeAdvertiseStartFailureCallback
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL
+Java_org_iotivity_jar_caleserverinterface_CALeAdvertiseStartFailureCallback
+(JNIEnv *, jobject, jint);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp b/resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp
new file mode 100644 (file)
index 0000000..a61c483
--- /dev/null
@@ -0,0 +1,113 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+//logger.h included first to avoid conflict with RBL library PROGMEM attribute
+#include "logger.h"
+
+#include "caleinterface_singlethread.h"
+
+#include <Arduino.h>
+#include <SPI.h>
+#include <boards.h>
+#include <RBL_nRF8001.h>
+
+#include "caleadapter_singlethread.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+/**
+ * @def TAG
+ * @brief Logging tag for module name
+ */
+#define TAG "LENW"
+
+/**
+ * @var g_caLEDeviceStateChangedCallback
+ * @brief Maintains the callback to be notified on device state changed.
+ */
+static CALEDeviceStateChangedCallback g_caLEDeviceStateChangedCallback = NULL;
+
+/**
+ * @var g_leAddress
+ * @brief Maintains the local BLE Shield Address
+ */
+static unsigned char *g_leAddress = NULL;
+
+CAResult_t CALEInitializeNetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALETerminateNetworkMonitor()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAGetLEAdapterState()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetLEAddress(char **leAddress)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(leAddress, TAG, "leAddress");
+
+    g_leAddress = ble_getAddress();
+    /**
+     *   Below Allocated Memory will be freed by caller API
+     */
+    *leAddress = (char*)OICMalloc(CA_MACADDR_SIZE);
+    if (NULL == *leAddress)
+    {
+        OIC_LOG(ERROR, TAG, "malloc fail");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memcpy(*leAddress, g_leAddress, CA_MACADDR_SIZE);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    g_caLEDeviceStateChangedCallback = callback;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUnSetLEAdapterStateChangedCb()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    g_caLEDeviceStateChangedCallback = NULL;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.cpp b/resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.cpp
new file mode 100644 (file)
index 0000000..1ad39b3
--- /dev/null
@@ -0,0 +1,92 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+
+//logger.h included first to avoid conflict with RBL library PROGMEM attribute
+#include "logger.h"
+
+#include "cableserver.h"
+
+#include <Arduino.h>
+#include <SPI.h>
+#include <boards.h>
+#include <RBL_nRF8001.h>
+
+#include "caleinterface_singlethread.h"
+#include "oic_malloc.h"
+#include "caadapterutils.h"
+
+#define TAG "LES"
+
+CAResult_t CAInitializeBle()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    // Set your BLE Shield name here, max. length 10
+    ble_set_name(__OIC_DEVICE_NAME__);
+
+    OIC_LOG(DEBUG, TAG, "LEName Set");
+
+    ble_begin();
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CATerminateBle()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    ble_radio_reset();
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+
+}
+
+unsigned char CAIsBleDataAvailable()
+{
+    return ble_available();
+}
+
+unsigned char CAIsBleConnected()
+{
+    return ble_connected();
+}
+char CAReadBleData()
+{
+    return (char)ble_read();
+}
+
+CAResult_t CABleDoEvents()
+{
+    ble_do_events();
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *char_value,
+                                                   uint8_t valueLength)
+{
+    // ble_write_bytes() api can send only max of 255 bytes at a time
+    // This function shall never be called to send more than 255 bytes by the fragmentation logic.
+    // Currently ble_write_bytes api returns void.
+    ble_write_bytes((unsigned char *)char_value, (unsigned char)valueLength);
+    return CA_STATUS_OK;
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.h b/resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.h
new file mode 100644 (file)
index 0000000..60e19b2
--- /dev/null
@@ -0,0 +1,93 @@
+/* ****************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the APIs related to the GATT Server functionalities.
+ * Creation of the GATT Server with the characteristics. Enabling the
+ * advertisement and updating the characteristics for the response and
+ * notifying the change of characteristcs for the request will be done here.
+ */
+
+#ifndef BLE_ADAPTER_ARDUINO_H_
+#define BLE_ADAPTER_ARDUINO_H_
+
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief API to initialize Arduino BLE module and advertise the service
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAInitializeBle();
+
+/**
+ * @brief API to Terminate Arduino BLE module and advertise the service
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CATerminateBle();
+
+/**
+ * @brief Send the received data to Connectivity Abstraction layer.
+ * @param data       [IN] Data received from BLE characteristics
+ * @param dataLen    [IN] Received data Length
+ * @param senderAdrs [IN] Sender Address.
+ * @param senderPort [IN] Sender port
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+void CANotifyCallback(const void *data, int32_t dataLen, const char *senderAdrs,
+                      int32_t senderPort);
+
+/**
+ * @brief API to check whether data is available in BLE shield
+ * @return - Received buffer length
+ */
+unsigned char CAIsBleDataAvailable();
+
+/**
+ * @brief API to check whether client is connected with BLE Shield
+ * @return - Connection state
+ */
+unsigned char CAIsBleConnected();
+
+/**
+ * @brief API to read data from BLE shield
+ * @return - Data read
+ */
+char CAReadBleData();
+
+/**
+ * @brief API to perform BLE events
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CABleDoEvents();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* BLE_ADAPTER_ARDUINO_H_ */
+
index ff60572..282cf88 100644 (file)
  ******************************************************************/
 #include "caleadapter.h"
 
-#ifdef __TIZEN__
-#include <arpa/inet.h>
-#include <sys/socket.h>
-#include <netdb.h>
-#include <ifaddrs.h>
-#include <unistd.h>
-#include <pthread.h>
-#endif //#ifdef __TIZEN__
 #include <stdio.h>
 #include <stdlib.h>
 
-#ifdef __TIZEN__
-#include "cableserver.h"
-#include "cableclient.h"
+#include "caleinterface.h"
 #include "cacommon.h"
-#else // __ARDUINO__
-#include "BLEAdapterArduino.h"
+#include "camutex.h"
 #include "caadapterutils.h"
-#endif //#ifdef __TIZEN__
+#include "caqueueingthread.h"
+#include "camsgparser.h"
+#include "oic_malloc.h"
+
+/**
+ * @var CALEADAPTER_TAG
+ * @brief Logging tag for module name.
+ */
 #define CALEADAPTER_TAG "CA_BLE_ADAPTER"
 
-static CANetworkChangeCallback gNetworkCallback = NULL;
-static char gLocalBLEAddress[16] =
-{ 0, };
-
-static int gIsServer = 0;
-
-int CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
-
-#ifdef __TIZEN__
-int CALEDeviceStateChangedCb(int result, bt_adapter_state_e adapter_state, void *user_data);
-#endif //#ifdef __TIZEN__
-
-pthread_mutex_t gBleIsServerMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
-
-pthread_mutex_t gBleNetworkCbMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
-
-pthread_mutex_t gBleLocalAddressMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
+/**
+ * @var g_networkCallback
+ * @brief Callback to provide the status of the network change to CA layer.
+ */
+static CANetworkChangeCallback g_networkCallback = NULL;
+
+/**
+ * @var g_localBLEAddress
+ * @brief bleAddress of the local adapter. Value will be initialized to zero, and will be updated later.
+ */
+static char g_localBLEAddress[16] = {0};
+
+/**
+ * @var g_isServer
+ * @brief Variable to differentiate btw GattServer and GattClient.
+ */
+static bool g_isServer = false;
+
+/**
+ * @var g_bleIsServerMutex
+ * @brief Mutex to synchronize the task to be executed on the GattServer function calls.
+ */
+static ca_mutex g_bleIsServerMutex = NULL;
+
+/**
+ * @var g_bleNetworkCbMutex
+ * @brief Mutex to synchronize the callback to be called for the network changes.
+ */
+static ca_mutex g_bleNetworkCbMutex = NULL;
+
+/**
+ * @var g_bleLocalAddressMutex
+ * @brief Mutex to synchronize the updation of the local LE address of the adapter.
+ */
+static ca_mutex g_bleLocalAddressMutex = NULL;
+
+/**
+ * @var g_bleAdapterThreadPool
+ * @brief reference to threadpool
+ */
+static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
+
+/**
+ * @var g_bleAdapterThreadPoolMutex
+ * @brief Mutex to synchronize the task to be pushed to thread pool.
+ */
+static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
+
+/**
+ * @var g_bleClientSendQueueHandle
+ * @brief Queue to process the outgoing packets from GATTClient.
+ */
+static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
+
+/**
+ * @var g_bleClientReceiverQueue
+ * @brief Queue to process the incoming packets to GATT Client.
+ */
+static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
+
+/**
+ * @var g_bleClientSendDataMutex
+ * @brief Mutex to synchronize the queing of the data from SenderQueue.
+ */
+static ca_mutex g_bleClientSendDataMutex = NULL;
+
+/**
+ * @var g_bleClientReceiveDataMutex
+ * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
+ */
+static ca_mutex g_bleClientReceiveDataMutex = NULL;
+
+/**
+ * @var g_dataReceiverHandlerState
+ * @brief Stop condition of recvhandler.
+ */
+static bool g_dataReceiverHandlerState = false;
+
+/**
+ * @var g_sendQueueHandle
+ * @brief Queue to process the outgoing packets from GATTServer.
+ */
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
+
+/**
+ * @var g_bleServerReceiverQueue
+ * @brief Queue to process the incoming packets to GATTServer
+ */
+static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
+
+/**
+ * @var g_bleServerSendDataMutex
+ * @brief Mutex to synchronize the queing of the data from SenderQueue.
+ */
+static ca_mutex g_bleServerSendDataMutex = NULL;
+
+/**
+ * @var g_bleServerReceiveDataMutex
+ * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
+ */
+static ca_mutex g_bleServerReceiveDataMutex = NULL;
+
+/**
+ * @var g_bleAdapterReqRespCbMutex
+ * @brief Mutex to synchronize the callback to be called for the adapterReqResponse.
+ */
+static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
+
+/**
+ * @var g_networkPacketReceivedCallback
+ * @brief Callback to be called when network packet recieved from either GattServer or GattClient.
+ */
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
+
+/**
+ * @ENUM CALeServerStatus
+ * @brief status of BLE Server Status
+ *  This ENUM provides information of LE Adapter Server status
+ */
+typedef enum
+{
+    CA_SERVER_NOTSTARTED = 0,
+    CA_LISTENING_SERVER,
+    CA_DISCOVERY_SERVER
+} CALeServerStatus;
+
+/**
+ * @var gLeServerStatus
+ * @brief structure to maintain the status of the server.
+ */
+static CALeServerStatus gLeServerStatus = CA_SERVER_NOTSTARTED;
+
+/**
+* @fn  CALERegisterNetworkNotifications
+* @brief  This function is used to register network change notification callback.
+*
+* @param[in]  netCallback CANetworkChangeCallback callback which will be set for the change in nwk.
+*
+* @return  0 on success otherwise a positive error value.
+* @retval  CA_STATUS_OK  Successful
+* @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
+* @retval  CA_STATUS_FAILED Operation failed
+*
+*/
+CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
+
+/**
+* @fn  CASetBleAdapterThreadPoolHandle
+* @brief  Used to Set the gThreadPool handle which is required for spawning new thread.
+*
+* @param[in] handle - Thread pool handle which is given by above layer for using thread creation task.
+*
+* @return  void
+*
+*/
+void CASetBleAdapterThreadPoolHandle(ca_thread_pool_t handle);
+
+/**
+* @fn  CALEDeviceStateChangedCb
+* @brief  This function is used to call the callback to the upper layer when the device state gets
+*         changed.
+*
+* @param[in]  adapter_state New state of the adapter to be notified to the upper layer.
+*
+* @return  None.
+*
+*/
+void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state);
+
+/**
+* @fn  CAInitBleAdapterMutex
+* @brief  Used to initialize all required mutex variable for LE Adapter implementation.
+*
+* @return  0 on success otherwise a positive error value.
+* @retval  CA_STATUS_OK  Successful
+* @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
+* @retval  CA_STATUS_FAILED Operation failed
+*
+*/
+CAResult_t CAInitBleAdapterMutex();
+
+/**
+* @fn  CATerminateBleAdapterMutex
+* @brief  Used to terminate all required mutex variable for LE adapter implementation.
+*
+* @return  void
+*/
+void CATerminateBleAdapterMutex();
+
+/**
+* @fn  CALEDataDestroyer
+* @brief  Used to free data
+*
+* @return  void
+*/
+static void CALEDataDestroyer(void *data, uint32_t size);
 
 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback)
+                          CANetworkPacketReceivedCallback reqRespCallback,
+                          CANetworkChangeCallback netCallback,
+                          ca_thread_pool_t handle)
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
     //Input validation
     VERIFY_NON_NULL(registerCallback, NULL, "RegisterConnectivity callback is null");
     VERIFY_NON_NULL(reqRespCallback, NULL, "PacketReceived Callback is null");
     VERIFY_NON_NULL(netCallback, NULL, "NetworkChange Callback is null");
 
-#ifdef __TIZEN__
+    CAResult_t result = CAInitBleAdapterMutex();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
+        return CA_STATUS_FAILED;
+    }
 
-    int ret = bt_initialize();
-    if (0 != ret)
+    result = CAInitializeLENetworkMonitor();
+    if (CA_STATUS_OK != result)
     {
-        OCLog(ERROR, CALEADAPTER_TAG, "bt_initialize failed!");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
         return CA_STATUS_FAILED;
     }
 
-#endif //#ifdef __TIZEN__
-    CASetBLEReqRescallback(reqRespCallback);
+    CAInitializeLEAdapter();
+
+    CASetBleClientThreadPoolHandle(handle);
+    CASetBleServerThreadPoolHandle(handle);
+    CASetBleAdapterThreadPoolHandle(handle);
+    CASetBLEReqRespServerCallback(CABLEServerReceivedData);
+    CASetBLEReqRespClientCallback(CABLEClientReceivedData);
+    CASetBLEReqRespAdapterCallback(reqRespCallback);
+
     CALERegisterNetworkNotifications(netCallback);
 
     CAConnectivityHandler_t connHandler;
+    connHandler.startAdapter = CAStartLE;
+    connHandler.stopAdapter = CAStopLE;
     connHandler.startListenServer = CAStartLEListeningServer;
-    connHandler.startDiscoverServer = CAStartLEDiscoveryServer;
+    connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
     connHandler.sendData = CASendLEUnicastData;
     connHandler.sendDataToAll = CASendLEMulticastData;
-    connHandler.startNotifyServer = CAStartLENotifyServer;
-    connHandler.sendNotification = CASendLENotification;
     connHandler.GetnetInfo = CAGetLEInterfaceInformation;
     connHandler.readData = CAReadLEData;
     connHandler.terminate = CATerminateLE;
     registerCallback(connHandler, CA_LE);
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 
     return CA_STATUS_OK;
 }
 
-void CATerminateLE()
+CAResult_t CAStartLE()
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG,
+        "There is no concept of unicast/multicast in LE. So This function is not implemented");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
 
-    CASetBLEReqRescallback(NULL);
-    CALERegisterNetworkNotifications(NULL);
+CAResult_t CAStopLE()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    CAStopBleQueues();
 
-    pthread_mutex_lock(&gBleIsServerMutex);
-    if (gIsServer == 1)
+    ca_mutex_lock(g_bleIsServerMutex);
+    if (true == g_isServer)
     {
         CAStopBleGattServer();
     }
@@ -114,304 +311,1495 @@ void CATerminateLE()
     {
         CAStopBLEGattClient();
     }
-    pthread_mutex_unlock(&gBleIsServerMutex);
+    ca_mutex_unlock(g_bleIsServerMutex);
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
-    return;
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+
+    return CA_STATUS_OK;
 }
 
-void CALEServerInitThreadFunc(void *param)
+void CATerminateLE()
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "[CALEServerInitThreadFunc]IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    CAStartBleGattServer();
+    CASetBLEReqRespServerCallback(NULL);
+    CASetBLEReqRespClientCallback(NULL);
+    CALERegisterNetworkNotifications(NULL);
+    CASetBLEReqRespAdapterCallback(NULL);
+    CATerminateLENetworkMonitor();
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "[CALEServerInitThreadFunc] OUT");
-}
+    ca_mutex_lock(g_bleIsServerMutex);
+    if (true == g_isServer)
+    {
+        CATerminateBleGattServer();
+    }
+    else
+    {
+        CATerminateBLEGattClient();
+    }
+    ca_mutex_unlock(g_bleIsServerMutex);
 
-void CALEClientInitThreadFunc(void *param)
-{
-    OCLog(DEBUG, CALEADAPTER_TAG, "[CALEClientInitThreadFunc]IN");
+    CATerminateBleQueues();
 
-    CAStartBLEGattClient();
+    CATerminateBleAdapterMutex();
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "[CALEClientInitThreadFunc] OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
 
 CAResult_t CAStartLEListeningServer()
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    int init_pthread_status = 0;
-    pthread_t pthread_id = 0;
-    pthread_attr_t attr;
-    pthread_attr_init(&attr);
-    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+    CAResult_t result = CAInitBleServerQueues();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
+        return CA_STATUS_FAILED;
+    }
 
-    init_pthread_status = pthread_create(&pthread_id, &attr, CALEServerInitThreadFunc, NULL);
+    result = CAGetLEAdapterState();
+    if (CA_ADAPTER_NOT_ENABLED == result)
+    {
+        gLeServerStatus = CA_LISTENING_SERVER;
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
+        return CA_STATUS_OK;
+    }
 
-    if (init_pthread_status != 0)
+    if (CA_STATUS_FAILED == result)
     {
-        OCLog(ERROR, CALEADAPTER_TAG, "pthread_create failed!");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
         return CA_STATUS_FAILED;
     }
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
-    pthread_mutex_lock(&gBleIsServerMutex);
-    gIsServer = 1;
-    pthread_mutex_unlock(&gBleIsServerMutex);
+    CAStartBleGattServer();
+
+    ca_mutex_lock(g_bleIsServerMutex);
+    g_isServer = true;
+    ca_mutex_unlock(g_bleIsServerMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartLEDiscoveryServer()
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    int init_pthread_status = 0;
-    pthread_t pthread_id = 0;
-    pthread_attr_t attr;
-    pthread_attr_init(&attr);
-    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+    CAResult_t result = CAInitBleClientQueues();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
+        return CA_STATUS_FAILED;
+    }
 
-    init_pthread_status = pthread_create(&pthread_id, &attr, CALEClientInitThreadFunc, NULL);
+    result = CAGetLEAdapterState();
+    if (CA_ADAPTER_NOT_ENABLED == result)
+    {
+        gLeServerStatus = CA_DISCOVERY_SERVER;
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
+        return CA_STATUS_OK;
+    }
 
-    if (init_pthread_status != 0)
+    if (CA_STATUS_FAILED == result)
     {
-        OCLog(ERROR, CALEADAPTER_TAG, "pthread_create failed!");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
         return CA_STATUS_FAILED;
     }
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
-    pthread_mutex_lock(&gBleIsServerMutex);
-    gIsServer = 0;
-    pthread_mutex_unlock(&gBleIsServerMutex);
+    CAStartBLEGattClient();
+
+    ca_mutex_lock(g_bleIsServerMutex);
+    g_isServer = false;
+    ca_mutex_unlock(g_bleIsServerMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartLENotifyServer()
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
-
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
-
-    return CA_STATUS_OK;
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return 0;
 }
 
 CAResult_t CAReadLEData()
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
-
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
     //Input validation
-    VERIFY_NON_NULL(endpoint, NULL, "Remote endpoint is null");
-    VERIFY_NON_NULL(data, NULL, "Data is null");
+    VERIFY_NON_NULL_RET(endpoint, NULL, "Remote endpoint is null", -1);
+    VERIFY_NON_NULL_RET(data, NULL, "Data is null", -1);
 
     CAResult_t result = CA_STATUS_FAILED;
 
-#ifdef __TIZEN__
-    pthread_mutex_lock(&gBleIsServerMutex);
-    if (gIsServer)
+    ca_mutex_lock(g_bleIsServerMutex);
+    if (true  == g_isServer)
     {
-        result = CAUpdateCharacteristicsInGattServer(data, dataLen);
+        result = CABLEServerSendData(endpoint, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OCLogv(ERROR, CALEADAPTER_TAG,
-                    "[SendLEUnicastData] sending unicast data to [%s] failed\n", endpoint->addressInfo.BT.btMacAddress);
-            pthread_mutex_unlock(&gBleIsServerMutex);
-            return 0;
+            OIC_LOG(ERROR, CALEADAPTER_TAG,
+                    "[SendLEUnicastData] CABleServerSenderQueueEnqueueMessage failed \n");
+            ca_mutex_unlock(g_bleIsServerMutex);
+            return -1;
         }
     }
     else
     {
-
-        result = CAUpdateCharacteristicsToGattServer(endpoint->addressInfo.BT.btMacAddress, data,
-                dataLen, UNICAST, 0);
+        result = CABLEClientSendData(endpoint, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OCLogv(ERROR, CALEADAPTER_TAG,
-                    "[SendLEUnicastData] sending unicast data to [%s] failed\n", endpoint->addressInfo.BT.btMacAddress);
-            pthread_mutex_unlock(&gBleIsServerMutex);
-            return 0;
+            OIC_LOG(ERROR, CALEADAPTER_TAG,
+                    "[SendLEUnicastData] CABleClientSenderQueueEnqueueMessage failed \n");
+            ca_mutex_unlock(g_bleIsServerMutex);
+            return -1;
         }
     }
-    pthread_mutex_unlock(&gBleIsServerMutex);
-#else
-    char *tempPath = "temp_path";
-    updateCharacteristicsInGattServer(tempPath, (char *) data, dataLen);
-#endif //#ifdef __TIZEN__
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+    ca_mutex_unlock(g_bleIsServerMutex);
 
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return dataLen;
 }
 
-uint32_t CASendLEMulticastData(void *data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
     //Input validation
-    VERIFY_NON_NULL(data, NULL, "Data is null");
+    VERIFY_NON_NULL_RET(data, NULL, "Data is null", -1);
 
     if (0 >= dataLen)
     {
-        OCLog(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
-        return 0;
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
+        return -1;
     }
 
     CAResult_t result = CA_STATUS_FAILED;
-#ifdef __TIZEN__
-    pthread_mutex_lock(&gBleIsServerMutex);
-    if (gIsServer)
+
+    ca_mutex_lock(g_bleIsServerMutex);
+    if (true  == g_isServer)
     {
-        result = CAUpdateCharacteristicsInGattServer(data, dataLen);
+        result = CABLEServerSendData(NULL, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OCLogv(ERROR, CALEADAPTER_TAG,
-                    "[CASendLEMulticastData] updating data in server is failed");
-            pthread_mutex_unlock(&gBleIsServerMutex);
-            return 0;
+            OIC_LOG(ERROR, CALEADAPTER_TAG,
+                    "[SendLEMulticastDataToAll] CABleServerSenderQueueEnqueueMessage failed" );
+            ca_mutex_unlock(g_bleIsServerMutex);
+            return -1;
         }
     }
     else
     {
-        result = CAUpdateCharacteristicsToAllGattServers(data, dataLen);
+        result = CABLEClientSendData(NULL, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            OCLogv(ERROR, CALEADAPTER_TAG,
-                    "[SendLEMulticastDataToAll] multicasting data to servers failed" );
-            pthread_mutex_unlock(&gBleIsServerMutex);
-            return 0;
+            OIC_LOG(ERROR, CALEADAPTER_TAG,
+                    "[SendLEMulticastDataToAll] CABleClientSenderQueueEnqueueMessage failed" );
+            ca_mutex_unlock(g_bleIsServerMutex);
+            return -1;
         }
     }
-    pthread_mutex_unlock(&gBleIsServerMutex);
-#else
-    char *tempPath = "temp_path";
-    updateCharacteristicsInGattServer(tempPath, (char *) data, dataLen);
-#endif //#ifdef __TIZEN__
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+    ca_mutex_unlock(g_bleIsServerMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return dataLen;
 }
 
-CAResult_t CAGetLEInterfaceInformation(CALocalConnectivityt_t **info, uint32_t *size)
+CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
     VERIFY_NON_NULL(info, NULL, "CALocalConnectivity info is null");
 
-#ifdef OIC_ARDUINODUE
-    OCLog(DEBUG, CALEADAPTER_TAG, "Info from ARDUINO");
-    //1: call corresponding Arduino API
-#endif
-
-#if __TIZEN__
-
     char *local_address = NULL;
 
-    bt_adapter_get_address(&local_address);
+    CAResult_t res = CAGetLEAddress(&local_address);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
+        return res;
+    }
+
     if (NULL == local_address)
     {
-        OCLog(ERROR, CALEADAPTER_TAG, "Get local bt adapter address failed");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
         return CA_STATUS_FAILED;
     }
 
-#endif //#if ARDUINODUE
     *size = 0;
-    (*info) = (CALocalConnectivityt_t *) OICMalloc(sizeof(CALocalConnectivityt_t));
+    (*info) = (CALocalConnectivity_t *) OICCalloc(1, sizeof(CALocalConnectivity_t));
     if (NULL == (*info))
     {
-        OCLog(ERROR, CALEADAPTER_TAG, "Malloc failure!");
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
+        OICFree(local_address);
         return CA_STATUS_FAILED;
     }
-    memset((*info), 0x0, sizeof(CALocalConnectivityt_t));
 
-    strncpy((*info)->addressInfo.BT.btMacAddress, local_address, strlen(local_address));
-    pthread_mutex_lock(&gBleLocalAddressMutex);
-    strncpy(gLocalBLEAddress, local_address, sizeof(gLocalBLEAddress));
-    pthread_mutex_unlock(&gBleLocalAddressMutex);
+    size_t local_address_len = strlen(local_address);
+
+    if(local_address_len >= sizeof(g_localBLEAddress) ||
+            local_address_len >= sizeof((*info)->addressInfo.BT.btMacAddress))
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
+        OICFree(*info);
+        OICFree(local_address);
+        return CA_STATUS_FAILED;
+    }
+
+    strncpy((*info)->addressInfo.BT.btMacAddress, local_address,
+            sizeof((*info)->addressInfo.BT.btMacAddress) - 1);
+    (*info)->addressInfo.BT.btMacAddress[sizeof((*info)->addressInfo.BT.btMacAddress)-1] = '\0';
+    ca_mutex_lock(g_bleLocalAddressMutex);
+    strncpy(g_localBLEAddress, local_address, sizeof(g_localBLEAddress) - 1);
+    g_localBLEAddress[sizeof(g_localBLEAddress)-1] = '\0';
+    ca_mutex_unlock(g_bleLocalAddressMutex);
 
     (*info)->type = CA_LE;
     *size = 1;
     OICFree(local_address);
 
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-int CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
+CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    pthread_mutex_lock(&gBleNetworkCbMutex);
-    gNetworkCallback = netCallback;
-    pthread_mutex_unlock(&gBleNetworkCbMutex);
-    int ret = 0;
-#ifdef __TIZEN__
+    ca_mutex_lock(g_bleNetworkCbMutex);
+    g_networkCallback = netCallback;
+    ca_mutex_unlock(g_bleNetworkCbMutex);
+    CAResult_t res = CA_STATUS_OK;
     if (netCallback)
     {
-        ret = bt_adapter_set_state_changed_cb(CALEDeviceStateChangedCb, NULL);
-        if(ret != 0)
+        res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
+        if (CA_STATUS_OK != res)
         {
-            OCLog(ERROR, CALEADAPTER_TAG, "bt_adapter_set_state_changed_cb failed!");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
         }
     }
     else
     {
-        ret = bt_adapter_unset_state_changed_cb();
-        if(ret != 0)
+        res = CAUnSetLEAdapterStateChangedCb();
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
+        }
+    }
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return res;
+}
+
+void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(g_localBLEAddress, NULL, "g_localBLEAddress is null");
+    CALocalConnectivity_t localEndpoint = {};
+
+    ca_mutex_lock(g_bleLocalAddressMutex);
+    strncpy(localEndpoint.addressInfo.BT.btMacAddress, g_localBLEAddress, strlen(g_localBLEAddress));
+    ca_mutex_unlock(g_bleLocalAddressMutex);
+
+    // Start a GattServer/Client if gLeServerStatus is SET
+    if (CA_LISTENING_SERVER == gLeServerStatus)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattServer");
+        CAStartBleGattServer();
+    }
+    else if (CA_DISCOVERY_SERVER == gLeServerStatus)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
+        CAStartBLEGattClient();
+    }
+    gLeServerStatus = CA_SERVER_NOTSTARTED;
+
+    ca_mutex_lock(g_bleNetworkCbMutex);
+    if (NULL != g_networkCallback)
+    {
+        g_networkCallback(&localEndpoint, adapter_state);
+    }
+    else
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
+    }
+    ca_mutex_unlock(g_bleNetworkCbMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAInitBleAdapterMutex()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    if (NULL == g_bleIsServerMutex)
+    {
+        g_bleIsServerMutex = ca_mutex_new();
+        if (NULL == g_bleIsServerMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleNetworkCbMutex)
+    {
+        g_bleNetworkCbMutex = ca_mutex_new();
+        if (NULL == g_bleNetworkCbMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleLocalAddressMutex)
+    {
+        g_bleLocalAddressMutex = ca_mutex_new();
+        if (NULL == g_bleLocalAddressMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleAdapterThreadPoolMutex)
+    {
+        g_bleAdapterThreadPoolMutex = ca_mutex_new();
+        if (NULL == g_bleAdapterThreadPoolMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleClientSendDataMutex)
+    {
+        g_bleClientSendDataMutex = ca_mutex_new();
+        if (NULL == g_bleClientSendDataMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleClientReceiveDataMutex)
+    {
+        g_bleClientReceiveDataMutex = ca_mutex_new();
+        if (NULL == g_bleClientReceiveDataMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleServerSendDataMutex)
+    {
+        g_bleServerSendDataMutex = ca_mutex_new();
+        if (NULL == g_bleServerSendDataMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleServerReceiveDataMutex)
+    {
+        g_bleServerReceiveDataMutex = ca_mutex_new();
+        if (NULL == g_bleServerReceiveDataMutex)
         {
-            OCLog(ERROR, CALEADAPTER_TAG, "bt_adapter_set_state_changed_cb failed!");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
         }
     }
-#endif //#ifdef __TIZEN__
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+
+    if (NULL == g_bleAdapterReqRespCbMutex)
+    {
+        g_bleAdapterReqRespCbMutex = ca_mutex_new();
+        if (NULL == g_bleAdapterReqRespCbMutex)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    return CA_STATUS_OK;
+}
+
+void CATerminateBleAdapterMutex()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    ca_mutex_free(g_bleIsServerMutex);
+    g_bleIsServerMutex = NULL;
+
+    ca_mutex_free(g_bleNetworkCbMutex);
+    g_bleNetworkCbMutex = NULL;
+
+    ca_mutex_free(g_bleLocalAddressMutex);
+    g_bleLocalAddressMutex = NULL;
+
+    ca_mutex_free(g_bleAdapterThreadPoolMutex);
+    g_bleAdapterThreadPoolMutex = NULL;
+
+    ca_mutex_free(g_bleClientSendDataMutex);
+    g_bleClientSendDataMutex = NULL;
+
+    ca_mutex_free(g_bleClientReceiveDataMutex);
+    g_bleClientReceiveDataMutex = NULL;
+
+    ca_mutex_free(g_bleServerSendDataMutex);
+    g_bleServerSendDataMutex = NULL;
+
+    ca_mutex_free(g_bleServerReceiveDataMutex);
+    g_bleServerReceiveDataMutex = NULL;
+
+    ca_mutex_free(g_bleAdapterReqRespCbMutex);
+    g_bleAdapterReqRespCbMutex = NULL;
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+void CAInitBleQueues()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    CAResult_t result = CAInitBleServerQueues();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerQueues failed");
+        return;
+    }
+
+    result = CAInitBleClientQueues();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
+        return;
+    }
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAInitBleServerQueues()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    ca_mutex_lock(g_bleAdapterThreadPoolMutex);
+
+    CAResult_t result = CAInitBleServerSenderQueue();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
+        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    result = CAInitBleServerReceiverQueue();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
+        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    g_dataReceiverHandlerState = true;
+
+    ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitBleClientQueues()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    ca_mutex_lock(g_bleAdapterThreadPoolMutex);
+
+    CAResult_t result = CAInitBleClientSenderQueue();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
+        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    result = CAInitBleClientReceiverQueue();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
+        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    g_dataReceiverHandlerState = true;
+
+    ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitBleServerSenderQueue()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    // Check if the message queue is already initialized
+    if (g_sendQueueHandle)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
+        return CA_STATUS_OK;
+    }
+
+    // Create send message queue
+    g_sendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+    if (!g_sendQueueHandle)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_bleAdapterThreadPool,
+            CABLEServerSendDataThread, CALEDataDestroyer))
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+        OICFree(g_sendQueueHandle);
+        g_sendQueueHandle = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
+        OICFree(g_sendQueueHandle);
+        g_sendQueueHandle = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-#ifdef __TIZEN__
+CAResult_t CAInitBleClientSenderQueue()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    if (g_bleClientSendQueueHandle)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
+        return CA_STATUS_OK;
+    }
+
+    // Create send message queue
+    g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+    if (!g_bleClientSendQueueHandle)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle, g_bleAdapterThreadPool,
+            CABLEClientSendDataThread, CALEDataDestroyer))
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+        OICFree(g_bleClientSendQueueHandle);
+        g_bleClientSendQueueHandle = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
+        OICFree(g_bleClientSendQueueHandle);
+        g_bleClientSendQueueHandle = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
 
-int CALEDeviceStateChangedCb(int result, bt_adapter_state_e adapter_state, void *user_data)
+CAResult_t CAInitBleServerReceiverQueue()
 {
-    OCLog(DEBUG, CALEADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+    // Check if the message queue is already initialized
+    if (g_bleServerReceiverQueue)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
+        return CA_STATUS_OK;
+    }
+
+    // Create send message queue
+    g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+    if (!g_bleServerReceiverQueue)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+        OICFree(g_sendQueueHandle);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
 
-    bt_adapter_state_e btAdaptorState = BT_ADAPTER_DISABLED;
-    if (BT_ADAPTER_ENABLED == adapter_state)
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue, g_bleAdapterThreadPool,
+            CABLEServerDataReceiverHandler, CALEDataDestroyer))
     {
-        btAdaptorState = BT_ADAPTER_ENABLED;
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+        OICFree(g_bleServerReceiverQueue);
+        g_bleServerReceiverQueue = NULL;
+        return CA_STATUS_FAILED;
     }
 
-    CALocalConnectivityt_t localEndpoint;
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
+        OICFree(g_bleServerReceiverQueue);
+        g_bleServerReceiverQueue = NULL;
+        return CA_STATUS_FAILED;
+    }
 
-    pthread_mutex_lock(&gBleLocalAddressMutex);
-    strncpy(localEndpoint.addressInfo.BT.btMacAddress, gLocalBLEAddress, strlen(gLocalBLEAddress));
-    pthread_mutex_unlock(&gBleLocalAddressMutex);
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
 
-    pthread_mutex_lock(&gBleNetworkCbMutex);
-    if(NULL != gNetworkCallback)
+CAResult_t CAInitBleClientReceiverQueue()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    // Check if the message queue is already initialized
+    if (g_bleClientReceiverQueue)
     {
-        gNetworkCallback(&localEndpoint, adapter_state);
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
     }
     else
     {
-        OCLog(ERROR, CALEADAPTER_TAG, "gNetworkCallback is NULL");
+        // Create send message queue
+        g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+        if (!g_bleClientReceiverQueue)
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+            OICFree(g_bleClientSendQueueHandle);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue, g_bleAdapterThreadPool,
+                CABLEClientDataReceiverHandler, NULL))
+        {
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
+            OICFree(g_bleClientSendQueueHandle);
+            OICFree(g_bleClientReceiverQueue);
+            g_bleClientReceiverQueue = NULL;
+            return CA_STATUS_FAILED;
+        }
     }
-    pthread_mutex_unlock(&gBleNetworkCbMutex);
-    OCLog(DEBUG, CALEADAPTER_TAG, "OUT");
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
+        OICFree(g_bleClientReceiverQueue);
+        g_bleClientReceiverQueue = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
-#endif //#ifdef OIC_TIZEN
+
+void CAStopBleQueues()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    ca_mutex_lock(g_bleClientSendDataMutex);
+    if (NULL != g_bleClientSendQueueHandle)
+    {
+        CAQueueingThreadStop(g_bleClientSendQueueHandle);
+    }
+    ca_mutex_unlock(g_bleClientSendDataMutex);
+
+    ca_mutex_lock(g_bleClientReceiveDataMutex);
+    if (NULL != g_bleClientReceiverQueue)
+    {
+        CAQueueingThreadStop(g_bleClientReceiverQueue);
+    }
+    ca_mutex_unlock(g_bleClientReceiveDataMutex);
+
+    ca_mutex_lock(g_bleServerSendDataMutex);
+    if (NULL != g_sendQueueHandle)
+    {
+        CAQueueingThreadStop(g_sendQueueHandle);
+    }
+    ca_mutex_unlock(g_bleServerSendDataMutex);
+
+    ca_mutex_lock(g_bleServerReceiveDataMutex);
+    if (NULL != g_bleServerReceiverQueue)
+    {
+        CAQueueingThreadStop(g_bleServerReceiverQueue);
+    }
+    ca_mutex_unlock(g_bleServerReceiveDataMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+void CATerminateBleQueues()
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
+    OICFree(g_bleClientSendQueueHandle);
+    g_bleClientSendQueueHandle = NULL;
+
+
+    CAQueueingThreadDestroy(g_bleClientReceiverQueue);
+    OICFree(g_bleClientReceiverQueue);
+    g_bleClientReceiverQueue = NULL;
+
+
+    CAQueueingThreadDestroy(g_sendQueueHandle);
+    OICFree(g_sendQueueHandle);
+    g_sendQueueHandle = NULL;
+
+
+    CAQueueingThreadDestroy(g_bleServerReceiverQueue);
+    OICFree(g_bleServerReceiverQueue);
+    g_bleServerReceiverQueue = NULL;
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+void CABLEServerDataReceiverHandler(void *threadData)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    static uint32_t recvDataLen = 0;
+    static uint32_t totalDataLen = 0;
+    static char *defragData = NULL;
+    static bool isHeaderAvailable = false;
+    static CARemoteEndpoint_t *remoteEndpoint = NULL;
+
+    ca_mutex_lock(g_bleServerReceiveDataMutex);
+
+    if (g_dataReceiverHandlerState)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
+
+        CALEData_t *bleData = (CALEData_t *) threadData;
+        if (!bleData)
+        {
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
+            return;
+        }
+
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
+
+        if (!isHeaderAvailable)
+        {
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
+            totalDataLen = CAParseHeader((char*)bleData->data);
+
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes", totalDataLen);
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%d] bytes", bleData->dataLen);
+
+            defragData = (char *) OICCalloc(totalDataLen + 1, sizeof(char));
+            if (NULL == defragData)
+            {
+                OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
+                return;
+            }
+
+            const char *remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
+            const char *serviceUUID = bleData->remoteEndpoint->resourceUri;
+
+            remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
+                             serviceUUID);
+
+            memcpy(defragData + recvDataLen, bleData->data + CA_HEADER_LENGTH,
+                   bleData->dataLen - CA_HEADER_LENGTH);
+            recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
+            isHeaderAvailable = true;
+        }
+        else
+        {
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
+            memcpy(defragData + recvDataLen, bleData->data, bleData->dataLen);
+            recvDataLen += bleData->dataLen ;
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
+                      totalDataLen, recvDataLen);
+        }
+        if (totalDataLen == recvDataLen)
+        {
+            ca_mutex_lock(g_bleAdapterReqRespCbMutex);
+            if (NULL == g_networkPacketReceivedCallback)
+            {
+                OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
+                ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
+                return;
+            }
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
+            g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
+            recvDataLen = 0;
+            totalDataLen = 0;
+            isHeaderAvailable = false;
+            remoteEndpoint = NULL;
+            defragData = NULL;
+            ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
+        }
+
+        if (false == g_dataReceiverHandlerState)
+        {
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
+            recvDataLen = 0;
+            totalDataLen = 0;
+            isHeaderAvailable = false;
+            OICFree(defragData);
+            CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+            ca_mutex_unlock(g_bleServerReceiveDataMutex);
+            return;
+        }
+    }
+    ca_mutex_unlock(g_bleServerReceiveDataMutex);
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+void CABLEClientDataReceiverHandler(void *threadData)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    static const char *remoteAddress = NULL;
+    static const char *serviceUUID = NULL;
+    static uint32_t recvDataLen = 0;
+    static uint32_t totalDataLen = 0;
+    static char *defragData = NULL;
+    static bool isHeaderAvailable = false;
+    static CARemoteEndpoint_t *remoteEndpoint = NULL;
+
+    ca_mutex_lock(g_bleClientReceiveDataMutex);
+
+    if (g_dataReceiverHandlerState)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
+
+        CALEData_t *bleData = (CALEData_t *) threadData;
+        if (!bleData)
+        {
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
+            return;
+        }
+
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
+
+        if (!isHeaderAvailable)
+        {
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
+
+            totalDataLen = CAParseHeader(bleData->data);
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes",
+                      totalDataLen);
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received in the first packet [%d] bytes",
+                      bleData->dataLen);
+
+            defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
+            if (NULL == defragData)
+            {
+                OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
+                return;
+            }
+
+            remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
+            serviceUUID = bleData->remoteEndpoint->resourceUri;
+
+            remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
+                                                           serviceUUID);
+
+            memcpy(defragData, bleData->data + CA_HEADER_LENGTH,
+                   bleData->dataLen - CA_HEADER_LENGTH);
+            recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
+            isHeaderAvailable = true;
+        }
+        else
+        {
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
+            memcpy(defragData + recvDataLen, bleData->data, bleData->dataLen);
+            recvDataLen += bleData->dataLen ;
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
+                      totalDataLen, recvDataLen);
+        }
+        if (totalDataLen == recvDataLen)
+        {
+            ca_mutex_lock(g_bleAdapterReqRespCbMutex);
+            if (NULL == g_networkPacketReceivedCallback)
+            {
+                OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
+                ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
+                return;
+            }
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
+            g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
+            recvDataLen = 0;
+            totalDataLen = 0;
+            isHeaderAvailable = false;
+            remoteEndpoint = NULL;
+            defragData = NULL;
+            ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
+        }
+
+        if (false == g_dataReceiverHandlerState)
+        {
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
+            OICFree(defragData);
+            CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+            ca_mutex_unlock(g_bleClientReceiveDataMutex);
+            return;
+        }
+    }
+    ca_mutex_unlock(g_bleClientReceiveDataMutex);
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+void CABLEServerSendDataThread(void *threadData)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    CALEData_t *bleData = (CALEData_t *) threadData;
+    if (!bleData)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
+        return;
+    }
+
+    char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
+    VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
+
+    int32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
+
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server total Data length with header is [%d]", totalLength);
+    char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
+    if (NULL == dataSegment)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
+        OICFree(header);
+        return;
+    }
+
+    CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
+    if (CA_STATUS_OK != result )
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
+        OICFree(header);
+        OICFree(dataSegment);
+        return ;
+    }
+
+    memcpy(dataSegment, header, CA_HEADER_LENGTH);
+    OICFree(header);
+
+    int32_t length = 0;
+    if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
+    {
+        length = totalLength;
+        memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
+    }
+    else
+    {
+        length =  CA_SUPPORTED_BLE_MTU_SIZE;
+        memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
+               CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
+    }
+
+    int32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
+    int32_t index = 0;
+    // Send the first segment with the header.
+     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
+        result = CAUpdateCharacteristicsToGattClient(
+                    bleData->remoteEndpoint->addressInfo.LE.leMacAddress, dataSegment, length);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+            OICFree(dataSegment);
+            return;
+        }
+
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
+        for (index = 1; index < iter; index++)
+        {
+            // Send the remaining header.
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
+            result = CAUpdateCharacteristicsToGattClient(
+                         bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+                         bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
+                         CA_SUPPORTED_BLE_MTU_SIZE);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG,
+                            "Update characteristics failed, result [%d]", result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
+                                               CA_SUPPORTED_BLE_MTU_SIZE);
+        }
+
+        int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
+        {
+            // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+            result = CAUpdateCharacteristicsToGattClient(
+                         bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         remainingLen);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
+        }
+     }
+    else
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
+        result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+            OICFree(dataSegment);
+            return;
+        }
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
+        for (index = 1; index < iter; index++)
+        {
+            // Send the remaining header.
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
+            result = CAUpdateCharacteristicsToAllGattClients(
+                         bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
+                         CA_SUPPORTED_BLE_MTU_SIZE);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
+        }
+
+        int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
+        {
+            // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+            result = CAUpdateCharacteristicsToAllGattClients(
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         remainingLen);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
+        }
+    }
+    OICFree(dataSegment);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+void CABLEClientSendDataThread(void *threadData)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    CALEData_t *bleData = (CALEData_t *) threadData;
+    if (!bleData)
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
+        return;
+    }
+
+    char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
+    VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
+
+    uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
+    char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
+    if (NULL == dataSegment)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
+        OICFree(header);
+        return;
+    }
+
+    CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
+    if (CA_STATUS_OK != result )
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
+        OICFree(header);
+        OICFree(dataSegment);
+        return ;
+    }
+    memcpy(dataSegment, header, CA_HEADER_LENGTH);
+    OICFree(header);
+
+    uint32_t length = 0;
+    if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
+    {
+        length = totalLength;
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
+        memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
+    }
+    else
+    {
+        length = CA_SUPPORTED_BLE_MTU_SIZE;
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length  [%d]", length);
+        memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
+               CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
+    }
+
+    uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
+    uint32_t index = 0;
+    if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
+    {
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
+        // Send the first segment with the header.
+        result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+                 dataSegment,
+                 length,
+                 LE_UNICAST, 0);
+
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+            OICFree(dataSegment);
+            return ;
+        }
+
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
+        for (index = 1; index < iter; index++)
+        {
+            // Send the remaining header.
+            result = CAUpdateCharacteristicsToGattServer(
+                     bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                     CA_SUPPORTED_BLE_MTU_SIZE,
+                     LE_UNICAST, 0);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
+                                               CA_SUPPORTED_BLE_MTU_SIZE);
+        }
+
+        uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
+        {
+            // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+            result = CAUpdateCharacteristicsToGattServer(
+                     bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                     remainingLen,
+                     LE_UNICAST, 0);
+
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
+                                                   result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
+        }
+    }
+    else
+    {
+        //Sending Mulitcast Data
+        // Send the first segment with the header.
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
+        result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed (all), result [%d]", result);
+            OICFree(dataSegment);
+            return ;
+        }
+        OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
+        // Send the remaining header.
+        for (index = 1; index < iter; index++)
+        {
+            result = CAUpdateCharacteristicsToAllGattServers(
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                         CA_SUPPORTED_BLE_MTU_SIZE);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]", result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
+        }
+
+        uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
+        if ( remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
+        {
+            // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
+            OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
+            result = CAUpdateCharacteristicsToAllGattServers(
+                         bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
+                          remainingLen);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]", result);
+                OICFree(dataSegment);
+                return;
+            }
+            OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
+        }
+
+    }
+
+    OICFree(dataSegment);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
+}
+
+CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                           uint32_t dataLength)
+{
+    CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
+    if (!bleData)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+        return NULL;
+    }
+
+    bleData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
+    bleData->data = (void *)OICCalloc(dataLength + 1, 1);
+    if (NULL == bleData->data)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
+        CAFreeBLEData(bleData);
+        return NULL;
+    }
+    memcpy(bleData->data, data, dataLength);
+    bleData->dataLen = dataLength;
+
+    return bleData;
+}
+
+void CAFreeBLEData(CALEData_t *bleData)
+{
+    VERIFY_NON_NULL_VOID(bleData, NULL, "Param bleData is NULL");
+
+    CAAdapterFreeRemoteEndpoint(bleData->remoteEndpoint);
+    OICFree(bleData->data);
+    OICFree(bleData);
+}
+
+void CALEDataDestroyer(void *data, uint32_t size)
+{
+    CALEData_t *ledata = (CALEData_t *) data;
+
+    CAFreeBLEData(ledata);
+}
+
+
+CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
+                               const void *data,
+                               uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(data, NULL, "Param data is NULL");
+
+    VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
+                        "g_bleClientSendQueueHandle is  NULL",
+                        CA_STATUS_FAILED);
+    VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
+                        "g_bleClientSendDataMutex is NULL",
+                        CA_STATUS_FAILED);
+
+    VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
+                        CA_STATUS_FAILED);
+
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
+
+    CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
+    if (!bleData)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    // Add message to send queue
+    ca_mutex_lock(g_bleClientSendDataMutex);
+    CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
+    ca_mutex_unlock(g_bleClientSendDataMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+
+CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
+                               const void *data,
+                               uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(data, NULL, "Param data is NULL");
+
+    VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG,
+                        "BleClientReceiverQueue is NULL",
+                        CA_STATUS_FAILED);
+    VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
+                        "BleClientSendDataMutex is NULL",
+                        CA_STATUS_FAILED);
+
+    VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
+                        CA_STATUS_FAILED);
+
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
+
+    CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
+    if (!bleData)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    // Add message to send queue
+    ca_mutex_lock(g_bleServerSendDataMutex);
+    CAQueueingThreadAddData(g_sendQueueHandle, bleData, sizeof(CALEData_t));
+    ca_mutex_unlock(g_bleServerSendDataMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
+                                   const void *data, uint32_t dataLength, uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    //Input validation
+    VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
+    VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
+    VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
+    VERIFY_NON_NULL_RET(g_bleServerReceiverQueue, CALEADAPTER_TAG, "g_bleServerReceiverQueue",
+                        CA_STATUS_FAILED);
+
+    //Add message to data queue
+    CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
+                                         serviceUUID);
+    if (NULL == remoteEndpoint)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
+        return CA_STATUS_FAILED;
+    }
+
+    // Create bleData to add to queue
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
+
+    CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
+    if (!bleData)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
+        CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+    // Add message to send queue
+    CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
+
+    *sentLength = dataLength;
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CABLEClientReceivedData(const char *remoteAddress, const char *serviceUUID,
+                                   const void *data, uint32_t dataLength, uint32_t *sentLength)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    //Input validation
+    VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
+    VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
+    VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
+    VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG, "g_bleClientReceiverQueue",
+                        CA_STATUS_FAILED);
+
+    //Add message to data queue
+    CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
+                                         serviceUUID);
+    if (NULL == remoteEndpoint)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
+
+    // Create bleData to add to queue
+    CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
+    if (!bleData)
+    {
+        OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
+        CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+    // Add message to send queue
+    CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
+
+    *sentLength = dataLength;
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CASetBleAdapterThreadPoolHandle(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+    g_bleAdapterThreadPool = handle;
+    ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
+void CASetBLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
+
+    ca_mutex_lock(g_bleAdapterReqRespCbMutex);
+
+    g_networkPacketReceivedCallback = callback;
+
+    ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
+
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
+}
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/caleadapter_singlethread.c b/resource/csdk/connectivity/src/bt_le_adapter/caleadapter_singlethread.c
new file mode 100644 (file)
index 0000000..7e6c1af
--- /dev/null
@@ -0,0 +1,429 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include "caleadapter_singlethread.h"
+
+#include "caleinterface_singlethread.h"
+#include "cableserver.h"
+#include "logger.h"
+#include "caadapterutils.h"
+#include "camsgparser.h"
+
+#define TAG "LAD"
+
+/**
+ * @def MAX_EVENT_COUNT
+ * @brief Maximum number of tries to get the event on BLE Shield address.
+ */
+#define MAX_EVENT_COUNT 20
+
+static CANetworkChangeCallback g_networkCallback = NULL;
+static bool g_serverRunning = false;
+static CANetworkPacketReceivedCallback g_respCallback;
+static char *g_coapBuffer = NULL;
+static uint32_t g_dataLen = 0;
+static uint32_t g_packetDataLen = 0;
+
+/**
+ * @brief API to register for BLE network notification.
+ * @param net_callback - network notification callback.
+ * @return - Error Code
+ */
+CAResult_t LERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
+
+/**
+ * @brief API to send received data to upper layer.
+ * @param[in] data - data received from BLE characteristics.
+ * @param[in] dataLen - received data Length.
+ * @param[in] senderAdrs - sender Address.
+ * @param[in] senderPort - sender port.
+ * @return - Error Code
+ */
+void CANotifyCallback(const void *data, int32_t dataLen, const char *senderAdrs,
+                      int32_t senderPort);
+
+/**
+ * @brief API to read the data from characteristics and invoke notifyCallback.
+ * @return - void
+ */
+void CACheckData();
+
+/**
+ * @brief API to Send the data.
+ * @return - Number of bytes sent. -1 on error.
+ */
+int32_t CASendLEData(const void *data, uint32_t dataLen);
+
+CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
+                          CANetworkPacketReceivedCallback reqRespCallback,
+                          CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == registerCallback || NULL == reqRespCallback || NULL == netCallback)
+    {
+        OIC_LOG(ERROR, TAG, "i/p null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    CAResult_t result = CALEInitializeNetworkMonitor();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "n/w init fail: %d", result);
+        return CA_STATUS_FAILED;
+    }
+
+    g_respCallback = reqRespCallback;
+    LERegisterNetworkNotifications(netCallback);
+    CAConnectivityHandler_t connHandler;
+    connHandler.startAdapter = CAStartLE;
+    connHandler.startListenServer = CAStartLEListeningServer;
+    connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
+    connHandler.sendData = CASendLEUnicastData;
+    connHandler.sendDataToAll = CASendLEMulticastData;
+    connHandler.GetnetInfo = CAGetLEInterfaceInformation;
+    connHandler.readData = CAReadLEData;
+    connHandler.stopAdapter = CAStopLE;
+    connHandler.terminate = CATerminateLE;
+    registerCallback(connHandler, CA_LE);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartLE()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartLEListeningServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAResult_t result = CAInitializeBle();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "ble init fail: %d", result);
+        return CA_STATUS_FAILED;
+    }
+    /**
+     * Below for loop is to process the BLE Events received from BLE Shield.
+     * BLE Events includes BLE Shield Address Added as a patch to RBL Library.
+     */
+    for (int iter = 0; iter < MAX_EVENT_COUNT; iter++)
+    {
+        CACheckData();
+    }
+
+    g_serverRunning = true;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartLEDiscoveryServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartLENotifyServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
+                              uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return 1;
+}
+
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                            uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == remoteEndpoint || NULL == data || dataLen == 0)
+    {
+        OIC_LOG(ERROR, TAG, "i/p null");
+        return -1;
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CASendLEData(data, dataLen);
+}
+
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == data || 0 == dataLen)
+    {
+        OIC_LOG(ERROR, TAG, "i/p null");
+        return -1;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CASendLEData(data, dataLen);
+}
+
+CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == info || NULL == size)
+    {
+        OIC_LOG(ERROR, TAG, "i/p null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    char *leAddress = NULL;
+    CAResult_t res = CAGetLEAddress(&leAddress);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "CAGetLEAddress has failed");
+        return res;
+    }
+
+    if (NULL == leAddress)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to get Le addr");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "leAddress = %s", leAddress);
+
+    /**
+     * Create local endpoint using util function
+     */
+    (*info) = CAAdapterCreateLocalEndpoint(CA_LE, leAddress);
+    if (NULL == (*info))
+    {
+        OIC_LOG(ERROR, TAG, "malloc fail");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    (*size) = 1;
+    if (*leAddress)
+    {
+        OICFree(leAddress);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAReadLEData()
+{
+    if (true == g_serverRunning)
+    {
+        CACheckData();
+    }
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopLE()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAStopBleGattServer();
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateLE()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_respCallback = NULL;
+    LERegisterNetworkNotifications(NULL);
+    CAResult_t result = CATerminateBle();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "ble terminate fail");
+        return;
+    }
+
+    CALETerminateNetworkMonitor();
+    g_serverRunning = false;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return;
+}
+
+CAResult_t LERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_networkCallback = netCallback;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartBleGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    // Done at time of setup i.e. in initializeBle api
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopBleGattServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    // There is no server running to stop.
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CANotifyCallback(const void *data, int32_t dataLen, const char *senderAdrs, int32_t senderPort)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (g_respCallback)
+    {
+
+        /* Cannot get Address as of now */
+        CARemoteEndpoint_t endPoint;
+        endPoint.resourceUri = "";     // will be filled by upper layer
+        endPoint.transportType= CA_LE;
+
+        g_respCallback(&endPoint, data, dataLen);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CACheckData()
+{
+    CABleDoEvents();
+
+    if (CAIsBleDataAvailable())
+    {
+        // Allocate Memory for COAP Buffer and do ParseHeader
+        if (NULL == g_coapBuffer)
+        {
+            OIC_LOG(DEBUG, TAG, "IN");
+            char headerArray[CA_HEADER_LENGTH] = "";
+            while (CAIsBleDataAvailable() && g_dataLen < CA_HEADER_LENGTH)
+            {
+                headerArray[g_dataLen++] = CAReadBleData();
+            }
+
+            g_packetDataLen = CAParseHeader(headerArray);
+
+            if (g_packetDataLen > COAP_MAX_PDU_SIZE)
+            {
+                OIC_LOG(ERROR, TAG, "len > pdu_size");
+                return;
+            }
+
+            g_coapBuffer = (char *)OICCalloc((size_t)g_packetDataLen, sizeof(char));
+            if (NULL == g_coapBuffer)
+            {
+                OIC_LOG(ERROR, TAG, "malloc");
+                return;
+            }
+
+            OIC_LOG(DEBUG, TAG, "OUT");
+            g_dataLen = 0;
+        }
+
+        OIC_LOG(DEBUG, TAG, "IN");
+        while (CAIsBleDataAvailable())
+        {
+            OIC_LOG(DEBUG, TAG, "In While loop");
+            g_coapBuffer[g_dataLen++] = CAReadBleData();
+            if (g_dataLen == g_packetDataLen)
+            {
+                OIC_LOG(DEBUG, TAG, "Read Comp BLE Pckt");
+                g_coapBuffer[g_dataLen] = '\0';
+                if (g_dataLen > 0)
+                {
+                    OIC_LOG_V(DEBUG, TAG, "recv dataLen=%d", g_dataLen);
+                    CANotifyCallback((void *)g_coapBuffer, g_dataLen, "", 0);
+                }
+                g_dataLen = 0;
+                OICFree(g_coapBuffer);
+                g_coapBuffer = NULL;
+                break;
+            }
+        }
+        OIC_LOG(DEBUG, TAG, "OUT");
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "NoData");
+    }
+    return;
+}
+
+int32_t CASendLEData(const void *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    char header[CA_HEADER_LENGTH] = {0};
+
+    CAResult_t result = CAGenerateHeader(header, dataLen);
+
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Generate header failed");
+        return -1;
+    }
+
+    if (!CAIsBleConnected())
+    {
+        OIC_LOG(ERROR, TAG, "le not conn");
+        return -1;
+    }
+
+    result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Update characteristics failed");
+        return -1;
+    }
+
+    int32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
+    for (int32_t iter = 0; iter < dataLimit; iter++)
+    {
+        result = CAUpdateCharacteristicsToAllGattClients((data +
+                                                         (iter * CA_SUPPORTED_BLE_MTU_SIZE)),
+                                                         CA_SUPPORTED_BLE_MTU_SIZE);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "Update characteristics failed");
+            return -1;
+        }
+        CABleDoEvents();
+    }
+
+    uint8_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
+    if(remainingLen)
+    {
+        result = CAUpdateCharacteristicsToAllGattClients((data +
+                                                         (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE)),
+                                                         remainingLen);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "Update characteristics failed");
+            return -1;
+        }
+        CABleDoEvents();
+    }
+
+    OIC_LOG(DEBUG, TAG, "writebytes done");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    // Arduino BLEWrite doesnot return value. So, Return the received DataLength
+    return dataLen;
+}
+
index fb7ec92..92d1990 100644 (file)
 
 #define TAG PCF("CA")
 
-static CANetworkPacketReceivedCallback gLEReceivedCallback = NULL;
+static CANetworkPacketReceivedCallback g_leReceivedCallback = NULL;
+static ca_thread_pool_t g_threadPoolHandle = NULL;
 
 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback)
+                          CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
+                          ca_thread_pool_t handle)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAInitializeLE");
+    OIC_LOG(DEBUG, TAG, "CAInitializeLE");
 
-    gLEReceivedCallback = reqRespCallback;
+    g_leReceivedCallback = reqRespCallback;
+    g_threadPoolHandle = handle;
 
     // register handlers
     CAConnectivityHandler_t handler;
@@ -42,11 +45,9 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
 
     handler.startAdapter = CAStartLE;
     handler.startListenServer = CAStartLEListeningServer;
-    handler.startDiscoverServer = CAStartLEDiscoveryServer;
+    handler.startDiscoveryServer = CAStartLEDiscoveryServer;
     handler.sendData = CASendLEUnicastData;
     handler.sendDataToAll = CASendLEMulticastData;
-    handler.startNotifyServer = CAStartLENotifyServer;
-    handler.sendNotification = CASendLENotification;
     handler.GetnetInfo = CAGetLEInterfaceInformation;
     handler.readData = CAReadLEData;
     handler.stopAdapter = CAStopLE;
@@ -59,75 +60,62 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
 
 CAResult_t CAStartLE()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartLE");
+    OIC_LOG(DEBUG, TAG, "CAStartLE");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartLEListeningServer()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartLEListeningServer");
+    OIC_LOG(DEBUG, TAG, "CAStartLEListeningServer");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStartLEDiscoveryServer()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartLEDiscoveryServer");
+    OIC_LOG(DEBUG, TAG, "CAStartLEDiscoveryServer");
 
     return CA_STATUS_OK;
 }
 
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "CASendLEUnicastData");
+    OIC_LOG(DEBUG, TAG, "CASendLEUnicastData");
 
-    return 0;
+    return -1;
 }
 
-uint32_t CASendLEMulticastData(void* data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
 {
-    OIC_LOG_V(DEBUG, TAG, "CASendLEMulticastData");
+    OIC_LOG(DEBUG, TAG, "CASendLEMulticastData");
 
-    return 0;
+    return -1;
 }
 
-CAResult_t CAStartLENotifyServer()
+CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartLENotifyServer");
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendLENotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendLENotification");
-
-    return 0;
-}
-
-CAResult_t CAGetLEInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size)
-{
-    OIC_LOG_V(DEBUG, TAG, "CAGetLEInterfaceInformation");
+    OIC_LOG(DEBUG, TAG, "CAGetLEInterfaceInformation");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAReadLEData()
 {
-    OIC_LOG_V(DEBUG, TAG, "Read LE Data");
+    OIC_LOG(DEBUG, TAG, "Read LE Data");
 
     return CA_STATUS_OK;
 }
 
 CAResult_t CAStopLE()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStopLE");
+    OIC_LOG(DEBUG, TAG, "CAStopLE");
 
     return CA_STATUS_OK;
 }
 
 void CATerminateLE()
 {
-    OIC_LOG_V(DEBUG, TAG, "TerminatLE");
+    OIC_LOG(DEBUG, TAG, "TerminatLE");
 }
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c
new file mode 100644 (file)
index 0000000..30199fa
--- /dev/null
@@ -0,0 +1,1489 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "cableclient.h"
+
+#include<stdio.h>
+#include<stdlib.h>
+#include<string.h>
+#include<arpa/inet.h>
+#include<sys/types.h>
+#include<sys/socket.h>
+#include<netinet/in.h>
+#include <pthread.h>
+#include <gio/gio.h>
+
+#include "camutex.h"
+#include "uarraylist.h"
+#include "caqueueingthread.h"
+#include "caadapterutils.h"
+#include "camsgparser.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+
+/**
+ * @def TZ_BLE_CLIENT_TAG
+ * @brief Logging tag for module name
+ */
+#define TZ_BLE_CLIENT_TAG "TZ_BLE_GATT_CLIENT"
+
+/**
+ * @var BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG
+ * @brief Its the constant value for characteristic descriptor from spec.
+ */
+#define BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG "2902"
+
+/**
+ * @var g_bLEServiceList
+ * @brief This contains the list of OIC services a client connect tot.
+ */
+static BLEServiceList *g_bLEServiceList = NULL;
+
+/**
+ * @var g_isBleGattClientStarted
+ * @brief Boolean variable to keep the state of the GATT Client.
+ */
+static bool g_isBleGattClientStarted = false;
+
+/**
+ * @var g_bleServiceListMutex
+ * @brief Mutex to synchronize access to BleServiceList.
+ */
+static ca_mutex g_bleServiceListMutex = NULL;
+
+/**
+ * @var g_bleReqRespClientCbMutex
+ * @brief Mutex to synchronize access to the requestResponse callback to be called
+ *           when the data needs to be sent from GATTClient.
+ */
+static ca_mutex g_bleReqRespClientCbMutex = NULL;
+
+/**
+ * @var g_bleReqRespClientCbMutex
+ * @brief Mutex to synchronize access to the requestResponse callback to be called
+ *           when the data needs to be sent from GATTClient.
+ */
+static ca_mutex g_bleClientConnectMutex = NULL;
+
+
+/**
+ * @var g_bleClientStateMutex
+ * @brief Mutex to synchronize the calls to be done to the platform from GATTClient
+ *           interfaces from different threads.
+ */
+static ca_mutex g_bleClientStateMutex = NULL;
+
+/**
+ * @var g_bleServerBDAddressMutex
+ * @brief Mutex to synchronize the Server BD Address update on client side.
+ */
+static ca_mutex g_bleServerBDAddressMutex = NULL;
+
+/**
+ * @var g_bleClientSendCondWait
+ * @brief Condition used for notifying handler the presence of data in send queue.
+ */
+static ca_cond g_bleClientSendCondWait = NULL;
+
+/**
+ * @var g_bleClientThreadPoolMutex
+ * @brief Mutex to synchronize the task to be pushed to thread pool.
+ */
+static ca_mutex g_bleClientThreadPoolMutex = NULL;
+
+/**
+ * @var gNetworkPacketReceivedClientCallback
+ * @brief Maintains the callback to be notified on receival of network packets from other
+ *           BLE devices
+ */
+static CABLEClientDataReceivedCallback g_bleClientDataReceivedCallback = NULL;
+
+/**
+ * @var g_eventLoop
+ * @brief gmainLoop to manage the threads to receive the callback from the platfrom.
+ */
+static GMainLoop *g_eventLoop = NULL;
+
+/**
+ * @var g_bleClientThreadPool
+ * @brief reference to threadpool
+ */
+static ca_thread_pool_t g_bleClientThreadPool = NULL;
+
+/**
+ * @struct stGattServiceInfo_t
+ * @brief structure to map the service attribute to BD Address.
+ */
+typedef struct gattService
+{
+    bt_gatt_attribute_h serviceInfo;         /**< bluetoth attribute for oic service*/
+    char *address;                           /**< BD Address of */
+} stGattServiceInfo_t;
+
+/**
+ * @var g_remoteAddress
+ * @brief Remote address of Gatt Server
+ */
+static char *g_remoteAddress = NULL;
+
+void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
+                                      unsigned char *value,
+                                      int valueLen, void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic is  [%s]", (char *)characteristic);
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic value length [%d]", valueLen);
+
+    ca_mutex_lock(g_bleReqRespClientCbMutex);
+    if (NULL == g_bleClientDataReceivedCallback)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gReqRespCallback is NULL!");
+        ca_mutex_unlock(g_bleReqRespClientCbMutex);
+        return;
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Sending data up !");
+
+    ca_mutex_lock(g_bleServerBDAddressMutex);
+    uint32_t sentLength = 0;
+    g_bleClientDataReceivedCallback(g_remoteAddress, OIC_BLE_SERVICE_ID,
+                                     value, valueLen, &sentLength);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Sent data Length is %d", sentLength);
+    ca_mutex_unlock(g_bleServerBDAddressMutex);
+
+    ca_mutex_unlock(g_bleReqRespClientCbMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CABleGattCharacteristicWriteCb(int result, void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
+
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
+}
+
+void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total,
+                                     bt_gatt_attribute_h descriptor,
+                                     bt_gatt_attribute_h characteristic, void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    stGattCharDescriptor_t *stTemp = (stGattCharDescriptor_t *)OICCalloc(1, sizeof(
+                                                                         stGattCharDescriptor_t));
+
+    VERIFY_NON_NULL_VOID(stTemp, TZ_BLE_CLIENT_TAG, "malloc failed!");
+
+    stTemp->desc = (uint8_t *)OICMalloc(total);
+    if (NULL == stTemp->desc)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "malloc failed");
+        OICFree(stTemp);
+        return;
+    }
+    memcpy(stTemp->desc, descriptor, total);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "result[%d] format[%d] total[%d]", result, format, total);
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "characteristic [%s]", (const char *) characteristic);
+
+
+    bt_gatt_clone_attribute_handle(&(stTemp->characteristic), characteristic);
+    stTemp->total = total;
+
+    ca_mutex_lock(g_bleClientThreadPoolMutex);
+    if (NULL == g_bleClientThreadPool)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
+        bt_gatt_destroy_attribute_handle(stTemp->characteristic);
+        OICFree(stTemp->desc);
+        OICFree(stTemp);
+        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+        return;
+    }
+
+    CAResult_t ret = ca_thread_pool_add_task(g_bleClientThreadPool,
+                                            CASetCharacteristicDescriptorValueThread,
+                                            stTemp);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_thread_pool_add_task failed");
+        bt_gatt_destroy_attribute_handle(stTemp->characteristic);
+        OICFree(stTemp->desc);
+        OICFree(stTemp);
+        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+        return;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG,
+            "LE Client initialization flow complete");
+
+    ca_mutex_unlock(g_bleClientThreadPoolMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+bool CABleGattCharacteristicsDiscoveredCb(int result,
+        int inputIndex, int total,
+        bt_gatt_attribute_h characteristic, void *userData)
+{
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(characteristic, TZ_BLE_CLIENT_TAG, "Param characteristic is NULL", false);
+
+    VERIFY_NON_NULL_RET(userData, TZ_BLE_CLIENT_TAG, "Param userData is NULL", false);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+              "result [%d] input_index [%d] total [%d]",
+              result, inputIndex, total);
+
+    BLEServiceInfo *bleServiceInfo = NULL;
+
+    ca_mutex_lock(g_bleServiceListMutex);
+
+    char *bdAddress = (char *) userData;
+    CAGetBLEServiceInfo(g_bLEServiceList, bdAddress, &bleServiceInfo);
+
+    ca_mutex_unlock(g_bleServiceListMutex);
+
+    char *uuid = NULL;
+    bt_gatt_get_service_uuid(characteristic, &uuid);
+
+    VERIFY_NON_NULL_RET(uuid, TZ_BLE_CLIENT_TAG, "uuid is NULL", false);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "New Characteristics[%s] of uuid[%s] is obtained",
+              (char *)characteristic, uuid);
+
+    if(0 == strcasecmp(uuid, CA_BLE_READ_CHAR_UUID)) // Server will read on this characterisctics
+    {
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Read characteristics is obtained");
+        OICFree(uuid);
+        CAResult_t retVal = CAAppendBLECharInfo(characteristic, BLE_GATT_READ_CHAR, bleServiceInfo);
+        if (CA_STATUS_OK != retVal)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAAppendBLECharInfo failed! ");
+            return false;
+        }
+
+        stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICCalloc(1,
+                                                                      sizeof(stGattServiceInfo_t));
+
+        VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "calloc failed!", false);
+
+        size_t len = strlen(bdAddress);
+        stTemp->address = (char *)OICMalloc(sizeof(char) * (len + 1));
+        if (NULL == stTemp->address)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
+            OICFree(stTemp);
+            return false;
+        }
+
+        strncpy(stTemp->address, bdAddress, len + 1);
+        bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), characteristic);
+
+        ca_mutex_lock(g_bleClientThreadPoolMutex);
+        if (NULL == g_bleClientThreadPool)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
+            bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
+            OICFree(stTemp->address);
+            OICFree(stTemp);
+            ca_mutex_unlock(g_bleClientThreadPoolMutex);
+            return false;
+        }
+
+        retVal = ca_thread_pool_add_task(g_bleClientThreadPool,
+                                        CADiscoverDescriptorThread,
+                                        stTemp);
+        if (CA_STATUS_OK != retVal)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                      "ca_thread_pool_add_task failed with ret [%d]", retVal);
+            bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
+            OICFree(stTemp->address);
+            OICFree(stTemp);
+            ca_mutex_unlock(g_bleClientThreadPoolMutex);
+            return false;
+        }
+        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+    }
+    else if (0 == strcasecmp(uuid, CA_BLE_WRITE_CHAR_UUID)) // Server will write on this characteristics.
+    {
+        OICFree(uuid);
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Write characteristics is obtained");
+        CAResult_t retVal = CAAppendBLECharInfo(characteristic, BLE_GATT_WRITE_CHAR, bleServiceInfo);
+        if (CA_STATUS_OK != retVal)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAAppendBLECharInfo failed ");
+            return false;
+        }
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return true;
+}
+
+bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count,
+                               void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(service, TZ_BLE_CLIENT_TAG, "Param service is NULL", false);
+
+    VERIFY_NON_NULL_RET(userData, TZ_BLE_CLIENT_TAG, "Param userData is NULL", false);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Service info [%s] index [%d] count [%d]", (char *)service,
+              index, count);
+
+    CAResult_t result = CAVerifyOICServiceByServiceHandle(service);
+
+    if (CA_STATUS_OK == result)
+    {
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its OIC service");
+
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG , "Registering to watch characteristics changes");
+
+        result = CABleGattWatchCharacteristicChanges(service);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
+                      "CABleGattWatchCharacteristicChanges failed!");
+            return false;
+        }
+
+        stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICCalloc(1,
+                                                                      sizeof(stGattServiceInfo_t));
+        VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "Calloc Failed", false);
+
+        char *bdAddress = (char *)userData;
+        size_t len = strlen(bdAddress);
+
+        stTemp->address = (char *)OICMalloc(sizeof(char) * (len + 1));
+        if (NULL == stTemp->address)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
+            OICFree(stTemp);
+            return false;
+        }
+
+        strncpy(stTemp->address, bdAddress, len + 1);
+
+        BLEServiceInfo *bleServiceInfo = NULL;
+
+        result = CACreateBLEServiceInfo(bdAddress, service, &bleServiceInfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CACreateBLEServiceInfo failed! ");
+            OICFree(stTemp->address);
+            OICFree(stTemp);
+            OICFree(bleServiceInfo);
+            return false;
+        }
+        if (NULL == bleServiceInfo )
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , " bleServiceInfo is NULL");
+            OICFree(stTemp->address);
+            OICFree(stTemp);
+            OICFree(bleServiceInfo);
+            return false;
+        }
+
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG ,
+                  " serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
+
+        ca_mutex_lock(g_bleServiceListMutex);
+        result = CAAddBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo);
+        ca_mutex_unlock(g_bleServiceListMutex);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAAddBLEServiceInfoToList failed!");
+            OICFree(stTemp->address);
+            OICFree(stTemp);
+            CAFreeBLEServiceInfo(bleServiceInfo);
+            return false;
+        }
+
+
+        ca_mutex_lock(g_bleClientThreadPoolMutex);
+        if (NULL == g_bleClientThreadPool)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
+            OICFree(stTemp->address);
+            OICFree(stTemp);
+            ca_mutex_lock(g_bleServiceListMutex);
+            CARemoveBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo,
+                                         bleServiceInfo->bdAddress);
+            ca_mutex_unlock(g_bleServiceListMutex);
+            ca_mutex_unlock(g_bleClientThreadPoolMutex);
+            return false;
+        }
+        bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), service);
+
+        result = ca_thread_pool_add_task(g_bleClientThreadPool,
+                                        CADiscoverCharThread,
+                                        stTemp);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                      "ca_thread_pool_add_task failed with ret [%d]", result);
+            OICFree(stTemp->address);
+            OICFree(stTemp);
+            ca_mutex_lock(g_bleServiceListMutex);
+            CARemoveBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo,
+                                         bleServiceInfo->bdAddress);
+            ca_mutex_unlock(g_bleServiceListMutex);
+            ca_mutex_unlock(g_bleClientThreadPoolMutex);
+            return false;
+        }
+        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
+    return true;;
+}
+
+void CABleGattConnectionStateChangedCb(int result, bool connected,
+                                       const char *remoteAddress, void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "CABleGattConnectionStateChangedCb result[%d] ", result);
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
+
+    CAResult_t ret = CA_STATUS_FAILED;
+    if (!connected)
+    {
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "DisConnected from [%s] ", remoteAddress);
+
+        ret = CABleGattStartDeviceDiscovery();
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattStartDeviceDiscovery failed");
+            return;
+        }
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Connected to [%s] ", remoteAddress);
+
+        ca_mutex_lock(g_bleServerBDAddressMutex);
+
+        g_remoteAddress = OICStrdup(remoteAddress);
+
+        ca_mutex_unlock(g_bleServerBDAddressMutex);
+
+        VERIFY_NON_NULL_VOID(g_remoteAddress, TZ_BLE_CLIENT_TAG, "Malloc failed");
+
+        char *addr = OICStrdup(remoteAddress);
+
+        ca_mutex_lock(g_bleClientThreadPoolMutex);
+        if (NULL == g_bleClientThreadPool)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
+            OICFree(addr);
+
+            ca_mutex_lock(g_bleServerBDAddressMutex);
+            OICFree(g_remoteAddress);
+            ca_mutex_unlock(g_bleServerBDAddressMutex);
+
+            ca_mutex_unlock(g_bleClientThreadPoolMutex);
+            return;
+        }
+
+        ret = ca_thread_pool_add_task(g_bleClientThreadPool, CADiscoverBLEServicesThread,
+                                     addr);
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
+            OICFree(addr);
+
+            ca_mutex_lock(g_bleServerBDAddressMutex);
+            OICFree(g_remoteAddress);
+            ca_mutex_unlock(g_bleServerBDAddressMutex);
+
+            ca_mutex_unlock(g_bleClientThreadPoolMutex);
+            return;
+        }
+        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
+        bt_adapter_le_device_discovery_state_e discoveryState,
+        bt_adapter_le_device_discovery_info_s *discoveryInfo,
+        void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    if (NULL  == discoveryInfo && BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND == discoveryState)
+    {
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "discoveryInfo is NULL");
+        return;
+    }
+
+    if (BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND != discoveryState)
+    {
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+                  " LE Discovery state is [%s]",
+          discoveryState == BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED ? "Started" : "Finished");
+    }
+    else
+    {
+        CAPrintDiscoveryInformation(discoveryInfo);
+
+        if (discoveryInfo->service_uuid == NULL)
+        {
+            OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "NO UUIDS from device");
+        }
+        else
+        {
+            for (int32_t i = discoveryInfo->service_count - 1; i >= 0; i--)
+            {
+                OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "uuid[%d]: [%s]",
+                          i, discoveryInfo->service_uuid[i]);
+                CAResult_t res = CAVerifyOICServiceByUUID(discoveryInfo->service_uuid[i]);
+                if (CA_STATUS_OK == res)
+                {
+
+                    size_t len = strlen(discoveryInfo->remote_address);
+
+                    char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+                    VERIFY_NON_NULL_VOID(addr, TZ_BLE_CLIENT_TAG, "Malloc failed");
+                    strncpy(addr, discoveryInfo->remote_address, len + 1);
+
+                    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+                              "Trying to do Gatt connection to [%s]", addr);
+
+                    ca_mutex_lock(g_bleClientThreadPoolMutex);
+                    if (NULL == g_bleClientThreadPool)
+                    {
+                        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
+                        OICFree(addr);
+                        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+                        return;
+                    }
+
+                    CAResult_t ret = ca_thread_pool_add_task(g_bleClientThreadPool,
+                                                  CAGattConnectThread, addr);
+                    if (CA_STATUS_OK != ret)
+                    {
+                        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                                  "ca_thread_pool_add_task failed with ret [%d]", ret);
+                        OICFree(addr);
+                        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+                        return;
+                    }
+                    ca_mutex_unlock(g_bleClientThreadPoolMutex);
+                    if (discoveryInfo->adv_data_len > 31 || discoveryInfo->scan_data_len > 31)
+                    {
+                        bt_adapter_le_stop_device_discovery();
+                        return;
+                    }
+                    break;  // Found the OIC Service. No need to verify remaining services.
+                }
+            }
+        }
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+
+void CAPrintDiscoveryInformation(const bt_adapter_le_device_discovery_info_s *discoveryInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    if (NULL == discoveryInfo)
+    {
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "discoveryInfo is NULL ");
+        return;
+    }
+
+    if (discoveryInfo->remote_address)
+    {
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Remote Address [%s]", discoveryInfo->remote_address);
+    }
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+              " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
+              discoveryInfo->adv_data_len, discoveryInfo->scan_data_len, discoveryInfo->rssi,
+              discoveryInfo->address_type);
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+              " Number of services present in device [%s] is [%d]",
+              discoveryInfo->remote_address, discoveryInfo->service_count);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CASetBleClientThreadPoolHandle(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    ca_mutex_lock(g_bleClientThreadPoolMutex);
+    g_bleClientThreadPool = handle;
+    ca_mutex_unlock(g_bleClientThreadPoolMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CASetBLEReqRespClientCallback(CABLEClientDataReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    ca_mutex_lock(g_bleReqRespClientCbMutex);
+
+    g_bleClientDataReceivedCallback = callback;
+
+    ca_mutex_unlock(g_bleReqRespClientCbMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CAStartBLEGattClient()
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    CAResult_t retVal = CAInitGattClientMutexVariables();
+
+    if (CA_STATUS_OK != retVal)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAInitGattClientMutexVariables failed!");
+        CATerminateGattClientMutexVariables();
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_bleClientThreadPoolMutex);
+    if (NULL == g_bleClientThreadPool)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleServerThreadPool is NULL");
+        CATerminateGattClientMutexVariables();
+        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    retVal = ca_thread_pool_add_task(g_bleClientThreadPool, CAStartBleGattClientThread,
+                                     NULL);
+    if (CA_STATUS_OK != retVal)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_thread_pool_add_task failed");
+        CATerminateGattClientMutexVariables();
+        ca_mutex_unlock(g_bleClientThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_bleClientThreadPoolMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAStartBleGattClientThread(void *data)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    ca_mutex_lock(g_bleClientStateMutex);
+
+    if (true  == g_isBleGattClientStarted)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Gatt Client is already running!!");
+        ca_mutex_unlock(g_bleClientStateMutex);
+        return;
+    }
+
+    CAResult_t  ret = CABleGattSetScanParameter();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleSetScanParameter Failed");
+        ca_mutex_unlock(g_bleClientStateMutex);
+        CATerminateBLEGattClient();
+        return;
+    }
+
+    ret = CABleGattSetCallbacks();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattSetCallbacks Failed");
+        ca_mutex_unlock(g_bleClientStateMutex);
+        CATerminateBLEGattClient();
+        return;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Starting LE device discovery");
+
+    ret = CABleGattStartDeviceDiscovery();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_start_device_discovery Failed");
+        ca_mutex_unlock(g_bleClientStateMutex);
+        CATerminateBLEGattClient();
+        return;
+    }
+
+    g_isBleGattClientStarted = true;
+
+    ca_mutex_unlock(g_bleClientStateMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Giveing the control to threadPool");
+
+    GMainContext *thread_context = g_main_context_new();
+
+    g_eventLoop = g_main_loop_new(thread_context, FALSE);
+
+    g_main_context_push_thread_default(thread_context);
+
+    g_main_loop_run(g_eventLoop);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CAStopBLEGattClient()
+{
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
+
+    ca_mutex_lock(g_bleClientStateMutex);
+
+    if (false == g_isBleGattClientStarted)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Gatt Client is not running to stop");
+        ca_mutex_unlock(g_bleClientStateMutex);
+        return;
+    }
+
+    CABleGattUnSetCallbacks();
+
+    CABleGattUnWatchCharacteristicChanges();
+
+    CABleGattStopDeviceDiscovery();
+
+    g_isBleGattClientStarted = false;
+
+    GMainContext  *context_event_loop = NULL;
+    // Required for waking up the thread which is running in gmain loop
+    if (NULL != g_eventLoop)
+    {
+        context_event_loop = g_main_loop_get_context(g_eventLoop);
+    }
+    if (context_event_loop)
+    {
+        OIC_LOG_V(DEBUG,  TZ_BLE_CLIENT_TAG, "g_eventLoop context %x", context_event_loop);
+        g_main_context_wakeup(context_event_loop);
+
+        // Kill g main loops and kill threads.
+        g_main_loop_quit(g_eventLoop);
+    }
+    else
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_eventLoop context is NULL");
+    }
+
+    ca_mutex_unlock(g_bleClientStateMutex);
+
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CATerminateBLEGattClient()
+{
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
+    ca_mutex_lock(g_bleClientStateMutex);
+
+    ca_mutex_lock(g_bleServerBDAddressMutex);
+
+    OICFree(g_remoteAddress);
+
+    ca_mutex_unlock(g_bleServerBDAddressMutex);
+
+    ca_mutex_lock(g_bleServiceListMutex);
+    CAFreeBLEServiceList(g_bLEServiceList);
+    g_bLEServiceList = NULL;
+    ca_mutex_unlock(g_bleServiceListMutex);
+
+    CAResetRegisteredServiceCount();
+
+    ca_mutex_unlock(g_bleClientStateMutex);
+
+    CATerminateGattClientMutexVariables();
+
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CAInitGattClientMutexVariables()
+{
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
+    if (NULL == g_bleClientStateMutex)
+    {
+        g_bleClientStateMutex = ca_mutex_new();
+        if (NULL == g_bleClientStateMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleServiceListMutex)
+    {
+        g_bleServiceListMutex = ca_mutex_new();
+        if (NULL == g_bleServiceListMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleReqRespClientCbMutex)
+    {
+        g_bleReqRespClientCbMutex = ca_mutex_new();
+        if (NULL == g_bleReqRespClientCbMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleClientThreadPoolMutex)
+    {
+        g_bleClientThreadPoolMutex = ca_mutex_new();
+        if (NULL == g_bleClientThreadPoolMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleClientConnectMutex)
+    {
+        g_bleClientConnectMutex = ca_mutex_new();
+        if (NULL == g_bleClientConnectMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleClientSendCondWait)
+    {
+        g_bleClientSendCondWait = ca_cond_new();
+        if (NULL == g_bleClientSendCondWait)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_cond_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleServerBDAddressMutex)
+    {
+        g_bleServerBDAddressMutex = ca_mutex_new();
+        if (NULL == g_bleServerBDAddressMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateGattClientMutexVariables()
+{
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
+
+    ca_mutex_free(g_bleClientStateMutex);
+    g_bleClientStateMutex = NULL;
+
+    ca_mutex_free(g_bleServiceListMutex);
+    g_bleServiceListMutex = NULL;
+
+    ca_mutex_free(g_bleReqRespClientCbMutex);
+    g_bleReqRespClientCbMutex = NULL;
+
+    ca_mutex_free(g_bleClientConnectMutex);
+    g_bleClientConnectMutex = NULL;
+
+    ca_mutex_free(g_bleClientThreadPoolMutex);
+    g_bleClientThreadPoolMutex = NULL;
+
+    ca_mutex_free(g_bleServerBDAddressMutex);
+    g_bleServerBDAddressMutex = NULL;
+
+    ca_cond_free(g_bleClientSendCondWait);
+    g_bleClientSendCondWait = NULL;
+
+
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CABleGattSetScanParameter()
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    bt_adapter_le_scan_params_s scan_param = { 0, };
+    scan_param.type = BT_ADAPTER_LE_PASSIVE_SCAN;
+    scan_param.interval = 1560;
+    scan_param.window = 160;
+
+    int ret = bt_adapter_le_set_scan_parameter(&scan_param);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_set_scan_parameter Failed with ret [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CABleGattSetCallbacks()
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    int ret = bt_gatt_set_connection_state_changed_cb(CABleGattConnectionStateChangedCb, NULL);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_set_connection_state_changed_cb Failed with return as [%s ]",
+                  CABTGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_adapter_le_set_device_discovery_state_changed_cb(
+              CABtAdapterLeDeviceDiscoveryStateChangedCb, NULL);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_adapter_le_set_device_discovery_state_changed_cb Failed with return as [%s ]",
+                  CABTGetErrorMsg(ret));;
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_gatt_set_characteristic_changed_cb(CABleGattCharacteristicChangedCb, NULL);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_set_characteristic_changed_cb Failed as [%s ]",
+                  CABTGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CABleGattUnSetCallbacks()
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    bt_gatt_unset_characteristic_changed_cb();
+
+    bt_gatt_unset_connection_state_changed_cb();
+
+    bt_adapter_le_unset_device_discovery_state_changed_cb();
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CABleGattWatchCharacteristicChanges(bt_gatt_attribute_h service)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    int ret = bt_gatt_watch_characteristic_changes(service);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_watch_characteristic_changes failed  with [%s]",
+                  CABTGetErrorMsg(ret));
+
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CABleGattUnWatchCharacteristicChanges()
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    int32_t count = CAGetRegisteredServiceCount();
+
+    for (int32_t index = 0; index < count; index++)
+    {
+        BLEServiceInfo *bleServiceInfo = NULL;
+
+        ca_mutex_lock(g_bleServiceListMutex);
+
+        CAResult_t  result = CAGetBLEServiceInfoByPosition(g_bLEServiceList, index, &bleServiceInfo);
+        if (CA_STATUS_OK == result && NULL != bleServiceInfo
+            && NULL != bleServiceInfo->service_clone)
+        {
+            bt_gatt_unwatch_characteristic_changes(bleServiceInfo->service_clone);
+            OIC_LOG(INFO, TZ_BLE_CLIENT_TAG, "bt_gatt_unwatch_characteristic_changes done");
+        }
+
+        ca_mutex_unlock(g_bleServiceListMutex);
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CABleGattStartDeviceDiscovery()
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+    bool isDiscovering = false;
+
+    int ret = bt_adapter_le_is_discovering(&isDiscovering);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_is_discovering Failed");
+        return CA_STATUS_FAILED;
+    }
+
+    if(!isDiscovering)
+    {
+        ret = bt_adapter_le_start_device_discovery();
+        if (BT_ERROR_NONE != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_start_device_discovery Failed Ret: %d, %x", ret, ret);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CABleGattStopDeviceDiscovery()
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    bool isDiscovering = false;
+
+    int ret = bt_adapter_le_is_discovering(&isDiscovering);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_is_discovering Failed");
+        return;
+    }
+
+    if(isDiscovering)
+    {
+        ret = bt_adapter_le_stop_device_discovery();
+        if (BT_ERROR_NONE != ret)
+        {
+            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_stop_device_discovery Failed");
+            return;
+        }
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+void CAGattConnectThread (void *remoteAddress)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
+
+    char *address  = (char *)remoteAddress;
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address is [%s]", address);
+
+    CAResult_t result = CABleGattConnect(address);
+
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_connect failed for [%s]", address);
+    }
+
+    OICFree(address);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CABleGattConnect(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
+
+    //Because of the platform issue, we added. Once platform is stablized, then it will be removed
+    sleep(1);
+
+    ca_mutex_lock(g_bleClientConnectMutex);
+
+    int ret = bt_gatt_connect(remoteAddress, true);
+
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_connect Failed with ret value [%s] ",
+                  CABTGetErrorMsg(ret));
+        ca_mutex_unlock(g_bleClientConnectMutex);
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_bleClientConnectMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CABleGattDisConnect(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
+
+    int32_t ret = bt_gatt_disconnect(remoteAddress);
+
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_disconnect Failed with ret value [%d] ",
+                  ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CADiscoverBLEServicesThread (void *remoteAddress)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
+
+    char *address  = (char *)remoteAddress;
+
+    CAResult_t result = CABleGattDiscoverServices(address);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattDiscoverServices failed");
+    }
+
+    OICFree(address);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
+}
+
+CAResult_t CABleGattDiscoverServices(const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
+
+    size_t len = strlen(remoteAddress);
+    char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+    VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
+
+    strncpy(addr, remoteAddress, len + 1);
+
+    int32_t ret = bt_gatt_foreach_primary_services(remoteAddress, CABleGattPrimaryServiceCb,
+                  (void *)addr); // addr memory will be free in callback.
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_foreach_primary_services Failed with ret value [%d] ", ret);
+        OICFree(addr);
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_foreach_primary_services success for address [%s]", remoteAddress);
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CADiscoverCharThread(void *stServiceInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
+
+    stGattServiceInfo_t *stTemp  = (stGattServiceInfo_t *)stServiceInfo;
+
+    VERIFY_NON_NULL_VOID(stTemp->address, TZ_BLE_CLIENT_TAG, "stTemp->address is NULL");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address [%s]", stTemp->address);
+
+    CAResult_t  result = CABleGattDiscoverCharacteristics(stTemp->serviceInfo, stTemp->address);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CABleGattDiscoverCharacteristics failed!");
+        bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
+        OICFree(stTemp->address);
+        OICFree(stTemp);
+        return;
+    }
+    bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
+    OICFree(stTemp->address);
+    OICFree(stTemp);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service,
+        const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(service, NULL, "service is NULL", CA_STATUS_FAILED);
+
+    VERIFY_NON_NULL_RET(remoteAddress, NULL, "remoteAddress is NULL", CA_STATUS_FAILED);
+
+    size_t len = strlen(remoteAddress);
+
+    char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+    VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
+    strncpy(addr, remoteAddress, len + 1);
+
+    int32_t ret = bt_gatt_discover_characteristics(service, CABleGattCharacteristicsDiscoveredCb,
+                  (void *)addr); // addr will be freed in callback.
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_discover_characteristics failed with error [%d]", ret);
+        OICFree(addr);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CADiscoverDescriptorThread(void *stServiceInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, " IN");
+
+    VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
+
+    stGattServiceInfo_t *stTemp  = (stGattServiceInfo_t *)stServiceInfo;
+
+    CAResult_t result = CABleGattDiscoverDescriptor(stTemp->serviceInfo, NULL);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_discover_characteristic_descriptor failed");
+        bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
+        OICFree(stTemp->address);
+        OICFree(stTemp);
+        return;
+    }
+
+    bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
+    OICFree(stTemp->address);
+    OICFree(stTemp);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service, const char *remoteAddress)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(service, NULL, "service is NULL", CA_STATUS_FAILED);
+
+    int ret = bt_gatt_discover_characteristic_descriptor(service,
+                  CABleGattDescriptorDiscoveredCb, NULL);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_discover_characteristic_descriptor failed with returns[%s]",
+                  CABTGetErrorMsg(ret));
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CASetCharacteristicDescriptorValueThread(void *stServiceInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
+
+    stGattCharDescriptor_t *stTemp  = (stGattCharDescriptor_t *)stServiceInfo;
+
+    CAResult_t  result = CASetCharacteristicDescriptorValue(stTemp);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CASetCharacteristicDescriptorValue failed!");
+        bt_gatt_destroy_attribute_handle(stTemp->characteristic);
+        OICFree(stTemp->desc);
+        OICFree(stTemp);
+        return;
+    }
+    bt_gatt_destroy_attribute_handle(stTemp->characteristic);
+    OICFree(stTemp->desc);
+    OICFree(stTemp);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+}
+
+CAResult_t CASetCharacteristicDescriptorValue(stGattCharDescriptor_t *stGattCharDescInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    unsigned char noti[4] = {0,};
+
+    char *strUUID = (char *)OICCalloc(5, sizeof(char));
+
+    VERIFY_NON_NULL_RET(strUUID, TZ_BLE_CLIENT_TAG, "calloc failed", CA_STATUS_FAILED);
+
+    snprintf(strUUID, 4, "%x%x", stGattCharDescInfo->desc[3], stGattCharDescInfo->desc[2]);
+    noti[0] = stGattCharDescInfo->desc[0];
+    noti[1] = stGattCharDescInfo->desc[1];
+    noti[2] = 0x01;
+    noti[3] = 0x00;
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x0 [%x]", stGattCharDescInfo->desc[0]);
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x1 [%x]", stGattCharDescInfo->desc[1]);
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x2 [%x]", stGattCharDescInfo->desc[2]);
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x3 [%x]", stGattCharDescInfo->desc[3]);
+
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG strUUID is [%s]",
+              strUUID);
+    //if (!strncmp(strUUID, BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG, 2))
+    {
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "setting notification/indication for descriptor");
+
+        int ret =  bt_gatt_set_characteristic_desc_value_request(
+                           stGattCharDescInfo->characteristic,
+                           noti,  4, CABleGattCharacteristicWriteCb);
+        if (BT_ERROR_NONE != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                      "bt_gatt_set_characteristic_desc_value_request failed with return[%s]",
+                      CABTGetErrorMsg(ret));
+            OICFree(strUUID);
+            return CA_STATUS_FAILED;
+        }
+    }
+    OICFree(strUUID);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
+        const char  *data, const uint32_t dataLen,
+        CALETransferType_t type, const int32_t position)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL(data, NULL, "data is NULL");
+
+    if (0 >= dataLen)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "dataLen is less than or equal zero. Invalid input!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    BLEServiceInfo *bleServiceInfo = NULL;
+
+    CAResult_t ret =  CA_STATUS_FAILED;
+
+    ca_mutex_lock(g_bleServiceListMutex);
+    if ( LE_UNICAST == type)
+    {
+        VERIFY_NON_NULL(remoteAddress, NULL, "remoteAddress is NULL");
+
+        ret = CAGetBLEServiceInfo(g_bLEServiceList, remoteAddress, &bleServiceInfo);
+    }
+    else if ( LE_MULTICAST == type)
+    {
+        ret = CAGetBLEServiceInfoByPosition(g_bLEServiceList, position, &bleServiceInfo);
+    }
+    ca_mutex_unlock(g_bleServiceListMutex);
+
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAGetBLEServiceInfoByPosition is failed");
+        return CA_STATUS_FAILED;
+    }
+
+    VERIFY_NON_NULL(bleServiceInfo, NULL, "bleServiceInfo is NULL");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Updating the data of length [%d] to [%s] ", dataLen,
+              bleServiceInfo->bdAddress);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Updating to write char [%s]",
+              bleServiceInfo->read_char);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+              "Updating the data of length [%d] to [%s]", dataLen,
+              bleServiceInfo->bdAddress);
+
+    int result = bt_gatt_set_characteristic_value(bleServiceInfo->write_char, (unsigned char *)data,
+                     dataLen);
+    if (BT_ERROR_NONE != result)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  "bt_gatt_set_characteristic_value Failed with return val [%d]",
+                  result);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t  CAUpdateCharacteristicsToAllGattServers(const char  *data,
+            uint32_t dataLen)
+{
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL(data, NULL, "data is NULL");
+
+    if (0 >= dataLen)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "dataLen is less than or equal zero. Invalid input !");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    int numOfServersConnected = CAGetRegisteredServiceCount();
+
+    for (int32_t pos = 0; pos < numOfServersConnected; pos++)
+    {
+        /*remoteAddress will be NULL.
+          Since we have to send to all destinations. pos will be used for getting remote address.
+         */
+        int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
+
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                      "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
+        }
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
+    return CA_STATUS_OK;
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.h
new file mode 100644 (file)
index 0000000..9985153
--- /dev/null
@@ -0,0 +1,396 @@
+/* ****************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the functionalities of GATT Client. Functionalities
+ * like LE device discovery, connecting to the LE device with OIC service,
+ * registering to the service and there characteristics, registering to the
+ * change in the charateristics, setting the value of the characteristcs
+ * for the request and response will be done here.
+ */
+
+#ifndef TZ_BLE_CLIENT_H_
+#define TZ_BLE_CLIENT_H_
+
+#include <bluetooth.h>
+#include <bluetooth_type.h>
+#include <bluetooth_product.h>
+
+#include "cacommon.h"
+#include "caadapterutils.h"
+#include "cableutil.h"
+#include "caadapterinterface.h"
+#include "logger.h"
+#include "cathreadpool.h"
+#include "caleinterface.h"
+#include "oic_malloc.h"
+
+
+/**
+ * @brief  This is the callback which will be called after the characteristic value changes happen.
+ *
+ * @param  characteristic [IN] The attribute handle of characteristic
+ * @param  value          [IN] Value of the characteristics of a service.
+ * @param  valueLen       [IN] length of data.
+ * @param  userData       [IN] The user data passed from the request function
+ * @return  NONE
+ */
+void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
+                            unsigned char *value, int valueLen, void *userData);
+/**
+ * @brief  This is the callback which will be called after the characteristics changed.
+ *
+ * @param  result   [IN] result of write value
+ * @param  userData [IN] user context
+ *
+ * @return  NONE
+ */
+void CABleGattCharacteristicWriteCb(int result, void *userData);
+
+/**
+ * @brief  This is the callback which will be called when descriptor of characteristics is found.
+ *
+ * @param  result         [IN] The result of discovering
+ * @param  format         [IN] format of descriptor.
+ * @param  total          [IN] The total number of descriptor in a characteristic
+ * @param  descriptor     [IN] The attribute handle of descriptor
+ * @param  characteristic [IN] The attribute handle of characteristic
+ * @param  userData       [IN] The user data passed from the request function
+ * @return  NONE
+ */
+void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total,
+                                     bt_gatt_attribute_h descriptor,
+                                     bt_gatt_attribute_h characteristic, void *userData);
+
+/**
+ * @brief  This is the callback which will be called after the characteristics are discovered by
+ *         bt_gatt_discover_characteristics()
+ *
+ * @param  result         [IN] The result of discovering
+ * @param  inputIndex     [IN] The index of characteristics in a service, starts from 0
+ * @param  total          [IN] The total number of characteristics in a service
+ * @param  characteristic [IN] The attribute handle of characteristic
+ * @param  userData       [IN] The user data passed from the request function
+ *
+ * @return  0 on failure and 1 on success.
+ */
+bool CABleGattCharacteristicsDiscoveredCb(int result, int inputIndex, int total,
+                                          bt_gatt_attribute_h characteristic, void *userData);
+
+/**
+ * @brief  This is the callback which will be called when we get the primary services repeatedly.
+ *
+ * @param service  [IN] The attribute handle of service. Unique identifier for service.
+ * @param index    [IN] The current index of the service
+ * @param count    [IN] Total number of services available in remote device
+ * @param userData [IN] user data
+ *
+ * @return  0 on failure and 1 on success.
+ */
+bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count,
+                                   void *userData);
+
+/**
+ * @brief  This is the callback which will be called whenever there is change in gatt connection
+ *         with server(Connected/Disconnected)
+ *
+ * @param  result        [IN] The result of discovering
+ * @param  connected     [IN] State of connection
+ * @param  remoteAddress [IN] Mac address of the remote device in which we made connection.
+ * @param  userData      [IN] The user data passed from the request function
+ *
+ * @return  NONE
+ */
+void CABleGattConnectionStateChangedCb(int result, bool connected,
+                const char *remoteAddress,void *userData);
+
+/**
+ * @brief  This is the callback which will be called when the device discovery state changes.
+ *
+ * @param  result         [IN] The result of discovering
+ * @param  discoveryState [IN] State of the discovery(FOUND/STARTED/ FINISHED)
+ * @param  discoveryInfo  [IN] Remote Device information.
+ * @param  userData       [IN] The user data passed from the request function
+ *
+ * @return  NONE
+ */
+void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
+        bt_adapter_le_device_discovery_state_e discoveryState,
+        bt_adapter_le_device_discovery_info_s *discoveryInfo,
+        void *userData);
+
+/**
+ * @brief  Used to print device information(Util method)
+ * @param discoveryInfo [IN] Device information structure.
+ * @return  NONE
+ */
+void CAPrintDiscoveryInformation(const bt_adapter_le_device_discovery_info_s *discoveryInfo);
+
+/**
+ * @brief This thread will be used to initialize the Gatt Client and start device discovery.
+ *        1. Set scan parameters
+ *        2. Setting neccessary callbacks for connection, characteristics changed and discovery.
+ *        3. Start device discovery
+ *
+ * @param data [IN] Currently it will be NULL(no parameter)
+ *
+ * @return NONE
+ *
+ */
+void CAStartBleGattClientThread(void *data);
+
+/**
+ * @brief  Used to initialize all required mutex variable for Gatt Client implementation.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitGattClientMutexVariables();
+
+/**
+ * @brief  Used to terminate all required mutex variable for Gatt Client implementation.
+ * @return NONE
+ */
+void CATerminateGattClientMutexVariables();
+
+/**
+ * @brief  Used to clear NonOICDeviceList
+ * @return NONE
+ */
+void CAClearNonOICDeviceList();
+
+/**
+ * @brief  Used to set scan parameter of starting discovery.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattSetScanParameter();
+
+/**
+ * @brief  Used to register required callbacks to BLE platform(connection, discovery, etc).
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattSetCallbacks();
+
+/**
+ * @brief  Used to unset all the registerd callbacks to BLE platform
+ * @return NONE
+ */
+void CABleGattUnSetCallbacks();
+
+/**
+ * @brief  Used to watch all the changes happening in characteristics of the service.
+ *
+ * @param service [IN] The attribute handle of the service.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattWatchCharacteristicChanges(bt_gatt_attribute_h service);
+
+/**
+ * @brief  Used to unwatch characteristics changes using bt_gatt_unwatch_characteristic_changes
+ * @return NONE
+ */
+void CABleGattUnWatchCharacteristicChanges();
+
+/**
+ * @brief  Used to start LE discovery for BLE  devices
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattStartDeviceDiscovery();
+
+/**
+ * @brief  Used to stop LE discovery for BLE  devices
+ * @return NONE
+ */
+void CABleGattStopDeviceDiscovery();
+
+/**
+ * @brief  This is the thread  which will be used for making gatt connection with remote devices
+ * @param remoteAddress [IN] MAC address of remote device to connect
+ * @return NONE
+ */
+void CAGattConnectThread (void *remoteAddress);
+
+/**
+ * @brief  Used to do connection with remote device
+ *
+ * @param remoteAddress [IN] Remote address inwhich we wants to connect with
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattConnect(const char *remoteAddress);
+
+/**
+ * @brief  Used to do disconnection with remote device
+ * @param remoteAddress [IN] Remote address inwhich we wants to disconnect with
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattDisConnect(const char *remoteAddress);
+
+/**
+ * @brief  This is thread which will be spawned for discovering ble services. Once called discover
+ *         api, then it will be terminated.
+ * @param remoteAddress [IN] Mac address of the remote device in which we want to search services.
+ * @return  NONE
+ */
+void CADiscoverBLEServicesThread (void *remoteAddress);
+
+/**
+ * @brief Used to discover the services that is advertised by Gatt Server asynchrounously.
+ *
+ * @param remoteAddress [IN] MAC address of remote device in which we want to discover the services.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattDiscoverServices(const char *remoteAddress);
+
+/**
+ * @brief  This is the thread which will be used for finding characteristic of a service.
+ *
+ * @param  stServiceInfo [IN] Service Information which contains the remote address, service
+ *                            handle and characteristic handle.
+ * @return  NONE
+ */
+void CADiscoverCharThread(void *stServiceInfo);
+
+/**
+ * @brief  Used to discover characteristics of service using  bt_gatt_discover_characteristics api.
+ *
+ * @param service       [IN]  The attribute handle for service.
+ * @param remoteAddress [IN]  Remote address inwhich we wants to discover characteristics of
+ *                            given service handle.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service,
+                    const char *remoteAddress);
+
+/**
+ * @brief  This is the thread which will be used for finding descriptor of characteristic.
+ *
+ * @param  stServiceInfo [IN] Service Information which contains the remote address, service
+ *                            handle and characteristic handle.
+ * @return  NONE
+ */
+void CADiscoverDescriptorThread(void *stServiceInfo);
+
+/**
+ * @brief  This is thread which will be used for calling CASetCharacteristicDescriptorValue api.
+ *
+ * @param service       [IN]  The attribute handle for characteristics.
+ * @param remoteAddress [IN]  Remote address inwhich we wants to discover descriptor of given
+ *                            char handle.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service,
+                const char *remoteAddress);
+
+/**
+ * @brief  This is thread which will be used for calling CASetCharacteristicDescriptorValue api.
+ *
+ * @param  stServiceInfo [IN] Service Information which contains the remote address, service
+ *                            handle and characteristic handle.
+ * @return NONE
+ */
+void CASetCharacteristicDescriptorValueThread(void *stServiceInfo);
+
+/**
+ * @brief  Used to set characteristic descriptor value using
+ *         bt_gatt_set_characteristic_desc_value_request api.
+ * @param  stGattCharDescriptorInfo [IN] Structure which contains char handle and descriptor handle.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CASetCharacteristicDescriptorValue
+            (stGattCharDescriptor_t *stGattCharDescriptorInfo);
+
+/**
+ * @brief  Used to enqueue the message into sender queue using CAAdapterEnqueueMessage and make
+ *         signal to the thread to process.
+ *
+ * @param  remoteEndpoint [IN] Remote device information
+ * @param  data           [IN] Data to be sent to remote device
+ * @param  dataLen        [IN] Length of data.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleClientSenderQueueEnqueueMessage
+                            (const CARemoteEndpoint_t *remoteEndpoint,
+                                                const void *data, uint32_t dataLen);
+
+/**
+ * @brief  This is the thread which will be used for processing sender queue.
+ *
+ * @return  NONE
+ */
+void CABleClientSenderQueueProcessor();
+
+/**
+ * @brief Synchronous function for reading characteristic value.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEReadDataFromLEClient();
+
+#endif /* TZ_BLE_CLIENT_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cablenwmonitor.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cablenwmonitor.c
new file mode 100644 (file)
index 0000000..790a079
--- /dev/null
@@ -0,0 +1,259 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "caleinterface.h"
+
+#include<stdio.h>
+#include<stdlib.h>
+#include<string.h>
+#include<arpa/inet.h>
+#include<sys/types.h>
+#include<sys/socket.h>
+#include<netinet/in.h>
+
+#include <bluetooth.h>
+#include <bluetooth_type.h>
+#include <bluetooth_product.h>
+
+
+#include "camutex.h"
+#include "caleadapter.h"
+#include "caadapterutils.h"
+
+/**
+ * @def TZ_LE_NWK_MONITOR_TAG
+ * @brief Logging tag for module name
+ */
+#define TZ_LE_NWK_MONITOR_TAG "TZ_BLE_ADAPTER_CONTROLLER"
+
+/**
+ * @var g_bleDeviceStateChangedCallback
+ * @brief Maintains the callback to be notified on device state changed.
+ */
+static CALEDeviceStateChangedCallback g_bleDeviceStateChangedCallback = NULL;
+
+/**
+ * @var g_bleDeviceStateChangedCbMutex
+ * @brief Mutex to synchronize access to the deviceStateChanged Callback when the state
+ *           of the LE adapter gets change.
+ */
+static ca_mutex g_bleDeviceStateChangedCbMutex = NULL;
+
+/**
+* @fn  CALEAdapterStateChangedCb
+* @brief  This is the callback which will be called when the adapter state gets changed.
+*
+* @param result         [IN] Result of the query done to the platform.
+* @param adapter_state  [IN] State of the LE adapter.
+* @param user_data      [IN] Any user_data passed by the caller when querying for the state changed cb.
+*
+* @return  None.
+*/
+void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
+                        void *user_data);
+
+CAResult_t CAInitializeLENetworkMonitor()
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    CAResult_t res = CAInitLENetworkMonitorMutexVariables();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "CAInitLENetworkMonitorMutexVariables() failed");
+        return CA_STATUS_FAILED;
+    }
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+void CATerminateLENetworkMonitorMutexVariables()
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+    g_bleDeviceStateChangedCbMutex = NULL;
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+}
+
+void CATerminateLENetworkMonitor()
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    CATerminateLENetworkMonitorMutexVariables();
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+}
+
+CAResult_t CAInitializeLEAdapter()
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    int ret = bt_initialize();
+    if (0 != ret)
+    {
+        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_initialize failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0);
+    if (0 != ret)
+    {
+        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_set_visibility failed");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetLEAdapterState()
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    bt_adapter_state_e adapterState = BT_ADAPTER_DISABLED;
+
+    //Get Bluetooth adapter state
+    int ret = bt_adapter_get_state(&adapterState);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "Bluetooth get state failed!, error num [%x]",
+                  ret);
+        return CA_STATUS_FAILED;
+    }
+
+    if (BT_ADAPTER_ENABLED != adapterState)
+    {
+        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "BT Adapter is not enabled");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetLEAddress(char **local_address)
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(local_address, TZ_LE_NWK_MONITOR_TAG, "local_address is null")
+
+    char *address = NULL;
+
+    int ret = bt_adapter_get_address(&address);
+    if (BT_ERROR_NONE != ret || !address)
+    {
+        OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_get_address failed!, error num [%x]",
+                  ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bd address[%s]", address);
+
+    *local_address = address;
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Setting CALEDeviceStateChangedCallback");
+
+    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    g_bleDeviceStateChangedCallback = callback;
+    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+
+    int ret = bt_adapter_set_state_changed_cb(CALEAdapterStateChangedCb, NULL);
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_set_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
+                                          void *user_data)
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+
+    if (NULL == g_bleDeviceStateChangedCallback)
+    {
+        OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "g_bleDeviceStateChangedCallback is NULL!");
+        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+        return;
+    }
+
+    if (BT_ADAPTER_DISABLED == adapter_state)
+    {
+        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Adapter is disabled");
+        g_bleDeviceStateChangedCallback(CA_ADAPTER_DISABLED);
+        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+        return;
+    }
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Adapter is Enabled");
+    g_bleDeviceStateChangedCallback(CA_ADAPTER_ENABLED);
+    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+}
+
+
+CAResult_t CAUnSetLEAdapterStateChangedCb()
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+
+    int ret = bt_adapter_unset_state_changed_cb();
+    if (BT_ERROR_NONE != ret)
+    {
+        OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_unset_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitLENetworkMonitorMutexVariables()
+{
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+    if (NULL == g_bleDeviceStateChangedCbMutex)
+    {
+        g_bleDeviceStateChangedCbMutex = ca_mutex_new();
+        if (NULL == g_bleDeviceStateChangedCbMutex)
+        {
+            OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c
new file mode 100644 (file)
index 0000000..36889f2
--- /dev/null
@@ -0,0 +1,816 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include <bluetooth.h>
+#include <bluetooth_type.h>
+#include <bluetooth_product.h>
+
+#include "cableserver.h"
+#include <pthread.h>
+#include "cacommon.h"
+#include "caadapterutils.h"
+#include <gio/gio.h>
+#include "camutex.h"
+#include "caqueueingthread.h"
+#include "caadapterutils.h"
+#include "camsgparser.h"
+#include "cableutil.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+
+/**
+ * @def TZ_BLE_SERVER_TAG
+ * @brief Logging tag for module name
+ */
+#define TZ_BLE_SERVER_TAG "TZ_BLE_GATT_SERVER"
+
+/**
+ * @def CA_BLE_SERVICE_UUID
+ * @brief UUID of OIC service. This UUID is common across all platform for LE transport.
+ */
+#define CA_BLE_SERVICE_UUID  "713D0000-503E-4C75-BA94-3148F18D941E"
+
+/**
+ * @def CA_BLE_INITIAL_BUF_SIZE
+ * @brief Initial buffer size for Gatt Server.
+ */
+#define CA_BLE_INITIAL_BUF_SIZE 512
+
+/**
+ * @var g_gattSvcPath
+ * @brief attribute handler for OIC server attribute.
+ */
+static char *g_gattSvcPath = NULL;
+
+/**
+ * @var g_gattReadCharPath
+ * @brief attribute handler for readCharacteristic of OIC server
+ */
+static char *g_gattReadCharPath = NULL;
+
+/**
+ * @var g_gattWriteCharPath
+ * @brief attribute handler for writeCharacteristic of OIC server
+ */
+static char *g_gattWriteCharPath = NULL;
+
+/**
+ * @var g_hAdvertiser
+ * @brief handler for OIC advertiser.
+ */
+static bt_advertiser_h g_hAdvertiser = NULL;
+
+/**
+ * @var    g_bleServerDataReceivedCallback
+ * @brief  Maintains the callback to be notified on receival of network packets from other
+ *           BLE devices
+ */
+static CABLEServerDataReceivedCallback g_bleServerDataReceivedCallback = NULL;
+
+/**
+ * @var g_isBleGattServerStarted
+ * @brief Boolean variable to keep the state of the GATTServer
+ */
+static bool g_isBleGattServerStarted = false;
+
+/**
+ * @var g_bleServerStateMutex
+ * @brief Mutex to synchronize the calls to be done to the platform from GATTServer
+ *           interfaces from different threads.
+ */
+static ca_mutex g_bleServerStateMutex = NULL;
+
+/**
+ * @var g_bleCharacteristicMutex
+ * @brief Mutex to synchronize writing operations on the characteristics.
+ */
+static  ca_mutex g_bleCharacteristicMutex = NULL;
+
+/**
+ * @var g_bleServiceMutex
+ * @brief  Mutex to synchronize to create the OIC service..
+ */
+static  ca_mutex g_bleServiceMutex = NULL;
+
+/**
+ * @var g_bleReqRespCbMutex
+ * @brief Mutex to synchronize access to the requestResponse callback to be called
+ *           when the data needs to be sent from GATTClient.
+ */
+static  ca_mutex g_bleReqRespCbMutex = NULL;
+
+/**
+ * @var g_bleServerThreadPoolMutex
+ * @brief Mutex to synchronize the task to be pushed to thread pool.
+ */
+static ca_mutex g_bleServerThreadPoolMutex = NULL;
+
+/**
+ * @var g_eventLoop
+ * @brief gmainLoop to manage the threads to receive the callback from the platfrom.
+ */
+static GMainLoop *g_eventLoop = NULL;
+
+/**
+ * @var g_bleServerThreadPool
+ * @brief reference to threadpool
+ */
+static ca_thread_pool_t g_bleServerThreadPool = NULL;
+
+void CABleGattServerConnectionStateChangedCb(int result, bool connected,
+                                       const char *remoteAddress, void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "CABleGattConnectionStateChangedCb result[%d]", result);
+
+    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_SERVER_TAG, "remote address is NULL");
+
+    if (connected)
+    {
+        OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Connected to [%s]", remoteAddress);
+    }
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+}
+
+CAResult_t CAStartBleGattServer()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    CAResult_t ret = CAInitGattServerMutexVariables();
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAInitGattServerMutexVariables failed!");
+        CATerminateGattServerMutexVariables();
+        return CA_SERVER_NOT_STARTED;
+    }
+
+    ca_mutex_lock(g_bleServerThreadPoolMutex);
+    if (NULL == g_bleServerThreadPool)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_bleServerThreadPool is NULL");
+        ca_mutex_unlock(g_bleServerThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ret = ca_thread_pool_add_task(g_bleServerThreadPool, CAStartBleGattServerThread,
+                                 NULL);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
+        ca_mutex_unlock(g_bleServerThreadPoolMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_unlock(g_bleServerThreadPoolMutex);
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAStartBleGattServerThread(void *data)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+    ca_mutex_lock(g_bleServerStateMutex);
+    if (true == g_isBleGattServerStarted)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Gatt Server is already running");
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    CAResult_t ret  =  CAInitBleGattService();
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_init_service failed");
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    sleep(5); // Sleep is must because of the platform issue.
+
+    char *serviceUUID = CA_BLE_SERVICE_UUID;
+
+    ret  = CAAddNewBleServiceInGattServer(serviceUUID);
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewBleServiceInGattServer failed");
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    char *charReadUUID = CA_BLE_READ_CHAR_UUID;
+    char charReadValue[] = {33, 44, 55, 66}; // These are initial random values
+
+    ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue,
+            CA_BLE_INITIAL_BUF_SIZE, true); // For Read Characteristics.
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    char *charWriteUUID = CA_BLE_WRITE_CHAR_UUID;
+    char charWriteValue[] = {33, 44, 55, 66}; // These are initial random values
+
+
+    ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue,
+            CA_BLE_INITIAL_BUF_SIZE, false); // For Write Characteristics.
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    ret = CARegisterBleServicewithGattServer(g_gattSvcPath);
+    if (CA_STATUS_OK != ret )
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CARegisterBleServicewithGattServer failed");
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    int res = bt_gatt_set_connection_state_changed_cb(CABleGattServerConnectionStateChangedCb,
+                                                          NULL);
+    if (BT_ERROR_NONE != res)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                  "bt_gatt_set_connection_state_changed_cb Failed with return as [%s]",
+                  CABTGetErrorMsg(res));
+        return;
+    }
+
+    bt_adapter_le_create_advertiser(&g_hAdvertiser);
+    if (NULL == g_hAdvertiser)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_hAdvertiser is NULL");
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    res = bt_adapter_le_start_advertising(g_hAdvertiser, NULL, NULL, NULL);
+    if (BT_ERROR_NONE != res)
+    {
+        OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "bt_adapter_le_start_advertising failed with ret [%d] ",
+                  res);
+        ca_mutex_unlock(g_bleServerStateMutex);
+        CATerminateBleGattServer();
+        return;
+    }
+
+    g_isBleGattServerStarted = true;
+
+    ca_mutex_unlock(g_bleServerStateMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG,
+            "LE Server initialization complete.");
+
+    GMainContext *thread_context = NULL;
+
+    thread_context = g_main_context_new();
+
+    g_eventLoop = g_main_loop_new(thread_context, FALSE);
+
+    g_main_context_push_thread_default(thread_context);
+
+    g_main_loop_run(g_eventLoop);
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+}
+
+CAResult_t CAStopBleGattServer()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    ca_mutex_lock(g_bleServerStateMutex);
+
+    if (false == g_isBleGattServerStarted)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Gatt Server is not running to stop");
+
+        ca_mutex_unlock(g_bleServerStateMutex);
+        return CA_STATUS_OK;
+    }
+
+    g_isBleGattServerStarted = false;
+    if (NULL != g_hAdvertiser )
+    {
+        int ret = 0;
+        ret  = bt_adapter_le_stop_advertising(g_hAdvertiser);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                      "bt_adapter_le_stop_advertising failed with ret [%d]", ret);
+        }
+
+        ret = bt_adapter_le_destroy_advertiser(g_hAdvertiser);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                      "bt_adapter_le_destroy_advertiser failed with ret [%d]", ret);
+        }
+        g_hAdvertiser = NULL;
+    }
+
+    CAResult_t res = CARemoveAllBleServicesFromGattServer();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "removeAllBleServicesFromGattServer failed");
+    }
+
+    res =  CADeInitBleGattService();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", res);
+    }
+
+    GMainContext  *context_event_loop = NULL;
+    // Required for waking up the thread which is running in gmain loop
+    if (NULL != g_eventLoop)
+    {
+        context_event_loop = g_main_loop_get_context(g_eventLoop);
+
+        if (context_event_loop)
+        {
+            OIC_LOG_V(DEBUG,  TZ_BLE_SERVER_TAG, "g_eventLoop context %x", context_event_loop);
+            g_main_context_wakeup(context_event_loop);
+
+            // Kill g main loops and kill threads
+            g_main_loop_quit(g_eventLoop);
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_eventLoop context is NULL");
+    }
+
+    ca_mutex_unlock(g_bleServerStateMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateBleGattServer()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    ca_mutex_lock(g_bleServerStateMutex);
+
+    // free service Path(unique identifier for ble service)
+    ca_mutex_lock(g_bleServiceMutex);
+    OICFree(g_gattSvcPath);
+    g_gattSvcPath = NULL;
+    ca_mutex_unlock(g_bleServiceMutex);
+
+    // freeing characteristics
+    ca_mutex_lock(g_bleCharacteristicMutex);
+    OICFree(g_gattReadCharPath);
+    g_gattReadCharPath = NULL;
+    OICFree(g_gattWriteCharPath);
+    g_gattWriteCharPath = NULL;
+    ca_mutex_unlock(g_bleCharacteristicMutex);
+
+    ca_mutex_unlock(g_bleServerStateMutex);
+
+    // Terminating all mutex variables.
+    CATerminateGattServerMutexVariables();
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+}
+
+CAResult_t CAInitGattServerMutexVariables()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+    if (NULL == g_bleServerStateMutex)
+    {
+        g_bleServerStateMutex = ca_mutex_new();
+        if (NULL == g_bleServerStateMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleServiceMutex)
+    {
+        g_bleServiceMutex = ca_mutex_new();
+        if (NULL == g_bleServiceMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleCharacteristicMutex)
+    {
+        g_bleCharacteristicMutex = ca_mutex_new();
+        if (NULL == g_bleCharacteristicMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    if (NULL == g_bleReqRespCbMutex)
+    {
+        g_bleReqRespCbMutex = ca_mutex_new();
+        if (NULL == g_bleReqRespCbMutex)
+        {
+            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "ca_mutex_new failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateGattServerMutexVariables()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+    ca_mutex_free(g_bleServerStateMutex);
+    g_bleServerStateMutex = NULL;
+
+
+    g_bleServerStateMutex = NULL;
+    ca_mutex_free(g_bleServiceMutex);
+    g_bleServiceMutex = NULL;
+    ca_mutex_free(g_bleCharacteristicMutex);
+    g_bleCharacteristicMutex = NULL;
+    ca_mutex_free(g_bleReqRespCbMutex);
+    g_bleReqRespCbMutex = NULL;
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+}
+
+CAResult_t CAInitBleGattService()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    int ret =  _bt_gatt_init_service();
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CADeInitBleGattService()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    int ret =  _bt_gatt_deinit_service();
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CASetBleServerThreadPoolHandle(ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+    ca_mutex_lock(g_bleServerThreadPoolMutex);
+    g_bleServerThreadPool = handle;
+    ca_mutex_unlock(g_bleServerThreadPoolMutex);
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+}
+
+CAResult_t CAAddNewBleServiceInGattServer(const char *serviceUUID)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceUUID, NULL, "Param serviceUUID is NULL");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "service uuid %s", serviceUUID);
+
+    char *svcPath = NULL;
+
+    int ret = bt_gatt_add_service(serviceUUID, &svcPath);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_add_service failed with ret [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    if (NULL != svcPath)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                  "AddNewBleServiceInGattServer ServicePath obtained is %s", svcPath);
+
+        ca_mutex_lock(g_bleServiceMutex);
+
+        if (NULL != g_gattSvcPath)
+        {
+            OICFree(g_gattSvcPath);
+            g_gattSvcPath = NULL;
+        }
+        g_gattSvcPath = svcPath;
+
+        ca_mutex_unlock(g_bleServiceMutex);
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARemoveBleServiceFromGattServer(const char *svcPath)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(svcPath, NULL, "Param svcPath is NULL");
+
+    int ret = bt_gatt_remove_service(svcPath);
+
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_remove_service failed [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARemoveAllBleServicesFromGattServer()
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+    int ret = bt_gatt_delete_services();
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_delete_services  failed with ret [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CABleGattRemoteCharacteristicWriteCb(char *charPath,
+        unsigned char *charValue,
+        int charValueLen, const char *remoteAddress, void *userData)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    if (NULL == charPath || NULL == charValue || NULL == remoteAddress)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Param callback values are NULL");
+        return;
+    }
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "charPath = [%s] charValue = [%s] len [%d]", charPath,
+              charValue, charValueLen);
+
+    char *data = (char *)OICMalloc(sizeof(char) * charValueLen);
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Malloc failed!");
+        return;
+    }
+
+    strncpy(data, (char *)charValue, charValueLen);
+
+    ca_mutex_lock(g_bleReqRespCbMutex);
+    if (NULL == g_bleServerDataReceivedCallback)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gReqRespCallback is NULL!");
+        ca_mutex_unlock(g_bleReqRespCbMutex);
+        OICFree(data);
+        return;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "Sending data up !");
+    uint32_t sentLength = 0;
+    g_bleServerDataReceivedCallback(remoteAddress, OIC_BLE_SERVICE_ID,
+                                     data, charValueLen, &sentLength);
+
+    ca_mutex_unlock(g_bleReqRespCbMutex);
+
+    OICFree(data);
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+}
+
+CAResult_t CARegisterBleServicewithGattServer(const char *svcPath)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(svcPath, NULL, "Param svcPath is NULL");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "svcPath:%s", svcPath);
+
+    int ret = bt_gatt_register_service(svcPath, CABleGattRemoteCharacteristicWriteCb, NULL);
+
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_register_service failed with ret [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *charUUID,
+        const char *charValue, int charValueLen, bool read)
+{
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    char *charFlags[1];
+    if(read)
+    {
+        charFlags[0] = "notify";
+    }
+    else
+    {
+        charFlags[0] = "write-without-response";
+    }
+
+    size_t flagLen = sizeof(charFlags) / sizeof(charFlags[0]);
+
+    char *charPath = NULL;
+    int ret = bt_gatt_add_characteristic(charUUID, charValue, charValueLen, charFlags, flagLen,
+                  svcPath, &charPath);
+
+    if (0 != ret || NULL == charPath)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                  "bt_gatt_add_characteristic  failed with ret [%d]", ret);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG,
+              "bt_gatt_add_characteristic charPath obtained: %s", charPath);
+
+    ca_mutex_lock(g_bleCharacteristicMutex);
+
+    if (read)
+    {
+        if (NULL != g_gattReadCharPath)
+        {
+            OICFree(g_gattReadCharPath);
+            g_gattReadCharPath = NULL;
+        }
+        g_gattReadCharPath = charPath;
+
+    }
+    else
+    {
+        if (NULL != g_gattWriteCharPath)
+        {
+            OICFree(g_gattWriteCharPath);
+            g_gattWriteCharPath = NULL;
+        }
+        g_gattWriteCharPath = charPath;
+    }
+
+    ca_mutex_unlock(g_bleCharacteristicMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARemoveCharacteristicsFromGattServer(const char *charPath)
+{
+    ///TODO: There is no api provided in bluetooth.h for removing characteristics.
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToGattClient(const char* address, const char *charValue,
+        const uint32_t charValueLen)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(charValue, NULL, "Param charValue is NULL");
+
+    VERIFY_NON_NULL(address, NULL, "Param address is NULL");
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Client's Unicast address for sending data [%s]", address);
+
+    ca_mutex_lock(g_bleCharacteristicMutex);
+
+    if (NULL  == g_gattReadCharPath)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_gattReadCharPath is NULL");
+        ca_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    char *data = (char *) OICMalloc(sizeof(char) * (charValueLen + 1));
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
+        ca_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+    memset(data, 0x0, (charValueLen + 1));
+
+    strncpy(data, charValue, charValueLen);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
+              (const char *)g_gattReadCharPath, data, charValueLen);
+
+    int ret =  bt_gatt_update_characteristic(g_gattReadCharPath, data, charValueLen, address);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                  "bt_gatt_update_characteristic failed with return [%d]", ret);
+        OICFree(data);
+        ca_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    OICFree(data);
+    ca_mutex_unlock(g_bleCharacteristicMutex);
+
+    OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
+        const uint32_t charValueLen)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(charValue, NULL, "Param charValue is NULL");
+
+    ca_mutex_lock(g_bleCharacteristicMutex);
+
+    if (NULL  == g_gattReadCharPath)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_gattReadCharPath is NULL");
+        ca_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    char *data = (char *) OICMalloc(sizeof(char) * (charValueLen + 1));
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
+        ca_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    strncpy(data, charValue, charValueLen + 1);
+
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
+              (const char *)g_gattReadCharPath, data, charValueLen);
+
+    int ret =  bt_gatt_update_characteristic(g_gattReadCharPath, data, charValueLen, NULL);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
+                  "bt_gatt_update_characteristic failed with return [%d]", ret);
+        OICFree(data);
+        ca_mutex_unlock(g_bleCharacteristicMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    OICFree(data);
+    ca_mutex_unlock(g_bleCharacteristicMutex);
+
+    OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CASetBLEReqRespServerCallback(CABLEServerDataReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
+
+    ca_mutex_lock(g_bleReqRespCbMutex);
+
+    g_bleServerDataReceivedCallback = callback;
+
+    ca_mutex_unlock(g_bleReqRespCbMutex);
+
+    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
+}
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h
new file mode 100644 (file)
index 0000000..fc087ae
--- /dev/null
@@ -0,0 +1,224 @@
+/* ****************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the APIs related to the GATT Server functionalities.
+ * Creation of the GattServer with the characteristics. Enabling the
+ * advertisement and updating the characteristics for the response and
+ * notifying the change of characteristcs for the request will be done here.
+ * LE adapter will interact with this sub module.
+ */
+
+#ifndef TZ_BLE_SERVER_H_
+#define TZ_BLE_SERVER_H_
+
+#include "caadapterinterface.h"
+#include "logger.h"
+#include "cathreadpool.h"
+#include "caleinterface.h"
+
+/**
+ * @brief  This is thread which will be used for creating ble service and advertise ble service.
+ *         1. Create New OIC Service 2. Add two read & write characteristics to service.
+ *         3. Register Service     4. Advertise service.
+ *
+ * @param data [IN] Currently it will be NULL.
+ * @return  NONE
+ */
+void CAStartBleGattServerThread(void *data);
+
+/**
+ * @brief  Used to initialize gatt service using _bt_gatt_init_service api.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitBleGattService();
+
+/**
+ * @brief  Used to de-initialize gatt service using _bt_gatt_deinit_service api.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CADeInitBleGattService();
+
+/**
+ * @brief  Used to initialize all required mutex variables for GATT server implementation.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAInitGattServerMutexVariables();
+
+
+/**
+ * @brief  Used to terminate all required mutex variables for GATT server implementation.
+ * @return NONE
+ */
+void CATerminateGattServerMutexVariables();
+
+/**
+ * @brief  Used to add new OIC service in GATT server using bt_gatt_add_service api and
+ *         internally store service path(outparam) in global variable.
+ *
+ * @param  serviceUUID [IN] unique identifier for BLE OIC service.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAAddNewBleServiceInGattServer(const char *serviceUUID);
+
+/**
+ * @brief  Used to remove already registered service from Gatt Server using
+ *         bt_gatt_remove_service api.
+ * @param svcPath [IN] unique identifier for BLE OIC service which is outparam of
+ *                     bt_gatt_add_service api.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CARemoveBleServiceFromGattServer(const char *svcPath);
+
+/**
+ * @brief  Used to remove all the registered service from Gatt Server using
+ *         bt_gatt_delete_services api.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CARemoveAllBleServicesFromGattServer();
+
+/**
+ * @brief  Used to register the service in Gatt Server using bt_gatt_register_service api.
+ *
+ * @param svcPath [IN] unique identifier for BLE OIC service which is outparam of
+ *                     bt_gatt_add_service api.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CARegisterBleServicewithGattServer(const char *svcPath);
+
+/**
+ * @brief  Used to add new characteristics(Read/Write) to the service in Gatt Server using
+ *         bt_gatt_add_characteristic api.
+ * @param svcPath        [IN] Service path to which this characteristic belongs to.
+ * @param charUUID       [IN] Gatt characteristic uuid.
+ * @param charValue      [IN] Gatt characteristic value.
+ * @param charValueLen   [IN] Characteristic value length.
+ * @param read           [IN] Boolean variable for checking whether read characteristics or
+ *                            write characteristics.
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *charUUID,
+                                               const char *charValue, int charValueLen,
+                                               bool read);
+
+/**
+ * @brief  Used to remove characteristics(Read/Write) from the service in Gatt Server.
+ *
+ * @param  charPath  [IN] Characteristic path registered on the interface and unique identifier
+ *                        for added characteristics.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CARemoveCharacteristicsFromGattServer(const char *charPath);
+
+/**
+ * @brief  This is the callback which will be called when client update one of the characteristics
+ *         with data.
+ * @param  charPath      [IN] characteristic path registered on the interface and unique
+ *                            identifier for added characteristics.
+ * @param  charValue     [IN] data which is send by client.
+ * @param  charValueLen  [IN] length of the data.
+ * @param  remoteAddress [IN] remote device bluetooth address in which data is received.
+ * @param  userData      [IN] user data
+ *
+ * @return NONE
+ */
+void CABleGattRemoteCharacteristicWriteCb(char *charPath, unsigned char *charValue,
+                                          int charValueLen, const char  *remoteAddress,
+                                          void *userData);
+
+/**
+ * @brief  This is the callback which will be called whenever there is change in gatt connection
+ *         with Client(Connected/Disconnected).
+ *
+ * @param  result        [IN] The result of discovering.
+ * @param  connected     [IN] State of connection.
+ * @param  remoteAddress [IN] Mac address of the remote device in which we made connection.
+ * @param  userData      [IN] The user data passed from the request function.
+ *
+ * @return  NONE
+ */
+void CABleGattServerConnectionStateChangedCb(int result, bool connected,
+                                             const char *remoteAddress, void *userData);
+
+/**
+ * @brief  Synchronous function for reading characteristic value.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEReadDataFromLEServer();
+
+/**
+ * @brief  Used to enqueue the message into sender queue using CAAdapterEnqueueMessage and make
+ *         signal to the thread to process.
+ *
+ * @param  remoteEndpoint [IN] Remote device information.
+ * @param  data           [IN] Data to be sent to remote device.
+ * @param  dataLen        [IN] Length of data.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CABleServerSenderQueueEnqueueMessage
+                (const CARemoteEndpoint_t *remoteEndpoint, const void *data, uint32_t dataLen);
+
+/**
+ * @brief  This is the thread which will be used for processing receiver queue.
+ * @return NONE
+ */
+void *CABleServerSenderQueueProcessor();
+
+#endif /* TZ_BLE_SERVER_H_ */
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c
new file mode 100644 (file)
index 0000000..cc2eb81
--- /dev/null
@@ -0,0 +1,448 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "cableutil.h"
+
+#include<stdio.h>
+#include<stdlib.h>
+#include<string.h>
+#include<arpa/inet.h>
+#include<sys/types.h>
+#include<sys/socket.h>
+#include<netinet/in.h>
+
+
+#include "caadapterutils.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+
+/**
+ * @def TZ_BLE_CLIENT_UTIL_TAG
+ * @brief Logging tag for module name
+ */
+#define TZ_BLE_CLIENT_UTIL_TAG "TZ_BLE_GATT_CLIENT_UTIL"
+
+/**
+ * @var g_numberOfServiceConnected
+ * @brief Number of services connected.
+ */
+static int32_t g_numberOfServiceConnected = 0;
+
+void CAIncrementRegisteredServiceCount()
+{
+    g_numberOfServiceConnected++;
+}
+
+void CADecrementRegisteredServiceCount()
+{
+    g_numberOfServiceConnected--;
+}
+
+void CAResetRegisteredServiceCount()
+{
+    g_numberOfServiceConnected = 0;
+}
+
+int32_t  CAGetRegisteredServiceCount()
+{
+    return g_numberOfServiceConnected ;
+}
+
+CAResult_t CACreateBLEServiceInfo(const char *bdAddress, bt_gatt_attribute_h service,
+                                  BLEServiceInfo **bleServiceInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(bdAddress, NULL, "Param bdAddress is NULL");
+    VERIFY_NON_NULL(service, NULL, "Param service is NULL");
+    VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
+
+    *bleServiceInfo = (BLEServiceInfo *) OICCalloc(1, sizeof(BLEServiceInfo));
+    if (NULL == *bleServiceInfo)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
+        return CA_STATUS_FAILED;
+    }
+
+    size_t len = strlen(bdAddress);
+    (*bleServiceInfo)->bdAddress = (char *) OICMalloc(sizeof(char) * (len + 1));
+
+    if (NULL == (*bleServiceInfo)->bdAddress)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
+        OICFree(*bleServiceInfo);
+        return CA_STATUS_FAILED;
+    }
+
+    strncpy((*bleServiceInfo)->bdAddress, bdAddress, len + 1);
+
+    if (service)
+    {
+        int32_t ret = bt_gatt_clone_attribute_handle(&((*bleServiceInfo)->service_clone), service);
+
+        if (BT_ERROR_NONE != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "service handle clone failed with ret [%d]",
+                      ret);
+            OICFree((*bleServiceInfo)->bdAddress);
+            OICFree(*bleServiceInfo);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAAppendBLECharInfo( bt_gatt_attribute_h characteristic, CHAR_TYPE type,
+                                BLEServiceInfo *bleServiceInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(characteristic, NULL, "Param characteristic is NULL");
+    VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
+
+    if (BLE_GATT_READ_CHAR == type )
+    {
+        int ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->read_char),
+            characteristic);
+        if (BT_ERROR_NONE != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "read_char clone failed with ret [%d]",
+                      ret);
+            return CA_STATUS_FAILED;
+        }
+    }
+    else  if (BLE_GATT_WRITE_CHAR == type)
+    {
+        int ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->write_char),
+            characteristic);
+        if (BT_ERROR_NONE != ret)
+        {
+            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "write_char clone failed with ret [%d]",
+                      ret);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList,
+    BLEServiceInfo *bleServiceInfo)
+{
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceList, NULL, "Param serviceList is NULL");
+    VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
+
+    BLEServiceList *node = (BLEServiceList *) OICCalloc(1, sizeof(BLEServiceList));
+    if (NULL == node)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
+        return CA_STATUS_FAILED;
+    }
+
+    node->serviceInfo = bleServiceInfo;
+    node->next = NULL;
+
+    if (*serviceList == NULL)   // Empty list
+    {
+        *serviceList = node;
+    }
+    else     // Add at front end
+    {
+        node->next = *serviceList;
+        *serviceList = node;
+    }
+
+    CAIncrementRegisteredServiceCount();
+
+    OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "Device [%s] added to list",
+        bleServiceInfo->bdAddress);
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARemoveBLEServiceInfoToList(BLEServiceList **serviceList,
+                                        BLEServiceInfo *bleServiceInfo,
+                                        const char *bdAddress)
+{
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceList, NULL, "Param serviceList is NULL");
+    VERIFY_NON_NULL(*serviceList, NULL, "Param *serviceList is NULL");
+    VERIFY_NON_NULL(bdAddress, NULL, "Param bdAddress is NULL");
+
+    BLEServiceList *prev = NULL;
+    BLEServiceList *cur = *serviceList;
+    while (cur != NULL)
+    {
+        if (!strcasecmp(cur->serviceInfo->bdAddress, bdAddress))
+        {
+            if (cur == *serviceList)
+            {
+                *serviceList = cur->next;
+
+                cur->next = NULL;
+                CAFreeBLEServiceList(cur);
+                CADecrementRegisteredServiceCount();
+                OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+                return CA_STATUS_OK;
+            }
+            else
+            {
+                prev->next = cur->next;
+
+                cur->next = NULL;
+                CAFreeBLEServiceList(cur);
+                CADecrementRegisteredServiceCount();
+                OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+                return CA_STATUS_OK;
+            }
+        }
+        else
+        {
+            prev = cur;
+            cur = cur->next;
+        }
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, " OUT");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CAGetBLEServiceInfo(BLEServiceList *serviceList, const char *bdAddress,
+                               BLEServiceInfo **bleServiceInfo)
+{
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceList, NULL, "Param serviceList is NULL");
+    VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
+    VERIFY_NON_NULL(bdAddress, NULL, "Param bdAddress is NULL");
+
+
+    BLEServiceList *cur = serviceList;
+    *bleServiceInfo = NULL;
+    while (cur != NULL)
+    {
+        if (!strcasecmp(cur->serviceInfo->bdAddress, bdAddress))
+        {
+            *bleServiceInfo = cur->serviceInfo;
+            OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+            return CA_STATUS_OK;
+        }
+
+        cur = cur->next;
+    }
+
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, " OUT");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CAGetBLEServiceInfoByPosition(BLEServiceList *serviceList, int32_t position,
+        BLEServiceInfo **bleServiceInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceList, NULL, "Param serviceList is NULL");
+    VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
+
+    if (0 > position)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Position Invalid input !");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    *bleServiceInfo = NULL;
+    int32_t count = 0;
+    BLEServiceList *cur = serviceList;
+    while (cur != NULL)
+    {
+        if (position == count)
+        {
+            *bleServiceInfo = cur->serviceInfo;
+            OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+            return CA_STATUS_OK;
+        }
+        count++;
+        cur = cur->next;
+    }
+    return CA_STATUS_FAILED;
+}
+
+void CAFreeBLEServiceList(BLEServiceList *serviceList)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+    while (serviceList)
+    {
+        BLEServiceList *temp = serviceList;
+        serviceList = serviceList->next;
+        CAFreeBLEServiceInfo(temp->serviceInfo);
+        OICFree(temp);
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+}
+
+void CAFreeBLEServiceInfo(BLEServiceInfo *bleServiceInfo)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+    if (bleServiceInfo)
+    {
+        if (bleServiceInfo->bdAddress)
+        {
+            bt_gatt_disconnect(bleServiceInfo->bdAddress);
+            OICFree(bleServiceInfo->bdAddress);
+            bt_gatt_destroy_attribute_handle(bleServiceInfo->service_clone);
+            bt_gatt_destroy_attribute_handle(bleServiceInfo->read_char);
+            bt_gatt_destroy_attribute_handle(bleServiceInfo->write_char);
+        }
+        OICFree(bleServiceInfo);
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+}
+
+CAResult_t CAVerifyOICServiceByUUID(const char* serviceUUID)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceUUID, NULL, "Param serviceHandle is NULL");
+
+    if (strcasecmp(serviceUUID, OIC_BLE_SERVICE_ID) != 0)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "It is not OIC service!");
+        return CA_STATUS_FAILED;
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAVerifyOICServiceByServiceHandle(bt_gatt_attribute_h serviceHandle)
+{
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
+
+    VERIFY_NON_NULL(serviceHandle, NULL, "Param serviceHandle is NULL");
+
+    char *uuid = NULL;
+    int ret = bt_gatt_get_service_uuid(serviceHandle, &uuid);
+
+    if (0 != ret || NULL == uuid)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "bt_gatt_get_service_uuid failed !");
+        return CA_STATUS_FAILED;
+    }
+
+    if (strcasecmp(uuid, OIC_BLE_SERVICE_ID) != 0)
+    {
+        OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "It is not OIC service!");
+        OICFree(uuid);
+        return CA_STATUS_FAILED;
+    }
+
+    OICFree(uuid);
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+const char *CABTGetErrorMsg(bt_error_e err)
+{
+    const char *errStr = NULL;
+
+    switch (err)
+    {
+        case BT_ERROR_NONE:
+            errStr = "BT_ERROR_NONE";
+            break;
+        case BT_ERROR_CANCELLED:
+            errStr = "BT_ERROR_CANCELLED";
+            break;
+        case BT_ERROR_INVALID_PARAMETER:
+            errStr = "BT_ERROR_INVALID_PARAMETER";
+            break;
+        case BT_ERROR_OUT_OF_MEMORY:
+            errStr = "BT_ERROR_OUT_OF_MEMORY";
+            break;
+        case BT_ERROR_RESOURCE_BUSY:
+            errStr = "BT_ERROR_RESOURCE_BUSY";
+            break;
+        case BT_ERROR_TIMED_OUT:
+            errStr = "BT_ERROR_TIMED_OUT";
+            break;
+        case BT_ERROR_NOW_IN_PROGRESS:
+            errStr = "BT_ERROR_NOW_IN_PROGRESS";
+            break;
+        case BT_ERROR_NOT_INITIALIZED:
+            errStr = "BT_ERROR_NOT_INITIALIZED";
+            break;
+        case BT_ERROR_NOT_ENABLED:
+            errStr = "BT_ERROR_NOT_ENABLED";
+            break;
+        case BT_ERROR_ALREADY_DONE:
+            errStr = "BT_ERROR_ALREADY_DONE";
+            break;
+        case BT_ERROR_OPERATION_FAILED:
+            errStr = "BT_ERROR_OPERATION_FAILED";
+            break;
+        case BT_ERROR_NOT_IN_PROGRESS:
+            errStr = "BT_ERROR_NOT_IN_PROGRESS";
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_BONDED:
+            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_BONDED";
+            break;
+        case BT_ERROR_AUTH_REJECTED:
+            errStr = "BT_ERROR_AUTH_REJECTED";
+            break;
+        case BT_ERROR_AUTH_FAILED:
+            errStr = "BT_ERROR_AUTH_FAILED";
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_FOUND:
+            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_FOUND";
+            break;
+        case BT_ERROR_SERVICE_SEARCH_FAILED:
+            errStr = "BT_ERROR_SERVICE_SEARCH_FAILED";
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED:
+            errStr = "BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED";
+            break;
+        case BT_ERROR_PERMISSION_DENIED:
+            errStr = "BT_ERROR_PERMISSION_DENIED";
+            break;
+        case BT_ERROR_SERVICE_NOT_FOUND:
+            errStr = "BT_ERROR_SERVICE_NOT_FOUND";
+            break;
+        case BT_ERROR_NOT_SUPPORTED:
+            errStr = "BT_ERROR_NOT_SUPPORTED";
+            break;
+        default:
+            errStr = "NOT Defined";
+            break;
+    }
+
+    return errStr;
+}
+
+
diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.h
new file mode 100644 (file)
index 0000000..b390f78
--- /dev/null
@@ -0,0 +1,275 @@
+/* ****************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the util function for LE adapter. This maintains the
+ * list of services an individual GATT Client connected to and operations on
+ * that list, such as getting the service info with BD address or with
+ * position etc. This is mainly useful for the multicast transmission of
+ * data where client needs to have the info of all the services to which it
+ * is connected.
+ */
+
+#ifndef TZ_BLE_UTIL_H_
+#define TZ_BLE_UTIL_H_
+
+#include <bluetooth.h>
+
+#include "cacommon.h"
+
+/**
+ * @struct BLEServiceInfo
+ * @brief Information regarding the GATTServer
+ *
+ * This structure holds the infomation about the GATTServer
+ * in the service and the characteristic level
+ */
+typedef struct
+{
+    bt_gatt_attribute_h service_clone; /**< GATT attribute handler for the OIC service. */
+    bt_gatt_attribute_h read_char;     /**< GATT attribute handler for OIC read characteristic.
+                                            Server will read.*/
+    bt_gatt_attribute_h write_char;    /**< GATT attribute handler for OIC write characteristic.
+                                            server will write*/
+    char *bdAddress;                   /**< BD address where OIC service is running. */
+} BLEServiceInfo;
+
+/**
+ * @struct BLEServiceList
+ * @brief List of the BLEServiceInfo structures.
+ *
+ * A list of BLEServiceInfo and gives the info about all the
+ * the registered services from the client side.
+ */
+typedef struct _BLEServiceList
+{
+    BLEServiceInfo *serviceInfo;    /**< BLEServiceInfo structure from an OIC Server */
+    struct _BLEServiceList *next;   /**< Next reference to the List*/
+} BLEServiceList;
+
+/**
+ * @enum CHAR_TYPE
+ * @brief Different characteristics types.
+ *
+ *  This provides information of different characteristics
+ *  which will be added to OIC service.
+ */
+typedef enum
+{
+    BLE_GATT_WRITE_CHAR = 0, /**< write_char This will be used to get the unicast response */
+    BLE_GATT_READ_CHAR,      /**< read_char This will be used update value to OIC server */
+    BLE_GATT_NOTIFY_CHAR     /**< Reserved char for the time being. */
+} CHAR_TYPE;
+
+/**
+ * @struct stGattCharDescriptor_t
+ * @brief Stores the information required to set the descriptor value of the Service.
+ */
+typedef struct gattCharDescriptor
+{
+    bt_gatt_attribute_h characteristic; /**< The attribute handle of descriptor */
+    uint8_t *desc;                      /**< Descriptor handle of characteristic, in byte array*/
+    int total;                          /**< The total number of descriptor in a characteristic */
+} stGattCharDescriptor_t;
+
+#define OIC_BLE_SERVICE_ID "713D0000-503E-4C75-BA94-3148F18D941E"
+///TODO: OIC_BLE_SERVICE_ID  will be generated by invoking API in future.
+
+/**
+ * @def CA_BLE_READ_CHAR_UUID
+ * @brief UUID of read characteristic. This UUID is common across all platform for LE transport.
+ */
+#define CA_BLE_READ_CHAR_UUID "713D0002-503E-4C75-BA94-3148F18D941E"
+
+/**
+ * @def CA_BLE_WRITE_CHAR_UUID
+ * @brief UUID of write characteristic. This UUID is common across all platform for LE transport.
+ */
+#define CA_BLE_WRITE_CHAR_UUID "713D0003-503E-4C75-BA94-3148F18D941E"
+
+/**
+ * @brief  Used to increment the registered service count.
+ * @return NONE
+ */
+void CAIncrementRegisteredServiceCount();
+
+/**
+ * @brief  Used to decrement the registered service count.
+ *
+ * @return NONE.
+ */
+void CADecrementRegisteredServiceCount();
+
+/**
+ * @brief  Used to reset the registered service count.
+ * @return  NONE
+ */
+void CAResetRegisteredServiceCount();
+
+/**
+ * @brief  Used to get the total registered service count.
+ * @return  Total registered service count.
+ */
+int32_t  CAGetRegisteredServiceCount();
+
+/**
+ * @brief  Used to create BLEServiceInfo structure with server handler and BD address will be
+ *         created.
+ * @param bdAddress      [IN] BD address of the device where GATTServer is running.
+ * @param service        [IN] service attribute handler.
+ * @param bleServiceInfo [IN] Pointer where serviceInfo structure needs to be stored.
+ *                            Memory will be allocated here and needs to be cleared by caller.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CACreateBLEServiceInfo(const char *bdAddress, bt_gatt_attribute_h service,
+                                  BLEServiceInfo **bleServiceInfo);
+
+/**
+ * @brief  Used to append the characteristic info to the already created serviceInfo structure.
+ *
+ * @param characteristic [IN] Charecteristic attribute handler.
+ * @param type           [IN] Specifies whether its BLE_GATT_READ_CHAR or BLE_GATT_WRITE_CHAR
+ * @param bleServiceInfo [IN] Pointer where serviceInfo structure needs to be appended with
+ *                            char info.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAAppendBLECharInfo(bt_gatt_attribute_h characteristic, CHAR_TYPE type,
+                               BLEServiceInfo *bleServiceInfo);
+
+/**
+ * @brief  Used to add the ServiceInfo structure to the Service List.
+ *
+ * @param serviceList    [IN] Pointer to the ble service list which holds the info of list of
+ *                            service registered from client.
+ * @param bleServiceInfo [IN] Pointer where serviceInfo structure needs to be appended with
+ *                            char info.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList,
+                BLEServiceInfo *bleServiceInfo);
+
+/**
+ * @brief  Used to remove the ServiceInfo structure from the Service List.
+ *
+ * @param serviceList    [IN] Pointer to the ble service list which holds the info of list of
+ *                            service registered from client.
+ * @param bleServiceInfo [IN] Pointer where serviceInfo structure needs to be appended with
+ *                            char info.
+ * @param bdAddress      [IN] BD address of the device where GATTServer is disconnected.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CARemoveBLEServiceInfoToList(BLEServiceList **serviceList,
+                                        BLEServiceInfo *bleServiceInfo,
+                                        const char *bdAddress);
+
+/**
+ * @brief  Used to get the serviceInfo from the list.
+ *
+ * @param serviceList    [IN]  Pointer to the ble service list which holds the info of list
+ *                             of service registered from client.
+ * @param bdAddress      [IN]  BD address of the device where GATTServer information is required.
+ * @param bleServiceInfo [OUT] Pointer where serviceInfo structure needs to provide the service
+ *                             and char info.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAGetBLEServiceInfo(BLEServiceList *serviceList, const char *bdAddress,
+                               BLEServiceInfo **bleServiceInfo);
+
+/**
+ * @brief  Used to get the serviceInfo from the list by position.
+ *
+ * @param serviceList    [IN]  Pointer to the ble service list which holds the info of list
+ *                             of service registered from client.
+ * @param position       [IN]  The service information of particular position in the list.
+ * @param bleServiceInfo [OUT] Pointer where serviceInfo structure needs to provide the service
+ *                             and char info.
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAGetBLEServiceInfoByPosition(BLEServiceList *serviceList, int32_t position,
+                                         BLEServiceInfo **bleServiceInfo);
+
+/**
+ * @brief  Used to clear BLE service list
+ *
+ * @param  serviceList [IN] Pointer to the ble service list which holds the info of list of
+ *                          service registered from client.
+ * @return NONE
+ */
+void CAFreeBLEServiceList(BLEServiceList *serviceList);
+
+/**
+ * @brief Used to get remove particular BLE service info from list
+ * @param serviceinfo [IN] Pointer to the structure which needs to be cleared.
+ *
+ * @return NONE
+ */
+void CAFreeBLEServiceInfo(BLEServiceInfo *bleServiceInfo);
+
+/**
+ * @brief  Used to check whether found handle is OIC service handle or not.
+ *
+ * @param serviceHandle [IN] Discovered service handle(unique identifier for service)
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAVerifyOICServiceByServiceHandle(bt_gatt_attribute_h serviceHandle);
+
+/**
+ * @brief  Used to check whether UUID of the discovered device is OIC service or not.
+ *
+ * @param  serviceUUID [IN] Service UUID
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK  Successful
+ * @retval #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAVerifyOICServiceByUUID(const char* serviceUUID);
+
+/**
+ * @brief  Used to get the Error message.
+ * @param err [IN] Error code(#bt_error_e)
+ * @return  Error string corresponding to the BT error code.
+ */
+const char *CABTGetErrorMsg(bt_error_e err);
+
+#endif /* TZ_BLE_UTIL_H_ */
index 29da713..1eabcec 100644 (file)
 #include "cainterface.h"
 #include "caremotehandler.h"
 #include "camessagehandler.h"
+#include "caprotocolmessage.h"
 #include "canetworkconfigurator.h"
 #include "cainterfacecontroller.h"
 #include "logger.h"
 
 #define TAG PCF("CA")
 
-static void CAMessageHandler(int32_t id, CADetachErrorCode code)
-{
-}
+#ifdef __WITH_DTLS__
+// CAAdapterNetDTLS will register the callback.
+// Taking callback all the way through adapters not the right approach, hence calling here.
+extern void CADTLSSetCredentialsCallback(CAGetDTLSCredentialsHandler credCallback);
+#endif
 
 CAResult_t CAInitialize()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAInitialize");
-
-    CASetMessageHandlerCallback(CAMessageHandler);
-
-    CAResult_t res = CAInitializeMessageHandler();
-
-    if (res != CA_STATUS_OK)
-    {
-        return res;
-    }
+    OIC_LOG(DEBUG, TAG, "CAInitialize");
 
-    return CA_STATUS_OK;
+    return CAInitializeMessageHandler();;
 }
 
 void CATerminate()
 {
-    OIC_LOG_V(DEBUG, TAG, "CATerminate");
+    OIC_LOG(DEBUG, TAG, "CATerminate");
 
     CATerminateMessageHandler();
+
+    CATerminateNetworkType();
 }
 
 CAResult_t CAStartListeningServer()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartListeningServer");
+    OIC_LOG(DEBUG, TAG, "CAStartListeningServer");
 
     return CAStartListeningServerAdapters();
 }
 
 CAResult_t CAStartDiscoveryServer()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStartDiscoveryServer");
+    OIC_LOG(DEBUG, TAG, "CAStartDiscoveryServer");
 
     return CAStartDiscoveryServerAdapters();
 }
 
-CAResult_t CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
+void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
 {
-    OIC_LOG_V(DEBUG, TAG, "CARegisterHandler");
+    OIC_LOG(DEBUG, TAG, "CARegisterHandler");
 
     CASetRequestResponseCallbacks(ReqHandler, RespHandler);
+}
 
+#ifdef __WITH_DTLS__
+CAResult_t CARegisterDTLSCredentialsHandler(
+                                             CAGetDTLSCredentialsHandler GetDTLSCredentialsHandler)
+{
+    OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
+    CADTLSSetCredentialsCallback(GetDTLSCredentialsHandler);
     return CA_STATUS_OK;
 }
+#endif //__WITH_DTLS__
 
-CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, CARemoteEndpoint_t** remoteEndpoint)
+CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, const CATransportType_t transportType,
+                                  CARemoteEndpoint_t **remoteEndpoint)
 {
-    OIC_LOG_V(DEBUG, TAG, "CACreateRemoteEndpoint");
-
-    CARemoteEndpoint_t* remote = CACreateRemoteEndpointUriInternal(uri);
+    OIC_LOG(DEBUG, TAG, "CACreateRemoteEndpoint");
 
-    *remoteEndpoint = remote;
+    CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, transportType);
 
     if (remote == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "remote is NULL!");
         return CA_STATUS_FAILED;
+    }
+
+    *remoteEndpoint = remote;
 
     return CA_STATUS_OK;
 }
 
-void CADestroyRemoteEndpoint(CARemoteEndpoint_trep)
+void CADestroyRemoteEndpoint(CARemoteEndpoint_t *rep)
 {
-    OIC_LOG_V(DEBUG, TAG, "CADestroyRemoteEndpoint");
+    OIC_LOG(DEBUG, TAG, "CADestroyRemoteEndpoint");
 
     CADestroyRemoteEndpointInternal(rep);
 }
 
-CAResult_t CAGenerateToken(CAToken_t* token)
+CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAGenerateToken");
+    OIC_LOG(DEBUG, TAG, "CAGenerateToken");
 
-    return CAGenerateTokenInternal(token);
+    return CAGenerateTokenInternal(token, tokenLength);
 }
 
 void CADestroyToken(CAToken_t token)
 {
-    OIC_LOG_V(DEBUG, TAG, "CADestroyToken");
+    OIC_LOG(DEBUG, TAG, "CADestroyToken");
 
     CADestroyTokenInternal(token);
 }
 
-CAResult_t CAGetNetworkInformation(CALocalConnectivityt_t **info, uint32_t* size)
+CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAGetNetworkInformation");
+    OIC_LOG(DEBUG, TAG, "CAGetNetworkInformation");
 
-    return CA_NOT_SUPPORTED;
+    return CAGetNetworkInformationInternal(info, size);
 }
 
-CAResult_t CAFindResource(const CAURI_t resourceUri)
+CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token, uint8_t tokenLength)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAFindResource");
-
-    int32_t actionId = -1;
-
-    actionId = CADetachMessageResourceUri(resourceUri);
+    OIC_LOG(DEBUG, TAG, "CAFindResource");
 
-    if (actionId == -1)
-        return CA_SEND_FAILED;
+    return CADetachMessageResourceUri(resourceUri, token, tokenLength, NULL, 0);
 
-    OIC_LOG_V(DEBUG, TAG, "action id : %d", actionId);
-
-    return CA_STATUS_OK;
 }
 
-CAResult_t CASendRequest(const CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo)
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object,const CARequestInfo_t *requestInfo)
 {
-    OIC_LOG_V(DEBUG, TAG, "CASendGetRequest");
-
-    int32_t actionId = -1;
-
-    actionId = CADetachRequestMessage(object, requestInfo);
-
-    if (actionId == -1)
-        return CA_SEND_FAILED;
+    OIC_LOG(DEBUG, TAG, "CASendGetRequest");
 
-    OIC_LOG_V(DEBUG, TAG, "action id : %d", actionId);
-
-    return CA_STATUS_OK;
+    return CADetachRequestMessage(object, requestInfo);
 }
 
-CAResult_t CASendNotification(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo)
+CAResult_t CASendRequestToAll(const CAGroupEndpoint_t *object,
+                              const CARequestInfo_t *requestInfo)
 {
-    OIC_LOG_V(DEBUG, TAG, "CASendNotification");
+    OIC_LOG(DEBUG, TAG, "CASendRequestToAll");
 
-    return CA_NOT_SUPPORTED;
+    return CADetachRequestToAllMessage(object, requestInfo);
 }
 
-CAResult_t CASendResponse(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo)
+CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
+    const CAResponseInfo_t *responseInfo)
 {
-    OIC_LOG_V(DEBUG, TAG, "CASendResponse");
+    OIC_LOG(DEBUG, TAG, "CASendNotification");
 
-    int32_t actionId = -1;
+    return CADetachResponseMessage(object, responseInfo);
 
-    actionId = CADetachResponseMessage(object, responseInfo);
+}
 
-    if (actionId == -1)
-        return CA_SEND_FAILED;
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
+    const CAResponseInfo_t *responseInfo)
+{
+    OIC_LOG(DEBUG, TAG, "CASendResponse");
 
-    OIC_LOG_V(DEBUG, TAG, "action id : %d", actionId);
+    return CADetachResponseMessage(object, responseInfo);
 
-    return CA_STATUS_OK;
 }
 
-CAResult_t CAAdvertiseResource(const CAURI_t uri, CAHeaderOption_t* options, uint8_t numOptions)
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
+                               uint8_t tokenLength, const CAHeaderOption_t *options,
+                               const uint8_t numOptions)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAAdvertiseResource");
+    OIC_LOG(DEBUG, TAG, "CAAdvertiseResource");
+
+    return CADetachMessageResourceUri(resourceUri, token, tokenLength, options, numOptions);
 
-    return CA_NOT_SUPPORTED;
 }
 
 CAResult_t CASelectNetwork(const uint32_t interestedNetwork)
@@ -193,45 +190,28 @@ CAResult_t CASelectNetwork(const uint32_t interestedNetwork)
     {
         return CA_NOT_SUPPORTED;
     }
-    CAResult_t res;
 
-    if (interestedNetwork & CA_ETHERNET)
-    {
-        res = CAAddNetworkType(CA_ETHERNET);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
-    }
+    CAResult_t res = CA_STATUS_OK;
 
-    if (interestedNetwork & CA_WIFI)
+    if (interestedNetwork & CA_IPV4)
     {
-        res = CAAddNetworkType(CA_WIFI);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
+        res = CAAddNetworkType(CA_IPV4);
+        OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_IPV4) function returns error : %d", res);
     }
 
     if (interestedNetwork & CA_EDR)
     {
         res = CAAddNetworkType(CA_EDR);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
+        OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_EDR) function returns error : %d", res);
     }
 
     if (interestedNetwork & CA_LE)
     {
         res = CAAddNetworkType(CA_LE);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
+        OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_LE) function returns error : %d", res);
     }
 
-    return CA_STATUS_OK;
+    return res;
 }
 
 CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork)
@@ -243,53 +223,36 @@ CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork)
         return CA_NOT_SUPPORTED;
     }
 
-    CAResult_t res;
+    CAResult_t res = CA_STATUS_OK;
 
-    if (nonInterestedNetwork & CA_ETHERNET)
+    if (nonInterestedNetwork & CA_IPV4)
     {
-        res = CARemoveNetworkType(CA_ETHERNET);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
-    }
-
-    if (nonInterestedNetwork & CA_WIFI)
-    {
-        res = CARemoveNetworkType(CA_WIFI);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
+        res = CARemoveNetworkType(CA_IPV4);
+        OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_IPV4) function returns error : %d", res);
     }
 
     if (nonInterestedNetwork & CA_EDR)
     {
         res = CARemoveNetworkType(CA_EDR);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
+        OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_EDR) function returns error : %d", res);
     }
 
     if (nonInterestedNetwork & CA_LE)
     {
         res = CARemoveNetworkType(CA_LE);
-        if (res != CA_STATUS_OK)
-        {
-            return res;
-        }
+        OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_LE) function returns error : %d", res);
     }
 
-    return CA_STATUS_OK;
+    return res;
 }
 
 CAResult_t CAHandleRequestResponse()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAHandleRequestResponse");
+    OIC_LOG(DEBUG, TAG, "CAHandleRequestResponse");
 
     CAHandleRequestResponseCallbacks();
 
     return CA_STATUS_OK;
 }
 
+
diff --git a/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c b/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c
new file mode 100644 (file)
index 0000000..8d25223
--- /dev/null
@@ -0,0 +1,245 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+#include "cainterface.h"
+#include "caremotehandler.h"
+#include "caprotocolmessage.h"
+#include "canetworkconfigurator.h"
+#include "logger.h"
+
+#include "cainterfacecontroller_singlethread.h"
+#include "camessagehandler_singlethread.h"
+
+#define TAG "CM_ST"
+
+CAResult_t CAInitialize()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    return CAInitializeMessageHandler();
+}
+
+void CATerminate()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CASetRequestResponseCallbacks(NULL, NULL);
+    CATerminateMessageHandler();
+
+    CATerminateNetworkType();
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAStartListeningServer()
+{
+    return CAStartListeningServerAdapters();
+}
+
+CAResult_t CAStartDiscoveryServer()
+{
+    return CAStartDiscoveryServerAdapters();
+}
+
+void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CASetRequestResponseCallbacks(ReqHandler, RespHandler);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, const CATransportType_t transportType,
+                                  CARemoteEndpoint_t **remoteEndpoint)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, transportType);
+
+    if (remote == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "remote endpoint is NULL");
+        return CA_STATUS_FAILED;
+    }
+
+    *remoteEndpoint = remote;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CADestroyRemoteEndpoint(CARemoteEndpoint_t *rep)
+{
+    CADestroyRemoteEndpointInternal(rep);
+}
+
+CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength)
+{
+    return CAGenerateTokenInternal(token, tokenLength);
+}
+
+void CADestroyToken(CAToken_t token)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CADestroyTokenInternal(token);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    return CAGetNetworkInformationInternal(info, size);
+}
+
+CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token, uint8_t tokenLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    return CADetachMessageResourceUri(resourceUri, token, tokenLength, NULL, 0);
+}
+
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object,const CARequestInfo_t *requestInfo)
+{
+    return CADetachRequestMessage(object, requestInfo);
+}
+
+CAResult_t CASendRequestToAll(const CAGroupEndpoint_t *object,
+                              const CARequestInfo_t *requestInfo)
+{
+    OIC_LOG(DEBUG, TAG, "CASendRequestToAll");
+
+    return CADetachRequestToAllMessage(object, requestInfo);
+}
+
+CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
+    const CAResponseInfo_t *responseInfo)
+{
+    return CADetachResponseMessage(object, responseInfo);
+}
+
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
+    const CAResponseInfo_t *responseInfo)
+{
+    return CADetachResponseMessage(object, responseInfo);
+}
+
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
+                               uint8_t tokenLength, const CAHeaderOption_t *options,
+                               const uint8_t numOptions)
+{
+    return CADetachMessageResourceUri(resourceUri, token, tokenLength, options, numOptions);
+}
+
+CAResult_t CASelectNetwork(const uint32_t interestedNetwork)
+{
+    OIC_LOG_V(DEBUG, TAG, "Selected n/W=%d", interestedNetwork);
+
+    if (!(interestedNetwork & 0xf))
+    {
+        OIC_LOG(ERROR, TAG, "not supported");
+        return CA_NOT_SUPPORTED;
+    }
+    CAResult_t res = CA_STATUS_OK;
+
+    if (interestedNetwork & CA_IPV4)
+    {
+        res = CAAddNetworkType(CA_IPV4);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
+            return res;
+        }
+    }
+
+    if (interestedNetwork & CA_EDR)
+    {
+        res = CAAddNetworkType(CA_EDR);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
+            return res;
+        }
+    }
+
+    if (interestedNetwork & CA_LE)
+    {
+        res = CAAddNetworkType(CA_LE);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
+            return res;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return res;
+}
+
+CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork)
+{
+    OIC_LOG_V(DEBUG, TAG, "unselected n/w=%d", nonInterestedNetwork);
+
+    if (!(nonInterestedNetwork & 0xf))
+    {
+        OIC_LOG(ERROR, TAG, "not supported");
+        return CA_NOT_SUPPORTED;
+    }
+
+    CAResult_t res = CA_STATUS_OK;
+
+    if (nonInterestedNetwork & CA_IPV4)
+    {
+        res = CARemoveNetworkType(CA_IPV4);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
+            return res;
+        }
+    }
+
+    if (nonInterestedNetwork & CA_EDR)
+    {
+        res = CARemoveNetworkType(CA_EDR);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
+            return res;
+        }
+    }
+
+    if (nonInterestedNetwork & CA_LE)
+    {
+        res = CARemoveNetworkType(CA_LE);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
+            return res;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return res;
+}
+
+CAResult_t CAHandleRequestResponse()
+{
+    CAHandleRequestResponseCallbacks();
+    return CA_STATUS_OK;
+}
+
+
index 981eef9..2abc0a8 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <stdint.h>
+#include <inttypes.h>
 
 #include "cainterfacecontroller.h"
+#include "caipadapter.h"
 #include "caedradapter.h"
 #include "caleadapter.h"
-#include "cawifiethernetadapter.h"
 #include "canetworkconfigurator.h"
+#include "caremotehandler.h"
+#include "oic_malloc.h"
 #include "logger.h"
+#include "cathreadpool.h"
 
 #define TAG PCF("CA")
 
-#define CA_CONNECTIVITY_TYPE_NUM   4
+#define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \
+    {OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} }
 
-static CAConnectivityHandler_t gAdapterHandler[CA_CONNECTIVITY_TYPE_NUM];
+#define CA_TRANSPORT_TYPE_NUM   4
 
-static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL;
+static CAConnectivityHandler_t g_adapterHandler[CA_TRANSPORT_TYPE_NUM];
 
-static int8_t CAGetAdapterIndex(CAConnectivityType_t cType)
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
+
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
+
+static int CAGetAdapterIndex(CATransportType_t cType)
 {
     switch (cType)
     {
-        case CA_ETHERNET:
+        case CA_IPV4:
             return 0;
-        case CA_WIFI:
+        case CA_IPV6:
             return 1;
         case CA_EDR:
             return 2;
         case CA_LE:
             return 3;
     }
+
+    OIC_LOG(DEBUG, TAG, "CA_TRANSPORT_TYPE_NUM is not 4");
+
     return -1;
 }
 
-static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityType_t cType)
+static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_t cType)
 {
-    int8_t index = -1;
+    OIC_LOG(DEBUG, TAG, "CARegisterCallback - Entry");
+
+    if(handler.startAdapter == NULL ||
+        handler.startListenServer == NULL ||
+        handler.startDiscoveryServer == NULL ||
+        handler.sendData == NULL ||
+        handler.sendDataToAll == NULL ||
+        handler.GetnetInfo == NULL ||
+        handler.readData == NULL ||
+        handler.stopAdapter == NULL ||
+        handler.terminate == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "connectivity handler is not enough to be used!");
+        return;
+    }
 
-    index = CAGetAdapterIndex(cType);
+    int index = CAGetAdapterIndex(cType);
 
     if (index == -1)
     {
-        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        OIC_LOG(ERROR, TAG, "unknown connectivity type!");
         return;
     }
 
-    memcpy(&gAdapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
+    memcpy(&g_adapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
 
     OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType);
 }
 
-static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
+                                     uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TAG, "receivedPacketCallback in interface controller");
 
     // Call the callback.
-    if (gNetworkPacketReceivedCallback != NULL)
+    if (g_networkPacketReceivedCallback != NULL)
+    {
+        g_networkPacketReceivedCallback(endpoint, data, dataLen);
+    }
+    else
     {
-        gNetworkPacketReceivedCallback(endpoint, data, dataLen);
+        OICFree(endpoint);
+        endpoint = NULL;
+        OICFree(data);
+        data = NULL;
+
+        OIC_LOG(ERROR, TAG, "network packet received callback is NULL!");
     }
 }
 
-static void CANetworkChangedCallback(CALocalConnectivityt_t* info, CANetworkStatus_t status)
+static void CANetworkChangedCallback(CALocalConnectivity_t *info,
+                                     CANetworkStatus_t status)
 {
     OIC_LOG(DEBUG, TAG, "Network Changed callback");
+
+    // Call the callback.
+    if (g_networkChangeCallback != NULL)
+    {
+        g_networkChangeCallback(info, status);
+    }
 }
 
-void CAInitializeAdapters()
+void CAInitializeAdapters(ca_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, TAG, "initialize adapters..");
 
-    memset(gAdapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM);
+    memset(g_adapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_TRANSPORT_TYPE_NUM);
 
     // Initialize adapters and register callback.
-#ifdef ETHERNET_ADAPTER
-    CAInitializeEthernet(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
-#endif /* ETHERNET_ADAPTER */
-
-#ifdef WIFI_ADAPTER
-    CAInitializeWifi(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
-#endif /* WIFI_ADAPTER */
+#ifdef IP_ADAPTER
+    CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+                         handle);
+#endif /* IP_ADAPTER */
 
 #ifdef EDR_ADAPTER
-    CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+    CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+                    handle);
 #endif /* EDR_ADAPTER */
 
 #ifdef LE_ADAPTER
-    CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+    CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+                   handle);
 #endif /* LE_ADAPTER */
 
 }
@@ -116,86 +157,185 @@ void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback)
 {
     OIC_LOG(DEBUG, TAG, "Set packet received callback");
 
-    gNetworkPacketReceivedCallback = callback;
+    g_networkPacketReceivedCallback = callback;
 }
 
-void CAStartAdapter(CAConnectivityType_t cType)
+void CASetNetworkChangeCallback(CANetworkChangeCallback callback)
 {
-    OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", cType);
+    OIC_LOG(DEBUG, TAG, "Set network change callback");
 
-    int8_t index = -1;
+    g_networkChangeCallback = callback;
+}
+
+CAResult_t CAStartAdapter(CATransportType_t transportType)
+{
+    OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", transportType);
 
-    index = CAGetAdapterIndex(cType);
+    int index = CAGetAdapterIndex(transportType);
 
     if (index == -1)
     {
-        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
-        return;
+        OIC_LOG(ERROR, TAG, "unknown connectivity type!");
+        return CA_STATUS_FAILED;
     }
 
-    if (gAdapterHandler[index].startAdapter != NULL)
+    if (g_adapterHandler[index].startAdapter != NULL)
     {
-        gAdapterHandler[index].startAdapter();
+        g_adapterHandler[index].startAdapter();
     }
+
+    return CA_STATUS_OK;
 }
 
-void CAStopAdapter(CAConnectivityType_t cType)
+void CAStopAdapter(CATransportType_t transportType)
 {
-    OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CAConnectivityType[%d]", cType);
-
-    int8_t index = -1;
+    OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CATransportType[%d]", transportType);
 
-    index = CAGetAdapterIndex(cType);
+    int index = CAGetAdapterIndex(transportType);
 
     if (index == -1)
     {
-        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        OIC_LOG(ERROR, TAG, "unknown transport type!");
         return;
     }
 
-    if (gAdapterHandler[index].stopAdapter != NULL)
+    if (g_adapterHandler[index].stopAdapter != NULL)
+    {
+        g_adapterHandler[index].stopAdapter();
+    }
+}
+
+CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size)
+{
+    if (info == NULL || size == NULL)
+    {
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    CALocalConnectivity_t *tempInfo[CA_TRANSPORT_TYPE_NUM] = { 0 };
+    uint32_t tempSize[CA_TRANSPORT_TYPE_NUM] = { 0 };
+
+    CAResult_t res = CA_STATUS_FAILED;
+    uint32_t resSize = 0;
+    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
+    {
+        if (g_adapterHandler[index].GetnetInfo != NULL)
+        {
+            // #1. get information for each adapter
+            res = g_adapterHandler[index].GetnetInfo(&tempInfo[index],
+                                                     &tempSize[index]);
+
+            // #2. total size
+            if (res == CA_STATUS_OK)
+            {
+                resSize += tempSize[index];
+            }
+
+            OIC_LOG_V(DEBUG,
+                      TAG,
+                      "%d adapter network info size is %" PRIu32 " res:%d",
+                      index,
+                      tempSize[index],
+                      res);
+        }
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "network info total size is %d!", resSize);
+
+    if (resSize == 0)
+    {
+        if (res == CA_ADAPTER_NOT_ENABLED || res == CA_NOT_SUPPORTED)
+        {
+            return res;
+        }
+        return CA_STATUS_FAILED;
+    }
+
+    // #3. add data into result
+    // memory allocation
+
+    CALocalConnectivity_t * resInfo = OICCalloc(resSize, sizeof(*resInfo));
+    CA_MEMORY_ALLOC_CHECK(resInfo);
+
+    // #4. save data
+    *info = resInfo;
+    *size = resSize;
+
+    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
     {
-        gAdapterHandler[index].stopAdapter();
+        // check information
+        if (tempSize[index] == 0)
+        {
+            continue;
+        }
+
+        memcpy(resInfo,
+               tempInfo[index],
+               sizeof(*resInfo) * tempSize[index]);
+
+        resInfo += tempSize[index];
+
+        // free adapter data
+        OICFree(tempInfo[index]);
+        tempInfo[index] = NULL;
     }
+
+    OIC_LOG(DEBUG, TAG, "each network info save success!");
+    return CA_STATUS_OK;
+
+    // memory error label.
+memory_error_exit:
+
+    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
+    {
+
+        OICFree(tempInfo[index]);
+        tempInfo[index] = NULL;
+    }
+
+    return CA_MEMORY_ALLOC_FAILED;
 }
 
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t length)
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length)
 {
     OIC_LOG(DEBUG, TAG, "Send unicast data to enabled interface..");
 
-    int8_t index = -1;
     CAResult_t res = CA_STATUS_FAILED;
 
     if (endpoint == NULL)
     {
-        OIC_LOG_V(DEBUG, TAG, "Invalid endpoint");
+        OIC_LOG(DEBUG, TAG, "Invalid endpoint");
         return CA_STATUS_INVALID_PARAM;
     }
 
-    CAConnectivityType_t type = endpoint->connectivityType;
+    CATransportType_t type = endpoint->transportType;
 
-    index = CAGetAdapterIndex(type);
+    int index = CAGetAdapterIndex(type);
 
     if (index == -1)
     {
-        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        OIC_LOG(ERROR, TAG, "unknown transport type!");
         return CA_STATUS_INVALID_PARAM;
     }
 
-    if (gAdapterHandler[index].sendData != NULL)
+    uint32_t sentDataLen = 0;
+
+    if (g_adapterHandler[index].sendData != NULL)
     {
-        res = gAdapterHandler[index].sendData(endpoint, data, length);
+        sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
     }
 
+    if (sentDataLen != -1)
+    {
+        res = CA_STATUS_OK;
+    }
     return res;
 }
 
-CAResult_t CASendMulticastData(void* data, uint32_t length)
+CAResult_t CASendMulticastData(const void *data, uint32_t length)
 {
     OIC_LOG(DEBUG, TAG, "Send multicast data to enabled interface..");
 
-    uint8_t i, type;
-    int8_t index = -1;
     CAResult_t res = CA_STATUS_FAILED;
     u_arraylist_t *list = CAGetSelectedNetworkList();
 
@@ -205,11 +345,19 @@ CAResult_t CASendMulticastData(void* data, uint32_t length)
         return CA_STATUS_FAILED;
     }
 
+    int i = 0;
     for (i = 0; i < u_arraylist_length(list); i++)
     {
-        type = *(int*) u_arraylist_get(list, i);
+        void* ptrType = u_arraylist_get(list, i);
+
+        if(ptrType == NULL)
+        {
+            continue;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
 
-        index = CAGetAdapterIndex(type);
+        int index = CAGetAdapterIndex(connType);
 
         if (index == -1)
         {
@@ -217,9 +365,28 @@ CAResult_t CASendMulticastData(void* data, uint32_t length)
             continue;
         }
 
-        if (gAdapterHandler[index].sendDataToAll != NULL)
+        uint32_t sentDataLen = 0;
+
+        if (g_adapterHandler[index].sendDataToAll != NULL)
+        {
+            void *payload = (void *) OICMalloc(length);
+            if (!payload)
+            {
+                OIC_LOG(ERROR, TAG, "Out of memory!");
+                return CA_MEMORY_ALLOC_FAILED;
+            }
+            memcpy(payload, data, length);
+            sentDataLen = g_adapterHandler[index].sendDataToAll(payload, length);
+            OICFree(payload);
+        }
+
+        if (sentDataLen == length)
         {
-            res = gAdapterHandler[index].sendDataToAll(data, length);
+           res = CA_STATUS_OK;
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "sendDataToAll failed!");
         }
     }
 
@@ -230,31 +397,35 @@ CAResult_t CAStartListeningServerAdapters()
 {
     OIC_LOG(DEBUG, TAG, "Start listening server from adapters..");
 
-    uint8_t i, type;
-    int8_t index = -1;
     u_arraylist_t *list = CAGetSelectedNetworkList();
-
     if (!list)
     {
-        OIC_LOG(DEBUG, TAG, "No selected network");
+        OIC_LOG(ERROR, TAG, "No selected network");
         return CA_STATUS_FAILED;
     }
 
+    int i = 0;
     for (i = 0; i < u_arraylist_length(list); i++)
     {
-        type = *(int*) u_arraylist_get(list, i);
+        void* ptrType = u_arraylist_get(list, i);
 
-        index = CAGetAdapterIndex(type);
+        if(ptrType == NULL)
+        {
+            continue;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
 
+        int index = CAGetAdapterIndex(connType);
         if (index == -1)
         {
-            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            OIC_LOG(ERROR, TAG, "unknown connectivity type!");
             continue;
         }
 
-        if (gAdapterHandler[index].startListenServer != NULL)
+        if (g_adapterHandler[index].startListenServer != NULL)
         {
-            gAdapterHandler[index].startListenServer();
+            g_adapterHandler[index].startListenServer();
         }
     }
 
@@ -265,31 +436,37 @@ CAResult_t CAStartDiscoveryServerAdapters()
 {
     OIC_LOG(DEBUG, TAG, "Start discovery server from adapters..");
 
-    uint8_t i, type;
-    int8_t index = -1;
     u_arraylist_t *list = CAGetSelectedNetworkList();
 
     if (!list)
     {
-        OIC_LOG(DEBUG, TAG, "No selected network");
+        OIC_LOG(ERROR, TAG, "No selected network");
         return CA_STATUS_FAILED;
     }
 
+    int i = 0;
     for (i = 0; i < u_arraylist_length(list); i++)
     {
-        type = *(int*) u_arraylist_get(list, i);
+        void* ptrType = u_arraylist_get(list, i);
 
-        index = CAGetAdapterIndex(type);
+        if(ptrType == NULL)
+        {
+            continue;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
+
+        int index = CAGetAdapterIndex(connType);
 
         if (index == -1)
         {
-            OIC_LOG_V(DEBUG, TAG, "unknown connectivity type!");
+            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
             continue;
         }
 
-        if (gAdapterHandler[index].startDiscoverServer != NULL)
+        if (g_adapterHandler[index].startDiscoveryServer != NULL)
         {
-            gAdapterHandler[index].startDiscoverServer();
+            g_adapterHandler[index].startDiscoveryServer();
         }
     }
 
@@ -300,13 +477,12 @@ void CATerminateAdapters()
 {
     OIC_LOG(DEBUG, TAG, "terminate all adapters..");
 
-    uint8_t index;
-
-    for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    uint32_t index;
+    for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
     {
-        if (gAdapterHandler[index].terminate != NULL)
+        if (g_adapterHandler[index].terminate != NULL)
         {
-            gAdapterHandler[index].terminate();
+            g_adapterHandler[index].terminate();
         }
     }
 }
diff --git a/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c b/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c
new file mode 100644 (file)
index 0000000..169ee7e
--- /dev/null
@@ -0,0 +1,512 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "cainterfacecontroller_singlethread.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "caipadapter_singlethread.h"
+#include "caedradapter_singlethread.h"
+#include "caleadapter_singlethread.h"
+#include "caadapterutils.h"
+
+#include "canetworkconfigurator.h"
+#include "oic_malloc.h"
+#include "logger.h"
+
+#define TAG "CAIFCNT_ST"
+
+#define CA_MEMORY_ALLOC_CHECK(arg) { if (arg == NULL) {OIC_LOG(ERROR, TAG, "Out of memory");\
+    goto memory_error_exit;} }
+
+#define CA_CONNECTIVITY_TYPE_NUM   4
+
+static CAConnectivityHandler_t g_adapterHandler[CA_CONNECTIVITY_TYPE_NUM];
+
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
+
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
+
+static int CAGetAdapterIndex(CATransportType_t cType)
+{
+    switch (cType)
+    {
+        case CA_IPV4:
+            return 0;
+        case CA_IPV6:
+            return 1;
+        case CA_EDR:
+            return 2;
+        case CA_LE:
+            return 3;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CA_CONNECTIVITY_TYPE_NUM is not 4");
+
+    return -1;
+}
+
+static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_t cType)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if(handler.startAdapter == NULL ||
+        handler.startListenServer == NULL ||
+        handler.startDiscoveryServer == NULL ||
+        handler.sendData == NULL ||
+        handler.sendDataToAll == NULL ||
+        handler.GetnetInfo == NULL ||
+        handler.readData == NULL ||
+        handler.stopAdapter == NULL ||
+        handler.terminate == NULL)
+    {
+        OIC_LOG(ERROR, TAG, "connectivity handler is not enough to be used!");
+        return;
+    }
+
+    int index = CAGetAdapterIndex(cType);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return;
+    }
+
+    memcpy(&g_adapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
+
+    OIC_LOG_V(DEBUG, TAG, "%d type adapter", cType);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
+    uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    // Call the callback.
+    if (g_networkPacketReceivedCallback != NULL)
+    {
+        g_networkPacketReceivedCallback(endpoint, data, dataLen);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    // Call the callback.
+    if (g_networkChangeCallback != NULL)
+    {
+        g_networkChangeCallback(info, status);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAInitializeAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    memset(g_adapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM);
+
+    // Initialize adapters and register callback.
+#ifdef IP_ADAPTER
+    CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+#endif /* IP_ADAPTER */
+
+#ifdef EDR_ADAPTER
+    CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+#endif /* EDR_ADAPTER */
+
+#ifdef LE_ADAPTER
+    CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+#endif /* LE_ADAPTER */
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    g_networkPacketReceivedCallback = callback;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetNetworkChangeCallback(CANetworkChangeCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    g_networkChangeCallback = callback;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAStartAdapter(CATransportType_t transportType)
+{
+    OIC_LOG_V(DEBUG, TAG, "transportType[%d]", transportType);
+
+    int index = CAGetAdapterIndex(transportType);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return CA_STATUS_FAILED;
+    }
+
+    if (g_adapterHandler[index].startAdapter != NULL)
+    {
+        g_adapterHandler[index].startAdapter();
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAStopAdapter(CATransportType_t transportType)
+{
+    OIC_LOG_V(DEBUG, TAG, "transportType[%d]", transportType);
+
+    int index = CAGetAdapterIndex(transportType);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return;
+    }
+
+    if (g_adapterHandler[index].stopAdapter != NULL)
+    {
+        g_adapterHandler[index].stopAdapter();
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(info, TAG, "info");
+    VERIFY_NON_NULL(size, TAG, "size");
+
+    CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM] = { 0 };
+    uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM] = { 0 };
+
+    CAResult_t res = CA_STATUS_FAILED;
+    // #1. get information each adapter
+    for (uint8_t index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        if (g_adapterHandler[index].GetnetInfo != NULL)
+        {
+            res = g_adapterHandler[index].GetnetInfo(&tempInfo[index], &tempSize[index]);
+
+            OIC_LOG_V (DEBUG, TAG, "%d adapter network info size is %d", index, tempSize[index]);
+        }
+    }
+
+    uint32_t resSize = 0;
+    for (uint8_t index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        // check information
+        if (tempInfo[index] == NULL || tempSize[index] <= 0)
+        {
+            continue;
+        }
+
+        // #2. total size
+        resSize += tempSize[index];
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "network info total size is %d!", resSize);
+
+    if (resSize <= 0)
+    {
+        if (CA_ADAPTER_NOT_ENABLED == res || CA_NOT_SUPPORTED == res)
+        {
+            return res;
+        }
+        return CA_STATUS_FAILED;
+    }
+
+    // #3. add data into result
+    // memory allocation
+    CALocalConnectivity_t *resInfo =
+        (CALocalConnectivity_t *) OICCalloc(resSize, sizeof(CALocalConnectivity_t));
+    CA_MEMORY_ALLOC_CHECK(resInfo);
+
+    uint8_t i = 0;
+    for (uint8_t index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        // check information
+        if (tempInfo[index] == NULL || tempSize[index] <= 0)
+        {
+            continue;
+        }
+
+        memcpy(resInfo + i, tempInfo[index], sizeof(CALocalConnectivity_t) * tempSize[index]);
+
+        i += tempSize[index];
+
+        // free adapter data
+        OICFree(tempInfo[index]);
+    }
+
+    // #5. save data
+    *info = resInfo;
+    *size = resSize;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return res;
+
+    // memory error label.
+memory_error_exit:
+
+    for (uint8_t index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+
+        OICFree(tempInfo[index]);
+    }
+
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t res = CA_STATUS_FAILED;
+
+    if (endpoint == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "RemoteEndpoint is NULL");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    CATransportType_t type = endpoint->transportType;
+
+    int index = CAGetAdapterIndex(type);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    uint32_t sentDataLen = 0;
+    if (g_adapterHandler[index].sendData != NULL)
+    {
+        sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
+    }
+
+    if (sentDataLen == length)
+    {
+        res = CA_STATUS_OK;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return res;
+}
+
+CAResult_t CASendMulticastData(const void *data, uint32_t length)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t res = CA_STATUS_FAILED;
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "No selected network");
+        return res;
+    }
+
+    for (uint8_t i = 0; i < u_arraylist_length(list); i++)
+    {
+        void* ptrType = u_arraylist_get(list, i);
+        if (NULL == ptrType)
+        {
+            continue;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
+
+        int index = CAGetAdapterIndex(connType);
+
+        if (index == -1)
+        {
+            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        uint32_t sentDataLen = 0;
+        if (g_adapterHandler[index].sendDataToAll != NULL)
+        {
+            sentDataLen = g_adapterHandler[index].sendDataToAll(data, length);
+        }
+
+        if (sentDataLen == length)
+        {
+            res = CA_STATUS_OK;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return res;
+}
+
+CAResult_t CAStartListeningServerAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "No selected network");
+        return CA_STATUS_FAILED;
+    }
+
+    for (uint8_t i = 0; i < u_arraylist_length(list); i++)
+    {
+        void* ptrType = u_arraylist_get(list, i);
+        if (NULL == ptrType)
+        {
+            OIC_LOG(ERROR, TAG, "Invalid conn type");
+            continue;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
+
+        int index = CAGetAdapterIndex(connType);
+
+        if (index == -1)
+        {
+            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        if (g_adapterHandler[index].startListenServer != NULL)
+        {
+            g_adapterHandler[index].startListenServer();
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartDiscoveryServerAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "No selected network");
+        return CA_STATUS_FAILED;
+    }
+
+    for (uint8_t i = 0; i < u_arraylist_length(list); i++)
+    {
+        void* ptrType = u_arraylist_get(list, i);
+        if (NULL == ptrType)
+        {
+            continue;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
+
+        int index = CAGetAdapterIndex(connType);
+
+        if (index == -1)
+        {
+            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        if (g_adapterHandler[index].startDiscoveryServer != NULL)
+        {
+            g_adapterHandler[index].startDiscoveryServer();
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    uint8_t index;
+
+    for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        if (g_adapterHandler[index].stopAdapter != NULL)
+        {
+            g_adapterHandler[index].stopAdapter();
+        }
+        if (g_adapterHandler[index].terminate != NULL)
+        {
+            g_adapterHandler[index].terminate();
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAReadData()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        return CA_STATUS_FAILED;
+    }
+
+    for (uint8_t i = 0; i < u_arraylist_length(list); i++)
+    {
+        void *ptrType = u_arraylist_get(list, i);
+        if (NULL == ptrType)
+        {
+            OIC_LOG(ERROR, TAG, "get list fail");
+            return CA_STATUS_FAILED;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
+
+        int index = CAGetAdapterIndex(connType);
+
+        if (-1 == index)
+        {
+            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        if (g_adapterHandler[index].readData != NULL)
+        {
+            g_adapterHandler[index].readData();
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
index 9552827..635289c 100644 (file)
 #include "camessagehandler.h"
 #include "caremotehandler.h"
 #include "cainterfacecontroller.h"
+#include "caprotocolmessage.h"
+#include "caretransmission.h"
+#include "caadapterutils.h"
 #include "uqueue.h"
 #include "logger.h"
 #include "config.h" /* for coap protocol */
-#include "coap.h"
-#include "uthreadpool.h" /* for thread pool */
-#include "umutex.h"
+#include "cathreadpool.h" /* for thread pool */
+#include "caqueueingthread.h"
+#include "camutex.h"
 #include "oic_malloc.h"
+#include "canetworkconfigurator.h"
 
 #define TAG PCF("CA")
+#define SINGLE_HANDLE
 
-#define MEMORY_ALLOCK_CHECK(arg) { if (arg == NULL) {OIC_LOG_V(DEBUG, TAG, "memory error"); goto memory_error_exit;} }
-#define MAX_ACTION_NUM   300
+#define MAX_THREAD_POOL_SIZE    20
 
-#define MAX_THREAD_POOL_SIZE    10
-
-#ifndef TRUE
-#define TRUE    1
-#endif
-
-#ifndef FALSE
-#define FALSE   0
-#endif
-
-typedef struct
+typedef enum
 {
-    int32_t actionId;
-    CARemoteEndpoint_t* remoteEndpoint;
-    CARequestInfo_t* requestInfo;
-    CAResponseInfo_t* responseInfo;
-} CAData_t;
-
-typedef void (*CAThreadTask)(CAData_t* data);
+    SEND_TYPE_MULTICAST = 0, SEND_TYPE_UNICAST
+} CASendDataType_t;
 
 typedef struct
 {
-    u_mutex threadMutex;
-    u_cond threadCond;
-    CAThreadTask threadTask;
-    int32_t isStop;
-    u_queue_t* dataQueue;
-} CAThread_t;
+    CASendDataType_t type;
+    CARemoteEndpoint_t *remoteEndpoint;
+    CARequestInfo_t *requestInfo;
+    CAResponseInfo_t *responseInfo;
+    CAHeaderOption_t *options;
+    uint8_t numOptions;
+} CAData_t;
 
 // thread pool handle
-static u_thread_pool_t gThreadPoolHandle = NULL;
+static ca_thread_pool_t g_threadPoolHandle = NULL;
 
 // message handler main thread
-static CAThread_t gSendThread;
+static CAQueueingThread_t g_sendThread;
+static CAQueueingThread_t g_receiveThread;
 
-// message handler callback
-static int32_t gCurrentActionId = 0;
-static CAMessageHandlerCallback gHandlerCallback = NULL;
+static CARetransmission_t g_retransmissionContext;
 
 // handler field
-static CARequestCallback gRequestHandler = NULL;
-static CAResponseCallback gResponseHandler = NULL;
+static CARequestCallback g_requestHandler = NULL;
+static CAResponseCallback g_responseHandler = NULL;
 
-static u_queue_t* gMessageQueue = NULL;
-static u_mutex gMessageQueueMutex = NULL;
-
-static void CAAddReceiveData(CAData_t* data)
+static bool CAIsSelectedNetworkAvailable()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAAddReceiveData");
-
-    // create thread data
-    u_queue_message_t* message = (u_queue_message_t*) OICMalloc(sizeof(u_queue_message_t));
-
-    if (message == NULL)
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+    if (!list || list->length == 0)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory error!!");
-        return;
+        OIC_LOG(ERROR, TAG, "No selected network");
+        return false;
     }
-    memset(message, 0, sizeof(u_queue_message_t));
-
-    message->msg = data;
-    message->size = sizeof(CAData_t);
 
-    // mutex lock
-    u_mutex_lock(gMessageQueueMutex);
-
-    // add thread data into list
-    u_queue_add_element(gMessageQueue, message);
-
-    // mutex unlock
-    u_mutex_unlock(gMessageQueueMutex);
+    return true;
 }
 
-static void CAAddSendData(CAData_t* data)
+static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAAddSendData!!");
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
+    VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
 
-    // create thread data
-    u_queue_message_t* message = (u_queue_message_t*) OICMalloc(sizeof(u_queue_message_t));
-
-    if (message == NULL)
+    CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
+    if (NULL == ep)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory error!!");
+        OIC_LOG(ERROR, TAG, "clone failed");
         return;
     }
-    memset(message, 0, sizeof(u_queue_message_t));
-
-    message->msg = data;
-    message->size = sizeof(CAData_t);
 
-    // mutex lock
-    u_mutex_lock(gSendThread.threadMutex);
+    CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
 
-    // add thread data into list
-    u_queue_add_element(gSendThread.dataQueue, message);
-
-    // notity the thread
-    u_cond_signal(gSendThread.threadCond);
-
-    // mutex unlock
-    u_mutex_unlock(gSendThread.threadMutex);
-}
-
-static void CAStopSendThread()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStopSendThread request!!");
-
-    // mutex lock
-    u_mutex_lock(gSendThread.threadMutex);
-
-    // set stop flag
-    gSendThread.isStop = TRUE;
-
-    // notity the thread
-    u_cond_signal(gSendThread.threadCond);
-
-    // mutex unlock
-    u_mutex_unlock(gSendThread.threadMutex);
-}
-
-static void CASendThreadProcess(CAData_t* data)
-{
-    if (data == NULL)
+    if (NULL == resInfo)
     {
-        OIC_LOG(DEBUG, TAG, "thread data error!!");
+        OIC_LOG(ERROR, TAG, "calloc failed");
+        CADestroyRemoteEndpointInternal(ep);
         return;
     }
 
-    if (NULL == data->remoteEndpoint)
+    resInfo->result = CA_RETRANSMIT_TIMEOUT;
+    resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
+    resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
+    CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info));
+    if (CA_STATUS_OK != res)
     {
-        OIC_LOG(DEBUG, TAG, "remoteEndpoint is null");
+        OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
+        OICFree(resInfo->info.token);
+        OICFree(resInfo);
+        CADestroyRemoteEndpointInternal(ep);
         return;
     }
 
-    OIC_LOG_V(DEBUG, TAG, "thread action id : %d", data->actionId);
-
-    CADetachErrorCode code = FAIL;
-    int32_t res = 0;
-
-    if (data->requestInfo != NULL)
+    CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    if (NULL == cadata)
     {
-        OIC_LOG(DEBUG, TAG, "requestInfo is available");
-
-        coap_pdu_t* pdu = NULL;
-        pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, data->requestInfo->method,
-                data->requestInfo->info);
-
-        // interface controller function call.
-        if (NULL != pdu)
-        {
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
-
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
-
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %s", pdu->hdr);
-
-            res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
-        }
+        OIC_LOG(ERROR, TAG, "memory allocation failed !");
+        CADestroyRemoteEndpointInternal(ep);
+        OICFree(resInfo);
+        return;
     }
-    else if (data->responseInfo != NULL)
-    {
-        OIC_LOG_V(DEBUG, TAG, "responseInfo is available..");
 
-        coap_pdu_t* pdu = NULL;
+    cadata->type = SEND_TYPE_UNICAST;
+    cadata->remoteEndpoint = ep;
+    cadata->requestInfo = NULL;
+    cadata->responseInfo = resInfo;
 
-        pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, data->responseInfo->result,
-                data->responseInfo->info);
-
-        // interface controller function call.
-        if (NULL != pdu)
-        {
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
-
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
+    CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %x", pdu->hdr);
+static void CADataDestroyer(void *data, uint32_t size)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAData_t *cadata = (CAData_t *) data;
 
-            res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
-        }
-    }
-    else
+    if (NULL == cadata)
     {
-        OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
+        OIC_LOG(ERROR, TAG, "cadata is NULL");
+        return;
+    }
 
-        coap_pdu_t* pdu = NULL;
-        CAInfo_t info;
-        memset(&info, 0, sizeof(CAInfo_t));
-        pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, CA_GET, info);
+    if (NULL != cadata->remoteEndpoint)
+    {
+        CADestroyRemoteEndpointInternal((CARemoteEndpoint_t *) cadata->remoteEndpoint);
+    }
 
-        if (NULL != pdu)
-        {
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
+    if (NULL != cadata->requestInfo)
+    {
+        CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
+    }
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
+    if (NULL != cadata->responseInfo)
+    {
+        CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
+    }
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
+    OICFree(cadata->options);
+    OICFree(cadata);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", pdu->hdr->id);
+static void CAReceiveThreadProcess(void *threadData)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    // Currently not supported
+    // This will be enabled when RI supports multi threading
+#ifndef SINGLE_HANDLE
+    CAData_t *data = (CAData_t *) threadData;
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %x", pdu->hdr);
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TAG, "thread data error!!");
+        return;
+    }
 
-            res = CASendMulticastData(pdu->hdr, pdu->length);
-        }
+    // parse the data and call the callbacks.
+    // #1 parse the data
+    // #2 get endpoint
+    CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *)(data->remoteEndpoint);
 
+    if (NULL == rep)
+    {
+        OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
+        return;
     }
 
-    if (res)
+    if (NULL != data->requestInfo)
     {
-        code = SUCCESS;
+        if (g_requestHandler)
+        {
+            g_requestHandler(rep, data->requestInfo);
+        }
     }
 
-    if (gHandlerCallback != NULL)
+    if (NULL != data->responseInfo)
     {
-        gHandlerCallback(data->actionId, code);
+        if (g_responseHandler)
+        {
+            g_responseHandler(rep, data->responseInfo);
+        }
     }
+#endif
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-static void* CAThreadBaseRoutine(void* treadData)
+static void CASendThreadProcess(void *threadData)
 {
-    OIC_LOG_V(DEBUG, TAG, "message handler main thread start..");
+    OIC_LOG(DEBUG, TAG, "IN");
+    CAData_t *data = (CAData_t *) threadData;
 
-    CAThread_t* thread = (CAThread_t*) treadData;
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
+    VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "remoteEndpoint");
 
-    if (thread == NULL)
-    {
-        OIC_LOG_V(DEBUG, TAG, "thread data passing error!!");
+    CAResult_t res = CA_STATUS_FAILED;
 
-        return NULL;
-    }
+    CASendDataType_t type = data->type;
 
-    while (!thread->isStop)
+    if (SEND_TYPE_UNICAST == type)
     {
-        // mutex lock
-        u_mutex_lock(thread->threadMutex);
+        coap_pdu_t *pdu = NULL;
 
-        // if queue is empty, thread will wait
-        if (u_queue_get_size(thread->dataQueue) <= 0)
+        if (NULL != data->requestInfo)
         {
-            OIC_LOG_V(DEBUG, TAG, "wait..");
-            // wait
-            u_cond_wait(thread->threadCond, thread->threadMutex);
+            OIC_LOG(DEBUG, TAG, "requestInfo is available..");
 
-            OIC_LOG_V(DEBUG, TAG, "wake up..");
+            pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
+                                               data->requestInfo->method,
+                                               data->requestInfo->info);
         }
+        else if (NULL != data->responseInfo)
+        {
+            OIC_LOG(DEBUG, TAG, "responseInfo is available..");
 
-        // mutex unlock
-        u_mutex_unlock(thread->threadMutex);
-
-        // check stop flag
-        if (thread->isStop)
-            continue;
-
-        // get data
-        u_queue_message_t* message = u_queue_get_element(thread->dataQueue);
+            pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
+                                               data->responseInfo->result,
+                                               data->responseInfo->info);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG, "request info, response info is empty");
+        }
 
-        CAData_t* data = (CAData_t*) message->msg;
+        // interface controller function call.
+        if (NULL != pdu)
+        {
+            CALogPDUInfo(pdu);
 
-        // process data
-        thread->threadTask(data);
+            res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+                coap_delete_pdu(pdu);
+                return;
+            }
+            // for retransmission
+            res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
+                                           pdu->length);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG_V(INFO, TAG, "retransmission will be not working: %d", res);
+                coap_delete_pdu(pdu);
+                return;
+            }
+
+            coap_delete_pdu(pdu);
+        }
     }
+    else if (SEND_TYPE_MULTICAST == type)
+    {
+        OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
 
-    OIC_LOG_V(DEBUG, TAG, "message handler main thread end..");
+        CAInfo_t info = data->requestInfo->info;
 
-    return NULL;
-}
+        info.options = data->options;
+        info.numOptions = data->numOptions;
 
-static int32_t CAIncreaseActionId()
-{
-    ++gCurrentActionId;
+        coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
+                                                       info);
+
+        if (NULL != pdu)
+        {
+            CALogPDUInfo(pdu);
 
-    gCurrentActionId = (gCurrentActionId > MAX_ACTION_NUM) ? 0 : gCurrentActionId;
+            res = CASendMulticastData(pdu->hdr, pdu->length);
+            if(CA_STATUS_OK != res)
+            {
+                OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+                coap_delete_pdu(pdu);
+                return;
+            }
+
+            coap_delete_pdu(pdu);
+        }
+    }
 
-    return gCurrentActionId;
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
 {
-    OIC_LOG(DEBUG, TAG, "receivedPacketCallback in message handler!!");
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
 
-    if (NULL == data)
+    uint32_t code = CA_NOT_FOUND;
+    coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
+    OICFree(data);
+
+    if (NULL == pdu)
     {
-        OIC_LOG(DEBUG, TAG, "received data is null");
+        OIC_LOG(ERROR, TAG, "Parse PDU failed");
+        CAAdapterFreeRemoteEndpoint(endpoint);
         return;
     }
 
-    coap_pdu_t* pdu;
-    uint32_t code = CA_NOT_FOUND;
-    pdu = CAParsePDU(data, &code);
+    char uri[CA_MAX_URI_LENGTH] = { 0, };
+    uint32_t bufLen = sizeof(uri);
 
-    if (code == CA_GET || code == CA_POST || code == CA_PUT || code == CA_DELETE)
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
-        CARequestInfo_t ReqInfo;
-        memset(&ReqInfo, 0, sizeof(CARequestInfo_t));
-        CAGetRequestInfoFromPdu(pdu, &ReqInfo);
-
-        if (NULL != ReqInfo.info.options && NULL != endpoint)
+        CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
+        if (NULL == ReqInfo)
         {
-            OIC_LOG_V(DEBUG, TAG, "Request PDU - optionID: %d", ReqInfo.info.options->optionID);
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
+            coap_delete_pdu(pdu);
+            CAAdapterFreeRemoteEndpoint(endpoint);
+            return;
+        }
 
-            OIC_LOG_V(DEBUG, TAG, "Request PDU - optionlist: %s", ReqInfo.info.options->optionData);
+        CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, bufLen);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
+            OICFree(ReqInfo);
+            coap_delete_pdu(pdu);
+            CAAdapterFreeRemoteEndpoint(endpoint);
+            return;
+        }
 
-            OIC_LOG_V(DEBUG, TAG, "Request PDU  - payload: %s", ReqInfo.info.payload);
+        if (NULL != ReqInfo->info.options)
+        {
+            uint32_t i;
+            for (i = 0; i < ReqInfo->info.numOptions; i++)
+            {
+                OIC_LOG_V(DEBUG, TAG, "Request- optionID: %d", ReqInfo->info.options[i].optionID);
 
-            OIC_LOG_V(DEBUG, TAG, "Request PDU  - code: %d", ReqInfo.method);
+                OIC_LOG_V(DEBUG, TAG, "Request- list: %s", ReqInfo->info.options[i].optionData);
+            }
+        }
 
-            endpoint->resourceUri = (char*) OICMalloc(strlen(ReqInfo.info.options->optionData) + 1);
-            memcpy(endpoint->resourceUri, ReqInfo.info.options->optionData,
-                    strlen(ReqInfo.info.options->optionData));
-            OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
+        if (NULL != ReqInfo->info.payload)
+        {
+            OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
+        }
+        OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
+        if (NULL != ReqInfo->info.token)
+        {
+            OIC_LOG(DEBUG, TAG, "Request- token:");
+            OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token,
+                           ReqInfo->info.tokenLength);
         }
 
+        OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
+        OIC_LOG(DEBUG, TAG, "Request- token");
+        OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
+        OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            if (NULL == endpoint->resourceUri)
+            {
+                OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
+                OICFree(ReqInfo);
+                coap_delete_pdu(pdu);
+                CAAdapterFreeRemoteEndpoint(endpoint);
+                return;
+            }
+            memcpy(endpoint->resourceUri, uri, bufLen);
+            endpoint->resourceUri[bufLen] = '\0';
+            OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
+        }
         // store the data at queue.
-        CAData_t* cadata = NULL;
-        cadata = (CAData_t*) OICMalloc(sizeof(CAData_t));
-        memset(cadata, 0, sizeof(CAData_t));
-        cadata->actionId = 1;
+        CAData_t *cadata = NULL;
+        cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+        if (NULL == cadata)
+        {
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+            OICFree(ReqInfo);
+            coap_delete_pdu(pdu);
+            CAAdapterFreeRemoteEndpoint(endpoint);
+            return;
+        }
+
+        cadata->type = SEND_TYPE_UNICAST;
         cadata->remoteEndpoint = endpoint;
-        cadata->requestInfo = &ReqInfo;
+        cadata->requestInfo = ReqInfo;
         cadata->responseInfo = NULL;
-        CAAddReceiveData(cadata);
-
+        CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
     }
     else
     {
-        CAResponseInfo_t ResInfo;
-        memset(&ResInfo, 0, sizeof(CARequestInfo_t));
-        CAGetResponseInfoFromPdu(pdu, &ResInfo);
+        CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
+        if (NULL == ResInfo)
+        {
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
+            coap_delete_pdu(pdu);
+            CAAdapterFreeRemoteEndpoint(endpoint);
+            return;
+        }
 
-        if (NULL != ResInfo.info.options && NULL != endpoint)
+        CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, bufLen);
+        if (CA_STATUS_OK != res)
         {
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - optionID: %d", ResInfo.info.options->optionID);
+            OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
+            OICFree(ResInfo);
+            coap_delete_pdu(pdu);
+            CAAdapterFreeRemoteEndpoint(endpoint);
+            return;
+        }
 
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - optionlist: %s", ResInfo.info.options->optionData);
+        if (NULL != ResInfo->info.options)
+        {
+            uint32_t i;
+            for (i = 0; i < ResInfo->info.numOptions; i++)
+            {
+                OIC_LOG_V(DEBUG, TAG, "Response- optionID: %d", ResInfo->info.options[i].optionID);
 
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - payload: %s", ResInfo.info.payload);
+                OIC_LOG_V(DEBUG, TAG, "Response- list: %s", ResInfo->info.options[i].optionData);
+            }
+        }
 
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - code: %d", ResInfo.result);
+        if (NULL != ResInfo->info.payload)
+        {
+            OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
+        }
+        OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
+        OIC_LOG_V(DEBUG, TAG, "Response- token : %s", ResInfo->info.token);
+        OIC_LOG_V(DEBUG, TAG, "Response- msgID: %d", ResInfo->info.messageId);
 
-            endpoint->resourceUri = (char*) OICMalloc(strlen(ResInfo.info.options->optionData) + 1);
-            memcpy(endpoint->resourceUri, ResInfo.info.options->optionData,
-                    strlen(ResInfo.info.options->optionData));
-            OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            if (NULL == endpoint->resourceUri)
+            {
+                OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+                OICFree(ResInfo);
+                coap_delete_pdu(pdu);
+                CAAdapterFreeRemoteEndpoint(endpoint);
+                return;
+            }
+            memcpy(endpoint->resourceUri, uri, bufLen);
+            endpoint->resourceUri[bufLen] = '\0';
+            OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
         }
 
         // store the data at queue.
-        CAData_t* cadata = NULL;
-        cadata = (CAData_t*) OICMalloc(sizeof(CAData_t));
-        memset(cadata, 0, sizeof(CAData_t));
-        cadata->actionId = 1;
+        CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+        if (NULL == cadata)
+        {
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+            OICFree(ResInfo);
+            coap_delete_pdu(pdu);
+            CAAdapterFreeRemoteEndpoint(endpoint);
+            return;
+        }
+
+        cadata->type = SEND_TYPE_UNICAST;
         cadata->remoteEndpoint = endpoint;
         cadata->requestInfo = NULL;
-        cadata->responseInfo = &ResInfo;
-        CAAddReceiveData(cadata);
+
+        // for retransmission
+        void *retransmissionPdu = NULL;
+        CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
+                                     &retransmissionPdu);
+
+        // get token from saved data in retransmission list
+        if (retransmissionPdu && CA_EMPTY == code)
+        {
+            CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
+                                               &(ResInfo->info));
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
+                OICFree(ResInfo->info.token);
+            }
+        }
+        OICFree(retransmissionPdu);
+        cadata->responseInfo = ResInfo;
+
+        CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+    }
+
+    if (pdu)
+    {
+        coap_delete_pdu(pdu);
     }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CAHandleRequestResponseCallbacks()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAHandleRequestResponseCallbacks");
+    OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks IN");
 
+#ifdef SINGLE_HANDLE
     // parse the data and call the callbacks.
     // #1 parse the data
     // #2 get endpoint
 
-    u_mutex_lock(gMessageQueueMutex);
+    ca_mutex_lock(g_receiveThread.threadMutex);
 
-    u_queue_message_t* item = u_queue_get_element(gMessageQueue);
+    u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
 
-    u_mutex_unlock(gMessageQueueMutex);
+    ca_mutex_unlock(g_receiveThread.threadMutex);
 
-    if (item == NULL)
+    if (NULL == item)
+    {
         return;
+    }
 
     // get values
-    voidmsg = item->msg;
+    void *msg = item->msg;
 
-    if (msg == NULL)
+    if (NULL == msg)
+    {
         return;
+    }
 
     // get endpoint
-    CAData_t* td = (CAData_t*) msg;
-
-    CARemoteEndpoint_t* rep = td->remoteEndpoint;
+    CAData_t *td = (CAData_t *) msg;
+    CARemoteEndpoint_t *rep = td->remoteEndpoint;
 
-    if (rep == NULL)
+    if (NULL == rep)
+    {
         return;
+    }
 
-    if (td->requestInfo != NULL)
+    if (NULL != td->requestInfo)
     {
-        if (gRequestHandler)
+        if (g_requestHandler)
         {
-            gRequestHandler(rep, NULL);
+            OIC_LOG_V(DEBUG, TAG, "callback will be sent : %d", td->requestInfo->info.numOptions);
+            g_requestHandler(rep, td->requestInfo);
         }
     }
 
-    if (td->responseInfo != NULL)
+    if (NULL != td->responseInfo)
     {
-        if (gResponseHandler)
+        if (g_responseHandler)
         {
-            gResponseHandler(rep, NULL);
+            g_responseHandler(rep, td->responseInfo);
         }
+
     }
+    CADataDestroyer(msg, sizeof(CAData_t));
 
-    u_queue_remove_element(gMessageQueue);
+#endif
+    OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks OUT");
 }
 
-int32_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequestInfo_t* request)
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
 {
-    OIC_LOG_V(DEBUG, TAG, "CADetachRequestMessage");
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(object, TAG, "object");
+    VERIFY_NON_NULL(request, TAG, "request");
 
-    if (object == NULL || request == NULL)
+    if (false == CAIsSelectedNetworkAvailable())
     {
-        return -1;
+        return CA_STATUS_FAILED;
     }
 
-    int32_t id = 0;
-
-    // create action id
-    id = CAIncreaseActionId();
-
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
-    MEMORY_ALLOCK_CHECK(data);
-
-    // initialize
-    memset(data, 0, sizeof(CAData_t));
+    CARemoteEndpoint_t *remoteEndpoint = NULL;
+    CARequestInfo_t *requestInfo = NULL;
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
 
     // clone remote endpoint
-    CARemoteEndpoint_t* remoteEndpoint = CACloneRemoteEndpoint(object);
-    MEMORY_ALLOCK_CHECK(remoteEndpoint);
+    remoteEndpoint = CACloneRemoteEndpoint(object);
+    CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
 
     // clone request info
-    CARequestInfo_t* requestInfo = CACloneRequestInfo(request);
-    MEMORY_ALLOCK_CHECK(requestInfo);
+    requestInfo = CACloneRequestInfo(request);
+    CA_MEMORY_ALLOC_CHECK(requestInfo);
 
     // save data
-    data->actionId = id;
+    data->type = SEND_TYPE_UNICAST;
     data->remoteEndpoint = remoteEndpoint;
     data->requestInfo = requestInfo;
     data->responseInfo = NULL;
 
     // add thread
-    CAAddSendData(data);
+    CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
 
-    return id;
+// memory error label.
+memory_error_exit:
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
+    CADestroyRequestInfoInternal(requestInfo);
 
-    // memory error label.
-    memory_error_exit:
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
+}
 
-    CADestroyRemoteEndpointInternal(remoteEndpoint);
+CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
+                                       const CARequestInfo_t *request)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
 
-    CADestroyRequestInfoInternal(requestInfo);
+    if (NULL == object || NULL == request || NULL == object->resourceUri)
+    {
+        return CA_STATUS_INVALID_PARAM;
+    }
 
-    if (data != NULL)
+    if ((request->method < CA_GET) || (request->method > CA_DELETE))
     {
-        OICFree(data);
+        OIC_LOG(ERROR, TAG, "Invalid method type!");
+
+        return CA_STATUS_INVALID_PARAM;
     }
 
-    return -1;
+    if (false == CAIsSelectedNetworkAvailable())
+    {
+        return CA_STATUS_FAILED;
+    }
+
+    CARemoteEndpoint_t *remoteEndpoint = NULL;
+    CARequestInfo_t *requestInfo = NULL;
+
+    // allocate & initialize
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
+
+    CAAddress_t addr = {};
+    remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
+                                                    object->transportType);
+
+    // clone request info
+    requestInfo = CACloneRequestInfo(request);
+    CA_MEMORY_ALLOC_CHECK(requestInfo);
+
+    // save data
+    data->type = SEND_TYPE_MULTICAST;
+    data->remoteEndpoint = remoteEndpoint;
+    data->requestInfo = requestInfo;
+    data->responseInfo = NULL;
+
+    // add thread
+    CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+
+// memory error label.
+memory_error_exit:
+
+    CADestroyRequestInfoInternal(requestInfo);
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
 }
 
-int32_t CADetachResponseMessage(const CARemoteEndpoint_t* object, const CAResponseInfo_t* response)
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *response)
 {
-    OIC_LOG_V(DEBUG, TAG, "CADetachResponseMessage");
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(object, TAG, "object");
+    VERIFY_NON_NULL(response, TAG, "response");
 
-    if (object == NULL || response == NULL)
+    if (false == CAIsSelectedNetworkAvailable())
     {
-        return -1;
+        return CA_STATUS_FAILED;
     }
 
-    int32_t id = 0;
-
-    // create action id
-    id = CAIncreaseActionId();
+    CARemoteEndpoint_t *remoteEndpoint = NULL;
+    CAResponseInfo_t *responseInfo = NULL;
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
-    MEMORY_ALLOCK_CHECK(data);
-
-    // initialize
-    memset(data, 0, sizeof(CAData_t));
+    // allocate & initialize
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
 
     // clone remote endpoint
-    CARemoteEndpoint_t* remoteEndpoint = CACloneRemoteEndpoint(object);
-    MEMORY_ALLOCK_CHECK(remoteEndpoint);
+    remoteEndpoint = CACloneRemoteEndpoint(object);
+    CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
 
     // clone response info
-    CAResponseInfo_t* responseInfo = CACloneResponseInfo(response);
-    MEMORY_ALLOCK_CHECK(responseInfo);
+    responseInfo = CACloneResponseInfo(response);
+    CA_MEMORY_ALLOC_CHECK(responseInfo);
 
     // save data
-    data->actionId = id;
+    data->type = SEND_TYPE_UNICAST;
     data->remoteEndpoint = remoteEndpoint;
     data->requestInfo = NULL;
     data->responseInfo = responseInfo;
 
     // add thread
-    CAAddSendData(data);
-
-    return id;
+    CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
 
-    // memory error label.
-    memory_error_exit:
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
 
+// memory error label.
+memory_error_exit:
     CADestroyRemoteEndpointInternal(remoteEndpoint);
-
     CADestroyResponseInfoInternal(responseInfo);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
 
-    if (data != NULL)
-    {
-        OICFree(data);
-    }
-
-    return -1;
+    return CA_MEMORY_ALLOC_FAILED;
 }
 
-int32_t CADetachMessageResourceUri(const CAURI_t resourceUri)
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
+                                      uint8_t tokenLength, const CAHeaderOption_t *options,
+                                      uint8_t numOptions)
 {
-    if (resourceUri == NULL)
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(resourceUri, TAG, "resourceUri is NULL");
+    VERIFY_NON_NULL(token, TAG, "Token is NULL");
+
+    if (false == CAIsSelectedNetworkAvailable())
     {
-        return -1;
+        return CA_STATUS_FAILED;
     }
 
-    int32_t id = 0;
+    CARemoteEndpoint_t *remoteEndpoint = NULL;
+    CARequestInfo_t *reqInfo = NULL;
+    char *tempToken = NULL;
 
-    // create action id
-    id = CAIncreaseActionId();
+    // allocate & initialize
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
-    MEMORY_ALLOCK_CHECK(data);
+    CAAddress_t addr = {};
+    remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
+                                                    CA_IPV4 | CA_EDR | CA_LE);
+
+    // create request info
+    reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
+    CA_MEMORY_ALLOC_CHECK(reqInfo);
+
+    if (tokenLength)
+    {
+        // copy token value
+        tempToken = (char *) OICMalloc(tokenLength);
+        CA_MEMORY_ALLOC_CHECK(tempToken);
+        memcpy(tempToken, token, tokenLength);
+    }
 
-    // initialize
-    memset(data, 0, sizeof(CAData_t));
+    // save request info data
+    reqInfo->method = CA_GET;
+    reqInfo->info.type = CA_MSG_NONCONFIRM;
 
-    CAAddress_t addr;
-    memset(&addr, 0, sizeof(CAAddress_t));
-    CARemoteEndpoint_t* remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
-            CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE);
+    reqInfo->info.token = tempToken;
+    reqInfo->info.tokenLength = tokenLength;
 
     // save data
-    data->actionId = id;
+    data->type = SEND_TYPE_MULTICAST;
     data->remoteEndpoint = remoteEndpoint;
-    data->requestInfo = NULL;
-    data->responseInfo = NULL;
+    data->requestInfo = reqInfo;
 
-    // add thread
-    CAAddSendData(data);
+    data->responseInfo = NULL;
+    data->options = NULL;
+    data->numOptions = 0;
+    if (NULL != options && 0 < numOptions)
+    {
+        // copy data
+        CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
+                                                                        * numOptions);
+        CA_MEMORY_ALLOC_CHECK(headerOption);
 
-    return id;
+        memcpy(headerOption, options, sizeof(CAHeaderOption_t) * numOptions);
 
-    // memory error label.
-    memory_error_exit:
+        data->options = headerOption;
+        data->numOptions = numOptions;
+    }
 
-    CADestroyRemoteEndpointInternal(remoteEndpoint);
+    // add thread
+    CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
 
-    if (data != NULL)
-    {
-        OICFree(data);
-    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
 
-    return -1;
-}
+// memory error label.
+memory_error_exit:
 
-void CASetMessageHandlerCallback(CAMessageHandlerCallback callback)
-{
-    OIC_LOG_V(DEBUG, TAG, "set message handler callback.");
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
 
-    gHandlerCallback = callback;
+    OICFree(tempToken);
+    OICFree(reqInfo);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
 }
 
 void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
 {
-    OIC_LOG_V(DEBUG, TAG, "set request, response handler callback.");
-
-    gRequestHandler = ReqHandler;
-    gResponseHandler = RespHandler;
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_requestHandler = ReqHandler;
+    g_responseHandler = RespHandler;
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 CAResult_t CAInitializeMessageHandler()
 {
+    OIC_LOG(DEBUG, TAG, "IN");
     CASetPacketReceivedCallback(CAReceivedPacketCallback);
 
+    CASetNetworkChangeCallback(CANetworkChangedCallback);
+
     // create thread pool
-    CAResult_t res;
-    res = u_thread_pool_init(MAX_THREAD_POOL_SIZE, &gThreadPoolHandle);
+    CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
 
     if (res != CA_STATUS_OK)
     {
-        OIC_LOG_V(DEBUG, TAG, "thread pool initialize error.");
+        OIC_LOG(ERROR, TAG, "thread pool initialize error.");
         return res;
     }
 
     // send thread initialize
-    memset(&gSendThread, 0, sizeof(CAThread_t));
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
+                                                   CASendThreadProcess, CADataDestroyer))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
+        return CA_STATUS_FAILED;
+    }
 
-    // mutex init
-    u_mutex_init();
+    // start send thread
+    res = CAQueueingThreadStart(&g_sendThread);
 
-    // set send thread data
-    gSendThread.dataQueue = u_queue_create();
-    gSendThread.threadMutex = u_mutex_new();
-    gSendThread.threadCond = u_cond_new();
-    gSendThread.isStop = FALSE;
-    gSendThread.threadTask = CASendThreadProcess;
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "thread start error(send thread).");
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        return res;
+    }
 
-    // start send thread
-    res = u_thread_pool_add_task(gThreadPoolHandle, CAThreadBaseRoutine, &gSendThread);
+    // receive thread initialize
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
+                                                   CAReceiveThreadProcess, CADataDestroyer))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
+        return CA_STATUS_FAILED;
+    }
+
+#ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
+    // start receive thread
+    res = CAQueueingThreadStart(&gReceiveThread);
 
     if (res != CA_STATUS_OK)
     {
-        OIC_LOG_V(DEBUG, TAG, "thread pool add task error.");
+        OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
         return res;
     }
+#endif
 
-    // set receive queue
-    gMessageQueue = u_queue_create();
-    gMessageQueueMutex = u_mutex_new();
+    // retransmission initialize
+    CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
+                               CATimeoutCallback, NULL);
 
-    // initialize interface adapters by controller
-    CAInitializeAdapters();
+    // start retransmission
+    res = CARetransmissionStart(&g_retransmissionContext);
+
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
+        return res;
+    }
 
+    // initialize interface adapters by controller
+    CAInitializeAdapters(g_threadPoolHandle);
+    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CATerminateMessageHandler()
 {
-    // terminate interface adapters by controller
-    CATerminateAdapters();
+    OIC_LOG(DEBUG, TAG, "IN");
+    CATransportType_t connType;
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+    uint32_t length = u_arraylist_length(list);
+
+    uint32_t i = 0;
+    for (i = 0; i < length; i++)
+    {
+        void* ptrType = u_arraylist_get(list, i);
+
+        if (NULL == ptrType)
+        {
+            continue;
+        }
+
+        connType = *(CATransportType_t *) ptrType;
+        CAStopAdapter(connType);
+    }
+
+    // stop retransmission
+    if (NULL != g_retransmissionContext.threadMutex)
+    {
+        CARetransmissionStop(&g_retransmissionContext);
+    }
 
     // stop thread
-    CAStopSendThread();
+    // delete thread data
+    if (NULL != g_sendThread.threadMutex)
+    {
+        CAQueueingThreadStop(&g_sendThread);
+    }
 
+    // stop thread
     // delete thread data
-    u_mutex_free(gSendThread.threadMutex);
-    u_cond_free(gSendThread.threadCond);
-    u_queue_delete(gSendThread.dataQueue);
+    if (NULL != g_receiveThread.threadMutex)
+    {
+#ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
+        CAQueueingThreadStop(&gReceiveThread);
+#endif
+    }
 
     // destroy thread pool
-    u_thread_pool_free(gThreadPoolHandle);
+    if (NULL != g_threadPoolHandle)
+    {
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+    }
+
+    CARetransmissionDestroy(&g_retransmissionContext);
+    CAQueueingThreadDestroy(&g_sendThread);
+    CAQueueingThreadDestroy(&g_receiveThread);
 
-    OIC_LOG_V(DEBUG, TAG, "message handler terminate completed!");
+    // terminate interface adapters by controller
+    CATerminateAdapters();
 
-    u_queue_delete(gMessageQueue);
-    u_mutex_free(gMessageQueueMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
+void CALogPDUInfo(coap_pdu_t *pdu)
+{
+    VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", ntohs(pdu->hdr->id));
+
+    OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
+
+    OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
+}
diff --git a/resource/csdk/connectivity/src/camessagehandler_singlethread.c b/resource/csdk/connectivity/src/camessagehandler_singlethread.c
new file mode 100644 (file)
index 0000000..6bad8a3
--- /dev/null
@@ -0,0 +1,599 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "cainterface.h"
+#include "camessagehandler_singlethread.h"
+#include "caremotehandler.h"
+#include "cainterfacecontroller_singlethread.h"
+#include "caprotocolmessage.h"
+#include "caretransmission_singlethread.h"
+#include "logger.h"
+#include "config.h" /* for coap protocol */
+#include "oic_malloc.h"
+
+#define TAG "CAMH_ST"
+
+#define CA_MAX_RT_ARRAY_SIZE    3
+
+typedef enum
+{
+    SEND_TYPE_MULTICAST = 0, SEND_TYPE_UNICAST
+} CASendDataType_t;
+
+typedef struct
+{
+    CASendDataType_t type;
+    CARemoteEndpoint_t *remoteEndpoint;
+    CARequestInfo_t *requestInfo;
+    CAResponseInfo_t *responseInfo;
+    CAHeaderOption_t *options;
+    uint8_t numOptions;
+} CAData_t;
+
+
+static CARetransmission_t g_retransmissionContext;
+
+// handler field
+static CARequestCallback g_requestHandler = NULL;
+static CAResponseCallback g_responseHandler = NULL;
+
+static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
+    if (NULL == ep)
+    {
+        OIC_LOG(ERROR, TAG, "clone failed");
+        return;
+    }
+
+    CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
+
+    if (NULL == resInfo)
+    {
+        OIC_LOG(ERROR, TAG, "calloc failed");
+        CADestroyRemoteEndpointInternal(ep);
+        return;
+    }
+
+    resInfo->result = CA_RETRANSMIT_TIMEOUT;
+    resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
+    resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
+
+    if (g_responseHandler)
+    {
+        g_responseHandler(ep, resInfo);
+    }
+
+    CADestroyRemoteEndpointInternal(ep);
+    OICFree(resInfo);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+static void CAProcessData(const CAData_t *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
+    VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "remoteEndpoint");
+
+    CAResult_t res = CA_STATUS_FAILED;
+
+    CASendDataType_t type = data->type;
+
+    if (SEND_TYPE_UNICAST == type)
+    {
+        coap_pdu_t *pdu = NULL;
+
+        if (NULL != data->requestInfo)
+        {
+            OIC_LOG(DEBUG, TAG, "reqInfo avlbl");
+
+            pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
+                                               data->requestInfo->method,
+                                               data->requestInfo->info);
+        }
+        else if (NULL != data->responseInfo)
+        {
+            OIC_LOG(DEBUG, TAG, "resInfo avlbl");
+
+            pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
+                                               data->responseInfo->result,
+                                               data->responseInfo->info);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG, "request info, response info is empty");
+        }
+
+        // interface controller function call.
+        if (NULL != pdu)
+        {
+            CALogPDUInfo(pdu);
+
+            res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+                coap_delete_pdu(pdu);
+                return;
+            }
+            // for retransmission
+            res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
+                                           pdu->length);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG_V(INFO, TAG, "retransmissions will not be working: %d", res);
+                coap_delete_pdu(pdu);
+                return;
+            }
+
+            coap_delete_pdu(pdu);
+        }
+    }
+    else if (SEND_TYPE_MULTICAST == type)
+    {
+        OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
+
+        CAInfo_t info = data->requestInfo->info;
+
+        info.options = data->options;
+        info.numOptions = data->numOptions;
+
+        coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
+                                                       info);
+
+        if (NULL != pdu)
+        {
+            CALogPDUInfo(pdu);
+            res = CASendMulticastData(pdu->hdr, pdu->length);
+            if(CA_STATUS_OK != res)
+            {
+                OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+                coap_delete_pdu(pdu);
+                return;
+            }
+            coap_delete_pdu(pdu);
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
+
+    uint32_t code = CA_NOT_FOUND;
+    coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
+
+    if (NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "Parse PDU failed");
+        return;
+    }
+
+    char uri[CA_MAX_URI_LENGTH] = { 0, };
+    uint32_t bufLen = sizeof(uri);
+
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
+    {
+        CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
+        if (NULL == ReqInfo)
+        {
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
+            coap_delete_pdu(pdu);
+            return;
+        }
+
+        CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, bufLen);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
+            OICFree(ReqInfo);
+            coap_delete_pdu(pdu);
+            return;
+        }
+
+        if (NULL != ReqInfo->info.options)
+        {
+            for (uint32_t i = 0; i < ReqInfo->info.numOptions; i++)
+            {
+                OIC_LOG_V(DEBUG, TAG, "optionID: %d", ReqInfo->info.options[i].optionID);
+
+                OIC_LOG_V(DEBUG, TAG, "list: %s", ReqInfo->info.options[i].optionData);
+            }
+        }
+
+        if (NULL != ReqInfo->info.payload)
+        {
+            OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
+        }
+
+        OIC_LOG_V(DEBUG, TAG, "code: %d", ReqInfo->method);
+        OIC_LOG(DEBUG, TAG, "token:");
+        OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            if (NULL == endpoint->resourceUri)
+            {
+                OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
+                OICFree(ReqInfo);
+                coap_delete_pdu(pdu);
+                return;
+            }
+            memcpy(endpoint->resourceUri, uri, bufLen);
+            endpoint->resourceUri[bufLen] = '\0';
+            OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
+        }
+
+        if (ReqInfo)
+        {
+            if (g_requestHandler)
+            {
+                g_requestHandler(endpoint, ReqInfo);
+            }
+
+            CADestroyRequestInfoInternal(ReqInfo);
+        }
+    }
+    else
+    {
+        CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
+        if (NULL == ResInfo)
+        {
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
+            coap_delete_pdu(pdu);
+            return;
+        }
+
+        CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, bufLen);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
+            OICFree(ResInfo);
+            coap_delete_pdu(pdu);
+            return;
+        }
+
+        if (NULL != ResInfo->info.options)
+        {
+            for (uint32_t i = 0; i < ResInfo->info.numOptions; i++)
+            {
+                OIC_LOG_V(DEBUG, TAG, "optionID: %d", ResInfo->info.options[i].optionID);
+
+                OIC_LOG_V(DEBUG, TAG, "list: %s", ResInfo->info.options[i].optionData);
+            }
+        }
+
+        if (NULL != ResInfo->info.payload)
+        {
+            OIC_LOG_V(DEBUG, TAG, "payload: %s", ResInfo->info.payload);
+        }
+        OIC_LOG_V(DEBUG, TAG, "code: %d", ResInfo->result);
+
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            if (NULL == endpoint->resourceUri)
+            {
+                OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+                OICFree(ResInfo);
+                coap_delete_pdu(pdu);
+                return;
+            }
+            memcpy(endpoint->resourceUri, uri, bufLen);
+            endpoint->resourceUri[bufLen] = '\0';
+            OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
+        }
+
+        // for retransmission
+        void *retransmissionPdu = NULL;
+        CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
+                                     &retransmissionPdu);
+
+        // get token from saved data in retransmission list
+        if (retransmissionPdu && CA_EMPTY == code)
+        {
+            CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
+                                               &(ResInfo->info));
+            if(CA_STATUS_OK != res)
+            {
+                OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
+                OICFree(ResInfo->info.token);
+            }
+        }
+        OICFree(retransmissionPdu);
+
+        if (NULL != ResInfo)
+        {
+            if (g_responseHandler)
+            {
+                g_responseHandler(endpoint, ResInfo);
+            }
+            CADestroyResponseInfoInternal(ResInfo);
+        }
+    }
+
+    if (endpoint && endpoint->resourceUri)
+    {
+        OICFree(endpoint->resourceUri);
+        endpoint->resourceUri = NULL;
+    }
+    if (pdu)
+    {
+        coap_delete_pdu(pdu);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAHandleRequestResponseCallbacks()
+{
+    CAReadData();
+    CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
+}
+
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL(object, TAG, "object");
+    VERIFY_NON_NULL(request, TAG, "request");
+
+    // If max retransmission queue is reached, then don't handle new request
+    if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
+    {
+        OIC_LOG(ERROR, TAG, "max RT queue size reached!");
+        return CA_SEND_FAILED;
+    }
+
+    // allocate & initialize
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
+
+    // save data
+    data->type = SEND_TYPE_UNICAST;
+    data->remoteEndpoint = object;
+    data->requestInfo = request;
+    data->responseInfo = NULL;
+
+    CAProcessData(data);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+
+// memory error label.
+memory_error_exit:
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
+                                       const CARequestInfo_t *request)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == object || NULL == request || NULL == object->resourceUri)
+    {
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if ((request->method < CA_GET) || (request->method > CA_DELETE))
+    {
+        OIC_LOG(ERROR, TAG, "Invalid method type!");
+
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // allocate & initialize
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
+
+    CAAddress_t addr = {0};
+    CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
+                                                                        object->transportType);
+
+    // save data
+    data->type = SEND_TYPE_MULTICAST;
+    data->remoteEndpoint = remoteEndpoint;
+    data->requestInfo = request;
+    data->responseInfo = NULL;
+
+    CAProcessData(data);
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
+
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+
+// memory error label.
+memory_error_exit:
+
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *response)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(object, TAG, "object");
+    VERIFY_NON_NULL(response, TAG, "response");
+
+    // allocate & initialize
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
+
+    // save data
+    data->type = SEND_TYPE_UNICAST;
+    data->remoteEndpoint = object;
+    data->requestInfo = NULL;
+    data->responseInfo = response;
+
+    CAProcessData(data);
+
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+
+// memory error label.
+memory_error_exit:
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
+                                      uint8_t tokenLength, const CAHeaderOption_t *options,
+                                      uint8_t numOptions)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(resourceUri, TAG, "resourceUri is NULL");
+    VERIFY_NON_NULL(token, TAG, "Token is NULL");
+
+    // allocate & initialize
+    CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    CA_MEMORY_ALLOC_CHECK(data);
+
+    CAAddress_t addr = {0};
+    CARemoteEndpoint_t *remoteEndpoint =
+            CACreateRemoteEndpointInternal(resourceUri, addr, CA_IPV4 | CA_EDR | CA_LE);
+
+    // create request info
+    CARequestInfo_t *reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
+    CA_MEMORY_ALLOC_CHECK(reqInfo);
+
+    // save request info data
+    reqInfo->method = CA_GET;
+    reqInfo->info.type = CA_MSG_NONCONFIRM;
+
+    reqInfo->info.token = token;
+    reqInfo->info.tokenLength = tokenLength;
+
+    // save data
+    data->type = SEND_TYPE_MULTICAST;
+    data->remoteEndpoint = remoteEndpoint;
+    data->requestInfo = reqInfo;
+
+    data->responseInfo = NULL;
+    data->options = NULL;
+    data->numOptions = 0;
+    CAHeaderOption_t *headerOption = NULL;
+    if (NULL != options && numOptions > 0)
+    {
+        // copy data
+        headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * numOptions);
+        CA_MEMORY_ALLOC_CHECK(headerOption);
+        memcpy(headerOption, options, sizeof(CAHeaderOption_t) * numOptions);
+
+        data->options = headerOption;
+        data->numOptions = numOptions;
+    }
+
+    CAProcessData(data);
+
+    CADestroyRemoteEndpoint(remoteEndpoint);
+    OICFree(headerOption);
+    OICFree(data);
+    OICFree(reqInfo);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+
+// memory error label.
+memory_error_exit:
+
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
+
+    OICFree(reqInfo);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_requestHandler = ReqHandler;
+    g_responseHandler = RespHandler;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAInitializeMessageHandler()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CASetPacketReceivedCallback(CAReceivedPacketCallback);
+
+    CASetNetworkChangeCallback(CANetworkChangedCallback);
+
+    // retransmission initialize
+    CARetransmissionInitialize(&g_retransmissionContext, CASendUnicastData,
+                               CATimeoutCallback, NULL);
+
+    CAInitializeAdapters();
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateMessageHandler()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    // terminate interface adapters by controller
+    CATerminateAdapters();
+
+    // stop retransmission
+    CARetransmissionStop(&g_retransmissionContext);
+    CARetransmissionDestroy(&g_retransmissionContext);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CALogPDUInfo(coap_pdu_t *pdu)
+{
+    VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", ntohs(pdu->hdr->id));
+
+    OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
+
+    OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
+}
+
index 0efe118..c5a89bc 100644 (file)
 #include <stdlib.h>
 
 #include "canetworkconfigurator.h"
+#include "cainterfacecontroller_singlethread.h"
 #include "uarraylist.h"
 #include "logger.h"
-#include "cainterfacecontroller.h"
 
-#define TAG PCF("CA")
+#define TAG "CANW"
 
-static u_arraylist_t *gSelectedNetworkList = NULL;
+static u_arraylist_t *g_selectedNetworkList = NULL;
+static uint32_t NETWORK_IP = CA_IPV4;
+static uint32_t NETWORK_EDR = CA_EDR;
+static uint32_t NETWORK_LE = CA_LE;
 
-CAResult_t CAAddNetworkType(uint32_t ConnectivityType)
+
+CAResult_t CAAddNetworkType(CATransportType_t transportType)
 {
-    if (gSelectedNetworkList == NULL)
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == g_selectedNetworkList)
     {
-        OIC_LOG_V(DEBUG, TAG, "Create network list");
+        OIC_LOG(DEBUG, TAG, "Create network list");
 
-        gSelectedNetworkList = u_arraylist_create();
-    }
+        g_selectedNetworkList = u_arraylist_create();
 
-    switch (ConnectivityType)
+        if (NULL == g_selectedNetworkList)
+        {
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+    CAResult_t res = CA_STATUS_OK;
+    switch (transportType)
     {
-        case CA_ETHERNET:
+        case CA_IPV4:
+        {
 
-#ifndef ETHERNET_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET) - Not Supported");
+#ifndef IP_ADAPTER
+            OIC_LOG(DEBUG, TAG, "Add network type(IP) - Not Supported");
             return CA_NOT_SUPPORTED;
-#endif /* ETHERNET_ADAPTER */
-
-            OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET)");
-            u_arraylist_add(gSelectedNetworkList, &NETWORK_ETHERNET);
-
-            break;
-
-        case CA_WIFI:
-
-#ifndef WIFI_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI) - Not Supported");
+#endif /* IP_ADAPTER */
+
+            OIC_LOG(DEBUG, TAG, "Add network type(IP)");
+            if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_IP))
+            {
+                goto exit;
+            }
+            res = u_arraylist_add(g_selectedNetworkList, &NETWORK_IP);
+        }
+        break;
+        case CA_IPV6:
+        {
+            OIC_LOG(ERROR, TAG, "Currently IPV6 is not supported");
             return CA_NOT_SUPPORTED;
-#endif /* WIFI_ADAPTER */
-
-            OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI)");
-            u_arraylist_add(gSelectedNetworkList, &NETWORK_WIFI);
-
-            break;
+        }
 
         case CA_EDR:
+        {
 
 #ifndef EDR_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Add network type(EDR) - Not Supported");
+            OIC_LOG(DEBUG, TAG, "Add network type(EDR) - Not Supported");
             return CA_NOT_SUPPORTED;
 #endif /* EDR_ADAPTER */
 
-            OIC_LOG_V(DEBUG, TAG, "Add network type(EDR)");
-            u_arraylist_add(gSelectedNetworkList, &NETWORK_EDR);
-            break;
+            OIC_LOG(DEBUG, TAG, "Add network type(EDR)");
+            if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_EDR))
+            {
+                goto exit;
+            }
+            res = u_arraylist_add(g_selectedNetworkList, &NETWORK_EDR);
+        }
+        break;
 
         case CA_LE:
+        {
 
-#ifdef LE_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Add network type(LE) - Not Supported");
+#ifndef LE_ADAPTER
+            OIC_LOG(DEBUG, TAG, "Add network type(LE) - Not Supported");
             return CA_NOT_SUPPORTED;
 #endif /* LE_ADAPTER */
 
-            OIC_LOG_V(DEBUG, TAG, "Add network type(LE)");
-            u_arraylist_add(gSelectedNetworkList, &NETWORK_LE);
-            break;
+            OIC_LOG(DEBUG, TAG, "Add network type(LE)");
+            if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_LE))
+            {
+                goto exit;
+            }
+            res = u_arraylist_add(g_selectedNetworkList, &NETWORK_LE);
+        }
+        break;
 
     }
 
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res);
+        return res;
+    }
     // start selected interface adapter
-    CAStartAdapter(ConnectivityType);
+    res = CAStartAdapter((CATransportType_t)transportType);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return res;
 
+exit:
+    OIC_LOG(DEBUG, TAG, "This adapter is already enabled");
     return CA_STATUS_OK;
 }
 
-CAResult_t CARemoveNetworkType(uint32_t ConnectivityType)
+CAResult_t CARemoveNetworkType(CATransportType_t transportType)
 {
-    if (gSelectedNetworkList == NULL)
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == g_selectedNetworkList)
     {
-        OIC_LOG_V(DEBUG, TAG, "Selected network not found");
+        OIC_LOG(ERROR, TAG, "SelectedNetwork list is NULL");
 
         return CA_STATUS_FAILED;
     }
 
-    switch (ConnectivityType)
+    uint32_t selectedNetworkLength = u_arraylist_length(g_selectedNetworkList);
+    for (uint32_t index = 0; index < selectedNetworkLength; index++)
     {
-        case CA_ETHERNET:
-
-#ifndef ETHERNET_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET) - Not Supported");
-            return CA_NOT_SUPPORTED;
+        void* ptrType = u_arraylist_get(g_selectedNetworkList, index);
+        if (NULL == ptrType)
+        {
+            continue;
+        }
+
+        CATransportType_t connType = *(CATransportType_t *) ptrType;
+
+        if (transportType == connType)
+        {
+            switch (transportType)
+            {
+                case CA_IPV4:
+
+#ifndef IP_ADAPTER
+                    OIC_LOG(DEBUG, TAG, "Remove network type(IP) - Not Supported");
+                    return CA_NOT_SUPPORTED;
 #else
 
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET)");
-            u_arraylist_remove(gSelectedNetworkList, &NETWORK_ETHERNET);
-#endif /* ETHERNET_ADAPTER */
-            break;
-
-        case CA_WIFI:
+                    OIC_LOG(DEBUG, TAG, "Remove network type(IP)");
+                    u_arraylist_remove(g_selectedNetworkList, index);
+#endif /* IP_ADAPTER */
+                    break;
 
-#ifndef WIFI_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI) - Not Supported");
-            return CA_NOT_SUPPORTED;
-#else
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI)");
-            u_arraylist_remove(gSelectedNetworkList, &NETWORK_WIFI);
-#endif /* WIFI_ADAPTER */
+                case CA_IPV6:
+                {
+                    OIC_LOG(ERROR, TAG, "Currently IPV6 is not supported");
+                    return CA_NOT_SUPPORTED;
+                }
 
-            break;
-
-        case CA_EDR:
+                case CA_EDR:
 
 #ifndef EDR_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR) - Not Supported");
-            return CA_NOT_SUPPORTED;
+                    OIC_LOG(DEBUG, TAG, "Remove network type(EDR) - Not Supported");
+                    return CA_NOT_SUPPORTED;
 #else
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR)");
-            u_arraylist_remove(gSelectedNetworkList, &NETWORK_EDR);
+                    OIC_LOG(DEBUG, TAG, "Remove network type(EDR)");
+                    u_arraylist_remove(g_selectedNetworkList, index);
 #endif /* EDR_ADAPTER */
 
-            break;
+                    break;
 
-        case CA_LE:
+                case CA_LE:
 
-#ifdef LE_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(LE) - Not Supported");
-            return CA_NOT_SUPPORTED;
+#ifndef LE_ADAPTER
+                    OIC_LOG(DEBUG, TAG, "Remove network type(LE) - Not Supported");
+                    return CA_NOT_SUPPORTED;
 #else
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(LE)");
-            u_arraylist_remove(gSelectedNetworkList, &NETWORK_LE);
+                    OIC_LOG(DEBUG, TAG, "Remove network type(LE)");
+                    u_arraylist_remove(g_selectedNetworkList, index);
 #endif /* LE_ADAPTER */
 
-            break;
+                    break;
+            }
+
+            // stop selected interface adapter
+            CAStopAdapter(connType);
+            return CA_STATUS_OK;
+        }
     }
 
-    // stop selected interface adapter
-    CAStopAdapter(ConnectivityType);
+    return CA_STATUS_FAILED;
+}
 
-    return CA_STATUS_OK;
+u_arraylist_t *CAGetSelectedNetworkList()
+{
+    return g_selectedNetworkList;
 }
 
-u_arraylist_t* CAGetSelectedNetworkList()
+CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size)
 {
-    if (gSelectedNetworkList == NULL)
+    OIC_LOG(DEBUG, TAG, "get network information.");
+
+    if (NULL == info || NULL == size)
     {
-        OIC_LOG_V(DEBUG, TAG, "Selected network not found");
+        OIC_LOG(ERROR, TAG, "Input parameter is invalid value");
 
-        return NULL;
+        return CA_STATUS_INVALID_PARAM;
     }
 
-    return gSelectedNetworkList;
+    return CAGetNetworkInfo(info, size);
+}
+
+CAResult_t CATerminateNetworkType()
+{
+    OIC_LOG(DEBUG, TAG, "CATerminateNetworkType()");
+    if (NULL != g_selectedNetworkList)
+    {
+        u_arraylist_free(&g_selectedNetworkList);
+    }
+    return CA_STATUS_OK;
 }
index fb5a3d5..23bd47c 100644 (file)
  *
  ******************************************************************/
 
+// Defining _BSD_SOURCE or _DEFAULT_SOURCE causes header files to expose
+// definitions that may otherwise be skipped. Skipping can cause implicit
+// declaration warnings and/or bugs and subtle problems in code execution.
+// For glibc information on feature test macros,
+// Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
+//
+// This file requires #define use due to random() and srandom()
+// For details on compatibility and glibc support,
+// Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
+#define _DEFAULT_SOURCE
+#define _BSD_SOURCE
+
+// Include files from the arduino platform do not provide these conversions:
+#ifdef ARDUINO
+#define htons(x) ( ((x)<< 8 & 0xFF00) | ((x)>> 8 & 0x00FF) )
+#define ntohs(x) htons(x)
+#else
+#define HAVE_TIME_H 1
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <stdbool.h>
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
 
 #include "caprotocolmessage.h"
 #include "logger.h"
 #include "oic_malloc.h"
 
-#define TAG PCF("CA")
+// ARM GCC compiler doesnt define srandom function.
+#if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
+#define HAVE_SRANDOM 1
+#endif
+
+#define TAG "CA"
+
+#define CA_BUFSIZE (128)
+#define CA_PDU_MIN_SIZE (4)
+#define CA_PORT_BUFFER_SIZE (4)
 
-#define CA_MAX_TOKEN_LEN   8
-#define CA_FLAGS_BLOCK 0x01
-#define CA_URI_MAX_SIZE 256
-#define CA_BUFSIZE 40
+static const char COAP_URI_HEADER[] = "coap://[::]/";
 
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t* outReqInfo)
+static uint32_t SEED = 0;
+
+CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
+                                   char *outUri, uint32_t buflen)
 {
-    OIC_LOG(DEBUG, TAG, "get request info from PDU");
-    if (NULL == pdu)
-        return 0;
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == pdu || NULL == outReqInfo || NULL == outUri)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
 
     uint32_t code = CA_NOT_FOUND;
-    CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info));
+
+    OIC_LOG_V(DEBUG, TAG, "buffer length : %d", buflen);
+    CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &(outReqInfo->info), outUri, buflen);
     outReqInfo->method = code;
-    return 1;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return ret;
 }
 
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t* outResInfo)
+CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
+                                    char *outUri, uint32_t buflen)
 {
-    OIC_LOG(DEBUG, TAG, "get response info from PDU");
-    if (NULL == pdu)
-        return 0;
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (NULL == pdu || NULL == outResInfo || NULL == outUri)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
 
     uint32_t code = CA_NOT_FOUND;
-    CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info));
+    CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &(outResInfo->info), outUri, buflen);
     outResInfo->result = code;
-
-    return 1;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return ret;
 }
 
-coap_pdu_t* CAGeneratePdu(const char* uri, const uint32_t code, const CAInfo_t info)
+coap_pdu_t *CAGeneratePDU(const char *uri, uint32_t code, const CAInfo_t info)
 {
-    OIC_LOG(DEBUG, TAG, "generate PDU");
+    OIC_LOG(DEBUG, TAG, "IN");
 
-    coap_pdu_t *pdu;
-    char* coapUri = NULL;
-    uint32_t coapHeaderLength = 12;
-    uint32_t length;
-    coap_list_t *optlist = NULL;
+    coap_pdu_t *pdu = NULL;
 
-    if (NULL == uri)
-        return NULL;
+    // RESET have to use only 4byte (empty message)
+    // and ACKNOWLEDGE can use empty message when code is empty.
+    if (CA_MSG_RESET == info.type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info.type))
+    {
+        OIC_LOG(DEBUG, TAG, "code is empty");
+        if (!(pdu = CAGeneratePDUImpl((code_t) code, NULL, info, NULL, 0)))
+        {
+            OIC_LOG(ERROR, TAG, "pdu NULL");
+            return NULL;
+        }
+    }
+    else
+    {
+        coap_list_t *optlist = NULL;
 
-    length = strlen(uri);
-    coapUri = (char*) OICMalloc(length + coapHeaderLength + 1);
-    memset(coapUri, 0, length + coapHeaderLength + 1);
+        if (CA_MSG_ACKNOWLEDGE != info.type)
+        {
+            if (NULL == uri)
+            {
+                OIC_LOG(ERROR, TAG, "uri NULL");
+                return NULL;
+            }
 
-    if (NULL != coapUri)
-    {
+            uint32_t length = strlen(uri);
+            if (CA_MAX_URI_LENGTH < length)
+            {
+                OIC_LOG(ERROR, TAG, "URI len err");
+                return NULL;
+            }
 
-        memcpy(coapUri, "coap://[::]/", coapHeaderLength);
-        memcpy(coapUri + coapHeaderLength, uri, length);
+            uint32_t uriLength = length + sizeof(COAP_URI_HEADER);
+            char *coapUri = (char *) OICCalloc(1, uriLength);
+            if (NULL == coapUri)
+            {
+                OIC_LOG(ERROR, TAG, "out of memory");
+                return NULL;
+            }
+            strcat(coapUri, COAP_URI_HEADER);
+            strcat(coapUri, uri);
 
-        // parsing options in URI
-        CAParseURI(coapUri, &optlist);
+            // parsing options in URI
+            CAResult_t res = CAParseURI(coapUri, &optlist);
+            if (CA_STATUS_OK != res)
+            {
+                if (optlist)
+                {
+                    coap_delete_list(optlist);
+                }
+                OICFree(coapUri);
+                return NULL;
+            }
 
+            OICFree(coapUri);
+        }
         // parsing options in HeadOption
-        if (NULL != &info)
+        CAResult_t ret = CAParseHeadOption(code, info, &optlist);
+        if (CA_STATUS_OK != ret)
         {
-            CAParseHeadOption(code, info, &optlist);
-        }
-
-        OICFree(coapUri);
-    }
-
-    if (NULL != info.payload)
-    {
-        if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload)))
+            coap_delete_list(optlist);
             return NULL;
-    }
-    else
-    {
-        if (!(pdu = CACreatePDUforRequest((code_t) code, optlist)))
+        }
+        size_t lenPayload = info.payload ? strlen(info.payload) : 0;
+        pdu = CAGeneratePDUImpl((code_t) code, optlist, info, info.payload, lenPayload);
+        if (NULL == pdu)
+        {
+            OIC_LOG(ERROR, TAG, "pdu NULL");
+            coap_delete_list(optlist);
             return NULL;
+        }
+
+        // free option list
+        coap_delete_list(optlist);
     }
 
     // pdu print method : coap_show_pdu(pdu);
-
+    OIC_LOG(DEBUG, TAG, "OUT");
     return pdu;
 }
 
-coap_pdu_t* CAParsePDU(const char* data, uint32_t* outCode)
-{
-    coap_pdu_t* outpdu = coap_new_pdu();
-    coap_pdu_parse((unsigned char *) data, strlen(data), outpdu);
-    (*outCode) = (uint32_t) outpdu->hdr->code;
-
-    return outpdu;
-}
-
-coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,
-        const char* payload)
+coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode)
 {
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload");
-
-    coap_pdu_t *pdu;
-    coap_list_t *opt;
-    unsigned char _token_data[8];
-    str the_token =
-    { 0, _token_data };
+    OIC_LOG(DEBUG, TAG, "IN");
 
-    if (!(pdu = coap_new_pdu()))
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TAG, "data is null");
         return NULL;
+    }
 
-    /* initialize message id */
-    unsigned short message_id;
-    prng((unsigned char *)&message_id, sizeof(unsigned short));
-
-    pdu->hdr->type = msgtype;
-    pdu->hdr->id = htons(++message_id);
-    pdu->hdr->code = code;
-
-    pdu->hdr->token_length = the_token.length;
-    if (!coap_add_token(pdu, the_token.length, the_token.s))
+    coap_pdu_t *outpdu = coap_new_pdu();
+    if (NULL == outpdu)
     {
-        OIC_LOG(DEBUG, TAG,"cannot add token to request");
+        OIC_LOG(ERROR, TAG, "outpdu is null");
+        return NULL;
     }
 
-    for (opt = options; opt; opt = opt->next)
+    if (0 >= coap_pdu_parse((unsigned char *) data, length, outpdu))
     {
-        coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data),
-                COAP_OPTION_LENGTH(*(coap_option *)opt->data),
-                COAP_OPTION_DATA(*(coap_option *)opt->data));
+        OIC_LOG(ERROR, TAG, "pdu parse failed");
+        coap_delete_pdu(outpdu);
+        return NULL;
     }
 
-    if (NULL != payload)
+    if (outCode)
     {
-        uint32_t len = strlen(payload);
-        if ((flags & CA_FLAGS_BLOCK) == 0)
-        {
-            OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload);
-            coap_add_data(pdu, len, payload);
-        }
-        else
-        {
-            OIC_LOG_V(DEBUG, TAG, "coap_add_block, payload: %s", payload);
-            coap_add_block(pdu, len, payload, block.num, block.szx);
-        }
+        (*outCode) = (uint32_t) CA_RESPONSE_CODE(outpdu->hdr->code);
     }
-    return pdu;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return outpdu;
 }
 
-coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options)
+coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t info,
+                              const char *payload, size_t payloadSize)
 {
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest");
+    OIC_LOG(DEBUG, TAG, "IN");
 
-    coap_pdu_t *pdu;
-    coap_list_t *opt;
-    unsigned char _token_data[8];
-    str the_token =
-    { 0, _token_data };
+    coap_pdu_t *pdu = coap_new_pdu();
 
-    if (!(pdu = coap_new_pdu()))
+    if (NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "malloc failed");
         return NULL;
+    }
 
-    /* initialize message id */
-    unsigned short message_id;
-    prng((unsigned char *)&message_id, sizeof(unsigned short));
+    OIC_LOG_V(DEBUG, TAG, "msgID is %d", info.messageId);
+    uint16_t message_id;
+    if (0 == info.messageId)
+    {
+        /* initialize message id */
+        prng((uint8_t * ) &message_id, sizeof(message_id));
 
-    pdu->hdr->type = msgtype;
-    pdu->hdr->id = htons(++message_id);
-    pdu->hdr->code = code;
+        OIC_LOG_V(DEBUG, TAG, "gen msg id=%d", message_id);
+    }
+    else
+    {
+        /* use saved message id */
+        message_id = info.messageId;
+    }
+    pdu->hdr->id = message_id;
+    OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->hdr->id);
+
+    pdu->hdr->type = info.type;
+    pdu->hdr->code = COAP_RESPONSE_CODE(code);
+
+    if (info.token && CA_EMPTY != code)
+    {
+        uint32_t tokenLength = info.tokenLength;
+        OIC_LOG_V(DEBUG, TAG, "token info token length: %d, token :", tokenLength);
+        OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info.token, tokenLength);
+
+        int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *) info.token);
+        if (0 == ret)
+        {
+            OIC_LOG(ERROR, TAG, "can't add token");
+        }
+    }
 
-    pdu->hdr->token_length = the_token.length;
-    if (!coap_add_token(pdu, the_token.length, the_token.s))
+    if (options)
     {
-        OIC_LOG(DEBUG, TAG, "cannot add token to request");
+        for (coap_list_t *opt = options; opt; opt = opt->next)
+        {
+            OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
+                      COAP_OPTION_DATA(*(coap_option *) opt->data));
+            coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+                            COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+                            COAP_OPTION_DATA(*(coap_option *) opt->data));
+        }
     }
 
-    for (opt = options; opt; opt = opt->next)
+    if (NULL != payload)
     {
-        coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data),
-                COAP_OPTION_LENGTH(*(coap_option *)opt->data),
-                COAP_OPTION_DATA(*(coap_option *)opt->data));
+        OIC_LOG_V(DEBUG, TAG, "add data, payload:%s", payload);
+        coap_add_data(pdu, payloadSize, (const unsigned char *) payload);
     }
 
+    OIC_LOG(DEBUG, TAG, "OUT");
     return pdu;
 }
 
-void CAParseURI(const char* uriInfo, coap_list_t **optlist)
+CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
 {
-    OIC_LOG(DEBUG, TAG, "parse URI");
+    OIC_LOG(DEBUG, TAG, "IN");
 
-    unsigned char portbuf[2];
-    unsigned char _buf[CA_BUFSIZE];
-    unsigned char *buf = _buf;
-    coap_uri_t uri;
-    size_t buflen;
-    uint32_t res;
+    if (NULL == uriInfo)
+    {
+        OIC_LOG(ERROR, TAG, "uriInfo is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
 
     OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
 
+    if (NULL == optlist)
+    {
+        OIC_LOG(ERROR, TAG, "optlist is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
     /* split arg into Uri-* options */
+    coap_uri_t uri;
     coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
 
     if (uri.port != COAP_DEFAULT_PORT)
     {
-        coap_insert(optlist,
-                CACreateNewOptionNode(COAP_OPTION_URI_PORT,
-                        coap_encode_var_bytes(portbuf, uri.port), portbuf), CAOrderOpts);
+        unsigned char portbuf[CA_PORT_BUFFER_SIZE] = { 0 };
+        int ret = coap_insert(optlist,
+                              CACreateNewOptionNode(COAP_OPTION_URI_PORT,
+                                                    coap_encode_var_bytes(portbuf, uri.port),
+                                                    portbuf),
+                              CAOrderOpts);
+        if (ret <= 0)
+        {
+            return CA_STATUS_INVALID_PARAM;
+        }
     }
 
-    if (uri.path.length)
+    if (uri.path.s && uri.path.length)
     {
-        buflen = CA_BUFSIZE;
-        res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
+        CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length, COAP_OPTION_URI_PATH,
+                                           optlist);
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri path)");
+            return ret;
+        }
+    }
 
-        while (res--)
+    if (uri.query.s && uri.query.length)
+    {
+        CAResult_t ret = CAParseUriPartial(uri.query.s, uri.query.length, COAP_OPTION_URI_QUERY,
+                                           optlist);
+        if (CA_STATUS_OK != ret)
         {
-            coap_insert(optlist,
-                    CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),
-                            COAP_OPT_VALUE(buf)), CAOrderOpts);
-            buf += COAP_OPT_SIZE(buf);
+            OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri query)");
+            return ret;
         }
     }
 
-    if (uri.query.length)
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target,
+                             coap_list_t **optlist)
+{
+    if (!optlist)
     {
-        buflen = CA_BUFSIZE;
-        buf = _buf;
-        res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);
+        OIC_LOG(ERROR, TAG, "optlist is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
 
-        while (res--)
+    if ((target != COAP_OPTION_URI_PATH) && (target != COAP_OPTION_URI_QUERY))
+    {
+        // should never occur. Log just in case.
+        OIC_LOG(DEBUG, TAG, "Unexpected URI component.");
+        return CA_NOT_SUPPORTED;
+    }
+    else if (str && length)
+    {
+        unsigned char uriBuffer[CA_BUFSIZE] = { 0 };
+        unsigned char *pBuf = uriBuffer;
+        size_t buflen = sizeof(uriBuffer);
+        int res = (target == COAP_OPTION_URI_PATH) ? coap_split_path(str, length, pBuf, &buflen) :
+                                                     coap_split_query(str, length, pBuf, &buflen);
+
+        if (res > 0)
         {
-            coap_insert(optlist,
-                    CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),
-                            COAP_OPT_VALUE(buf)), CAOrderOpts);
+            size_t prevIdx = 0;
+            while (res--)
+            {
+                int ret = coap_insert(optlist,
+                                      CACreateNewOptionNode(target, COAP_OPT_LENGTH(pBuf),
+                                                            COAP_OPT_VALUE(pBuf)),
+                                      CAOrderOpts);
+                if (ret <= 0)
+                {
+                    return CA_STATUS_INVALID_PARAM;
+                }
 
-            buf += COAP_OPT_SIZE(buf);
+                size_t optSize = COAP_OPT_SIZE(pBuf);
+                if ((prevIdx + optSize) < buflen)
+                {
+                    pBuf += optSize;
+                    prevIdx += optSize;
+                }
+            }
         }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "Problem parsing URI : %d for %d", res, target);
+            return CA_STATUS_FAILED;
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "str or length is not available");
+        return CA_STATUS_FAILED;
     }
 
+    return CA_STATUS_OK;
 }
 
-void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist)
+CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t info, coap_list_t **optlist)
 {
-    OIC_LOG_V(DEBUG, TAG, "start parse Head Option : %d", info.numOptions);
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info.numOptions);
 
-    uint32_t i;
-    for (i = 0; i < info.numOptions; i++)
+    if (!optlist)
     {
-        coap_insert(optlist,
-                CACreateNewOptionNode(info.options->optionID, info.options->optionLength,
-                        info.options->optionData), CAOrderOpts);
+        OIC_LOG(ERROR, TAG, "optlist is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    for (uint32_t i = 0; i < info.numOptions; i++)
+    {
+        if(!(info.options + i))
+        {
+            OIC_LOG(ERROR, TAG, "options is not available");
+            return CA_STATUS_FAILED;
+        }
+
+        uint32_t id = (info.options + i)->optionID;
+        if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
+        {
+            OIC_LOG_V(DEBUG, TAG, "not Header Opt: %d", id);
+        }
+        else
+        {
+            if ((info.options + i)->optionData && (info.options + i)->optionLength > 0)
+            {
+                OIC_LOG_V(DEBUG, TAG, "Head opt ID: %d", id);
+                OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info.options + i)->optionData);
+                OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info.options + i)->optionLength);
+                int ret = coap_insert(optlist,
+                                      CACreateNewOptionNode(id, (info.options + i)->optionLength,
+                                                            (info.options + i)->optionData),
+                                      CAOrderOpts);
+                if (ret <= 0)
+                {
+                    return CA_STATUS_INVALID_PARAM;
+                }
+            }
+        }
     }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
 }
 
-coap_list_t* CACreateNewOptionNode(const uint16_t key, const uint32_t length, const uint8_t *data)
+coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const uint8_t *data)
 {
-    coap_option *option;
-    coap_list_t *node;
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (!data)
+    {
+        OIC_LOG(ERROR, TAG, "invalid pointer parameter");
+        return NULL;
+    }
 
-    option = coap_malloc(sizeof(coap_option) + length);
+    coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
     if (!option)
-        goto error;
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory");
+        return NULL;
+    }
+    memset(option, 0, sizeof(coap_option) + length + 1);
 
     COAP_OPTION_KEY(*option) = key;
     COAP_OPTION_LENGTH(*option) = length;
     memcpy(COAP_OPTION_DATA(*option), data, length);
 
     /* we can pass NULL here as delete function since option is released automatically  */
-    node = coap_new_listnode(option, NULL);
+    coap_list_t *node = coap_new_listnode(option, NULL);
 
-    if (node)
-        return node;
+    if (!node)
+    {
+        OIC_LOG(ERROR, TAG, "node is NULL");
+        coap_free(option);
+        return NULL;
+    }
 
-    error: perror("new_option_node: malloc");
-    coap_free( option);
-    return NULL;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return node;
 }
 
-int32_t CAOrderOpts(void *a, void *b)
+int CAOrderOpts(void *a, void *b)
 {
+    OIC_LOG(DEBUG, TAG, "IN");
     if (!a || !b)
+    {
         return a < b ? -1 : 1;
+    }
 
-    if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option *)b))
+    if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option * ) b))
+    {
         return -1;
+    }
 
-    return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option *)b);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option * ) b);
 }
 
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* outInfo)
+uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
 {
-    unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
-    uint32_t encode = 0;
-    coap_opt_iterator_t opt_iter;
-    coap_opt_t *option;
-    char optionResult[CA_URI_MAX_SIZE] =
-    { 0, };
+    OIC_LOG(DEBUG, TAG, "IN");
     uint32_t count = 0;
-    uint32_t isfirstsetflag = 0;
+    coap_opt_t *option;
+
+    while ((option = coap_option_next(&opt_iter)))
+    {
+        if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type)
+        {
+            count++;
+        }
+    }
 
-    /* show options, if any */
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return count;
+}
+
+CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
+                            char *outUri, uint32_t buflen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (!pdu || !outCode || !outInfo || !outUri)
+    {
+        OIC_LOG(ERROR, TAG, "NULL pointer param");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    coap_opt_iterator_t opt_iter;
     coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL);
 
-    memset(optionResult, 0, sizeof(optionResult));
-    while ((option = coap_option_next(&opt_iter)))
+    if (outCode)
     {
+        (*outCode) = (uint32_t) CA_RESPONSE_CODE(pdu->hdr->code);
+    }
 
-        if (print_readable(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), buf, sizeof(buf),
-                encode))
+    // init HeaderOption list
+    uint32_t count = CAGetOptionCount(opt_iter);
+    memset(outInfo, 0, sizeof(*outInfo));
+
+    outInfo->numOptions = count;
+
+    // set type
+    outInfo->type = pdu->hdr->type;
+
+    // set message id
+    outInfo->messageId = pdu->hdr->id;
+
+    if (count > 0)
+    {
+        outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t));
+        if (NULL == outInfo->options)
         {
-            if (opt_iter.type == COAP_OPTION_URI_PATH || opt_iter.type == COAP_OPTION_URI_QUERY)
+            OIC_LOG(ERROR, TAG, "Out of memory");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+
+    coap_opt_t *option;
+    char optionResult[CA_MAX_URI_LENGTH] = {0};
+    uint32_t idx = 0;
+    uint32_t optionLength = 0;
+    bool isfirstsetflag = false;
+    bool isQueryBeingProcessed = false;
+
+    while ((option = coap_option_next(&opt_iter)))
+    {
+        char buf[COAP_MAX_PDU_SIZE] = {0};
+        if (CAGetOptionData((uint8_t *)(COAP_OPT_VALUE(option)),
+                            COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf)))
+        {
+            OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
+            uint32_t bufLength = strlen(buf);
+            if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
             {
-                if (0 == isfirstsetflag)
+                if (false == isfirstsetflag)
                 {
-                    isfirstsetflag = 1;
-                    memcpy(optionResult + count, buf, strlen(buf));
-                    count += strlen(buf);
-
+                    isfirstsetflag = true;
+                    optionResult[optionLength] = '/';
+                    optionLength++;
+                    // Make sure there is enough room in the optionResult buffer
+                    if ((optionLength + bufLength) < sizeof(optionResult))
+                    {
+                        memcpy(&optionResult[optionLength], buf, bufLength);
+                        optionLength += bufLength;
+                    }
+                    else
+                    {
+                        goto exit;
+                    }
                 }
                 else
                 {
-                    if (opt_iter.type == COAP_OPTION_URI_PATH)
+                    if (COAP_OPTION_URI_PATH == opt_iter.type)
                     {
-                        memcpy(optionResult + count, "/", 1);
-                        count++;
+                        // Make sure there is enough room in the optionResult buffer
+                        if (optionLength < sizeof(optionResult))
+                        {
+                            optionResult[optionLength] = '/';
+                            optionLength++;
+                        }
+                        else
+                        {
+                            goto exit;
+                        }
                     }
-                    else if (opt_iter.type == COAP_OPTION_URI_QUERY)
+                    else if (COAP_OPTION_URI_QUERY == opt_iter.type)
                     {
-                        memcpy(optionResult + count, "?", 1);
-                        count++;
+                        if (false == isQueryBeingProcessed)
+                        {
+                            // Make sure there is enough room in the optionResult buffer
+                            if (optionLength < sizeof(optionResult))
+                            {
+                                optionResult[optionLength] = '?';
+                                optionLength++;
+                                isQueryBeingProcessed = true;
+                            }
+                            else
+                            {
+                                goto exit;
+                            }
+                        }
+                        else
+                        {
+                            // Make sure there is enough room in the optionResult buffer
+                            if (optionLength < sizeof(optionResult))
+                            {
+                                optionResult[optionLength] = '&';
+                                optionLength++;
+                            }
+                            else
+                            {
+                                goto exit;
+                            }
+                        }
+                    }
+                    // Make sure there is enough room in the optionResult buffer
+                    if ((optionLength + bufLength) < sizeof(optionResult))
+                    {
+                        memcpy(&optionResult[optionLength], buf, bufLength);
+                        optionLength += bufLength;
+                    }
+                    else
+                    {
+                        goto exit;
+                    }
+                }
+            }
+            else
+            {
+                if (idx < count)
+                {
+                    uint32_t length = bufLength;
+
+                    if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH)
+                    {
+                        outInfo->options[idx].optionID = opt_iter.type;
+                        outInfo->options[idx].optionLength = length;
+                        outInfo->options[idx].protocolID = CA_COAP_ID;
+                        memcpy(outInfo->options[idx].optionData, buf, length);
+                        idx++;
                     }
-                    memcpy(optionResult + count, buf, strlen(buf));
-                    count += strlen(buf);
                 }
             }
         }
     }
 
-    OIC_LOG(DEBUG, TAG, "set CAInfo_t after parsing");
+    // set token data
+    if (pdu->hdr->token_length > 0)
+    {
+        OIC_LOG_V(DEBUG, TAG, "inside token length : %d", pdu->hdr->token_length);
+        outInfo->token = (char *) OICMalloc(pdu->hdr->token_length);
+        if (NULL == outInfo->token)
+        {
+            OIC_LOG(ERROR, TAG, "Out of memory");
+            OICFree(outInfo->options);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+        memcpy(outInfo->token, pdu->hdr->token, pdu->hdr->token_length);
+    }
+
+    outInfo->tokenLength = pdu->hdr->token_length;
+
+    // set payload data
+    if (NULL != pdu->data)
+    {
+        uint32_t payloadLength = strlen((char*) pdu->data);
+        OIC_LOG(DEBUG, TAG, "inside pdu->data");
+        outInfo->payload = (char *) OICMalloc(payloadLength + 1);
+        if (NULL == outInfo->payload)
+        {
+            OIC_LOG(ERROR, TAG, "Out of memory");
+            OICFree(outInfo->options);
+            OICFree(outInfo->token);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+        memcpy(outInfo->payload, pdu->data, payloadLength);
+        outInfo->payload[payloadLength] = '\0';
+    }
 
-    // set pdu info
-    (*outCode) = (uint32_t) pdu->hdr->code;
-    memset(outInfo, 0, sizeof(CAInfo_t));
+    uint32_t length = strlen(optionResult);
+    OIC_LOG_V(DEBUG, TAG, "URL length:%d,%d,%d", length, buflen, strlen(outUri));
+    if (buflen >= length)
+    {
+        memcpy(outUri, optionResult, length);
+        outUri[length] = '\0';
+#ifdef ARDUINO
+        OIC_LOG_V(DEBUG, TAG, "made URL:%s\n", optionResult);
+#else
+        OIC_LOG_V(DEBUG, TAG, "made URL : %s, %s", optionResult, outUri);
+#endif
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
 
-    outInfo->options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t));
-    memset(outInfo->options, 0, sizeof(CAHeaderOption_t));
+exit:
+    OIC_LOG(ERROR, TAG, "buffer too small");
+    OICFree(outInfo->options);
+    return CA_STATUS_FAILED;
+}
 
-    outInfo->options->optionID = opt_iter.type;
-    outInfo->options->optionLength = count;
-    memcpy(outInfo->options->optionData, optionResult, CA_MAX_HEADER_OPTION_DATA_LENGTH);
+CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == pdu_hdr)
+    {
+        OIC_LOG(ERROR, TAG, "pdu_hdr is null");
+        return CA_STATUS_INVALID_PARAM;
+    }
 
-    if (pdu->hdr->token_length > 0)
+    if (NULL == outInfo)
     {
-        outInfo->token = (char*) OICMalloc(pdu->hdr->token_length);
-        memcpy(outInfo->token, pdu->hdr->token, pdu->hdr->token_length);
+        OIC_LOG(ERROR, TAG, "outInfo is null");
+        return CA_STATUS_INVALID_PARAM;
     }
 
-    if (NULL != pdu->data)
+    // set token data
+    if (pdu_hdr->token_length > 0)
     {
-        outInfo->payload = (char*) OICMalloc(strlen(pdu->data) + 1);
-        memcpy(outInfo->payload, pdu->data, strlen(pdu->data) + 1);
+        OIC_LOG_V(DEBUG, TAG, "token len:%d", pdu_hdr->token_length);
+        outInfo->token = (char *) OICMalloc(pdu_hdr->token_length);
+        if (NULL == outInfo->token)
+        {
+            OIC_LOG(ERROR, TAG, "out of memory");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+        memcpy(outInfo->token, pdu_hdr->token, pdu_hdr->token_length);
     }
+
+    outInfo->tokenLength = pdu_hdr->token_length;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
 }
 
-CAResult_t CAGenerateTokenInternal(CAToken_t* token)
+CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
 {
-    OIC_LOG(DEBUG, TAG, "generate the token");
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    if (!token)
+    {
+        OIC_LOG(ERROR, TAG, "invalid token pointer");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if ((tokenLength > CA_MAX_TOKEN_LEN) || (0 == tokenLength))
+    {
+        OIC_LOG(ERROR, TAG, "invalid token length");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (SEED == 0)
+    {
+#ifdef ARDUINO
+        SEED = now();
+#else
+        SEED = time(NULL);
+#endif
+        if (SEED == -1)
+        {
+            OIC_LOG(ERROR, TAG, "seed is not made");
+            SEED = 0;
+            return CA_STATUS_FAILED;
+        }
+#if HAVE_SRANDOM
+        srandom(SEED);
+#else
+        srand(SEED);
+#endif
+    }
+
+    // memory allocation
+    char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
+    if (NULL == temp)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    // set random byte
+    for (uint8_t index = 0; index < tokenLength; index++)
+    {
+        // use valid characters
+#ifdef ARDUINO
+        temp[index] = rand() & 0x00FF;
+#else
+        temp[index] = random() & 0x00FF;
+#endif
+    }
+
+    // save token
+    *token = temp;
+
+    OIC_LOG_V(DEBUG, TAG, "token len:%d, token:", tokenLength);
+    OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)(*token), tokenLength);
 
+    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CADestroyTokenInternal(CAToken_t token)
 {
-    OIC_LOG(DEBUG, TAG, "destroy the token!!");
+    OIC_LOG(DEBUG, TAG, "IN");
+    OICFree(token);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CADestroyInfo(CAInfo_t *info)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
 
-    if (token != NULL)
+    if (NULL != info)
     {
-        OICFree(token);
+        OIC_LOG(DEBUG, TAG, "free options");
+        OICFree(info->options);
+
+        OIC_LOG(DEBUG, TAG, "free token");
+        OICFree(info->token);
+
+        OIC_LOG(DEBUG, TAG, "free payload");
+        OICFree(info->payload);
     }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *option, uint32_t buflen)
+{
+    if (0 == buflen || 0 == len)
+    {
+        OIC_LOG(ERROR, TAG, "len 0");
+        return 0;
+    }
+
+    if (NULL == data || NULL == option)
+    {
+        OIC_LOG(ERROR, TAG, "data/option NULL");
+        return 0;
+    }
+
+    if (buflen <= len)
+    {
+        OIC_LOG(ERROR, TAG, "option buffer too small");
+        return 0;
+    }
+
+    memcpy(option, data, len);
+    option[len] = '\0';
+
+    return len;
+}
+
+CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
+{
+    if (NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "pdu is null");
+        return CA_MSG_NONCONFIRM;
+    }
+
+    // pdu minimum size is 4 byte.
+    if (size < CA_PDU_MIN_SIZE)
+    {
+        OIC_LOG(ERROR, TAG, "min size");
+        return CA_MSG_NONCONFIRM;
+    }
+
+    coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+    return (CAMessageType_t) hdr->type;
+}
+
+uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
+{
+    if (NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "pdu is null");
+        return 0;
+    }
+
+    // pdu minimum size is 4 byte.
+    if (size < CA_PDU_MIN_SIZE)
+    {
+        OIC_LOG(ERROR, TAG, "min size");
+        return 0;
+    }
+
+    coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+    return hdr->id;
+}
+
+CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
+{
+    if (NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "pdu is null");
+        return CA_NOT_FOUND;
+    }
+
+    // pdu minimum size is 4 byte.
+    if (size < CA_PDU_MIN_SIZE)
+    {
+        OIC_LOG(ERROR, TAG, "min size");
+        return CA_NOT_FOUND;
+    }
+
+    coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+
+    return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->code);
 }
diff --git a/resource/csdk/connectivity/src/caqueueingthread.c b/resource/csdk/connectivity/src/caqueueingthread.c
new file mode 100644 (file)
index 0000000..01bed4b
--- /dev/null
@@ -0,0 +1,277 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+
+#include "caqueueingthread.h"
+#include "oic_malloc.h"
+#include "logger.h"
+
+#define TAG PCF("CA")
+
+static void CAQueueingThreadBaseRoutine(void *threadValue)
+{
+    OIC_LOG(DEBUG, TAG, "message handler main thread start..");
+
+    CAQueueingThread_t *thread = (CAQueueingThread_t *) threadValue;
+
+    if (NULL == thread)
+    {
+        OIC_LOG(ERROR, TAG, "thread data passing error!!");
+
+        return;
+    }
+
+    while (!thread->isStop)
+    {
+        // mutex lock
+        ca_mutex_lock(thread->threadMutex);
+
+        // if queue is empty, thread will wait
+        if (!thread->isStop && u_queue_get_size(thread->dataQueue) <= 0)
+        {
+            OIC_LOG(DEBUG, TAG, "wait..");
+
+            // wait
+            ca_cond_wait(thread->threadCond, thread->threadMutex);
+
+            OIC_LOG(DEBUG, TAG, "wake up..");
+        }
+
+        // mutex unlock
+        ca_mutex_unlock(thread->threadMutex);
+
+        // check stop flag
+        if (thread->isStop)
+        {
+            continue;
+        }
+
+        // get data
+        u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
+        if (NULL == message)
+        {
+            continue;
+        }
+
+        // process data
+        thread->threadTask(message->msg);
+
+        // free
+        if (NULL != thread->destroy)
+        {
+            thread->destroy(message->msg, message->size);
+        }
+        else
+        {
+            OICFree(message->msg);
+        }
+
+        OICFree(message);
+    }
+
+    // remove all remained list data.
+    while (u_queue_get_size(thread->dataQueue) > 0)
+    {
+        // get data
+        u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
+
+        // free
+        if(NULL != message)
+        {
+            if (NULL != thread->destroy)
+            {
+                thread->destroy(message->msg, message->size);
+            }
+            else
+            {
+                OICFree(message->msg);
+            }
+
+            OICFree(message);
+        }
+    }
+
+    ca_mutex_lock(thread->threadMutex);
+    ca_cond_signal(thread->threadCond);
+    ca_mutex_unlock(thread->threadMutex);
+
+    OIC_LOG(DEBUG, TAG, "message handler main thread end..");
+}
+
+CAResult_t CAQueueingThreadInitialize(CAQueueingThread_t *thread, ca_thread_pool_t handle,
+                                      CAThreadTask task, CADataDestroyFunction destroy)
+{
+    if (NULL == thread)
+    {
+        OIC_LOG(ERROR, TAG, "thread instance is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (NULL == handle)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    OIC_LOG(DEBUG, TAG, "thread initialize..");
+
+    // set send thread data
+    thread->threadPool = handle;
+    thread->dataQueue = u_queue_create();
+    thread->threadMutex = ca_mutex_new();
+    thread->threadCond = ca_cond_new();
+    thread->isStop = true;
+    thread->threadTask = task;
+    thread->destroy = destroy;
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread)
+{
+    if (NULL == thread)
+    {
+        OIC_LOG(ERROR, TAG, "thread instance is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (NULL == thread->threadPool)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (false == thread->isStop) //Queueing thread already running
+    {
+        OIC_LOG(DEBUG, TAG, "queueing thread already running..");
+        return CA_STATUS_OK;
+    }
+
+    // mutex lock
+    ca_mutex_lock(thread->threadMutex);
+    thread->isStop = false;
+    // mutex unlock
+    ca_mutex_unlock(thread->threadMutex);
+
+    CAResult_t res = ca_thread_pool_add_task(thread->threadPool, CAQueueingThreadBaseRoutine,
+                                            thread);
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
+    }
+
+    return res;
+}
+
+CAResult_t CAQueueingThreadAddData(CAQueueingThread_t *thread, void *data, uint32_t size)
+{
+    if (NULL == thread)
+    {
+        OIC_LOG(ERROR, TAG, "thread instance is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (NULL == data || 0 == size)
+    {
+        OIC_LOG(ERROR, TAG, "data is empty..");
+
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // create thread data
+    u_queue_message_t *message = (u_queue_message_t *) OICMalloc(sizeof(u_queue_message_t));
+
+    if (NULL == message)
+    {
+        OIC_LOG(ERROR, TAG, "memory error!!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    message->msg = data;
+    message->size = size;
+
+    // mutex lock
+    ca_mutex_lock(thread->threadMutex);
+
+    // add thread data into list
+    u_queue_add_element(thread->dataQueue, message);
+
+    // notity the thread
+    ca_cond_signal(thread->threadCond);
+
+    // mutex unlock
+    ca_mutex_unlock(thread->threadMutex);
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAQueueingThreadDestroy(CAQueueingThread_t *thread)
+{
+    if (NULL == thread)
+    {
+        OIC_LOG(ERROR, TAG, "thread instance is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    OIC_LOG(DEBUG, TAG, "thread destroy..");
+
+    ca_mutex_free(thread->threadMutex);
+    thread->threadMutex = NULL;
+    ca_cond_free(thread->threadCond);
+    u_queue_delete(thread->dataQueue);
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAQueueingThreadStop(CAQueueingThread_t *thread)
+{
+    if (NULL == thread)
+    {
+        OIC_LOG(ERROR, TAG, "thread instance is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    OIC_LOG(DEBUG, TAG, "thread stop request!!");
+
+    if (!thread->isStop)
+    {
+        // mutex lock
+        ca_mutex_lock(thread->threadMutex);
+
+        // set stop flag
+        thread->isStop = true;
+
+        // notify the thread
+        ca_cond_signal(thread->threadCond);
+
+        ca_cond_wait(thread->threadCond, thread->threadMutex);
+
+        // mutex unlock
+        ca_mutex_unlock(thread->threadMutex);
+    }
+
+    return CA_STATUS_OK;
+}
index f193168..9bf509a 100644 (file)
  *
  ******************************************************************/
 
+#include <string.h>
+
 #include "oic_malloc.h"
 #include "caremotehandler.h"
 #include "logger.h"
 
-#define TAG PCF("CA")
+#define TAG "CA"
 
-CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep)
+CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *rep)
 {
-    char* temp = NULL;
-    int len = 0;
-
-    if (rep == NULL)
+    if (NULL == rep)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
         return NULL;
+    }
 
     // allocate the remote end point structure.
-    CARemoteEndpoint_t* clone = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t));
-    if (clone == NULL)
+    CARemoteEndpoint_t *clone = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
+    if (NULL == clone)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+        OIC_LOG(ERROR, TAG, "CACloneRemoteEndpoint Out of memory");
         return NULL;
     }
-    memset(clone, 0, sizeof(CARemoteEndpoint_t));
     memcpy(clone, rep, sizeof(CARemoteEndpoint_t));
 
-    if (rep->resourceUri != NULL)
+    if (NULL != rep->resourceUri)
     {
         // allocate reference uri field
-        len = strlen(rep->resourceUri);
+        size_t len = strlen(rep->resourceUri);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
-        if (temp == NULL)
+        char *temp = (char *) OICCalloc(len + 1, sizeof(char));
+        if (NULL == temp)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG(ERROR, TAG, "CACloneRemoteEndpoint Out of memory");
 
             CADestroyRemoteEndpointInternal(clone);
 
             return NULL;
         }
-        memset(temp, 0, sizeof(char) * (len + 1));
+
         strncpy(temp, rep->resourceUri, len);
 
         // save the uri
@@ -68,13 +69,19 @@ CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep)
 
 #define COAP_PREFIX         "coap://"
 #define COAP_PREFIX_LEN     7
+#define COAPS_PREFIX         "coaps://"
+#define COAPS_PREFIX_LEN     8
+
 
 // return 1 : ip
 // return 0 : mac
-static int32_t getCAAddress(const char* pAddress, CAAddress_t* outAddress)
+static int32_t getCAAddress(const char *pAddress, CAAddress_t *outAddress)
 {
-    if (pAddress == NULL || outAddress == NULL)
+    if (NULL == pAddress || NULL == outAddress)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
         return -1;
+    }
 
     // simple parse, it will be change.
     // 10.11.12.13:4545 (ip)
@@ -84,7 +91,6 @@ static int32_t getCAAddress(const char* pAddress, CAAddress_t* outAddress)
 
     int32_t isIp = 0;
     int32_t ipLen = 0;
-    int32_t port = 0;
 
     int i = 0;
     for (i = 0; i < len; i++)
@@ -104,12 +110,29 @@ static int32_t getCAAddress(const char* pAddress, CAAddress_t* outAddress)
 
     if (isIp)
     {
-        strncpy(outAddress->IP.ipAddress, pAddress, ipLen == 0 ? len : ipLen);
+        if(ipLen && ipLen < sizeof(outAddress->IP.ipAddress))
+        {
+            strncpy(outAddress->IP.ipAddress, pAddress, ipLen);
+            outAddress->IP.ipAddress[ipLen] = '\0';
+        }
+        else if (!ipLen && len < sizeof(outAddress->IP.ipAddress))
+        {
+            strncpy(outAddress->IP.ipAddress, pAddress, len);
+            outAddress->IP.ipAddress[len] = '\0';
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "IP Address too long: %d", ipLen==0 ? len : ipLen);
+            return -1;
+        }
+
 
         if (ipLen > 0)
+        {
             outAddress->IP.port = atoi(pAddress + ipLen + 1);
+        }
 
-        OIC_LOG_V(DEBUG, TAG, "ip: %s,port: %d", outAddress->IP.ipAddress, outAddress->IP.port);
+        OIC_LOG_V(DEBUG, TAG, "ip: %s, port: %d", outAddress->IP.ipAddress, outAddress->IP.port);
     }
     else
     {
@@ -121,48 +144,59 @@ static int32_t getCAAddress(const char* pAddress, CAAddress_t* outAddress)
     return isIp;
 }
 
-CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri)
+CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri,
+                                                      const CATransportType_t transportType)
 {
     // support URI type
     // coap://10.11.12.13:4545/resource_uri
     // coap://10:11:12:13:45:45/resource_uri
 
-    if (uri == NULL)
+    if (NULL == uri)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
         return NULL;
+    }
 
     // parse uri
     // #1. check prefix
     int startIndex = 0;
-
+    bool secured = false;
     if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
     {
         OIC_LOG_V(DEBUG, TAG, "uri has '%s' prefix.", COAP_PREFIX);
         startIndex = COAP_PREFIX_LEN;
     }
 
+    if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
+    {
+        OIC_LOG_V(DEBUG, TAG, "uri has '%s' prefix.", COAPS_PREFIX);
+        startIndex = COAPS_PREFIX_LEN;
+        secured = true;
+    }
+
     // #2. copy uri for parse
-    char* cloneUri = NULL;
     int32_t len = strlen(uri) - startIndex;
 
     if (len <= 0)
     {
-        OIC_LOG_V(DEBUG, TAG, "uri length is 0!");
+        OIC_LOG(ERROR, TAG, "uri length is 0!");
         return NULL;
     }
 
-    cloneUri = (char*) OICMalloc(sizeof(char) * (len + 1));
-    if (cloneUri == NULL)
+    char *cloneUri = (char *) OICCalloc(len + 1, sizeof(char));
+    if (NULL == cloneUri)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory error!!");
+        OIC_LOG(ERROR, TAG, "CACreateRemoteEndpointUriInternal Out of memory");
         return NULL;
     }
-    memset(cloneUri, 0, sizeof(char) * (len + 1));
-    memcpy(cloneUri, &uri[startIndex], sizeof(char) * (len + 1));
+
+    memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
+    cloneUri[len] = '\0';
 
     // #3. parse address
     // #4. parse resource uri
-    charpAddress = cloneUri;
-    charpResourceUri = NULL;
+    char *pAddress = cloneUri;
+    char *pResourceUri = NULL;
 
     int32_t i = 0;
     for (i = 0; i < len; i++)
@@ -184,13 +218,12 @@ CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri)
     OIC_LOG_V(DEBUG, TAG, "pResourceUri : %s", pResourceUri == NULL ? "" : pResourceUri);
 
     // address
-    CAAddress_t address;
-    memset(&address, 0, sizeof(CAAddress_t));
+    CAAddress_t address = {};
 
     int resType = getCAAddress(pAddress, &address);
     if (resType == -1)
     {
-        OIC_LOG_V(DEBUG, TAG, "address parse error");
+        OIC_LOG(DEBUG, TAG, "address parse error");
 
         OICFree(cloneUri);
         return NULL;
@@ -199,61 +232,56 @@ CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri)
     // resource uri
     CAURI_t resourceUri = pResourceUri;
 
-    // connectivity type
-    CAConnectivityType_t type;
-
-    if (resType == 1)
+    CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address,
+                                                                        transportType);
+    if (NULL == remoteEndpoint)
     {
-        type = CA_WIFI;
-    }
-    else
-    {
-        type = CA_EDR;
-    }
+        OIC_LOG(ERROR, TAG, "create remote endpoint fail");
 
-    CARemoteEndpoint_t* remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address, type);
+        OICFree(cloneUri);
+        return NULL;
+    }
+    remoteEndpoint->isSecured = secured;
 
     OICFree(cloneUri);
 
+    OIC_LOG_V(DEBUG, TAG, "Remote endpoint successfully created [%d]!", remoteEndpoint->isSecured);
     return remoteEndpoint;
 }
 
-CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
-        const CAAddress_t addr, const CAConnectivityType_t type)
+CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
+                                                   const CAAddress_t addr,
+                                                   const CATransportType_t type)
 {
-    char* temp = NULL;
-    int len = 0;
-
-    if (resourceUri == NULL)
+    if (NULL == resourceUri)
     {
-        OIC_LOG_V(DEBUG, TAG, "uri is null value");
+        OIC_LOG(ERROR, TAG, "uri is null value");
         return NULL;
     }
 
     // allocate the remote end point structure.
-    CARemoteEndpoint_t* rep = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t));
+    CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *) OICCalloc(1, sizeof(CARemoteEndpoint_t));
 
-    if (rep == NULL)
+    if (NULL == rep)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error");
+        OIC_LOG(ERROR, TAG, "CACreateRemoteEndpointInternal of memory");
         return NULL;
     }
-    memset(rep, 0, sizeof(CARemoteEndpoint_t));
 
     // allocate reference uri field
-    len = strlen(resourceUri);
+    size_t len = strlen(resourceUri);
 
-    temp = (char*) OICMalloc(sizeof(char) * (len + 1));
-    if (temp == NULL)
+    char *temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+    if (NULL == temp)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error");
+        OIC_LOG(ERROR, TAG, "CACreateRemoteEndpointInternal Out of memory");
 
         CADestroyRemoteEndpointInternal(rep);
 
         return NULL;
     }
-    memset(temp, 0, sizeof(char) * (len + 1));
     strncpy(temp, resourceUri, len);
+    temp[len] = '\0';
 
     // save the uri
     rep->resourceUri = temp;
@@ -262,74 +290,92 @@ CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
     memcpy(&(rep->addressInfo), &addr, sizeof(CAAddress_t));
 
     // save the type
-    rep->connectivityType = type;
+    rep->transportType = type;
 
     return rep;
 }
 
-CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep)
+CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
 {
-    char* temp = NULL;
-    int len = 0;
-
-    if (rep == NULL)
+    if (NULL == rep)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
         return NULL;
+    }
 
     // allocate the request info structure.
-    CARequestInfo_t* clone = (CARequestInfo_t*) OICMalloc(sizeof(CARequestInfo_t));
-    if (clone == NULL)
+    CARequestInfo_t *clone = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
+    if (!clone)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+        OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
         return NULL;
     }
-    memset(clone, 0, sizeof(CARequestInfo_t));
+
     memcpy(clone, rep, sizeof(CARequestInfo_t));
 
-    if (rep->info.token != NULL)
+    if (rep->info.token)
     {
+        char *temp = NULL;
+
         // allocate token field
-        len = strlen(rep->info.token);
+        uint8_t len = rep->info.tokenLength;
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
-        if (temp == NULL)
+        if (len)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            temp = (char *) OICCalloc(len, sizeof(char));
+            if (!temp)
+            {
+                OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
 
-            CADestroyRequestInfoInternal(clone);
+                CADestroyRequestInfoInternal(clone);
 
-            return NULL;
+                return NULL;
+            }
+            memcpy(temp, rep->info.token, len);
         }
-        memset(temp, 0, sizeof(char) * (len + 1));
-        strncpy(temp, rep->info.token, len);
 
         // save the token
         clone->info.token = temp;
+        clone->info.tokenLength = len;
     }
 
-    if (rep->info.options != NULL)
+    if (NULL != rep->info.options && 0 < rep->info.numOptions)
     {
         // save the options
-        clone->info.options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t));
-        memset(clone->info.options, 0, sizeof(CAHeaderOption_t));
-        memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t));
+        clone->info.options =
+            (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * rep->info.numOptions);
+        if (NULL == clone->info.options)
+        {
+            OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
+            OICFree(clone->info.token);
+            OICFree(clone);
+            return NULL;
+        }
+        memcpy(clone->info.options, rep->info.options,
+               sizeof(CAHeaderOption_t) * rep->info.numOptions);
+    }
+    else
+    {
+        clone->info.options = NULL;
+        clone->info.numOptions = 0;
     }
 
-    if (rep->info.payload != NULL)
+    if (NULL != rep->info.payload)
     {
         // allocate payload field
-        len = strlen(rep->info.payload);
+        size_t len = strlen(rep->info.payload);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
-        if (temp == NULL)
+        char *temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+        if (NULL == temp)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
 
             CADestroyRequestInfoInternal(clone);
 
             return NULL;
         }
-        memset(temp, 0, sizeof(char) * (len + 1));
         strncpy(temp, rep->info.payload, len);
+        temp[len] = '\0';
 
         // save the payload
         clone->info.payload = temp;
@@ -338,68 +384,85 @@ CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep)
     return clone;
 }
 
-CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep)
+CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep)
 {
-    char* temp = NULL;
-    int len = 0;
-
-    if (rep == NULL)
+    if (NULL == rep)
+    {
+        OIC_LOG(ERROR, TAG, "Response pointer is NULL");
         return NULL;
+    }
 
     // allocate the response info structure.
-    CAResponseInfo_t* clone = (CAResponseInfo_t*) OICMalloc(sizeof(CAResponseInfo_t));
-    if (clone == NULL)
+    CAResponseInfo_t *clone = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
+    if (NULL == clone)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+        OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
         return NULL;
     }
-    memset(clone, 0, sizeof(CAResponseInfo_t));
     memcpy(clone, rep, sizeof(CAResponseInfo_t));
 
-    if (rep->info.token != NULL)
+    if (rep->info.token)
     {
+        char *temp = NULL;
+
         // allocate token field
-        len = strlen(rep->info.token);
+        uint8_t len = rep->info.tokenLength;
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
-        if (temp == NULL)
+        if (len)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            temp = (char *) OICCalloc(len, sizeof(char));
+            if (!temp)
+            {
+                OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
 
-            CADestroyResponseInfoInternal(clone);
+                CADestroyResponseInfoInternal(clone);
 
-            return NULL;
+                return NULL;
+            }
+            memcpy(temp, rep->info.token, len);
         }
-        memset(temp, 0, sizeof(char) * (len + 1));
-        strncpy(temp, rep->info.token, len);
-
         // save the token
         clone->info.token = temp;
+        clone->info.tokenLength = len;
     }
 
-    if (rep->info.options != NULL)
+    if (NULL != rep->info.options && rep->info.numOptions)
     {
         // save the options
-        clone->info.options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t));
-        memset(clone->info.options, 0, sizeof(CAHeaderOption_t));
-        memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t));
+        clone->info.options =
+                (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * rep->info.numOptions);
+
+        if (NULL == clone->info.options)
+        {
+            OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
+
+            OICFree(clone->info.token);
+            OICFree(clone);
+            return NULL;
+        }
+        memcpy(clone->info.options, rep->info.options,
+                sizeof(CAHeaderOption_t) * rep->info.numOptions);
+    }
+    else
+    {
+        clone->info.options = NULL;
+        clone->info.numOptions = 0;
     }
 
-    if (rep->info.payload != NULL)
+    if (NULL != rep->info.payload)
     {
         // allocate payload field
-        len = strlen(rep->info.payload);
+        int32_t len = strlen(rep->info.payload);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
-        if (temp == NULL)
+        char *temp = (char *) OICCalloc(len + 1, sizeof(char));
+        if (NULL == temp)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
 
             CADestroyResponseInfoInternal(clone);
 
             return NULL;
         }
-        memset(temp, 0, sizeof(char) * (len + 1));
         strncpy(temp, rep->info.payload, len);
 
         // save the payload
@@ -409,69 +472,61 @@ CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep)
     return clone;
 }
 
-void CADestroyRemoteEndpointInternal(CARemoteEndpoint_trep)
+void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t *rep)
 {
-    if (rep == NULL)
+    if (NULL == rep)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
         return;
+    }
 
     // free uri field
-    if (rep->resourceUri != NULL)
-    {
-        OICFree((char*) rep->resourceUri);
-    }
+    OICFree((char *) rep->resourceUri);
 
     // free remote end point structure.
     OICFree(rep);
 }
 
-void CADestroyRequestInfoInternal(CARequestInfo_trep)
+void CADestroyRequestInfoInternal(CARequestInfo_t *rep)
 {
-    if (rep == NULL)
+    if (NULL == rep)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
         return;
+    }
 
     // free token field
-    if (rep->info.token != NULL)
-    {
-        OICFree((char*) rep->info.token);
-    }
+    OICFree(rep->info.token);
 
     // free options field
-    if (rep->info.options != NULL)
-    {
-        OICFree((CAHeaderOption_t*) rep->info.options);
-    }
+    OICFree((CAHeaderOption_t *) rep->info.options);
 
     // free payload field
-    if (rep->info.payload != NULL)
-    {
-        OICFree((char*) rep->info.payload);
-    }
+    OICFree((char *) rep->info.payload);
 
     OICFree(rep);
 }
 
-void CADestroyResponseInfoInternal(CAResponseInfo_trep)
+void CADestroyResponseInfoInternal(CAResponseInfo_t *rep)
 {
-    if (rep == NULL)
+    if (NULL == rep)
+    {
+        OIC_LOG(ERROR, TAG, "parameter is null");
         return;
+    }
 
     // free token field
-    if (rep->info.token != NULL)
-    {
-        OICFree((char*) rep->info.token);
-    }
+    OICFree(rep->info.token);
 
     // free options field
-    if (rep->info.options != NULL)
+    if (rep->info.options != NULL && rep->info.numOptions)
     {
-        OICFree((CAHeaderOption_t*) rep->info.options);
+        OICFree((CAHeaderOption_t *) rep->info.options);
     }
 
     // free payload field
-    if (rep->info.payload != NULL)
-    {
-        OICFree((char*) rep->info.payload);
-    }
+    OICFree((char *) rep->info.payload);
 
     OICFree(rep);
 }
+
diff --git a/resource/csdk/connectivity/src/caretransmission.c b/resource/csdk/connectivity/src/caretransmission.c
new file mode 100644 (file)
index 0000000..aeb2b5d
--- /dev/null
@@ -0,0 +1,630 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+// Defining _BSD_SOURCE or _DEFAULT_SOURCE causes header files to expose
+// definitions that may otherwise be skipped. Skipping can cause implicit
+// declaration warnings and/or bugs and subtle problems in code execution.
+// For glibc information on feature test macros,
+// Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
+//
+// This file requires #define use due to random()
+// For details on compatibility and glibc support,
+// Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
+#define _DEFAULT_SOURCE
+#define _BSD_SOURCE
+
+// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1b, Real-time extensions
+// (IEEE Std 1003.1b-1993) specification
+//
+// For this specific file, see use of clock_gettime,
+// Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
+// and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/time.h>
+
+#if defined(__ANDROID__)
+#include <linux/time.h>
+#endif
+
+#include "caretransmission.h"
+#include "caremotehandler.h"
+#include "caprotocolmessage.h"
+#include "oic_malloc.h"
+#include "logger.h"
+
+#define TAG PCF("CA")
+
+typedef struct
+{
+    uint64_t timeStamp;                 /**< last sent time. microseconds */
+    uint64_t timeout;                   /**< timeout value. microseconds */
+    uint8_t triedCount;                 /**< retransmission count */
+    uint16_t messageId;                 /**< coap PDU message id */
+    CARemoteEndpoint_t *endpoint;       /**< remote endpoint */
+    void *pdu;                          /**< coap PDU */
+    uint32_t size;                      /**< coap PDU size */
+} CARetransmissionData_t;
+
+static const uint64_t USECS_PER_SEC = 1000000;
+
+/**
+ * @brief   getCurrent monotonic time
+ * @return  current time in microseconds
+ */
+uint64_t getCurrentTimeInMicroSeconds();
+
+/**
+ * @brief   check timeout routine
+ * @param   currentTime     [IN]microseconds
+ * @param   timeStamp       [IN]microseconds
+ * @param   timeoutValue    [IN]microseconds
+ * @param   triedCount      [IN]Number of retransmission tried
+ * @return  true if the timeout period has elapsed, false otherwise
+ */
+static bool CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint64_t timeoutValue,
+                           uint8_t triedCount)
+{
+    // #1. calculate timeout
+    uint32_t milliTimeoutValue = timeoutValue * 0.001;
+    uint64_t timeout = (milliTimeoutValue << triedCount) * (uint64_t) 1000;
+
+    if (currentTime >= timeStamp + timeout)
+    {
+        OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%d)", timeout, triedCount);
+        return true;
+    }
+
+    return false;
+}
+
+/**
+ * @brief   timeout value is
+ *          between DEFAULT_ACK_TIMEOUT_SEC and
+ *          (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
+ *          DEFAULT_RANDOM_FACTOR       1.5 (CoAP)
+ * @return  microseconds.
+ */
+static uint64_t CAGetTimeoutValue()
+{
+    return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
+            (uint64_t) 1000;
+}
+
+static void CACheckRetransmissionList(CARetransmission_t *context)
+{
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "context is null..");
+        return;
+    }
+
+    // mutex lock
+    ca_mutex_lock(context->threadMutex);
+
+    uint32_t i = 0;
+    uint32_t len = u_arraylist_length(context->dataList);
+
+    for (i = 0; i < len; i++)
+    {
+        CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
+
+        if (NULL == retData)
+        {
+            continue;
+        }
+
+        uint64_t currentTime = getCurrentTimeInMicroSeconds();
+
+        if (CACheckTimeout(currentTime, retData->timeStamp, retData->timeout, retData->triedCount))
+        {
+            // #2. if time's up, send the data.
+            if (NULL != context->dataSendMethod)
+            {
+                OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, message id(%d)",
+                          retData->messageId);
+                context->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
+            }
+
+            // #3. increase the retransmission count and update timestamp.
+            retData->timeStamp = currentTime;
+            retData->triedCount++;
+        }
+
+        // #4. if tried count is max, remove the retransmission data from list.
+        if (retData->triedCount >= context->config.tryingCount)
+        {
+            CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
+
+            if (NULL != removedData)
+            {
+                OIC_LOG_V(DEBUG, TAG, "max trying count, remove retransmission CON data!!,\
+                          message id(%d)", removedData->messageId);
+
+                // callback for retransmit timeout
+                if (NULL != context->timeoutCallback)
+                {
+                    context->timeoutCallback(removedData->endpoint, removedData->pdu,
+                                             removedData->size);
+                }
+
+                CADestroyRemoteEndpointInternal(removedData->endpoint);
+                OICFree(removedData->pdu);
+
+                OICFree(removedData);
+
+                // modify loop value.
+                len = u_arraylist_length(context->dataList);
+
+                --i;
+            }
+            else
+            {
+                OIC_LOG(ERROR, TAG, "arraylist remove error");
+            }
+
+        }
+    }
+
+    // mutex unlock
+    ca_mutex_unlock(context->threadMutex);
+}
+
+static void CARetransmissionBaseRoutine(void *threadValue)
+{
+    OIC_LOG(DEBUG, TAG, "retransmission main thread start..");
+
+    CARetransmission_t *context = (CARetransmission_t *) threadValue;
+
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "thread data passing error!!");
+
+        return;
+    }
+
+    while (!context->isStop)
+    {
+        // mutex lock
+        ca_mutex_lock(context->threadMutex);
+
+        if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
+        {
+            // if list is empty, thread will wait
+            OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
+
+            // wait
+            ca_cond_wait(context->threadCond, context->threadMutex);
+
+            OIC_LOG(DEBUG, TAG, "wake up..");
+        }
+        else if (!context->isStop)
+        {
+            // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
+            OIC_LOG_V(DEBUG, TAG, "wait..(%d)microseconds",
+                      RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
+
+            // wait
+            uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
+            ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
+        }
+        else
+        {
+            // we are stopping, so we want to unlock and finish stopping
+        }
+
+        // mutex unlock
+        ca_mutex_unlock(context->threadMutex);
+
+        // check stop flag
+        if (context->isStop)
+        {
+            continue;
+        }
+
+        CACheckRetransmissionList(context);
+    }
+
+    ca_mutex_lock(context->threadMutex);
+    ca_cond_signal(context->threadCond);
+    ca_mutex_unlock(context->threadMutex);
+
+    OIC_LOG(DEBUG, TAG, "retransmission main thread end..");
+
+}
+
+CAResult_t CARetransmissionInitialize(CARetransmission_t *context, ca_thread_pool_t handle,
+                                      CADataSendMethod_t retransmissionSendMethod,
+                                      CATimeoutCallback_t timeoutCallback,
+                                      CARetransmissionConfig_t* config)
+{
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "thread instance is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (NULL == handle)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    OIC_LOG(DEBUG, TAG, "thread initialize..");
+
+    memset(context, 0, sizeof(CARetransmission_t));
+
+    CARetransmissionConfig_t cfg = { 0 };
+
+    if (NULL == config)
+    {
+        // setDefault
+        cfg.supportType = DEFAULT_RETRANSMISSION_TYPE;
+        cfg.tryingCount = DEFAULT_MAX_RETRANSMIT;
+    }
+    else
+    {
+        cfg = *config;
+    }
+
+    // set send thread data
+    context->threadPool = handle;
+    context->threadMutex = ca_mutex_new();
+    context->threadCond = ca_cond_new();
+    context->dataSendMethod = retransmissionSendMethod;
+    context->timeoutCallback = timeoutCallback;
+    context->config = cfg;
+    context->isStop = false;
+    context->dataList = u_arraylist_create();
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionStart(CARetransmission_t *context)
+{
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "context is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (NULL == context->threadPool)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
+                                            context);
+
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
+        return res;
+    }
+
+    return res;
+}
+
+CAResult_t CARetransmissionSentData(CARetransmission_t *context,
+                                    const CARemoteEndpoint_t* endpoint, const void* pdu,
+                                    uint32_t size)
+{
+    if (NULL == context || NULL == endpoint || NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "invalid parameter..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // #0. check support transport type
+    if (!(context->config.supportType & endpoint->transportType))
+    {
+        OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)",
+                  endpoint->transportType);
+        return CA_NOT_SUPPORTED;
+    }
+
+    // #1. check PDU method type and get message id.
+    CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
+    uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
+
+    OIC_LOG_V(DEBUG, TAG, "sent pdu, message type(%d), message id(%d)", type, messageId);
+
+    if (CA_MSG_CONFIRM != type)
+    {
+        OIC_LOG(DEBUG, TAG, "not supported message type for retransmission..");
+        return CA_NOT_SUPPORTED;
+    }
+
+    // create retransmission data
+    CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
+                                          1, sizeof(CARetransmissionData_t));
+
+    if (NULL == retData)
+    {
+        OIC_LOG(ERROR, TAG, "memory error!!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    // copy PDU data
+    void *pduData = (void *) OICMalloc(size);
+    if (NULL == pduData)
+    {
+        OICFree(retData);
+        OIC_LOG(ERROR, TAG, "memory error!!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memcpy(pduData, pdu, size);
+
+    // clone remote endpoint
+    CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(endpoint);
+    if (NULL == remoteEndpoint)
+    {
+        OICFree(retData);
+        OICFree(pduData);
+        OIC_LOG(ERROR, TAG, "memory error!!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    // #2. add additional information. (time stamp, retransmission count...)
+    retData->timeStamp = getCurrentTimeInMicroSeconds();
+    retData->timeout = CAGetTimeoutValue();
+    retData->triedCount = 0;
+    retData->messageId = messageId;
+    retData->endpoint = remoteEndpoint;
+    retData->pdu = pduData;
+    retData->size = size;
+
+    // mutex lock
+    ca_mutex_lock(context->threadMutex);
+
+    uint32_t i = 0;
+    uint32_t len = u_arraylist_length(context->dataList);
+
+    // #3. add data into list
+    for (i = 0; i < len; i++)
+    {
+        CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
+
+        if (NULL == currData)
+        {
+            continue;
+        }
+
+        // found index
+        if (NULL != currData->endpoint && currData->messageId == messageId
+            && (currData->endpoint->transportType == endpoint->transportType))
+        {
+            OIC_LOG(ERROR, TAG, "Duplicate message ID");
+
+            // mutex unlock
+            ca_mutex_unlock(context->threadMutex);
+
+            OICFree(retData);
+            OICFree(pduData);
+            OICFree(remoteEndpoint);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    u_arraylist_add(context->dataList, (void *) retData);
+
+    // notify the thread
+    ca_cond_signal(context->threadCond);
+
+    // mutex unlock
+    ca_mutex_unlock(context->threadMutex);
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
+                                        const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                        uint32_t size, void **retransmissionPdu)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CARetransmissionReceivedData");
+    if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
+    {
+        OIC_LOG(ERROR, TAG, "invalid parameter..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // #0. check support transport type
+    if (!(context->config.supportType & endpoint->transportType))
+    {
+        OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)",
+                  endpoint->transportType);
+        return CA_STATUS_OK;
+    }
+
+    // #1. check PDU method type and get message id.
+    // ACK, RST --> remove the CON data
+    CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
+    uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
+
+    OIC_LOG_V(DEBUG, TAG, "received pdu, message type(%d), message id(%d)", type, messageId);
+
+    if ((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
+    {
+        return CA_STATUS_OK;
+    }
+
+    // mutex lock
+    ca_mutex_lock(context->threadMutex);
+    uint32_t len = u_arraylist_length(context->dataList);
+
+    // find index
+    uint32_t i;
+    for (i = 0; i < len; i++)
+    {
+        CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
+                context->dataList, i);
+
+        if (NULL == retData)
+        {
+            continue;
+        }
+
+        // found index
+        if (NULL != retData->endpoint && retData->messageId == messageId
+            && (retData->endpoint->transportType == endpoint->transportType))
+        {
+            // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
+            // if retransmission was finish..token will be unavailable.
+            if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
+            {
+                OIC_LOG(DEBUG, TAG, "code is CA_EMPTY..");
+
+                if (NULL == retData->pdu)
+                {
+                    OIC_LOG(ERROR, TAG, "retData->pdu is null");
+                    OICFree(retData);
+                    // mutex unlock
+                    ca_mutex_unlock(context->threadMutex);
+
+                    return CA_STATUS_FAILED;
+                }
+
+                // copy PDU data
+                (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
+                if ((*retransmissionPdu) == NULL)
+                {
+                    OICFree(retData);
+                    OIC_LOG(ERROR, TAG, "memory error!!");
+
+                    // mutex unlock
+                    ca_mutex_unlock(context->threadMutex);
+
+                    return CA_MEMORY_ALLOC_FAILED;
+                }
+                memcpy((*retransmissionPdu), retData->pdu, retData->size);
+            }
+
+            // #2. remove data from list
+            CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
+            if (NULL == removedData)
+            {
+                OIC_LOG(ERROR, TAG, "Removed data is NULL");
+
+                // mutex unlock
+                ca_mutex_unlock(context->threadMutex);
+
+                return CA_STATUS_FAILED;
+            }
+
+            OIC_LOG_V(DEBUG, TAG, "remove retransmission CON data!!, message id(%d)",
+                      messageId);
+
+            CADestroyRemoteEndpointInternal(removedData->endpoint);
+            OICFree(removedData->pdu);
+            OICFree(removedData);
+
+            break;
+        }
+    }
+
+    // mutex unlock
+    ca_mutex_unlock(context->threadMutex);
+
+    OIC_LOG(DEBUG, TAG, "OUT - CARetransmissionReceivedData");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionStop(CARetransmission_t *context)
+{
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "context is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
+
+    // mutex lock
+    ca_mutex_lock(context->threadMutex);
+
+    // set stop flag
+    context->isStop = true;
+
+    // notify the thread
+    ca_cond_signal(context->threadCond);
+
+    ca_cond_wait(context->threadCond, context->threadMutex);
+
+    // mutex unlock
+    ca_mutex_unlock(context->threadMutex);
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
+{
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "context is empty..");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
+
+    ca_mutex_free(context->threadMutex);
+    context->threadMutex = NULL;
+    ca_cond_free(context->threadCond);
+    u_arraylist_free(&context->dataList);
+
+    return CA_STATUS_OK;
+}
+
+uint64_t getCurrentTimeInMicroSeconds()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    uint64_t currentTime = 0;
+
+#ifdef __ANDROID__
+    struct timespec getTs;
+
+    clock_gettime(CLOCK_MONOTONIC, &getTs);
+
+    currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
+    OIC_LOG_V(DEBUG, TAG, "current time = %d", currentTime);
+#else
+#if _POSIX_TIMERS > 0
+    struct timespec ts;
+    clock_gettime(CLOCK_MONOTONIC, &ts);
+    currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#else
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
+#endif
+#endif
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return currentTime;
+}
diff --git a/resource/csdk/connectivity/src/caretransmission_singlethread.c b/resource/csdk/connectivity/src/caretransmission_singlethread.c
new file mode 100644 (file)
index 0000000..e419278
--- /dev/null
@@ -0,0 +1,440 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "caretransmission_singlethread.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "caremotehandler.h"
+#include "caprotocolmessage.h"
+#include "oic_malloc.h"
+#include "logger.h"
+
+#ifndef __ARDUINO__
+#include <sys/time.h>
+#endif
+
+#define TAG "RT"
+
+typedef struct
+{
+    /** last sent time. microseconds **/
+    uint64_t timeStamp;
+
+    /** retransmission count **/
+    uint8_t triedCount;
+
+    /** coap PDU message id **/
+    uint16_t messageId;
+
+    /** remote endpoint **/
+    CARemoteEndpoint_t *endpoint;
+
+    /** coap PDU **/
+    void *pdu;
+
+    /** coap PDU size**/
+    uint32_t size;
+
+} CARetransmissionData_t;
+
+static CARetransmission_t *g_retransmissionPtr = NULL;
+
+/**
+ * getCurrent monotonic time.
+ *
+ * @return current time in microseconds.
+ */
+uint64_t getCurrentTimeInMicroSeconds();
+
+/**
+ * @brief   check timeout routine
+ * @param   currentTime     [IN]microseconds
+ * @param   timeStamp       [IN]microseconds
+ * @param   triedCount      [IN]Number of retransmission tried.
+ * @return  true if the timeout period has elapsed, false otherwise.
+ */
+static bool CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint8_t triedCount)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    // #1. calculate timeout
+    uint64_t timeOut = (2 << triedCount) * 1000000;
+
+    if (currentTime >= timeStamp + timeOut)
+    {
+        OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d", (2 << triedCount), triedCount);
+        return true;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return false;
+}
+
+void CACheckRetransmissionList()
+{
+    uint32_t len = u_arraylist_length(g_retransmissionPtr->dataList);
+
+    OIC_LOG_V(DEBUG, TAG, "len=%d", len);
+    for (uint32_t i = 0; i < len; i++)
+    {
+        CARetransmissionData_t *retData =
+                (CARetransmissionData_t *) u_arraylist_get(g_retransmissionPtr->dataList, i);
+
+        if (NULL == retData)
+        {
+            continue;
+        }
+
+        uint64_t currentTime = getCurrentTimeInMicroSeconds();
+
+        OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
+        if (CACheckTimeout(currentTime, retData->timeStamp, retData->triedCount))
+        {
+
+            OIC_LOG(DEBUG, TAG, "RTdata-Success");
+            // #2. if time's up, send the data.
+            if (NULL != g_retransmissionPtr->dataSendMethod)
+            {
+                OIC_LOG_V(DEBUG, TAG, "retry CON data-msgid=%d", retData->messageId);
+                g_retransmissionPtr->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
+            }
+
+            // #3. increase the retransmission count and update timestamp.
+            retData->timeStamp = currentTime;
+            retData->triedCount++;
+        }
+
+        // #4. if tried count is max, remove the retransmission data from list.
+        if (retData->triedCount >= g_retransmissionPtr->config.tryingCount)
+        {
+            CARetransmissionData_t *removedData = (CARetransmissionData_t *) u_arraylist_remove(
+                    g_retransmissionPtr->dataList, i);
+            if (NULL == removedData)
+            {
+                OIC_LOG(ERROR, TAG, "Removed data is NULL");
+                return;
+            }
+
+            OIC_LOG(DEBUG, TAG, "max trycount rchd");
+
+            OIC_LOG_V(DEBUG, TAG, "max trycount, remove retransmission CON data!!, messageid=%d",
+                      removedData->messageId);
+
+            // callback for retransmit timeout
+            if (NULL != g_retransmissionPtr->timeoutCallback)
+            {
+                g_retransmissionPtr->timeoutCallback(removedData->endpoint, removedData->pdu,
+                                                     removedData->size);
+            }
+
+            CADestroyRemoteEndpointInternal(removedData->endpoint);
+            OICFree(removedData->pdu);
+
+            OICFree(removedData);
+
+            // modify loop value.
+            len = u_arraylist_length(g_retransmissionPtr->dataList);
+            --i;
+        }
+    }
+}
+
+void CARetransmissionBaseRoutine(void *threadValue)
+{
+    CARetransmission_t *context = (CARetransmission_t *) threadValue;
+
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "cnxt null");
+        return;
+    }
+
+    if (true == context->isStop)
+    {
+        OIC_LOG(DEBUG, TAG, "thread stopped");
+        return;
+    }
+    g_retransmissionPtr = context;
+    CACheckRetransmissionList();
+}
+
+CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
+                                      CADataSendMethod_t retransmissionSendMethod,
+                                      CATimeoutCallback_t timeoutCallback,
+                                      CARetransmissionConfig_t *config)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "cnxt null");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    memset(context, 0, sizeof(CARetransmission_t));
+
+    CARetransmissionConfig_t cfg;
+    memset(&cfg, 0, sizeof(CARetransmissionConfig_t));
+
+    if (NULL == config)
+    {
+        // setDefault
+        cfg.supportType = (CATransportType_t) DEFAULT_RETRANSMISSION_TYPE;
+        cfg.tryingCount = DEFAULT_RETRANSMISSION_COUNT;
+    }
+    else
+    {
+        cfg = *config;
+    }
+
+    // set send thread data
+    context->dataSendMethod = retransmissionSendMethod;
+    context->timeoutCallback = timeoutCallback;
+    context->config = cfg;
+    context->isStop = false;
+    context->dataList = u_arraylist_create();
+
+    // Enable TimedAction for CACheckRetransmissionList API
+    g_retransmissionPtr = context;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionSentData(CARetransmission_t *context, const CARemoteEndpoint_t *endpoint,
+                                    const void *pdu, uint32_t size)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == context || NULL == endpoint || NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "error");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // #0. check support connectivity type
+    if (!(context->config.supportType & endpoint->transportType))
+    {
+        OIC_LOG(ERROR, TAG, "error");
+        OIC_LOG_V(ERROR, TAG, "not supported conntype=%d", endpoint->transportType);
+        return CA_NOT_SUPPORTED;
+    }
+
+    // #1. check PDU method type and get message id.
+    CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
+    uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
+
+    OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d,msgid=%d", type, messageId);
+
+    if (CA_MSG_CONFIRM != type)
+    {
+        OIC_LOG(DEBUG, TAG, "not supported message type");
+        return CA_NOT_SUPPORTED;
+    }
+
+    // create retransmission data
+    CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
+            1, sizeof(CARetransmissionData_t));
+
+    if (NULL == retData)
+    {
+        OIC_LOG(ERROR, TAG, "error");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    // copy PDU data
+    void *pduData = (void *) OICMalloc(size);
+    if (NULL == pduData)
+    {
+        OICFree(retData);
+        OIC_LOG(ERROR, TAG, "error");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    memcpy(pduData, pdu, size);
+
+    // clone remote endpoint
+    CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(endpoint);
+    if (NULL == remoteEndpoint)
+    {
+        OICFree(retData);
+        OICFree(pduData);
+        OIC_LOG(ERROR, TAG, "error");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    // #2. add additional information. (time stamp, retransmission count...)
+    retData->timeStamp = getCurrentTimeInMicroSeconds();
+    retData->triedCount = 0;
+    retData->messageId = messageId;
+    retData->endpoint = remoteEndpoint;
+    retData->pdu = pduData;
+    retData->size = size;
+
+    // #3. add data into list
+    u_arraylist_add(context->dataList, (void *) retData);
+
+    // #4. Initiate Re-transmission for added entry
+    g_retransmissionPtr = context;
+    CACheckRetransmissionList();
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
+                                        const CARemoteEndpoint_t *endpoint, const void *pdu,
+                                        uint32_t size, void **retransmissionPdu)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
+    {
+        OIC_LOG(ERROR, TAG, "error");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // #0. check support connectivity type
+    if (!(context->config.supportType & endpoint->transportType))
+    {
+        OIC_LOG_V(DEBUG, TAG, "not supp conntype=%d", endpoint->transportType);
+        return CA_STATUS_OK;
+    }
+
+    // #1. check PDU method type and get message id.
+    // ACK, RST --> remove the CON data
+    CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
+    uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
+
+    OIC_LOG_V(DEBUG, TAG, "recv pdu, msgtype=%d,msgid=%d", type, messageId);
+
+    if (CA_MSG_ACKNOWLEDGE != type && CA_MSG_RESET != type)
+    {
+        return CA_STATUS_OK;
+    }
+
+    uint32_t len = u_arraylist_length(context->dataList);
+
+    // find index
+    for (uint32_t i = 0; i < len; i++)
+    {
+        CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
+                context->dataList, i);
+
+        if (NULL == retData)
+        {
+            continue;
+        }
+
+        // found index
+        if (NULL != retData->endpoint && retData->messageId == messageId
+            && (retData->endpoint->transportType == endpoint->transportType))
+        {
+            // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
+            // if retransmission was finish..token will be unavailable.
+            if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
+            {
+                OIC_LOG(DEBUG, TAG, "CA_EMPTY");
+
+                if (NULL == retData->pdu)
+                {
+                    OIC_LOG(ERROR, TAG, "retData->pdu is null");
+                    OICFree(retData);
+                    return CA_STATUS_FAILED;
+                }
+
+                // copy PDU data
+                (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
+                if (NULL == (*retransmissionPdu))
+                {
+                    OICFree(retData);
+                    OIC_LOG(ERROR, TAG, "error");
+                    return CA_MEMORY_ALLOC_FAILED;
+                }
+                memcpy((*retransmissionPdu), retData->pdu, retData->size);
+            }
+
+            // #2. remove data from list
+            CARetransmissionData_t *removedData = (CARetransmissionData_t *) u_arraylist_remove(
+                    context->dataList, i);
+            if (NULL == removedData)
+            {
+                OIC_LOG(ERROR, TAG, "Removed data is NULL");
+                return CA_STATUS_FAILED;
+            }
+
+            OIC_LOG_V(DEBUG, TAG, "remove RTCON data, msgid=%d", messageId);
+
+            CADestroyRemoteEndpointInternal(removedData->endpoint);
+            OICFree(removedData->pdu);
+
+            OICFree(removedData);
+
+            break;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionStop(CARetransmission_t *context)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "error");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    // set stop flag
+    context->isStop = true;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (NULL == context)
+    {
+        OIC_LOG(ERROR, TAG, "error");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    u_arraylist_free(&context->dataList);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+uint64_t getCurrentTimeInMicroSeconds()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    uint64_t currentTime = 0;
+
+#ifdef __ARDUINO__
+    currentTime = millis() * 1000;
+
+    OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
+#else
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
+#endif
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return currentTime;
+}
+
diff --git a/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetadapter.c b/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetadapter.c
deleted file mode 100644 (file)
index e73c2fd..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "caethernetadapter.h"
-#include "logger.h"
-
-#define TAG PCF("CA")
-
-static CANetworkPacketReceivedCallback gEthernetReceivedCallback = NULL;
-
-CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback)
-{
-    OIC_LOG_V(DEBUG, TAG, "CAInitializeEthernet");
-
-    gEthernetReceivedCallback = reqRespCallback;
-
-    // register handlers
-    CAConnectivityHandler_t handler;
-    memset(&handler, 0, sizeof(CAConnectivityHandler_t));
-
-    handler.startAdapter = CAStartEthernet;
-    handler.startListenServer = CAStartEthernetListeningServer;
-    handler.startDiscoverServer = CAStartEthernetDiscoveryServer;
-    handler.sendData = CASendEthernetUnicastData;
-    handler.sendDataToAll = CASendEthernetMulticastData;
-    handler.startNotifyServer = CAStartEthernetNotifyServer;
-    handler.sendNotification = CASendEthernetNotification;
-    handler.GetnetInfo = CAGetEthernetInterfaceInformation;
-    handler.readData = CAReadEthernetData;
-    handler.stopAdapter = CAStopEthernet;
-    handler.terminate = CATerminateEthernet;
-
-    registerCallback(handler, CA_ETHERNET);
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAStartEthernet()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStartEthernet");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAStartEthernetListeningServer()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStartEthernetListeningServer");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAStartEthernetDiscoveryServer()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStartEthernetDiscoveryServer");
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendEthernetUnicastData");
-
-    return 0;
-}
-
-uint32_t CASendEthernetMulticastData(void* data, uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendEthernetMulticastData");
-
-    return 0;
-}
-
-CAResult_t CAStartEthernetNotifyServer()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStartEthernetNotifyServer");
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendEthernetNotification(const CARemoteEndpoint_t* endpoint, void* data,
-        uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendEthernetNotification");
-
-    return 0;
-}
-
-CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size)
-{
-    OIC_LOG_V(DEBUG, TAG, "CAGetEthernetInterfaceInformation");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAReadEthernetData()
-{
-    OIC_LOG_V(DEBUG, TAG, "Read Ethernet Data");
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAStopEthernet()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStopEthernet");
-
-    return CA_STATUS_OK;
-}
-
-void CATerminateEthernet()
-{
-    OIC_LOG_V(DEBUG, TAG, "CATerminateEthernet");
-}
diff --git a/resource/csdk/connectivity/src/ip_adapter/SConscript b/resource/csdk/connectivity/src/ip_adapter/SConscript
new file mode 100644 (file)
index 0000000..2320380
--- /dev/null
@@ -0,0 +1,48 @@
+#######################################################
+#      Building IP adapter
+#######################################################
+
+Import('env')
+
+print "Reading IP adapter script"
+
+target_os = env.get('TARGET_OS')
+inc_files = env.get('CPPPATH')
+src_dir = './ip_adapter/'
+
+if target_os == 'tizen':
+    env.ParseConfig("pkg-config --cflags --libs capi-network-wifi")
+
+#Source files to build common for all platforms
+if target_os == 'arduino':
+       env.AppendUnique(CA_SRC=[src_dir+'caipadapter_singlethread.c'])
+       env.AppendUnique(CPPPATH=[src_dir+'arduino/'])
+else:
+      env.AppendUnique(CA_SRC=[src_dir+'caipadapter.c'])
+      env.AppendUnique(CA_SRC=[src_dir+'caipclient.c'])
+      env.AppendUnique(CA_SRC=[src_dir+'caipserver.c'])
+
+#Source files to build in Linux platform
+if target_os == 'linux':
+       env.AppendUnique(CA_SRC=[src_dir+'linux/caipnwmonitor.c'])
+
+if target_os == 'tizen':
+       env.AppendUnique(CA_SRC=[src_dir+'tizen/caipnwmonitor.c'])
+
+#Source files to build in Arduino platform
+if target_os == 'arduino':
+       env.AppendUnique(CA_SRC=[src_dir+'arduino/caipnwmonitor.cpp'])
+       if env.get('SHIELD') == 'WIFI':
+               env.AppendUnique(CA_SRC=[src_dir+'arduino/caipclient_wifi.cpp',
+                               src_dir+'arduino/caipserver_wifi.cpp',
+                               ])
+       else:
+               env.AppendUnique(CA_SRC=[src_dir+'arduino/caipadapterutils_eth.cpp',
+                               src_dir+'arduino/caipclient_eth.cpp',
+                               src_dir+'arduino/caipserver_eth.cpp',
+                               ])
+
+#Source files to build in android platform
+if target_os == 'android':
+       env.AppendUnique(CA_SRC=[src_dir+'android/caipnwmonitor.c'])
+       env.AppendUnique(CPPPATH=[src_dir+'android/'])
diff --git a/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c
new file mode 100644 (file)
index 0000000..4272e65
--- /dev/null
@@ -0,0 +1,882 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "caipinterface.h"
+
+#include <string.h>
+#include <sys/ioctl.h>
+#include <arpa/inet.h>
+#include <linux/if.h>
+#include <netdb.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "caadapterutils.h"
+#include "camutex.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "org_iotivity_ca_CaIpInterface.h"
+
+#define IP_MONITOR_TAG "IP_MONITOR"
+#define MAX_INTERFACE_INFO_LENGTH (1024)
+
+/**
+ * @var g_stopNetworkMonitor
+ * @brief  Used to stop the network monitor thread.
+ */
+static bool g_stopNetworkMonitor = false;
+
+/**
+ * @var g_stopNetworkMonitorMutex
+ * @brief  Mutex for synchronizing access to g_stopNetworkMonitor flag.
+ */
+static ca_mutex g_stopNetworkMonitorMutex = NULL;
+
+/**
+ * @struct CAIPNwMonitorContext
+ * @brief  Used for storing network monitor context information.
+ */
+typedef struct
+{
+    u_arraylist_t *netInterfaceList;
+    ca_thread_pool_t threadPool;
+    CANetworkStatus_t nwConnectivityStatus;
+    CAIPConnectionStateChangeCallback networkChangeCb;
+} CAIPNetworkMonitorContext;
+
+/**
+ * @var g_networkMonitorContext
+ * @brief  network monitor context.
+ */
+static CAIPNetworkMonitorContext *g_networkMonitorContext = NULL;
+
+/**
+ * @var g_networkMonitorContextMutex
+ * @brief  Mutex for synchronizing access to cached interface and IP address information.
+ */
+static ca_mutex g_networkMonitorContextMutex = NULL;
+
+/**
+ * @var g_jvm
+ * @brief pointer to store JavaVM
+ */
+static JavaVM *g_jvm = NULL;
+
+/**
+ * @var g_context
+ * @brief pointer to store Application Context
+ */
+static jobject g_context = NULL;
+
+/**
+ * @fn CAIPUpdateInterfaceInformation
+ * @brief This methods gets local interface name and IP address information.
+ */
+static CAResult_t CAIPUpdateInterfaceInformation(u_arraylist_t **netInterfaceList);
+/**
+ * @fn CACreateIPJNIInterfaceObject
+ * @brief creates new instance of caipinterface through JNI
+ */
+static CAResult_t CACreateIPJNIInterfaceObject(jobject context);
+
+/**
+ * @fn CAIPSendNetworkChangeCallback
+ * @brief updates network status to IP adapter
+ */
+static void CAIPSendNetworkChangeCallback(CANetworkStatus_t currNetworkStatus);
+
+CAResult_t CAIPJniInit()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPJniInit");
+    g_jvm = CANativeJNIGetJavaVM();
+
+    if (!g_jvm)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "JNI initialize error");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPJniSetContext()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPJniSetContext");
+    g_context = (jobject) CANativeJNIGetContext();
+
+    if (!g_context)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "unable to get application context");
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CACreateIPJNIInterfaceObject(jobject context)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACreateIPJNIInterfaceObject");
+
+    VERIFY_NON_NULL(context, IP_MONITOR_TAG, "context");
+
+    JNIEnv* env;
+
+    if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get JNIEnv pointer");
+        return CA_STATUS_FAILED;
+    }
+
+    //getApplicationContext
+    jclass contextClass = (*env)->FindClass(env, "android/content/Context");
+    if (!contextClass)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get context object class");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID getApplicationContextMethod = (*env)->GetMethodID(env, contextClass,
+                                                                "getApplicationContext",
+                                                                "()Landroid/content/Context;");
+    if (!getApplicationContextMethod)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get getApplicationContext method");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject gApplicationContext = (*env)->CallObjectMethod(env, context,
+                                                           getApplicationContextMethod);
+    if (!getApplicationContextMethod)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get getApplicationContext");
+        return CA_STATUS_FAILED;
+    }
+
+    //Create caipinterface jni instance
+    jclass IPJniInterface = (*env)->FindClass(env, "org/iotivity/ca/CaIpInterface");
+    if (!IPJniInterface)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get caipinterface class");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID IPInterfaceConstructorMethod = (*env)->GetMethodID(env, IPJniInterface, "<init>",
+                                                                   "(Landroid/content/Context;)V");
+    if (!IPInterfaceConstructorMethod)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get caipinterface constructor method");
+        return CA_STATUS_FAILED;
+    }
+
+    (*env)->NewObject(env, IPJniInterface, IPInterfaceConstructorMethod, gApplicationContext);
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "Create caipinterface instance, success");
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+static CAResult_t CAIPUpdateInterfaceInformation(u_arraylist_t **netInterfaceList)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null");
+
+    /* Get a socket handle. */
+    int sck = -1;
+#ifdef SOCK_CLOEXEC
+    sck = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
+#endif
+
+    if ( -1 == sck)
+    {
+        sck=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+    }
+
+    if (sck < 0)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Error in socket creation");
+        return CA_STATUS_FAILED;
+    }
+
+    char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
+    struct ifconf ifc;
+
+    /* Query available interfaces. */
+    ifc.ifc_len = MAX_INTERFACE_INFO_LENGTH;
+    ifc.ifc_buf = buf;
+
+    if (ioctl(sck, SIOCGIFCONF, &ifc) < 0)
+    {
+        close(sck);
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Failed to get interface info");
+        return CA_STATUS_FAILED;
+    }
+
+    /* Iterate through the list of interfaces. */
+    struct ifreq* ifr = ifc.ifc_req;
+    int32_t interfaces = ifc.ifc_len / sizeof(struct ifreq);
+
+    OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPUpdateInterfaceInformation : %d", interfaces);
+
+    for (int32_t i = 0; i < interfaces; i++)
+    {
+        struct ifreq temp_ifr = { 0 };
+        struct ifreq* item = &ifr[i];
+
+        char interfaceAddress[CA_IPADDR_SIZE] = { 0 };
+        char interfaceSubnetMask[CA_IPADDR_SIZE] = { 0 };
+        socklen_t len = sizeof(struct sockaddr_in);
+
+        strcpy(temp_ifr.ifr_name, item->ifr_name);
+
+        if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr))
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG,
+                    "CAIPUpdateInterfaceInformation, SIOCGIFFLAGS Failed");
+            close(sck);
+            return CA_STATUS_FAILED;
+        }
+
+        if ((temp_ifr.ifr_flags & IFF_LOOPBACK)
+            || !(temp_ifr.ifr_flags & IFF_UP) || !(temp_ifr.ifr_flags & IFF_RUNNING))
+        {
+            continue;
+        }
+
+        if (AF_INET != ((struct sockaddr_in*) &item->ifr_addr)->sin_family)
+        {
+            continue;
+        }
+
+        //get the interface ip address
+        if (0 != getnameinfo(&item->ifr_addr, len, interfaceAddress, sizeof(interfaceAddress),
+                             NULL, 0, NI_NUMERICHOST))
+        {
+            OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get IPAddress, Error code: %s",
+                    strerror(errno));
+            close(sck);
+            return CA_STATUS_FAILED;
+        }
+
+        if (ioctl((int) sck, SIOCGIFNETMASK, item) < 0)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG,
+                    "CAIPUpdateInterfaceInformation, SIOCGIFNETMASK Failed");
+            close(sck);
+            return CA_STATUS_FAILED;
+        }
+
+        // get the interface subnet mask
+        if (0 != getnameinfo(&item->ifr_netmask, len, interfaceSubnetMask,
+                             sizeof(interfaceSubnetMask), NULL, 0, NI_NUMERICHOST))
+        {
+            OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get subnet mask, Error code: %s",
+                    strerror(errno));
+            close(sck);
+            return CA_STATUS_FAILED;
+        }
+
+        CANetInfo_t *netInfo = (CANetInfo_t *) OICCalloc(1, sizeof(CANetInfo_t));
+        if (!netInfo)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed");
+            close(sck);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        // set interface name
+        strncpy(netInfo->interfaceName, item->ifr_name, strlen(item->ifr_name));
+
+        // set local ip address
+        strncpy(netInfo->ipAddress, interfaceAddress, strlen(interfaceAddress));
+
+        // set subnet mask
+        strncpy(netInfo->subnetMask, interfaceSubnetMask, strlen(interfaceSubnetMask));
+
+        CAResult_t result = u_arraylist_add(*netInterfaceList, (void *) netInfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!Thread exiting.");
+            close(sck);
+            return CA_STATUS_FAILED;
+        }
+
+        OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "ipAddress : %s, interfaceName : %s, subnetmask : %s",
+                netInfo->ipAddress, netInfo->interfaceName, netInfo->subnetMask);
+        close(sck);
+        return CA_STATUS_OK;
+
+        break;
+    }
+
+    close(sck);
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_FAILED;
+}
+
+static bool CACheckIsAnyInterfaceDown(const u_arraylist_t *netInterfaceList,
+                                      const CANetInfo_t *info)
+{
+    VERIFY_NON_NULL_RET(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null", false);
+    VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false);
+
+    uint32_t list_length = u_arraylist_length(netInterfaceList);
+    for (uint32_t list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, list_index);
+        if (!netInfo)
+        {
+            continue;
+        }
+        if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0)
+        {
+            return false;
+        }
+    }
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down");
+    return true;
+}
+
+static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info)
+{
+    VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false);
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    for (uint32_t list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(
+                               g_networkMonitorContext->netInterfaceList, list_index);
+        if (!netInfo)
+        {
+            continue;
+        }
+        if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0)
+        {
+            if (strncmp(netInfo->ipAddress, info->ipAddress, strlen(info->ipAddress)) == 0)
+            {
+                ca_mutex_unlock(g_networkMonitorContextMutex);
+                return false;
+            }
+            else
+            {
+                OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network interface info changed");
+                if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index))
+                {
+                    if (g_networkMonitorContext->networkChangeCb)
+                    {
+                        g_networkMonitorContext->networkChangeCb(netInfo->ipAddress,
+                                                                 CA_INTERFACE_DOWN);
+                    }
+                    OICFree(netInfo);
+                }
+                else
+                {
+                    OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed");
+                }
+                break;
+            }
+        }
+    }
+
+    CANetInfo_t *newNetInfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t));
+    if (!newNetInfo)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "newNetInfo malloc failed");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    memcpy(newNetInfo, info, sizeof(*newNetInfo));
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found");
+
+    CAResult_t result = u_arraylist_add(g_networkMonitorContext->netInterfaceList,
+                                        (void *) newNetInfo);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!");
+        OICFree(newNetInfo);
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    /*Callback will be unset only at the time of termination. By that time, all the threads will be
+      stopped gracefully. This callback is properly protected*/
+    if (g_networkMonitorContext->networkChangeCb)
+    {
+        g_networkMonitorContext->networkChangeCb(newNetInfo->ipAddress, CA_INTERFACE_UP);
+    }
+
+    return true;
+}
+
+static CAResult_t CAInitializeNetworkMonitorMutexes()
+{
+    if (!g_networkMonitorContextMutex)
+    {
+        g_networkMonitorContextMutex = ca_mutex_new();
+        if (!g_networkMonitorContextMutex)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContextMutex Malloc  failed");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+
+    if (!g_stopNetworkMonitorMutex)
+    {
+        g_stopNetworkMonitorMutex = ca_mutex_new();
+        if (!g_stopNetworkMonitorMutex)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "g_stopNetworkMonitorMutex Malloc  failed");
+            ca_mutex_free(g_networkMonitorContextMutex);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+    return CA_STATUS_OK;
+}
+
+static void CADestroyNetworkMonitorMutexes()
+{
+    ca_mutex_free(g_networkMonitorContextMutex);
+    g_networkMonitorContextMutex = NULL;
+
+    ca_mutex_free(g_stopNetworkMonitorMutex);
+    g_stopNetworkMonitorMutex = NULL;
+}
+
+CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPInitializeNetworkMonitor IN");
+
+    VERIFY_NON_NULL(threadPool, IP_MONITOR_TAG, "threadPool is null");
+
+    CAResult_t ret = CAIPJniInit();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Initialization failed");
+        return ret;
+    }
+
+    ret = CAIPJniSetContext();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPJniSetContext failed");
+        return ret;
+    }
+
+    ret = CACreateIPJNIInterfaceObject(g_context);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "unable to create caipinterface instance");
+        return ret;
+    }
+
+    ret = CAInitializeNetworkMonitorMutexes();
+
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "CAInitializeNetworkMonitorMutexes failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+    g_networkMonitorContext = (CAIPNetworkMonitorContext *) OICCalloc(
+            1, sizeof(*g_networkMonitorContext));
+    if (!g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext Malloc  failed");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        CADestroyNetworkMonitorMutexes();
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    g_networkMonitorContext->threadPool = threadPool;
+
+    g_networkMonitorContext->netInterfaceList = u_arraylist_create();
+    if (!g_networkMonitorContext->netInterfaceList)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_create failed");
+        OICFree(g_networkMonitorContext);
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        CADestroyNetworkMonitorMutexes();
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    CAIPUpdateInterfaceInformation(&g_networkMonitorContext->netInterfaceList);
+
+    if (u_arraylist_length(g_networkMonitorContext->netInterfaceList))
+    {
+        g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_UP;
+    }
+    else
+    {
+        g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN;
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAIPTerminateNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    g_networkMonitorContext->threadPool = NULL;
+
+    CAClearNetInterfaceInfoList(g_networkMonitorContext->netInterfaceList);
+
+    g_networkMonitorContext->netInterfaceList = NULL;
+    g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN;
+    g_networkMonitorContext->networkChangeCb = NULL;
+    g_networkMonitorContext->threadPool = NULL;
+
+    OICFree(g_networkMonitorContext);
+    g_networkMonitorContext = NULL;
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    ca_mutex_lock(g_stopNetworkMonitorMutex);
+    g_stopNetworkMonitor = true;
+    ca_mutex_unlock(g_stopNetworkMonitorMutex);
+
+    CADestroyNetworkMonitorMutexes();
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+CAResult_t CAIPStartNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_stopNetworkMonitorMutex);
+    g_stopNetworkMonitor = false;
+    ca_mutex_unlock(g_stopNetworkMonitorMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext is null");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    ca_mutex_lock(g_stopNetworkMonitorMutex);
+    if (!g_stopNetworkMonitor)
+    {
+        g_stopNetworkMonitor = true;
+    }
+    else
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStopNetworkMonitor, already stopped!");
+    }
+    ca_mutex_unlock(g_stopNetworkMonitorMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "u_array_list is null");
+    VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, "g_networkMonitorContext is null");
+    VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG,
+                    "g_networkMonitorContextMutex is null");
+
+    // Get the interface and ipaddress information from cache
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList
+        || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList)))
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Network not enabled");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo list length [%d]",
+            list_length);
+    for (uint32_t list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get(
+                g_networkMonitorContext->netInterfaceList, list_index);
+        if (!info)
+        {
+            continue;
+        }
+        OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo ip [%s]",
+                  info->ipAddress);
+        CANetInfo_t *newNetinfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t));
+        if (!newNetinfo)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed!");
+            ca_mutex_unlock(g_networkMonitorContextMutex);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        memcpy(newNetinfo, info, sizeof(*info));
+
+        CAResult_t result = u_arraylist_add(*netInterfaceList, (void *) newNetinfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!");
+            ca_mutex_unlock(g_networkMonitorContextMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(subnetMask, IP_MONITOR_TAG, "subnet mask");
+    VERIFY_NON_NULL(ipAddress, IP_MONITOR_TAG, "ipAddress is null");
+    VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, "g_networkMonitorContext is null");
+    VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG,
+                    "g_networkMonitorContextMutex is null");
+
+    // Get the interface and ipaddress information from cache
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList
+        || (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList)))
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network not enabled");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "list lenght [%d]", list_length);
+    for (uint32_t list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get(
+                g_networkMonitorContext->netInterfaceList, list_index);
+        if (!info)
+        {
+            continue;
+        }
+
+        if (strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0)
+        {
+            OIC_LOG_V(DEBUG, IP_MONITOR_TAG,
+                      "CAIPGetInterfaceSubnetMask subnetmask is %s", info->subnetMask);
+            *subnetMask = OICStrdup(info->subnetMask);
+            break;
+        }
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+bool CAIPIsConnected()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+    if (!g_networkMonitorContextMutex || !g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected");
+        return false;
+    }
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList))
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return true;
+}
+
+void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+    if (!g_networkMonitorContextMutex || !g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPSetConnectionStateChangeCallback failed");
+        return;
+    }
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+    g_networkMonitorContext->networkChangeCb = callback;
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+void CAIPSendNetworkChangeCallback(CANetworkStatus_t currNetworkStatus)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+    ca_mutex_lock(g_stopNetworkMonitorMutex);
+
+    if (g_stopNetworkMonitor)
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "Stop Network Monitor Thread is called");
+        ca_mutex_unlock(g_stopNetworkMonitorMutex);
+        return;
+    }
+    ca_mutex_unlock(g_stopNetworkMonitorMutex);
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if(!g_networkMonitorContext)
+    {
+       OIC_LOG(DEBUG, IP_MONITOR_TAG, "g_networkChangeCb is NULL");
+       ca_mutex_unlock(g_networkMonitorContextMutex);
+       return;
+    }
+    if (!g_networkMonitorContext->networkChangeCb)
+    {    
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkChangeCb->networkChangeCb is NULL");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return;
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+  
+    u_arraylist_t *netInterfaceList = u_arraylist_create();
+
+    VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG,
+                         "memory allocation failed for netInterfaceList");
+
+    // if network status is changed
+    CAResult_t ret = CAIPUpdateInterfaceInformation(&netInterfaceList);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "could not update interface information");
+    }
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG,
+                "u_arraylist_create failed. Network Monitor thread stopped");
+        CAClearNetInterfaceInfoList(netInterfaceList);
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return;
+    }
+
+    uint32_t listLength = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    for (uint32_t listIndex = 0; listIndex < listLength;)
+    {
+        CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get(
+                g_networkMonitorContext->netInterfaceList, listIndex);
+        if (!info)
+        {
+            listIndex++;
+            continue;
+        }
+
+        bool ret = CACheckIsAnyInterfaceDown(netInterfaceList, info);
+        if (ret)
+        {
+            OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down");
+            if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, listIndex))
+            {
+                OIC_LOG(DEBUG, IP_MONITOR_TAG, "u_arraylist_remove success");
+                if (g_networkMonitorContext->networkChangeCb)
+                {
+                    g_networkMonitorContext->networkChangeCb(info->ipAddress, CA_INTERFACE_DOWN);
+                }
+                OICFree(info);
+                listLength--;
+            }
+            else
+            {
+                OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed");
+                break;
+            }
+        }
+        else
+        {
+            listIndex++;
+        }
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    listLength = u_arraylist_length(netInterfaceList);
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex);
+        if (!info)
+        {
+            continue;
+        }
+        bool ret = CACheckIsInterfaceInfoChanged(info);
+        if (ret)
+        {
+            OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACheckIsInterfaceInfoChanged true");
+        }
+    }
+
+    CAClearNetInterfaceInfoList(netInterfaceList);
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+JNIEXPORT void JNICALL Java_org_iotivity_ca_CaIpInterface_stateEnabled
+  (JNIEnv *env, jclass clazz)
+{
+    CANetworkStatus_t currNetworkStatus = CA_INTERFACE_UP;
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStateEnabled");
+
+    CAIPSendNetworkChangeCallback(currNetworkStatus);
+}
+
+JNIEXPORT void JNICALL Java_org_iotivity_ca_CaIpInterface_stateDisabled
+  (JNIEnv *env, jclass clazz)
+{
+    CANetworkStatus_t currNetworkStatus = CA_INTERFACE_DOWN;
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStateDisabled");
+
+    CAIPSendNetworkChangeCallback(currNetworkStatus);
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/android/org_iotivity_ca_CaIpInterface.h b/resource/csdk/connectivity/src/ip_adapter/android/org_iotivity_ca_CaIpInterface.h
new file mode 100644 (file)
index 0000000..1d66553
--- /dev/null
@@ -0,0 +1,29 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */\r
+#include <jni.h>\r
+/* Header for class org_iotivity_ca_CaIpInterface */\r
+\r
+#ifndef _Included_org_iotivity_ca_CaIpInterface\r
+#define _Included_org_iotivity_ca_CaIpInterface\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+/*\r
+ * Class:     org_iotivity_ca_CaIpInterface\r
+ * Method:    stateEnabled\r
+ * Signature: ()V\r
+ */\r
+JNIEXPORT void JNICALL Java_org_iotivity_ca_CaIpInterface_stateEnabled\r
+  (JNIEnv *, jclass);\r
+\r
+/*\r
+ * Class:     org_iotivity_ca_CaIpInterface\r
+ * Method:    stateDisabled\r
+ * Signature: ()V\r
+ */\r
+JNIEXPORT void JNICALL Java_org_iotivity_ca_CaIpInterface_stateDisabled\r
+  (JNIEnv *, jclass);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.cpp
new file mode 100644 (file)
index 0000000..534d3a4
--- /dev/null
@@ -0,0 +1,132 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include "caipadapterutils_eth.h"
+
+#include <Arduino.h>
+#include <Ethernet.h>
+#include <socket.h>
+#include <w5100.h>
+#include <EthernetUdp.h>
+#include <IPAddress.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "caadapterinterface.h"
+#include "caipadapter_singlethread.h"
+#include "caadapterutils.h"
+
+#define TAG "IPU"
+
+CAResult_t CAArduinoGetAvailableSocket(int *sockID)
+{
+    VERIFY_NON_NULL(sockID, TAG, "sockID");
+    uint8_t state;
+    //Is any socket available to work with ?
+    *sockID = 0;
+    for (int i = 1; i < MAX_SOCK_NUM; i++)
+    {
+        state = W5100.readSnSR(i);
+        if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT)
+        {
+            *sockID = i;
+            break;
+        }
+    }
+
+    if (*sockID == 0)
+    {
+        OIC_LOG(ERROR, TAG, "sockID 0");
+        return CA_SOCKET_OPERATION_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAArduinoInitUdpSocket(uint16_t *port, int *socketID)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(port, TAG, "port");
+    VERIFY_NON_NULL(socketID, TAG, "socketID");
+
+    CAResult_t ret = CAArduinoGetAvailableSocket(socketID);
+    if (ret != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "get sock fail");
+        return ret;
+    }
+
+    //Create a datagram socket on which to recv/send.
+    if (!socket(*socketID, SnMR::UDP, *port, 0))
+    {
+        OIC_LOG(ERROR, TAG, "sock fail");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "socketId:%d", *socketID);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress,
+                                           uint16_t mport,
+                                           uint16_t lport, int *socketID)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(mcastAddress, TAG, "address");
+    VERIFY_NON_NULL(socketID, TAG, "socket");
+
+    uint8_t mcastMacAddr[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00};
+    uint8_t ipAddr[4] = { 0 };
+    uint16_t parsedPort = 0;
+    if (CAParseIPv4AddressInternal(mcastAddress, ipAddr, sizeof(ipAddr),
+                                   &parsedPort) != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "parse fail");
+        return CA_STATUS_FAILED;
+    }
+
+    *socketID = 0;
+    CAResult_t ret = CAArduinoGetAvailableSocket(socketID);
+    if (ret != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "sock fail");
+        return ret;
+    }
+
+    //Calculate Multicast MAC address
+    mcastMacAddr[3] = ipAddr[1] & 0x7F;
+    mcastMacAddr[4] = ipAddr[2];
+    mcastMacAddr[5] = ipAddr[3];
+    W5100.writeSnDIPR(*socketID, (uint8_t *)ipAddr);
+    W5100.writeSnDHAR(*socketID, mcastMacAddr);
+    W5100.writeSnDPORT(*socketID, mport);
+
+    //Create a datagram socket on which to recv/send.
+    if (!socket(*socketID, SnMR::UDP, lport, SnMR::MULTI))
+    {
+        OIC_LOG(ERROR, TAG, "sock fail");
+        return CA_SOCKET_OPERATION_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "socketId:%d", *socketID);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.h b/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.h
new file mode 100644 (file)
index 0000000..c6b8213
--- /dev/null
@@ -0,0 +1,80 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+ * @file caethernetadapterutils.h
+ * @brief This file provides APIs ethernet client/server/network monitor modules
+ */
+
+#ifndef CA_ETHERNET_ADAPTER_UTILS_
+#define CA_ETHERNET_ADAPTER_UTILS_
+
+#include <Arduino.h>
+#include <Ethernet.h>
+#include <socket.h>
+#include <w5100.h>
+#include <EthernetUdp.h>
+#include <IPAddress.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "caadapterinterface.h"
+#include "caipadapter_singlethread.h"
+#include "caadapterutils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief Get available UDP socket
+ * @param   sockID      [OUT]   Available UDP socket ID
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAArduinoGetAvailableSocket(int *sockID);
+
+/**
+ * @brief Initialize Unicast UDP socket
+ * @param   port        [INOUT] Port to start the unicast server
+ * @param   socketID    [OUT    Unicast socket ID
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAArduinoInitUdpSocket(uint16_t *port, int *socketID);
+
+/**
+ * @brief Initialize Multicast UDP socket
+ * @param   mcastAddress    [IN]  Port to start the unicast server
+ * @param   mport           [IN]  Multicast port
+ * @param   lport           [IN]  Local port on which the server is started
+ * @param   socketID        [OUT] Multicast socket ID
+ * @return  #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress,
+                                           uint16_t mport, uint16_t lport,
+                                           int *socketID);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CA_ETHERNET_ADAPTER_UTILS_ */
+
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_eth.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_eth.cpp
new file mode 100644 (file)
index 0000000..95b9334
--- /dev/null
@@ -0,0 +1,138 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include "caipinterface_singlethread.h"
+
+#include <Arduino.h>
+#include <Ethernet.h>
+#include <socket.h>
+#include <w5100.h>
+#include <EthernetUdp.h>
+#include <IPAddress.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "caadapterinterface.h"
+#include "caipadapter_singlethread.h"
+#include "caipadapterutils_eth.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+#define TAG "IPC"
+
+static int g_sockID = 0;
+
+/**
+ * @var g_unicastPort
+ * @brief Unicast Port
+ */
+static uint16_t g_unicastPort = 0;
+
+void CAIPSetUnicastSocket(int socketID)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (0 < socketID)
+    {
+        g_sockID = socketID;
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "sock err");
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return;
+}
+
+void CAIPSetUnicastPort(uint16_t port)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_unicastPort = port;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return;
+}
+
+uint32_t CAIPSendData(const char *remoteAddress, uint16_t port,
+                      const char *buf, uint32_t bufLen, bool isMulticast)
+{
+    if (!isMulticast && 0 == g_unicastPort)
+    {
+        OIC_LOG(ERROR, TAG, "port 0");
+        return 0;
+    }
+
+    VERIFY_NON_NULL(buf, TAG, "buf");
+    VERIFY_NON_NULL(remoteAddress, TAG, "address");
+
+    int socketID = 0;
+    if (isMulticast)
+    {
+        if (CAArduinoInitMulticastUdpSocket(remoteAddress, port, g_unicastPort, &socketID)
+            != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "init mcast err");
+            return 0;
+        }
+        OIC_LOG_V(DEBUG, TAG, "MPORT:%d", port);
+        OIC_LOG_V(DEBUG, TAG, "LPORT:%d", g_unicastPort);
+        OIC_LOG_V(DEBUG, TAG, "SOCKET ID:%d", socketID);
+    }
+    else
+    {
+        if (0 == g_sockID)
+        {
+            if (CAArduinoInitUdpSocket(&port, &socketID) != CA_STATUS_OK)
+            {
+                OIC_LOG(ERROR, TAG, "init ucast err");
+                return 0;
+            }
+        }
+        else
+        {
+            socketID = g_sockID;
+        }
+    }
+
+    uint32_t ret;
+    uint8_t ipAddr[4] = { 0 };
+    uint16_t parsedPort = 0;
+    if (CAParseIPv4AddressInternal(remoteAddress, ipAddr, sizeof(ipAddr),
+                                   &parsedPort) != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "parse fail");
+        return 0;
+    }
+
+    if (bufLen > 65535) // Max value for uint16_t
+    {
+        // This will never happen as max buffer size we are dealing with is COAP_MAX_PDU_SIZE
+        OIC_LOG(ERROR, TAG, "Size exceeded");
+        return 0;
+    }
+
+    ret = sendto(socketID, (const uint8_t *)buf, (uint16_t)bufLen, ipAddr, port);
+    if (g_sockID != socketID)
+    {
+        close(socketID);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return ret;
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_wifi.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_wifi.cpp
new file mode 100644 (file)
index 0000000..38acd84
--- /dev/null
@@ -0,0 +1,102 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include "caipinterface_singlethread.h"
+
+#include <Arduino.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#include <SPI.h>
+#include <utility/server_drv.h>
+#include <utility/wifi_drv.h>
+#include <IPAddress.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "caadapterinterface.h"
+#include "caipadapter_singlethread.h"
+#include "caadapterutils.h"
+
+/// This is the max buffer size between Arduino and WiFi Shield
+#define ARDUINO_IP_BUFFERSIZE (90)
+#define TAG "IPC"
+
+static WiFiUDP Udp;
+
+void CAIPSetUnicastSocket(int socketID)
+{
+
+}
+
+void CAIPSetUnicastPort(uint16_t port)
+{
+
+}
+
+uint32_t CAIPSendData(const char *remoteAddress, uint16_t port,
+                      const char *data, uint32_t dataLength, bool isMulticast)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_RET(data, TAG, "data", 0);
+    VERIFY_NON_NULL_RET(remoteAddress, TAG, "address", 0);
+
+    OIC_LOG_V(DEBUG, TAG, "remoteip: %s", remoteAddress);
+    OIC_LOG_V(DEBUG, TAG, "port: %d", port);
+
+    uint8_t ip[4] = {0};
+    uint16_t parsedPort = 0;
+    CAResult_t res = CAParseIPv4AddressInternal(remoteAddress, ip, sizeof(ip),
+                                                &parsedPort);
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Remote adrs parse fail %d", res);
+        return 0;
+    }
+
+    IPAddress remoteIp(ip);
+    Udp.beginPacket(remoteIp, (uint16_t)port);
+
+    uint32_t bytesWritten = 0;
+    while(bytesWritten < dataLength)
+    {
+        // get remaining bytes
+        size_t writeCount = dataLength - bytesWritten;
+        // write upto max ARDUINO_WIFI_BUFFERSIZE bytes
+        writeCount = Udp.write((uint8_t *)data + bytesWritten,
+                                (writeCount > ARDUINO_IP_BUFFERSIZE ?
+                                 ARDUINO_IP_BUFFERSIZE:writeCount));
+        if(writeCount == 0)
+        {
+            // write failed
+            OIC_LOG_V(ERROR, TAG, "Failed after %u", bytesWritten);
+            break;
+        }
+        bytesWritten += writeCount;
+    }
+
+    if (Udp.endPacket() == 0)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to send");
+        return 0;
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return bytesWritten;
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor.cpp
new file mode 100644 (file)
index 0000000..a64142a
--- /dev/null
@@ -0,0 +1,63 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+/**
+ * @file caipnwmonitor.cpp
+ * @brief This file is to keep design in sync with other platforms.  Right now there is no
+ *        api for network monitioring in arduino.
+ */
+
+#include "caipinterface_singlethread.h"
+
+#define TAG "IPNW"
+
+CAResult_t CAIPInitializeNetworkMonitor(void)
+{
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartNetworkMonitor(void)
+{
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPGetInterfaceInfo(char **ipAddress, char **interfaceName)
+{
+    return CA_STATUS_OK;
+}
+
+bool CAIPIsConnected(void)
+{
+    return true;
+}
+
+void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
+{
+    return;
+}
+
+CAResult_t CAIPStopNetworkMonitor(void)
+{
+    return CA_STATUS_OK;
+}
+
+void CAIPTerminateNetworkMonitor(void)
+{
+    return;
+}
diff --git a/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp
new file mode 100644 (file)
index 0000000..0b7f3df
--- /dev/null
@@ -0,0 +1,265 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "caipinterface_singlethread.h"
+
+#include <Arduino.h>
+#include <Ethernet.h>
+#include <socket.h>
+#include <w5100.h>
+#include <EthernetUdp.h>
+#include <IPAddress.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "cainterface.h"
+#include "caadapterinterface.h"
+#include "caipadapter_singlethread.h"
+#include "caipadapterutils_eth.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+#define TAG "IPS"
+
+// Length of the IP address decimal notation string
+#define IPNAMESIZE (16)
+
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
+                                        const bool forceStart, int32_t *serverFD);
+static CAResult_t CAArduinoRecvData(int32_t sockFd);
+static CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen);
+static void CAArduinoCheckData();
+static void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port,
+                              const void *data, const uint32_t dataLength);
+
+static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
+static int g_unicastSocket = 0;
+static int g_multicastSocket = 0;
+
+/**
+ * @var g_unicastPort
+ * @brief Unicast Port
+ */
+static uint16_t g_unicastPort = 0;
+
+CAResult_t CAIPInitializeServer(void)
+{
+    return CA_STATUS_OK;
+}
+
+void CAIPTerminateServer(void)
+{
+    return;
+}
+
+CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port,
+                                          int *serverID)
+{
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
+                                        const bool forceStart, int *serverFD)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(port, TAG, "port");
+
+    uint8_t rawIPAddr[4];
+    char address[16];
+    W5100.getIPAddress(rawIPAddr);
+    sprintf(address, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]);
+    OIC_LOG_V(DEBUG, TAG, "address:%s", address);
+
+    if (CAArduinoInitUdpSocket(port, serverFD) != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    g_unicastPort = *port;
+    g_unicastSocket = *serverFD;
+    OIC_LOG_V(DEBUG, TAG, "g_unicastPort: %d", g_unicastPort);
+    OIC_LOG_V(DEBUG, TAG, "g_unicastSocket: %d", g_unicastSocket);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
+                                    uint16_t multicastPort, int *serverFD)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (CAArduinoInitMulticastUdpSocket(multicastAddress, multicastPort, multicastPort,
+                                        serverFD) != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    g_multicastSocket = *serverFD;
+    OIC_LOG_V(DEBUG, TAG, "gMulticastPort: %d", multicastPort);
+    OIC_LOG_V(DEBUG, TAG, "g_multicastSocket: %d", g_multicastSocket);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopUnicastServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    close(g_unicastSocket);
+    g_unicastSocket = 0;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopMulticastServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    close(g_multicastSocket);
+    g_multicastSocket = 0;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port,
+                              const void *data, const uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (g_packetReceivedCallback)
+    {
+        g_packetReceivedCallback(ipAddress, port, data, dataLength);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAArduinoCheckData()
+{
+    if (g_unicastSocket)
+    {
+        if (CAArduinoRecvData(g_unicastSocket) != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "rcv fail");
+            CAIPStopUnicastServer();
+        }
+    }
+
+    if (g_multicastSocket)
+    {
+        if (CAArduinoRecvData(g_multicastSocket) != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, TAG, "rcv fail");
+            CAIPStopMulticastServer();
+        }
+    }
+}
+
+/** Retrieve any available data from UDP socket and call callback.
+ *  This is a non-blocking call.
+ */
+CAResult_t CAArduinoRecvData(int32_t sockFd)
+{
+    /**Bug : When there are multiple UDP packets in Wiznet buffer, W5100.getRXReceivedSize
+     * will not return correct length of the first packet.
+     * Fix : Use the patch provided for arduino/libraries/Ethernet/utility/socket.cpp
+     */
+
+    void *data = NULL;
+    uint8_t senderAddr[4] = { 0 };
+    char addr[IPNAMESIZE] = {0};
+    uint16_t senderPort = 0;
+
+    uint16_t recvLen = W5100.getRXReceivedSize(sockFd);
+    if (recvLen == 0)
+    {
+        // No data available on socket
+        return CA_STATUS_OK;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "rcvd %d", recvLen);
+    recvLen = recvLen > COAP_MAX_PDU_SIZE ? COAP_MAX_PDU_SIZE:recvLen;
+
+    data = OICCalloc(recvLen + 1, 1);
+    if (NULL == data)
+    {
+        OIC_LOG(DEBUG, TAG, "Out of memory!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    // Read available data.
+    int32_t ret = recvfrom(sockFd, (uint8_t *)data, recvLen + 1, senderAddr, &senderPort);
+    if (ret < 0)
+    {
+        OIC_LOG(ERROR, TAG, "rcv fail");
+        OICFree(data);
+        return CA_STATUS_FAILED;
+    }
+    else if (ret > 0)
+    {
+        OIC_LOG(DEBUG, TAG, "data recvd");
+        snprintf(addr, sizeof(addr), "%d.%d.%d.%d", senderAddr[0], senderAddr[1], senderAddr[2],
+                 senderAddr[3]);
+        CAPacketReceivedCallback(addr, senderPort, data, ret);
+    }
+
+    OICFree(data);
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_packetReceivedCallback = callback;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
+{
+    // TODO
+}
+
+void CAIPPullData()
+{
+    CAArduinoCheckData();
+}
+
+/// Retrieves the IP address assigned to Arduino Ethernet shield
+CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(address, TAG, "address");
+
+    //TODO : Fix this for scenarios when this API is invoked when device is not connected
+    uint8_t rawIPAddr[4];
+    if (addrLen < IPNAMESIZE)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid addrLen");
+        return CA_STATUS_FAILED;
+    }
+
+    W5100.getIPAddress(rawIPAddr);
+    snprintf(address, sizeof(address), "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2],
+             rawIPAddr[3]);
+
+    OIC_LOG_V(DEBUG, TAG, "address:%s", address);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp
new file mode 100644 (file)
index 0000000..97dd582
--- /dev/null
@@ -0,0 +1,230 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "caipinterface_singlethread.h"
+
+#include <Arduino.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#include <SPI.h>
+#include <utility/server_drv.h>
+#include <utility/wifi_drv.h>
+#include <IPAddress.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "cainterface.h"
+#include "caadapterinterface.h"
+#include "caipadapter_singlethread.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+#define TAG "IPS"
+
+// Length of the IP address decimal notation string
+#define IPNAMESIZE (16)
+
+// Start offsets based on end of received data buffer
+#define IP_RECBUF_IPADDR_OFFSET  (6)
+#define IP_RECBUF_PORT_OFFSET    (2)
+
+#define IP_RECBUF_IPADDR_SIZE    (IP_RECBUF_IPADDR_OFFSET - IP_RECBUF_PORT_OFFSET)
+#define IP_RECBUF_PORT_SIZE      (IP_RECBUF_PORT_OFFSET - 0)
+#define IP_RECBUF_FOOTER_SIZE    (IP_RECBUF_IPADDR_SIZE + IP_RECBUF_PORT_SIZE)
+
+static CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen);
+static void CAArduinoCheckData();
+static void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port,
+                                     const void *data, const uint32_t dataLength);
+
+static CAIPPacketReceivedCallback gPacketReceivedCallback = NULL;
+static int32_t gUnicastSocket = 0;
+static bool gServerRunning = false;
+static WiFiUDP Udp;
+
+CAResult_t CAIPInitializeServer(void)
+{
+    /**
+     * This API is to keep design in sync with other platforms.
+     * The required implementation is done in Start() api's.
+     */
+    return CA_STATUS_OK;
+}
+
+void CAIPTerminateServer(void)
+{
+    /**
+     * This API is to keep design in sync with other platforms.
+     * The required implementation is done in Stop() api's.
+     */
+}
+
+CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port, int *serverID)
+{
+    /*
+     * This API is to keep design in sync with other platforms.
+     * Will be implemented as and when CA layer wants this info.
+     */
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
+                                  bool forceStart, int *serverFD)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(port, TAG, "port");
+
+    if (gServerRunning)
+    {
+        // already running
+        OIC_LOG(DEBUG, TAG, "Error");
+        return CA_STATUS_FAILED;
+    }
+
+    if (WiFi.status() != WL_CONNECTED)
+    {
+        OIC_LOG(ERROR, TAG, "ERROR:No WIFI");
+        return CA_STATUS_FAILED;
+    }
+
+    char localIpAddress[CA_IPADDR_SIZE];
+    int32_t localIpAddressLen = sizeof(localIpAddress);
+    CAArduinoGetInterfaceAddress(localIpAddress, localIpAddressLen);
+    OIC_LOG_V(DEBUG, TAG, "address: %s", localIpAddress);
+    OIC_LOG_V(DEBUG, TAG, "port: %d", *port);
+
+    Udp.begin((uint16_t ) *port);
+    gServerRunning = true;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
+                                      uint16_t multicastPort, int *serverFD)
+{
+    // wifi shield does not support multicast
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_NOT_SUPPORTED;
+}
+
+CAResult_t CAIPStopUnicastServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    Udp.stop();
+
+    gServerRunning = false;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopMulticastServer()
+{
+    return CAIPStopUnicastServer();
+}
+
+void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port,
+                              const void *data, const uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (gPacketReceivedCallback)
+    {
+        gPacketReceivedCallback(ipAddress, port, data, dataLength);
+        OIC_LOG(DEBUG, TAG, "Notified network packet");
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAArduinoCheckData()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    char addr[IPNAMESIZE] = {0};
+    uint16_t senderPort = 0;
+    int16_t packetSize = Udp.parsePacket();
+    OIC_LOG_V(DEBUG, TAG, "Rcv packet of size:%d ", packetSize);
+    if (packetSize)
+    {
+        packetSize = packetSize > COAP_MAX_PDU_SIZE ? COAP_MAX_PDU_SIZE:packetSize;
+        char *data = (char *)OICMalloc(packetSize + 1);
+        if (NULL == data)
+        {
+            return;
+        }
+        IPAddress remoteIp = Udp.remoteIP();
+        senderPort = Udp.remotePort();
+        sprintf(addr, "%d.%d.%d.%d", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3]);
+        OIC_LOG_V(DEBUG, TAG, "remoteip: %s, port: %d", addr, senderPort);
+        // read the packet into packetBufffer
+        int32_t dataLen = Udp.read(data, COAP_MAX_PDU_SIZE);
+        if (dataLen > 0)
+        {
+            data[dataLen] = 0;
+        }
+        CAPacketReceivedCallback(addr, senderPort, data, dataLen);
+        OICFree(data);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    gPacketReceivedCallback = callback;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
+{
+    // TODO
+}
+
+void CAIPPullData()
+{
+    CAArduinoCheckData();
+}
+
+/// Retrieves the IP address assigned to Arduino WiFi shield
+CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (WiFi.status() != WL_CONNECTED)
+    {
+        OIC_LOG(DEBUG, TAG, "No WIFI");
+        return CA_STATUS_FAILED;
+    }
+
+    VERIFY_NON_NULL(address, TAG, "Invalid address");
+    if (addrLen < IPNAMESIZE)
+    {
+        OIC_LOG_V(ERROR, TAG, "AddrLen MUST be atleast %d", IPNAMESIZE);
+        return CA_STATUS_FAILED;
+    }
+
+    IPAddress ip = WiFi.localIP();
+    sprintf((char *)address, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+
+    OIC_LOG_V(DEBUG, TAG, "Wifi shield address is: %s", address);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/caipadapter.c b/resource/csdk/connectivity/src/ip_adapter/caipadapter.c
new file mode 100644 (file)
index 0000000..bd9af23
--- /dev/null
@@ -0,0 +1,822 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "caipadapter.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "caipinterface.h"
+#include "caqueueingthread.h"
+#include "caadapterutils.h"
+#ifdef __WITH_DTLS__
+#include "caadapternetdtls.h"
+#endif
+#include "camutex.h"
+#include "uarraylist.h"
+#include "logger.h"
+#include "oic_malloc.h"
+
+/**
+ * @def IP_ADAPTER_TAG
+ * @brief Logging tag for module name
+ */
+#define IP_ADAPTER_TAG "IP_ADAP"
+
+/**
+ * @def CA_PORT
+ * @brief Port to listen for incoming data
+ */
+#define CA_PORT   6298
+
+/**
+ * @def CA_SECURE_PORT
+ * @brief Secured (unicast) port number as defined in COAP Specification, RFC-7252.
+ */
+#define CA_SECURE_PORT   5684
+
+/**
+ * @def CA_MCAST_PORT
+ * @brief Multicast port number as defined in COAP Specification, RFC-7252.
+ */
+#define CA_MCAST_PORT   5683
+
+/**
+ * @def CA_MULTICAST_IP
+ * @brief Multicast IP Address as defined in COAP Specification, RFC-7252.
+ */
+#define CA_MULTICAST_IP "224.0.1.187"
+
+/**
+ * @var CAIPData
+ * @brief Holds inter thread ip data information.
+ */
+typedef struct
+{
+    CARemoteEndpoint_t *remoteEndpoint;
+    void *data;
+    uint32_t dataLen;
+} CAIPData;
+
+/**
+ * @var g_networkPacketCallback
+ * @brief Network Packet Received Callback to CA
+ */
+static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
+
+/**
+ * @var g_networkChangeCallback
+ * @brief Network Changed Callback to CA
+ */
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
+
+/**
+ * @var g_sendQueueHandle
+ * @brief Queue handle for Send Data
+ */
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
+
+/**
+ * @var g_threadPool
+ * @brief ThreadPool for storing ca_thread_pool_t handle passed from CA
+ */
+static ca_thread_pool_t g_threadPool = NULL;
+
+static CAResult_t CAIPInitializeQueueHandles();
+
+static void CAIPDeinitializeQueueHandles();
+
+static void CAIPNotifyNetworkChange(const char *address, uint16_t port,
+                                          CANetworkStatus_t status);
+
+static void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status);
+
+static void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, const void *data,
+                                       uint32_t dataLength, bool isSecured);
+#ifdef __WITH_DTLS__
+static uint32_t CAIPPacketSendCB(const char *ipAddress, uint16_t port,
+                                       const void *data, uint32_t dataLength);
+#endif
+
+static CAResult_t CAIPStopServers();
+
+static void CAIPSendDataThread(void *threadData);
+
+static CAIPData *CACreateIPData(const CARemoteEndpoint_t *remoteEndpoint,
+                                            const void *data, uint32_t dataLength);
+void CAFreeIPData(CAIPData *ipData);
+
+static void CADataDestroyer(void *data, uint32_t size);
+
+CAResult_t CAIPInitializeQueueHandles()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    // Check if the message queue is already initialized
+    if (g_sendQueueHandle)
+    {
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG, "send queue handle is already initialized!");
+        return CA_STATUS_OK;
+    }
+
+    // Create send message queue
+    g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
+    if (!g_sendQueueHandle)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory allocation failed!");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_threadPool,
+                                                   CAIPSendDataThread, CADataDestroyer))
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Initialize send queue thread");
+        OICFree(g_sendQueueHandle);
+        g_sendQueueHandle = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAIPDeinitializeQueueHandles()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    CAQueueingThreadDestroy(g_sendQueueHandle);
+    OICFree(g_sendQueueHandle);
+    g_sendQueueHandle = NULL;
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+void CAIPNotifyNetworkChange(const char *address, uint16_t port, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(address, IP_ADAPTER_TAG, "address is NULL");
+
+    CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address);
+    if (!localEndpoint)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "localEndpoint creation failed!");
+        return;
+    }
+
+    localEndpoint->addressInfo.IP.port = port;
+
+    if (g_networkChangeCallback)
+    {
+        g_networkChangeCallback(localEndpoint, status);
+    }
+    else
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "g_networkChangeCallback is NULL");
+    }
+
+    CAAdapterFreeLocalEndpoint(localEndpoint);
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL");
+
+    if (CA_INTERFACE_UP == status)
+    {
+        uint16_t port = CA_PORT;
+        CAResult_t ret = CAIPStartUnicastServer(ipAddress, &port, false, false);
+        if (CA_STATUS_OK == ret)
+        {
+            OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Unicast server started on %d port", port);
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to start Unicast server port[%d]", ret);
+        }
+
+#ifdef __WITH_DTLS__
+        port = CA_SECURE_PORT;
+        ret = CAIPStartUnicastServer(ipAddress, &port, false, true);
+        if (CA_STATUS_OK == ret)
+        {
+            OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Secure Unicast server started on %d", port);
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to start secure Unicast server [%d]",
+                      ret);
+        }
+#endif
+        ret = CAIPStartMulticastServer(ipAddress, CA_MULTICAST_IP, CA_MCAST_PORT);
+        if (CA_STATUS_OK == ret)
+        {
+            OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Multicast server started on port[%d]",
+                      CA_MCAST_PORT);
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to start Multicast server port[%d]",
+                      ret);
+        }
+
+        // Notify network change to CA
+        CAIPNotifyNetworkChange(ipAddress, port, status);
+    }
+    else
+    {
+        CAIPNotifyNetworkChange(ipAddress, 0, status);
+
+        // Stop Unicast, Secured unicast and Multicast servers
+        CAIPStopServer(ipAddress);
+    }
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+#ifdef __WITH_DTLS__
+uint32_t CAIPPacketSendCB(const char *ipAddress, uint16_t port,
+        const void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL", 0);
+
+    VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "data is NULL", 0);
+
+    uint32_t sentLength = CAIPSendData(ipAddress, port, data, dataLength, false, true);
+
+    OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Successfully sent %d of encrypted data!", sentLength);
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+
+    return sentLength;
+}
+#endif
+
+void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, const void *data,
+                                uint32_t dataLength, bool isSecured)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_VOID(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL");
+
+    VERIFY_NON_NULL_VOID(data, IP_ADAPTER_TAG, "data is NULL");
+
+    OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Address: %s, port:%d", ipAddress, port);
+
+    // CA is freeing this memory
+    CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_IPV4, ipAddress, NULL );
+    if (!endPoint)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "EndPoint creation failed!");
+        return;
+    }
+    endPoint->addressInfo.IP.port = port;
+    endPoint->isSecured = isSecured;
+
+    void *buf = OICCalloc(dataLength + 1, sizeof(char));
+    if (!buf)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory Allocation failed!");
+        CAAdapterFreeRemoteEndpoint(endPoint);
+        return;
+    }
+    memcpy(buf, data, dataLength);
+    if (g_networkPacketCallback)
+    {
+        g_networkPacketCallback(endPoint, buf, dataLength);
+    }
+    else
+    {
+        OICFree(buf);
+        CAAdapterFreeRemoteEndpoint(endPoint);
+    }
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
+                                CANetworkPacketReceivedCallback networkPacketCallback,
+                                CANetworkChangeCallback netCallback, ca_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+    VERIFY_NON_NULL(registerCallback, IP_ADAPTER_TAG, "registerCallback");
+    VERIFY_NON_NULL(networkPacketCallback, IP_ADAPTER_TAG, "networkPacketCallback");
+    VERIFY_NON_NULL(netCallback, IP_ADAPTER_TAG, "netCallback");
+    VERIFY_NON_NULL(handle, IP_ADAPTER_TAG, "thread pool handle");
+
+    g_threadPool = handle;
+    g_networkChangeCallback = netCallback;
+    g_networkPacketCallback = networkPacketCallback;
+
+    CAResult_t ret = CAIPInitializeNetworkMonitor(g_threadPool);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to initialize n/w monitor![%d]", ret);
+        return ret;
+    }
+    CAIPSetConnectionStateChangeCallback(CAIPConnectionStateCB);
+
+    ret = CAIPInitializeServer(g_threadPool);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to initialize server![%d]", ret);
+        CATerminateIP();
+        return ret;
+    }
+
+    CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB);
+#ifdef __WITH_DTLS__
+    CAAdapterNetDtlsInit();
+
+    CADTLSSetAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, DTLS_IP);
+#endif
+
+    CAConnectivityHandler_t ipHandler;
+    ipHandler.startAdapter = CAStartIP;
+    ipHandler.startListenServer = CAStartIPListeningServer;
+    ipHandler.startDiscoveryServer = CAStartIPDiscoveryServer;
+    ipHandler.sendData = CASendIPUnicastData;
+    ipHandler.sendDataToAll = CASendIPMulticastData;
+    ipHandler.GetnetInfo = CAGetIPInterfaceInformation;
+    ipHandler.readData = CAReadIPData;
+    ipHandler.stopAdapter = CAStopIP;
+    ipHandler.terminate = CATerminateIP;
+    registerCallback(ipHandler, CA_IPV4);
+
+    if (CA_STATUS_OK != CAIPInitializeQueueHandles())
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Initialize Queue Handle");
+        CATerminateIP();
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(INFO, IP_ADAPTER_TAG, "OUT IntializeIP is Success");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartIP()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    // Start monitoring IP network
+    CAResult_t ret = CAIPStartNetworkMonitor();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Start n/w monitor");
+        return ret;
+    }
+
+    // Start send queue thread
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Start Send Data Thread");
+        return CA_STATUS_FAILED;
+    }
+
+    bool retVal = CAIPIsConnected();
+    if (false == retVal)
+    {
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IP is not Connected");
+        return CA_STATUS_OK;
+    }
+
+    u_arraylist_t *netInterfaceList = u_arraylist_create();
+
+    VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL");
+
+    ret = CAIPGetInterfaceInfo(&netInterfaceList);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to get IP interface info [%d]", ret);
+        CAClearNetInterfaceInfoList(netInterfaceList);
+        return ret;
+    }
+
+    uint32_t listIndex = 0;
+    uint32_t listLength = u_arraylist_length(netInterfaceList);
+    for (listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex);
+        if (!netInfo)
+        {
+            continue;
+        }
+        uint16_t unicastPort = CA_PORT;
+        ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, false, false);
+        if (CA_STATUS_OK == ret)
+        {
+            OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Unicast server started on %d port",
+                      unicastPort);
+        }
+
+#ifdef __WITH_DTLS__
+        unicastPort = CA_SECURE_PORT;
+        ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, false, true);
+
+        if (CA_STATUS_OK == ret)
+        {
+            OIC_LOG_V(DEBUG, IP_ADAPTER_TAG,
+                      "Secure Unicast server started on %d port", unicastPort);
+        }
+#endif
+    }
+    CAClearNetInterfaceInfoList(netInterfaceList);
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartIPListeningServer()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    bool retVal = CAIPIsConnected();
+    if (false == retVal)
+    {
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG,
+                  "IP not Connected. Couldn't start multicast server");
+        return CA_STATUS_OK;
+    }
+
+    u_arraylist_t *netInterfaceList = u_arraylist_create();
+
+    VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL");
+
+    CAResult_t ret = CAIPGetInterfaceInfo(&netInterfaceList);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to get IP interface info [%d]", ret);
+        CAClearNetInterfaceInfoList(netInterfaceList);
+        return ret;
+    }
+
+    uint32_t listIndex = 0;
+    uint32_t listLength = u_arraylist_length(netInterfaceList);
+    for (listIndex = 0; listIndex < listLength; listIndex++)
+    {
+
+        CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex);
+        if (!netInfo)
+        {
+            continue;
+        }
+
+        OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Ip address for multicast interface %s",
+                  netInfo->ipAddress);
+        ret = CAIPStartMulticastServer(netInfo->ipAddress, CA_MULTICAST_IP, CA_MCAST_PORT);
+        if (CA_STATUS_OK == ret)
+        {
+            OIC_LOG(INFO, IP_ADAPTER_TAG, "Multicast Server is Started Successfully");
+        }
+    }
+
+    CAClearNetInterfaceInfoList(netInterfaceList);
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartIPDiscoveryServer()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+    return CAStartIPListeningServer();
+}
+
+int32_t CASendIPUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                                  uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteEndpoint, IP_ADAPTER_TAG, "remoteEndpoint", -1);
+    VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "data", -1);
+    VERIFY_NON_NULL_RET(g_sendQueueHandle, IP_ADAPTER_TAG, "sendQueueHandle", -1);
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Invalid Data Length");
+        return -1;
+    }
+
+    // Create IPData to add to queue
+    CAIPData *ipData = CACreateIPData(remoteEndpoint, data, dataLength);
+    if (!ipData)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to create ipData!");
+        return -1;
+    }
+    else
+    {
+        // Add message to send queue
+        CAQueueingThreadAddData(g_sendQueueHandle, ipData, sizeof(CAIPData));
+
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+        return dataLength;
+    }
+}
+
+int32_t CASendIPMulticastData(const void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "data", -1);
+    VERIFY_NON_NULL_RET(g_sendQueueHandle, IP_ADAPTER_TAG, "sendQueueHandle", -1);
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Invalid Data Length");
+        return -1;
+    }
+
+    // Create IPData to add to queue
+    CAIPData *ipData = CACreateIPData(NULL, data, dataLength);
+    if (!ipData)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to create ipData!");
+        return -1;
+    }
+    else
+    {
+        // Add message to send queue
+        CAQueueingThreadAddData(g_sendQueueHandle, ipData, sizeof(CAIPData));
+
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+        return dataLength;
+    }
+}
+
+CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(info, IP_ADAPTER_TAG, "info is NULL");
+    VERIFY_NON_NULL(size, IP_ADAPTER_TAG, "size is NULL");
+
+    bool retVal = CAIPIsConnected();
+    if (false == retVal)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG,
+                "Failed to get interface address, IP not Connected");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    u_arraylist_t *netInterfaceList = u_arraylist_create();
+
+    VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL");
+
+    CAResult_t ret = CAIPGetInterfaceInfo(&netInterfaceList);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "CAIPGetInterfaceInfo failed:%d", ret);
+        CAClearNetInterfaceInfoList(netInterfaceList);
+        return ret;
+    }
+
+    uint32_t listLength = u_arraylist_length(netInterfaceList);
+    uint32_t netInfoSize = listLength;
+
+#ifdef __WITH_DTLS__
+    if (listLength)
+    {
+        netInfoSize = listLength * 2;
+    }
+#endif
+
+    CALocalConnectivity_t *conInfo = (CALocalConnectivity_t *) OICCalloc(
+                                      netInfoSize, sizeof(CALocalConnectivity_t));
+    if (!conInfo)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Malloc Failed");
+        CAClearNetInterfaceInfoList(netInterfaceList);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    uint32_t listIndex = 0;
+    uint32_t count = 0;
+    for (listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex);
+        if (!netInfo)
+        {
+            continue;
+        }
+
+        conInfo[count].type = CA_IPV4;
+        conInfo[count].isSecured = false;
+        conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, false);
+        strncpy(conInfo[count].addressInfo.IP.ipAddress, netInfo->ipAddress,
+                strlen(netInfo->ipAddress));
+
+#ifdef __WITH_DTLS__
+        // copy secure unicast server information
+        {
+            count ++;
+            conInfo[count].type = CA_IPV4;
+            conInfo[count].isSecured = true;
+            conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, true);
+            strncpy(conInfo[count].addressInfo.IP.ipAddress, netInfo->ipAddress,
+                    strlen(netInfo->ipAddress));
+        }
+#endif
+        count ++;
+    }
+    *size = count;
+    *info = conInfo;
+    CAClearNetInterfaceInfoList(netInterfaceList);
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAReadIPData()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopServers()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    // Stop all unicast and multicast servers.
+    if (CA_STATUS_OK == CAIPStopAllServers())
+    {
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG, "CAIPStopAllServers success");
+    }
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopIP()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+#ifdef __WITH_DTLS__
+    CAAdapterNetDtlsDeInit();
+#endif
+
+    // Stop IP network monitor
+    CAIPStopNetworkMonitor();
+
+    // Stop send queue thread
+    if (g_sendQueueHandle)
+    {
+        CAQueueingThreadStop(g_sendQueueHandle);
+    }
+
+    // Stop Unicast, Secured unicast and Multicast servers running
+    CAIPStopServers();
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateIP()
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    // Stop IP adapter
+    CAStopIP();
+
+#ifdef __WITH_DTLS__
+    CADTLSSetAdapterCallbacks(NULL, NULL, DTLS_IP);
+#endif
+
+    CAIPSetPacketReceiveCallback(NULL);
+
+    // Terminate IP server
+    CAIPTerminateServer();
+
+    // Terminate network monitor
+    CAIPSetConnectionStateChangeCallback(NULL);
+    CAIPTerminateNetworkMonitor();
+
+    // Terminate message queue handler
+    CAIPDeinitializeQueueHandles();
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+void CAIPSendDataThread(void *threadData)
+{
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
+
+    CAIPData *ipData = (CAIPData *) threadData;
+    if (!ipData)
+    {
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Invalid ip data!");
+        return;
+    }
+
+    //If remoteEndpoint is NULL, its Multicast, else its Unicast.
+    if (ipData->remoteEndpoint)
+    {
+        //Processing for sending unicast
+        char *address = ipData->remoteEndpoint->addressInfo.IP.ipAddress;
+        uint16_t port = ipData->remoteEndpoint->addressInfo.IP.port;
+
+#ifdef __WITH_DTLS__
+        if (!ipData->remoteEndpoint->isSecured)
+        {
+            OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Unicast Data is called");
+            CAIPSendData(address, port, ipData->data, ipData->dataLen, false,
+                               ipData->remoteEndpoint->isSecured);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
+            uint8_t cacheFlag = 0;
+            CAResult_t result = CAAdapterNetDtlsEncrypt(address, port, ipData->data,
+                                                        ipData->dataLen, &cacheFlag,
+                                                        DTLS_IP);
+
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG(ERROR, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt failed!");
+            }
+            OIC_LOG_V(DEBUG, IP_ADAPTER_TAG,
+                      "CAAdapterNetDtlsEncrypt returned with cache[%d]", cacheFlag);
+        }
+#else
+        CAIPSendData(address, port, ipData->data, ipData->dataLen, false,
+                           ipData->remoteEndpoint->isSecured);
+#endif
+    }
+    else
+    {
+        //Processing for sending multicast
+        OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Multicast Data is called");
+        CAIPSendData(CA_MULTICAST_IP, CA_MCAST_PORT, ipData->data,
+                           ipData->dataLen, true, false);
+    }
+
+    OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
+}
+
+CAIPData *CACreateIPData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                                     uint32_t dataLength)
+{
+    VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "IPData is NULL", NULL);
+
+    CAIPData *ipData = (CAIPData *) OICMalloc(sizeof(CAIPData));
+    if (!ipData)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory allocation failed!");
+        return NULL;
+    }
+
+    ipData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
+    ipData->data = (void *) OICMalloc(dataLength);
+    if (!ipData->data)
+    {
+        OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory allocation failed!");
+        CAFreeIPData(ipData);
+        return NULL;
+    }
+
+    memcpy(ipData->data, data, dataLength);
+    ipData->dataLen = dataLength;
+
+    return ipData;
+}
+
+void CAFreeIPData(CAIPData *ipData)
+{
+    VERIFY_NON_NULL_VOID(ipData, IP_ADAPTER_TAG, "ipData is NULL");
+
+    CAAdapterFreeRemoteEndpoint(ipData->remoteEndpoint);
+    OICFree(ipData->data);
+    OICFree(ipData);
+}
+
+void CADataDestroyer(void *data, uint32_t size)
+{
+    CAIPData *etdata = (CAIPData *) data;
+
+    CAFreeIPData(etdata);
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/caipadapter_singlethread.c b/resource/csdk/connectivity/src/ip_adapter/caipadapter_singlethread.c
new file mode 100644 (file)
index 0000000..9a36455
--- /dev/null
@@ -0,0 +1,487 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "caipadapter_singlethread.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include "caadapterutils.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "caipinterface_singlethread.h"
+
+/**
+ * @def TAG
+ * @brief Logging tag for module name
+ */
+#define TAG "IPAD"
+
+/**
+ * @def CA_PORT
+ * @brief Unicast port number (to listen for incoming data on unicast server).
+ * Note :- Actual port number may differ based on result of bind() operation.
+ */
+#define CA_PORT   6298
+
+/**
+ * @def CA_SECURE_PORT
+ * @brief Secured (unicast) port number as defined in COAP Specification, RFC-7252.
+ */
+#define CA_SECURE_PORT   5684
+
+/**
+ * @def CA_MCAST_PORT
+ * @brief Multicast port number as defined in COAP Specification, RFC-7252.
+ */
+#define CA_MCAST_PORT   5683
+
+/**
+ * @def CA_MULTICAST_IP
+ * @brief Multicast IP Address
+ */
+#define CA_MULTICAST_IP "224.0.1.187"
+
+/* Skip Queue */
+/**
+ * @var g_networkPacketCallback
+ * @brief Network Packet Received Callback to CA
+ */
+static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
+
+/**
+ * @var g_networkChangeCallback
+ * @brief Network Changed Callback to CA
+ */
+
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
+
+/**
+ * @var g_isMulticastServerStarted
+ * @brief Flag to check if multicast server is started
+ */
+static bool g_isMulticastServerStarted = false;
+
+/**
+ * @var g_startUnicastServerRequested
+ * @brief Flag to check if server start requested by CA.
+ */
+static bool g_startUnicastServerRequested = false;
+
+/**
+ * @var g_unicastServerport
+ * @brief port number on which unicast server is running.
+ */
+static uint16_t g_unicastServerport = 0;
+
+/**
+ * @var g_startMulticastServerRequested
+ * @brief Flag to check if server start requested by CA.
+ */
+static bool g_startMulticastServerRequested = false;
+
+
+static void CAIPNotifyNetworkChange(const char *address, uint16_t port,
+                                          CANetworkStatus_t status);
+static void CAIPConnectionStateCB(const char *ipAddress,
+                                        CANetworkStatus_t status);
+static void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port,
+                                       const void *data, uint32_t dataLength);
+static CAResult_t CAIPStopServers();
+
+void CAIPNotifyNetworkChange(const char *address, uint16_t port, CANetworkStatus_t status)
+{
+    CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address);
+    if (!localEndpoint)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory!");
+        return;
+    }
+    localEndpoint->addressInfo.IP.port = port;
+
+    if (NULL != g_networkChangeCallback)
+    {
+        g_networkChangeCallback(localEndpoint, status);
+    }
+
+    CAAdapterFreeLocalEndpoint(localEndpoint);
+}
+
+void CAIPConnectionStateCB(const char *ipAddr,
+                                 CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t ret = CA_STATUS_FAILED;
+    /* If IP is connected, then get the latest IP from the IP Interface
+      * and start unicast and multicast servers if requested earlier */
+    if (CA_INTERFACE_UP == status)
+    {
+        uint16_t port = CA_PORT;
+        int32_t serverFd = -1;
+        /* Start Unicast server if requested earlier */
+        if (g_startUnicastServerRequested)
+        {
+            ret = CAIPStartUnicastServer("0.0.0.0", &port, false, &serverFd);
+            if (CA_STATUS_OK == ret)
+            {
+                OIC_LOG_V(DEBUG, TAG, "unicast started:%d", port);
+                CAIPSetUnicastSocket(serverFd);
+                CAIPSetUnicastPort(port);
+                g_unicastServerport = port;
+            }
+            else
+            {
+                OIC_LOG_V(ERROR, TAG, "FAILED:%d", ret);
+            }
+        }
+
+        /* Start Multicast server if requested earlier */
+        if (g_startMulticastServerRequested)
+        {
+            uint16_t multicastPort = CA_MCAST_PORT;
+            ret = CAIPStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFd);
+            if (CA_STATUS_OK == ret)
+            {
+                OIC_LOG_V(DEBUG, TAG, "multicast started:%d", multicastPort);
+                g_isMulticastServerStarted = true;
+            }
+            else
+            {
+                OIC_LOG_V(ERROR, TAG, "strt mcast srv fail:%d", ret);
+            }
+        }
+
+        char *ipAddress = NULL;
+        char *ifcName = NULL;
+        CAResult_t ret = CAIPGetInterfaceInfo(&ifcName, &ipAddress);
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "get interface info fail:%d", ret);
+            OICFree(ipAddress);
+            OICFree(ifcName);
+            return;
+        }
+        /* Notify network change to CA */
+        CAIPNotifyNetworkChange(ipAddress, port, status);
+        OICFree(ipAddress);
+        OICFree(ifcName);
+    }
+    else
+    {
+        CAIPNotifyNetworkChange("", 0, status);
+        /* Stop both Unicast and Multicast servers */
+        ret = CAIPStopServers();
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "stop srv fail:%d", ret);
+            return;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port,
+                                const void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG_V(DEBUG, TAG, "sddress:%s", ipAddress);
+    OIC_LOG_V(DEBUG, TAG, "port:%d", port);
+    OIC_LOG_V(DEBUG, TAG, "data:%s", data);
+
+    /* CA is freeing this memory */
+    CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_IPV4, ipAddress, NULL);
+    if (NULL == endPoint)
+    {
+        OIC_LOG(ERROR, TAG, "Out of memory!");
+        return;
+    }
+    endPoint->addressInfo.IP.port = port;
+
+    if (g_networkPacketCallback)
+    {
+        g_networkPacketCallback(endPoint, data, dataLength);
+    }
+    CAAdapterFreeRemoteEndpoint(endPoint);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
+                                CANetworkPacketReceivedCallback networkPacketCallback,
+                                CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
+    VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
+    VERIFY_NON_NULL(netCallback, TAG, "netCallback");
+
+    g_networkChangeCallback = netCallback;
+    g_networkPacketCallback = networkPacketCallback;
+
+    CAResult_t ret = CAIPInitializeNetworkMonitor();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "init n/w fail:%d", ret);
+        return ret;
+    }
+    CAIPSetConnectionStateChangeCallback(CAIPConnectionStateCB);
+
+    ret = CAIPInitializeServer();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "init fail:%d", ret);
+        CATerminateIP();
+        return ret;
+    }
+    CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB);
+
+    CAConnectivityHandler_t IPHandler;
+    IPHandler.startAdapter = CAStartIP;
+    IPHandler.startListenServer = CAStartIPListeningServer;
+    IPHandler.startDiscoveryServer = CAStartIPDiscoveryServer;
+    IPHandler.sendData = CASendIPUnicastData;
+    IPHandler.sendDataToAll = CASendIPMulticastData;
+    IPHandler.GetnetInfo = CAGetIPInterfaceInformation;
+    IPHandler.readData = CAReadIPData;
+    IPHandler.stopAdapter = CAStopIP;
+    IPHandler.terminate = CATerminateIP;
+    registerCallback(IPHandler, CA_IPV4);
+
+    OIC_LOG(INFO, TAG, "success");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartIP()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    /* Start monitoring IP network */
+    CAResult_t ret = CAIPStartNetworkMonitor();
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "strt n/w monitor fail");
+    }
+
+    g_startUnicastServerRequested = true;
+    bool retVal = CAIPIsConnected();
+    if (false == retVal)
+    {
+        OIC_LOG(ERROR, TAG, "not connected");
+        return ret;
+    }
+
+    uint16_t unicastPort = CA_PORT;
+    int32_t serverFd = 0;
+    // Address is hardcoded as we are using Single Interface
+    ret = CAIPStartUnicastServer("0.0.0.0", &unicastPort, false, &serverFd);
+    if (CA_STATUS_OK == ret)
+    {
+        OIC_LOG_V(DEBUG, TAG, "unicast started:%d", unicastPort);
+        CAIPSetUnicastSocket(serverFd);
+        CAIPSetUnicastPort(unicastPort);
+        g_unicastServerport = unicastPort;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartIPListeningServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAResult_t ret = CA_STATUS_OK;
+    uint16_t multicastPort = CA_MCAST_PORT;
+    int32_t serverFD = 1;
+    if (g_isMulticastServerStarted == true)
+    {
+        OIC_LOG(ERROR, TAG, "Already Started!");
+        return CA_SERVER_STARTED_ALREADY;
+    }
+
+    g_startMulticastServerRequested = true;
+    bool retVal = CAIPIsConnected();
+    if (false == retVal)
+    {
+        OIC_LOG(ERROR, TAG,"Not connected");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    ret = CAIPStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFD);
+    if (CA_STATUS_OK == ret)
+    {
+        OIC_LOG(INFO, TAG, "multicast success");
+        g_isMulticastServerStarted = true;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartIPDiscoveryServer()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    /* Both listening and discovery server are same */
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CAStartIPListeningServer();
+}
+
+int32_t CASendIPUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+                                  uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint", -1);
+    VERIFY_NON_NULL_RET(data, TAG, "data", -1);
+    if (dataLength == 0)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid length");
+        return -1;
+    }
+
+    CAIPSendData(remoteEndpoint->addressInfo.IP.ipAddress,
+                       remoteEndpoint->addressInfo.IP.port, data, dataLength, false);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return dataLength;
+}
+
+int32_t CASendIPMulticastData(const void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    VERIFY_NON_NULL_RET(data, TAG, "data", -1);
+    if (dataLength == 0)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid length");
+        return -1;
+    }
+
+    CAIPSendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, true);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return dataLength;
+}
+
+CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(info, TAG, "info");
+    VERIFY_NON_NULL(size, TAG, "size");
+
+    bool retVal = CAIPIsConnected();
+    if (false == retVal)
+    {
+        OIC_LOG(ERROR, TAG, "Not connected");
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    char *ipAddress = NULL;
+    char *ifcName = NULL;
+    CAResult_t ret = CAIPGetInterfaceInfo(&ipAddress, &ifcName);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "get interface info fail:%d", ret);
+        OICFree(ipAddress);
+        OICFree(ifcName);
+        return ret;
+    }
+
+    // Create local endpoint using util function
+    (*info) = CAAdapterCreateLocalEndpoint(CA_IPV4, ipAddress);
+    if (NULL == (*info))
+    {
+        OIC_LOG(ERROR, TAG, "malloc fail");
+        OICFree(ipAddress);
+        OICFree(ifcName);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    (*info)->addressInfo.IP.port = g_unicastServerport;
+    (*size) = 1;
+
+    OICFree(ipAddress);
+    OICFree(ifcName);
+
+    OIC_LOG(INFO, TAG, "success");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAReadIPData()
+{
+    CAIPPullData();
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopServers()
+{
+    CAResult_t result = CAIPStopUnicastServer();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "stop ucast srv fail:%d", result);
+        return result;
+    }
+    CAIPSetUnicastSocket(-1);
+    CAIPSetUnicastPort(0);
+    g_unicastServerport = 0;
+
+    result = CAIPStopMulticastServer();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "stop mcast srv fail:%d", result);
+        return result;
+    }
+    g_isMulticastServerStarted = false;
+
+    return result;
+}
+
+CAResult_t CAStopIP()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    g_startUnicastServerRequested = false;
+    g_startMulticastServerRequested = false;
+    CAIPStopNetworkMonitor();
+    CAResult_t result = CAIPStopServers();
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "stop srv fail:%d", result);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return result;
+}
+
+void CATerminateIP()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CAIPSetConnectionStateChangeCallback(NULL);
+    CAIPTerminateNetworkMonitor();
+    CAIPSetPacketReceiveCallback(NULL);
+    OIC_LOG(INFO, TAG, "Terminated Ethernet");
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return;
+}
+
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/caipclient.c b/resource/csdk/connectivity/src/ip_adapter/caipclient.c
new file mode 100644 (file)
index 0000000..2f9cfd0
--- /dev/null
@@ -0,0 +1,147 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "caipinterface.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <errno.h>
+
+#include "caadapterutils.h"
+
+/**
+ * @def IP_CLIENT_TAG
+ * @brief Logging tag for module name
+ */
+#define IP_CLIENT_TAG "IP_CLIENT"
+#define OC_MULTICAST_IP "224.0.1.187"
+
+static uint32_t CASendData(const char *remoteAddress, uint16_t port, const void *data,
+                           uint32_t dataLength, int sockfd)
+{
+    OIC_LOG(DEBUG, IP_CLIENT_TAG, "IN");
+
+    VERIFY_NON_NULL_RET(remoteAddress, IP_CLIENT_TAG, "IP address is NULL", 0);
+    VERIFY_NON_NULL_RET(data, IP_CLIENT_TAG, "data is NULL", 0);
+
+    if (0 == dataLength)
+    {
+        OIC_LOG(ERROR, IP_CLIENT_TAG, "Data length is 0!");
+        return 0;
+    }
+
+    if (0 > sockfd)
+    {
+        OIC_LOG(ERROR, IP_CLIENT_TAG, "Unicast Server is not running!");
+        return 0;
+    }
+
+    struct sockaddr_in destAddr = { 0 };
+    destAddr.sin_family = AF_INET;
+    destAddr.sin_port = htons(port);
+
+    int ret = inet_pton(AF_INET, remoteAddress, &(destAddr.sin_addr));
+    if (1 != ret)
+    {
+        OIC_LOG(ERROR, IP_CLIENT_TAG, "inet_pton failed!");
+        return 0;
+    }
+
+    ssize_t sendDataLength = sendto(sockfd, data, dataLength, 0, (struct sockaddr *) &destAddr,
+                                    sizeof(destAddr));
+    if (-1 == sendDataLength)
+    {
+        OIC_LOG_V(ERROR, IP_CLIENT_TAG, "sendto failed, Error code: %s",
+                  strerror(errno));
+        return 0;
+    }
+
+    OIC_LOG_V(INFO, IP_CLIENT_TAG, "Sending data is successful, sent bytes[%d] to ip[%s:%d]",
+              sendDataLength, remoteAddress, port);
+    OIC_LOG(DEBUG, IP_CLIENT_TAG, "OUT");
+    return sendDataLength;
+}
+
+uint32_t CAIPSendData(const char *remoteAddress, uint16_t remotePort, const void *data,
+                            uint32_t dataLength, bool isMulticast, bool isSecured)
+{
+    u_arraylist_t *tempServerInfoList = u_arraylist_create();
+    if (!tempServerInfoList)
+    {
+        OIC_LOG(ERROR, IP_CLIENT_TAG, "u_arraylist_create failed");
+        return 0;
+    }
+
+    CAResult_t res = CAGetIPServerInfoList(&tempServerInfoList);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, IP_CLIENT_TAG, "CAGetIPServerInfoList failed");
+        CAClearServerInfoList(tempServerInfoList);
+        return 0;
+    }
+
+    uint32_t len = 0;
+    if (isMulticast || strcmp(remoteAddress, OC_MULTICAST_IP) == 0)
+    {
+        uint32_t listIndex = 0;
+        uint32_t listLength = u_arraylist_length(tempServerInfoList);
+        for (listIndex = 0; listIndex < listLength; listIndex++)
+        {
+            CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(tempServerInfoList,
+                                                                      listIndex);
+            if (!info || info->isMulticastServer || info->isSecured)
+            {
+                continue;
+            }
+
+            if (info->socketFd < 0)
+            {
+                OIC_LOG(ERROR, IP_CLIENT_TAG, "Invalid Socket Fd");
+                continue;
+            }
+
+            OIC_LOG_V(DEBUG, IP_CLIENT_TAG,
+                      "CA IP Multicast SendData with src ip %s port %d sockFd %d",
+                      info->ipAddress, info->port, info->socketFd);
+            len = CASendData(remoteAddress, remotePort, data, dataLength, info->socketFd);
+        }
+    }
+    else
+    {
+        int sockFd = CAGetSocketFdForUnicastServer(tempServerInfoList, remoteAddress, isSecured,
+                                                   isMulticast, CA_IPV4);
+
+        if (sockFd < 0)
+        {
+            OIC_LOG(ERROR, IP_CLIENT_TAG, "Invalid Socket Fd");
+            CAClearServerInfoList(tempServerInfoList);
+            return len;
+        }
+
+        OIC_LOG_V(DEBUG, IP_CLIENT_TAG, "IP unicast SendData sockFd %d", sockFd);
+
+        len = CASendData(remoteAddress, remotePort, data, dataLength, sockFd);
+
+    }
+    CAClearServerInfoList(tempServerInfoList);
+    return len;
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/caipserver.c b/resource/csdk/connectivity/src/ip_adapter/caipserver.c
new file mode 100644 (file)
index 0000000..38f164c
--- /dev/null
@@ -0,0 +1,986 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "caipinterface.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/select.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <errno.h>
+
+#include "pdu.h"
+#include "caadapterutils.h"
+#ifdef __WITH_DTLS__
+#include "caadapternetdtls.h"
+#endif
+#include "camutex.h"
+#include "oic_malloc.h"
+
+/**
+ * @def IP_SERVER_TAG
+ * @brief Logging tag for module name
+ */
+#define IP_SERVER_TAG "IP_SERVER"
+
+/**
+ * @def CA_UDP_BIND_RETRY_COUNT
+ * @brief Retry count in case of socket bind failure.
+ */
+#define CA_UDP_BIND_RETRY_COUNT 10
+
+/**
+ * @def IPNAMESIZE
+ * @brief Max length for ip address.
+ */
+#define IPNAMESIZE 16
+
+/**
+ * @def SOCKETOPTION
+ * @brief Socket option.
+ */
+#define SOCKETOPTION 1
+
+/**
+ * @var g_packetHandlerStopFlag
+ * @brief Flag for stopping packet handler thread.
+ */
+static bool g_packetHandlerStopFlag = false;
+
+/**
+ * @var CAAdapterIPServerContext_t
+ * @brief Thread context information for callbacks and threadpool.
+ */
+typedef struct
+{
+    ca_thread_pool_t threadPool;
+    CAIPPacketReceivedCallback packetReceivedCallback;
+    CAIPExceptionCallback exceptionCallback;
+} CAAdapterIPServerContext_t;
+
+/**
+ * @var g_serverInfoList
+ * @brief Mutex to synchronize ethenet adapter context.
+ */
+static u_arraylist_t *g_serverInfoList = NULL;
+
+/**
+ * @var g_mutexServerInfoList
+ * @brief Mutex to synchronize Server Information.
+ */
+static ca_mutex g_mutexServerInfoList = NULL;
+
+/**
+ * @var g_adapterEthServerContext
+ * @brief Mutex to synchronize ethenet adapter context.
+ */
+static CAAdapterIPServerContext_t *g_adapterEthServerContext = NULL;
+
+/**
+ * @var g_mutexAdapterServerContext
+ * @brief Mutex to synchronize unicast server
+ */
+static ca_mutex g_mutexAdapterServerContext = NULL;
+
+static void CAReceiveHandler(void *data)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    fd_set readFds;
+    int maxSd = 0;
+    struct timeval timeout;
+    char recvBuffer[COAP_MAX_PDU_SIZE] = { 0 };
+
+    while (true != g_packetHandlerStopFlag)
+    {
+        timeout.tv_sec = 1;
+        timeout.tv_usec = 0;
+        FD_ZERO(&readFds);
+
+        ca_mutex_lock(g_mutexServerInfoList);
+        uint32_t listIndex = 0;
+        uint32_t listLength = u_arraylist_length(g_serverInfoList);
+
+        u_arraylist_t *tempServerInfoList = u_arraylist_create();
+        if (!tempServerInfoList)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_create failed");
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return;
+        }
+
+        for (listIndex = 0; listIndex < listLength; listIndex++)
+        {
+            CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
+            if (!info)
+            {
+                listIndex++;
+                continue;
+            }
+
+            int sd = info->socketFd;
+            //if valid socket descriptor then add to read list
+            if (sd > 0)
+            {
+                FD_SET(sd, &readFds);
+            }
+
+            //highest file descriptor number, need it for the select function
+            if (sd > maxSd)
+            {
+                maxSd = sd;
+            }
+
+            CAServerInfo_t *newInfo = (CAServerInfo_t *) OICMalloc(sizeof(CAServerInfo_t));
+            if (!newInfo)
+            {
+                OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
+                CAClearServerInfoList(tempServerInfoList);
+                ca_mutex_unlock(g_mutexServerInfoList);
+                return;
+            }
+
+            memcpy(newInfo, info, sizeof(CAServerInfo_t));
+
+            CAResult_t result = u_arraylist_add(tempServerInfoList, (void *) newInfo);
+            if (CA_STATUS_OK != result)
+            {
+                OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_add failed!Thread exit");
+                CAClearServerInfoList(tempServerInfoList);
+                ca_mutex_unlock(g_mutexServerInfoList);
+                return;
+            }
+        }
+
+        ca_mutex_unlock(g_mutexServerInfoList);
+
+        int ret = select(maxSd + 1, &readFds, NULL, NULL, &timeout);
+        if (g_packetHandlerStopFlag)
+        {
+            OIC_LOG_V(DEBUG, IP_SERVER_TAG,
+                      "Packet receiver handler Stop request received. Thread exited");
+            CAClearServerInfoList(tempServerInfoList);
+            break;
+        }
+        if (ret < 0)
+        {
+            OIC_LOG_V(FATAL, IP_SERVER_TAG, "select returned error %s", strerror(errno));
+            CAClearServerInfoList(tempServerInfoList);
+            continue;
+        }
+
+        listLength = u_arraylist_length(tempServerInfoList);
+        for (listIndex = 0; listIndex < listLength; listIndex++)
+        {
+            CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(tempServerInfoList,
+                                                                      listIndex);
+            if (!info)
+            {
+                continue;
+            }
+
+            int sd = info->socketFd;
+            if (FD_ISSET(sd , &readFds))
+            {
+                OIC_LOG_V(ERROR, IP_SERVER_TAG,
+                          "data Received server information ip %s, port %d socket %d",
+                          info->ipAddress, info->port, sd);
+                memset(recvBuffer, 0, sizeof(recvBuffer));
+
+                struct sockaddr_in srcSockAddress = { 0 };
+                socklen_t srcAddressLen = sizeof(srcSockAddress);
+
+                //Reading from socket
+                ssize_t recvLen = recvfrom(sd, recvBuffer, sizeof(recvBuffer), 0,
+                                           (struct sockaddr *) &srcSockAddress, &srcAddressLen);
+                if (-1 == recvLen)
+                {
+                    OIC_LOG_V(ERROR, IP_SERVER_TAG, "Recvfrom failed %s", strerror(errno));
+                    continue;
+                }
+                else if (0 == recvLen)
+                {
+                    OIC_LOG_V(ERROR, IP_SERVER_TAG, "Server socket shutdown sock fd[%d]", sd);
+                    ca_mutex_lock(g_mutexAdapterServerContext);
+                    // Notify upper layer this exception
+                    if (g_adapterEthServerContext->exceptionCallback)
+                    {
+                        // need to make proper exception callback.
+                        //g_adapterEthServerContext->exceptionCallback(ctx->type);
+                    }
+                    ca_mutex_unlock(g_mutexAdapterServerContext);
+                }
+
+                char srcIPAddress[CA_IPADDR_SIZE] = { 0 };
+                if (!inet_ntop(AF_INET, &srcSockAddress.sin_addr.s_addr, srcIPAddress,
+                               sizeof(srcIPAddress)))
+                {
+
+                    OIC_LOG(ERROR, IP_SERVER_TAG, "inet_ntop is failed!");
+                    continue;
+                }
+
+                uint16_t srcPort = ntohs(srcSockAddress.sin_port);
+
+                OIC_LOG_V(DEBUG, IP_SERVER_TAG, "Received packet from %s:%d len %d",
+                          srcIPAddress, srcPort, recvLen);
+
+                char *netMask = NULL;
+                if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(info->ifAddr, &netMask))
+                {
+                    OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet");
+                    continue;
+                }
+
+                if (!CAAdapterIsSameSubnet(info->ifAddr, srcIPAddress, netMask))
+                {
+                    OIC_LOG(DEBUG, IP_SERVER_TAG,
+                            "Packet received from different subnet, Ignore!");
+                    OICFree(netMask);
+                    continue;
+                }
+                OICFree(netMask);
+
+                if (info->isSecured)
+                {
+#ifdef __WITH_DTLS__
+                    CAResult_t ret = CAAdapterNetDtlsDecrypt(srcIPAddress, srcPort,
+                                                             (uint8_t *)recvBuffer, recvLen,
+                                                             DTLS_IP);
+                    OIC_LOG_V(DEBUG, IP_SERVER_TAG,
+                              "CAAdapterNetDtlsDecrypt returns [%d]", ret);
+#endif
+                }
+                else //both multicast and unicast
+                {
+                    ca_mutex_lock(g_mutexAdapterServerContext);
+
+                    if (g_adapterEthServerContext->packetReceivedCallback)
+                    {
+                        g_adapterEthServerContext->packetReceivedCallback(srcIPAddress, srcPort,
+                                                                          recvBuffer, recvLen,
+                                                                          false);
+                    }
+
+                    ca_mutex_unlock(g_mutexAdapterServerContext);
+                }
+            }
+        }
+        CAClearServerInfoList(tempServerInfoList);
+    }
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+}
+
+static CAResult_t CACreateSocket(int *socketFD, const char *localIp, uint16_t *port,
+                                 bool forceBindStart)
+{
+    VERIFY_NON_NULL(socketFD, IP_SERVER_TAG, "socketFD is NULL");
+    VERIFY_NON_NULL(localIp, IP_SERVER_TAG, "localIp is NULL");
+    VERIFY_NON_NULL(port, IP_SERVER_TAG, "port is NULL");
+    // Create a UDP socket
+    int sock = -1;
+
+#ifdef SOCK_CLOEXEC
+    sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
+#endif
+
+    if (-1 == sock)
+    {
+        sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+    }
+
+    if (-1 == sock)
+    {
+        OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to create Socket, Error code: %s",
+                  strerror(errno));
+        return CA_STATUS_FAILED;
+    }
+
+    // Make the socket non-blocking
+    if (-1 == fcntl(sock, F_SETFL, O_NONBLOCK))
+    {
+        OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to set non-block mode, Error code: %s",
+                  strerror(errno));
+
+        close(sock);
+        return CA_STATUS_FAILED;
+    }
+
+    if (true == forceBindStart)
+    {
+        int setOptionOn = SOCKETOPTION;
+        if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &setOptionOn,
+                             sizeof(setOptionOn)))
+        {
+            OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to set SO_REUSEADDR! Error code: %s",
+                      strerror(errno));
+            close(sock);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    struct sockaddr_in sockAddr = { 0 };
+    uint16_t serverPort = *port;
+    sockAddr.sin_family = AF_INET;
+    sockAddr.sin_port = htons(serverPort);
+    if (localIp)
+    {
+        sockAddr.sin_addr.s_addr = inet_addr(localIp);
+    }
+
+    int16_t i = 0;
+    bool isBound = false;
+    for (i = 0; i < CA_UDP_BIND_RETRY_COUNT; i++)
+    {
+        if (-1 == bind(sock, (struct sockaddr *) &sockAddr, sizeof(sockAddr)))
+        {
+            if (false == forceBindStart)
+            {
+                OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]. Trying again..",
+                          strerror(errno));
+
+                //Set the port to next one
+                serverPort += 1;
+                sockAddr.sin_port = htons(serverPort);
+                continue;
+            }
+            else
+            {
+                OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]!",
+                          strerror(errno));
+                break;
+            }
+        }
+
+        isBound = true;
+        break;
+    }
+
+    if (false == isBound)
+    {
+        close(sock);
+        return CA_STATUS_FAILED;
+    }
+
+    *port = serverPort;
+    *socketFD = sock;
+    return CA_STATUS_OK;
+}
+
+static void CACloseSocket(int socketFD)
+{
+    if (-1 == socketFD)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid Socket Fd");
+        return;
+    }
+
+    // close the socket
+    if (-1 == close(socketFD))
+    {
+        OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to close the socket, Error code: %s\n",
+                  strerror(errno));
+    }
+}
+
+static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
+                                       bool forceBindStart, bool isSecured, int *serverFD)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(serverFD, IP_SERVER_TAG, "serverFD");
+    VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
+    VERIFY_NON_NULL(port, IP_SERVER_TAG, "port");
+
+    CAResult_t ret = CACreateSocket(serverFD, localAddress, port, forceBindStart);
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create unicast socket");
+    }
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+    return ret;
+}
+
+static CAResult_t CAIPStartPacketReceiverHandler()
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    ca_mutex_lock(g_mutexServerInfoList);
+
+    uint32_t listLength = u_arraylist_length(g_serverInfoList);
+
+    ca_mutex_unlock(g_mutexServerInfoList);
+
+    ca_mutex_lock(g_mutexAdapterServerContext);
+
+    if (!g_adapterEthServerContext)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
+        ca_mutex_unlock(g_mutexAdapterServerContext);
+        return CA_STATUS_FAILED;
+    }
+
+    if (1 == listLength) //Its first time.
+    {
+        g_packetHandlerStopFlag = false;
+        if (CA_STATUS_OK != ca_thread_pool_add_task(g_adapterEthServerContext->threadPool,
+                                                   CAReceiveHandler, NULL ))
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "thread_pool_add_task failed!");
+            ca_mutex_unlock(g_mutexAdapterServerContext);
+            return CA_STATUS_FAILED;
+        }
+        OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread started successfully.");
+    }
+    else
+    {
+        OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread already is running");
+    }
+    ca_mutex_unlock(g_mutexAdapterServerContext);
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+static void CAIPServerDestroyMutex(void)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    if (g_mutexServerInfoList)
+    {
+        ca_mutex_free(g_mutexServerInfoList);
+        g_mutexServerInfoList = NULL;
+    }
+
+    if (g_mutexAdapterServerContext)
+    {
+        ca_mutex_free(g_mutexAdapterServerContext);
+        g_mutexAdapterServerContext = NULL;
+    }
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+}
+
+static CAResult_t CAIPServerCreateMutex(void)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    g_mutexServerInfoList = ca_mutex_new();
+    if (!g_mutexServerInfoList)
+    {
+        OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    g_mutexAdapterServerContext = ca_mutex_new();
+    if (!g_mutexAdapterServerContext)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to created mutex!");
+        ca_mutex_free(g_mutexServerInfoList);
+        g_mutexServerInfoList = NULL;
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(threadPool, IP_SERVER_TAG, "Thread pool handle is NULL");
+
+    // Initialize mutex
+    if (CA_STATUS_OK != CAIPServerCreateMutex())
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create mutex!");
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_mutexAdapterServerContext);
+    g_adapterEthServerContext = (CAAdapterIPServerContext_t *) OICCalloc(1,
+                                 sizeof(CAAdapterIPServerContext_t));
+
+    if (!g_adapterEthServerContext)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
+        ca_mutex_unlock(g_mutexAdapterServerContext);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    g_adapterEthServerContext->threadPool = threadPool;
+
+    ca_mutex_unlock(g_mutexAdapterServerContext);
+
+    ca_mutex_lock(g_mutexServerInfoList);
+
+    g_serverInfoList = u_arraylist_create();
+    if (!g_serverInfoList)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_create failed");
+        ca_mutex_unlock(g_mutexServerInfoList);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    ca_mutex_unlock(g_mutexServerInfoList);
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAIPTerminateServer()
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+    ca_mutex_lock(g_mutexAdapterServerContext);
+    if (!g_adapterEthServerContext)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
+        ca_mutex_unlock(g_mutexAdapterServerContext);
+        return;
+    }
+
+    OICFree(g_adapterEthServerContext);
+    g_adapterEthServerContext = NULL;
+
+    ca_mutex_unlock(g_mutexAdapterServerContext);
+
+    ca_mutex_lock(g_mutexServerInfoList);
+
+    CAClearServerInfoList(g_serverInfoList);
+    g_serverInfoList = NULL;
+
+    ca_mutex_unlock(g_mutexServerInfoList);
+    // Destroy mutex
+    CAIPServerDestroyMutex();
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+
+}
+
+CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
+                                        bool forceBindStart, bool isSecured)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
+    VERIFY_NON_NULL(port, IP_SERVER_TAG, "port");
+
+    if (0 >= *port)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid input: port is invalid!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    ca_mutex_lock(g_mutexServerInfoList);
+    bool isUnicastServerStarted = CAIsUnicastServerStarted(g_serverInfoList, localAddress, *port);
+    if (!isUnicastServerStarted)
+    {
+        int unicastServerFd = -1;
+        if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceBindStart, isSecured,
+                                                 &unicastServerFd))
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to start unicast server!");
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return CA_STATUS_FAILED;
+        }
+
+        CAServerInfo_t *info = (CAServerInfo_t *) OICCalloc(1, sizeof(CAServerInfo_t));
+        if (!info)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
+            close(unicastServerFd);
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        char *netMask = NULL;
+        if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(localAddress, &netMask))
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet");
+        }
+        if (netMask)
+        {
+            strncpy(info->subNetMask, netMask, sizeof(info->subNetMask) - 1);
+            info->subNetMask[sizeof(info->subNetMask)-1] = '\0';
+            OICFree(netMask);
+        }
+        strncpy(info->ipAddress, localAddress, sizeof(info->ipAddress) - 1);
+        info->ipAddress[sizeof(info->ipAddress) - 1] = '\0';
+        info->port = *port;
+        info->socketFd = unicastServerFd;
+        info->isSecured = isSecured;
+        info->isServerStarted = true;
+        info->isMulticastServer = false;
+        strncpy(info->ifAddr, localAddress, sizeof(info->ifAddr) - 1);
+        info->ifAddr[sizeof(info->ifAddr) - 1] = '\0';
+
+        CAResult_t res = CAAddServerInfo(g_serverInfoList, info);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "CAAddServerInfo failed!");
+            close(unicastServerFd);
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return res;
+        }
+        ca_mutex_unlock(g_mutexServerInfoList);
+
+        res = CAIPStartPacketReceiverHandler();
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "CAIPStartPacketReceiverHandler failed!");
+            close(unicastServerFd);
+            return res;
+        }
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, IP_SERVER_TAG, "Already Unicast Server Started ip [%s] port [%d]",
+                  localAddress, *port);
+        ca_mutex_unlock(g_mutexServerInfoList);
+    }
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
+                                          uint16_t multicastPort)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    // Input validation
+    VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
+    VERIFY_NON_NULL(multicastAddress, IP_SERVER_TAG, "port");
+
+    uint16_t port = multicastPort;
+    if (0 >= port)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid input: Multicast port is invalid!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    ca_mutex_lock(g_mutexServerInfoList);
+    bool isMulticastServerStarted = CAIsMulticastServerStarted(g_serverInfoList, localAddress,
+                                                               multicastAddress, port);
+    if (!isMulticastServerStarted)
+    {
+        int mulicastServerFd = -1;
+        CAResult_t ret = CACreateSocket(&mulicastServerFd, multicastAddress, &port, true);
+        if (ret != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create multicast socket");
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return ret;
+        }
+
+        struct ip_mreq multicastMemberReq = {.imr_interface.s_addr = inet_addr(localAddress)};
+        inet_aton(multicastAddress, &multicastMemberReq.imr_multiaddr);
+
+        if (-1 == setsockopt(mulicastServerFd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
+                             (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
+        {
+            OIC_LOG_V(ERROR, IP_SERVER_TAG,
+                      "Failed to add to multicast group, Error code: %s\n", strerror(errno));
+            close(mulicastServerFd);
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return CA_STATUS_FAILED;
+        }
+
+        CAServerInfo_t *info = (CAServerInfo_t *) OICCalloc(1, sizeof(CAServerInfo_t));
+        if (!info)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
+            close(mulicastServerFd);
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        char *netMask = NULL;
+        if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(localAddress, &netMask))
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet");
+        }
+        if (netMask)
+        {
+            strncpy(info->subNetMask, netMask, sizeof(info->subNetMask) - 1);
+            info->subNetMask[sizeof(info->subNetMask) -1] = '\0';
+            OICFree(netMask);
+        }
+
+        strncpy(info->ipAddress, multicastAddress, sizeof(info->ipAddress) - 1);
+        info->ipAddress[sizeof(info->ipAddress) -1] = '\0';
+        info->port = multicastPort;
+        info->socketFd = mulicastServerFd;
+        info->isSecured = false;
+        info->isServerStarted = true;
+        info->isMulticastServer = true;
+        strncpy(info->ifAddr, localAddress, sizeof(info->ifAddr)-1);
+        info->ifAddr[sizeof(info->ifAddr) -1] = '\0';
+
+        ret = CAAddServerInfo(g_serverInfoList, info);
+
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "CAAddServerInfo failed!");
+            close(mulicastServerFd);
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return ret;
+        }
+        ca_mutex_unlock(g_mutexServerInfoList);
+
+        ret = CAIPStartPacketReceiverHandler();
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "CAIPStartPacketReceiverHandler failed!");
+            close(mulicastServerFd);
+            return ret;
+        }
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, IP_SERVER_TAG,
+                  "Multicast Server is already started on interface addr[%s]", localAddress);
+        ca_mutex_unlock(g_mutexServerInfoList);
+    }
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopServer(const char *interfaceAddress)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    VERIFY_NON_NULL(interfaceAddress, IP_SERVER_TAG, "interfaceAddress is NULL");
+
+    ca_mutex_lock(g_mutexServerInfoList);
+    uint32_t listIndex = 0;
+    uint32_t listLength = u_arraylist_length(g_serverInfoList);
+
+    for (listIndex = 0; listIndex < listLength;)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
+        if (!info)
+        {
+            listIndex++;
+            continue;
+        }
+
+        if (info->isMulticastServer && strncmp(interfaceAddress, info->ifAddr, strlen(info->ifAddr))
+                == 0)
+        {
+            if (u_arraylist_remove(g_serverInfoList, listIndex))
+            {
+                struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
+
+                multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
+                inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
+                if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+                                     (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
+                {
+                    OIC_LOG_V(ERROR, IP_SERVER_TAG,
+                              "Failed to leave multicast group, Error code: %s", strerror(errno));
+                }
+                CACloseSocket(info->socketFd);
+                OICFree(info);
+                OIC_LOG(DEBUG, IP_SERVER_TAG, "Multicast server is stopped successfully.");
+                // Reduce list length by 1 as we removed one element.
+                listLength--;
+            }
+            else
+            {
+                OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
+                ca_mutex_unlock(g_mutexServerInfoList);
+                return CA_STATUS_FAILED;
+            }
+        }
+        else if (strncmp(interfaceAddress, info->ipAddress, strlen(info->ipAddress)) == 0)
+        {
+            if (u_arraylist_remove(g_serverInfoList, listIndex))
+            {
+                CACloseSocket(info->socketFd);
+                OICFree(info);
+                OIC_LOG(DEBUG, IP_SERVER_TAG, "Unicast server is stopped successfully.");
+                // Reduce list length by 1 as we removed one element.
+                listLength--;
+            }
+            else
+            {
+                OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
+                ca_mutex_unlock(g_mutexServerInfoList);
+                return CA_STATUS_FAILED;
+            }
+        }
+        else
+        {
+            listIndex++;
+        }
+    }
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+    ca_mutex_unlock(g_mutexServerInfoList);
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopAllServers()
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    g_packetHandlerStopFlag = true;
+
+    ca_mutex_lock(g_mutexServerInfoList);
+
+    uint32_t listIndex = 0;
+    uint32_t listLength = u_arraylist_length(g_serverInfoList);
+    for (listIndex = 0; listIndex < listLength;)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
+        if (!info)
+        {
+            listIndex++;
+            continue;
+        }
+        if (u_arraylist_remove(g_serverInfoList, listIndex))
+        {
+            if (info->isMulticastServer)
+            {
+                struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
+
+                multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
+                inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
+                if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+                                     (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
+                {
+                    OIC_LOG_V(ERROR, IP_SERVER_TAG,
+                              "Failed to leave multicast group, Error code: %s", strerror(errno));
+                }
+            }
+            CACloseSocket(info->socketFd);
+            //Freeing server info.
+            OICFree(info);
+            // Reduce list length by 1 as we removed one element.
+            listLength--;
+        }
+        else
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    ca_mutex_unlock(g_mutexServerInfoList);
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "All Server stopped successfully. OUT");
+    return CA_STATUS_OK;
+}
+
+uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured)
+{
+    ca_mutex_lock(g_mutexServerInfoList);
+
+    uint16_t port = CAGetServerPort(g_serverInfoList, ipAddress, isSecured);
+
+    ca_mutex_unlock(g_mutexServerInfoList);
+
+    return port;
+}
+
+CAResult_t CAGetIPServerInfoList(u_arraylist_t **serverInfoList)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+    ca_mutex_lock(g_mutexServerInfoList);
+
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_serverInfoList);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, list_index);
+        if (!info)
+        {
+            continue;
+        }
+
+        CAServerInfo_t *newNetinfo = (CAServerInfo_t *) OICMalloc(sizeof(CAServerInfo_t));
+        if (!newNetinfo)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed!");
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        memcpy(newNetinfo, info, sizeof(*info));
+
+        CAResult_t result = u_arraylist_add(*serverInfoList, (void *) newNetinfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_add failed!");
+            ca_mutex_unlock(g_mutexServerInfoList);
+            return CA_STATUS_FAILED;
+        }
+    }
+    ca_mutex_unlock(g_mutexServerInfoList);
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+
+    ca_mutex_lock(g_mutexAdapterServerContext);
+
+    if (!g_adapterEthServerContext)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
+        ca_mutex_unlock(g_mutexAdapterServerContext);
+        return;
+    }
+    g_adapterEthServerContext->packetReceivedCallback = callback;
+
+    ca_mutex_unlock(g_mutexAdapterServerContext);
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+}
+
+void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
+{
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
+    ca_mutex_lock(g_mutexAdapterServerContext);
+
+    if (!g_adapterEthServerContext)
+    {
+        OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
+        ca_mutex_unlock(g_mutexAdapterServerContext);
+        return;
+    }
+    g_adapterEthServerContext->exceptionCallback = callback;
+
+    ca_mutex_unlock(g_mutexAdapterServerContext);
+
+    OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c
new file mode 100644 (file)
index 0000000..c077580
--- /dev/null
@@ -0,0 +1,664 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "caipinterface.h"
+
+#include <sys/types.h>
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <sys/socket.h>
+#include <netdb.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "caadapterutils.h"
+#include "camutex.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#define IP_MONITOR_TAG "IP_MONITOR"
+
+/**
+ * @var g_networkMonitorContextMutex
+ * @brief  Mutex for synchronizing access to cached interface and IP address information.
+ */
+static ca_mutex g_networkMonitorContextMutex = NULL;
+
+/**
+ * @var g_stopNetworkMonitor
+ * @brief  Used to stop the network monitor thread.
+ */
+static bool g_stopNetworkMonitor = false;
+
+/**
+ * @var g_stopNetworkMonitorMutex
+ * @brief  Mutex for synchronizing access to g_stopNetworkMonitor flag.
+ */
+static ca_mutex g_stopNetworkMonitorMutex = NULL;
+
+/**
+ * @struct CAIPNwMonitorContext
+ * @brief  Used for storing network monitor context information.
+ */
+typedef struct
+{
+    u_arraylist_t  *netInterfaceList;
+    ca_thread_pool_t threadPool;
+    CANetworkStatus_t nwConnectivityStatus;
+    CAIPConnectionStateChangeCallback networkChangeCb;
+} CAIPNetworkMonitorContext;
+
+/**
+ * @var g_networkMonitorContext
+ * @brief  network monitor context.
+ */
+static CAIPNetworkMonitorContext *g_networkMonitorContext = NULL;
+
+static void CAIPGetInterfaceInformation(u_arraylist_t **netInterfaceList)
+{
+
+    VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null");
+
+    struct ifaddrs *ifp = NULL;
+    if (-1 == getifaddrs(&ifp))
+    {
+        OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface list!, Error code: %s",
+                  strerror(errno));
+        return;
+    }
+
+    struct ifaddrs *ifa = NULL;
+    for (ifa = ifp; ifa; ifa = ifa->ifa_next)
+    {
+        char interfaceAddress[CA_IPADDR_SIZE] = {0};
+        char interfaceSubnetMask[CA_IPADDR_SIZE] = {0};
+        socklen_t len = sizeof(struct sockaddr_in);
+
+        if (!ifa->ifa_addr)
+        {
+            continue;
+        }
+
+        int type = ifa->ifa_addr->sa_family;
+        if (ifa->ifa_flags & IFF_LOOPBACK
+            || !((ifa->ifa_flags & IFF_UP) && (ifa->ifa_flags & IFF_RUNNING)))
+        {
+            continue;
+        }
+
+        if (AF_INET != type)
+        {
+            continue;
+        }
+
+        // get the interface ip address
+        if (0 != getnameinfo(ifa->ifa_addr, len, interfaceAddress,
+                             sizeof(interfaceAddress), NULL, 0, NI_NUMERICHOST))
+        {
+            OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get IPAddress, Error code: %s",
+                      strerror(errno));
+            continue;
+        }
+
+        // get the interface subnet mask
+        if (0 != getnameinfo(ifa->ifa_netmask, len, interfaceSubnetMask,
+                             sizeof(interfaceSubnetMask), NULL, 0, NI_NUMERICHOST))
+        {
+            OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get subnet mask, Error code: %s",
+                      strerror(errno));
+            continue;
+        }
+
+        CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t));
+        if (!netInfo)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed");
+            freeifaddrs(ifp);
+            return;
+        }
+        // set interface name
+        strncpy(netInfo->interfaceName, ifa->ifa_name, sizeof(netInfo->interfaceName) - 1);
+        netInfo->interfaceName[sizeof(netInfo->interfaceName)-1] = '\0';
+
+        // set local ip address
+        strncpy(netInfo->ipAddress, interfaceAddress, strlen(interfaceAddress));
+
+        // set subnet mask
+        strncpy(netInfo->subnetMask, interfaceSubnetMask, strlen(interfaceSubnetMask));
+
+        CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!Thread exiting.");
+            freeifaddrs(ifp);
+            return;
+        }
+    }
+
+    freeifaddrs(ifp);
+}
+
+static bool CACheckIsAnyInterfaceDown(const u_arraylist_t *netInterfaceList,
+                                      const CANetInfo_t *info)
+{
+    VERIFY_NON_NULL_RET(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null", false);
+    VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false);
+
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(netInterfaceList);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get(netInterfaceList,
+                               list_index);
+        if (!netInfo)
+        {
+            continue;
+        }
+        if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0)
+        {
+            return false;
+        }
+    }
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down");
+    return true;
+}
+
+static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info)
+{
+    VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false);
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get(
+                               g_networkMonitorContext->netInterfaceList, list_index);
+        if (!netInfo)
+        {
+            continue;
+        }
+        if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0)
+        {
+            if (strncmp(netInfo->ipAddress, info->ipAddress, strlen(info->ipAddress)) == 0)
+            {
+                ca_mutex_unlock(g_networkMonitorContextMutex);
+                return false;
+            }
+            else
+            {
+                OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network interface info changed");
+                if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index))
+                {
+                    if (g_networkMonitorContext->networkChangeCb)
+                    {
+                        g_networkMonitorContext->networkChangeCb(netInfo->ipAddress,
+                                                                 CA_INTERFACE_DOWN);
+                    }
+                    OICFree(netInfo);
+                }
+                else
+                {
+                    OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed");
+                }
+                break;
+            }
+        }
+    }
+
+    CANetInfo_t *newNetInfo = (CANetInfo_t *)OICMalloc(sizeof(CANetInfo_t));
+    if (!newNetInfo)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "newNetInfo malloc failed");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    memcpy(newNetInfo, info, sizeof(*newNetInfo));
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found");
+
+    CAResult_t result = u_arraylist_add(g_networkMonitorContext->netInterfaceList,
+                                        (void *)newNetInfo);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!");
+        OICFree(newNetInfo);
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    /*Callback will be unset only at the time of termination. By that time, all the threads will be
+      stopped gracefully. This callback is properly protected*/
+    if (g_networkMonitorContext->networkChangeCb)
+    {
+        g_networkMonitorContext->networkChangeCb(newNetInfo->ipAddress, CA_INTERFACE_UP);
+    }
+
+    return true;
+}
+
+static void CANetworkMonitorThread(void *threadData)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    while (!g_stopNetworkMonitor)
+    {
+        u_arraylist_t  *netInterfaceList = u_arraylist_create();
+
+        VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null");
+
+        CAIPGetInterfaceInformation(&netInterfaceList);
+
+        ca_mutex_lock(g_networkMonitorContextMutex);
+        if (!g_networkMonitorContext->netInterfaceList)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG,
+                    "u_arraylist_create failed. Network Monitor thread stopped");
+            CAClearNetInterfaceInfoList(netInterfaceList);
+            ca_mutex_unlock(g_networkMonitorContextMutex);
+            return;
+        }
+
+        uint32_t listIndex = 0;
+        uint32_t listLength = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+        for (listIndex = 0; listIndex < listLength;)
+        {
+            CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get(
+                                    g_networkMonitorContext->netInterfaceList, listIndex);
+            if (!info)
+            {
+                listIndex++;
+                continue;
+            }
+
+            bool ret = CACheckIsAnyInterfaceDown(netInterfaceList, info);
+            if (ret)
+            {
+                OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down");
+                if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, listIndex))
+                {
+                    OIC_LOG(DEBUG, IP_MONITOR_TAG, "u_arraylist_remove success");
+                    if (g_networkMonitorContext->networkChangeCb)
+                    {
+                        g_networkMonitorContext->networkChangeCb(info->ipAddress,
+                                                                 CA_INTERFACE_DOWN);
+                    }
+                    OICFree(info);
+                    listLength--;
+                }
+                else
+                {
+                    OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed");
+                    break;
+                }
+            }
+            else
+            {
+                listIndex++;
+            }
+        }
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+
+        listLength = u_arraylist_length(netInterfaceList);
+        for (listIndex = 0; listIndex < listLength; listIndex++)
+        {
+            CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get(netInterfaceList, listIndex);
+            if (!info)
+            {
+                continue;
+            }
+            bool ret = CACheckIsInterfaceInfoChanged(info);
+            if (ret)
+            {
+                OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACheckIsInterfaceInfoChanged true");
+            }
+        }
+        CAClearNetInterfaceInfoList(netInterfaceList);
+        sleep(2); // To avoid maximum cpu usage.
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+static CAResult_t CAInitializeNetworkMonitorMutexes()
+{
+    if (!g_networkMonitorContextMutex)
+    {
+        g_networkMonitorContextMutex = ca_mutex_new();
+        if (!g_networkMonitorContextMutex)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContextMutex Malloc  failed");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+
+    if (!g_stopNetworkMonitorMutex)
+    {
+        g_stopNetworkMonitorMutex = ca_mutex_new();
+        if (!g_stopNetworkMonitorMutex)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "g_stopNetworkMonitorMutex Malloc  failed");
+            ca_mutex_free(g_networkMonitorContextMutex);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+    return CA_STATUS_OK;
+}
+static void CADestroyNetworkMonitorMutexes()
+{
+    ca_mutex_free(g_networkMonitorContextMutex);
+    g_networkMonitorContextMutex = NULL;
+
+    ca_mutex_free(g_stopNetworkMonitorMutex);
+    g_stopNetworkMonitorMutex = NULL;
+}
+
+CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(threadPool, IP_MONITOR_TAG, "threadPool is null");
+
+    CAResult_t ret = CAInitializeNetworkMonitorMutexes();
+
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "CAInitializeNetworkMonitorMutexes failed");
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+    g_networkMonitorContext = (CAIPNetworkMonitorContext *)OICCalloc(1,
+                              sizeof(*g_networkMonitorContext));
+    if (!g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext Malloc  failed");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        CADestroyNetworkMonitorMutexes();
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+    g_networkMonitorContext->threadPool = threadPool;
+
+    g_networkMonitorContext->netInterfaceList = u_arraylist_create();
+    if (!g_networkMonitorContext->netInterfaceList)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_create failed");
+        OICFree(g_networkMonitorContext);
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        CADestroyNetworkMonitorMutexes();
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    CAIPGetInterfaceInformation(&g_networkMonitorContext->netInterfaceList);
+
+
+    if (u_arraylist_length(g_networkMonitorContext->netInterfaceList))
+    {
+        g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_UP;
+    }
+    else
+    {
+        g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN;
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAIPTerminateNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    g_networkMonitorContext->threadPool = NULL;
+
+    CAClearNetInterfaceInfoList(g_networkMonitorContext->netInterfaceList);
+
+    g_networkMonitorContext->netInterfaceList = NULL;
+    g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN;
+    g_networkMonitorContext->networkChangeCb = NULL;
+    g_networkMonitorContext->threadPool = NULL;
+
+    OICFree(g_networkMonitorContext);
+    g_networkMonitorContext = NULL;
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    ca_mutex_lock(g_stopNetworkMonitorMutex);
+    g_stopNetworkMonitor = true;
+    ca_mutex_unlock(g_stopNetworkMonitorMutex);
+
+    CADestroyNetworkMonitorMutexes();
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+CAResult_t CAIPStartNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_stopNetworkMonitorMutex);
+
+    g_stopNetworkMonitor = false;
+
+    ca_mutex_unlock(g_stopNetworkMonitorMutex);
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+    if (!g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext is null");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_networkMonitorContext->threadPool,
+            CANetworkMonitorThread, NULL))
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "[ThreadPool] thread_pool_add_task failed!");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext is null");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    ca_mutex_lock(g_stopNetworkMonitorMutex);
+    if (!g_stopNetworkMonitor)
+    {
+        g_stopNetworkMonitor = true;
+    }
+    else
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStopNetworkMonitor, already stopped!");
+    }
+    ca_mutex_unlock(g_stopNetworkMonitorMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "u_array_list is null");
+    VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG,
+                    "g_networkMonitorContext is null");
+    VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG,
+                    "g_networkMonitorContextMutex is null");
+
+    // Get the interface and ipaddress information from cache
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList
+        || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList)))
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Network not enabled");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo list length [%d]",
+              list_length);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get(
+                            g_networkMonitorContext->netInterfaceList, list_index);
+        if (!info)
+        {
+            continue;
+        }
+        OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo ip [%s]",
+                  info->ipAddress);
+        CANetInfo_t *newNetinfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t));
+        if (!newNetinfo)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed!");
+            ca_mutex_unlock(g_networkMonitorContextMutex);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        memcpy(newNetinfo, info, sizeof(*info));
+
+        CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)newNetinfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!");
+            ca_mutex_unlock(g_networkMonitorContextMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(subnetMask, IP_MONITOR_TAG, "subnet mask");
+    VERIFY_NON_NULL(ipAddress, IP_MONITOR_TAG, "ipAddress is null");
+    VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG,
+                    "g_networkMonitorContext is null");
+    VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG,
+                    "g_networkMonitorContextMutex is null");
+
+    // Get the interface and ipaddress information from cache
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList
+        || (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList)))
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network not enabled");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "list lenght [%d]", list_length);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get(
+                            g_networkMonitorContext->netInterfaceList, list_index);
+        if (!info)
+        {
+            continue;
+        }
+
+        if (strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0)
+        {
+            OIC_LOG_V(DEBUG, IP_MONITOR_TAG,
+                      "CAIPGetInterfaceSubnetMask subnetmask is %s", info->subnetMask);
+            *subnetMask = OICStrdup(info->subnetMask);
+            break;
+        }
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+bool CAIPIsConnected()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+    if (!g_networkMonitorContextMutex || !g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected");
+        return false;
+    }
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList))
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return true;
+}
+
+void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+    if (!g_networkMonitorContextMutex || !g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPSetConnectionStateChangeCallback failed");
+        return;
+    }
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+    g_networkMonitorContext->networkChangeCb = callback;
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
diff --git a/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c
new file mode 100644 (file)
index 0000000..1a46cd8
--- /dev/null
@@ -0,0 +1,645 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "caipinterface.h"
+
+#include <wifi.h>
+
+#include "caadapterutils.h"
+#include "camutex.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#define IP_MONITOR_TAG "IP_MONITOR"
+
+/**
+ * @var g_networkMonitorContextMutex
+ * @brief  Mutex for synchronizing access to cached interface and IP address information.
+ */
+static ca_mutex g_networkMonitorContextMutex = NULL;
+
+/**
+ * @struct CAIPNwMonitorContext
+ * @brief  Used for storing network monitor context information.
+ */
+typedef struct
+{
+    u_arraylist_t  *netInterfaceList;
+    ca_thread_pool_t threadPool;
+    CANetworkStatus_t nwConnectivityStatus;
+    CAIPConnectionStateChangeCallback networkChangeCb;
+} CAIPNetworkMonitorContext;
+
+/**
+ * @var g_networkMonitorContext
+ * @brief  network monitor context.
+ */
+static CAIPNetworkMonitorContext *g_networkMonitorContext = NULL;
+
+static void CARemoveInterfaceInfo()
+{
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG,
+                "netInterfaceList is empty");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return;
+    }
+
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get(
+                               g_networkMonitorContext->netInterfaceList, list_index);
+        if (!netInfo)
+        {
+            continue;
+        }
+
+        if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index))
+        {
+            if (g_networkMonitorContext->networkChangeCb)
+            {
+                g_networkMonitorContext->networkChangeCb(netInfo->ipAddress,
+                                                         CA_INTERFACE_DOWN);
+            }
+        }
+        else
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed");
+        }
+
+        OICFree(netInfo);
+    }
+
+    u_arraylist_free(&g_networkMonitorContext->netInterfaceList);
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+}
+
+static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info)
+{
+    VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false);
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get(
+                               g_networkMonitorContext->netInterfaceList, list_index);
+        if (!netInfo)
+        {
+            continue;
+        }
+
+        if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0)
+        {
+            if (strncmp(netInfo->ipAddress, info->ipAddress, strlen(info->ipAddress)) == 0)
+            {
+                ca_mutex_unlock(g_networkMonitorContextMutex);
+                return false;
+            }
+            else
+            {
+                OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network interface info changed");
+                if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index))
+                {
+                    if (g_networkMonitorContext->networkChangeCb)
+                    {
+                        g_networkMonitorContext->networkChangeCb(netInfo->ipAddress,
+                                                                 CA_INTERFACE_DOWN);
+                    }
+                    OICFree(netInfo);
+                }
+                else
+                {
+                    OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed");
+                }
+                break;
+            }
+        }
+    }
+
+    CANetInfo_t *newNetInfo = (CANetInfo_t *)OICMalloc(sizeof(CANetInfo_t));
+    if (!newNetInfo)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "newNetInfo malloc failed");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    memcpy(newNetInfo, info, sizeof(*newNetInfo));
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found");
+
+    CAResult_t result = u_arraylist_add(g_networkMonitorContext->netInterfaceList,
+                                        (void *)newNetInfo);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!");
+        OICFree(newNetInfo);
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return false;
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    /*Callback will be unset only at the time of termination. By that time, all the threads will be
+      stopped gracefully. This callback is properly protected*/
+    if (g_networkMonitorContext->networkChangeCb)
+    {
+        g_networkMonitorContext->networkChangeCb(newNetInfo->ipAddress, CA_INTERFACE_UP);
+    }
+
+    return true;
+}
+
+void CAWiFiGetInterfaceInformation(char **interfaceName, char **ipAddress, char **subnetMask)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    int ret = WIFI_ERROR_NONE;
+
+    if (!interfaceName || !ipAddress || !subnetMask)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Invalid input: interface/ipaddress holder is NULL!");
+        return;
+    }
+
+    // Get wifi interface name
+    if (WIFI_ERROR_NONE != (ret = wifi_get_network_interface_name(interfaceName)))
+    {
+        OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface name! error num [%d]", ret);
+        return;
+    }
+
+    // Get wifi connected IP address
+    wifi_ap_h accessPoint = NULL;
+    if (WIFI_ERROR_NONE != (ret = wifi_get_connected_ap(&accessPoint)))
+    {
+        OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get access point! error num [%d]",
+                  ret);
+
+        OICFree(*interfaceName);
+        *interfaceName = NULL;
+        return;
+    }
+
+    if (WIFI_ERROR_NONE != (ret = wifi_ap_get_ip_address(accessPoint, WIFI_ADDRESS_FAMILY_IPV4,
+                                  ipAddress)))
+    {
+        OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface address! error num [%d]",
+                  ret);
+        OICFree(*interfaceName);
+        *interfaceName = NULL;
+        return;
+    }
+
+    if (WIFI_ERROR_NONE != (ret = wifi_ap_get_subnet_mask(accessPoint, WIFI_ADDRESS_FAMILY_IPV4,
+                                  subnetMask)))
+    {
+        OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface address! error num [%d]",
+                  ret);
+        OICFree(*ipAddress);
+        OICFree(*interfaceName);
+        *ipAddress = NULL;
+        *interfaceName = NULL;
+        return;
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+static void CAIPGetInterfaceInformation(u_arraylist_t **netInterfaceList)
+{
+    VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null");
+
+    // Get wifi network information
+    char *interfaceName = NULL;
+    char *ipAddress = NULL;
+    char *subnetMask = NULL;
+    ///TODO: currently we are filling single interface. Once found the proper tizen apis for
+    // getting multiple interfaces, then this function will be updated.
+    CAWiFiGetInterfaceInformation(&interfaceName, &ipAddress, &subnetMask);
+
+    if (!interfaceName || !ipAddress || !subnetMask)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "interface/ipaddress/subnetmask is NULL!");
+        return;
+    }
+
+    CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t));
+    if (!netInfo)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed");
+        OICFree(interfaceName);
+        OICFree(ipAddress);
+        OICFree(subnetMask);
+        return;
+    }
+
+    // set interface name
+    strncpy(netInfo->interfaceName, interfaceName, strlen(interfaceName));
+
+    // set local ip address
+    strncpy(netInfo->ipAddress, ipAddress, strlen(ipAddress));
+
+    // set subnet mask
+    strncpy(netInfo->subnetMask, subnetMask, strlen(subnetMask));
+
+    CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo);
+    if (CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!");
+    }
+    OICFree(interfaceName);
+    OICFree(ipAddress);
+    OICFree(subnetMask);
+}
+
+
+void CAWIFIConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap,
+                                    void *userData)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    if (WIFI_CONNECTION_STATE_ASSOCIATION == state
+        || WIFI_CONNECTION_STATE_CONFIGURATION == state)
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "Connection is in Association State");
+        return;
+    }
+
+    // If Wifi is connected, then get the latest IP from the WIFI Interface
+    if (WIFI_CONNECTION_STATE_CONNECTED == state)
+    {
+        // Get network information
+        char *interfaceName = NULL;
+        char *ipAddress = NULL;
+        char *subnetMask = NULL;
+        CAWiFiGetInterfaceInformation(&interfaceName, &ipAddress, &subnetMask);
+
+        CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t));
+        if (!netInfo)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed");
+            OICFree(interfaceName);
+            OICFree(ipAddress);
+            OICFree(subnetMask);
+            return;
+        }
+
+        // set interface name
+        strncpy(netInfo->interfaceName, interfaceName, strlen(interfaceName));
+
+        // set local ip address
+        strncpy(netInfo->ipAddress, ipAddress, strlen(ipAddress));
+
+        // set subnet mask
+        strncpy(netInfo->subnetMask, subnetMask, strlen(subnetMask));
+
+        bool ret = CACheckIsInterfaceInfoChanged(netInfo);
+        if (ret)
+        {
+            OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACheckIsInterfaceInfoChanged true");
+        }
+
+        OICFree(interfaceName);
+        OICFree(ipAddress);
+        OICFree(subnetMask);
+    }
+    else
+    {
+        CARemoveInterfaceInfo();
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+void CAWIFIDeviceStateChangedCb(wifi_device_state_e state, void *userData)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    if (WIFI_DEVICE_STATE_ACTIVATED == state)
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "Wifi is in Activated State");
+    }
+    else
+    {
+        CAWIFIConnectionStateChangedCb(WIFI_CONNECTION_STATE_DISCONNECTED, NULL, NULL);
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "Wifi is in Deactivated State");
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+static CAResult_t CAInitializeNetworkMonitorMutexes()
+{
+    if (!g_networkMonitorContextMutex)
+    {
+        g_networkMonitorContextMutex = ca_mutex_new();
+        if (!g_networkMonitorContextMutex)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContextMutex Malloc  failed");
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+
+    return CA_STATUS_OK;
+}
+
+static void CADestroyNetworkMonitorMutexes()
+{
+    ca_mutex_free(g_networkMonitorContextMutex);
+    g_networkMonitorContextMutex = NULL;
+}
+
+CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(threadPool, IP_MONITOR_TAG, "threadPool is null");
+
+    CAResult_t ret = CAInitializeNetworkMonitorMutexes();
+
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "CAInitializeNetworkMonitorMutexes failed");
+        return CA_STATUS_FAILED;
+    }
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+     // Initialize Wifi service
+    wifi_error_e retValue = wifi_initialize();
+    if (WIFI_ERROR_NONE != retValue)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_initialize failed");
+        return CA_STATUS_FAILED;
+    }
+
+    g_networkMonitorContext = (CAIPNetworkMonitorContext *)OICCalloc(1,
+                              sizeof(*g_networkMonitorContext));
+    if (!g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext Malloc  failed");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        CADestroyNetworkMonitorMutexes();
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    g_networkMonitorContext->netInterfaceList = u_arraylist_create();
+    if (!g_networkMonitorContext->netInterfaceList)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_create failed");
+        OICFree(g_networkMonitorContext);
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        CADestroyNetworkMonitorMutexes();
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    CAIPGetInterfaceInformation(&g_networkMonitorContext->netInterfaceList);
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAIPTerminateNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+     // Deinitialize Wifi service
+    wifi_error_e ret = wifi_deinitialize();
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_deinitialize failed");
+    }
+
+    CAClearNetInterfaceInfoList(g_networkMonitorContext->netInterfaceList);
+
+    g_networkMonitorContext->netInterfaceList = NULL;
+    g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN;
+    g_networkMonitorContext->networkChangeCb = NULL;
+
+    OICFree(g_networkMonitorContext);
+    g_networkMonitorContext = NULL;
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    CADestroyNetworkMonitorMutexes();
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
+
+CAResult_t CAIPStartNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+     // Set callback for receiving state changes
+    wifi_error_e ret = wifi_set_device_state_changed_cb(CAWIFIDeviceStateChangedCb, NULL);
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_set_device_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+
+    // Set callback for receiving connection state changes
+    ret = wifi_set_connection_state_changed_cb(CAWIFIConnectionStateChangedCb, NULL);
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_set_connection_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopNetworkMonitor()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+     // Reset callback for receiving state changes
+    wifi_error_e ret = wifi_unset_device_state_changed_cb();
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_unset_device_state_changed_cb failed");
+    }
+
+    // Reset callback for receiving connection state changes
+    ret = wifi_unset_connection_state_changed_cb();
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_unset_connection_state_changed_cb failed");
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "u_array_list is null");
+    VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG,
+                    "g_networkMonitorContext is null");
+    VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG,
+                    "g_networkMonitorContextMutex is null");
+
+    // Get the interface and ipaddress information from cache
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList
+        || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList)))
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Network not enabled");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo list length [%d]",
+              list_length);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get(
+                            g_networkMonitorContext->netInterfaceList, list_index);
+        if (!info)
+        {
+            continue;
+        }
+        OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo ip [%s]",
+                  info->ipAddress);
+        CANetInfo_t *newNetinfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t));
+        if (!newNetinfo)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed!");
+            ca_mutex_unlock(g_networkMonitorContextMutex);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+
+        memcpy(newNetinfo, info, sizeof(*info));
+
+        CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)newNetinfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!");
+            ca_mutex_unlock(g_networkMonitorContextMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    VERIFY_NON_NULL(subnetMask, IP_MONITOR_TAG, "subnet mask");
+    VERIFY_NON_NULL(ipAddress, IP_MONITOR_TAG, "ipAddress is null");
+    VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG,
+                    "g_networkMonitorContext is null");
+    VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG,
+                    "g_networkMonitorContextMutex is null");
+
+    // Get the interface and ipaddress information from cache
+    ca_mutex_lock(g_networkMonitorContextMutex);
+    if (!g_networkMonitorContext->netInterfaceList
+        || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList)))
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network not enabled");
+        ca_mutex_unlock(g_networkMonitorContextMutex);
+        return CA_ADAPTER_NOT_ENABLED;
+    }
+
+    uint32_t list_index = 0;
+    uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList);
+    OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "list lenght [%d]", list_length);
+    for (list_index = 0; list_index < list_length; list_index++)
+    {
+        CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get(
+                            g_networkMonitorContext->netInterfaceList, list_index);
+        if (!info)
+        {
+            continue;
+        }
+
+        if (strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0)
+        {
+            OIC_LOG_V(DEBUG, IP_MONITOR_TAG,
+                      "CAIPGetInterfaceSubnetMask subnetmask is %s", info->subnetMask);
+            *subnetMask = OICStrdup(info->subnetMask);
+            break;
+        }
+    }
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+bool CAIPIsConnected()
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+
+    wifi_connection_state_e connection_state;
+    wifi_error_e ret = wifi_get_connection_state(&connection_state);
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "Failed to get the Connection State");
+        return false;
+    }
+
+    if (WIFI_CONNECTION_STATE_DISCONNECTED == connection_state)
+    {
+        OIC_LOG(DEBUG, IP_MONITOR_TAG, "WIFI is not Connected");
+        return false;
+    }
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+    return true;
+}
+
+void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
+{
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN");
+    if (!g_networkMonitorContextMutex || !g_networkMonitorContext)
+    {
+        OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPSetConnectionStateChangeCallback failed");
+        return;
+    }
+    ca_mutex_lock(g_networkMonitorContextMutex);
+
+    g_networkMonitorContext->networkChangeCb = callback;
+
+    ca_mutex_unlock(g_networkMonitorContextMutex);
+
+    OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT");
+}
diff --git a/resource/csdk/connectivity/src/wifi_adapter/cawifiethernetadapter.c b/resource/csdk/connectivity/src/wifi_adapter/cawifiethernetadapter.c
deleted file mode 100644 (file)
index a6033cc..0000000
+++ /dev/null
@@ -1,371 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-#include "cawifiethernetadapter.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdint.h>
-#include "caadapterutils.h"
-#include "umutex.h"
-
-#ifdef __TIZEN__
-#include "cawifiserver.h"
-#include "cawificlient.h"
-#include "cawifimonitor.h"
-#elif defined(OIC_ARDUINODUE)
-#include <logger.h>
-#include <string.h>
-#include "cawifiadapter.h"
-#endif //#ifdef __TIZEN__
-/**
- * @def WIFI_ETHERNET_ADAPTER_TAG
- * @brief Logging tag for module name
- */
-#define WIFI_ETHERNET_ADAPTER_TAG "WIFI_ETHERNET_ADAPTER"
-
-/**
- * @def CA_PORT
- * @brief Port to listen for incoming data
- */
-#define CA_PORT   5283
-
-#define CA_MCAST_PORT   5298
-
-/**
- * @def CA_MULTICAST_IP
- * @brief Multicast IP Address
- */
-#define CA_MULTICAST_IP "224.0.1.187"
-
-/**
- * @var gNetworkCallback
- * @brief Network callback
- */
-static CANetworkChangeCallback gNetworkCallback = NULL;
-
-/**
- * @var gIsMulticastServerStarted
- * @brief Flag to check if multicast server is started
- */
-static int gIsMulticastServerStarted = 0;
-static u_mutex gMutexIsMulticastServerStarted = NULL;
-
-void CAInitializeMutex()
-{
-    u_mutex_init();
-    gMutexIsMulticastServerStarted = u_mutex_new();
-}
-
-int CAWIFIRegisterNetworkNotifications(CANetworkChangeCallback netCallback)
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    gNetworkCallback = netCallback; //TODO: Remove and set using API define in arduino specific file
-#ifdef __TIZEN__
-            if (netCallback != NULL)
-            {
-                CAInitializeWIFIAdapter();
-                CASetWIFINetworkChangeCallback(netCallback);
-            }
-            else
-            {
-                CADeinitializeWIFIAdapter();
-            }
-#endif
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback)
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-    CAResult_t ret = CA_STATUS_OK;
-
-    VERIFY_NON_NULL(registerCallback, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument");
-    VERIFY_NON_NULL(reqRespCallback, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument");
-    VERIFY_NON_NULL(netCallback, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument");
-
-    CAConnectivityHandler_t wifiHandler;
-    wifiHandler.startAdapter = CAStartWIFI;
-    wifiHandler.startListenServer = CAStartWIFIListeningServer;
-    wifiHandler.startDiscoverServer = CAStartWIFIDiscoveryServer;
-    wifiHandler.sendData = CASendWIFIUnicastData;
-    wifiHandler.sendDataToAll = CASendWIFIMulticastData;
-    wifiHandler.startNotifyServer = CAStartWIFINotifyRecvServers;
-    wifiHandler.sendNotification = CASendWIFINotification;
-    wifiHandler.GetnetInfo = CAGetWIFIInterfaceInformation;
-    wifiHandler.readData = CAReadWIFIData;
-    wifiHandler.stopAdapter = CAStopWIFI;
-    wifiHandler.terminate = CATerminateWifi;
-    registerCallback(wifiHandler, CA_WIFI);
-
-    CASetWIFINetworkPacketCallback(reqRespCallback);
-    CAWIFIRegisterNetworkNotifications(netCallback);
-    CAInitializeMutex();
-    CAInitializeServerMutex();
-    //ret = CAStartWIFIUnicastServer();
-
-    OCLog(INFO, WIFI_ETHERNET_ADAPTER_TAG, "IntializeWifi Success");
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return ret;
-}
-
-CAResult_t CAStartWIFI()
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-    int16_t unicastPort = CA_PORT;
-    CAResult_t ret = CA_STATUS_OK;
-
-#ifdef __TIZEN__
-    CASetIsStartServerInvoked();
-    int retVal = CAIsWIFIConnected();
-    if(retVal == 0)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "WIFI is not Connected");
-        return ret;
-    }
-#endif
-    /*Address is hardcoded as we are using Single Interface*/
-    ret = CAStartUnicastServer("0.0.0.0", &unicastPort);
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return ret;
-}
-
-CAResult_t CAStartWIFIListeningServer()
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    CAResult_t ret = CA_STATUS_OK;
-    int16_t multicastPort = CA_MCAST_PORT;
-
-    if (gIsMulticastServerStarted == 1)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Server is already Started");
-        return CA_STATUS_OK;
-    }
-#ifdef __TIZEN__
-    int retVal = CAIsWIFIConnected();
-    if(retVal == 0)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "WIFI is not Connected");
-        return CA_STATUS_FAILED;
-    }
-#endif
-    ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort);
-    if (ret == CA_STATUS_OK)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Multicast Server is Started Successfully");
-        u_mutex_lock(gMutexIsMulticastServerStarted);
-        gIsMulticastServerStarted = 1;
-        u_mutex_unlock(gMutexIsMulticastServerStarted);
-    }
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return ret;
-}
-
-CAResult_t CAStartWIFIDiscoveryServer()
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    CAResult_t ret = CA_STATUS_OK;
-    int16_t multicastPort = CA_MCAST_PORT;
-
-    if (gIsMulticastServerStarted == 1)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Server is already Started");
-        return CA_STATUS_OK;
-    }
-#ifdef __TIZEN__
-    /*int retVal = CAIsWIFIConnected();
-     if(retVal == 0)
-     {
-     OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "WIFI is not Connected");
-     return CA_STATUS_FAILED;
-     }*/ //VV
-#endif
-    ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort);
-    if (ret == CA_STATUS_OK)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Multicast Server is Started Successfully");
-        u_mutex_lock(gMutexIsMulticastServerStarted);
-        gIsMulticastServerStarted = 1;
-        u_mutex_unlock(gMutexIsMulticastServerStarted);
-    }
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return ret;
-}
-
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
-        uint32_t dataLen)
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    uint32_t dataSize = 0;
-
-    VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument", dataSize);
-    VERIFY_NON_NULL_RET(data, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument", dataSize);
-
-    if (dataLen <= 0)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Data Length is 0");
-        return dataSize;
-
-    }
-
-    dataSize = CAWIFISendData(remoteEndpoint->addressInfo.IP.ipAddress,
-            remoteEndpoint->addressInfo.IP.port, data, dataLen, 0);
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return dataSize;
-}
-
-uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLength)
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    uint32_t dataSize = 0;
-
-    VERIFY_NON_NULL_RET(data, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument", dataSize);
-
-    if (dataLength <= 0)
-    {
-        OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Data Length is 0");
-        return 0;
-
-    }
-    dataSize = CAWIFISendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, 1);
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return dataSize;
-}
-
-CAResult_t CAStartWIFINotifyRecvServers()
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t **info, uint32_t* size)
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-
-    VERIFY_NON_NULL(info, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument");
-    //VERIFY_NON_NULL(size, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument");
-    char localIpAddress[CA_IPADDR_SIZE];
-    int32_t localIpAddressLen = sizeof(localIpAddress);
-#ifdef __TIZEN__
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Getting WIFI address");
-    CAGetInterfaceAddress(localIpAddress, localIpAddressLen);
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Got WIFI address");
-#else
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Getting shield address");
-    arduinoGetInterfaceAddress(localIpAddress, localIpAddressLen);
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Got shield address");
-#endif //#if __ARDUINO__
-    /**
-     * Create local endpoint using util function
-     */
-    (*info) = CreateLocalEndpoint(CA_WIFI, localIpAddress, "WiFi");
-    if (NULL == (*info))
-    {
-        OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG, "Error while Createing Memory");
-        return CA_STATUS_FAILED;
-    }
-
-    (*size) = 1;
-
-    OCLog(INFO, WIFI_ETHERNET_ADAPTER_TAG, "GetWIFIInterfaceInformation success");
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAReadWIFIData()
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-#ifdef __ARDUINO__
-    arduoinoCheckServerData();
-#endif //#ifdef __ARDUINO__
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-CAResult_t CAStopWIFI()
-{
-    CAResult_t result = CA_STATUS_FAILED;
-    result = CAStopUnicastServer();
-    if (result != CA_STATUS_OK)
-    {
-        OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG, "Error while stopping UnicastServer");
-        return CA_STATUS_FAILED;
-    }
-#ifdef __TIZEN__
-    CAUnsetIsStartServerInvoked();
-#endif
-    result = CAStopMulticastServer();
-    if (result != CA_STATUS_OK)
-    {
-        OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG, "Error while stopping MulticastServer");
-        return CA_STATUS_FAILED;
-    }
-    else
-    {
-        u_mutex_lock(gMutexIsMulticastServerStarted);
-        gIsMulticastServerStarted = 0;
-        u_mutex_unlock(gMutexIsMulticastServerStarted);
-    }
-    return CA_STATUS_OK;
-}
-
-void CATerminateWifi()
-{
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN");
-    CAResult_t result = CA_STATUS_FAILED;
-
-    CASetWIFINetworkPacketCallback(NULL);
-    result = CAWIFIRegisterNetworkNotifications(NULL);
-    if (result != CA_STATUS_OK)
-    {
-        OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG,
-                "Error while wifiRegisterNetworkNotifications(NULL)");
-    }
-
-    OCLog(INFO, WIFI_ETHERNET_ADAPTER_TAG, "TerminateWifi Success");
-
-    OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT");
-    return;
-}
diff --git a/resource/csdk/connectivity/src/wifi_adapter/linux/cawifiadapter.c b/resource/csdk/connectivity/src/wifi_adapter/linux/cawifiadapter.c
deleted file mode 100644 (file)
index 298f50f..0000000
+++ /dev/null
@@ -1,190 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "cawifiadapter.h"
-
-#include "config.h"
-#include "coap.h"
-
-#include "cawificore.h"
-
-#include "logger.h"
-
-#define TAG PCF("CA")
-
-// received packet callback
-static CANetworkPacketReceivedCallback gWifiReceivedCallback = NULL;
-
-static void CAWiFiPacketReceiveCallback(const char* address, const char* data)
-{
-    OIC_LOG_V(DEBUG, TAG,
-            "CAWiFiPacketReceiveCallback, from: %s, data: %s", address, data);
-
-    // call the callback
-    if (gWifiReceivedCallback != NULL)
-    {
-        CARemoteEndpoint_t* endpoint = NULL;
-        endpoint = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t));
-
-        // set address
-        memset((void*) endpoint->addressInfo.IP.ipAddress, 0, CA_IPADDR_SIZE);
-        if (CA_IPADDR_SIZE > strlen(address))
-            strcpy((char*) endpoint->addressInfo.IP.ipAddress, address);
-
-        // set connectivity type
-        endpoint->connectivityType = CA_WIFI;
-
-        gWifiReceivedCallback(endpoint, data, strlen(data));
-    }
-}
-
-CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback)
-{
-    OIC_LOG(DEBUG, TAG, "IntializeWifi");
-
-    gWifiReceivedCallback = reqRespCallback;
-
-    // register handlers
-    CAConnectivityHandler_t handler;
-    memset(&handler, 0, sizeof(CAConnectivityHandler_t));
-
-    handler.startAdapter = CAStartWIFI;
-    handler.startListenServer = CAStartWIFIListeningServer;
-    handler.startDiscoverServer = CAStartWIFIDiscoveryServer;
-    handler.sendData = CASendWIFIUnicastData;
-    handler.sendDataToAll = CASendWIFIMulticastData;
-    handler.startNotifyServer = CAStartWIFINotifyRecvServers;
-    handler.sendNotification = CASendWIFINotification;
-    handler.GetnetInfo = CAGetWIFIInterfaceInformation;
-    handler.readData = CAReadWIFIData;
-    handler.stopAdapter = CAStopWIFI;
-    handler.terminate = CATerminateWIfI;
-
-    registerCallback(handler, CA_WIFI);
-
-    CAWiFiSetCallback(CAWiFiPacketReceiveCallback);
-
-    return 0;
-}
-
-void CATerminateWIfI()
-{
-    OIC_LOG(DEBUG, TAG, "TerminateWifi");
-
-    CAWiFiTerminate();
-}
-
-CAResult_t CAStartWIFI()
-{
-    OIC_LOG(DEBUG, TAG, "CAStartWIFI");
-    CAWiFiInitialize();
-
-    OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer");
-    CAWiFiStartUnicastServer("0.0.0.0", atoi("5283"));
-
-    return 0;
-}
-
-CAResult_t CAStopWIFI()
-{
-    OIC_LOG(DEBUG, TAG, "CAStopWIFI");
-
-    // ToDo:
-
-    return 0;
-}
-
-CAResult_t CAStartWIFIListeningServer()
-{
-    OIC_LOG(DEBUG, TAG, "StartWIFIListeningServer");
-
-    CAWiFiStartMulticastServer("0.0.0.0", atoi("5283"));
-
-    return 0;
-}
-
-CAResult_t CAStartWIFIDiscoveryServer()
-{
-    OIC_LOG(DEBUG, TAG, "StartWIFIDiscoveryServer");
-
-    CAWiFiStartMulticastServer("0.0.0.0", atoi("5283"));
-
-    return 0;
-}
-
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG(DEBUG, TAG, "SendWIFIUnicastData");
-
-    CAWiFiSendUnicastMessage(endpoint->addressInfo.IP.ipAddress, data, dataLen);
-
-    return 0;
-}
-
-uint32_t CASendWIFIMulticastData(void* data, uint32_t dataLen)
-{
-    OIC_LOG(DEBUG, TAG, "CASendWIFIMulticastData");
-
-    CAWiFiSendMulticastMessage("0.0.0.0", (char*) data);
-
-    return 0;
-}
-
-CAResult_t CAStartWIFINotifyRecvServers()
-{
-    OIC_LOG(DEBUG, TAG, "StartWIFINotifyRecvServers");
-
-    // ToDo:
-
-    return 0;
-}
-
-uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG(DEBUG, TAG, "SendWIFINotification");
-
-    // ToDo:
-
-    return 0;
-}
-
-CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size)
-{
-    OIC_LOG(DEBUG, TAG, "GetWIFIInterfaceInformation");
-
-    // ToDo:
-
-    return 0;
-}
-
-CAResult_t CAReadWIFIData()
-{
-    OIC_LOG(DEBUG, TAG, "Read WIFI Data");
-
-    // ToDo:
-
-    return 0;
-}
-
diff --git a/resource/csdk/connectivity/src/wifi_adapter/linux/cawificore.c b/resource/csdk/connectivity/src/wifi_adapter/linux/cawificore.c
deleted file mode 100644 (file)
index f3d4f5f..0000000
+++ /dev/null
@@ -1,500 +0,0 @@
-#include <stdio.h>
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <string.h>
-#include <pthread.h>
-#include <unistd.h>
-#include "cawificore.h"
-#include <errno.h>
-#include <sys/types.h>
-#include <ifaddrs.h>
-#include <netinet/in.h>
-#include <string.h>
-#include <arpa/inet.h>
-#include "logger.h"
-
-#define TAG PCF("CA")
-
-#define CA_MAX_BUFFER_SIZE 512  // Max length of buffer
-#define CA_UNICAST_PORT 5283 // The port on which to listen for incoming data
-int32_t unicast_socket;
-pthread_t pthread_unicast_server;
-pthread_t pthread_unicast_client;
-pthread_mutex_t mutex_unicast;
-pthread_cond_t sync_cond_unicast;
-int32_t unicast_send_thread_flag = 0; // 0: run, 1: stop
-
-char* target = NULL;
-void* list = NULL;
-
-#define CA_MULTICAST_ADDR "224.0.1.187"
-#define CA_MULTICAST_PORT 5683
-
-int32_t multicast_send_socket;
-struct sockaddr_in multicast_send_interface_addr;
-
-pthread_t pthread_multicast_server;
-pthread_t pthread_multicast_client;
-
-int32_t multicast_receive_socket;
-struct sockaddr_in multicast_receive_interface_addr;
-
-void* data_list = NULL;
-
-pthread_mutex_t mutex_multicast;
-pthread_cond_t sync_cond_multicast;
-int32_t multicast_send_thread_flag = 0; // 0: run, 1: stop
-
-CAPacketReceiveCallback gPacketReceiveCallback = NULL;
-
-void CAWiFiInitialize()
-{
-    OIC_LOG(DEBUG, TAG, "CAWiFiInitialize");
-
-    pthread_mutex_init(&mutex_unicast, NULL);
-
-    pthread_mutex_init(&mutex_multicast, NULL);
-
-    // [UDP Server]
-    struct sockaddr_in si_me;
-
-    // create a UDP socket
-    if ((unicast_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
-    {
-        OIC_LOG_V(DEBUG, TAG, "CAWiFiInit, creating socket failed");
-
-        return;
-    }
-
-    OIC_LOG_V(DEBUG, TAG, "CAWiFiInit, socket created");
-
-    // zero out the structure
-    memset((char *) &si_me, 0, sizeof(si_me));
-
-    si_me.sin_family = AF_INET;
-    si_me.sin_port = htons(CA_UNICAST_PORT);
-    si_me.sin_addr.s_addr = htonl(INADDR_ANY);
-
-    // bind socket to port
-    if (bind(unicast_socket, (struct sockaddr*) &si_me, sizeof(si_me)) == -1)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, binding socket failed");
-
-        return;
-    }
-
-    OIC_LOG(DEBUG, TAG, "CAWiFiInit, socket binded");
-
-    // [multicast sender]
-    uint32_t multiTTL = 1;
-
-    // 1. Set up a typical UDP socket
-    multicast_send_socket = socket(AF_INET, SOCK_DGRAM, 0);
-    if (multicast_send_socket < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Socket error");
-
-        return;
-    }
-
-    memset(&multicast_send_interface_addr, 0, sizeof(multicast_send_interface_addr));
-    multicast_send_interface_addr.sin_family = AF_INET;
-    multicast_send_interface_addr.sin_addr.s_addr = inet_addr(CA_MULTICAST_ADDR);
-    multicast_send_interface_addr.sin_port = htons(CA_MULTICAST_PORT);
-
-    // [multicast receiver]
-    // 1. Create a typical UDP socket and set Non-blocking for reading
-    multicast_receive_socket = socket(AF_INET, SOCK_DGRAM, 0);
-    if (multicast_receive_socket < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Socket error");
-
-        return;
-    }
-
-    // 2. Allow multiple sockets to use the same port number
-    int32_t ret_val = setsockopt(multicast_receive_socket, SOL_SOCKET, SO_REUSEADDR, &multiTTL,
-            sizeof(multiTTL));
-    if (ret_val < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to set REUSEADDR");
-    }
-
-    // 3. Set up the interface
-    memset(&multicast_receive_interface_addr, 0, sizeof(multicast_receive_interface_addr));
-    multicast_receive_interface_addr.sin_family = AF_INET;
-    multicast_receive_interface_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-    multicast_receive_interface_addr.sin_port = htons(CA_MULTICAST_PORT);
-
-    // 4. Bind to the interface
-    ret_val = bind(multicast_receive_socket, (struct sockaddr *) &multicast_receive_interface_addr,
-            sizeof(multicast_receive_interface_addr));
-    if (ret_val < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to bind socket");
-
-        return;
-    }
-
-    // 5. Join the multicast group
-    struct ip_mreq mreq;
-    memset(&mreq, 0, sizeof(mreq));
-    mreq.imr_multiaddr.s_addr = inet_addr(CA_MULTICAST_ADDR);
-    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
-    ret_val = setsockopt(multicast_receive_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
-            sizeof(mreq));
-    if (ret_val < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to join multicast group");
-
-        return;
-    }
-}
-
-void CAWiFiTerminate()
-{
-    OIC_LOG(DEBUG, TAG, "CAWiFiTerminate");
-
-    pthread_mutex_destroy(&mutex_unicast);
-
-    pthread_mutex_destroy(&mutex_multicast);
-
-    close(unicast_socket);
-
-    close(multicast_send_socket);
-
-    close(multicast_receive_socket);
-}
-
-int32_t CAWiFiSendUnicastMessage(const char* address, const char* data, int lengh)
-{
-    CASendUnicastMessage(address, data);
-
-    return 0;
-}
-
-int32_t CAWiFiSendMulticastMessage(const char* m_address, const char* data)
-{
-    CASendMulticastMessage(data);
-
-    return 0;
-}
-
-int32_t CAWiFiStartUnicastServer(const char* address, int port)
-{
-    OIC_LOG_V(DEBUG, TAG, "CAWiFiStartUnicastServer(%s, %d)", address, port);
-
-    int32_t result = pthread_create(&pthread_unicast_server, NULL, (void *) &CAUnicastReceiveThread,
-            (void *) NULL);
-    if (result < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, creating unicast_receive_thread failed");
-
-        return -1;
-    }
-
-    result = pthread_create(&pthread_unicast_client, NULL, (void *) &CAUnicastSendThread,
-            (void *) NULL);
-    if (result < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, creating unicast_send_thread failed");
-
-        return -1;
-    }
-
-    OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, receive & send thread created");
-
-    return 0;
-}
-
-int32_t CAWiFiStartMulticastServer(const char* m_address, int port)
-{
-    OIC_LOG_V(DEBUG, TAG, "CAWiFiStartMulticastServer(%s, %d)", m_address, port);
-
-    int32_t result = pthread_create(&pthread_multicast_server, NULL,
-            (void *) &CAMulticastReceiveThread, (void *) NULL);
-    if (result < 0)
-    {
-
-        return -1;
-    }
-
-    result = pthread_create(&pthread_multicast_client, NULL, (void *) &CAMulticastSendThread,
-            (void *) NULL);
-    if (result < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "creating receive_thread failed");
-
-        return -1;
-    }
-
-    return 0;
-}
-
-int32_t CAWiFiStopUnicastServer(int32_t server_id)
-{
-
-    CAStopUnicastSendThread();
-
-    return 0;
-}
-
-int32_t CAWiFiStopMulticastServer(int32_t server_id)
-{
-
-    CAStopMulticastSendThread();
-
-    return 0;
-}
-
-void CAWiFiSetCallback(CAPacketReceiveCallback callback)
-{
-    gPacketReceiveCallback = callback;
-}
-
-void* CAUnicastReceiveThread(void* data)
-{
-    OIC_LOG(DEBUG, TAG, "CAUnicastReceiveThread");
-
-    char buf[CA_MAX_BUFFER_SIZE];
-    int32_t recv_len;
-
-    struct sockaddr_in si_other;
-    int32_t slen = sizeof(si_other);
-
-    // keep listening for data
-    while (1)
-    {
-        OIC_LOG(DEBUG, TAG, "CAUnicastReceiveThread, Waiting for data...");
-        fflush(stdout);
-
-        memset(buf, 0, sizeof(char) * CA_MAX_BUFFER_SIZE);
-
-        // try to receive some data, this is a blocking call
-        if ((recv_len = recvfrom(unicast_socket, buf, CA_MAX_BUFFER_SIZE, 0,
-                (struct sockaddr *) &si_other, &slen)) == -1)
-        {
-            OIC_LOG(DEBUG, TAG, "CAUnicastReceiveThread, recv_len() error");
-            continue;
-        }
-
-        // print details of the client/peer and the data received
-        OIC_LOG_V(DEBUG, TAG, "CAUnicastReceiveThread, Received packet from %s:%d",
-                inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
-               OIC_LOG_V(DEBUG, TAG, "CAUnicastReceiveThread, Data: %s", buf);
-
-        if (gPacketReceiveCallback != NULL)
-        {
-            gPacketReceiveCallback(inet_ntoa(si_other.sin_addr), buf);
-        }
-    }
-
-    return (void*) 0;
-}
-
-void* CAUnicastSendThread(void* data)
-{
-    OIC_LOG(DEBUG, TAG, "CAUnicastSendThread");
-
-    while (!unicast_send_thread_flag)
-    {
-        pthread_mutex_lock(&mutex_unicast);
-
-        pthread_cond_wait(&sync_cond_unicast, &mutex_unicast);
-
-        pthread_mutex_unlock(&mutex_unicast);
-
-        if (unicast_send_thread_flag)
-            return (void*) 0;
-
-        CASendUnicastMessageImpl(target, list, strlen(list));
-    }
-
-    return (void*) 0;
-}
-
-void CASendUnicastMessage(char* address, void* data)
-{
-    target = address;
-    list = data;
-    unicast_send_thread_flag = 0;
-
-    pthread_cond_signal(&sync_cond_unicast);
-}
-
-int32_t CASendUnicastMessageImpl(const char* address, const char* data, int32_t lengh)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, address: %s, data: %s", address, data);
-
-    // [UDP Client]
-    struct sockaddr_in si_other;
-    int32_t slen = sizeof(si_other);
-
-    memset((char *) &si_other, 0, sizeof(si_other));
-
-    si_other.sin_family = AF_INET;
-    si_other.sin_port = htons(CA_UNICAST_PORT);
-    if (inet_aton(address, &si_other.sin_addr) == 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, inet_aton, error...");
-        return 0;
-    }
-
-    OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, to: %s, data: %s", address, data);
-    if (sendto(unicast_socket, data, strlen(data), 0, (struct sockaddr *) &si_other, slen) == -1)
-    {
-        OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, error...");
-
-        return 0;
-    }
-
-    return 0;
-}
-
-void CAStopUnicastSendThread()
-{
-    unicast_send_thread_flag = 1;
-
-    pthread_cond_signal(&sync_cond_unicast);
-}
-
-void* CAMulticastReceiveThread(void* data)
-{
-    OIC_LOG(DEBUG, TAG, "CAMulticastReceiveThread");
-
-    // 6. Read from the socket and print out a message when one is received
-    char msgbuf[CA_MAX_BUFFER_SIZE];
-
-    struct sockaddr_in client;
-    int32_t addrlen = sizeof(client);
-
-    OIC_LOG(DEBUG, TAG, "CAMulticastReceiveThread, waiting for input...");
-
-    while (1)
-    {
-        int32_t recv_bytes = recvfrom(multicast_receive_socket, msgbuf, CA_MAX_BUFFER_SIZE, 0,
-                (struct sockaddr *) &client, (socklen_t *) &addrlen);
-        if (recv_bytes < 0)
-        {
-            if (errno != EAGAIN)
-            {
-                OIC_LOG(DEBUG, TAG, "CAMulticastReceiveThread, error recvfrom");
-
-                return (void*) 0;
-            }
-
-            continue;
-        }
-
-        msgbuf[recv_bytes] = 0;
-
-        OIC_LOG_V(DEBUG, TAG, "Received msg: %s, size: %d", msgbuf, recv_bytes);
-
-        char* sender = inet_ntoa(client.sin_addr);
-        char local[INET_ADDRSTRLEN];
-        CAGetLocalAddress(local);
-        if (strcmp(sender, local) == 0)
-        {
-            OIC_LOG_V(DEBUG, TAG, "skip the local request (via multicast)");
-        }
-        else
-        {
-            if (gPacketReceiveCallback != NULL)
-            {
-                gPacketReceiveCallback(inet_ntoa(client.sin_addr), msgbuf);
-            }
-        }
-
-    }
-
-    return (void*) 0;
-}
-
-void* CAMulticastSendThread(void* data)
-{
-    OIC_LOG(DEBUG, TAG, "CAMulticastSendThread");
-
-    while (!multicast_send_thread_flag)
-    {
-        pthread_mutex_lock(&mutex_multicast);
-
-        pthread_cond_wait(&sync_cond_multicast, &mutex_multicast);
-
-        pthread_mutex_unlock(&mutex_multicast);
-
-        if (multicast_send_thread_flag)
-            return (void*) 0;
-
-        CASendMulticastMessageImpl(data_list);
-    }
-
-    return (void*) 0;
-}
-
-void CASendMulticastMessage(void* data)
-{
-    data_list = data;
-    multicast_send_thread_flag = 0;
-
-    pthread_cond_signal(&sync_cond_multicast);
-}
-
-int32_t CASendMulticastMessageImpl(const char* msg)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, sendto, data: %s", msg);
-
-    int32_t result = sendto(multicast_send_socket, msg, strlen(msg), 0,
-            (struct sockaddr *) &multicast_send_interface_addr,
-            sizeof(multicast_send_interface_addr));
-    if (result < 0)
-    {
-        OIC_LOG(DEBUG, TAG, "CASendMulticastMessageImpl, sending message error...");
-
-        return -1;
-    }
-
-    return 0;
-}
-
-void CAStopMulticastSendThread()
-{
-    multicast_send_thread_flag = 1;
-
-    pthread_cond_signal(&sync_cond_multicast);
-}
-
-void CAGetLocalAddress(char* addressBuffer)
-{
-    //char addressBuffer[INET_ADDRSTRLEN];
-    memset(addressBuffer, 0, INET_ADDRSTRLEN);
-
-    struct ifaddrs* ifAddrStruct = NULL;
-    struct ifaddrs* ifa = NULL;
-    void* tmpAddrPtr = NULL;
-
-    getifaddrs(&ifAddrStruct);
-
-    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
-    {
-        if (!ifa->ifa_addr)
-        {
-            continue;
-        }
-
-        if (ifa->ifa_addr->sa_family == AF_INET)
-        { // check it is IP4
-            // is a valid IP4 Address
-            tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
-
-            memset(addressBuffer, 0, INET_ADDRSTRLEN);
-            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
-
-            if (strcmp(addressBuffer, "127.0.0.1") == 0)
-                continue;
-        }
-    }
-
-    if (ifAddrStruct != NULL)
-        freeifaddrs(ifAddrStruct);
-}
-
diff --git a/resource/csdk/connectivity/test/SConscript b/resource/csdk/connectivity/test/SConscript
new file mode 100644 (file)
index 0000000..7189319
--- /dev/null
@@ -0,0 +1,93 @@
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+import os
+import os.path
+catest_env = env.Clone()
+
+src_dir = catest_env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+catest_env.PrependUnique(CPPPATH = [
+                '../../ocsocket/include',
+                '../../logger/include',
+                '../../stack/include',
+                '../../ocmalloc/include',
+                '../../extlibs/cjson',
+                '../../../oc_logger/include',
+                '../../../../extlibs/gtest/gtest-1.7.0/include'
+               ])
+
+tmplist = catest_env['LINKFLAGS'][:]
+if '-lpthread' in tmplist:
+    tmplist.remove('-lpthread')
+    catest_env.Replace(LINKFLAGS = tmplist)
+
+catest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+catest_env.AppendUnique(LIBS = ['pthread'])
+catest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+catest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
+catest_env.PrependUnique(LIBS = ['m',
+                                    'octbstack',
+                                    'connectivity_abstraction',
+                                    'coap',
+                                    'gtest',
+                                    'gtest_main'])
+
+target_os = env.get('TARGET_OS')
+
+if target_os not in ['arduino', 'darwin', 'ios']:
+       catest_env.AppendUnique(LIBS=['rt'])
+
+if target_os != 'darwin':
+    catest_env.PrependUnique(LIBS = ['oc_logger'])
+
+if env.get('SECURED') == '1':
+    catest_env.AppendUnique(LIBS = ['tinydtls'])
+
+if env.get('LOGGING'):
+       catest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+catests = catest_env.Program('catests', ['catests.cpp',
+                                         'caprotocolmessagetest.cpp',
+                                               'ca_api_unittest.cpp',
+                                               'camutex_tests.cpp'])
+
+Alias("test", [catests])
+
+env.AppendTarget('test')
+if env.get('TEST') == '1':
+        target_os = env.get('TARGET_OS')
+        if target_os == 'linux':
+                out_dir = env.get('BUILD_DIR')
+                result_dir = env.get('BUILD_DIR') + '/test_out/'
+                if not os.path.isdir(result_dir):
+                        os.makedirs(result_dir)
+                catest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
+                catest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+                catest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
+                ut = catest_env.Command ('ut', None, 'valgrind -q --leak-check=full --xml=yes --xml-file=resource_csdk_connectivity_test.memcheck ' + out_dir + 'resource/csdk/connectivity/test/catests')
+                AlwaysBuild ('ut')
diff --git a/resource/csdk/connectivity/test/ca_api_unittest.cpp b/resource/csdk/connectivity/test/ca_api_unittest.cpp
new file mode 100644 (file)
index 0000000..e684abd
--- /dev/null
@@ -0,0 +1,757 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "gtest/gtest.h"
+#include "cainterface.h"
+#include "cacommon.h"
+
+
+class CATests : public testing::Test {
+    protected:
+    virtual void SetUp() {
+        CAInitialize();
+    }
+
+    virtual void TearDown()
+    {
+        CATerminate();
+    }
+};
+
+void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
+void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
+CAResult_t checkGetNetworkInfo();
+CAResult_t checkSelectNetwork();
+
+
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+{
+
+}
+
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+{
+
+}
+
+static char* uri = NULL;
+static CARemoteEndpoint_t* tempRep = NULL;
+static CARequestInfo_t requestInfo;
+static CAInfo_t requestData;
+static CAInfo_t responseData;
+static CAResponseInfo_t responseInfo;
+static CAToken_t tempToken = NULL;
+static uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+static const char URI[] = "coap://10.11.12.13:4545/a/light";
+static const char RESOURCE_URI[] = "/a/light";
+
+static const char SECURE_INFO_DATA[] =
+                                    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[] =
+                                    "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+                                     "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
+
+#ifdef __WITH_DTLS__
+
+/**
+ * @def RS_IDENTITY
+ * @brief
+ */
+#define IDENTITY     ("1111111111111111")
+/* @def RS_CLIENT_PSK
+ * @brief
+ */
+#define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
+
+static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
+
+void clearDtlsCredentialInfo()
+{
+    printf("clearDtlsCredentialInfo IN\n");
+    if (pskCredsBlob)
+    {
+        // Initialize sensitive data to zeroes before freeing.
+        memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+        free(pskCredsBlob->creds);
+
+        memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
+        free(pskCredsBlob);
+        pskCredsBlob = NULL;
+    }
+    printf("clearDtlsCredentialInfo OUT\n");
+}
+
+// Internal API. Invoked by OC stack to retrieve credentials from this module
+void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+{
+    printf("CAGetDtlsPskCredentials IN\n");
+
+    if (pskCredsBlob != NULL)
+    {
+        *credInfo = pskCredsBlob;
+    }
+
+    printf("CAGetDtlsPskCredentials OUT\n");
+}
+
+int32_t SetCredentials()
+{
+    printf("SetCredentials IN\n");
+    pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
+
+    memset(pskCredsBlob, 0x0, sizeof(CADtlsPskCredsBlob_t));
+    memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+
+    pskCredsBlob->num = 1;
+
+    pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+
+    memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
+    memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
+
+    printf("SetCredentials OUT\n");
+    return 1;
+}
+#endif
+
+int main(int argc, char **argv)
+{
+    testing::InitGoogleTest(&argc, argv);
+    return RUN_ALL_TESTS();
+}
+
+// CAInitialize TC
+// check return value
+TEST(InitializeTest, TC_01_Positive_01)
+{
+    EXPECT_EQ(CA_STATUS_OK, CAInitialize());
+    CATerminate();
+}
+
+//CATerminate TC
+TEST_F(CATests, TerminateTest)
+{
+    CATerminate();
+
+    char* check = (char *) "terminate success";
+    EXPECT_STREQ(check, "terminate success");
+
+    CAInitialize();
+}
+// CAStartListeningServer TC
+// check return value
+TEST(StartListeningServerTest, DISABLED_TC_03_Positive_01)
+{
+    CASelectNetwork(CA_IPV4);
+    EXPECT_EQ(CA_STATUS_OK, CAStartListeningServer());
+}
+
+// CAStartDiscoveryServer TC
+// check return value
+TEST(StartDiscoveryServerTest, DISABLED_TC_04_Positive_01)
+{
+    EXPECT_EQ(CA_STATUS_OK, CAStartDiscoveryServer());
+}
+
+// CARegisterHandlerTest TC
+// check return value
+TEST_F(CATests, RegisterHandlerTest)
+{
+    CARegisterHandler(request_handler, response_handler);
+    char* check = (char *) "registerHandler success";
+    EXPECT_STREQ(check, "registerHandler success");
+}
+
+// CACreateRemoteEndpoint TC
+// check return value
+TEST_F(CATests, CreateRemoteEndpointTestGood)
+{
+    uri = (char *) URI;
+
+    EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep));
+
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// check remoteEndpoint and values of remoteEndpoint
+TEST_F(CATests, CreateRemoteEndpointTestValues)
+{
+    uri = (char *) URI;
+
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    EXPECT_TRUE(tempRep != NULL);
+
+    if (tempRep != NULL)
+    {
+        EXPECT_STRNE(NULL, tempRep->resourceUri);
+    }
+
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// check return value when uri is NULL
+TEST_F(CATests, CreateRemoteEndpointTestBad)
+{
+    uri = NULL;
+
+    EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep));
+
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// check values of remoteEndpoint when uri is NULL
+TEST_F(CATests, CreateRemoteEndpointTestWithNullUri)
+{
+    uri = NULL;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    if (tempRep != NULL)
+    {
+        EXPECT_STREQ(NULL, tempRep->resourceUri);
+
+    }
+
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// CADestroyRemoteEndpoint TC
+// check destroyed remoteEndpoint
+TEST_F(CATests, DestroyRemoteEndpointTest)
+{
+    uri = (char *) URI;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    CADestroyRemoteEndpoint(tempRep);
+    tempRep = NULL;
+
+    char * check = (char *) "destroy success";
+    EXPECT_STREQ(check, "destroy success");
+}
+
+// CAGerateToken TC
+// check return value
+TEST_F(CATests, GenerateTokenTestGood)
+{
+    EXPECT_EQ(CA_STATUS_OK, CAGenerateToken(&tempToken, tokenLength));
+
+    CADestroyToken(tempToken);
+}
+
+// check return value when CAGenerateToken is passed a NULL instead a valid pointer
+TEST_F(CATests, GenerateTokenTestBad)
+{
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CAGenerateToken(NULL, tokenLength));
+}
+
+// CADestroyToken TC
+// check destroyed token
+TEST_F(CATests, DestroyTokenTest)
+{
+    CAGenerateToken(&tempToken, tokenLength);
+    CADestroyToken(tempToken);
+
+    char * check = (char *) "destroy success";
+    EXPECT_STREQ(check, "destroy success");
+}
+
+// CAFindResource TC
+// check return value
+TEST(FindResourceTest, DISABLED_TC_14_Positive_01)
+{
+    uri = (char *) RESOURCE_URI;
+
+    CAGenerateToken(&tempToken, tokenLength);
+    EXPECT_EQ(CA_STATUS_OK, CAFindResource(uri, tempToken, tokenLength));
+    CADestroyToken(tempToken);
+}
+
+// check return value when uri is NULL
+TEST_F(CATests, FindResourceTest)
+{
+    uri = NULL;
+    CAGenerateToken(&tempToken, tokenLength);
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CAFindResource(uri, tempToken, tokenLength));
+    CADestroyToken(tempToken);
+}
+
+// CASendRequest TC
+// check return value
+TEST(SendRequestTest, DISABLED_TC_16_Positive_01)
+{
+    uri = (char *) URI;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    memset(&requestData, 0, sizeof(CAInfo_t));
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    int length = strlen(NORMAL_INFO_DATA) + strlen("a/light");
+    requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+
+    if(!requestData.payload)
+    {
+        CADestroyToken(tempToken);
+        FAIL() << "requestData.payload allocation failed";
+    }
+
+    snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
+    requestData.type = CA_MSG_NONCONFIRM;
+
+    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    EXPECT_EQ(CA_STATUS_OK, CASendRequest(tempRep, &requestInfo));
+
+    CADestroyToken(tempToken);
+
+    free(requestData.payload);
+
+    CADestroyRemoteEndpoint(tempRep);
+    tempRep = NULL;
+
+}
+
+// check return value when uri is NULL
+TEST_F(CATests, SendRequestTestWithNullURI)
+{
+    uri = NULL;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    memset(&requestData, 0, sizeof(CAInfo_t));
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    int length = strlen(NORMAL_INFO_DATA) + strlen("a/light");
+    requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+
+    if(!requestData.payload)
+    {
+        CADestroyToken(tempToken);
+        FAIL() << "requestData.payload allocation failed";
+    }
+
+    snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
+    requestData.type = CA_MSG_NONCONFIRM;
+
+    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequest(tempRep, &requestInfo));
+
+    CADestroyToken(tempToken);
+
+    free(requestData.payload);
+
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// check return value when a NULL is passed instead of a valid CARequestInfo_t address
+TEST_F(CATests, SendRequestTestWithNullAddr)
+{
+    uri = (char *) URI;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequest(tempRep, NULL));
+
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// CASendResponse TC
+// check return value
+TEST(SendResponseTest, DISABLED_TC_19_Positive_01)
+{
+    uri = (char *) URI;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    memset(&responseData, 0, sizeof(CAInfo_t));
+    responseData.type = CA_MSG_NONCONFIRM;
+    responseData.messageId = 1;
+    responseData.payload = (char *) "response payload";
+
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+    responseInfo.result = CA_SUCCESS;
+    responseInfo.info = responseData;
+
+    EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
+
+    CADestroyToken(tempToken);
+    CADestroyRemoteEndpoint(tempRep);
+    tempRep = NULL;
+}
+
+// check return value when uri is NULL
+TEST(SendResponseTest, DISABLED_TC_20_Negative_01)
+{
+    uri = NULL;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    memset(&responseData, 0, sizeof(CAInfo_t));
+    responseData.type = CA_MSG_NONCONFIRM;
+    responseData.messageId = 1;
+    responseData.payload = (char *) "response payload";
+
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+    responseInfo.result = CA_SUCCESS;
+    responseInfo.info = responseData;
+
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendResponse(tempRep, &responseInfo));
+
+    CADestroyToken(tempToken);
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// check return value NULL is passed instead of a valid CAResponseInfo_t address
+TEST_F(CATests, SendResponseTest)
+{
+    uri = (char *) URI;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendResponse(tempRep, NULL));
+
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// CASendNotification TC
+// check return value
+TEST(SendNotificationTest, DISABLED_TC_22_Positive_01)
+{
+    uri = (char *) URI;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    memset(&responseData, 0, sizeof(CAInfo_t));
+    responseData.type = CA_MSG_NONCONFIRM;
+    responseData.payload = (char *) "Temp Notification Data";
+
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+    responseInfo.result = CA_SUCCESS;
+    responseInfo.info = responseData;
+
+    EXPECT_EQ(CA_STATUS_OK, CASendNotification(tempRep, &responseInfo));
+
+    CADestroyToken(tempToken);
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// check return value when uri is NULL
+TEST_F(CATests, SendNotificationTest)
+{
+    uri = NULL;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+
+    memset(&responseData, 0, sizeof(CAInfo_t));
+    responseData.type = CA_MSG_NONCONFIRM;
+    responseData.payload = (char *) "Temp Notification Data";
+
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+    responseInfo.result = CA_SUCCESS;
+    responseInfo.info = responseData;
+
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendNotification(tempRep, &responseInfo));
+
+    CADestroyToken(tempToken);
+    if (tempRep != NULL)
+    {
+        CADestroyRemoteEndpoint(tempRep);
+        tempRep = NULL;
+    }
+}
+
+// CAAdvertiseResource TC
+// check return value
+TEST(AdvertiseResourceTest, DISABLED_TC_24_Positive_01)
+{
+    uri = (char *) RESOURCE_URI;
+    int optionNum = 2;
+
+    CAHeaderOption_t* headerOpt;
+    headerOpt = (CAHeaderOption_t *) calloc(1, optionNum * sizeof(CAHeaderOption_t));
+
+    if(!headerOpt)
+    {
+        FAIL() <<"Allocation for headerOpt failed";
+    }
+
+    char* tmpOptionData1 = (char *) "Hello";
+    size_t tmpOptionDataLen = (strlen(tmpOptionData1) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
+            strlen(tmpOptionData1) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
+    headerOpt[0].optionID = 3000;
+    memcpy(headerOpt[0].optionData, tmpOptionData1, tmpOptionDataLen);
+    headerOpt[0].optionLength = (uint16_t) tmpOptionDataLen;
+
+    char* tmpOptionData2 = (char *) "World";
+    tmpOptionDataLen = (strlen(tmpOptionData2) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
+                strlen(tmpOptionData2) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
+    headerOpt[1].optionID = 3001;
+    memcpy(headerOpt[1].optionData, tmpOptionData2, tmpOptionDataLen);
+    headerOpt[1].optionLength = (uint16_t) tmpOptionDataLen;
+
+    CAGenerateToken(&tempToken, tokenLength);
+
+    EXPECT_EQ(CA_STATUS_OK, CAAdvertiseResource(uri, tempToken, tokenLength,
+                                                headerOpt, (uint8_t )optionNum));
+
+    CADestroyToken(tempToken);
+
+    free(headerOpt);
+}
+
+// check return value when uri is NULL
+TEST_F(CATests, AdvertiseResourceTest)
+{
+    uri = NULL;
+    int optionNum = 2;
+
+    CAHeaderOption_t* headerOpt;
+    headerOpt = (CAHeaderOption_t *) calloc(1, optionNum * sizeof(CAHeaderOption_t));
+
+    if(!headerOpt)
+    {
+        FAIL() << "Allocation for headerOpt failed";
+    }
+
+    char* tmpOptionData1 = (char *) "Hello";
+    size_t tmpOptionDataLen = (strlen(tmpOptionData1) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
+            strlen(tmpOptionData1) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
+    headerOpt[0].optionID = 3000;
+    memcpy(headerOpt[0].optionData, tmpOptionData1, tmpOptionDataLen);
+    headerOpt[0].optionLength = (uint16_t) tmpOptionDataLen;
+
+    char* tmpOptionData2 = (char *) "World";
+    tmpOptionDataLen = (strlen(tmpOptionData2) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
+                strlen(tmpOptionData2) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
+    headerOpt[1].optionID = 3001;
+    memcpy(headerOpt[1].optionData, tmpOptionData2, tmpOptionDataLen);
+    headerOpt[1].optionLength = (uint16_t) tmpOptionDataLen;
+
+    CAGenerateToken(&tempToken, tokenLength);
+
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CAAdvertiseResource(uri, tempToken, tokenLength,
+                                                           headerOpt, (uint8_t )optionNum));
+
+    CADestroyToken(tempToken);
+
+    free(headerOpt);
+}
+
+// CASelectNewwork TC
+// check return value
+TEST_F(CATests, SelectNetworkTestGood)
+{
+    CAResult_t res = checkSelectNetwork();
+    EXPECT_EQ(CA_STATUS_OK, res);
+}
+
+CAResult_t checkSelectNetwork()
+{
+    CAResult_t res = CASelectNetwork(CA_IPV4);
+
+    if (CA_STATUS_OK == res)
+    {
+        EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_IPV4));
+        return CA_STATUS_OK;
+    }
+    if (CA_NOT_SUPPORTED == res)
+    {
+        EXPECT_EQ(CA_STATUS_FAILED, CAUnSelectNetwork(CA_IPV4));
+        return CA_STATUS_OK;
+    }
+
+    return res;
+}
+
+// check return value when selected network is disable
+TEST_F(CATests, SelectNetworkTestBad)
+{
+    //Select disable network
+    EXPECT_EQ(CA_NOT_SUPPORTED, CASelectNetwork(1000));
+}
+
+// check return value when selected network is disable
+TEST_F(CATests, UnSelectNetworkTest)
+{
+    //UnSelect disable network
+    EXPECT_EQ(CA_STATUS_FAILED, CAUnSelectNetwork(1000));
+}
+
+// CAHandlerRequestResponse TC
+// check return value
+TEST_F(CATests, HandlerRequestResponseTest)
+{
+    EXPECT_EQ(CA_STATUS_OK, CAHandleRequestResponse());
+}
+
+// CASendRequestToAll TC
+// check return value
+TEST(SendRequestToAllTest, DISABLED_TC_31_Positive_01)
+{
+    CASelectNetwork(CA_IPV4);
+
+    uri = (char *) RESOURCE_URI;
+    CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+    CAGroupEndpoint_t *group = NULL;
+    group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+    if(!group)
+    {
+        FAIL() << "Allocation for group failed";
+    }
+
+    group->transportType = tempRep->transportType;
+    group->resourceUri = tempRep->resourceUri;
+
+    memset(&requestData, 0, sizeof(CAInfo_t));
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    requestData.payload = (char *) "Temp Json Payload";
+    requestData.type = CA_MSG_NONCONFIRM;
+    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    EXPECT_EQ(CA_STATUS_OK, CASendRequestToAll(group, &requestInfo));
+
+    CADestroyToken(tempToken);
+
+    CADestroyRemoteEndpoint(tempRep);
+    tempRep = NULL;
+
+    free(group);
+}
+
+// check return value when group->resourceUri is NULL
+TEST(SendRequestToAllTest, DISABLED_TC_32_Negative_01)
+{
+    uri = (char *) RESOURCE_URI;
+    CAGroupEndpoint_t *group = NULL;
+
+    memset(&requestData, 0, sizeof(CAInfo_t));
+    CAGenerateToken(&tempToken, tokenLength);
+    requestData.token = tempToken;
+    requestData.tokenLength = tokenLength;
+
+    requestData.payload = (char *) "Temp Json Payload";
+    requestData.type = CA_MSG_NONCONFIRM;
+    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+    requestInfo.method = CA_GET;
+    requestInfo.info = requestData;
+
+    EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequestToAll(group, &requestInfo));
+
+    CADestroyToken(tempToken);
+}
+
+// CAGetNetworkInformation TC
+// check return value
+TEST_F (CATests, GetNetworkInformationTestGood)
+{
+    EXPECT_EQ(CA_STATUS_OK, checkGetNetworkInfo());
+}
+
+TEST_F(CATests, RegisterDTLSCredentialsHandlerTest)
+{
+#ifdef __WITH_DTLS__
+    if (SetCredentials() == 0)
+    {
+        printf("SetCredentials failed\n");
+    }
+
+    EXPECT_EQ(CA_STATUS_OK, CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials));
+#endif
+}
+
+CAResult_t checkGetNetworkInfo()
+{
+    CALocalConnectivity_t *tempInfo = NULL;
+    uint32_t tempSize = 0;
+
+    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+
+    free(tempInfo);
+
+    if (CA_STATUS_OK == res || CA_ADAPTER_NOT_ENABLED == res ||
+            CA_NOT_SUPPORTED == res)
+    {
+        return CA_STATUS_OK;
+    }
+    else
+    {
+        return CA_STATUS_FAILED;
+    }
+}
diff --git a/resource/csdk/connectivity/test/camutex_tests.cpp b/resource/csdk/connectivity/test/camutex_tests.cpp
new file mode 100644 (file)
index 0000000..98def7e
--- /dev/null
@@ -0,0 +1,554 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+//
+//*********************************************************************
+
+// Defining _POSIX_C_SOURCE macro with 200809L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2008 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2008 base specification,
+// Refer http://pubs.opengroup.org/stage7tc1/
+//
+// For this specific file, see use of usleep
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif // _POSIX_C_SOURCE
+
+#include "gtest/gtest.h"
+
+#include <camutex.h>
+#include <cathreadpool.h>
+
+#include <time.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+//#define DEBUG_VERBOSE 1
+
+// The debug print lines are left in for now since the output can be
+// helpful for developers trying to debug or extend the tests.
+// However, by default they are #defined out so as not to get in
+// the way of normal test runs.
+#ifdef DEBUG_VERBOSE
+#define DBG_printf(...) printf(__VA_ARGS__)
+#else
+#define DBG_printf(...)
+#endif
+
+static const uint64_t USECS_PER_SEC = 1000000;
+
+static const uint64_t USECS_PER_MSEC = 1000;
+
+static const int MINIMAL_LOOP_SLEEP = 20;
+static const int MINIMAL_EXTRA_SLEEP = 25;
+
+uint64_t getAbsTime()
+{
+    uint64_t currentTime=0;
+#if _POSIX_TIMERS > 0
+    struct timespec ts;
+    clock_gettime(CLOCK_MONOTONIC, &ts);
+    currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#else
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
+#endif
+    return currentTime;
+}
+
+TEST(MutexTests, TC_01_CREATE)
+{
+    ca_mutex mymutex = ca_mutex_new();
+
+    EXPECT_TRUE(mymutex != NULL);
+    if (mymutex != NULL)
+    {
+        ca_mutex_free(mymutex);
+    }
+}
+
+TEST(MutexTests, TC_02_TRY_LOCK)
+{
+    ca_mutex mymutex = ca_mutex_new();
+
+    EXPECT_TRUE(mymutex != NULL);
+    if (mymutex != NULL)
+    {
+        EXPECT_TRUE(ca_mutex_trylock(mymutex)); // acquire it
+
+        ca_mutex_unlock(mymutex); // release it
+
+        ca_mutex_lock(mymutex); // acquire it
+
+        EXPECT_FALSE(ca_mutex_trylock(mymutex)); // he should be lock
+
+        EXPECT_FALSE(ca_mutex_trylock(NULL));
+
+        ca_mutex_unlock(mymutex); // release it
+        ca_mutex_free(mymutex);
+
+        EXPECT_FALSE(ca_mutex_trylock(NULL));
+    }
+}
+
+typedef struct _tagFunc1
+{
+    ca_mutex mutex;
+    volatile bool thread_up;
+    volatile bool finished;
+} _func1_struct;
+
+void mutexFunc(void *context)
+{
+    _func1_struct* pData = (_func1_struct*) context;
+
+    DBG_printf("Thread: trying to lock\n");
+
+    // setting the flag must be done before lock attempt, as the test
+    // thread starts off with the mutex locked
+    pData->thread_up = true;
+    ca_mutex_lock(pData->mutex);
+
+    DBG_printf("Thread: got lock\n");
+    usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+    DBG_printf("Thread: releasing\n");
+
+    pData->finished = true; // assignment guarded by lock
+
+    ca_mutex_unlock(pData->mutex);
+}
+
+TEST(MutexTests, TC_03_THREAD_LOCKING)
+{
+    ca_thread_pool_t mythreadpool;
+
+    EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
+
+    _func1_struct pData = {};
+
+    pData.mutex = ca_mutex_new();
+
+    EXPECT_TRUE(pData.mutex != NULL);
+    if (pData.mutex != NULL)
+    {
+        DBG_printf("test: Holding mutex in test\n");
+        ca_mutex_lock(pData.mutex);
+
+        DBG_printf("test: starting thread\n");
+        //start thread
+        EXPECT_EQ(CA_STATUS_OK,
+                  ca_thread_pool_add_task(mythreadpool, mutexFunc, &pData));
+
+        DBG_printf("test: waiting for thread to be up.\n");
+
+        while (!pData.thread_up)
+        {
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+        }
+        // At this point the thread is running and close to trying to lock.
+        // For test purposes only, use of condition variables is being avoided,
+        // so a minor sleep is used.
+        usleep(MINIMAL_EXTRA_SLEEP * USECS_PER_MSEC);
+
+        DBG_printf("test: unlocking\n");
+
+        ca_mutex_unlock(pData.mutex);
+
+        DBG_printf("test: waiting for thread to release\n");
+        while (!pData.finished)
+        {
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+        }
+
+        ca_mutex_lock(pData.mutex);
+
+        // Cleanup Everything
+
+        ca_mutex_unlock(pData.mutex);
+        ca_mutex_free(pData.mutex);
+    }
+
+    ca_thread_pool_free(mythreadpool);
+}
+
+TEST(ConditionTests, TC_01_CREATE)
+{
+    ca_cond mycond = ca_cond_new();
+
+    EXPECT_TRUE(mycond != NULL);
+    if (mycond != NULL)
+    {
+        ca_cond_free(mycond);
+    }
+}
+
+// Normally we would use one pair of mutex/cond-var communicating to the
+// worker threads and one pair back to the main thread. However since
+// testing the ca_cond itself is the point, only one pair is used here.
+typedef struct _tagFunc2
+{
+    int id;
+    ca_mutex mutex;
+    ca_cond condition;
+    volatile bool thread_up;
+    volatile bool finished;
+} _func2_struct;
+
+void condFunc(void *context)
+{
+    _func2_struct* pData = (_func2_struct*) context;
+
+    DBG_printf("Thread_%d: waiting on condition\n", pData->id);
+
+    ca_mutex_lock(pData->mutex);
+
+    pData->thread_up = true;
+
+    ca_cond_wait(pData->condition, pData->mutex);
+
+    pData->finished = true; // assignment guarded by lock
+
+    ca_mutex_unlock(pData->mutex);
+
+    DBG_printf("Thread_%d: completed.\n", pData->id);
+}
+
+TEST(ConditionTests, TC_02_SIGNAL)
+{
+    const int MAX_WAIT_MS = 2000;
+    ca_thread_pool_t mythreadpool;
+
+    EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
+
+    ca_mutex sharedMutex = ca_mutex_new();
+    ca_cond sharedCond = ca_cond_new();
+
+    _func2_struct pData1 =
+    { 1, sharedMutex, sharedCond, false, false };
+    _func2_struct pData2 =
+    { 2, sharedMutex, sharedCond, false, false };
+
+    EXPECT_TRUE(pData1.mutex != NULL);
+    if (pData1.mutex != NULL)
+    {
+        DBG_printf("starting thread\n");
+        // start threads
+        EXPECT_EQ(CA_STATUS_OK,
+                  ca_thread_pool_add_task(mythreadpool, condFunc, &pData1));
+        EXPECT_EQ(CA_STATUS_OK,
+                  ca_thread_pool_add_task(mythreadpool, condFunc, &pData2));
+
+        DBG_printf("test    : sleeping\n");
+
+        while (!pData1.thread_up || !pData2.thread_up)
+        {
+            // For test purposes only, use of condition variables is being
+            // avoided, so a minor sleep is used.
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+        }
+        // At this point the threads are running and both have locked. One
+        // has already started waiting on the condition and the other is at
+        // least close.
+
+        ca_mutex_lock(sharedMutex);
+        // once the lock is acquired it means both threads were waiting.
+        DBG_printf("test    : signaling first thread\n");
+        ca_cond_signal(sharedCond);
+        ca_mutex_unlock(sharedMutex);
+
+        // At this point either of the child threads might lock the mutex in
+        // their cond_wait call, or this test thread might lock it again if
+        // mutex_lock gets executed before the child threads can react to
+        // the signaling. Thus we wait on their flag variables
+        int waitCount = 1; // start with 1 for minumum targetWait value.
+        while (!pData1.finished && !pData2.finished)
+        {
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+            waitCount++;
+        }
+
+        // As a rough hueristic wait twice as long for the second to possibly
+        // finish:
+        int targetWait = waitCount * 2;
+        for (int i = 0;
+             (i < targetWait) && (!pData1.finished && !pData2.finished); i++)
+        {
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+        }
+        usleep(MINIMAL_EXTRA_SLEEP);
+
+        // only one should be finished
+        ca_mutex_lock(sharedMutex);
+        EXPECT_NE(pData1.finished, pData2.finished);
+        ca_mutex_unlock(sharedMutex);
+
+        DBG_printf("test    : signaling another thread\n");
+
+        ca_mutex_lock(sharedMutex);
+        ca_cond_signal(sharedCond);
+        ca_mutex_unlock(sharedMutex);
+
+        waitCount = 0;
+        while ((!pData1.finished || !pData2.finished)
+               && ((waitCount * MINIMAL_EXTRA_SLEEP) < MAX_WAIT_MS))
+        {
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+            waitCount++;
+        }
+
+        // both should finally be finished
+        EXPECT_TRUE(pData1.finished);
+        EXPECT_TRUE(pData2.finished);
+
+        // Cleanup Everything
+
+        ca_mutex_free(pData1.mutex);
+    }
+
+    ca_cond_free(pData1.condition);
+
+    ca_thread_pool_free(mythreadpool);
+}
+
+TEST(ConditionTests, TC_03_BROADCAST)
+{
+    const int MAX_WAIT_MS = 2000;
+    ca_thread_pool_t mythreadpool;
+
+    EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
+
+    ca_mutex sharedMutex = ca_mutex_new();
+    ca_cond sharedCond = ca_cond_new();
+
+    _func2_struct pData1 =
+    { 1, sharedMutex, sharedCond, false, false };
+    _func2_struct pData2 =
+    { 2, sharedMutex, sharedCond, false, false };
+
+    EXPECT_TRUE(pData1.mutex != NULL);
+    if (pData1.mutex != NULL)
+    {
+        DBG_printf("starting thread\n");
+        // start threads
+        EXPECT_EQ(CA_STATUS_OK,
+                  ca_thread_pool_add_task(mythreadpool, condFunc, &pData1));
+        EXPECT_EQ(CA_STATUS_OK,
+                  ca_thread_pool_add_task(mythreadpool, condFunc, &pData2));
+
+        DBG_printf("test    : sleeping\n");
+
+        while (!pData1.thread_up || !pData2.thread_up)
+        {
+            // For test purposes only, use of condition variables is being
+            // avoided, so a minor sleep is used.
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+        }
+        // At this point the threads are running and both have locked. One
+        // has already started waiting on the condition and the other is at
+        // least close.
+
+        DBG_printf("test    : signaling all threads\n");
+
+        ca_mutex_lock(sharedMutex);
+        // once the lock is acquired it means both threads were waiting.
+        ca_cond_broadcast(sharedCond);
+        ca_mutex_unlock(sharedMutex);
+
+        int waitCount = 0;
+        while ((!pData1.finished || !pData2.finished)
+               && ((waitCount * MINIMAL_EXTRA_SLEEP) < MAX_WAIT_MS))
+        {
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+            waitCount++;
+        }
+
+        // both should finally be finished
+        EXPECT_TRUE(pData1.finished);
+        EXPECT_TRUE(pData2.finished);
+
+        // Cleanup Everything
+
+        ca_mutex_free(sharedMutex);
+    }
+
+    ca_cond_free(sharedCond);
+
+    ca_thread_pool_free(mythreadpool);
+}
+
+TEST(CondTests, TC_04_TIMECHECK)
+{
+    uint64_t begin = getAbsTime();
+
+    usleep(1);
+
+    uint64_t end = getAbsTime();
+
+    EXPECT_LT(begin, end); // should never be the same value
+}
+
+void timedFunc(void *context)
+{
+    _func2_struct* pData = (_func2_struct*) context;
+
+    DBG_printf("Thread_%d: waiting for timeout \n", pData->id);
+
+    ca_mutex_lock(pData->mutex);
+
+    uint64_t abs = USECS_PER_SEC / 2; // 1/2 seconds
+
+    // test UTIMEDOUT
+    CAWaitResult_t ret = ca_cond_wait_for(pData->condition,
+                                          pData->mutex, abs);
+    EXPECT_EQ(CA_WAIT_TIMEDOUT, ret);
+
+    pData->thread_up = true;
+
+    DBG_printf("Thread_%d: waiting for signal \n", pData->id);
+
+    abs = 5 * USECS_PER_SEC; // 5 seconds
+
+    // test signal
+    ret = ca_cond_wait_for(pData->condition, pData->mutex, abs);
+    EXPECT_EQ(CA_WAIT_SUCCESS, ret);
+
+    pData->finished = true; // assignment guarded by lock
+
+    ca_mutex_unlock(pData->mutex);
+
+    DBG_printf("Thread_%d: stopping\n", pData->id);
+}
+
+TEST(ConditionTests, TC_05_WAIT)
+{
+    const int MAX_WAIT_MS = 5000;
+    ca_thread_pool_t mythreadpool;
+
+    EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
+
+    ca_mutex sharedMutex = ca_mutex_new();
+    ca_cond sharedCond = ca_cond_new();
+
+    _func2_struct pData1 =
+    { 1, sharedMutex, sharedCond, false, false };
+
+    EXPECT_TRUE(sharedMutex != NULL);
+    if (sharedMutex != NULL)
+    {
+        DBG_printf("test    : starting thread\n");
+        //start thread
+        EXPECT_EQ(CA_STATUS_OK,
+                  ca_thread_pool_add_task(mythreadpool, timedFunc, &pData1));
+
+        DBG_printf("test    : waiting for thread to timeout once.\n");
+
+        while (!pData1.thread_up)
+        {
+            // For test purposes only, use of condition variables is being
+            // avoided, so a minor sleep is used.
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+        }
+
+
+        DBG_printf("test    : signaling first thread\n");
+
+        ca_mutex_lock(sharedMutex);
+        ca_cond_signal(sharedCond);
+        ca_mutex_unlock(sharedMutex);
+
+        int waitCount = 0;
+        while (!pData1.finished
+               && ((waitCount * MINIMAL_EXTRA_SLEEP) < MAX_WAIT_MS))
+        {
+            usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
+            waitCount++;
+        }
+
+        EXPECT_TRUE(pData1.finished); // thread should finally be finished
+
+        // Cleanup Everything
+
+        ca_mutex_free(sharedMutex);
+    }
+
+    ca_cond_free(sharedCond);
+
+    ca_thread_pool_free(mythreadpool);
+}
+
+// Disabled because this should no longer be a valid test
+TEST(ConditionTests, DISABLED_TC_06_INVALIDWAIT)
+{
+
+    ca_mutex sharedMutex = ca_mutex_new();
+    ca_cond sharedCond = ca_cond_new();
+
+    ca_mutex_lock(sharedMutex);
+
+    int ret = ca_cond_wait_for(NULL, sharedMutex, 5000);
+    EXPECT_EQ(CA_WAIT_INVAL,ret);
+
+    ret = ca_cond_wait_for(sharedCond, NULL, 5000);
+    EXPECT_EQ(CA_WAIT_INVAL,ret);
+
+    ret = ca_cond_wait_for(NULL, NULL, 5000);
+    EXPECT_EQ(CA_WAIT_INVAL,ret);
+
+    ca_mutex_unlock(sharedMutex);
+
+    // Cleanup Everything
+
+    ca_mutex_free(sharedMutex);
+
+    ca_cond_free(sharedCond);
+}
+
+TEST(ConditionTests, TC_07_WAITDURATION)
+{
+    const double TARGET_WAIT = 1.125;
+
+    ca_mutex sharedMutex = ca_mutex_new();
+    ca_cond sharedCond = ca_cond_new();
+
+    ca_mutex_lock(sharedMutex);
+
+    uint64_t beg = getAbsTime();
+
+    CAWaitResult_t ret = ca_cond_wait_for(sharedCond, sharedMutex,
+                                          TARGET_WAIT * USECS_PER_SEC);
+    EXPECT_EQ(CA_WAIT_TIMEDOUT,ret);
+
+    uint64_t end = getAbsTime();
+
+    double secondsDiff = (end - beg) / (double) USECS_PER_SEC;
+
+    EXPECT_NEAR(TARGET_WAIT, secondsDiff, 0.05);
+
+    ca_mutex_unlock(sharedMutex);
+
+    // Cleanup Everything
+
+    ca_mutex_free(sharedMutex);
+
+    ca_cond_free(sharedCond);
+}
diff --git a/resource/csdk/connectivity/test/caprotocolmessagetest.cpp b/resource/csdk/connectivity/test/caprotocolmessagetest.cpp
new file mode 100644 (file)
index 0000000..12d6701
--- /dev/null
@@ -0,0 +1,187 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <stdio.h>
+
+#include "gtest/gtest.h"
+
+#include "caprotocolmessage.h"
+
+namespace {
+
+static const char COAP_HEADER[] = "coap://[::]/";
+
+class CoAPOptionCase
+{
+public:
+    unsigned short key;
+    unsigned int length;
+    std::string dataStr; // data could be binary... for testing we'll use str
+};
+
+
+
+/**
+ * Helper to validate the state of CoAP URI parsing.
+ *
+ * @param cases array of expected parse results.
+ * @param numCases number of expected parse results.
+ * @param optlist parsed option list to verify.
+ */
+void verifyParsedOptions(CoAPOptionCase const *cases,
+                        size_t numCases,
+                        coap_list_t *optlist)
+{
+    size_t index = 0;
+    for (coap_list_t *opt = optlist; opt; opt = opt->next)
+    {
+        coap_option *option = (coap_option *) opt->data;
+        EXPECT_TRUE(option != NULL);
+        EXPECT_LT(index, numCases);
+        if (option && (index < numCases))
+        {
+            unsigned short key = COAP_OPTION_KEY(*option);
+            unsigned int length = COAP_OPTION_LENGTH(*option);
+            std::string dataStr((const char*)COAP_OPTION_DATA(*option), length);
+            // First validate the test case:
+            EXPECT_EQ(cases[index].length, cases[index].dataStr.length());
+
+            // Ensure data matches expected parsing
+            EXPECT_EQ(cases[index].key, key);
+            EXPECT_EQ(cases[index].length, length);
+            EXPECT_EQ(cases[index].dataStr, dataStr);
+        }
+
+        index++;
+    }
+    // Ensure we saw the proper number of parts:
+    EXPECT_EQ(numCases, index);
+}
+
+} // namespace
+
+TEST(CAProtocolMessage, CAParseURIBase)
+{
+    char sampleURI[] = "coap://[::]/oc/core?rt=core.sensor&if=core.mi.ll";
+
+    CoAPOptionCase cases[] = {
+        {COAP_OPTION_URI_PATH, 2, "oc"},
+        {COAP_OPTION_URI_PATH, 4, "core"},
+        {COAP_OPTION_URI_QUERY, 14, "rt=core.sensor"},
+        {COAP_OPTION_URI_QUERY, 13, "if=core.mi.ll"},
+    };
+    size_t numCases = sizeof(cases) / sizeof(cases[0]);
+
+
+    coap_list_t *optlist = NULL;
+    CAParseURI(sampleURI, &optlist);
+
+
+    verifyParsedOptions(cases, numCases, optlist);
+}
+
+// Try for multiple URI path components that still total less than 128
+TEST(CAProtocolMessage, CAParseURIManyPath)
+{
+    char sampleURI[] = "coap://[::]"
+        "/medium/a/b/c/d/e/f/g/h/i/j/"
+        "?rt=core.sensor&if=core.mi.ll";
+
+    CoAPOptionCase cases[] = {
+        {COAP_OPTION_URI_PATH, 6, "medium"},
+        {COAP_OPTION_URI_PATH, 1, "a"},
+        {COAP_OPTION_URI_PATH, 1, "b"},
+        {COAP_OPTION_URI_PATH, 1, "c"},
+        {COAP_OPTION_URI_PATH, 1, "d"},
+        {COAP_OPTION_URI_PATH, 1, "e"},
+        {COAP_OPTION_URI_PATH, 1, "f"},
+        {COAP_OPTION_URI_PATH, 1, "g"},
+        {COAP_OPTION_URI_PATH, 1, "h"},
+        {COAP_OPTION_URI_PATH, 1, "i"},
+        {COAP_OPTION_URI_PATH, 1, "j"},
+        {COAP_OPTION_URI_QUERY, 14, "rt=core.sensor"},
+        {COAP_OPTION_URI_QUERY, 13, "if=core.mi.ll"},
+    };
+    size_t numCases = sizeof(cases) / sizeof(cases[0]);
+
+
+    coap_list_t *optlist = NULL;
+    CAParseURI(sampleURI, &optlist);
+
+
+    verifyParsedOptions(cases, numCases, optlist);
+}
+
+// Try for multiple URI parameters that still total less than 128
+TEST(CAProtocolMessage, CAParseURIManyParams)
+{
+    char sampleURI[] = "coap://[::]/oc/core/"
+        "?rt=core.sensor&a=0&b=1&c=2&d=3&e=4&f=5&g=6&h=7&i=8&j=9";
+
+    CoAPOptionCase cases[] = {
+        {COAP_OPTION_URI_PATH, 2, "oc"},
+        {COAP_OPTION_URI_PATH, 4, "core"},
+        {COAP_OPTION_URI_QUERY, 14, "rt=core.sensor"},
+        {COAP_OPTION_URI_QUERY, 3, "a=0"},
+        {COAP_OPTION_URI_QUERY, 3, "b=1"},
+        {COAP_OPTION_URI_QUERY, 3, "c=2"},
+        {COAP_OPTION_URI_QUERY, 3, "d=3"},
+        {COAP_OPTION_URI_QUERY, 3, "e=4"},
+        {COAP_OPTION_URI_QUERY, 3, "f=5"},
+        {COAP_OPTION_URI_QUERY, 3, "g=6"},
+        {COAP_OPTION_URI_QUERY, 3, "h=7"},
+        {COAP_OPTION_URI_QUERY, 3, "i=8"},
+        {COAP_OPTION_URI_QUERY, 3, "j=9"},
+    };
+    size_t numCases = sizeof(cases) / sizeof(cases[0]);
+
+
+    coap_list_t *optlist = NULL;
+    CAParseURI(sampleURI, &optlist);
+
+
+    verifyParsedOptions(cases, numCases, optlist);
+}
+
+// Test that an initial long path component won't hide latter ones.
+TEST(CAProtocolMessage, CAParseURILongPath)
+{
+    char sampleURI[] = "coap://[::]/oc"
+        "123456789012345678901234567890123456789012345678901234567890"
+        "12345678901234567890123456789012345678901234567890"
+        "/core?rt=core.sensor&if=core.mi.ll";
+
+    CoAPOptionCase cases[] = {
+        {COAP_OPTION_URI_PATH, 112, "oc"
+        "123456789012345678901234567890123456789012345678901234567890"
+        "12345678901234567890123456789012345678901234567890"},
+        {COAP_OPTION_URI_PATH, 4, "core"},
+        {COAP_OPTION_URI_QUERY, 14, "rt=core.sensor"},
+        {COAP_OPTION_URI_QUERY, 13, "if=core.mi.ll"},
+    };
+    size_t numCases = sizeof(cases) / sizeof(cases[0]);
+
+
+    coap_list_t *optlist = NULL;
+    CAParseURI(sampleURI, &optlist);
+
+
+    verifyParsedOptions(cases, numCases, optlist);
+}
diff --git a/resource/csdk/connectivity/test/catests.cpp b/resource/csdk/connectivity/test/catests.cpp
new file mode 100644 (file)
index 0000000..b07eb6f
--- /dev/null
@@ -0,0 +1,56 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "gtest/gtest.h"
+
+#include <pthread.h>
+
+/**
+ * Simple holder of work-arounds for link-time issues.
+ */
+void workaroundHook()
+{
+    pthread_key_t key = {0};
+    int ret = pthread_key_create(&key, NULL);
+    if (!ret)
+    {
+        void *ptr = pthread_getspecific(key); // should return NULL
+        ret = pthread_setspecific(key, &ptr);
+        if (ret)
+        {
+            // Something went wrong. Since this is a stub, we don't care.
+        }
+
+        pthread_key_delete(key);
+    }
+}
+
+
+TEST(BaseTest, WorldIsSane)
+{
+    workaroundHook();
+
+    EXPECT_EQ(1 + 1, 2);
+
+    int a = 1;
+    int b = 5;
+
+    EXPECT_GT(b, a);
+}
diff --git a/resource/csdk/connectivity/unittests/linux/sample1_unittest.cc b/resource/csdk/connectivity/unittests/linux/sample1_unittest.cc
deleted file mode 100644 (file)
index 6d8be53..0000000
+++ /dev/null
@@ -1,366 +0,0 @@
-#include "gtest/gtest.h"
-#include "cainterface.h"
-#include "cacommon.h"
-#include <string.h>
-
-using namespace std;
-
-void request_handler(CARemoteEndpoint* object, CARequestInfo* requestInfo);
-void response_handler(CARemoteEndpoint* object, CAResponseInfo* responseInfo);
-
-void request_handler(CARemoteEndpoint* object, CARequestInfo* requestInfo)
-{
-    cout << "request_handler, uri : " << (object != NULL) ? object->resourceUri : "";
-    cout << ", data : " << (requestInfo != NULL) ? requestInfo->info.payload : "";
-    cout << endl;
-}
-
-void response_handler(CARemoteEndpoint* object, CAResponseInfo* responseInfo)
-{
-    cout << "response_handler, uri : " << (object != NULL) ? object->resourceUri : "";
-    cout << ", data : " << (responseInfo != NULL) ? responseInfo->info.payload : "";
-    cout << endl;
-}
-
-char* uri;
-CARemoteEndpoint* tempRep = NULL;
-CARequestInfo requestInfo;
-CAInfo responseData;
-CAResponseInfo responseInfo;
-CAToken tempToken;
-
-int main(int argc, char **argv)
-{
-    testing::InitGoogleTest(&argc, argv);
-    return RUN_ALL_TESTS();
-}
-
-// CAInitialize TC
-// check return value
-TEST(InitializeTest, TC_01_Positive_01)
-{
-    EXPECT_EQ(CA_STATUS_OK, CAInitialize());
-}
-
-//CATerminate TC
-TEST(TerminateTest, TC_02_Positive_01)
-{
-    CATerminate();
-
-    char* check = (char *) "terminate success";
-    EXPECT_STREQ(check, "terminate success");
-
-    CAInitialize();
-}
-// CAStartListeningServer TC
-// check return value
-TEST(StartListeningServerTest, TC_03_Positive_01)
-{
-    CASelectNetwork(CA_WIFI);
-    EXPECT_EQ(CA_STATUS_OK, CAStartListeningServer());
-}
-
-// CAStartDiscoveryServer TC
-// check return value
-TEST(StartDiscoveryServerTest, TC_04_Positive_01)
-{
-    EXPECT_EQ(CA_STATUS_OK, CAStartDiscoveryServer());
-}
-
-// CARegisterHandlerTest TC
-// check return value
-TEST(RegisterHandlerTest, TC_05_Positive_01)
-{
-    EXPECT_EQ(CA_STATUS_OK, CARegisterHandler(request_handler, response_handler));
-}
-
-// CACreateRemoteEndpoint TC
-// check return value
-TEST(CreateRemoteEndpointTest, TC_06_Positive_01)
-{
-    uri = (char *) "referenceUri";
-
-    EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, &tempRep));
-
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// check remoteEndpoint and values of remoteEndpoint
-TEST(CreateRemoteEndpointTest, TC_07_Positive_02)
-{
-    uri = (char *) "referenceUri";
-    CACreateRemoteEndpoint(uri, &tempRep);
-
-    EXPECT_TRUE(tempRep != NULL);
-
-    if (tempRep != NULL)
-    {
-        EXPECT_STRNE(NULL, tempRep->resourceUri);
-    }
-
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(CreateRemoteEndpointTest, TC_08_Nagative_01)
-{
-    uri = NULL;
-
-    EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, &tempRep));
-
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// check values of remoteEndpoint if uri is NULL
-TEST(CreateRemoteEndpointTest, TC_09_Nagative_02)
-{
-    uri = NULL;
-    CACreateRemoteEndpoint(uri, &tempRep);
-
-    if (tempRep != NULL)
-    {
-        EXPECT_STREQ(NULL, tempRep->resourceUri);
-    }
-
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// CADestroyRemoteEndpoint TC
-// check destroyed remoteEndpoint
-TEST(DestroyRemoteEndpointTest, TC_10_Positive_01)
-{
-    uri = (char *) "referenceUri";
-    CACreateRemoteEndpoint(uri, &tempRep);
-
-    CADestroyRemoteEndpoint(tempRep);
-
-    char * check = (char *) "destroy success";
-    EXPECT_STREQ(check, "destroy success");
-}
-
-// CAGerateToken TC
-// check return value
-TEST(GenerateTokenTest, TC_11_Positive_01)
-{
-    EXPECT_EQ(CA_STATUS_OK, CAGenerateToken(&tempToken));
-
-    CADestroyToken(tempToken);
-}
-
-// CADestroyToken TC
-// check destroyed token
-TEST(DestroyTokenTest, TC_12_Positive_01)
-{
-    CAGenerateToken(&tempToken);
-    CADestroyToken(tempToken);
-
-    char * check = (char *) "destroy success";
-    EXPECT_STREQ(check, "destroy success");
-}
-
-// CAFindResource TC
-// check return value
-TEST(FindResourceTest, TC_13_Positive_01)
-{
-    CARegisterHandler(request_handler, response_handler);
-    uri = (char *) "referenceUri";
-    EXPECT_EQ(CA_STATUS_OK, CAFindResource(uri));
-}
-
-// check return value if uri is NULL
-TEST(FindResourceTest, TC_14_Nagative_01)
-{
-    CARegisterHandler(request_handler, response_handler);
-    uri = NULL;
-    EXPECT_EQ(CA_SEND_FAILED, CAFindResource(uri));
-}
-
-// CASendRequest TC
-// check return value
-TEST(SendRequestTest, TC_15_Positive_01)
-{
-    uri = (char *) "referenceUri";
-    memset(&requestInfo, 0, sizeof(CARequestInfo));
-    CACreateRemoteEndpoint(uri, &tempRep);
-    CAGenerateToken(&tempToken);
-    requestInfo.method = CA_GET;
-    requestInfo.info.token = tempToken;
-    requestInfo.info.payload = (char *) "request payload";
-
-    EXPECT_EQ(CA_STATUS_OK, CASendRequest(tempRep, &requestInfo));
-
-    CADestroyToken(tempToken);
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(SendRequestTest, TC_16_Nagative_01)
-{
-    uri = NULL;
-    memset(&requestInfo, 0, sizeof(CARequestInfo));
-    CACreateRemoteEndpoint(uri, &tempRep);
-    CAGenerateToken(&tempToken);
-    requestInfo.method = CA_GET;
-    requestInfo.info.token = tempToken;
-    requestInfo.info.payload = (char *) "request payload";
-
-    EXPECT_EQ(CA_SEND_FAILED, CASendRequest(tempRep, &requestInfo));
-
-    CADestroyToken(tempToken);
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// CASendResponse TC
-// check return value
-TEST(SendResponseTest, TC_17_Positive_01)
-{
-    uri = (char *) "referenceUri";
-    CACreateRemoteEndpoint(uri, &tempRep);
-
-    memset(&responseData, 0, sizeof(CAInfo));
-    CAGenerateToken(&tempToken);
-    responseData.token = tempToken;
-    responseData.payload = (char *) "response payload";
-
-    memset(&responseInfo, 0, sizeof(CAResponseInfo));
-    responseInfo.result = CA_SUCCESS;
-    responseInfo.info = responseData;
-
-    EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
-
-    CADestroyToken(tempToken);
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(SendResponseTest, TC_18_Nagative_01)
-{
-    uri = NULL;
-    CACreateRemoteEndpoint(uri, &tempRep);
-
-    memset(&responseData, 0, sizeof(CAInfo));
-    CAGenerateToken(&tempToken);
-    responseData.token = tempToken;
-    responseData.payload = (char *) "response payload";
-
-    memset(&responseInfo, 0, sizeof(CAResponseInfo));
-    responseInfo.result = CA_SUCCESS;
-    responseInfo.info = responseData;
-
-    EXPECT_EQ(CA_SEND_FAILED, CASendResponse(tempRep, &responseInfo));
-
-    CADestroyToken(tempToken);
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// CASendNotification TC
-// check return value
-TEST(SendNotificationTest, TC_19_Positive_01)
-{
-    uri = (char *) "referenceUri";
-    CACreateRemoteEndpoint(uri, &tempRep);
-
-    memset(&responseData, 0, sizeof(CAInfo));
-    CAGenerateToken(&tempToken);
-    responseData.token = tempToken;
-    responseData.payload = (char *) "response payload";
-
-    memset(&responseInfo, 0, sizeof(CAResponseInfo));
-    responseInfo.result = CA_SUCCESS;
-    responseInfo.info = responseData;
-
-    EXPECT_EQ(CA_NOT_SUPPORTED, CASendNotification(tempRep, &responseInfo));
-
-    CADestroyToken(tempToken);
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(SendNotificationTest, TC_20_Nagative_01)
-{
-    uri = NULL;
-    CACreateRemoteEndpoint(uri, &tempRep);
-
-    memset(&responseData, 0, sizeof(CAInfo));
-    CAGenerateToken(&tempToken);
-    responseData.token = tempToken;
-    responseData.payload = (char *) "response payload";
-
-    memset(&responseInfo, 0, sizeof(CAResponseInfo));
-    responseInfo.result = CA_SUCCESS;
-    responseInfo.info = responseData;
-
-    EXPECT_EQ(CA_NOT_SUPPORTED, CASendNotification(tempRep, &responseInfo));
-
-    CADestroyToken(tempToken);
-    CADestroyRemoteEndpoint(tempRep);
-}
-
-// CAAdvertiseResource TC
-// check return value
-TEST(AdvertiseResourceTest, TC_21_Positive_01)
-{
-    CAURI uri = (char *) "resourceUri";
-    CAHeaderOption* options = NULL;
-    uint8_t numOptions = 0;
-
-    EXPECT_EQ(CA_NOT_SUPPORTED, CAAdvertiseResource(uri, options, numOptions));
-}
-
-// check return value if token is NULL
-TEST(AdvertiseResourceTest, TC_22_Nagative_01)
-{
-    CAURI uri = NULL;
-    CAHeaderOption* options = NULL;
-    uint8_t numOptions = 0;
-
-    EXPECT_EQ(CA_NOT_SUPPORTED, CAAdvertiseResource(uri, options, numOptions));
-}
-
-// CASelectNewwork TC
-// check return value
-TEST(SelectNetworkTest, TC_23_Positive_01)
-{
-    //Select wifi network
-    EXPECT_EQ(CA_STATUS_OK, CASelectNetwork(CA_WIFI));
-}
-
-// check return value if selected network is disable
-TEST(SelectNetworkTest, TC_24_Nagative_01)
-{
-    //Select disable network
-    EXPECT_EQ(CA_NOT_SUPPORTED, CASelectNetwork(20));
-}
-
-// CAUnSelectNewwork TC
-// check return value
-TEST(UnSelectNetworkTest, TC_25_Positive_01)
-{
-    //Unselect wifi network
-    EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_WIFI));
-}
-
-// check return value if selected network is disable
-TEST(UnSelectNetworkTest, TC_26_Nagative_01)
-{
-    //UnSelect disable network
-    EXPECT_EQ(CA_NOT_SUPPORTED, CAUnSelectNetwork(20));
-}
-
-// CAGetNetworkInfomation TC
-// check return value
-TEST (GetNetworkInfomation, TC_27_Positive_01)
-{
-    CALocalConnectivity* info = NULL;
-    uint32_t* size = NULL;
-
-    EXPECT_EQ(CA_NOT_SUPPORTED, CAGetNetworkInformation(&info, size));
-}
-
-// CAHandlerRequestResponse TC
-// check return value
-TEST (HandlerRequestResponseTest, TC_28_Positive_01)
-{
-    EXPECT_EQ(CA_STATUS_OK, CAHandleRequestResponse());
-}
-
diff --git a/resource/csdk/doc/Doxyfile b/resource/csdk/doc/Doxyfile
new file mode 100644 (file)
index 0000000..ca2ba59
--- /dev/null
@@ -0,0 +1,1824 @@
+# Doxyfile 1.8.2
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+#       TAG = value [value, ...]
+# For lists items can also be appended using:
+#       TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or sequence of words) that should
+# identify the project. Note that if you do not use Doxywizard you need
+# to put quotes around the project name if it contains spaces.
+
+PROJECT_NAME           = "IoTivity C SDK"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER         = 
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer
+# a quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is
+# included in the documentation. The maximum height of the logo should not
+# exceed 55 pixels and the maximum width should not exceed 200 pixels.
+# Doxygen will copy the logo to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = docs
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES        = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip. Note that you specify absolute paths here, but also
+# relative paths, which will be relative from the directory where doxygen is
+# started.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful if your file system
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF      = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE               = 8
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding
+# "class=itcl::class" will allow you to use the command class in the
+# itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension,
+# and language is one of the parsers supported by doxygen: IDL, Java,
+# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C,
+# C++. For instance to make doxygen treat .inc files as Fortran files (default
+# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note
+# that for custom extensions you also need to set FILE_PATTERNS otherwise the
+# files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all
+# comments according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you
+# can mix doxygen, HTML, and XML commands with Markdown formatting.
+# Disable only in case of backward compatibilities issues.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented classes,
+# or namespaces to their corresponding documentation. Such a link can be
+# prevented in individual cases by by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also makes the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES (the
+# default) will make doxygen replace the get and set methods by a property in
+# the documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and
+# unions are shown inside the group in which they are included (e.g. using
+# @ingroup) instead of on a separate page (for HTML and Man pages) or
+# section (for LaTeX and RTF).
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and
+# unions with only public data fields will be shown inline in the documentation
+# of the scope in which they are defined (i.e. file, namespace, or group
+# documentation), provided this scope is documented. If set to NO (the default),
+# structs, classes, and unions are shown on a separate page (for HTML and Man
+# pages) or section (for LaTeX and RTF).
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be
+# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given
+# their name and scope. Since this can be an expensive process and often the
+# same symbol appear multiple times in the code, doxygen keeps a cache of
+# pre-resolved symbols. If the cache is too small doxygen will become slower.
+# If the cache is too large, memory is wasted. The cache size is given by this
+# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols.
+
+LOOKUP_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC         = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespaces are hidden.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES       = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES     = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
+# will sort the (brief and detailed) documentation of class members so that
+# constructors and destructors are listed first. If set to NO (the default)
+# the constructors will appear in the respective orders defined by
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to
+# do proper type resolution of all parameters of a function it will reject a
+# match between the prototype and the implementation of a member function even
+# if there is only one candidate or it is obvious which candidate to choose
+# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
+# will still accept a match between prototype and implementation in such cases.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or macro consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and macros in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES  = 125
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES        = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.  This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option.
+# You can optionally specify a file name after the option, if omitted
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE            = ../../docs/doxygenLayout.xml
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files
+# containing the references data. This must be a list of .bib files. The
+# .bib extension is automatically appended if omitted. Using this command
+# requires the bibtex tool to be installed. See also
+# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style
+# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this
+# feature you need bibtex and perl available in the search path.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS               = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR      = YES
+
+# The WARN_NO_PARAMDOC option can be enabled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT                  = . \
+                                                ../stack/include \
+                                                ../ocsocket/include \
+                                                ../ocmalloc/include \
+                                                ../ocrandom/include \
+                                                ../occoap/include \
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh
+# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py
+# *.f90 *.f *.for *.vhd *.vhdl
+
+FILE_PATTERNS          = *.c \
+                         *.cc \
+                         *.cxx \
+                         *.cpp \
+                         *.c++ \
+                         *.d \
+                         *.java \
+                         *.ii \
+                         *.ixx \
+                         *.ipp \
+                         *.i++ \
+                         *.inl \
+                         *.h \
+                         *.hh \
+                         *.hxx \
+                         *.hpp \
+                         *.h++ \
+                         *.idl \
+                         *.odl \
+                         *.cs \
+                         *.php \
+                         *.php3 \
+                         *.inc \
+                         *.m \
+                         *.markdown \
+                         *.md \
+                         *.mm \
+                         *.dox \
+                         *.py \
+                         *.f90 \
+                         *.f \
+                         *.for \
+                         *.vhd \
+                         *.vhdl \
+                         *.txt
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE              = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH             = ../../docs/img
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.  If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.  Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.  The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty or if
+# non of the patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
+# and it is also possible to disable source filtering for a specific pattern
+# using *.ext= (so without naming a filter). This option only has effect when
+# FILTER_SOURCE_FILES is enabled.
+
+FILTER_SOURCE_PATTERNS =
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER         = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C, C++ and Fortran comments will always remain visible.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.  Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX     = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header. Note that when using a custom header you are responsible
+# for the proper inclusion of any scripts and style sheets that doxygen
+# needs, which is dependent on the configuration options used.
+# It is advised to generate a default header using "doxygen -w html
+# header.html footer.html stylesheet.css YourConfigFile" and then modify
+# that header. Note that the header is subject to change so you typically
+# have to redo this when upgrading to a newer version of doxygen or when
+# changing the value of configuration settings such as GENERATE_TREEVIEW!
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER            = ../../docs/html/footer.html
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If left blank doxygen will
+# generate a default style sheet. Note that it is recommended to use
+# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this
+# tag will in the future become obsolete.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional
+# user-defined cascading style sheet that is included after the standard
+# style sheets created by doxygen. Using this option one can overrule
+# certain style aspects. This is preferred over using HTML_STYLESHEET
+# since it does not replace the standard style sheet and is therefor more
+# robust against future updates. Doxygen will copy the style sheet file to
+# the output directory.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that
+# the files will be copied as-is; there are no commands or markers available.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
+# Doxygen will adjust the colors in the style sheet and background images
+# according to this color. Hue is specified as an angle on a colorwheel,
+# see http://en.wikipedia.org/wiki/Hue for more information.
+# For instance the value 0 represents red, 60 is yellow, 120 is green,
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
+# the colors in the HTML output. For a value of 0 the output will use
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
+# the luminance component of the colors in the HTML output. Values below
+# 100 gradually make the output lighter, whereas values above 100 make
+# the output darker. The value divided by 100 is the actual gamma applied,
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of
+# entries shown in the various tree structured indices initially; the user
+# can expand and collapse entries dynamically later on. Doxygen will expand
+# the tree to such a level that at most the specified number of entries are
+# visible (unless a fully collapsed tree already exceeds this amount).
+# So setting the number of entries 1 will produce a full collapsed tree by
+# default. 0 is a special value representing an infinite number of entries
+# and will result in a full expanded tree by default.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+
+GENERATE_DOCSET        = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely
+# identify the documentation publisher. This should be a reverse domain-name
+# style string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP      = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE               =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION           =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI           = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING     =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
+# that can be used as input for Qt's qhelpgenerator to generate a
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
+# add. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
+# Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
+# Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
+# the help appears.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs)
+# at top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it. Since the tabs have the same information as the
+# navigation tree you can set this option to NO if you already set
+# GENERATE_TREEVIEW to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+# Since the tree basically has the same information as the tab index you
+# could consider to set DISABLE_INDEX to NO when enabling this option.
+
+GENERATE_TREEVIEW      = YES
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values
+# (range [0,1..20]) that doxygen will group on one line in the generated HTML
+# documentation. Note that a value of 0 will completely suppress the enum
+# values from appearing in the overview section.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are
+# not supported properly for IE 6.0, but are supported on all modern browsers.
+# Note that when changing this option you need to delete any form_*.png files
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
+# (see http://www.mathjax.org) which uses client side Javascript for the
+# rendering instead of using prerendered bitmaps. Use this if you do not
+# have LaTeX installed or if you want to formulas look prettier in the HTML
+# output. When enabled you may also need to install MathJax separately and
+# configure the path to it using the MATHJAX_RELPATH option.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you need to specify the location relative to the
+# HTML output directory using the MATHJAX_RELPATH option. The destination
+# directory should contain the MathJax.js script. For instance, if the mathjax
+# directory is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to
+# the MathJax Content Delivery Network so you can quickly see the result without
+# installing MathJax.  However, it is strongly recommended to install a local
+# copy of MathJax from http://www.mathjax.org before deployment.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension
+# names that should be enabled during MathJax rendering.
+
+MATHJAX_EXTENSIONS     =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box
+# for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
+# (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a PHP enabled web server instead of at the web client
+# using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server
+# based approach is that it scales better to large projects and allows
+# full text search. The disadvantages are that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for
+# the generated latex document. The footer should contain everything after
+# the last chapter. If it is left blank doxygen will generate a
+# standard footer. Notice: only use this tag if you know what you are doing!
+
+LATEX_FOOTER           =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE        = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include
+# source code with syntax highlighting in the LaTeX output.
+# Note that which sources are shown also depends on other settings
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See
+# http://en.wikipedia.org/wiki/BibTeX for more info.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS         = NO
+
+# Load style sheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE    =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT             = xml
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.  This is useful
+# if you want to understand what is going on.  On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# pointed to by INCLUDE_PATH will be searched when a #include is found.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition that
+# overrules the definition found in the source code.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all references to function-like macros
+# that are alone on a line, have an all uppercase name, and do not end with a
+# semicolon, because these will confuse the parser if not removed.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles. For each
+# tag file the location of the external documentation should be added. The
+# format of a tag file without this location is as follows:
+#   TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#   TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths
+# or URLs. Note that each tag file must have a unique name (where the name does
+# NOT include the path). If a tag file is not located in the directory in which
+# doxygen is run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS        = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option also works with HAVE_DOT disabled, but it is recommended to
+# install and use dot, since it yields more powerful graphs.
+
+CLASS_DIAGRAMS         = NO
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT               = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
+# allowed to run in parallel. When set to 0 (the default) doxygen will
+# base this on the number of processors available in the system. You can set it
+# explicitly to a value larger than 0 to get control over the balance
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS        = 0
+
+# By default doxygen will use the Helvetica font for all dot files that
+# doxygen generates. When you want a differently looking font you can specify
+# the font name using DOT_FONTNAME. You need to make sure dot is able to find
+# the font, which can be done by putting it in a standard location or by setting
+# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
+# directory containing the font.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the Helvetica font.
+# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to
+# set the path where dot can find it.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside
+# the class node. If there are many fields or methods and many nodes the
+# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS
+# threshold limits the number of items for each type to make the size more
+# managable. Set this to 0 for no limit. Note that the threshold may be
+# exceeded by 50% before the limit is enforced.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH          = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will generate a graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are svg, png, jpg, or gif.
+# If left blank png will be used. If you choose svg you need to set
+# HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible in IE 9+ (other browsers do not have this requirement).
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+# Note that this requires a modern browser other than Internet Explorer.
+# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you
+# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible. Older versions of IE do not have SVG support.
+
+INTERACTIVE_SVG        = NO
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the
+# \mscfile command).
+
+MSCFILE_DIRS           =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP            = YES
diff --git a/resource/csdk/libcoap b/resource/csdk/libcoap
deleted file mode 120000 (symlink)
index ec55e69..0000000
+++ /dev/null
@@ -1 +0,0 @@
-libcoap-4.1.1
\ No newline at end of file
diff --git a/resource/csdk/libcoap-4.1.1/ChangeLog b/resource/csdk/libcoap-4.1.1/ChangeLog
deleted file mode 100644 (file)
index 404e331..0000000
+++ /dev/null
@@ -1,159 +0,0 @@
-2014-02-04  Olaf Bergmann  <bergmann@tzi.org>
-
-       * resource.c (coap_print_link): This function now takes an offset
-       where printing starts. This is used for generating blocks on the
-       fly.
-
-       * net.c (wellknown_response): Added support for Block2 options
-       when generating a response for .well-known/core.
-
-       * block.h (coap_opt_block_num): Fixed handling of zero-length
-       options. COAP_OPT_BLOCK_LAST now returns NULL when the option
-       value's length is zero.
-
-2014-01-07  Olaf Bergmann  <bergmann@tzi.org>
-
-       * resource.c (coap_print_link): Output partial resource
-       descriptions. The function now provides a sliding window over the
-       textual representation of the resource. Output starts at the given
-       offset and ends at the buffer's upper bound. The meaning of the
-       return value has changed to allow distinguishing whether or not
-       the resource description has been truncated at the buffer's upper
-       bound.
-       (print_wellknown): Support for the new coap_print_link(). An
-       additional parameter now is used to provide the offset into the
-       resource description. The meaning of the return value has been
-       adjusted accordingly.
-
-2013-12-23  Olaf Bergmann  <bergmann@tzi.org>
-
-       * configure.in: merged with LWIP port from chrysn
-       <https://git.gitorious.org/coap-lwip/coap-lwip.git>. This
-       introduces new compiler flags WITH_POSIX and WITH_LWIP to
-       distinguish target platforms.
-
-2013-09-03  Olaf Bergmann  <bergmann@tzi.org>
-
-       * option.h (coap_option_setb): increased size of option type
-       argument
-
-       * tests/test_error_response.c (t_init_error_response_tests): new
-       tests for error response generation
-
-       * tests/test_pdu.c (t_encode_pdu5): fixed number for option Accept
-
-       * net.c (coap_new_error_response): fixed option size calculation
-
-2013-07-04  Olaf Bergmann  <bergmann@tzi.org>
-
-       * net.c (coap_new_context): register critical Accept option
-
-       * pdu.c: option codes for Accept and Size1 according to coap-18
-
-2013-02-01  Olaf Bergmann  <bergmann@tzi.org>
-
-       * coap_time.h (coap_clock_init_impl): fix invalid preprocessor
-       directive. #warning is now only used for gcc only (close sf bug #15)
-
-       * net.c (wellknown_response): applied patch from chrysn to
-       fix bug in generation of .well-known/core representation
-
-2013-01-21  Olaf Bergmann  <bergmann@tzi.org>
-
-       * option.h: renamed option field in coap_opt_iterator_t to
-       next_option to detect erroneous use in old code
-
-2013-01-18  Olaf Bergmann  <bergmann@tzi.org>
-
-       * configure.in: new option --with-tests to enable unit tests
-
-       * tests/testdriver.c: unit tests for parser functions
-
-       * pdu.c (coap_pdu_parse): new PDU parser for Klaus-encoding
-       according to coap-13
-
-       * net.c (coap_read): call coap_pdu_parse() to check PDU integrity
-
-       * option.c: Klaus-encoding for coap-13, including new option
-       iterator interface
-
-2012-11-20  Olaf Bergmann  <bergmann@tzi.org>
-
-       * net.c (next_option_safe): made option parsing more robust in
-       presence of option jumps
-
-       * pdu.h: new option codes from draft-ietf-core-coap-12
-
-       * option.c (coap_opt_setlength): new function to set option length
-
-       * uri.c (make_decoded_option): use coap_opt_setlength() instead of
-       obsolete macro COAP_OPT_SETLENGTH.
-
-2012-11-19  Olaf Bergmann  <bergmann@tzi.org>
-
-       * uri.c (make_decoded_option): use coap_opt_encode() instead of writing
-
-2012-11-03  Olaf Bergmann  <bergmann@tzi.org>
-
-       * net.c (coap_read): read new option encoding
-
-2012-11-01  Olaf Bergmann  <bergmann@tzi.org>
-
-       * option.c (coap_opt_size, coap_opt_value, coap_opt_length):
-       several functions to access fields of options (possibly preceeded
-       by option jump)
-
-2012-10-25  Olaf Bergmann  <bergmann@tzi.org>
-
-       * option.c (coap_opt_encode): new function for option encoding
-       with option jumps
-
-2012-03-23  Olaf Bergmann  <bergmann@tzi.org>
-
-       * examples/client.c (clear_obs): clear observation relationship after
-       user-specified duration
-
-2012-03-21  Olaf Bergmann  <bergmann@tzi.org>
-
-       * resource.c (print_wellknown): filtering by attributes
-
-2012-03-19  Olaf Bergmann  <bergmann@tzi.org>
-
-       * pdu.c (coap_add_option): allow more than 15 options.
-
-2012-03-15  Olaf Bergmann  <bergmann@tzi.org>
-
-       * examples/client.c (cmdline_uri): split path and query here to
-       make it easier to include these options in subsequent requests for
-       block transfer.
-
-2012-03-14  Olaf Bergmann  <bergmann@tzi.org>
-
-       * examples/etsi_iot_01.c: Support for POST, PUT, DELETE on /test
-
-2012-03-13  Olaf Bergmann  <bergmann@tzi.org>
-
-       * encode.c (coap_encode_var_bytes): more efficient coding for 0
-
-2012-03-11  Olaf Bergmann  <bergmann@tzi.org>
-
-       * examples/etsi_iot_01.c: Test cases for 1st ETSI CoAP Plugtest,
-       March 24/25, 2012 in Paris, France.
-
-2012-03-10  Olaf Bergmann  <bergmann@tzi.org>
-
-       * block.c: support for block transfer.
-
-2012-03-07  Olaf Bergmann  <bergmann@tzi.org>
-
-       * examples/client.c (usage): new command line options
-       -B to set timeout after which the main loop is left.
-       -e to specify a payload (incompatible with -f)
-       (message_handler): bugfixes
-
-       * resource.h: (coap_method_handler_t): new API for method handlers.
-
-
-Copyright 2012 Olaf Bergmann, TZI
-Copying and distribution of this file, with or without modification, are
-permitted provided the copyright notice and this notice are preserved.
diff --git a/resource/csdk/libcoap-4.1.1/LICENSE.BSD b/resource/csdk/libcoap-4.1.1/LICENSE.BSD
deleted file mode 100644 (file)
index 2fc333a..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-Copyright (c) 2010--2011, Olaf Bergmann
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-  o Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-
-  o Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in
-    the documentation and/or other materials provided with the
-    distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/resource/csdk/libcoap-4.1.1/LICENSE.GPL b/resource/csdk/libcoap-4.1.1/LICENSE.GPL
deleted file mode 100644 (file)
index d8cf7d4..0000000
+++ /dev/null
@@ -1,280 +0,0 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-                            Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-                    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-                            NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
diff --git a/resource/csdk/libcoap-4.1.1/Makefile.in b/resource/csdk/libcoap-4.1.1/Makefile.in
deleted file mode 100644 (file)
index d9b1c55..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-# Makefile for libcoap
-#
-# Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
-#
-# This file is part of the CoAP library libcoap. Please see
-# README for terms of use. 
-
-# the library's version
-VERSION:=@PACKAGE_VERSION@
-
-# tools
-@SET_MAKE@
-RANLIB=@RANLIB@
-SHELL = /bin/sh
-MKDIR = mkdir
-ETAGS = @ETAGS@
-
-abs_builddir = @abs_builddir@
-top_builddir = @top_builddir@
-package = @PACKAGE_TARNAME@-@PACKAGE_VERSION@
-
-# files and flags
-SOURCES:= pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \
-        str.c option.c async.c subscribe.c block.c
-OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
-HEADERS:=coap.h config.h debug.h pdu.h net.h encode.h uri.h coap_list.h mem.h \
-       str.h option.h bits.h uthash.h utlist.h resource.h hashkey.h async.h \
-       subscribe.h block.h address.h prng.h coap_time.h t_list.h
-CFLAGS:=-Wall -Wextra -std=c99 -pedantic @CFLAGS@
-CPPFLAGS:=@CPPFLAGS@
-DISTDIR=$(top_builddir)/$(package)
-SUBDIRS:=examples doc tests
-FILES:=ChangeLog README LICENSE.BSD LICENSE.GPL Makefile.in configure configure.in config.h.in $(SOURCES) $(HEADERS)
-LIB:=libcoap.a
-LDSOFLAGS=-shared
-LDFLAGS:=@LIBS@
-ARFLAGS:=cru
-examples:=examples
-doc:=doc
-@BUILD_SO@
-
-ifdef BUILD_SO
-  MACHINE?=$(shell $(CC) -dumpmachine)
-  ifeq ($(findstring Darwin, $(MACHINE)), Darwin)
-    LDSOFLAGS=-dynamiclib
-    LIBSO=libcoap.dylib
-  endif
-  ifeq ($(findstring Windows, $(MACHINE)), Windows)
-    LIBSO=libcoap.dll
-  endif
-  # more platforms go here
-  ifndef LIBSO
-    LIBSO=libcoap.so
-  endif
-  ifndef PICFLAG
-    CFLAGS+=-fPIC
-  else
-    CFLAGS+=$(PICFLAG)
-  endif
-endif
-
-.PHONY: all dirs clean distclean .gitignore doc TAGS
-
-.SUFFIXES:
-.SUFFIXES:      .c .o
-
-all:   $(LIB) $(LIBSO) dirs
-
-check: 
-       echo DISTDIR: $(DISTDIR)
-       echo top_builddir: $(top_builddir)
-       $(MAKE) -C examples check
-
-dirs:  $(SUBDIRS)
-       for dir in $^; do \
-               $(MAKE) -C $$dir ; \
-       done
-
-$(LIB):        $(OBJECTS)
-       $(AR) $(ARFLAGS) $@ $^ 
-       $(RANLIB) $@
-
-$(LIBSO):      $(OBJECTS)
-       $(LD) $(LDSOFLAGS) $(LDFLAGS) -o $@ $^
-
-clean:
-       @rm -f $(PROGRAM) main.o $(LIB) $(LIBSO) $(OBJECTS)
-       for dir in $(SUBDIRS); do \
-               $(MAKE) -C $$dir clean ; \
-       done
-
-doc:   
-       $(MAKE) -C doc
-
-distclean:     clean
-       @rm -rf $(DISTDIR)
-       @rm -f *~ $(DISTDIR).tar.gz
-
-dist:  $(FILES) $(SUBDIRS)
-       test -d $(DISTDIR) || mkdir $(DISTDIR)
-       cp $(FILES) $(DISTDIR)
-       for dir in $(SUBDIRS); do \
-               $(MAKE) -C $$dir dist; \
-       done
-       tar czf $(package).tar.gz $(DISTDIR)
-
-TAGS:  
-       $(ETAGS) -o $@.new $(SOURCES) 
-       $(ETAGS) -a -o $@.new $(HEADERS) 
-       mv $@.new $@
-
-.gitignore:
-       echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@
diff --git a/resource/csdk/libcoap-4.1.1/README b/resource/csdk/libcoap-4.1.1/README
deleted file mode 100644 (file)
index 043a317..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-libcoap: A C implementation of IETF Core Application protocol
-
-Copyright (C) 2010--2013 by Olaf Bergmann <bergmann@tzi.org>
-
-ABOUT LIBCOAP 
-
-libcoap is a C implementation of a lightweight application-protocol
-for devices that are constrained their resources such as computing
-power, RF range, memory, bandwith, or network packet sizes. This
-protocol, CoAP, is developed in the IETF working group "Constrained
-RESTful Environments (core)", see <http://6lowapp.net>.
-
-PACKAGE CONTENTS
-
-This directory contains a protocol parser and basic networking
-functions for platform with support for malloc() and BSD-style
-sockets. The examples directory contains a client and a server to
-demonstrate the use of this library. 
-
-LICENSE INFORMATION
-
-This library is published as open-source software without any warranty
-of any kind. Use is permitted under the terms of the GNU General
-Public License (GPL), Version 2 or higher, OR the revised BSD
-license. Please refer to LICENSE.GPL oder LICENSE.BSD for further
-details.
-
-NOTICE - TRANSITION TO SCONS
-
-The IoTivity build system is transitioning to SCONS. Although the 
-makefiles are still available (until v1.0) and some developers are 
-still using them, they are currently no longer supported. To learn more 
-about building using SCONS see Readme.scons.txt in the repository root 
-directory. The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
-BUILD STEPS FOR INTEL OC STACK
-
-Use below command to build libcoap:
-make all PLATFORM=linux
-make all PLATFORM=android
-
diff --git a/resource/csdk/libcoap-4.1.1/SConscript b/resource/csdk/libcoap-4.1.1/SConscript
deleted file mode 100644 (file)
index d10bba0..0000000
+++ /dev/null
@@ -1,86 +0,0 @@
-##
-# libcoap (share library) build script
-##
-
-Import('env')
-
-libcoap_env = env.Clone()
-
-target_os = env.get('TARGET_OS')
-# As in the source code(C) includes arduino Time library head file(C++)
-# It requires compile the .c with g++
-if target_os == 'arduino':
-       libcoap_env.Replace(CC = env.get('CXX'))
-       libcoap_env.Replace(CFLAGS = env.get('CXXFLAGS'))
-
-######################################################################
-# Build flags
-######################################################################
-libcoap_env.PrependUnique(CPPPATH = [
-               '../ocsocket/include',
-               '../ocmalloc/include',
-               '../logger/include',
-               '../ocrandom/include',
-               '../stack',
-               '../../oc_logger/include'
-               ])
-
-if target_os not in ['arduino', 'windows', 'winrt']:
-       libcoap_env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
-       libcoap_env.AppendUnique(CFLAGS = ['-std=gnu99', '-fPIC'])
-
-if target_os not in ['windows', 'winrt']:
-       libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
-                       '-fdata-sections', '-fno-exceptions'])
-
-if target_os == 'android':
-       libcoap_env.AppendUnique(LIBS = ['log'])
-
-if target_os == 'arduino':
-       libcoap_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-
-if target_os in ['darwin', 'ios']:
-       libcoap_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
-
-if not env.get('RELEASE'):
-       libcoap_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-######################################################################
-# Source files and Target(s)
-######################################################################
-libcoap_src = [
-       'pdu.c',
-       'net.c',
-       'debug.c',
-       'encode.c',
-       'uri.c',
-       'coap_list.c',
-#      'resource.c',
-       'hashkey.c',
-    'str.c',
-       'option.c',
-       'async.c',
-       'subscribe.c',
-       'block.c',
-       '../logger/src/logger.c',
-       '../ocrandom/src/ocrandom.c',
-       '../ocmalloc/src/ocmalloc.c',
-       '../../oc_logger/c/oc_logger.c',
-       '../../oc_logger/c/oc_console_logger.c'
-       ]
-
-if target_os == 'arduino':
-       if env.get('NET') == 'Wifi':
-               libcoap_src.append(['../ocsocket/src/ocsocket_arduino_wifi.cpp'])
-       else:
-               libcoap_src.append(['../ocsocket/src/ocsocket_arduino.cpp'])
-else:
-       libcoap_src.append(['../ocsocket/src/ocsocket.c'])
-
-if target_os == 'arduino':
-       static_libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
-       libcoap_env.InstallTarget(static_libcoap, 'libcoap')
-else:
-       static_libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
-       shared_libcoap = libcoap_env.SharedLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
-       libcoap_env.InstallTarget([static_libcoap, shared_libcoap], 'libcoap')
diff --git a/resource/csdk/libcoap-4.1.1/address.h b/resource/csdk/libcoap-4.1.1/address.h
deleted file mode 100644 (file)
index 39e1221..0000000
+++ /dev/null
@@ -1,208 +0,0 @@
-/* address.h -- representation of network addresses
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-/** 
- * @file address.h
- * @brief representation of network addresses
- */
-
-#ifndef _COAP_ADDRESS_H_
-#define _COAP_ADDRESS_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "config.h"
-
-#ifdef HAVE_ASSERT_H
-#include <assert.h>
-#else
-#ifndef assert
-#warning "assertions are disabled"
-#  define assert(x)
-#endif
-#endif
-
-#include <string.h>
-#include <stdint.h>
-#include "ocsocket.h"
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETINET_IN_H
-#include <sys/socket.h>
-#endif
-
-#ifdef WITH_LWIP
-#include <lwip/ip_addr.h>
-
-typedef struct coap_address_t {
-       uint16_t port;
-       ip_addr_t addr;
-} coap_address_t;
-
-/* FIXME oversimplification: just assuming it's an ipv4 address instead of
- * looking up the appropraite lwip function */
-
-#define _coap_address_equals_impl(A, B) ((A)->addr.addr == (B)->addr.addr && A->port == B->port)
-
-/* FIXME sure there is something in lwip */
-
-#define _coap_is_mcast_impl(Address) 0
-
-#endif /* WITH_LWIP */
-#ifdef WITH_CONTIKI
-#include "uip.h"
-
-typedef struct coap_address_t {
-  unsigned char size;
-  uip_ipaddr_t addr;
-  unsigned short port;
-} coap_address_t;
-
-#define _coap_address_equals_impl(A,B)                         \
-  ((A)->size == (B)->size                                      \
-   && (A)->port == (B)->port                                   \
-   && uip_ipaddr_cmp(&((A)->addr),&((B)->addr)))
-
-#define _coap_is_mcast_impl(Address) uip_is_addr_mcast(&((Address)->addr))
-#endif /* WITH_CONTIKI */
-
-#ifdef WITH_POSIX
-
-#pragma pack(push, 1)
-/** multi-purpose address abstraction */
-typedef struct coap_address_t {
-  socklen_t size;              /**< size of addr */
-  union {
-    struct sockaddr     sa;
-    struct sockaddr_storage st;
-    struct sockaddr_in  sin;
-    struct sockaddr_in6 sin6;
-  } addr;
-} coap_address_t;
-#pragma pack(pop)
-
-static inline int 
-_coap_address_equals_impl(const coap_address_t *a,
-                         const coap_address_t *b) {
-  if (a->size != b->size || a->addr.sa.sa_family != b->addr.sa.sa_family)
-    return 0;
-  
-  /* need to compare only relevant parts of sockaddr_in6 */
- switch (a->addr.sa.sa_family) {
- case AF_INET:
-   return 
-     a->addr.sin.sin_port == b->addr.sin.sin_port && 
-     memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr, 
-           sizeof(struct in_addr)) == 0;
- case AF_INET6:
-   return a->addr.sin6.sin6_port == b->addr.sin6.sin6_port && 
-     memcmp(&a->addr.sin6.sin6_addr, &b->addr.sin6.sin6_addr, 
-           sizeof(struct in6_addr)) == 0;
- default: /* fall through and signal error */
-   ;
- }
- return 0;
-}
-
-static inline int
-_coap_is_mcast_impl(const coap_address_t *a) {
-  if (!a)
-    return 0;
-
- switch (a->addr.sa.sa_family) {
- case AF_INET:
-   return IN_MULTICAST(a->addr.sin.sin_addr.s_addr);
-case  AF_INET6:
-  return IN6_IS_ADDR_MULTICAST(&a->addr.sin6.sin6_addr);
- default:                      /* fall through and signal error */
-   ;
-  }
- return 0;
-}
-
-#endif /* WITH_POSIX */
-
-#ifdef WITH_ARDUINO
-typedef OCDevAddr coap_address_t;
-
-static inline int 
-_coap_address_equals_impl(const coap_address_t *a,
-        const coap_address_t *b) {
-    uint32_t i;
-
-    if ((a == NULL) || (b == NULL))
-        return 0;
-
-    if (a->size != b->size)
-        return 0;
-
-    for (i = 0; i < a->size; i++)
-    {
-        if (a->addr[i] != b->addr[i])
-            return 0;
-    }
-    return 1;
-}
-
-static inline int
-_coap_is_mcast_impl(const coap_address_t *a) {
-    if (!a)
-        return 0;
-
-    /* TODO */
-    return 0;
-}
-
-#endif /* WITH_ARDUINO */
-
-/** 
- * Resets the given coap_address_t object @p addr to its default
- * values.  In particular, the member size must be initialized to the
- * available size for storing addresses.
- * 
- * @param addr The coap_address_t object to initialize.
- */
-static inline void
-coap_address_init(coap_address_t *addr) {
-  assert(addr);
-  memset(addr, 0, sizeof(coap_address_t));
-#ifndef WITH_LWIP
-  /* lwip has constandt address sizes and doesn't need the .size part */
-  addr->size = sizeof(addr->addr);
-#endif
-}
-
-/**
- * Compares given address objects @p a and @p b. This function returns
- * @c 1 if addresses are equal, @c 0 otherwise. The parameters @p a
- * and @p b must not be @c NULL;
- */
-static inline int
-coap_address_equals(const coap_address_t *a, const coap_address_t *b) {
-  assert(a); assert(b);
-  return _coap_address_equals_impl(a, b);
-}
-
-/**
- * Checks if given address @p a denotes a multicast address.  This
- * function returns @c 1 if @p a is multicast, @c 0 otherwise.
- */
-static inline int 
-coap_is_mcast(const coap_address_t *a) {
-  return a && _coap_is_mcast_impl(a);
-}
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_ADDRESS_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/async.c b/resource/csdk/libcoap-4.1.1/async.c
deleted file mode 100644 (file)
index 976bf63..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-/* async.c -- state management for asynchronous messages
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-/** 
- * @file async.c
- * @brief state management for asynchronous messages
- */
-
-#ifndef WITHOUT_ASYNC
-
-#include "config.h"
-
-#include "utlist.h"
-
-#include "mem.h"
-#include "debug.h"
-#include "async.h"
-
-coap_async_state_t *
-coap_register_async(coap_context_t *context, coap_address_t *peer,
-                   coap_pdu_t *request, unsigned char flags, void *data) {
-  coap_async_state_t *s;
-  coap_tid_t id;
-
-  coap_transaction_id(peer, request, &id);
-  LL_SEARCH_SCALAR(context->async_state,s,id,id);
-
-  if (s != NULL) {
-    /* We must return NULL here as the caller must know that he is
-     * responsible for releasing @p data. */
-    debug("asynchronous state for transaction %d already registered\n", id);
-    return NULL;
-  }
-
-  /* store information for handling the asynchronous task */
-  s = (coap_async_state_t *)coap_malloc(sizeof(coap_async_state_t) + 
-                                       request->hdr->token_length);
-  if (!s) {
-    coap_log(LOG_CRIT, "coap_register_async: insufficient memory\n");
-    return NULL;
-  }
-
-  memset(s, 0, sizeof(coap_async_state_t) + request->hdr->token_length);
-
-  /* set COAP_ASYNC_CONFIRM according to request's type */
-  s->flags = flags & ~COAP_ASYNC_CONFIRM;
-  if (request->hdr->type == COAP_MESSAGE_CON)
-    s->flags |= COAP_ASYNC_CONFIRM;
-
-  s->appdata = data;
-
-  memcpy(&s->peer, peer, sizeof(coap_address_t));
-
-  if (request->hdr->token_length) {
-    s->tokenlen = request->hdr->token_length;
-    memcpy(s->token, request->hdr->token, request->hdr->token_length);
-  }
-    
-  memcpy(&s->id, &id, sizeof(coap_tid_t));
-
-  coap_touch_async(s);
-
-  LL_PREPEND(context->async_state, s);
-
-  return s;
-}
-
-coap_async_state_t *
-coap_find_async(coap_context_t *context, coap_tid_t id) {
-  coap_async_state_t *tmp;
-  LL_SEARCH_SCALAR(context->async_state,tmp,id,id);  
-  return tmp;
-}
-
-int
-coap_remove_async(coap_context_t *context, coap_tid_t id, 
-                 coap_async_state_t **s) {
-  coap_async_state_t *tmp = coap_find_async(context, id);
-
-  if (tmp)
-    LL_DELETE(context->async_state,tmp);
-
-  *s = tmp;
-  return tmp != NULL;
-}
-
-void 
-coap_free_async(coap_async_state_t *s) {
-  if (s && (s->flags & COAP_ASYNC_RELEASE_DATA) != 0)
-    coap_free(s->appdata);
-  coap_free(s); 
-}
-
-#else
-void does_not_exist(); /* make some compilers happy */
-#endif /* WITHOUT_ASYNC */
diff --git a/resource/csdk/libcoap-4.1.1/async.h b/resource/csdk/libcoap-4.1.1/async.h
deleted file mode 100644 (file)
index cf0554b..0000000
+++ /dev/null
@@ -1,154 +0,0 @@
-/* async.h -- state management for asynchronous messages
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-/**
- * @file async.h
- * @brief state management for asynchronous messages
- */
-
-
-#ifndef _COAP_ASYNC_H_
-#define _COAP_ASYNC_H_
-
-#include "config.h"
-#include "net.h"
-
-#ifndef WITHOUT_ASYNC
-
-/**
- * @defgroup coap_async Asynchronous Messaging
- * @{
- * Structure for managing asynchronous state of CoAP resources. A
- * coap_resource_t object holds a list of coap_async_state_t objects
- * that can be used to generate a separate response in case a result
- * of an operation cannot be delivered in time, or the resource has
- * been explicitly subscribed to with the option @c observe.
- */
-typedef struct coap_async_state_t {
-  unsigned char flags; /**< holds the flags to control behaviour */
-
-  /**
-   * Holds the internal time when the object was registered with a
-   * resource. This field will be updated whenever
-   * coap_register_async() is called for a specific resource.
-   */
-  coap_tick_t created;
-
-  /**
-   * This field can be used to register opaque application data with
-   * the asynchronous state object. */
-  void *appdata;
-
-  unsigned short message_id;   /**< id of last message seen */
-  coap_tid_t id;               /**< transaction id */
-
-  struct coap_async_state_t *next; /**< internally used for linking */
-
-  coap_address_t peer;         /**< the peer to notify */
-  size_t tokenlen;             /**< length of the token */
-#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-pedantic"
-#endif
-  __extension__ unsigned char token[]; /**< the token to use in a response */
-#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
-#pragma GCC diagnostic pop
-#endif
-} coap_async_state_t;
-
-/* Definitions for Async Status Flags These flags can be used to
- * control the behaviour of asynchronous response generation. */
-#define COAP_ASYNC_CONFIRM   0x01 /**< send confirmable response */
-#define COAP_ASYNC_SEPARATE  0x02 /**< send separate response */
-#define COAP_ASYNC_OBSERVED  0x04 /**< the resource is being observed */
-
-/** release application data on destruction */
-#define COAP_ASYNC_RELEASE_DATA  0x08
-
-/**
- * Allocates a new coap_async_state_t object and fills its fields
- * according to the given @p request. The @p flags are used to control
- * generation of empty ACK responses to stop retransmissions and to
- * release registered @p data when the resource is deleted by
- * coap_free_async().  This function returns a pointer to the registered
- * coap_async_t object or @c NULL on error. Note that this function will
- * return @c NULL in case that an object with the same identifier is
- * already registered.
- *
- * @param context  The context to use.
- * @param peer     The remote peer that is to be asynchronously notified.
- * @param request  The request that is handled asynchronously.
- * @param flags    Flags to control state management.
- * @param data     Opaque application data to register. Note that the
- *                 storage occupied by @p data is released on destruction
- *                 only if flag COAP_ASYNC_RELEASE_DATA is set.
- *
- * @return A pointer to the registered coap_async_state_t object or
- * @c NULL in case of an error.
- */
-coap_async_state_t *
-coap_register_async(coap_context_t *context, coap_address_t *peer,
-                   coap_pdu_t *request, unsigned char flags, void *data);
-
-/**
- * Removes the state object identified by @p id from @p context. The
- * removed object is returned in @p s, if found. Otherwise, @p s is
- * undefined. This function returns @c 1 if the object was removed, @c
- * 0 otherwise. Note that the storage allocated for the stored object
- * is not released by this functions. You will have to call
- * coap_free_async() to do so.
- *
- * @param context The context where the async object is registered.
- * @param id      The identifier of the asynchronous transaction.
- * @param s       Will be set to the object identified by @p id
- * after removal.
- *
- * @return @c 1 if object was removed and @p s updated, or @c 0 if no
- * object was found with the given id. @p s is valid only if the
- * return value is @c 1.
- */
-int coap_remove_async(coap_context_t *context, coap_tid_t id,
-                     coap_async_state_t **s);
-
-/**
- * Releases the memory that was allocated by coap_async_state_init()
- * for the object @p s. The registered application data will be
- * released automatically if COAP_ASYNC_RELEASE_DATA is set.
- *
- * @param s The object to delete.
- */
-void
-coap_free_async(coap_async_state_t *state);
-
-/**
- * Retrieves the object identified by @p id from the list of asynchronous
- * transactions that are registered with @p context. This function returns
- * a pointer to that object or @c NULL if not found.
- *
- * @param context The context where the asynchronous objects are
- * registered with.
- * @param id      The id of the object to retrieve.
- *
- * @return A pointer to the object identified by @p id or @c NULL if
- * not found.
- */
-coap_async_state_t *coap_find_async(coap_context_t *context, coap_tid_t id);
-
-/**
- * Updates the time stamp of @p s.
- *
- * @param s The state object to update.
- */
-static inline void
-coap_touch_async(coap_async_state_t *s) { coap_ticks(&s->created); }
-
-/** @} */
-
-#endif /*  WITHOUT_ASYNC */
-
-#endif /* _COAP_ASYNC_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/bits.h b/resource/csdk/libcoap-4.1.1/bits.h
deleted file mode 100644 (file)
index 6569c75..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * bits.h -- bit vector manipulation
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-/**
- * @file bits.h
- * @brief bit vector manipulation
- */
-
-#ifndef _BITS_H_
-#define _BITS_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-#include <stdint.h>
-
-/**
- * Sets the bit @p bit in bit-vector @p vec. This function returns @c
- * 1 if bit was set or @c -1 on error (i.e. when the given bit does
- * not fit in the vector).
- *
- * @param vec  The bit-vector to change.
- * @param size The size of @p vec in bytes.
- * @param bit  The bit to set in @p vec.
- *
- * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
- */
-inline static int
-bits_setb(uint8_t *vec, size_t size, uint16_t bit) {
-  if (size <= (size_t)(bit >> 3))
-    return -1;
-
-  *(vec + (bit >> 3)) |= (uint8_t)(1 << (bit & 0x07));
-  return 1;
-}
-
-/**
- * Clears the bit @p bit from bit-vector @p vec. This function returns
- * @c 1 if bit was cleared or @c -1 on error (i.e. when the given bit
- * does not fit in the vector).
- *
- * @param vec  The bit-vector to change.
- * @param size The size of @p vec in bytes.
- * @param bit  The bit to clear from @p vec.
- *
- * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
- */
-inline static int
-bits_clrb(uint8_t *vec, size_t size, uint16_t bit) {
-  if (size <= (size_t)(bit >> 3))
-    return -1;
-
-  *(vec + (bit >> 3)) &= (uint8_t)(~(1 << (bit & 0x07)));
-  return 1;
-}
-
-/**
- * Gets the status of bit @p bit from bit-vector @p vec. This function returns
- * @c 1 if the bit is set, @c 0 otherwise (even in case of an error)..
- *
- * @param vec  The bit-vector to read from..
- * @param size The size of @p vec in bytes.
- * @param bit  The bit to get from @p vec.
- *
- * @return @c 1 if the bit is set, @c 0 otherwise.
- */
-inline static int
-bits_getb(const uint8_t *vec, size_t size, uint16_t bit) {
-  if (size <= (size_t)(bit >> 3))
-    return -1;
-
-  return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0;
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _BITS_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/block.c b/resource/csdk/libcoap-4.1.1/block.c
deleted file mode 100644 (file)
index 402fd8c..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/* block.c -- block transfer
- *
- * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#include "config.h"
-
-#if defined(HAVE_ASSERT_H) && !defined(assert)
-# include <assert.h>
-#endif
-
-#ifdef WITH_ARDUINO
-/* On Arduino the abort function, needed for assert, is defined in std lib */
-#include <stdlib.h>
-#endif
-
-#include "debug.h"
-#include "block.h"
-
-#define min(a,b) ((a) < (b) ? (a) : (b))
-
-#ifndef WITHOUT_BLOCK
-unsigned int
-coap_opt_block_num(const coap_opt_t *block_opt) {
-  unsigned int num = 0;
-  unsigned short len;
-  
-  len = coap_opt_length(block_opt);
-
-  if (len == 0) {
-    return 0;
-  }
-  
-  if (len > 1) {
-    num = coap_decode_var_bytes(COAP_OPT_VALUE(block_opt), 
-                               COAP_OPT_LENGTH(block_opt) - 1);
-  }
-  
-  return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4);
-}
-
-int
-coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block) {
-  coap_opt_iterator_t opt_iter;
-  coap_opt_t *option;
-
-  assert(block);
-  memset(block, 0, sizeof(coap_block_t));
-
-  if (pdu && (option = coap_check_option(pdu, type, &opt_iter))) {
-    block->szx = COAP_OPT_BLOCK_SZX(option);
-    if (COAP_OPT_BLOCK_MORE(option))
-      block->m = 1;
-    block->num = coap_opt_block_num(option);
-    return 1;
-  }
-
-  return 0;
-}
-
-int
-coap_write_block_opt(coap_block_t *block, unsigned short type,
-                    coap_pdu_t *pdu, size_t data_length) {
-  size_t start, want, avail;
-  unsigned char buf[3];
-
-  assert(pdu);
-
-  /* Block2 */
-  if (type != COAP_OPTION_BLOCK2) {
-    warn("coap_write_block_opt: skipped unknown option\n");
-    return -1;
-  }
-
-  start = block->num << (block->szx + 4);
-  if (data_length <= start) {
-    debug("illegal block requested\n");
-    return -2;
-  }
-  
-  avail = pdu->max_size - pdu->length - 4;
-  want = 1 << (block->szx + 4);
-
-  /* check if entire block fits in message */
-  if (want <= avail) {
-    block->m = want < data_length - start;
-  } else {
-    /* Sender has requested a block that is larger than the remaining
-     * space in pdu. This is ok if the remaining data fits into the pdu
-     * anyway. The block size needs to be adjusted only if there is more
-     * data left that cannot be delivered in this message. */
-
-    if (data_length - start <= avail) {
-
-      /* it's the final block and everything fits in the message */
-      block->m = 0;
-    } else {
-      unsigned char szx;
-
-      /* we need to decrease the block size */
-      if (avail < 16) {        /* bad luck, this is the smallest block size */
-       debug("not enough space, even the smallest block does not fit");
-       return -3;
-      }
-      debug("decrease block size for %d to %d\n", avail, coap_fls(avail) - 5);
-      szx = block->szx;
-      block->szx = coap_fls(avail) - 5;
-      block->m = 1;
-      block->num <<= szx - block->szx;
-    }
-  }
-
-  /* to re-encode the block option */
-  coap_add_option(pdu, type, coap_encode_var_bytes(buf, ((block->num << 4) | 
-                                                        (block->m << 3) | 
-                                                        block->szx)), 
-                 buf);
-
-  return 1;
-}
-
-int 
-coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data,
-              unsigned int block_num, unsigned char block_szx) {
-  size_t start;
-  start = block_num << (block_szx + 4);
-
-  if (len <= start)
-    return 0;
-  
-  return coap_add_data(pdu, 
-                      min(len - start, (unsigned int)(1 << (block_szx + 4))),
-                      data + start);
-}
-#endif /* WITHOUT_BLOCK  */
diff --git a/resource/csdk/libcoap-4.1.1/block.h b/resource/csdk/libcoap-4.1.1/block.h
deleted file mode 100644 (file)
index ee2d5a9..0000000
+++ /dev/null
@@ -1,145 +0,0 @@
-/* block.h -- block transfer
- *
- * Copyright (C) 2010--2012,2014 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#ifndef _COAP_BLOCK_H_
-#define _COAP_BLOCK_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "option.h"
-#include "encode.h"
-#include "pdu.h"
-
-/**
- * @defgroup block Block Transfer
- * @{
- */
-
-#ifndef COAP_MAX_BLOCK_SZX
-/**
- * The largest value for the SZX component in a Block option. Note
- * that 1 << (COAP_MAX_BLOCK_SZX + 4) should not exceed
- * COAP_MAX_PDU_SIZE.
- */
-#define COAP_MAX_BLOCK_SZX      4
-#endif /* COAP_MAX_BLOCK_SZX */
-
-#if (COAP_MAX_PDU_SIZE - 6) < (1 << (COAP_MAX_BLOCK_SZX + 4))
-#error "COAP_MAX_BLOCK_SZX too large"
-#endif
-
-/**
- * Structure of Block options.
- */
-typedef struct {
-  unsigned int num:20;  /**< block number */
-  unsigned int m:1;     /**< 1 if more blocks follow, 0 otherwise */
-  unsigned int szx:3;   /**< block size */
-} coap_block_t;
-
-/**
- * Returns the value of the least significant byte of a Block option @p opt.
- * For zero-length options (i.e. num == m == szx == 0), COAP_OPT_BLOCK_LAST
- * returns @c NULL.
- */
-#define COAP_OPT_BLOCK_LAST(opt) \
-  (COAP_OPT_LENGTH(opt) ? (COAP_OPT_VALUE(opt) + (COAP_OPT_LENGTH(opt)-1)) : 0)
-
-/** Returns the value of the More-bit of a Block option @p opt. */
-#define COAP_OPT_BLOCK_MORE(opt) \
-  (COAP_OPT_LENGTH(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x08) : 0)
-
-/** Returns the value of the SZX-field of a Block option @p opt. */
-#define COAP_OPT_BLOCK_SZX(opt)  \
-  (COAP_OPT_LENGTH(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x07) : 0)
-
-/**
- * Returns the value of field @c num in the given block option @p
- * block_opt.
- */
-unsigned int coap_opt_block_num(const coap_opt_t *block_opt);
-
-/**
- * Checks if more than @p num blocks are required to deliver @p data_len
- * bytes of data for a block size of 1 << (@p szx + 4).
- */
-static inline int
-coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx) {
-  return ((num+1) << (szx + 4)) < data_len;
-}
-
-/** Sets the More-bit in @p block_opt */
-static inline void
-coap_opt_block_set_m(coap_opt_t *block_opt, int m) {
-  if (m)
-    *(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) |= 0x08;
-  else
-    *(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) &= ~0x08;
-}
-
-/**
- * Initializes @p block from @p pdu. @p type must be either COAP_OPTION_BLOCK1
- * or COAP_OPTION_BLOCK2. When option @p type was found in @p pdu, @p block
- * is initialized with values from this option and the function returns the
- * value @c 1. Otherwise, @c 0 is returned.
- *
- * @param pdu   The pdu to search for option @p type.
- * @param type  The option to search for (must be COAP_OPTION_BLOCK1 or
- *              COAP_OPTION_BLOCK2)
- * @param block The block structure to initilize.
- * @return @c 1 on success, @c 0 otherwise.
- */
-int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block);
-
-/**
- * Writes a block option of type @p type to message @p pdu. If the
- * requested block size is too large to fit in @p pdu, it is reduced
- * accordingly. An exception is made for the final block when less
- * space is required. The actual length of the resource is specified
- * in @p data_length.
- *
- * This function may change *block to reflect the values written to
- * @p pdu. As the function takes into consideration the remaining space
- * @p pdu, no more options should be added after coap_write_block_opt()
- * has returned.
- *
- * @param block      The block structure to use. On return, this object
- *                   is updated according to the values that have been
- *                   written to @p pdu.
- * @param type       COAP_OPTION_BLOCK1 or COAP_OPTION_BLOCK2
- * @param pdu        The message where the block option should be
- *                   written.
- * @param data_length The length of the actual data that will be added
- *                   the @p pdu by calling coap_add_block().
- * @return @c 1 on success, or a negative value on error.
- */
-int coap_write_block_opt(coap_block_t *block, unsigned short type,
-                         coap_pdu_t *pdu, size_t data_length);
-
-/**
- * Adds the @p block_num block of size 1 << (@p block_szx + 4) from
- * source @p data to @p pdu.
- *
- * @param pdu    The message to add the block
- * @param len    The length of @p data.
- * @param data   The source data to fill the block with
- * @param block_num The actual block number
- * @param block_szx Encoded size of block @p block_number
- * @return @c 1 on success, @c 0 otherwise.
- */
-int coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data,
-                   unsigned int block_num, unsigned char block_szx);
-/**@}*/
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_BLOCK_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/coap.h b/resource/csdk/libcoap-4.1.1/coap.h
deleted file mode 100644 (file)
index 2e7440a..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/* coap.h -- main header file for CoAP stack
- *
- * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#ifndef _COAP_H_
-#define _COAP_H_
-
-#include "net.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "config.h"
-#include "debug.h"
-#include "mem.h"
-#include "coap_list.h"
-#include "pdu.h"
-#include "option.h"
-#include "encode.h"
-#include "str.h"
-#include "uri.h"
-#include "async.h"
-#include "t_list.h"
-#include "subscribe.h"
-#include "block.h"
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/coap_list.c b/resource/csdk/libcoap-4.1.1/coap_list.c
deleted file mode 100644 (file)
index e147a17..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-/* coap_list.c -- CoAP list structures
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-
-#include <stdio.h>
-#include <string.h>
-
-#include "debug.h"
-#include "mem.h"
-#include "coap_list.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int
-coap_insert(coap_list_t **queue, coap_list_t *node,
-           int (*order)(void *, void *node) ) {
-  coap_list_t *p, *q;
-  if ( !queue || !node )
-    return 0;
-
-  /* set queue head if empty */
-  if ( !*queue ) {
-    *queue = node;
-    return 1;
-  }
-
-  /* replace queue head if new node has to be added before the existing queue head */
-  q = *queue;
-  if ( order( node->data, q->data ) < 0) {
-    node->next = q;
-    *queue = node;
-    return 1;
-  }
-
-  /* search for right place to insert */
-  do {
-    p = q;
-    q = q->next;
-  } while ( q && order( node->data, q->data ) >= 0);
-
-  /* insert new item */
-  node->next = q;
-  p->next = node;
-  return 1;
-}
-
-int
-coap_delete(coap_list_t *node) {
-  if ( !node )
-    return 0;
-
-  if ( node->delete_func )
-    node->delete_func( node->data );
-  coap_free( node->data );
-  coap_free( node );
-
-  return 1;
-}
-
-void
-coap_delete_list(coap_list_t *queue) {
-  if ( !queue )
-    return;
-
-  coap_delete_list( queue->next );
-  coap_delete( queue );
-}
-
-coap_list_t *
-coap_new_listnode(void *data, void (*delete_func)(void *) ) {
-  coap_list_t *node = (coap_list_t*)coap_malloc( sizeof(coap_list_t) );
-  if ( ! node ) {
-#ifndef NDEBUG
-    coap_log(LOG_CRIT, "coap_new_listnode: malloc\n");
-#endif
-    return NULL;
-  }
-
-  memset(node, 0, sizeof(coap_list_t));
-  node->data = data;
-  node->delete_func = delete_func;
-  return node;
-}
-
-#ifdef __cplusplus
-}
-#endif
-
diff --git a/resource/csdk/libcoap-4.1.1/coap_list.h b/resource/csdk/libcoap-4.1.1/coap_list.h
deleted file mode 100644 (file)
index 9e47b26..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/* coap_list.h -- CoAP list structures
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#ifndef _COAP_LIST_H_
-#define _COAP_LIST_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct coap_linkedlistnode {
-  struct coap_linkedlistnode *next;
-  void *data;
-
-  /**
-   * Callback function that is called from coap_delete to release
-   * additional memory allocated by data Set to NULL if you do not
-   * need this. Note that data is free'd automatically. */
-  void (*delete_func)(void *);
-};
-
-typedef struct coap_linkedlistnode coap_list_t;
-
-/**
- * Adds node to given queue, ordered by specified order function. Returns 1
- * when insert was successful, 0 otherwise.
- */
-int coap_insert(coap_list_t **queue, coap_list_t *node,
-               int (*order)(void *, void *) );
-
-/* destroys specified node */
-int coap_delete(coap_list_t *node);
-
-/* removes all items from given queue and frees the allocated storage */
-void coap_delete_list(coap_list_t *queue);
-
-/**
- * Creates a new list node and adds the given data object. The memory allocated
- * by data will be released by coap_delete() with the new node. Returns the
- * new list node.
- */
-coap_list_t *coap_new_listnode(void *data, void (*delete_func)(void *) );
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_LIST_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/coap_time.h b/resource/csdk/libcoap-4.1.1/coap_time.h
deleted file mode 100644 (file)
index 6255eb8..0000000
+++ /dev/null
@@ -1,193 +0,0 @@
-/* coap_time.h -- Clock Handling
- *
- * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-/** 
- * @file coap_time.h
- * @brief Clock Handling
- */
-
-#ifndef _COAP_TIME_H_
-#define _COAP_TIME_H_
-
-/*
-** Make sure we can call this stuff from C++.
-*/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-#include "config.h"
-
-/**
- * @defgroup clock Clock Handling
- * Default implementation of internal clock. You should redefine this if
- * you do not have time() and gettimeofday().
- * @{
- */
-
-#ifdef WITH_LWIP
-
-#include <stdint.h>
-#include <lwip/sys.h>
-
-/* lwIP provides ms in sys_now */
-#define COAP_TICKS_PER_SECOND 1000
-
-typedef uint32_t coap_tick_t;
-
-static inline void coap_ticks_impl(coap_tick_t *t)
-{
-       *t = sys_now();
-}
-
-static inline void coap_clock_init_impl(void)
-{
-}
-
-#define coap_clock_init coap_clock_init_impl
-
-#define coap_ticks coap_ticks_impl
-
-#endif
-#ifdef WITH_CONTIKI
-#include "clock.h"
-
-typedef clock_time_t coap_tick_t;
-
-/**
- * This data type is used to represent the difference between two
- * clock_tick_t values. This data type must have the same size in
- * memory as coap_tick_t to allow wrapping.
- */
-typedef int coap_tick_diff_t;
-
-#define COAP_TICKS_PER_SECOND CLOCK_SECOND
-
-/** Set at startup to initialize the internal clock (time in seconds). */
-extern clock_time_t clock_offset;
-
-static inline void
-contiki_clock_init_impl(void) {
-  clock_init();
-  clock_offset = clock_time();
-}
-
-#define coap_clock_init contiki_clock_init_impl
-
-static inline void
-contiki_ticks_impl(coap_tick_t *t) {
-  *t = clock_time();
-}
-
-#define coap_ticks contiki_ticks_impl
-
-#endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
-typedef unsigned int coap_tick_t; 
-
-/**
- * This data type is used to represent the difference between two
- * clock_tick_t values. This data type must have the same size in
- * memory as coap_tick_t to allow wrapping.
- */
-typedef int coap_tick_diff_t;
-
-#define COAP_TICKS_PER_SECOND 1024
-
-/** Set at startup to initialize the internal clock (time in seconds). */
-extern time_t clock_offset;
-#endif /* WITH_POSIX */
-
-#ifdef WITH_ARDUINO
-#include "Time.h"
-typedef time_t coap_tick_t;
-
-/**
- * This data type is used to represent the difference between two
- * clock_tick_t values. This data type must have the same size in
- * memory as coap_tick_t to allow wrapping.
- */
-typedef int coap_tick_diff_t;
-
-/* TODO: Ticks per second value for Arduino needs verification from 
- * documentation */
-#define COAP_TICKS_PER_SECOND 1000
-
-extern time_t clock_offset;
-
-#endif /* WITH_ARDUINO */
-
-#ifndef coap_clock_init
-static inline void
-coap_clock_init_impl(void) {
-#ifdef HAVE_TIME_H
-  clock_offset = time(NULL);
-#else
-#  ifdef WITH_ARDUINO
-     clock_offset = now();
-#  else
-#    ifdef __GNUC__
-      /* Issue a warning when using gcc. Other prepropressors do 
-       *  not seem to have a similar feature. */ 
-#     warning "cannot initialize clock"
-#    endif
-     clock_offset = 0;
-#  endif /* WITH_ARDUINO */
-#endif /* HAVE_TIME */
-}
-#define coap_clock_init coap_clock_init_impl
-#endif /* coap_clock_init */
-
-#ifndef coap_ticks
-static inline void
-coap_ticks_impl(coap_tick_t *t) {
-#ifdef HAVE_SYS_TIME_H
-  struct timeval tv;
-  gettimeofday(&tv, NULL);
-  *t = (tv.tv_sec - clock_offset) * COAP_TICKS_PER_SECOND 
-    + (tv.tv_usec * COAP_TICKS_PER_SECOND / 1000000);
-#else
-#  ifdef WITH_ARDUINO
-    coap_tick_t tv;
-    tv = now();
-    *t = (tv - clock_offset)*COAP_TICKS_PER_SECOND;
-#  else
-#    error "clock not implemented"
-#  endif /* WITH_ARDUINO */
-#endif /* HAVE_SYS_TIME_H */
-}
-#define coap_ticks coap_ticks_impl
-#endif /* coap_ticks */
-
-/**
- * Returns @c 1 if and only if @p a is less than @p b where less is
- * defined on a signed data type.
- */
-static inline
-int coap_time_lt(coap_tick_t a, coap_tick_t b) {
-  return ((coap_tick_diff_t)(a - b)) < 0;
-}
-
-/**
- * Returns @c 1 if and only if @p a is less than or equal @p b where
- * less is defined on a signed data type.
- */
-static inline
-int coap_time_le(coap_tick_t a, coap_tick_t b) {
-  return a == b || coap_time_lt(a,b);
-}
-
-/** @} */
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /* _COAP_TIME_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/config.h b/resource/csdk/libcoap-4.1.1/config.h
deleted file mode 100644 (file)
index 91d21d6..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
-
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_ARPA_INET_H 1
-#endif
-
-/* Define to 1 if you have the <assert.h> header file. */
-#define HAVE_ASSERT_H 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `coap' library (-lcoap). */
-/* #undef HAVE_LIBCOAP */
-
-/* Define to 1 if you have the <limits.h> header file. */
-#define HAVE_LIMITS_H 1
-
-/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
-   to 0 otherwise. */
-#define HAVE_MALLOC 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `memset' function. */
-#define HAVE_MEMSET 1
-
-/* Define to 1 if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H 1
-
-/* Define to 1 if you have the <netinet/in.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_NETINET_IN_H 1
-#endif
-
-/* Define to 1 if you have the `select' function. */
-#define HAVE_SELECT 1
-
-/* Define to 1 if you have the `socket' function. */
-#define HAVE_SOCKET 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the `strcasecmp' function. */
-#define HAVE_STRCASECMP 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strnlen' function. */
-#define HAVE_STRNLEN 1
-
-/* Define to 1 if you have the `strrchr' function. */
-#define HAVE_STRRCHR 1
-
-/* Define to 1 if you have the <syslog.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYSLOG_H 1
-#endif
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_SOCKET_H 1
-#endif
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TIME_H 1
-#endif
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TYPES_H 1
-#endif
-
-/* Define to 1 if you have the <sys/unistd.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_UNISTD_H 1
-#endif
-
-/* Define to 1 if you have the <time.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_TIME_H 1
-#endif
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_UNISTD_H 1
-#endif
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libcoap"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libcoap 4.1.1"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libcoap"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "4.1.1"
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
-   significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-#  define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-/* #  undef WORDS_BIGENDIAN */
-# endif
-#endif
-
-/* Define to rpl_malloc if the replacement function should be used. */
-/* #undef malloc */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef ssize_t */
diff --git a/resource/csdk/libcoap-4.1.1/config.h.in b/resource/csdk/libcoap-4.1.1/config.h.in
deleted file mode 100644 (file)
index 4a0f3c6..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if building universal (internal helper macro) */
-#undef AC_APPLE_UNIVERSAL_BUILD
-
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#undef HAVE_ARPA_INET_H
-
-/* Define to 1 if you have the <assert.h> header file. */
-#undef HAVE_ASSERT_H
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#undef HAVE_GETADDRINFO
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#undef HAVE_INTTYPES_H
-
-/* Define to 1 if you have the `coap' library (-lcoap). */
-#undef HAVE_LIBCOAP
-
-/* Define to 1 if you have the <limits.h> header file. */
-#undef HAVE_LIMITS_H
-
-/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
-   to 0 otherwise. */
-#undef HAVE_MALLOC
-
-/* Define to 1 if you have the <memory.h> header file. */
-#undef HAVE_MEMORY_H
-
-/* Define to 1 if you have the `memset' function. */
-#undef HAVE_MEMSET
-
-/* Define to 1 if you have the <netdb.h> header file. */
-#undef HAVE_NETDB_H
-
-/* Define to 1 if you have the <netinet/in.h> header file. */
-#undef HAVE_NETINET_IN_H
-
-/* Define to 1 if you have the `select' function. */
-#undef HAVE_SELECT
-
-/* Define to 1 if you have the `socket' function. */
-#undef HAVE_SOCKET
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#undef HAVE_STDINT_H
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#undef HAVE_STDLIB_H
-
-/* Define to 1 if you have the `strcasecmp' function. */
-#undef HAVE_STRCASECMP
-
-/* Define to 1 if you have the <strings.h> header file. */
-#undef HAVE_STRINGS_H
-
-/* Define to 1 if you have the <string.h> header file. */
-#undef HAVE_STRING_H
-
-/* Define to 1 if you have the `strnlen' function. */
-#undef HAVE_STRNLEN
-
-/* Define to 1 if you have the `strrchr' function. */
-#undef HAVE_STRRCHR
-
-/* Define to 1 if you have the <syslog.h> header file. */
-#undef HAVE_SYSLOG_H
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#undef HAVE_SYS_SOCKET_H
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#undef HAVE_SYS_STAT_H
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#undef HAVE_SYS_TIME_H
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#undef HAVE_SYS_TYPES_H
-
-/* Define to 1 if you have the <sys/unistd.h> header file. */
-#undef HAVE_SYS_UNISTD_H
-
-/* Define to 1 if you have the <time.h> header file. */
-#undef HAVE_TIME_H
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#undef HAVE_UNISTD_H
-
-/* Define to the address where bug reports for this package should be sent. */
-#undef PACKAGE_BUGREPORT
-
-/* Define to the full name of this package. */
-#undef PACKAGE_NAME
-
-/* Define to the full name and version of this package. */
-#undef PACKAGE_STRING
-
-/* Define to the one symbol short name of this package. */
-#undef PACKAGE_TARNAME
-
-/* Define to the home page for this package. */
-#undef PACKAGE_URL
-
-/* Define to the version of this package. */
-#undef PACKAGE_VERSION
-
-/* Define to 1 if you have the ANSI C header files. */
-#undef STDC_HEADERS
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
-   significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-#  define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-#  undef WORDS_BIGENDIAN
-# endif
-#endif
-
-/* Define to rpl_malloc if the replacement function should be used. */
-#undef malloc
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-#undef size_t
-
-/* Define to `int' if <sys/types.h> does not define. */
-#undef ssize_t
diff --git a/resource/csdk/libcoap-4.1.1/configure b/resource/csdk/libcoap-4.1.1/configure
deleted file mode 100755 (executable)
index b6f5dad..0000000
+++ /dev/null
@@ -1,5411 +0,0 @@
-#! /bin/sh
-# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for libcoap 4.1.1.
-#
-#
-# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
-#
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-       expr "X$arg" : "X\\(.*\\)$as_nl";
-       arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
-      PATH_SEPARATOR=';'
-  }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""       $as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-  done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-# Use a proper internal environment variable to ensure we don't fall
-  # into an infinite loop, continuously re-executing ourselves.
-  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
-    _as_can_reexec=no; export _as_can_reexec;
-    # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
-  *v*x* | *x*v* ) as_opts=-vx ;;
-  *v* ) as_opts=-v ;;
-  *x* ) as_opts=-x ;;
-  * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-as_fn_exit 255
-  fi
-  # We don't want this to propagate to other subprocesses.
-          { _as_can_reexec=; unset _as_can_reexec;}
-if test "x$CONFIG_SHELL" = x; then
-  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '\${1+\"\$@\"}'='\"\$@\"'
-  setopt NO_GLOB_SUBST
-else
-  case \`(set -o) 2>/dev/null\` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-"
-  as_required="as_fn_return () { (exit \$1); }
-as_fn_success () { as_fn_return 0; }
-as_fn_failure () { as_fn_return 1; }
-as_fn_ret_success () { return 0; }
-as_fn_ret_failure () { return 1; }
-
-exitcode=0
-as_fn_success || { exitcode=1; echo as_fn_success failed.; }
-as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
-as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
-as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
-if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
-
-else
-  exitcode=1; echo positional parameters were not saved.
-fi
-test x\$exitcode = x0 || exit 1
-test -x / || exit 1"
-  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
-  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
-  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
-  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
-test \$(( 1 + 1 )) = 2 || exit 1"
-  if (eval "$as_required") 2>/dev/null; then :
-  as_have_required=yes
-else
-  as_have_required=no
-fi
-  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
-
-else
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-as_found=false
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  as_found=:
-  case $as_dir in #(
-        /*)
-          for as_base in sh bash ksh sh5; do
-            # Try only shells that exist, to save several forks.
-            as_shell=$as_dir/$as_base
-            if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
-                   { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
-  CONFIG_SHELL=$as_shell as_have_required=yes
-                  if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
-  break 2
-fi
-fi
-          done;;
-       esac
-  as_found=false
-done
-$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
-             { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
-  CONFIG_SHELL=$SHELL as_have_required=yes
-fi; }
-IFS=$as_save_IFS
-
-
-      if test "x$CONFIG_SHELL" != x; then :
-  export CONFIG_SHELL
-             # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
-  *v*x* | *x*v* ) as_opts=-vx ;;
-  *v* ) as_opts=-v ;;
-  *x* ) as_opts=-x ;;
-  * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-exit 255
-fi
-
-    if test x$as_have_required = xno; then :
-  $as_echo "$0: This script requires a shell more modern than all"
-  $as_echo "$0: the shells that I found on your system."
-  if test x${ZSH_VERSION+set} = xset ; then
-    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
-    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
-  else
-    $as_echo "$0: Please tell bug-autoconf@gnu.org about your system,
-$0: including any error possibly output before this
-$0: message. Then install a modern shell, or manually run
-$0: the script under such a shell if you do have one."
-  fi
-  exit 1
-fi
-fi
-fi
-SHELL=${CONFIG_SHELL-/bin/sh}
-export SHELL
-# Unset more variables known to interfere with behavior of common tools.
-CLICOLOR_FORCE= GREP_OPTIONS=
-unset CLICOLOR_FORCE GREP_OPTIONS
-
-## --------------------- ##
-## M4sh Shell Functions. ##
-## --------------------- ##
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
-  { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
-  return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
-  set +e
-  as_fn_set_status $1
-  exit $1
-} # as_fn_exit
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || eval $as_mkdir_p || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_dir" : 'X\(//\)[^/]' \| \
-        X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
-  test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
-  eval 'as_fn_append ()
-  {
-    eval $1+=\$2
-  }'
-else
-  as_fn_append ()
-  {
-    eval $1=\$$1\$2
-  }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
-  eval 'as_fn_arith ()
-  {
-    as_val=$(( $* ))
-  }'
-else
-  as_fn_arith ()
-  {
-    as_val=`expr "$@" || test $? -eq 1`
-  }
-fi # as_fn_arith
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
-  as_status=$1; test $as_status -eq 0 && as_status=1
-  if test "$4"; then
-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
-  fi
-  $as_echo "$as_me: error: $2" >&2
-  as_fn_exit $as_status
-} # as_fn_error
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-        X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-
-  as_lineno_1=$LINENO as_lineno_1a=$LINENO
-  as_lineno_2=$LINENO as_lineno_2a=$LINENO
-  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
-  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
-  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=
-  ' <$as_myself |
-    sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
-      N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
-      t loop
-      s/-\n.*//
-    ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
-    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
-
-  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
-  # already done that, so ensure we don't try to do so again and fall
-  # in an infinite loop.  This has already happened in practice.
-  _as_can_reexec=no; export _as_can_reexec
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensitive to this).
-  . "./$as_me.lineno"
-  # Exit status is that of the last command.
-  exit
-}
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
-  case `echo 'xy\c'` in
-  *c*) ECHO_T='        ';;     # ECHO_T is single tab character.
-  xy)  ECHO_C='\c';;
-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
-       ECHO_T='        ';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
-  if ln -s conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s='ln -s'
-    # ... but there are two gotchas:
-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -pR'.
-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -pR'
-  elif ln conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s=ln
-  else
-    as_ln_s='cp -pR'
-  fi
-else
-  as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p='mkdir -p "$as_dir"'
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-test -n "$DJDIR" || exec 7<&0 </dev/null
-exec 6>&1
-
-# Name of the host.
-# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
-# so uname gets run too.
-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
-
-#
-# Initializations.
-#
-ac_default_prefix=/usr/local
-ac_clean_files=
-ac_config_libobj_dir=.
-LIBOBJS=
-cross_compiling=no
-subdirs=
-MFLAGS=
-MAKEFLAGS=
-
-# Identity of this package.
-PACKAGE_NAME='libcoap'
-PACKAGE_TARNAME='libcoap'
-PACKAGE_VERSION='4.1.1'
-PACKAGE_STRING='libcoap 4.1.1'
-PACKAGE_BUGREPORT=''
-PACKAGE_URL=''
-
-ac_unique_file="coap.h"
-# Factoring default headers for most tests.
-ac_includes_default="\
-#include <stdio.h>
-#ifdef HAVE_SYS_TYPES_H
-# include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_STAT_H
-# include <sys/stat.h>
-#endif
-#ifdef STDC_HEADERS
-# include <stdlib.h>
-# include <stddef.h>
-#else
-# ifdef HAVE_STDLIB_H
-#  include <stdlib.h>
-# endif
-#endif
-#ifdef HAVE_STRING_H
-# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
-#  include <memory.h>
-# endif
-# include <string.h>
-#endif
-#ifdef HAVE_STRINGS_H
-# include <strings.h>
-#endif
-#ifdef HAVE_INTTYPES_H
-# include <inttypes.h>
-#endif
-#ifdef HAVE_STDINT_H
-# include <stdint.h>
-#endif
-#ifdef HAVE_UNISTD_H
-# include <unistd.h>
-#endif"
-
-ac_subst_vars='LTLIBOBJS
-BUILD_SO
-TESTS
-LIBOBJS
-EGREP
-GREP
-CPP
-ETAGS
-DOXYGEN
-RANLIB
-OBJEXT
-EXEEXT
-ac_ct_CC
-CPPFLAGS
-LDFLAGS
-CFLAGS
-CC
-SET_MAKE
-target_alias
-host_alias
-build_alias
-LIBS
-ECHO_T
-ECHO_N
-ECHO_C
-DEFS
-mandir
-localedir
-libdir
-psdir
-pdfdir
-dvidir
-htmldir
-infodir
-docdir
-oldincludedir
-includedir
-localstatedir
-sharedstatedir
-sysconfdir
-datadir
-datarootdir
-libexecdir
-sbindir
-bindir
-program_transform_name
-prefix
-exec_prefix
-PACKAGE_URL
-PACKAGE_BUGREPORT
-PACKAGE_STRING
-PACKAGE_VERSION
-PACKAGE_TARNAME
-PACKAGE_NAME
-PATH_SEPARATOR
-SHELL'
-ac_subst_files=''
-ac_user_opts='
-enable_option_checking
-with_contiki
-with_debug
-with_async
-with_block
-with_observe
-with_query_filter
-with_tests
-with_shared
-'
-      ac_precious_vars='build_alias
-host_alias
-target_alias
-CC
-CFLAGS
-LDFLAGS
-LIBS
-CPPFLAGS
-CPP'
-
-
-# Initialize some variables set by options.
-ac_init_help=
-ac_init_version=false
-ac_unrecognized_opts=
-ac_unrecognized_sep=
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-cache_file=/dev/null
-exec_prefix=NONE
-no_create=
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-verbose=
-x_includes=NONE
-x_libraries=NONE
-
-# Installation directory options.
-# These are left unexpanded so users can "make install exec_prefix=/foo"
-# and all the variables that are supposed to be based on exec_prefix
-# by default will actually change.
-# Use braces instead of parens because sh, perl, etc. also accept them.
-# (The list follows the same order as the GNU Coding Standards.)
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datarootdir='${prefix}/share'
-datadir='${datarootdir}'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
-infodir='${datarootdir}/info'
-htmldir='${docdir}'
-dvidir='${docdir}'
-pdfdir='${docdir}'
-psdir='${docdir}'
-libdir='${exec_prefix}/lib'
-localedir='${datarootdir}/locale'
-mandir='${datarootdir}/man'
-
-ac_prev=
-ac_dashdash=
-for ac_option
-do
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval $ac_prev=\$ac_option
-    ac_prev=
-    continue
-  fi
-
-  case $ac_option in
-  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
-  *=)   ac_optarg= ;;
-  *)    ac_optarg=yes ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case $ac_dashdash$ac_option in
-  --)
-    ac_dashdash=yes ;;
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir=$ac_optarg ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build_alias ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build_alias=$ac_optarg ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file=$ac_optarg ;;
-
-  --config-cache | -C)
-    cache_file=config.cache ;;
-
-  -datadir | --datadir | --datadi | --datad)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=*)
-    datadir=$ac_optarg ;;
-
-  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
-  | --dataroo | --dataro | --datar)
-    ac_prev=datarootdir ;;
-  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
-  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
-    datarootdir=$ac_optarg ;;
-
-  -disable-* | --disable-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"enable_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval enable_$ac_useropt=no ;;
-
-  -docdir | --docdir | --docdi | --doc | --do)
-    ac_prev=docdir ;;
-  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
-    docdir=$ac_optarg ;;
-
-  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
-    ac_prev=dvidir ;;
-  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
-    dvidir=$ac_optarg ;;
-
-  -enable-* | --enable-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"enable_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval enable_$ac_useropt=\$ac_optarg ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix=$ac_optarg ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he | -h)
-    ac_init_help=long ;;
-  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
-    ac_init_help=recursive ;;
-  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
-    ac_init_help=short ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host_alias ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host_alias=$ac_optarg ;;
-
-  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
-    ac_prev=htmldir ;;
-  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
-  | --ht=*)
-    htmldir=$ac_optarg ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir=$ac_optarg ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir=$ac_optarg ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir=$ac_optarg ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir=$ac_optarg ;;
-
-  -localedir | --localedir | --localedi | --localed | --locale)
-    ac_prev=localedir ;;
-  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
-    localedir=$ac_optarg ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst | --locals)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
-    localstatedir=$ac_optarg ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir=$ac_optarg ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c | -n)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir=$ac_optarg ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix=$ac_optarg ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix=$ac_optarg ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix=$ac_optarg ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name=$ac_optarg ;;
-
-  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
-    ac_prev=pdfdir ;;
-  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
-    pdfdir=$ac_optarg ;;
-
-  -psdir | --psdir | --psdi | --psd | --ps)
-    ac_prev=psdir ;;
-  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
-    psdir=$ac_optarg ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir=$ac_optarg ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir=$ac_optarg ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site=$ac_optarg ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir=$ac_optarg ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir=$ac_optarg ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target_alias ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target_alias=$ac_optarg ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers | -V)
-    ac_init_version=: ;;
-
-  -with-* | --with-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"with_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval with_$ac_useropt=\$ac_optarg ;;
-
-  -without-* | --without-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"with_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
-        ac_unrecognized_sep=', ';;
-    esac
-    eval with_$ac_useropt=no ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes=$ac_optarg ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries=$ac_optarg ;;
-
-  -*) as_fn_error $? "unrecognized option: \`$ac_option'
-Try \`$0 --help' for more information"
-    ;;
-
-  *=*)
-    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
-    # Reject names that are not valid shell variable names.
-    case $ac_envvar in #(
-      '' | [0-9]* | *[!_$as_cr_alnum]* )
-      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
-    esac
-    eval $ac_envvar=\$ac_optarg
-    export $ac_envvar ;;
-
-  *)
-    # FIXME: should be removed in autoconf 3.0.
-    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
-    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
-  as_fn_error $? "missing argument to $ac_option"
-fi
-
-if test -n "$ac_unrecognized_opts"; then
-  case $enable_option_checking in
-    no) ;;
-    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
-    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
-  esac
-fi
-
-# Check all directory arguments for consistency.
-for ac_var in  exec_prefix prefix bindir sbindir libexecdir datarootdir \
-               datadir sysconfdir sharedstatedir localstatedir includedir \
-               oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-               libdir localedir mandir
-do
-  eval ac_val=\$$ac_var
-  # Remove trailing slashes.
-  case $ac_val in
-    */ )
-      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
-      eval $ac_var=\$ac_val;;
-  esac
-  # Be sure to have absolute directory names.
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* )  continue;;
-    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
-  esac
-  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
-done
-
-# There might be people who depend on the old broken behavior: `$host'
-# used to hold the argument of --host etc.
-# FIXME: To remove some day.
-build=$build_alias
-host=$host_alias
-target=$target_alias
-
-# FIXME: To remove some day.
-if test "x$host_alias" != x; then
-  if test "x$build_alias" = x; then
-    cross_compiling=maybe
-  elif test "x$build_alias" != "x$host_alias"; then
-    cross_compiling=yes
-  fi
-fi
-
-ac_tool_prefix=
-test -n "$host_alias" && ac_tool_prefix=$host_alias-
-
-test "$silent" = yes && exec 6>/dev/null
-
-
-ac_pwd=`pwd` && test -n "$ac_pwd" &&
-ac_ls_di=`ls -di .` &&
-ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
-  as_fn_error $? "working directory cannot be determined"
-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
-  as_fn_error $? "pwd does not report name of working directory"
-
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then the parent directory.
-  ac_confdir=`$as_dirname -- "$as_myself" ||
-$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_myself" : 'X\(//\)[^/]' \| \
-        X"$as_myself" : 'X\(//\)$' \| \
-        X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_myself" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-  srcdir=$ac_confdir
-  if test ! -r "$srcdir/$ac_unique_file"; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r "$srcdir/$ac_unique_file"; then
-  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
-  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
-fi
-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
-ac_abs_confdir=`(
-       cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
-       pwd)`
-# When building in place, set srcdir=.
-if test "$ac_abs_confdir" = "$ac_pwd"; then
-  srcdir=.
-fi
-# Remove unnecessary trailing slashes from srcdir.
-# Double slashes in file names in object file debugging info
-# mess up M-x gdb in Emacs.
-case $srcdir in
-*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
-esac
-for ac_var in $ac_precious_vars; do
-  eval ac_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_env_${ac_var}_value=\$${ac_var}
-  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_cv_env_${ac_var}_value=\$${ac_var}
-done
-
-#
-# Report the --help message.
-#
-if test "$ac_init_help" = "long"; then
-  # Omit some internal or obsolete options to make the list less imposing.
-  # This message is too long to be a string in the A/UX 3.1 sh.
-  cat <<_ACEOF
-\`configure' configures libcoap 4.1.1 to adapt to many kinds of systems.
-
-Usage: $0 [OPTION]... [VAR=VALUE]...
-
-To assign environment variables (e.g., CC, CFLAGS...), specify them as
-VAR=VALUE.  See below for descriptions of some of the useful variables.
-
-Defaults for the options are specified in brackets.
-
-Configuration:
-  -h, --help              display this help and exit
-      --help=short        display options specific to this package
-      --help=recursive    display the short help of all the included packages
-  -V, --version           display version information and exit
-  -q, --quiet, --silent   do not print \`checking ...' messages
-      --cache-file=FILE   cache test results in FILE [disabled]
-  -C, --config-cache      alias for \`--cache-file=config.cache'
-  -n, --no-create         do not create output files
-      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
-
-Installation directories:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-                          [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-                          [PREFIX]
-
-By default, \`make install' will install all the files in
-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
-an installation prefix other than \`$ac_default_prefix' using \`--prefix',
-for instance \`--prefix=\$HOME'.
-
-For better control, use the options below.
-
-Fine tuning of the installation directories:
-  --bindir=DIR            user executables [EPREFIX/bin]
-  --sbindir=DIR           system admin executables [EPREFIX/sbin]
-  --libexecdir=DIR        program executables [EPREFIX/libexec]
-  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
-  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
-  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
-  --libdir=DIR            object code libraries [EPREFIX/lib]
-  --includedir=DIR        C header files [PREFIX/include]
-  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
-  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
-  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
-  --infodir=DIR           info documentation [DATAROOTDIR/info]
-  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
-  --mandir=DIR            man documentation [DATAROOTDIR/man]
-  --docdir=DIR            documentation root [DATAROOTDIR/doc/libcoap]
-  --htmldir=DIR           html documentation [DOCDIR]
-  --dvidir=DIR            dvi documentation [DOCDIR]
-  --pdfdir=DIR            pdf documentation [DOCDIR]
-  --psdir=DIR             ps documentation [DOCDIR]
-_ACEOF
-
-  cat <<\_ACEOF
-_ACEOF
-fi
-
-if test -n "$ac_init_help"; then
-  case $ac_init_help in
-     short | recursive ) echo "Configuration of libcoap 4.1.1:";;
-   esac
-  cat <<\_ACEOF
-
-Optional Packages:
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --with-contiki          build libcoap for the Contiki OS
-  --without-debug         disable all debug output and assertions
-  --without-async         disable handling of asynchronous transactions and
-                          observe
-  --without-block         disable block transfer
-  --without-observe       disable resource observation
-  --without-query-filter  disable support for filters on /.well-known/core
-  --with-tests            enable unit tests (requires cunit)
-  --with-shared           build shared library
-
-Some influential environment variables:
-  CC          C compiler command
-  CFLAGS      C compiler flags
-  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
-              nonstandard directory <lib dir>
-  LIBS        libraries to pass to the linker, e.g. -l<library>
-  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
-              you have headers in a nonstandard directory <include dir>
-  CPP         C preprocessor
-
-Use these variables to override the choices made by `configure' or to help
-it to find libraries and programs with nonstandard names/locations.
-
-Report bugs to the package provider.
-_ACEOF
-ac_status=$?
-fi
-
-if test "$ac_init_help" = "recursive"; then
-  # If there are subdirs, report their specific --help.
-  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d "$ac_dir" ||
-      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
-      continue
-    ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-    cd "$ac_dir" || { ac_status=$?; continue; }
-    # Check for guested configure.
-    if test -f "$ac_srcdir/configure.gnu"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
-    elif test -f "$ac_srcdir/configure"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure" --help=recursive
-    else
-      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi || ac_status=$?
-    cd "$ac_pwd" || { ac_status=$?; break; }
-  done
-fi
-
-test -n "$ac_init_help" && exit $ac_status
-if $ac_init_version; then
-  cat <<\_ACEOF
-libcoap configure 4.1.1
-generated by GNU Autoconf 2.69
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This configure script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it.
-_ACEOF
-  exit
-fi
-
-## ------------------------ ##
-## Autoconf initialization. ##
-## ------------------------ ##
-
-# ac_fn_c_try_compile LINENO
-# --------------------------
-# Try to compile conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_compile ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext
-  if { { ac_try="$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compile") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && {
-        test -z "$ac_c_werror_flag" ||
-        test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_compile
-
-# ac_fn_c_try_run LINENO
-# ----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
-# that executables *can* be run.
-ac_fn_c_try_run ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
-  { { case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_try") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: program exited with status $ac_status" >&5
-       $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=$ac_status
-fi
-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_run
-
-# ac_fn_c_try_cpp LINENO
-# ----------------------
-# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_cpp ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } > conftest.i && {
-        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-        test ! -s conftest.err
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-    ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_cpp
-
-# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists and can be compiled using the include files in
-# INCLUDES, setting the cache variable VAR accordingly.
-ac_fn_c_check_header_compile ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  eval "$3=yes"
-else
-  eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_compile
-
-# ac_fn_c_try_link LINENO
-# -----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_link ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext conftest$ac_exeext
-  if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && {
-        test -z "$ac_c_werror_flag" ||
-        test ! -s conftest.err
-       } && test -s conftest$ac_exeext && {
-        test "$cross_compiling" = yes ||
-        test -x conftest$ac_exeext
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=1
-fi
-  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
-  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
-  # interfere with the next link command; also delete a directory that is
-  # left behind by Apple's compiler.  We do this before executing the actions.
-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_link
-
-# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists, giving a warning if it cannot be compiled using
-# the include files in INCLUDES and setting the cache variable VAR
-# accordingly.
-ac_fn_c_check_header_mongrel ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if eval \${$3+:} false; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
-$as_echo_n "checking $2 usability... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_header_compiler=yes
-else
-  ac_header_compiler=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
-$as_echo "$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
-$as_echo_n "checking $2 presence... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <$2>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  ac_header_preproc=yes
-else
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
-$as_echo "$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
-  yes:no: )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
-$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-  no:yes:* )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
-$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
-$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
-$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
-$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-esac
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eval "$3=\$ac_header_compiler"
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_mongrel
-
-# ac_fn_c_check_type LINENO TYPE VAR INCLUDES
-# -------------------------------------------
-# Tests whether TYPE exists after having included INCLUDES, setting cache
-# variable VAR accordingly.
-ac_fn_c_check_type ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eval "$3=no"
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-int
-main ()
-{
-if (sizeof ($2))
-        return 0;
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-int
-main ()
-{
-if (sizeof (($2)))
-           return 0;
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
-  eval "$3=yes"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_type
-
-# ac_fn_c_check_func LINENO FUNC VAR
-# ----------------------------------
-# Tests whether FUNC exists, setting the cache variable VAR accordingly
-ac_fn_c_check_func ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-/* Define $2 to an innocuous variant, in case <limits.h> declares $2.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $2 innocuous_$2
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $2 (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $2
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $2 ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$2 || defined __stub___$2
-choke me
-#endif
-
-int
-main ()
-{
-return $2 ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  eval "$3=yes"
-else
-  eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_func
-cat >config.log <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by libcoap $as_me 4.1.1, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
-
-  $ $0 $@
-
-_ACEOF
-exec 5>>config.log
-{
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
-
-/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
-/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
-/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
-
-_ASUNAME
-
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    $as_echo "PATH: $as_dir"
-  done
-IFS=$as_save_IFS
-
-} >&5
-
-cat >&5 <<_ACEOF
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-_ACEOF
-
-
-# Keep a trace of the command line.
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Strip out --silent because we don't want to record it for future runs.
-# Also quote any args containing shell meta-characters.
-# Make two passes to allow for proper duplicate-argument suppression.
-ac_configure_args=
-ac_configure_args0=
-ac_configure_args1=
-ac_must_keep_next=false
-for ac_pass in 1 2
-do
-  for ac_arg
-  do
-    case $ac_arg in
-    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
-    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-    | -silent | --silent | --silen | --sile | --sil)
-      continue ;;
-    *\'*)
-      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    case $ac_pass in
-    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
-    2)
-      as_fn_append ac_configure_args1 " '$ac_arg'"
-      if test $ac_must_keep_next = true; then
-       ac_must_keep_next=false # Got value, back to normal.
-      else
-       case $ac_arg in
-         *=* | --config-cache | -C | -disable-* | --disable-* \
-         | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
-         | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
-         | -with-* | --with-* | -without-* | --without-* | --x)
-           case "$ac_configure_args0 " in
-             "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
-           esac
-           ;;
-         -* ) ac_must_keep_next=true ;;
-       esac
-      fi
-      as_fn_append ac_configure_args " '$ac_arg'"
-      ;;
-    esac
-  done
-done
-{ ac_configure_args0=; unset ac_configure_args0;}
-{ ac_configure_args1=; unset ac_configure_args1;}
-
-# When interrupted or exit'd, cleanup temporary files, and complete
-# config.log.  We remove comments because anyway the quotes in there
-# would cause problems or look ugly.
-# WARNING: Use '\'' to represent an apostrophe within the trap.
-# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
-trap 'exit_status=$?
-  # Save into config.log some information that might help in debugging.
-  {
-    echo
-
-    $as_echo "## ---------------- ##
-## Cache variables. ##
-## ---------------- ##"
-    echo
-    # The following way of writing the cache mishandles newlines in values,
-(
-  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
-      *) { eval $ac_var=; unset $ac_var;} ;;
-      esac ;;
-    esac
-  done
-  (set) 2>&1 |
-    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      sed -n \
-       "s/'\''/'\''\\\\'\'''\''/g;
-         s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
-      ;; #(
-    *)
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-)
-    echo
-
-    $as_echo "## ----------------- ##
-## Output variables. ##
-## ----------------- ##"
-    echo
-    for ac_var in $ac_subst_vars
-    do
-      eval ac_val=\$$ac_var
-      case $ac_val in
-      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-      esac
-      $as_echo "$ac_var='\''$ac_val'\''"
-    done | sort
-    echo
-
-    if test -n "$ac_subst_files"; then
-      $as_echo "## ------------------- ##
-## File substitutions. ##
-## ------------------- ##"
-      echo
-      for ac_var in $ac_subst_files
-      do
-       eval ac_val=\$$ac_var
-       case $ac_val in
-       *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-       esac
-       $as_echo "$ac_var='\''$ac_val'\''"
-      done | sort
-      echo
-    fi
-
-    if test -s confdefs.h; then
-      $as_echo "## ----------- ##
-## confdefs.h. ##
-## ----------- ##"
-      echo
-      cat confdefs.h
-      echo
-    fi
-    test "$ac_signal" != 0 &&
-      $as_echo "$as_me: caught signal $ac_signal"
-    $as_echo "$as_me: exit $exit_status"
-  } >&5
-  rm -f core *.core core.conftest.* &&
-    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
-    exit $exit_status
-' 0
-for ac_signal in 1 2 13 15; do
-  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
-done
-ac_signal=0
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -f -r conftest* confdefs.h
-
-$as_echo "/* confdefs.h */" > confdefs.h
-
-# Predefined preprocessor variables.
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_URL "$PACKAGE_URL"
-_ACEOF
-
-
-# Let the site file select an alternate cache file if it wants to.
-# Prefer an explicitly selected file to automatically selected ones.
-ac_site_file1=NONE
-ac_site_file2=NONE
-if test -n "$CONFIG_SITE"; then
-  # We do not want a PATH search for config.site.
-  case $CONFIG_SITE in #((
-    -*)  ac_site_file1=./$CONFIG_SITE;;
-    */*) ac_site_file1=$CONFIG_SITE;;
-    *)   ac_site_file1=./$CONFIG_SITE;;
-  esac
-elif test "x$prefix" != xNONE; then
-  ac_site_file1=$prefix/share/config.site
-  ac_site_file2=$prefix/etc/config.site
-else
-  ac_site_file1=$ac_default_prefix/share/config.site
-  ac_site_file2=$ac_default_prefix/etc/config.site
-fi
-for ac_site_file in "$ac_site_file1" "$ac_site_file2"
-do
-  test "x$ac_site_file" = xNONE && continue
-  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
-$as_echo "$as_me: loading site script $ac_site_file" >&6;}
-    sed 's/^/| /' "$ac_site_file" >&5
-    . "$ac_site_file" \
-      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5; }
-  fi
-done
-
-if test -r "$cache_file"; then
-  # Some versions of bash will fail to source /dev/null (special files
-  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
-  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
-$as_echo "$as_me: loading cache $cache_file" >&6;}
-    case $cache_file in
-      [\\/]* | ?:[\\/]* ) . "$cache_file";;
-      *)                      . "./$cache_file";;
-    esac
-  fi
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
-$as_echo "$as_me: creating cache $cache_file" >&6;}
-  >$cache_file
-fi
-
-# Check that the precious variables saved in the cache have kept the same
-# value.
-ac_cache_corrupted=false
-for ac_var in $ac_precious_vars; do
-  eval ac_old_set=\$ac_cv_env_${ac_var}_set
-  eval ac_new_set=\$ac_env_${ac_var}_set
-  eval ac_old_val=\$ac_cv_env_${ac_var}_value
-  eval ac_new_val=\$ac_env_${ac_var}_value
-  case $ac_old_set,$ac_new_set in
-    set,)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,set)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,);;
-    *)
-      if test "x$ac_old_val" != "x$ac_new_val"; then
-       # differences in whitespace do not lead to failure.
-       ac_old_val_w=`echo x $ac_old_val`
-       ac_new_val_w=`echo x $ac_new_val`
-       if test "$ac_old_val_w" != "$ac_new_val_w"; then
-         { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
-$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
-         ac_cache_corrupted=:
-       else
-         { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
-$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
-         eval $ac_var=\$ac_old_val
-       fi
-       { $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
-$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
-       { $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
-$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
-      fi;;
-  esac
-  # Pass precious variables to config.status.
-  if test "$ac_new_set" = set; then
-    case $ac_new_val in
-    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
-    *) ac_arg=$ac_var=$ac_new_val ;;
-    esac
-    case " $ac_configure_args " in
-      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
-      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
-    esac
-  fi
-done
-if $ac_cache_corrupted; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
-$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
-  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
-fi
-## -------------------- ##
-## Main body of script. ##
-## -------------------- ##
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-
-# First check for Contiki build to quit configure before any other test
-
-# Check whether --with-contiki was given.
-if test "${with_contiki+set}" = set; then :
-  withval=$with_contiki; cp -p Makefile.contiki Makefile
-   cp -p config.h.contiki config.h
-   { $as_echo "$as_me:${as_lineno-$LINENO}: Contiki build prepared" >&5
-$as_echo "$as_me: Contiki build prepared" >&6;}
-   exit 0
-fi
-
-
-# Checks for programs.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
-$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
-set x ${MAKE-make}
-ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
-if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat >conftest.make <<\_ACEOF
-SHELL = /bin/sh
-all:
-       @echo '@@@%%%=$(MAKE)=@@@%%%'
-_ACEOF
-# GNU make sometimes prints "make[1]: Entering ...", which would confuse us.
-case `${MAKE-make} -f conftest.make 2>/dev/null` in
-  *@@@%%%=?*=@@@%%%*)
-    eval ac_cv_prog_make_${ac_make}_set=yes;;
-  *)
-    eval ac_cv_prog_make_${ac_make}_set=no;;
-esac
-rm -f conftest.make
-fi
-if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-  SET_MAKE=
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_CC"; then
-  ac_ct_CC=$CC
-  # Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_CC" = x; then
-    CC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
-else
-  CC="$ac_cv_prog_CC"
-fi
-
-if test -z "$CC"; then
-          if test -n "$ac_tool_prefix"; then
-    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  fi
-fi
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  ac_prog_rejected=no
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
-       ac_prog_rejected=yes
-       continue
-     fi
-    ac_cv_prog_CC="cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# != 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
-  fi
-fi
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$CC"; then
-  if test -n "$ac_tool_prefix"; then
-  for ac_prog in cl.exe
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-    test -n "$CC" && break
-  done
-fi
-if test -z "$CC"; then
-  ac_ct_CC=$CC
-  for ac_prog in cl.exe
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$ac_ct_CC" && break
-done
-
-  if test "x$ac_ct_CC" = x; then
-    CC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
-fi
-
-fi
-
-
-test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5; }
-
-# Provide some information about the compiler.
-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
-set X $ac_compile
-ac_compiler=$2
-for ac_option in --version -v -V -qversion; do
-  { { ac_try="$ac_compiler $ac_option >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    sed '10a\
-... rest of stderr output deleted ...
-         10q' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-  fi
-  rm -f conftest.er1 conftest.err
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-done
-
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
-# Try to create an executable without -o first, disregard a.out.
-# It will help us diagnose broken compilers, and finding out an intuition
-# of exeext.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
-$as_echo_n "checking whether the C compiler works... " >&6; }
-ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-
-# The possible output files:
-ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
-
-ac_rmfiles=
-for ac_file in $ac_files
-do
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
-    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
-  esac
-done
-rm -f $ac_rmfiles
-
-if { { ac_try="$ac_link_default"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link_default") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
-# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
-# in a Makefile.  We should not override ac_cv_exeext if it was cached,
-# so that the user can short-circuit this test for compilers unknown to
-# Autoconf.
-for ac_file in $ac_files ''
-do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
-       ;;
-    [ab].out )
-       # We found the default executable, but exeext='' is most
-       # certainly right.
-       break;;
-    *.* )
-       if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
-       then :; else
-          ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-       fi
-       # We set ac_cv_exeext here because the later test for it is not
-       # safe: cross compilers may not add the suffix if given an `-o'
-       # argument, so we may need to know it at that point already.
-       # Even if this section looks crufty: it has the advantage of
-       # actually working.
-       break;;
-    * )
-       break;;
-  esac
-done
-test "$ac_cv_exeext" = no && ac_cv_exeext=
-
-else
-  ac_file=''
-fi
-if test -z "$ac_file"; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-$as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
-$as_echo_n "checking for C compiler default output file name... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
-$as_echo "$ac_file" >&6; }
-ac_exeext=$ac_cv_exeext
-
-rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
-$as_echo_n "checking for suffix of executables... " >&6; }
-if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  # If both `conftest.exe' and `conftest' are `present' (well, observable)
-# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
-# work properly (i.e., refer to `conftest.exe'), while it won't with
-# `rm'.
-for ac_file in conftest.exe conftest conftest.*; do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
-    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-         break;;
-    * ) break;;
-  esac
-done
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest conftest$ac_cv_exeext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
-$as_echo "$ac_cv_exeext" >&6; }
-
-rm -f conftest.$ac_ext
-EXEEXT=$ac_cv_exeext
-ac_exeext=$EXEEXT
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdio.h>
-int
-main ()
-{
-FILE *f = fopen ("conftest.out", "w");
- return ferror (f) || fclose (f) != 0;
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files="$ac_clean_files conftest.out"
-# Check that the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
-$as_echo_n "checking whether we are cross compiling... " >&6; }
-if test "$cross_compiling" != yes; then
-  { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-  if { ac_try='./conftest$ac_cv_exeext'
-  { { case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_try") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then
-    cross_compiling=no
-  else
-    if test "$cross_compiling" = maybe; then
-       cross_compiling=yes
-    else
-       { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5; }
-    fi
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
-$as_echo "$cross_compiling" >&6; }
-
-rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
-$as_echo_n "checking for suffix of object files... " >&6; }
-if ${ac_cv_objext+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.o conftest.obj
-if { { ac_try="$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compile") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  for ac_file in conftest.o conftest.obj conftest.*; do
-  test -f "$ac_file" || continue;
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
-    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
-       break;;
-  esac
-done
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest.$ac_cv_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
-$as_echo "$ac_cv_objext" >&6; }
-OBJEXT=$ac_cv_objext
-ac_objext=$OBJEXT
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-#ifndef __GNUC__
-       choke me
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_compiler_gnu=yes
-else
-  ac_compiler_gnu=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_c_compiler_gnu=$ac_compiler_gnu
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
-$as_echo "$ac_cv_c_compiler_gnu" >&6; }
-if test $ac_compiler_gnu = yes; then
-  GCC=yes
-else
-  GCC=
-fi
-ac_test_CFLAGS=${CFLAGS+set}
-ac_save_CFLAGS=$CFLAGS
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
-$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_save_c_werror_flag=$ac_c_werror_flag
-   ac_c_werror_flag=yes
-   ac_cv_prog_cc_g=no
-   CFLAGS="-g"
-   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_g=yes
-else
-  CFLAGS=""
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
-  ac_c_werror_flag=$ac_save_c_werror_flag
-        CFLAGS="-g"
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_g=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-   ac_c_werror_flag=$ac_save_c_werror_flag
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
-$as_echo "$ac_cv_prog_cc_g" >&6; }
-if test "$ac_test_CFLAGS" = set; then
-  CFLAGS=$ac_save_CFLAGS
-elif test $ac_cv_prog_cc_g = yes; then
-  if test "$GCC" = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-g"
-  fi
-else
-  if test "$GCC" = yes; then
-    CFLAGS="-O2"
-  else
-    CFLAGS=
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_prog_cc_c89=no
-ac_save_CC=$CC
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdarg.h>
-#include <stdio.h>
-struct stat;
-/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
-struct buf { int x; };
-FILE * (*rcsopen) (struct buf *, struct stat *, int);
-static char *e (p, i)
-     char **p;
-     int i;
-{
-  return p[i];
-}
-static char *f (char * (*g) (char **, int), char **p, ...)
-{
-  char *s;
-  va_list v;
-  va_start (v,p);
-  s = g (p, va_arg (v,int));
-  va_end (v);
-  return s;
-}
-
-/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
-   function prototypes and stuff, but not '\xHH' hex character constants.
-   These don't provoke an error unfortunately, instead are silently treated
-   as 'x'.  The following induces an error, until -std is added to get
-   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
-   array size at least.  It's necessary to write '\x00'==0 to get something
-   that's true only with -std.  */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
-
-/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
-   inside strings and character constants.  */
-#define FOO(x) 'x'
-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
-
-int test (int i, double x);
-struct s1 {int (*f) (int a);};
-struct s2 {int (*f) (double a);};
-int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
-int argc;
-char **argv;
-int
-main ()
-{
-return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
-  ;
-  return 0;
-}
-_ACEOF
-for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
-       -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
-do
-  CC="$ac_save_CC $ac_arg"
-  if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_c89=$ac_arg
-fi
-rm -f core conftest.err conftest.$ac_objext
-  test "x$ac_cv_prog_cc_c89" != "xno" && break
-done
-rm -f conftest.$ac_ext
-CC=$ac_save_CC
-
-fi
-# AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
-  x)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
-$as_echo "none needed" >&6; } ;;
-  xno)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; } ;;
-  *)
-    CC="$CC $ac_cv_prog_cc_c89"
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
-esac
-if test "x$ac_cv_prog_cc_c89" != xno; then :
-
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
-$as_echo "$RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_RANLIB"; then
-  ac_ct_RANLIB=$RANLIB
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_RANLIB"; then
-  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RANLIB="ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
-$as_echo "$ac_ct_RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_RANLIB" = x; then
-    RANLIB=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    RANLIB=$ac_ct_RANLIB
-  fi
-else
-  RANLIB="$ac_cv_prog_RANLIB"
-fi
-
-# Extract the first word of "doxygen", so it can be a program name with args.
-set dummy doxygen; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_DOXYGEN+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $DOXYGEN in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_path_DOXYGEN" && ac_cv_path_DOXYGEN=":"
-  ;;
-esac
-fi
-DOXYGEN=$ac_cv_path_DOXYGEN
-if test -n "$DOXYGEN"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5
-$as_echo "$DOXYGEN" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-# Extract the first word of "etags", so it can be a program name with args.
-set dummy etags; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_ETAGS+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $ETAGS in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_ETAGS="$ETAGS" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_ETAGS="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_path_ETAGS" && ac_cv_path_ETAGS="/bin/false"
-  ;;
-esac
-fi
-ETAGS=$ac_cv_path_ETAGS
-if test -n "$ETAGS"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ETAGS" >&5
-$as_echo "$ETAGS" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
-$as_echo_n "checking how to run the C preprocessor... " >&6; }
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-  if ${ac_cv_prog_CPP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
-    do
-      ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-                    Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-  break
-fi
-
-    done
-    ac_cv_prog_CPP=$CPP
-
-fi
-  CPP=$ac_cv_prog_CPP
-else
-  ac_cv_prog_CPP=$CPP
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
-$as_echo "$CPP" >&6; }
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-                    Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
-$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if ${ac_cv_path_GREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -z "$GREP"; then
-  ac_path_GREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in grep ggrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_GREP" || continue
-# Check for GNU ac_path_GREP and select it if it is found.
-  # Check for GNU $ac_path_GREP
-case `"$ac_path_GREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'GREP' >> "conftest.nl"
-    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_GREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_GREP="$ac_path_GREP"
-      ac_path_GREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_GREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_GREP"; then
-    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_GREP=$GREP
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
-$as_echo "$ac_cv_path_GREP" >&6; }
- GREP="$ac_cv_path_GREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
-$as_echo_n "checking for egrep... " >&6; }
-if ${ac_cv_path_EGREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
-   then ac_cv_path_EGREP="$GREP -E"
-   else
-     if test -z "$EGREP"; then
-  ac_path_EGREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in egrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_EGREP" || continue
-# Check for GNU ac_path_EGREP and select it if it is found.
-  # Check for GNU $ac_path_EGREP
-case `"$ac_path_EGREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'EGREP' >> "conftest.nl"
-    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_EGREP="$ac_path_EGREP"
-      ac_path_EGREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_EGREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_EGREP"; then
-    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_EGREP=$EGREP
-fi
-
-   fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
-$as_echo "$ac_cv_path_EGREP" >&6; }
- EGREP="$ac_cv_path_EGREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
-$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_header_stdc=yes
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" = yes; then :
-  :
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ctype.h>
-#include <stdlib.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
-                  (('a' <= (c) && (c) <= 'i') \
-                    || ('j' <= (c) && (c) <= 'r') \
-                    || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
-
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
-  int i;
-  for (i = 0; i < 256; i++)
-    if (XOR (islower (i), ISLOWER (i))
-       || toupper (i) != TOUPPER (i))
-      return 2;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
-$as_echo "$ac_cv_header_stdc" >&6; }
-if test $ac_cv_header_stdc = yes; then
-
-$as_echo "#define STDC_HEADERS 1" >>confdefs.h
-
-fi
-
-# On IRIX 5.3, sys/types and inttypes.h are conflicting.
-for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
-                 inttypes.h stdint.h unistd.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
-"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
-$as_echo_n "checking whether byte ordering is bigendian... " >&6; }
-if ${ac_cv_c_bigendian+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_c_bigendian=unknown
-    # See if we're dealing with a universal compiler.
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifndef __APPLE_CC__
-              not a universal capable compiler
-            #endif
-            typedef int dummy;
-
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-       # Check for potential -arch flags.  It is not universal unless
-       # there are at least two -arch flags with different values.
-       ac_arch=
-       ac_prev=
-       for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do
-        if test -n "$ac_prev"; then
-          case $ac_word in
-            i?86 | x86_64 | ppc | ppc64)
-              if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then
-                ac_arch=$ac_word
-              else
-                ac_cv_c_bigendian=universal
-                break
-              fi
-              ;;
-          esac
-          ac_prev=
-        elif test "x$ac_word" = "x-arch"; then
-          ac_prev=arch
-        fi
-       done
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    if test $ac_cv_c_bigendian = unknown; then
-      # See if sys/param.h defines the BYTE_ORDER macro.
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
-            #include <sys/param.h>
-
-int
-main ()
-{
-#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \
-                    && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \
-                    && LITTLE_ENDIAN)
-             bogus endian macros
-            #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  # It does; now see whether it defined to BIG_ENDIAN or not.
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
-               #include <sys/param.h>
-
-int
-main ()
-{
-#if BYTE_ORDER != BIG_ENDIAN
-                not big endian
-               #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_bigendian=yes
-else
-  ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    fi
-    if test $ac_cv_c_bigendian = unknown; then
-      # See if <limits.h> defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris).
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <limits.h>
-
-int
-main ()
-{
-#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN)
-             bogus endian macros
-            #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  # It does; now see whether it defined to _BIG_ENDIAN or not.
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <limits.h>
-
-int
-main ()
-{
-#ifndef _BIG_ENDIAN
-                not big endian
-               #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_bigendian=yes
-else
-  ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    fi
-    if test $ac_cv_c_bigendian = unknown; then
-      # Compile a test program.
-      if test "$cross_compiling" = yes; then :
-  # Try to guess by grepping values from an object file.
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-short int ascii_mm[] =
-                 { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
-               short int ascii_ii[] =
-                 { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
-               int use_ascii (int i) {
-                 return ascii_mm[i] + ascii_ii[i];
-               }
-               short int ebcdic_ii[] =
-                 { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
-               short int ebcdic_mm[] =
-                 { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
-               int use_ebcdic (int i) {
-                 return ebcdic_mm[i] + ebcdic_ii[i];
-               }
-               extern int foo;
-
-int
-main ()
-{
-return use_ascii (foo) == use_ebcdic (foo);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then
-             ac_cv_c_bigendian=yes
-           fi
-           if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then
-             if test "$ac_cv_c_bigendian" = unknown; then
-               ac_cv_c_bigendian=no
-             else
-               # finding both strings is unlikely to happen, but who knows?
-               ac_cv_c_bigendian=unknown
-             fi
-           fi
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-
-            /* Are we little or big endian?  From Harbison&Steele.  */
-            union
-            {
-              long int l;
-              char c[sizeof (long int)];
-            } u;
-            u.l = 1;
-            return u.c[sizeof (long int) - 1] == 1;
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-  ac_cv_c_bigendian=no
-else
-  ac_cv_c_bigendian=yes
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-    fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5
-$as_echo "$ac_cv_c_bigendian" >&6; }
- case $ac_cv_c_bigendian in #(
-   yes)
-     $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h
-;; #(
-   no)
-      ;; #(
-   universal)
-
-$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
-
-     ;; #(
-   *)
-     as_fn_error $? "unknown endianness
- presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;;
- esac
-
-
-# Checks for libraries.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for coap_new_pdu in -lcoap" >&5
-$as_echo_n "checking for coap_new_pdu in -lcoap... " >&6; }
-if ${ac_cv_lib_coap_coap_new_pdu+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lcoap  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char coap_new_pdu ();
-int
-main ()
-{
-return coap_new_pdu ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_coap_coap_new_pdu=yes
-else
-  ac_cv_lib_coap_coap_new_pdu=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_coap_coap_new_pdu" >&5
-$as_echo "$ac_cv_lib_coap_coap_new_pdu" >&6; }
-if test "x$ac_cv_lib_coap_coap_new_pdu" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBCOAP 1
-_ACEOF
-
-  LIBS="-lcoap $LIBS"
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gethostbyname" >&5
-$as_echo_n "checking for library containing gethostbyname... " >&6; }
-if ${ac_cv_search_gethostbyname+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gethostbyname ();
-int
-main ()
-{
-return gethostbyname ();
-  ;
-  return 0;
-}
-_ACEOF
-for ac_lib in '' nsl; do
-  if test -z "$ac_lib"; then
-    ac_res="none required"
-  else
-    ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
-  fi
-  if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_search_gethostbyname=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext
-  if ${ac_cv_search_gethostbyname+:} false; then :
-  break
-fi
-done
-if ${ac_cv_search_gethostbyname+:} false; then :
-
-else
-  ac_cv_search_gethostbyname=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gethostbyname" >&5
-$as_echo "$ac_cv_search_gethostbyname" >&6; }
-ac_res=$ac_cv_search_gethostbyname
-if test "$ac_res" != no; then :
-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing socket" >&5
-$as_echo_n "checking for library containing socket... " >&6; }
-if ${ac_cv_search_socket+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char socket ();
-int
-main ()
-{
-return socket ();
-  ;
-  return 0;
-}
-_ACEOF
-for ac_lib in '' socket; do
-  if test -z "$ac_lib"; then
-    ac_res="none required"
-  else
-    ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
-  fi
-  if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_search_socket=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext
-  if ${ac_cv_search_socket+:} false; then :
-  break
-fi
-done
-if ${ac_cv_search_socket+:} false; then :
-
-else
-  ac_cv_search_socket=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_socket" >&5
-$as_echo "$ac_cv_search_socket" >&6; }
-ac_res=$ac_cv_search_socket
-if test "$ac_res" != no; then :
-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-
-# configuration options that may change compile flags
-
-# Check whether --with-debug was given.
-if test "${with_debug+set}" = set; then :
-  withval=$with_debug; CPPFLAGS="${CPPFLAGS} -DNDEBUG"
-fi
-
-
-
-# Check whether --with-async was given.
-if test "${with_async+set}" = set; then :
-  withval=$with_async; CPPFLAGS="${CPPFLAGS} -DWITHOUT_ASYNC"
-fi
-
-
-
-# Check whether --with-block was given.
-if test "${with_block+set}" = set; then :
-  withval=$with_block; CPPFLAGS="${CPPFLAGS} -DWITHOUT_BLOCK"
-fi
-
-
-
-# Check whether --with-observe was given.
-if test "${with_observe+set}" = set; then :
-  withval=$with_observe; CPPFLAGS="${CPPFLAGS} -DWITHOUT_OBSERVE"
-fi
-
-
-
-# Check whether --with-query-filter was given.
-if test "${with_query_filter+set}" = set; then :
-  withval=$with_query_filter; CPPFLAGS="${CPPFLAGS} -DWITHOUT_QUERY_FILTER"
-fi
-
-
-
-# Check whether --with-tests was given.
-if test "${with_tests+set}" = set; then :
-  withval=$with_tests; TESTS="tests"
-fi
-
-
-
-# Check whether --with-shared was given.
-if test "${with_shared+set}" = set; then :
-  withval=$with_shared; BUILD_SO="BUILD_SO=1"
-fi
-
-
-# disambiguate between autoconf generated setups and contiki / lwip setups
-# which use explicit config.h.* files
-CPPFLAGS="${CPPFLAGS} -DWITH_POSIX"
-
-# Checks for header files.
-for ac_header in assert.h arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h strings.h sys/socket.h sys/time.h time.h unistd.h sys/unistd.h syslog.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-# Checks for typedefs, structures, and compiler characteristics.
-ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default"
-if test "x$ac_cv_type_size_t" = xyes; then :
-
-else
-
-cat >>confdefs.h <<_ACEOF
-#define size_t unsigned int
-_ACEOF
-
-fi
-
-ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default"
-if test "x$ac_cv_type_ssize_t" = xyes; then :
-
-else
-
-cat >>confdefs.h <<_ACEOF
-#define ssize_t int
-_ACEOF
-
-fi
-
-
-# Checks for library functions.
-for ac_header in stdlib.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default"
-if test "x$ac_cv_header_stdlib_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_STDLIB_H 1
-_ACEOF
-
-fi
-
-done
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5
-$as_echo_n "checking for GNU libc compatible malloc... " >&6; }
-if ${ac_cv_func_malloc_0_nonnull+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test "$cross_compiling" = yes; then :
-  ac_cv_func_malloc_0_nonnull=no
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#if defined STDC_HEADERS || defined HAVE_STDLIB_H
-# include <stdlib.h>
-#else
-char *malloc ();
-#endif
-
-int
-main ()
-{
-return ! malloc (0);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-  ac_cv_func_malloc_0_nonnull=yes
-else
-  ac_cv_func_malloc_0_nonnull=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5
-$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; }
-if test $ac_cv_func_malloc_0_nonnull = yes; then :
-
-$as_echo "#define HAVE_MALLOC 1" >>confdefs.h
-
-else
-  $as_echo "#define HAVE_MALLOC 0" >>confdefs.h
-
-   case " $LIBOBJS " in
-  *" malloc.$ac_objext "* ) ;;
-  *) LIBOBJS="$LIBOBJS malloc.$ac_objext"
- ;;
-esac
-
-
-$as_echo "#define malloc rpl_malloc" >>confdefs.h
-
-fi
-
-
-for ac_func in memset select socket strcasecmp strrchr getaddrinfo strnlen
-do :
-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-
-
-
-
-ac_config_headers="$ac_config_headers config.h"
-
-
-ac_config_files="$ac_config_files Makefile doc/Makefile doc/Doxyfile examples/Makefile tests/Makefile"
-
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems.  If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
-
-_ACEOF
-
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, we kill variables containing newlines.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(
-  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
-      *) { eval $ac_var=; unset $ac_var;} ;;
-      esac ;;
-    esac
-  done
-
-  (set) 2>&1 |
-    case $as_nl`(ac_space=' '; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      # `set' does not quote correctly, so add quotes: double-quote
-      # substitution turns \\\\ into \\, and sed turns \\ into \.
-      sed -n \
-       "s/'/'\\\\''/g;
-         s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
-      ;; #(
-    *)
-      # `set' quotes correctly as required by POSIX, so do not add quotes.
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-) |
-  sed '
-     /^ac_cv_env_/b end
-     t clear
-     :clear
-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
-     t end
-     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
-     :end' >>confcache
-if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
-  if test -w "$cache_file"; then
-    if test "x$cache_file" != "x/dev/null"; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
-$as_echo "$as_me: updating cache $cache_file" >&6;}
-      if test ! -f "$cache_file" || test -h "$cache_file"; then
-       cat confcache >"$cache_file"
-      else
-        case $cache_file in #(
-        */* | ?:*)
-         mv -f confcache "$cache_file"$$ &&
-         mv -f "$cache_file"$$ "$cache_file" ;; #(
-        *)
-         mv -f confcache "$cache_file" ;;
-       esac
-      fi
-    fi
-  else
-    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
-$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
-  fi
-fi
-rm -f confcache
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-DEFS=-DHAVE_CONFIG_H
-
-ac_libobjs=
-ac_ltlibobjs=
-U=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
-  # 1. Remove the extension, and $U if already installed.
-  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
-  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
-  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
-  #    will be set to the directory where LIBOBJS objects are built.
-  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
-  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
-
-LTLIBOBJS=$ac_ltlibobjs
-
-
-
-
-: "${CONFIG_STATUS=./config.status}"
-ac_write_fail=0
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
-$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
-as_write_fail=0
-cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-
-SHELL=\${CONFIG_SHELL-$SHELL}
-export SHELL
-_ASEOF
-cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-       expr "X$arg" : "X\\(.*\\)$as_nl";
-       arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
-      PATH_SEPARATOR=';'
-  }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""       $as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-  done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
-  as_status=$1; test $as_status -eq 0 && as_status=1
-  if test "$4"; then
-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
-  fi
-  $as_echo "$as_me: error: $2" >&2
-  as_fn_exit $as_status
-} # as_fn_error
-
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
-  return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
-  set +e
-  as_fn_set_status $1
-  exit $1
-} # as_fn_exit
-
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
-  { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
-  eval 'as_fn_append ()
-  {
-    eval $1+=\$2
-  }'
-else
-  as_fn_append ()
-  {
-    eval $1=\$$1\$2
-  }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
-  eval 'as_fn_arith ()
-  {
-    as_val=$(( $* ))
-  }'
-else
-  as_fn_arith ()
-  {
-    as_val=`expr "$@" || test $? -eq 1`
-  }
-fi # as_fn_arith
-
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-        X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\/\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
-  case `echo 'xy\c'` in
-  *c*) ECHO_T='        ';;     # ECHO_T is single tab character.
-  xy)  ECHO_C='\c';;
-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
-       ECHO_T='        ';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
-  if ln -s conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s='ln -s'
-    # ... but there are two gotchas:
-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -pR'.
-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -pR'
-  elif ln conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s=ln
-  else
-    as_ln_s='cp -pR'
-  fi
-else
-  as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || eval $as_mkdir_p || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_dir" : 'X\(//\)[^/]' \| \
-        X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p='mkdir -p "$as_dir"'
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
-  test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-## ----------------------------------- ##
-## Main body of $CONFIG_STATUS script. ##
-## ----------------------------------- ##
-_ASEOF
-test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# Save the log message, to keep $0 and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by libcoap $as_me 4.1.1, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
-
-  CONFIG_FILES    = $CONFIG_FILES
-  CONFIG_HEADERS  = $CONFIG_HEADERS
-  CONFIG_LINKS    = $CONFIG_LINKS
-  CONFIG_COMMANDS = $CONFIG_COMMANDS
-  $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-_ACEOF
-
-case $ac_config_files in *"
-"*) set x $ac_config_files; shift; ac_config_files=$*;;
-esac
-
-case $ac_config_headers in *"
-"*) set x $ac_config_headers; shift; ac_config_headers=$*;;
-esac
-
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-# Files that config.status was made for.
-config_files="$ac_config_files"
-config_headers="$ac_config_headers"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-ac_cs_usage="\
-\`$as_me' instantiates files and other configuration actions
-from templates according to the current configuration.  Unless the files
-and actions are specified as TAGs, all are instantiated by default.
-
-Usage: $0 [OPTION]... [TAG]...
-
-  -h, --help       print this help, then exit
-  -V, --version    print version number and configuration settings, then exit
-      --config     print configuration, then exit
-  -q, --quiet, --silent
-                   do not print progress messages
-  -d, --debug      don't remove temporary files
-      --recheck    update $as_me by reconfiguring in the same conditions
-      --file=FILE[:TEMPLATE]
-                   instantiate the configuration file FILE
-      --header=FILE[:TEMPLATE]
-                   instantiate the configuration header FILE
-
-Configuration files:
-$config_files
-
-Configuration headers:
-$config_headers
-
-Report bugs to the package provider."
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
-ac_cs_version="\\
-libcoap config.status 4.1.1
-configured by $0, generated by GNU Autoconf 2.69,
-  with options \\"\$ac_cs_config\\"
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='$ac_pwd'
-srcdir='$srcdir'
-test -n "\$AWK" || AWK=awk
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# The default lists apply if the user does not specify any file.
-ac_need_defaults=:
-while test $# != 0
-do
-  case $1 in
-  --*=?*)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
-    ac_shift=:
-    ;;
-  --*=)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=
-    ac_shift=:
-    ;;
-  *)
-    ac_option=$1
-    ac_optarg=$2
-    ac_shift=shift
-    ;;
-  esac
-
-  case $ac_option in
-  # Handling of the options.
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    ac_cs_recheck=: ;;
-  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    $as_echo "$ac_cs_version"; exit ;;
-  --config | --confi | --conf | --con | --co | --c )
-    $as_echo "$ac_cs_config"; exit ;;
-  --debug | --debu | --deb | --de | --d | -d )
-    debug=: ;;
-  --file | --fil | --fi | --f )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    '') as_fn_error $? "missing file argument" ;;
-    esac
-    as_fn_append CONFIG_FILES " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --header | --heade | --head | --hea )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --he | --h)
-    # Conflict between --help and --header
-    as_fn_error $? "ambiguous option: \`$1'
-Try \`$0 --help' for more information.";;
-  --help | --hel | -h )
-    $as_echo "$ac_cs_usage"; exit ;;
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil | --si | --s)
-    ac_cs_silent=: ;;
-
-  # This is an error.
-  -*) as_fn_error $? "unrecognized option: \`$1'
-Try \`$0 --help' for more information." ;;
-
-  *) as_fn_append ac_config_targets " $1"
-     ac_need_defaults=false ;;
-
-  esac
-  shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
-  exec 6>/dev/null
-  ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-if \$ac_cs_recheck; then
-  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
-  shift
-  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
-  CONFIG_SHELL='$SHELL'
-  export CONFIG_SHELL
-  exec "\$@"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-  $as_echo "$ac_log"
-} >&5
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
-  case $ac_config_target in
-    "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
-    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-    "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;;
-    "doc/Doxyfile") CONFIG_FILES="$CONFIG_FILES doc/Doxyfile" ;;
-    "examples/Makefile") CONFIG_FILES="$CONFIG_FILES examples/Makefile" ;;
-    "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;;
-
-  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
-  esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used.  Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
-fi
-
-# Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
-  tmp= ac_tmp=
-  trap 'exit_status=$?
-  : "${ac_tmp:=$tmp}"
-  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
-' 0
-  trap 'as_fn_exit 1' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
-  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
-  test -d "$tmp"
-}  ||
-{
-  tmp=./conf$$-$RANDOM
-  (umask 077 && mkdir "$tmp")
-} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
-ac_tmp=$tmp
-
-# Set up the scripts for CONFIG_FILES section.
-# No need to generate them if there are no CONFIG_FILES.
-# This happens for instance with `./config.status config.h'.
-if test -n "$CONFIG_FILES"; then
-
-
-ac_cr=`echo X | tr X '\015'`
-# On cygwin, bash can eat \r inside `` if the user requested igncr.
-# But we know of no other shell where ac_cr would be empty at this
-# point, so we can use a bashism as a fallback.
-if test "x$ac_cr" = x; then
-  eval ac_cr=\$\'\\r\'
-fi
-ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
-if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
-  ac_cs_awk_cr='\\r'
-else
-  ac_cs_awk_cr=$ac_cr
-fi
-
-echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
-_ACEOF
-
-
-{
-  echo "cat >conf$$subs.awk <<_ACEOF" &&
-  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
-  echo "_ACEOF"
-} >conf$$subs.sh ||
-  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
-ac_delim='%!_!# '
-for ac_last_try in false false false false false :; do
-  . ./conf$$subs.sh ||
-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-
-  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
-  if test $ac_delim_n = $ac_delim_num; then
-    break
-  elif $ac_last_try; then
-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-rm -f conf$$subs.sh
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
-_ACEOF
-sed -n '
-h
-s/^/S["/; s/!.*/"]=/
-p
-g
-s/^[^!]*!//
-:repl
-t repl
-s/'"$ac_delim"'$//
-t delim
-:nl
-h
-s/\(.\{148\}\)..*/\1/
-t more1
-s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
-p
-n
-b repl
-:more1
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t nl
-:delim
-h
-s/\(.\{148\}\)..*/\1/
-t more2
-s/["\\]/\\&/g; s/^/"/; s/$/"/
-p
-b
-:more2
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t delim
-' <conf$$subs.awk | sed '
-/^[^""]/{
-  N
-  s/\n//
-}
-' >>$CONFIG_STATUS || ac_write_fail=1
-rm -f conf$$subs.awk
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACAWK
-cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
-  for (key in S) S_is_set[key] = 1
-  FS = "\a"
-
-}
-{
-  line = $ 0
-  nfields = split(line, field, "@")
-  substed = 0
-  len = length(field[1])
-  for (i = 2; i < nfields; i++) {
-    key = field[i]
-    keylen = length(key)
-    if (S_is_set[key]) {
-      value = S[key]
-      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
-      len += length(value) + length(field[++i])
-      substed = 1
-    } else
-      len += 1 + keylen
-  }
-
-  print line
-}
-
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
-  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
-else
-  cat
-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
-  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
-_ACEOF
-
-# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
-# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[         ]*VPATH[        ]*=[    ]*/{
-h
-s///
-s/^/:/
-s/[     ]*$/:/
-s/:\$(srcdir):/:/g
-s/:\${srcdir}:/:/g
-s/:@srcdir@:/:/g
-s/^:*//
-s/:*$//
-x
-s/\(=[  ]*\).*/\1/
-G
-s/\n//
-s/^[^=]*=[      ]*$//
-}'
-fi
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-fi # test -n "$CONFIG_FILES"
-
-# Set up the scripts for CONFIG_HEADERS section.
-# No need to generate them if there are no CONFIG_HEADERS.
-# This happens for instance with `./config.status Makefile'.
-if test -n "$CONFIG_HEADERS"; then
-cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
-BEGIN {
-_ACEOF
-
-# Transform confdefs.h into an awk script `defines.awk', embedded as
-# here-document in config.status, that substitutes the proper values into
-# config.h.in to produce config.h.
-
-# Create a delimiter string that does not exist in confdefs.h, to ease
-# handling of long lines.
-ac_delim='%!_!# '
-for ac_last_try in false false :; do
-  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
-  if test -z "$ac_tt"; then
-    break
-  elif $ac_last_try; then
-    as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-
-# For the awk script, D is an array of macro values keyed by name,
-# likewise P contains macro parameters if any.  Preserve backslash
-# newline sequences.
-
-ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
-sed -n '
-s/.\{148\}/&'"$ac_delim"'/g
-t rset
-:rset
-s/^[    ]*#[    ]*define[       ][      ]*/ /
-t def
-d
-:def
-s/\\$//
-t bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[    ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3"/p
-s/^ \('"$ac_word_re"'\)[        ]*\(.*\)/D["\1"]=" \2"/p
-d
-:bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[    ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3\\\\\\n"\\/p
-t cont
-s/^ \('"$ac_word_re"'\)[        ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p
-t cont
-d
-:cont
-n
-s/.\{148\}/&'"$ac_delim"'/g
-t clear
-:clear
-s/\\$//
-t bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/"/p
-d
-:bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
-b cont
-' <confdefs.h | sed '
-s/'"$ac_delim"'/"\\\
-"/g' >>$CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-  for (key in D) D_is_set[key] = 1
-  FS = "\a"
-}
-/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
-  line = \$ 0
-  split(line, arg, " ")
-  if (arg[1] == "#") {
-    defundef = arg[2]
-    mac1 = arg[3]
-  } else {
-    defundef = substr(arg[1], 2)
-    mac1 = arg[2]
-  }
-  split(mac1, mac2, "(") #)
-  macro = mac2[1]
-  prefix = substr(line, 1, index(line, defundef) - 1)
-  if (D_is_set[macro]) {
-    # Preserve the white space surrounding the "#".
-    print prefix "define", macro P[macro] D[macro]
-    next
-  } else {
-    # Replace #undef with comments.  This is necessary, for example,
-    # in the case of _POSIX_SOURCE, which is predefined and required
-    # on some systems where configure will not decide to define it.
-    if (defundef == "undef") {
-      print "/*", prefix defundef, macro, "*/"
-      next
-    }
-  }
-}
-{ print }
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
-fi # test -n "$CONFIG_HEADERS"
-
-
-eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "
-shift
-for ac_tag
-do
-  case $ac_tag in
-  :[FHLC]) ac_mode=$ac_tag; continue;;
-  esac
-  case $ac_mode$ac_tag in
-  :[FHL]*:*);;
-  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
-  :[FH]-) ac_tag=-:-;;
-  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
-  esac
-  ac_save_IFS=$IFS
-  IFS=:
-  set x $ac_tag
-  IFS=$ac_save_IFS
-  shift
-  ac_file=$1
-  shift
-
-  case $ac_mode in
-  :L) ac_source=$1;;
-  :[FH])
-    ac_file_inputs=
-    for ac_f
-    do
-      case $ac_f in
-      -) ac_f="$ac_tmp/stdin";;
-      *) # Look for the file first in the build tree, then in the source tree
-        # (if the path is not absolute).  The absolute path cannot be DOS-style,
-        # because $ac_f cannot contain `:'.
-        test -f "$ac_f" ||
-          case $ac_f in
-          [\\/$]*) false;;
-          *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
-          esac ||
-          as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
-      esac
-      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
-      as_fn_append ac_file_inputs " '$ac_f'"
-    done
-
-    # Let's still pretend it is `configure' which instantiates (i.e., don't
-    # use $as_me), people would be surprised to read:
-    #    /* config.h.  Generated by config.status.  */
-    configure_input='Generated from '`
-         $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
-       `' by configure.'
-    if test x"$ac_file" != x-; then
-      configure_input="$ac_file.  $configure_input"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
-$as_echo "$as_me: creating $ac_file" >&6;}
-    fi
-    # Neutralize special characters interpreted by sed in replacement strings.
-    case $configure_input in #(
-    *\&* | *\|* | *\\* )
-       ac_sed_conf_input=`$as_echo "$configure_input" |
-       sed 's/[\\\\&|]/\\\\&/g'`;; #(
-    *) ac_sed_conf_input=$configure_input;;
-    esac
-
-    case $ac_tag in
-    *:-:* | *:-) cat >"$ac_tmp/stdin" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
-    esac
-    ;;
-  esac
-
-  ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$ac_file" : 'X\(//\)[^/]' \| \
-        X"$ac_file" : 'X\(//\)$' \| \
-        X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)[^/].*/{
-           s//\1/
-           q
-         }
-         /^X\(\/\/\)$/{
-           s//\1/
-           q
-         }
-         /^X\(\/\).*/{
-           s//\1/
-           q
-         }
-         s/.*/./; q'`
-  as_dir="$ac_dir"; as_fn_mkdir_p
-  ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
-  case $ac_mode in
-  :F)
-  #
-  # CONFIG_FILE
-  #
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-ac_sed_dataroot='
-/datarootdir/ {
-  p
-  q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p'
-case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-  ac_datarootdir_hack='
-  s&@datadir@&$datadir&g
-  s&@docdir@&$docdir&g
-  s&@infodir@&$infodir&g
-  s&@localedir@&$localedir&g
-  s&@mandir@&$mandir&g
-  s&\\\${datarootdir}&$datarootdir&g' ;;
-esac
-_ACEOF
-
-# Neutralize VPATH when `$srcdir' = `.'.
-# Shell code in configure.ac might set extrasub.
-# FIXME: do we really want to maintain this feature?
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_sed_extra="$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s|@configure_input@|$ac_sed_conf_input|;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@top_build_prefix@&$ac_top_build_prefix&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-$ac_datarootdir_hack
-"
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
-  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
-  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
-  { ac_out=`sed -n '/^[         ]*datarootdir[  ]*:*=/p' \
-      "$ac_tmp/out"`; test -z "$ac_out"; } &&
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&5
-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&2;}
-
-  rm -f "$ac_tmp/stdin"
-  case $ac_file in
-  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
-  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
-  esac \
-  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- ;;
-  :H)
-  #
-  # CONFIG_HEADER
-  #
-  if test x"$ac_file" != x-; then
-    {
-      $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
-    } >"$ac_tmp/config.h" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
-$as_echo "$as_me: $ac_file is unchanged" >&6;}
-    else
-      rm -f "$ac_file"
-      mv "$ac_tmp/config.h" "$ac_file" \
-       || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    fi
-  else
-    $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
-      || as_fn_error $? "could not create -" "$LINENO" 5
-  fi
- ;;
-
-
-  esac
-
-done # for ac_tag
-
-
-as_fn_exit 0
-_ACEOF
-ac_clean_files=$ac_clean_files_save
-
-test $ac_write_fail = 0 ||
-  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
-
-
-# configure is writing to config.log, and then calls config.status.
-# config.status does its own redirection, appending to config.log.
-# Unfortunately, on DOS this fails, as config.log is still kept open
-# by configure, so config.status won't be able to write to it; its
-# output is simply discarded.  So we exec the FD to /dev/null,
-# effectively closing config.log, so it can be properly (re)opened and
-# appended to by config.status.  When coming back to configure, we
-# need to make the FD available again.
-if test "$no_create" != yes; then
-  ac_cs_success=:
-  ac_config_status_args=
-  test "$silent" = yes &&
-    ac_config_status_args="$ac_config_status_args --quiet"
-  exec 5>/dev/null
-  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
-  exec 5>>config.log
-  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
-  # would make configure fail if this is the last instruction.
-  $ac_cs_success || as_fn_exit 1
-fi
-if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
-$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
-fi
-
diff --git a/resource/csdk/libcoap-4.1.1/configure.in b/resource/csdk/libcoap-4.1.1/configure.in
deleted file mode 100644 (file)
index 77f6c8f..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-#                                               -*- Autoconf -*-
-# Process this file with autoconf to produce a configure script.
-#
-# Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
-#
-# This file is part of the CoAP library libcoap. Please see
-# README for terms of use. 
-
-AC_PREREQ([2.65])
-AC_INIT([libcoap], [4.1.1])
-AC_CONFIG_SRCDIR([coap.h])
-
-# First check for Contiki build to quit configure before any other test
-AC_ARG_WITH(contiki,
-  [AS_HELP_STRING([--with-contiki],[build libcoap for the Contiki OS])],
-  [cp -p Makefile.contiki Makefile
-   cp -p config.h.contiki config.h
-   AC_MSG_NOTICE([Contiki build prepared])
-   exit 0], 
-  [])
-
-# Checks for programs.
-AC_PROG_MAKE_SET
-AC_PROG_CC
-AC_PROG_RANLIB
-AC_PATH_PROG(DOXYGEN, doxygen, [:])
-AC_PATH_PROG(ETAGS, etags, [/bin/false])
-
-AC_C_BIGENDIAN
-
-# Checks for libraries.
-AC_CHECK_LIB([coap], [coap_new_pdu])
-
-AC_SEARCH_LIBS([gethostbyname], [nsl])
-AC_SEARCH_LIBS([socket], [socket])
-
-# configuration options that may change compile flags 
-AC_ARG_WITH(debug,
-  [AS_HELP_STRING([--without-debug],[disable all debug output and assertions])],
-  [CPPFLAGS="${CPPFLAGS} -DNDEBUG"], 
-  [])
-
-AC_ARG_WITH(async,
-  [AS_HELP_STRING([--without-async],[disable handling of asynchronous transactions and observe])],
-  [CPPFLAGS="${CPPFLAGS} -DWITHOUT_ASYNC"], 
-  [])
-
-AC_ARG_WITH(block,
-  [AS_HELP_STRING([--without-block],[disable block transfer])],
-  [CPPFLAGS="${CPPFLAGS} -DWITHOUT_BLOCK"], 
-  [])
-
-AC_ARG_WITH(observe,
-  [AS_HELP_STRING([--without-observe],[disable resource observation])],
-  [CPPFLAGS="${CPPFLAGS} -DWITHOUT_OBSERVE"], 
-  [])
-
-AC_ARG_WITH(query-filter,
-  [AS_HELP_STRING([--without-query-filter],[disable support for filters on /.well-known/core])],
-  [CPPFLAGS="${CPPFLAGS} -DWITHOUT_QUERY_FILTER"], 
-  [])
-
-AC_ARG_WITH(tests,
-  [AS_HELP_STRING([--with-tests],[enable unit tests (requires cunit)])],       
-  [TESTS="tests"],
-  [])
-
-AC_ARG_WITH(shared,
-  [AS_HELP_STRING([--with-shared],[build shared library])],    
-  [BUILD_SO="BUILD_SO=1"],
-  [])
-
-# disambiguate between autoconf generated setups and contiki / lwip setups
-# which use explicit config.h.* files
-CPPFLAGS="${CPPFLAGS} -DWITH_POSIX"
-
-# Checks for header files.
-AC_CHECK_HEADERS([assert.h arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h strings.h sys/socket.h sys/time.h time.h unistd.h sys/unistd.h syslog.h])
-
-# Checks for typedefs, structures, and compiler characteristics.
-AC_TYPE_SIZE_T
-AC_TYPE_SSIZE_T
-
-# Checks for library functions.
-AC_FUNC_MALLOC
-AC_CHECK_FUNCS([memset select socket strcasecmp strrchr getaddrinfo strnlen])
-
-AC_SUBST(TESTS)
-AC_SUBST(BUILD_SO)
-
-AC_CONFIG_HEADERS([config.h])
-
-AC_CONFIG_FILES([Makefile
-                 doc/Makefile
-                 doc/Doxyfile
-                 examples/Makefile
-                 tests/Makefile])
-AC_OUTPUT
diff --git a/resource/csdk/libcoap-4.1.1/debug.c b/resource/csdk/libcoap-4.1.1/debug.c
deleted file mode 100644 (file)
index 3a03806..0000000
+++ /dev/null
@@ -1,383 +0,0 @@
-/* debug.c -- debug utilities
- *
- * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-
-#if defined(HAVE_ASSERT_H) && !defined(assert)
-# include <assert.h>
-#endif
-
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-#ifdef HAVE_TIME_H
-#include <time.h>
-#endif
-
-#include "debug.h"
-#include "net.h"
-
-#ifdef WITH_CONTIKI
-# ifndef DEBUG
-#  define DEBUG DEBUG_PRINT
-# endif /* DEBUG */
-#include "net/uip-debug.h"
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-static coap_log_t maxlog = LOG_WARNING;        /* default maximum log level */
-
-coap_log_t
-coap_get_log_level() {
-  return maxlog;
-}
-
-void
-coap_set_log_level(coap_log_t level) {
-  maxlog = level;
-}
-
-/* this array has the same order as the type log_t */
-static char *loglevels[] = {
-  "EMRG", "ALRT", "CRIT", "ERR", "WARN", "NOTE", "INFO", "DEBG"
-};
-
-#ifdef HAVE_TIME_H
-
-static inline size_t
-print_timestamp(char *s, size_t len, coap_tick_t t) {
-  struct tm *tmp;
-  time_t now = clock_offset + (t / COAP_TICKS_PER_SECOND);
-  tmp = localtime(&now);
-  return strftime(s, len, "%b %d %H:%M:%S", tmp);
-}
-
-#else /* alternative implementation: just print the timestamp */
-
-static inline size_t
-print_timestamp(char *s, size_t len, coap_tick_t t) {
-#ifdef HAVE_SNPRINTF
-  return snprintf(s, len, "%u.%03u",
-                 (unsigned int)(clock_offset + (t / COAP_TICKS_PER_SECOND)),
-                 (unsigned int)(t % COAP_TICKS_PER_SECOND));
-#else /* HAVE_SNPRINTF */
-  /* @todo do manual conversion of timestamp */
-  return 0;
-#endif /* HAVE_SNPRINTF */
-}
-
-#endif /* HAVE_TIME_H */
-
-#ifndef NDEBUG
-
-#ifndef HAVE_STRNLEN
-/**
- * A length-safe strlen() fake.
- *
- * @param s      The string to count characters != 0.
- * @param maxlen The maximum length of @p s.
- *
- * @return The length of @p s.
- */
-static inline size_t
-strnlen(const char *s, size_t maxlen) {
-  size_t n = 0;
-  while(*s++ && n < maxlen)
-    ++n;
-  return n;
-}
-#endif /* HAVE_STRNLEN */
-
-unsigned int
-print_readable( const unsigned char *data, unsigned int len,
-               unsigned char *result, unsigned int buflen, int encode_always ) {
-  const unsigned char hex[] = "0123456789ABCDEF";
-  unsigned int cnt = 0;
-  assert(data || len == 0);
-
-  if (buflen == 0 || len == 0)
-    return 0;
-
-  while (len) {
-    if (!encode_always && isprint(*data)) {
-      if (cnt == buflen)
-       break;
-      *result++ = *data;
-      ++cnt;
-    } else {
-      if (cnt+4 < buflen) {
-       *result++ = '\\';
-       *result++ = 'x';
-       *result++ = hex[(*data & 0xf0) >> 4];
-       *result++ = hex[*data & 0x0f];
-       cnt += 4;
-      } else
-       break;
-    }
-
-    ++data; --len;
-  }
-
-  *result = '\0';
-  return cnt;
-}
-
-#ifndef min
-#define min(a,b) ((a) < (b) ? (a) : (b))
-#endif
-
-size_t
-coap_print_addr(const coap_address_t *addr, unsigned char *buf, size_t len) {
-TODO(FIX: Fix this)
-    (void)addr;
-    (void)buf;
-    (void)len;
-#if 0
-#ifdef HAVE_ARPA_INET_H
-  const void *addrptr = NULL;
-  in_port_t port;
-  unsigned char *p = buf;
-
-  switch (addr->addr.sa.sa_family) {
-  case AF_INET:
-    addrptr = &addr->addr.sin.sin_addr;
-    port = ntohs(addr->addr.sin.sin_port);
-    break;
-  case AF_INET6:
-    if (len < 7) /* do not proceed if buffer is even too short for [::]:0 */
-      return 0;
-
-    *p++ = '[';
-
-    addrptr = &addr->addr.sin6.sin6_addr;
-    port = ntohs(addr->addr.sin6.sin6_port);
-
-    break;
-  default:
-    memcpy(buf, "(unknown address type)", min(22, len));
-    return min(22, len);
-  }
-
-  if (inet_ntop(addr->addr.sa.sa_family, addrptr, (char *)p, len) == 0) {
-    perror("coap_print_addr");
-    return 0;
-  }
-
-  p += strnlen((char *)p, len);
-
-  if (addr->addr.sa.sa_family == AF_INET6) {
-    if (p < buf + len) {
-      *p++ = ']';
-    } else
-      return 0;
-  }
-
-  p += snprintf((char *)p, buf + len - p + 1, ":%d", port);
-
-  return buf + len - p;
-#else /* HAVE_ARPA_INET_H */
-# if WITH_CONTIKI
-  unsigned char *p = buf;
-  uint8_t i;
-#  if WITH_UIP6
-  const unsigned char hex[] = "0123456789ABCDEF";
-
-  if (len < 41)
-    return 0;
-
-  *p++ = '[';
-
-  for (i=0; i < 16; i += 2) {
-    if (i) {
-      *p++ = ':';
-    }
-    *p++ = hex[(addr->addr.u8[i] & 0xf0) >> 4];
-    *p++ = hex[(addr->addr.u8[i] & 0x0f)];
-    *p++ = hex[(addr->addr.u8[i+1] & 0xf0) >> 4];
-    *p++ = hex[(addr->addr.u8[i+1] & 0x0f)];
-  }
-  *p++ = ']';
-#  else /* WITH_UIP6 */
-#   warning "IPv4 network addresses will not be included in debug output"
-
-  if (len < 21)
-    return 0;
-#  endif /* WITH_UIP6 */
-  if (buf + len - p < 6)
-    return 0;
-
-#ifdef HAVE_SNPRINTF
-  p += snprintf((char *)p, buf + len - p + 1, ":%d", uip_htons(addr->port));
-#else /* HAVE_SNPRINTF */
-  /* @todo manual conversion of port number */
-#endif /* HAVE_SNPRINTF */
-
-  return p - buf;
-# else /* WITH_CONTIKI */
-  /* TODO: output addresses manually */
-#   warning "inet_ntop() not available, network addresses will not be included in debug output"
-# endif /* WITH_CONTIKI */
-  return 0;
-#endif
-#endif //if 0
-}
-
-#ifndef WITH_CONTIKI
-void
-coap_show_pdu(const coap_pdu_t *pdu) {
-  unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
-  int encode = 0, have_options = 0;
-  coap_opt_iterator_t opt_iter;
-  coap_opt_t *option;
-
-  fprintf(COAP_DEBUG_FD, "v:%d t:%d tkl:%d c:%d id:%u",
-         pdu->hdr->version, pdu->hdr->type,
-         pdu->hdr->token_length,
-         pdu->hdr->code, ntohs(pdu->hdr->id));
-
-  /* show options, if any */
-  coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL);
-
-  while ((option = coap_option_next(&opt_iter))) {
-    if (!have_options) {
-      have_options = 1;
-      fprintf(COAP_DEBUG_FD, " o: [");
-    } else {
-      fprintf(COAP_DEBUG_FD, ",");
-    }
-
-    if (opt_iter.type == COAP_OPTION_URI_PATH ||
-       opt_iter.type == COAP_OPTION_PROXY_URI ||
-       opt_iter.type == COAP_OPTION_URI_HOST ||
-       opt_iter.type == COAP_OPTION_LOCATION_PATH ||
-       opt_iter.type == COAP_OPTION_LOCATION_QUERY ||
-    opt_iter.type == COAP_OPTION_URI_PATH ||
-    opt_iter.type == COAP_OPTION_OBSERVE ||
-       opt_iter.type == COAP_OPTION_URI_QUERY) {
-      encode = 0;
-    } else {
-      encode = 1;
-    }
-
-    if (print_readable(COAP_OPT_VALUE(option),
-                      COAP_OPT_LENGTH(option),
-                      buf, sizeof(buf), encode ))
-      fprintf(COAP_DEBUG_FD, " %d:'%s'", opt_iter.type, buf);
-  }
-
-  if (have_options)
-    fprintf(COAP_DEBUG_FD, " ]");
-
-  if (pdu->data) {
-    assert(pdu->data < (unsigned char *)pdu->hdr + pdu->length);
-    print_readable(pdu->data,
-                  (unsigned char *)pdu->hdr + pdu->length - pdu->data,
-                  buf, sizeof(buf), 0 );
-    fprintf(COAP_DEBUG_FD, " d:%s", buf);
-  }
-  fprintf(COAP_DEBUG_FD, "\n");
-  fflush(COAP_DEBUG_FD);
-}
-
-#else /* WITH_CONTIKI */
-
-void
-coap_show_pdu(const coap_pdu_t *pdu) {
-  unsigned char buf[80]; /* need some space for output creation */
-
-  PRINTF("v:%d t:%d oc:%d c:%d id:%u",
-         pdu->hdr->version, pdu->hdr->type,
-         pdu->hdr->optcnt, pdu->hdr->code, uip_ntohs(pdu->hdr->id));
-
-  /* show options, if any */
-  if (pdu->hdr->optcnt) {
-    coap_opt_iterator_t opt_iter;
-    coap_opt_t *option;
-    coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL);
-
-    PRINTF(" o:");
-    while ((option = coap_option_next(&opt_iter))) {
-
-      if (print_readable(COAP_OPT_VALUE(option),
-                        COAP_OPT_LENGTH(option),
-                        buf, sizeof(buf), 0))
-       PRINTF(" %d:%s", opt_iter.type, buf);
-    }
-  }
-
-  if (pdu->data < (unsigned char *)pdu->hdr + pdu->length) {
-    print_readable(pdu->data,
-                  (unsigned char *)pdu->hdr + pdu->length - pdu->data,
-                  buf, sizeof(buf), 0 );
-    PRINTF(" d:%s", buf);
-  }
-  PRINTF("\r\n");
-}
-#endif /* WITH_CONTIKI */
-
-#endif /* NDEBUG */
-
-#ifndef WITH_CONTIKI
-void
-coap_log_impl(coap_log_t level, const char *format, ...) {
-  char timebuf[32];
-  coap_tick_t now;
-  va_list ap;
-  FILE *log_fd;
-
-  if (maxlog < level)
-    return;
-
-  log_fd = level <= LOG_CRIT ? COAP_ERR_FD : COAP_DEBUG_FD;
-
-  coap_ticks(&now);
-  if (print_timestamp(timebuf,sizeof(timebuf), now))
-    fprintf(log_fd, "%s ", timebuf);
-
-  if (level <= LOG_DEBUG)
-    fprintf(log_fd, "%s ", loglevels[level]);
-
-  va_start(ap, format);
-  vfprintf(log_fd, format, ap);
-  va_end(ap);
-  fflush(log_fd);
-}
-#else /* WITH_CONTIKI */
-void
-coap_log_impl(coap_log_t level, const char *format, ...) {
-  char timebuf[32];
-  coap_tick_t now;
-  va_list ap;
-
-  if (maxlog < level)
-    return;
-
-  coap_ticks(&now);
-  if (print_timestamp(timebuf,sizeof(timebuf), now))
-    PRINTF("%s ", timebuf);
-
-  if (level <= LOG_DEBUG)
-    PRINTF("%s ", loglevels[level]);
-
-  va_start(ap, format);
-  PRINTF(format, ap);
-  va_end(ap);
-}
-#endif /* WITH_CONTIKI */
-#ifdef __cplusplus
-}
-#endif
diff --git a/resource/csdk/libcoap-4.1.1/debug.h b/resource/csdk/libcoap-4.1.1/debug.h
deleted file mode 100644 (file)
index d599e1b..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-/* debug.h -- debug utilities
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#ifndef _COAP_DEBUG_H_
-#define _COAP_DEBUG_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "config.h"
-
-#ifndef COAP_DEBUG_FD
-#define COAP_DEBUG_FD stdout
-#endif
-
-#ifndef COAP_ERR_FD
-#define COAP_ERR_FD stderr
-#endif
-
-#ifdef HAVE_SYSLOG_H
-#include <syslog.h>
-typedef short coap_log_t;
-#else
-/** Pre-defined log levels akin to what is used in \b syslog. */
-typedef enum { LOG_EMERG=0, LOG_ALERT, LOG_CRIT, LOG_WARNING, 
-       LOG_NOTICE, LOG_INFO, LOG_DEBUG
-} coap_log_t;
-#endif
-
-
-
-/** Returns the current log level. */
-coap_log_t coap_get_log_level();
-
-/** Sets the log level to the specified value. */
-void coap_set_log_level(coap_log_t level);
-
-/** 
- * Writes the given text to @c COAP_ERR_FD (for @p level <= @c
- * LOG_CRIT) or @c COAP_DEBUG_FD (for @p level >= @c LOG_WARNING). The
- * text is output only when @p level is below or equal to the log
- * level that set by coap_set_log_level().
- */
-void coap_log_impl(coap_log_t level, const char *format, ...);
-
-#ifndef coap_log
-#define coap_log(...) coap_log_impl(__VA_ARGS__)
-#endif
-
-#if !defined(TB_LOG) && !defined(NDEBUG)
-#define NDEBUG
-#endif
-
-#ifndef NDEBUG
-
-/* A set of convenience macros for common log levels. */
-#define info(...) coap_log(LOG_INFO, __VA_ARGS__)
-#define warn(...) coap_log(LOG_WARNING, __VA_ARGS__)
-#define debug(...) coap_log(LOG_DEBUG, __VA_ARGS__)
-
-#define DO_PRAGMA(x) _Pragma (#x)
-#define TODO(x) DO_PRAGMA(message ("TODO - " #x))
-
-#include "pdu.h"
-void coap_show_pdu(const coap_pdu_t *);
-
-#include "address.h"
-size_t coap_print_addr(const coap_address_t *, unsigned char *, size_t);
-
-
-#else
-
-#define debug(...)
-#define info(...)
-#define warn(...)
-
-#define TODO(x)
-#define coap_show_pdu(x)
-#define coap_print_addr(...)
-
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_DEBUG_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/doc/Doxyfile b/resource/csdk/libcoap-4.1.1/doc/Doxyfile
deleted file mode 100644 (file)
index 053479d..0000000
+++ /dev/null
@@ -1,1551 +0,0 @@
-# Doxyfile 1.6.3
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
-#
-# All text after a hash (#) is considered a comment and will be ignored
-# The format is:
-#       TAG = value [value, ...]
-# For lists items can also be appended using:
-#       TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (" ")
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# This tag specifies the encoding used for all characters in the config file
-# that follow. The default is UTF-8 which is also the encoding used for all
-# text before the first occurrence of this tag. Doxygen uses libiconv (or the
-# iconv built into libc) for the transcoding. See
-# http://www.gnu.org/software/libiconv for the list of possible encodings.
-
-DOXYFILE_ENCODING      = UTF-8
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
-# by quotes) that should identify the project.
-
-PROJECT_NAME           = libcoap
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number.
-# This could be handy for archiving the generated documentation or
-# if some version control system is used.
-
-PROJECT_NUMBER         = 4.1.1
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
-# base path where the generated documentation will be put.
-# If a relative path is entered, it will be relative to the location
-# where doxygen was started. If left blank the current directory will be used.
-
-OUTPUT_DIRECTORY       =
-
-# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
-# 4096 sub-directories (in 2 levels) under the output directory of each output
-# format and will distribute the generated files over these directories.
-# Enabling this option can be useful when feeding doxygen a huge amount of
-# source files, where putting all generated files in the same directory would
-# otherwise cause performance problems for the file system.
-
-CREATE_SUBDIRS         = NO
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all constant output in the proper language.
-# The default language is English, other supported languages are:
-# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
-# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
-# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
-# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
-# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
-# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
-
-OUTPUT_LANGUAGE        = English
-
-# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
-# include brief member descriptions after the members that are listed in
-# the file and class documentation (similar to JavaDoc).
-# Set to NO to disable this.
-
-BRIEF_MEMBER_DESC      = YES
-
-# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
-# the brief description of a member or function before the detailed description.
-# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-
-REPEAT_BRIEF           = YES
-
-# This tag implements a quasi-intelligent brief description abbreviator
-# that is used to form the text in various listings. Each string
-# in this list, if found as the leading text of the brief description, will be
-# stripped from the text and the result after processing the whole list, is
-# used as the annotated text. Otherwise, the brief description is used as-is.
-# If left blank, the following values are used ("$name" is automatically
-# replaced with the name of the entity): "The $name class" "The $name widget"
-# "The $name file" "is" "provides" "specifies" "contains"
-# "represents" "a" "an" "the"
-
-ABBREVIATE_BRIEF       =
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# Doxygen will generate a detailed section even if there is only a brief
-# description.
-
-ALWAYS_DETAILED_SEC    = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
-# inherited members of a class in the documentation of that class as if those
-# members were ordinary class members. Constructors, destructors and assignment
-# operators of the base classes will not be shown.
-
-INLINE_INHERITED_MEMB  = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
-# path before files name in the file list and in the header files. If set
-# to NO the shortest path that makes the file name unique will be used.
-
-FULL_PATH_NAMES        = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
-# can be used to strip a user-defined part of the path. Stripping is
-# only done if one of the specified strings matches the left-hand part of
-# the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the
-# path to strip.
-
-STRIP_FROM_PATH        =
-
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
-# the path mentioned in the documentation of a class, which tells
-# the reader which header file to include in order to use a class.
-# If left blank only the name of the header file containing the class
-# definition is used. Otherwise one should specify the include paths that
-# are normally passed to the compiler using the -I flag.
-
-STRIP_FROM_INC_PATH    =
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
-# (but less readable) file names. This can be useful is your file systems
-# doesn't support long names like on DOS, Mac, or CD-ROM.
-
-SHORT_NAMES            = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
-# will interpret the first line (until the first dot) of a JavaDoc-style
-# comment as the brief description. If set to NO, the JavaDoc
-# comments will behave just like regular Qt-style comments
-# (thus requiring an explicit @brief command for a brief description.)
-
-JAVADOC_AUTOBRIEF      = YES
-
-# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
-# interpret the first line (until the first dot) of a Qt-style
-# comment as the brief description. If set to NO, the comments
-# will behave just like regular Qt-style comments (thus requiring
-# an explicit \brief command for a brief description.)
-
-QT_AUTOBRIEF           = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
-# treat a multi-line C++ special comment block (i.e. a block of //! or ///
-# comments) as a brief description. This used to be the default behaviour.
-# The new default is to treat a multi-line C++ comment block as a detailed
-# description. Set this tag to YES if you prefer the old behaviour instead.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
-# member inherits the documentation from any documented member that it
-# re-implements.
-
-INHERIT_DOCS           = YES
-
-# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
-# a new page for each member. If set to NO, the documentation of a member will
-# be part of the file/class/namespace that contains it.
-
-SEPARATE_MEMBER_PAGES  = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab.
-# Doxygen uses this value to replace tabs by spaces in code fragments.
-
-TAB_SIZE               = 4
-
-# This tag can be used to specify a number of aliases that acts
-# as commands in the documentation. An alias has the form "name=value".
-# For example adding "sideeffect=\par Side Effects:\n" will allow you to
-# put the command \sideeffect (or @sideeffect) in the documentation, which
-# will result in a user-defined paragraph with heading "Side Effects:".
-# You can put \n's in the value part of an alias to insert newlines.
-
-ALIASES                =
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
-# sources only. Doxygen will then generate output that is more tailored for C.
-# For instance, some of the names that are used will be different. The list
-# of all members will be omitted, etc.
-
-OPTIMIZE_OUTPUT_FOR_C  = YES
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
-# sources only. Doxygen will then generate output that is more tailored for
-# Java. For instance, namespaces will be presented as packages, qualified
-# scopes will look different, etc.
-
-OPTIMIZE_OUTPUT_JAVA   = NO
-
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources only. Doxygen will then generate output that is more tailored for
-# Fortran.
-
-OPTIMIZE_FOR_FORTRAN   = NO
-
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for
-# VHDL.
-
-OPTIMIZE_OUTPUT_VHDL   = NO
-
-# Doxygen selects the parser to use depending on the extension of the files it parses.
-# With this tag you can assign which parser to use for a given extension.
-# Doxygen has a built-in mapping, but you can override or extend it using this tag.
-# The format is ext=language, where ext is a file extension, and language is one of
-# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP,
-# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat
-# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran),
-# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
-
-EXTENSION_MAPPING      =
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should
-# set this tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
-# func(std::string) {}). This also make the inheritance and collaboration
-# diagrams that involve STL classes more complete and accurate.
-
-BUILTIN_STL_SUPPORT    = NO
-
-# If you use Microsoft's C++/CLI language, you should set this option to YES to
-# enable parsing support.
-
-CPP_CLI_SUPPORT        = NO
-
-# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
-# Doxygen will parse them like normal C++ but will assume all classes use public
-# instead of private inheritance when no explicit protection keyword is present.
-
-SIP_SUPPORT            = NO
-
-# For Microsoft's IDL there are propget and propput attributes to indicate getter
-# and setter methods for a property. Setting this option to YES (the default)
-# will make doxygen to replace the get and set methods by a property in the
-# documentation. This will only work if the methods are indeed getting or
-# setting a simple type. If this is not the case, or you want to show the
-# methods anyway, you should set this option to NO.
-
-IDL_PROPERTY_SUPPORT   = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES, then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
-
-DISTRIBUTE_GROUP_DOC   = NO
-
-# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
-# the same type (for instance a group of public functions) to be put as a
-# subgroup of that type (e.g. under the Public Functions section). Set it to
-# NO to prevent subgrouping. Alternatively, this can be done per class using
-# the \nosubgrouping command.
-
-SUBGROUPING            = YES
-
-# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
-# is documented as struct, union, or enum with the name of the typedef. So
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
-# with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically
-# be useful for C code in case the coding convention dictates that all compound
-# types are typedef'ed and only the typedef is referenced, never the tag name.
-
-TYPEDEF_HIDES_STRUCT   = NO
-
-# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
-# determine which symbols to keep in memory and which to flush to disk.
-# When the cache is full, less often used symbols will be written to disk.
-# For small to medium size projects (<1000 input files) the default value is
-# probably good enough. For larger projects a too small cache size can cause
-# doxygen to be busy swapping symbols to and from disk most of the time
-# causing a significant performance penality.
-# If the system has enough physical memory increasing the cache will improve the
-# performance by keeping more symbols in memory. Note that the value works on
-# a logarithmic scale so increasing the size by one will rougly double the
-# memory usage. The cache size is given by this formula:
-# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
-# corresponding to a cache size of 2^16 = 65536 symbols
-
-SYMBOL_CACHE_SIZE      = 0
-
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
-# documentation are documented, even if no documentation was available.
-# Private class members and static file members will be hidden unless
-# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
-
-EXTRACT_ALL            = YES
-
-# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
-# will be included in the documentation.
-
-EXTRACT_PRIVATE        = NO
-
-# If the EXTRACT_STATIC tag is set to YES all static members of a file
-# will be included in the documentation.
-
-EXTRACT_STATIC         = YES
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
-# defined locally in source files will be included in the documentation.
-# If set to NO only classes defined in header files are included.
-
-EXTRACT_LOCAL_CLASSES  = YES
-
-# This flag is only useful for Objective-C code. When set to YES local
-# methods, which are defined in the implementation section but not in
-# the interface are included in the documentation.
-# If set to NO (the default) only methods in the interface are included.
-
-EXTRACT_LOCAL_METHODS  = NO
-
-# If this flag is set to YES, the members of anonymous namespaces will be
-# extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base
-# name of the file that contains the anonymous namespace. By default
-# anonymous namespace are hidden.
-
-EXTRACT_ANON_NSPACES   = NO
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
-# undocumented members of documented classes, files or namespaces.
-# If set to NO (the default) these members will be included in the
-# various overviews, but no documentation section is generated.
-# This option has no effect if EXTRACT_ALL is enabled.
-
-HIDE_UNDOC_MEMBERS     = NO
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy.
-# If set to NO (the default) these classes will be included in the various
-# overviews. This option has no effect if EXTRACT_ALL is enabled.
-
-HIDE_UNDOC_CLASSES     = NO
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
-# friend (class|struct|union) declarations.
-# If set to NO (the default) these declarations will be included in the
-# documentation.
-
-HIDE_FRIEND_COMPOUNDS  = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
-# documentation blocks found inside the body of a function.
-# If set to NO (the default) these blocks will be appended to the
-# function's detailed documentation block.
-
-HIDE_IN_BODY_DOCS      = NO
-
-# The INTERNAL_DOCS tag determines if documentation
-# that is typed after a \internal command is included. If the tag is set
-# to NO (the default) then the documentation will be excluded.
-# Set it to YES to include the internal documentation.
-
-INTERNAL_DOCS          = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
-# file names in lower-case letters. If set to YES upper-case letters are also
-# allowed. This is useful if you have classes or files whose names only differ
-# in case and if your file system supports case sensitive file names. Windows
-# and Mac users are advised to set this option to NO.
-
-CASE_SENSE_NAMES       = YES
-
-# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
-# will show members with their full class and namespace scopes in the
-# documentation. If set to YES the scope will be hidden.
-
-HIDE_SCOPE_NAMES       = NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
-# will put a list of the files that are included by a file in the documentation
-# of that file.
-
-SHOW_INCLUDE_FILES     = YES
-
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
-# will list include files with double quotes in the documentation
-# rather than with sharp brackets.
-
-FORCE_LOCAL_INCLUDES   = NO
-
-# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
-# is inserted in the documentation for inline members.
-
-INLINE_INFO            = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
-# will sort the (detailed) documentation of file and class members
-# alphabetically by member name. If set to NO the members will appear in
-# declaration order.
-
-SORT_MEMBER_DOCS       = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
-# brief documentation of file, namespace and class members alphabetically
-# by member name. If set to NO (the default) the members will appear in
-# declaration order.
-
-SORT_BRIEF_DOCS        = NO
-
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
-
-SORT_MEMBERS_CTORS_1ST = NO
-
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
-# hierarchy of group names into alphabetical order. If set to NO (the default)
-# the group names will appear in their defined order.
-
-SORT_GROUP_NAMES       = NO
-
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
-# sorted by fully-qualified names, including namespaces. If set to
-# NO (the default), the class list will be sorted only by class name,
-# not including the namespace part.
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the
-# alphabetical list.
-
-SORT_BY_SCOPE_NAME     = NO
-
-# The GENERATE_TODOLIST tag can be used to enable (YES) or
-# disable (NO) the todo list. This list is created by putting \todo
-# commands in the documentation.
-
-GENERATE_TODOLIST      = YES
-
-# The GENERATE_TESTLIST tag can be used to enable (YES) or
-# disable (NO) the test list. This list is created by putting \test
-# commands in the documentation.
-
-GENERATE_TESTLIST      = YES
-
-# The GENERATE_BUGLIST tag can be used to enable (YES) or
-# disable (NO) the bug list. This list is created by putting \bug
-# commands in the documentation.
-
-GENERATE_BUGLIST       = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
-# disable (NO) the deprecated list. This list is created by putting
-# \deprecated commands in the documentation.
-
-GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional
-# documentation sections, marked by \if sectionname ... \endif.
-
-ENABLED_SECTIONS       =
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
-# the initial value of a variable or define consists of for it to appear in
-# the documentation. If the initializer consists of more lines than specified
-# here it will be hidden. Use a value of 0 to hide initializers completely.
-# The appearance of the initializer of individual variables and defines in the
-# documentation can be controlled using \showinitializer or \hideinitializer
-# command in the documentation regardless of this setting.
-
-MAX_INITIALIZER_LINES  = 30
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
-# at the bottom of the documentation of classes and structs. If set to YES the
-# list will mention the files that were used to generate the documentation.
-
-SHOW_USED_FILES        = YES
-
-# If the sources in your project are distributed over multiple directories
-# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
-# in the documentation. The default is NO.
-
-SHOW_DIRECTORIES       = NO
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
-# This will remove the Files entry from the Quick Index and from the
-# Folder Tree View (if specified). The default is YES.
-
-SHOW_FILES             = YES
-
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
-# Namespaces page.
-# This will remove the Namespaces entry from the Quick Index
-# and from the Folder Tree View (if specified). The default is YES.
-
-SHOW_NAMESPACES        = YES
-
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that
-# doxygen should invoke to get the current version for each file (typically from
-# the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command <command> <input-file>, where <command> is the value of
-# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
-# provided by doxygen. Whatever the program writes to standard output
-# is used as the file version. See the manual for examples.
-
-FILE_VERSION_FILTER    =
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by
-# doxygen. The layout file controls the global structure of the generated output files
-# in an output format independent way. The create the layout file that represents
-# doxygen's defaults, run doxygen with the -l option. You can optionally specify a
-# file name after the option, if omitted DoxygenLayout.xml will be used as the name
-# of the layout file.
-
-LAYOUT_FILE            =
-
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated
-# by doxygen. Possible values are YES and NO. If left blank NO is used.
-
-QUIET                  = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated by doxygen. Possible values are YES and NO. If left blank
-# NO is used.
-
-WARNINGS               = YES
-
-# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
-# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
-# automatically be disabled.
-
-WARN_IF_UNDOCUMENTED   = YES
-
-# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some
-# parameters in a documented function, or documenting parameters that
-# don't exist or using markup commands wrongly.
-
-WARN_IF_DOC_ERROR      = YES
-
-# This WARN_NO_PARAMDOC option can be abled to get warnings for
-# functions that are documented, but have no documentation for their parameters
-# or return value. If set to NO (the default) doxygen will only warn about
-# wrong or incomplete parameter documentation, but not about the absence of
-# documentation.
-
-WARN_NO_PARAMDOC       = NO
-
-# The WARN_FORMAT tag determines the format of the warning messages that
-# doxygen can produce. The string should contain the $file, $line, and $text
-# tags, which will be replaced by the file and line number from which the
-# warning originated and the warning text. Optionally the format may contain
-# $version, which will be replaced by the version of the file (if it could
-# be obtained via FILE_VERSION_FILTER)
-
-WARN_FORMAT            = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning
-# and error messages should be written. If left blank the output is written
-# to stderr.
-
-WARN_LOGFILE           =
-
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag can be used to specify the files and/or directories that contain
-# documented source files. You may enter file names like "myfile.cpp" or
-# directories like "/usr/src/myproject". Separate the files or directories
-# with spaces.
-
-INPUT                  = .. ../examples
-
-# This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
-# also the default input encoding. Doxygen uses libiconv (or the iconv built
-# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
-# the list of possible encodings.
-
-INPUT_ENCODING         = UTF-8
-
-# If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank the following patterns are tested:
-# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
-# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
-
-FILE_PATTERNS          =
-
-# The RECURSIVE tag can be used to turn specify whether or not subdirectories
-# should be searched for input files as well. Possible values are YES and NO.
-# If left blank NO is used.
-
-RECURSIVE              = NO
-
-# The EXCLUDE tag can be used to specify files and/or directories that should
-# excluded from the INPUT source files. This way you can easily exclude a
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-
-EXCLUDE                =
-
-# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
-# directories that are symbolic links (a Unix filesystem feature) are excluded
-# from the input.
-
-EXCLUDE_SYMLINKS       = NO
-
-# If the value of the INPUT tag contains directories, you can use the
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories. Note that the wildcards are matched
-# against the file with absolute path, so to exclude all test directories
-# for example use the pattern */test/*
-
-EXCLUDE_PATTERNS       =
-
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
-# (namespaces, classes, functions, etc.) that should be excluded from the
-# output. The symbol name can be a fully qualified name, a word, or if the
-# wildcard * is used, a substring. Examples: ANamespace, AClass,
-# AClass::ANamespace, ANamespace::*Test
-
-EXCLUDE_SYMBOLS        =
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or
-# directories that contain example code fragments that are included (see
-# the \include command).
-
-EXAMPLE_PATH           =
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank all files are included.
-
-EXAMPLE_PATTERNS       =
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude
-# commands irrespective of the value of the RECURSIVE tag.
-# Possible values are YES and NO. If left blank NO is used.
-
-EXAMPLE_RECURSIVE      = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or
-# directories that contain image that are included in the documentation (see
-# the \image command).
-
-IMAGE_PATH             =
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should
-# invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command <filter> <input-file>, where <filter>
-# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
-# input file. Doxygen will then use the output that the filter program writes
-# to standard output.
-# If FILTER_PATTERNS is specified, this tag will be
-# ignored.
-
-INPUT_FILTER           =
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis.
-# Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match.
-# The filters are a list of the form:
-# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
-# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
-# is applied to all files.
-
-FILTER_PATTERNS        =
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER) will be used to filter the input files when producing source
-# files to browse (i.e. when SOURCE_BROWSER is set to YES).
-
-FILTER_SOURCE_FILES    = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will
-# be generated. Documented entities will be cross-referenced with these sources.
-# Note: To get rid of all source code in the generated output, make sure also
-# VERBATIM_HEADERS is set to NO.
-
-SOURCE_BROWSER         = YES
-
-# Setting the INLINE_SOURCES tag to YES will include the body
-# of functions and classes directly in the documentation.
-
-INLINE_SOURCES         = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
-# doxygen to hide any special comment blocks from generated source code
-# fragments. Normal C and C++ comments will always remain visible.
-
-STRIP_CODE_COMMENTS    = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES
-# then for each documented function all documented
-# functions referencing it will be listed.
-
-REFERENCED_BY_RELATION = NO
-
-# If the REFERENCES_RELATION tag is set to YES
-# then for each documented function all documented entities
-# called/used by that function will be listed.
-
-REFERENCES_RELATION    = NO
-
-# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
-# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
-# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
-# link to the source code.
-# Otherwise they will link to the documentation.
-
-REFERENCES_LINK_SOURCE = YES
-
-# If the USE_HTAGS tag is set to YES then the references to source code
-# will point to the HTML generated by the htags(1) tool instead of doxygen
-# built-in source browser. The htags tool is part of GNU's global source
-# tagging system (see http://www.gnu.org/software/global/global.html). You
-# will need version 4.8.6 or higher.
-
-USE_HTAGS              = NO
-
-# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
-# will generate a verbatim copy of the header file for each class for
-# which an include is specified. Set to NO to disable this.
-
-VERBATIM_HEADERS       = YES
-
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
-# of all compounds will be generated. Enable this if the project
-# contains a lot of classes, structs, unions or interfaces.
-
-ALPHABETICAL_INDEX     = NO
-
-# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
-# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
-# in which this list will be split (can be a number in the range [1..20])
-
-COLS_IN_ALPHA_INDEX    = 5
-
-# In case all classes in a project start with a common prefix, all
-# classes will be put under the same header in the alphabetical index.
-# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
-# should be ignored while generating the index headers.
-
-IGNORE_PREFIX          =
-
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
-# generate HTML output.
-
-GENERATE_HTML          = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `html' will be used as the default path.
-
-HTML_OUTPUT            = html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
-# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
-# doxygen will generate files with .html extension.
-
-HTML_FILE_EXTENSION    = .html
-
-# The HTML_HEADER tag can be used to specify a personal HTML header for
-# each generated HTML page. If it is left blank doxygen will generate a
-# standard header.
-
-HTML_HEADER            =
-
-# The HTML_FOOTER tag can be used to specify a personal HTML footer for
-# each generated HTML page. If it is left blank doxygen will generate a
-# standard footer.
-
-HTML_FOOTER            =
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
-# style sheet that is used by each HTML page. It can be used to
-# fine-tune the look of the HTML output. If the tag is left blank doxygen
-# will generate a default style sheet. Note that doxygen will try to copy
-# the style sheet file to the HTML output directory, so don't put your own
-# stylesheet in the HTML output directory as well, or it will be erased!
-
-HTML_STYLESHEET        =
-
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
-# page will contain the date and time when the page was generated. Setting
-# this to NO can help when comparing the output of multiple runs.
-
-HTML_TIMESTAMP         = YES
-
-# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
-# files or namespaces will be aligned in HTML using tables. If set to
-# NO a bullet list will be used.
-
-HTML_ALIGN_MEMBERS     = YES
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
-# documentation will contain sections that can be hidden and shown after the
-# page has loaded. For this to work a browser that supports
-# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
-# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
-
-HTML_DYNAMIC_SECTIONS  = NO
-
-# If the GENERATE_DOCSET tag is set to YES, additional index files
-# will be generated that can be used as input for Apple's Xcode 3
-# integrated development environment, introduced with OSX 10.5 (Leopard).
-# To create a documentation set, doxygen will generate a Makefile in the
-# HTML output directory. Running make will produce the docset in that
-# directory and running "make install" will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
-# it at startup.
-# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.
-
-GENERATE_DOCSET        = NO
-
-# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
-# feed. A documentation feed provides an umbrella under which multiple
-# documentation sets from a single provider (such as a company or product suite)
-# can be grouped.
-
-DOCSET_FEEDNAME        = "Doxygen generated docs"
-
-# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
-# should uniquely identify the documentation set bundle. This should be a
-# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
-# will append .docset to the name.
-
-DOCSET_BUNDLE_ID       = org.doxygen.Project
-
-# If the GENERATE_HTMLHELP tag is set to YES, additional index files
-# will be generated that can be used as input for tools like the
-# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
-# of the generated HTML documentation.
-
-GENERATE_HTMLHELP      = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
-# be used to specify the file name of the resulting .chm file. You
-# can add a path in front of the file if the result should not be
-# written to the html output directory.
-
-CHM_FILE               =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
-# be used to specify the location (absolute path including file name) of
-# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
-# the HTML help compiler on the generated index.hhp.
-
-HHC_LOCATION           =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
-# controls if a separate .chi index file is generated (YES) or that
-# it should be included in the master .chm file (NO).
-
-GENERATE_CHI           = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
-# is used to encode HtmlHelp index (hhk), content (hhc) and project file
-# content.
-
-CHM_INDEX_ENCODING     =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
-# controls whether a binary table of contents is generated (YES) or a
-# normal table of contents (NO) in the .chm file.
-
-BINARY_TOC             = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members
-# to the contents of the HTML help documentation and to the tree view.
-
-TOC_EXPAND             = NO
-
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER
-# are set, an additional index file will be generated that can be used as input for
-# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated
-# HTML documentation.
-
-GENERATE_QHP           = NO
-
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
-# be used to specify the file name of the resulting .qch file.
-# The path specified is relative to the HTML output folder.
-
-QCH_FILE               =
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#namespace
-
-QHP_NAMESPACE          = org.doxygen.Project
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#virtual-folders
-
-QHP_VIRTUAL_FOLDER     = doc
-
-# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add.
-# For more information please see
-# http://doc.trolltech.com/qthelpproject.html#custom-filters
-
-QHP_CUST_FILTER_NAME   =
-
-# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see
-# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>.
-
-QHP_CUST_FILTER_ATTRS  =
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's
-# filter section matches.
-# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>.
-
-QHP_SECT_FILTER_ATTRS  =
-
-# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
-# be used to specify the location of Qt's qhelpgenerator.
-# If non-empty doxygen will try to run qhelpgenerator on the generated
-# .qhp file.
-
-QHG_LOCATION           =
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
-#  will be generated, which together with the HTML files, form an Eclipse help
-#  plugin. To install this plugin and make it available under the help contents
-# menu in Eclipse, the contents of the directory containing the HTML and XML
-# files needs to be copied into the plugins directory of eclipse. The name of
-# the directory within the plugins directory should be the same as
-# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears.
-
-GENERATE_ECLIPSEHELP   = NO
-
-# A unique identifier for the eclipse help plugin. When installing the plugin
-# the directory name containing the HTML and XML files should also have
-# this name.
-
-ECLIPSE_DOC_ID         = org.doxygen.Project
-
-# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
-# top of each HTML page. The value NO (the default) enables the index and
-# the value YES disables it.
-
-DISABLE_INDEX          = NO
-
-# This tag can be used to set the number of enum values (range [1..20])
-# that doxygen will group on one line in the generated HTML documentation.
-
-ENUM_VALUES_PER_LINE   = 4
-
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information.
-# If the tag value is set to YES, a side panel will be generated
-# containing a tree-like index structure (just like the one that
-# is generated for HTML Help). For this to work a browser that supports
-# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
-# Windows users are probably better off using the HTML help feature.
-
-GENERATE_TREEVIEW      = NO
-
-# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
-# and Class Hierarchy pages using a tree view instead of an ordered list.
-
-USE_INLINE_TREES       = NO
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
-# used to set the initial width (in pixels) of the frame in which the tree
-# is shown.
-
-TREEVIEW_WIDTH         = 250
-
-# Use this tag to change the font size of Latex formulas included
-# as images in the HTML documentation. The default is 10. Note that
-# when you change the font size after a successful doxygen run you need
-# to manually remove any form_*.png images from the HTML output directory
-# to force them to be regenerated.
-
-FORMULA_FONTSIZE       = 10
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript
-# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should
-# typically be disabled. For large projects the javascript based search engine
-# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
-
-SEARCHENGINE           = YES
-
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index
-# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup
-# and does not have live searching capabilities.
-
-SERVER_BASED_SEARCH    = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
-# generate Latex output.
-
-GENERATE_LATEX         = NO
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `latex' will be used as the default path.
-
-LATEX_OUTPUT           = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked. If left blank `latex' will be used as the default command name.
-# Note that when enabling USE_PDFLATEX this option is only used for
-# generating bitmaps for formulas in the HTML output, but not in the
-# Makefile that is written to the output directory.
-
-LATEX_CMD_NAME         = latex
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
-# generate index for LaTeX. If left blank `makeindex' will be used as the
-# default command name.
-
-MAKEINDEX_CMD_NAME     = makeindex
-
-# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
-# LaTeX documents. This may be useful for small projects and may help to
-# save some trees in general.
-
-COMPACT_LATEX          = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used
-# by the printer. Possible values are: a4, a4wide, letter, legal and
-# executive. If left blank a4wide will be used.
-
-PAPER_TYPE             = a4wide
-
-# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
-# packages that should be included in the LaTeX output.
-
-EXTRA_PACKAGES         =
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
-# the generated latex document. The header should contain everything until
-# the first chapter. If it is left blank doxygen will generate a
-# standard header. Notice: only use this tag if you know what you are doing!
-
-LATEX_HEADER           =
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
-# is prepared for conversion to pdf (using ps2pdf). The pdf file will
-# contain links (just like the HTML output) instead of page references
-# This makes the output suitable for online browsing using a pdf viewer.
-
-PDF_HYPERLINKS         = YES
-
-# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
-# plain latex in the generated Makefile. Set this option to YES to get a
-# higher quality PDF documentation.
-
-USE_PDFLATEX           = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
-# command to the generated LaTeX files. This will instruct LaTeX to keep
-# running if errors occur, instead of asking the user for help.
-# This option is also used when generating formulas in HTML.
-
-LATEX_BATCHMODE        = NO
-
-# If LATEX_HIDE_INDICES is set to YES then doxygen will not
-# include the index chapters (such as File Index, Compound Index, etc.)
-# in the output.
-
-LATEX_HIDE_INDICES     = NO
-
-# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER.
-
-LATEX_SOURCE_CODE      = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
-# The RTF output is optimized for Word 97 and may not look very pretty with
-# other RTF readers or editors.
-
-GENERATE_RTF           = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `rtf' will be used as the default path.
-
-RTF_OUTPUT             = rtf
-
-# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
-# RTF documents. This may be useful for small projects and may help to
-# save some trees in general.
-
-COMPACT_RTF            = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
-# will contain hyperlink fields. The RTF file will
-# contain links (just like the HTML output) instead of page references.
-# This makes the output suitable for online browsing using WORD or other
-# programs which support those fields.
-# Note: wordpad (write) and others do not support links.
-
-RTF_HYPERLINKS         = NO
-
-# Load stylesheet definitions from file. Syntax is similar to doxygen's
-# config file, i.e. a series of assignments. You only have to provide
-# replacements, missing definitions are set to their default value.
-
-RTF_STYLESHEET_FILE    =
-
-# Set optional variables used in the generation of an rtf document.
-# Syntax is similar to doxygen's config file.
-
-RTF_EXTENSIONS_FILE    =
-
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
-# generate man pages
-
-GENERATE_MAN           = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `man' will be used as the default path.
-
-MAN_OUTPUT             = man
-
-# The MAN_EXTENSION tag determines the extension that is added to
-# the generated man pages (default is the subroutine's section .3)
-
-MAN_EXTENSION          = .3
-
-# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
-# then it will generate one additional man file for each entity
-# documented in the real man page(s). These additional files
-# only source the real man page, but without them the man command
-# would be unable to find the correct page. The default is NO.
-
-MAN_LINKS              = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES Doxygen will
-# generate an XML file that captures the structure of
-# the code including all documentation.
-
-GENERATE_XML           = NO
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `xml' will be used as the default path.
-
-XML_OUTPUT             = xml
-
-# The XML_SCHEMA tag can be used to specify an XML schema,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_SCHEMA             =
-
-# The XML_DTD tag can be used to specify an XML DTD,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_DTD                =
-
-# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
-# dump the program listings (including syntax highlighting
-# and cross-referencing information) to the XML output. Note that
-# enabling this will significantly increase the size of the XML output.
-
-XML_PROGRAMLISTING     = YES
-
-#---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
-# generate an AutoGen Definitions (see autogen.sf.net) file
-# that captures the structure of the code including all
-# documentation. Note that this feature is still experimental
-# and incomplete at the moment.
-
-GENERATE_AUTOGEN_DEF   = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES Doxygen will
-# generate a Perl module file that captures the structure of
-# the code including all documentation. Note that this
-# feature is still experimental and incomplete at the
-# moment.
-
-GENERATE_PERLMOD       = NO
-
-# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
-# the necessary Makefile rules, Perl scripts and LaTeX code to be able
-# to generate PDF and DVI output from the Perl module output.
-
-PERLMOD_LATEX          = NO
-
-# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
-# nicely formatted so it can be parsed by a human reader.
-# This is useful
-# if you want to understand what is going on.
-# On the other hand, if this
-# tag is set to NO the size of the Perl module output will be much smaller
-# and Perl will parse it just the same.
-
-PERLMOD_PRETTY         = YES
-
-# The names of the make variables in the generated doxyrules.make file
-# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
-# This is useful so different doxyrules.make files included by the same
-# Makefile don't overwrite each other's variables.
-
-PERLMOD_MAKEVAR_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
-# evaluate all C-preprocessor directives found in the sources and include
-# files.
-
-ENABLE_PREPROCESSING   = YES
-
-# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
-# names in the source code. If set to NO (the default) only conditional
-# compilation will be performed. Macro expansion can be done in a controlled
-# way by setting EXPAND_ONLY_PREDEF to YES.
-
-MACRO_EXPANSION        = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
-# then the macro expansion is limited to the macros specified with the
-# PREDEFINED and EXPAND_AS_DEFINED tags.
-
-EXPAND_ONLY_PREDEF     = NO
-
-# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
-# in the INCLUDE_PATH (see below) will be search if a #include is found.
-
-SEARCH_INCLUDES        = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by
-# the preprocessor.
-
-INCLUDE_PATH           =
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
-# patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will
-# be used.
-
-INCLUDE_FILE_PATTERNS  =
-
-# The PREDEFINED tag can be used to specify one or more macro names that
-# are defined before the preprocessor is started (similar to the -D option of
-# gcc). The argument of the tag is a list of macros of the form: name
-# or name=definition (no spaces). If the definition and the = are
-# omitted =1 is assumed. To prevent a macro definition from being
-# undefined via #undef or recursively expanded use the := operator
-# instead of the = operator.
-
-PREDEFINED             =
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
-# this tag can be used to specify a list of macro names that should be expanded.
-# The macro definition that is found in the sources will be used.
-# Use the PREDEFINED tag if you want to use a different macro definition.
-
-EXPAND_AS_DEFINED      =
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
-# doxygen's preprocessor will remove all function-like macros that are alone
-# on a line, have an all uppercase name, and do not end with a semicolon. Such
-# function macros are typically used for boiler-plate code, and will confuse
-# the parser if not removed.
-
-SKIP_FUNCTION_MACROS   = YES
-
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES option can be used to specify one or more tagfiles.
-# Optionally an initial location of the external documentation
-# can be added for each tagfile. The format of a tag file without
-# this location is as follows:
-#
-# TAGFILES = file1 file2 ...
-# Adding location for the tag files is done as follows:
-#
-# TAGFILES = file1=loc1 "file2 = loc2" ...
-# where "loc1" and "loc2" can be relative or absolute paths or
-# URLs. If a location is present for each tag, the installdox tool
-# does not have to be run to correct the links.
-# Note that each tag file must have a unique name
-# (where the name does NOT include the path)
-# If a tag file is not located in the directory in which doxygen
-# is run, you must also specify the path to the tagfile here.
-
-TAGFILES               =
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create
-# a tag file that is based on the input files it reads.
-
-GENERATE_TAGFILE       =
-
-# If the ALLEXTERNALS tag is set to YES all external classes will be listed
-# in the class index. If set to NO only the inherited external classes
-# will be listed.
-
-ALLEXTERNALS           = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
-# in the modules index. If set to NO, only the current project's groups will
-# be listed.
-
-EXTERNAL_GROUPS        = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script
-# interpreter (i.e. the result of `which perl').
-
-PERL_PATH              = /usr/bin/perl
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
-# or super classes. Setting the tag to NO turns the diagrams off. Note that
-# this option is superseded by the HAVE_DOT option below. This is only a
-# fallback. It is recommended to install and use dot, since it yields more
-# powerful graphs.
-
-CLASS_DIAGRAMS         = NO
-
-# You can define message sequence charts within doxygen comments using the \msc
-# command. Doxygen will then run the mscgen tool (see
-# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
-# documentation. The MSCGEN_PATH tag allows you to specify the directory where
-# the mscgen tool resides. If left empty the tool is assumed to be found in the
-# default search path.
-
-MSCGEN_PATH            =
-
-# If set to YES, the inheritance and collaboration graphs will hide
-# inheritance and usage relations if the target is undocumented
-# or is not a class.
-
-HIDE_UNDOC_RELATIONS   = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz, a graph visualization
-# toolkit from AT&T and Lucent Bell Labs. The other options in this section
-# have no effect if this option is set to NO (the default)
-
-HAVE_DOT               = NO
-
-# By default doxygen will write a font called FreeSans.ttf to the output
-# directory and reference it in all dot files that doxygen generates. This
-# font does not include all possible unicode characters however, so when you need
-# these (or just want a differently looking font) you can specify the font name
-# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
-# which can be done by putting it in a standard location or by setting the
-# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
-# containing the font.
-
-DOT_FONTNAME           = FreeSans
-
-# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
-# The default size is 10pt.
-
-DOT_FONTSIZE           = 10
-
-# By default doxygen will tell dot to use the output directory to look for the
-# FreeSans.ttf font (which doxygen will put there itself). If you specify a
-# different font using DOT_FONTNAME you can set the path where dot
-# can find it using this tag.
-
-DOT_FONTPATH           =
-
-# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect inheritance relations. Setting this tag to YES will force the
-# the CLASS_DIAGRAMS tag to NO.
-
-CLASS_GRAPH            = YES
-
-# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect implementation dependencies (inheritance, containment, and
-# class references variables) of the class with other documented classes.
-
-COLLABORATION_GRAPH    = YES
-
-# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for groups, showing the direct groups dependencies
-
-GROUP_GRAPHS           = YES
-
-# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
-# collaboration diagrams in a style similar to the OMG's Unified Modeling
-# Language.
-
-UML_LOOK               = NO
-
-# If set to YES, the inheritance and collaboration graphs will show the
-# relations between templates and their instances.
-
-TEMPLATE_RELATIONS     = NO
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
-# tags are set to YES then doxygen will generate a graph for each documented
-# file showing the direct and indirect include dependencies of the file with
-# other documented files.
-
-INCLUDE_GRAPH          = YES
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
-# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
-# documented header file showing the documented files that directly or
-# indirectly include this file.
-
-INCLUDED_BY_GRAPH      = YES
-
-# If the CALL_GRAPH and HAVE_DOT options are set to YES then
-# doxygen will generate a call dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable call graphs
-# for selected functions only using the \callgraph command.
-
-CALL_GRAPH             = NO
-
-# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
-# doxygen will generate a caller dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable caller
-# graphs for selected functions only using the \callergraph command.
-
-CALLER_GRAPH           = NO
-
-# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
-# will graphical hierarchy of all classes instead of a textual one.
-
-GRAPHICAL_HIERARCHY    = YES
-
-# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
-# then doxygen will show the dependencies a directory has on other directories
-# in a graphical way. The dependency relations are determined by the #include
-# relations between the files in the directories.
-
-DIRECTORY_GRAPH        = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot. Possible values are png, jpg, or gif
-# If left blank png will be used.
-
-DOT_IMAGE_FORMAT       = png
-
-# The tag DOT_PATH can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found in the path.
-
-DOT_PATH               =
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the
-# \dotfile command).
-
-DOTFILE_DIRS           =
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
-# nodes that will be shown in the graph. If the number of nodes in a graph
-# becomes larger than this value, doxygen will truncate the graph, which is
-# visualized by representing a node as a red box. Note that doxygen if the
-# number of direct children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
-# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-
-DOT_GRAPH_MAX_NODES    = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
-# graphs generated by dot. A depth value of 3 means that only nodes reachable
-# from the root by following a path via at most 3 edges will be shown. Nodes
-# that lay further from the root node will be omitted. Note that setting this
-# option to 1 or 2 may greatly reduce the computation time needed for large
-# code bases. Also note that the size of a graph can be further restricted by
-# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
-
-MAX_DOT_GRAPH_DEPTH    = 0
-
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not
-# seem to support this out of the box. Warning: Depending on the platform used,
-# enabling this option may lead to badly anti-aliased labels on the edges of
-# a graph (i.e. they become hard to read).
-
-DOT_TRANSPARENT        = NO
-
-# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
-# files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10)
-# support this, this feature is disabled by default.
-
-DOT_MULTI_TARGETS      = YES
-
-# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
-# generate a legend page explaining the meaning of the various boxes and
-# arrows in the dot generated graphs.
-
-GENERATE_LEGEND        = YES
-
-# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
-# remove the intermediate dot files that are used to generate
-# the various graphs.
-
-DOT_CLEANUP            = YES
diff --git a/resource/csdk/libcoap-4.1.1/doc/Doxyfile.in b/resource/csdk/libcoap-4.1.1/doc/Doxyfile.in
deleted file mode 100644 (file)
index 6a62039..0000000
+++ /dev/null
@@ -1,1551 +0,0 @@
-# Doxyfile 1.6.3
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
-#
-# All text after a hash (#) is considered a comment and will be ignored
-# The format is:
-#       TAG = value [value, ...]
-# For lists items can also be appended using:
-#       TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (" ")
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# This tag specifies the encoding used for all characters in the config file
-# that follow. The default is UTF-8 which is also the encoding used for all
-# text before the first occurrence of this tag. Doxygen uses libiconv (or the
-# iconv built into libc) for the transcoding. See
-# http://www.gnu.org/software/libiconv for the list of possible encodings.
-
-DOXYFILE_ENCODING      = UTF-8
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
-# by quotes) that should identify the project.
-
-PROJECT_NAME           = @PACKAGE_NAME@
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number.
-# This could be handy for archiving the generated documentation or
-# if some version control system is used.
-
-PROJECT_NUMBER         = @PACKAGE_VERSION@
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
-# base path where the generated documentation will be put.
-# If a relative path is entered, it will be relative to the location
-# where doxygen was started. If left blank the current directory will be used.
-
-OUTPUT_DIRECTORY       =
-
-# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
-# 4096 sub-directories (in 2 levels) under the output directory of each output
-# format and will distribute the generated files over these directories.
-# Enabling this option can be useful when feeding doxygen a huge amount of
-# source files, where putting all generated files in the same directory would
-# otherwise cause performance problems for the file system.
-
-CREATE_SUBDIRS         = NO
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all constant output in the proper language.
-# The default language is English, other supported languages are:
-# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
-# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
-# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
-# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
-# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
-# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
-
-OUTPUT_LANGUAGE        = English
-
-# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
-# include brief member descriptions after the members that are listed in
-# the file and class documentation (similar to JavaDoc).
-# Set to NO to disable this.
-
-BRIEF_MEMBER_DESC      = YES
-
-# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
-# the brief description of a member or function before the detailed description.
-# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-
-REPEAT_BRIEF           = YES
-
-# This tag implements a quasi-intelligent brief description abbreviator
-# that is used to form the text in various listings. Each string
-# in this list, if found as the leading text of the brief description, will be
-# stripped from the text and the result after processing the whole list, is
-# used as the annotated text. Otherwise, the brief description is used as-is.
-# If left blank, the following values are used ("$name" is automatically
-# replaced with the name of the entity): "The $name class" "The $name widget"
-# "The $name file" "is" "provides" "specifies" "contains"
-# "represents" "a" "an" "the"
-
-ABBREVIATE_BRIEF       =
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# Doxygen will generate a detailed section even if there is only a brief
-# description.
-
-ALWAYS_DETAILED_SEC    = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
-# inherited members of a class in the documentation of that class as if those
-# members were ordinary class members. Constructors, destructors and assignment
-# operators of the base classes will not be shown.
-
-INLINE_INHERITED_MEMB  = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
-# path before files name in the file list and in the header files. If set
-# to NO the shortest path that makes the file name unique will be used.
-
-FULL_PATH_NAMES        = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
-# can be used to strip a user-defined part of the path. Stripping is
-# only done if one of the specified strings matches the left-hand part of
-# the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the
-# path to strip.
-
-STRIP_FROM_PATH        =
-
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
-# the path mentioned in the documentation of a class, which tells
-# the reader which header file to include in order to use a class.
-# If left blank only the name of the header file containing the class
-# definition is used. Otherwise one should specify the include paths that
-# are normally passed to the compiler using the -I flag.
-
-STRIP_FROM_INC_PATH    =
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
-# (but less readable) file names. This can be useful is your file systems
-# doesn't support long names like on DOS, Mac, or CD-ROM.
-
-SHORT_NAMES            = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
-# will interpret the first line (until the first dot) of a JavaDoc-style
-# comment as the brief description. If set to NO, the JavaDoc
-# comments will behave just like regular Qt-style comments
-# (thus requiring an explicit @brief command for a brief description.)
-
-JAVADOC_AUTOBRIEF      = YES
-
-# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
-# interpret the first line (until the first dot) of a Qt-style
-# comment as the brief description. If set to NO, the comments
-# will behave just like regular Qt-style comments (thus requiring
-# an explicit \brief command for a brief description.)
-
-QT_AUTOBRIEF           = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
-# treat a multi-line C++ special comment block (i.e. a block of //! or ///
-# comments) as a brief description. This used to be the default behaviour.
-# The new default is to treat a multi-line C++ comment block as a detailed
-# description. Set this tag to YES if you prefer the old behaviour instead.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
-# member inherits the documentation from any documented member that it
-# re-implements.
-
-INHERIT_DOCS           = YES
-
-# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
-# a new page for each member. If set to NO, the documentation of a member will
-# be part of the file/class/namespace that contains it.
-
-SEPARATE_MEMBER_PAGES  = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab.
-# Doxygen uses this value to replace tabs by spaces in code fragments.
-
-TAB_SIZE               = 4
-
-# This tag can be used to specify a number of aliases that acts
-# as commands in the documentation. An alias has the form "name=value".
-# For example adding "sideeffect=\par Side Effects:\n" will allow you to
-# put the command \sideeffect (or @sideeffect) in the documentation, which
-# will result in a user-defined paragraph with heading "Side Effects:".
-# You can put \n's in the value part of an alias to insert newlines.
-
-ALIASES                =
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
-# sources only. Doxygen will then generate output that is more tailored for C.
-# For instance, some of the names that are used will be different. The list
-# of all members will be omitted, etc.
-
-OPTIMIZE_OUTPUT_FOR_C  = YES
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
-# sources only. Doxygen will then generate output that is more tailored for
-# Java. For instance, namespaces will be presented as packages, qualified
-# scopes will look different, etc.
-
-OPTIMIZE_OUTPUT_JAVA   = NO
-
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources only. Doxygen will then generate output that is more tailored for
-# Fortran.
-
-OPTIMIZE_FOR_FORTRAN   = NO
-
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for
-# VHDL.
-
-OPTIMIZE_OUTPUT_VHDL   = NO
-
-# Doxygen selects the parser to use depending on the extension of the files it parses.
-# With this tag you can assign which parser to use for a given extension.
-# Doxygen has a built-in mapping, but you can override or extend it using this tag.
-# The format is ext=language, where ext is a file extension, and language is one of
-# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP,
-# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat
-# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran),
-# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
-
-EXTENSION_MAPPING      =
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should
-# set this tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
-# func(std::string) {}). This also make the inheritance and collaboration
-# diagrams that involve STL classes more complete and accurate.
-
-BUILTIN_STL_SUPPORT    = NO
-
-# If you use Microsoft's C++/CLI language, you should set this option to YES to
-# enable parsing support.
-
-CPP_CLI_SUPPORT        = NO
-
-# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
-# Doxygen will parse them like normal C++ but will assume all classes use public
-# instead of private inheritance when no explicit protection keyword is present.
-
-SIP_SUPPORT            = NO
-
-# For Microsoft's IDL there are propget and propput attributes to indicate getter
-# and setter methods for a property. Setting this option to YES (the default)
-# will make doxygen to replace the get and set methods by a property in the
-# documentation. This will only work if the methods are indeed getting or
-# setting a simple type. If this is not the case, or you want to show the
-# methods anyway, you should set this option to NO.
-
-IDL_PROPERTY_SUPPORT   = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES, then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
-
-DISTRIBUTE_GROUP_DOC   = NO
-
-# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
-# the same type (for instance a group of public functions) to be put as a
-# subgroup of that type (e.g. under the Public Functions section). Set it to
-# NO to prevent subgrouping. Alternatively, this can be done per class using
-# the \nosubgrouping command.
-
-SUBGROUPING            = YES
-
-# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
-# is documented as struct, union, or enum with the name of the typedef. So
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
-# with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically
-# be useful for C code in case the coding convention dictates that all compound
-# types are typedef'ed and only the typedef is referenced, never the tag name.
-
-TYPEDEF_HIDES_STRUCT   = NO
-
-# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
-# determine which symbols to keep in memory and which to flush to disk.
-# When the cache is full, less often used symbols will be written to disk.
-# For small to medium size projects (<1000 input files) the default value is
-# probably good enough. For larger projects a too small cache size can cause
-# doxygen to be busy swapping symbols to and from disk most of the time
-# causing a significant performance penality.
-# If the system has enough physical memory increasing the cache will improve the
-# performance by keeping more symbols in memory. Note that the value works on
-# a logarithmic scale so increasing the size by one will rougly double the
-# memory usage. The cache size is given by this formula:
-# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
-# corresponding to a cache size of 2^16 = 65536 symbols
-
-SYMBOL_CACHE_SIZE      = 0
-
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
-# documentation are documented, even if no documentation was available.
-# Private class members and static file members will be hidden unless
-# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
-
-EXTRACT_ALL            = YES
-
-# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
-# will be included in the documentation.
-
-EXTRACT_PRIVATE        = NO
-
-# If the EXTRACT_STATIC tag is set to YES all static members of a file
-# will be included in the documentation.
-
-EXTRACT_STATIC         = YES
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
-# defined locally in source files will be included in the documentation.
-# If set to NO only classes defined in header files are included.
-
-EXTRACT_LOCAL_CLASSES  = YES
-
-# This flag is only useful for Objective-C code. When set to YES local
-# methods, which are defined in the implementation section but not in
-# the interface are included in the documentation.
-# If set to NO (the default) only methods in the interface are included.
-
-EXTRACT_LOCAL_METHODS  = NO
-
-# If this flag is set to YES, the members of anonymous namespaces will be
-# extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base
-# name of the file that contains the anonymous namespace. By default
-# anonymous namespace are hidden.
-
-EXTRACT_ANON_NSPACES   = NO
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
-# undocumented members of documented classes, files or namespaces.
-# If set to NO (the default) these members will be included in the
-# various overviews, but no documentation section is generated.
-# This option has no effect if EXTRACT_ALL is enabled.
-
-HIDE_UNDOC_MEMBERS     = NO
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy.
-# If set to NO (the default) these classes will be included in the various
-# overviews. This option has no effect if EXTRACT_ALL is enabled.
-
-HIDE_UNDOC_CLASSES     = NO
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
-# friend (class|struct|union) declarations.
-# If set to NO (the default) these declarations will be included in the
-# documentation.
-
-HIDE_FRIEND_COMPOUNDS  = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
-# documentation blocks found inside the body of a function.
-# If set to NO (the default) these blocks will be appended to the
-# function's detailed documentation block.
-
-HIDE_IN_BODY_DOCS      = NO
-
-# The INTERNAL_DOCS tag determines if documentation
-# that is typed after a \internal command is included. If the tag is set
-# to NO (the default) then the documentation will be excluded.
-# Set it to YES to include the internal documentation.
-
-INTERNAL_DOCS          = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
-# file names in lower-case letters. If set to YES upper-case letters are also
-# allowed. This is useful if you have classes or files whose names only differ
-# in case and if your file system supports case sensitive file names. Windows
-# and Mac users are advised to set this option to NO.
-
-CASE_SENSE_NAMES       = YES
-
-# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
-# will show members with their full class and namespace scopes in the
-# documentation. If set to YES the scope will be hidden.
-
-HIDE_SCOPE_NAMES       = NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
-# will put a list of the files that are included by a file in the documentation
-# of that file.
-
-SHOW_INCLUDE_FILES     = YES
-
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
-# will list include files with double quotes in the documentation
-# rather than with sharp brackets.
-
-FORCE_LOCAL_INCLUDES   = NO
-
-# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
-# is inserted in the documentation for inline members.
-
-INLINE_INFO            = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
-# will sort the (detailed) documentation of file and class members
-# alphabetically by member name. If set to NO the members will appear in
-# declaration order.
-
-SORT_MEMBER_DOCS       = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
-# brief documentation of file, namespace and class members alphabetically
-# by member name. If set to NO (the default) the members will appear in
-# declaration order.
-
-SORT_BRIEF_DOCS        = NO
-
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
-
-SORT_MEMBERS_CTORS_1ST = NO
-
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
-# hierarchy of group names into alphabetical order. If set to NO (the default)
-# the group names will appear in their defined order.
-
-SORT_GROUP_NAMES       = NO
-
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
-# sorted by fully-qualified names, including namespaces. If set to
-# NO (the default), the class list will be sorted only by class name,
-# not including the namespace part.
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the
-# alphabetical list.
-
-SORT_BY_SCOPE_NAME     = NO
-
-# The GENERATE_TODOLIST tag can be used to enable (YES) or
-# disable (NO) the todo list. This list is created by putting \todo
-# commands in the documentation.
-
-GENERATE_TODOLIST      = YES
-
-# The GENERATE_TESTLIST tag can be used to enable (YES) or
-# disable (NO) the test list. This list is created by putting \test
-# commands in the documentation.
-
-GENERATE_TESTLIST      = YES
-
-# The GENERATE_BUGLIST tag can be used to enable (YES) or
-# disable (NO) the bug list. This list is created by putting \bug
-# commands in the documentation.
-
-GENERATE_BUGLIST       = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
-# disable (NO) the deprecated list. This list is created by putting
-# \deprecated commands in the documentation.
-
-GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional
-# documentation sections, marked by \if sectionname ... \endif.
-
-ENABLED_SECTIONS       =
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
-# the initial value of a variable or define consists of for it to appear in
-# the documentation. If the initializer consists of more lines than specified
-# here it will be hidden. Use a value of 0 to hide initializers completely.
-# The appearance of the initializer of individual variables and defines in the
-# documentation can be controlled using \showinitializer or \hideinitializer
-# command in the documentation regardless of this setting.
-
-MAX_INITIALIZER_LINES  = 30
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
-# at the bottom of the documentation of classes and structs. If set to YES the
-# list will mention the files that were used to generate the documentation.
-
-SHOW_USED_FILES        = YES
-
-# If the sources in your project are distributed over multiple directories
-# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
-# in the documentation. The default is NO.
-
-SHOW_DIRECTORIES       = NO
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
-# This will remove the Files entry from the Quick Index and from the
-# Folder Tree View (if specified). The default is YES.
-
-SHOW_FILES             = YES
-
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
-# Namespaces page.
-# This will remove the Namespaces entry from the Quick Index
-# and from the Folder Tree View (if specified). The default is YES.
-
-SHOW_NAMESPACES        = YES
-
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that
-# doxygen should invoke to get the current version for each file (typically from
-# the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command <command> <input-file>, where <command> is the value of
-# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
-# provided by doxygen. Whatever the program writes to standard output
-# is used as the file version. See the manual for examples.
-
-FILE_VERSION_FILTER    =
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by
-# doxygen. The layout file controls the global structure of the generated output files
-# in an output format independent way. The create the layout file that represents
-# doxygen's defaults, run doxygen with the -l option. You can optionally specify a
-# file name after the option, if omitted DoxygenLayout.xml will be used as the name
-# of the layout file.
-
-LAYOUT_FILE            =
-
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated
-# by doxygen. Possible values are YES and NO. If left blank NO is used.
-
-QUIET                  = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated by doxygen. Possible values are YES and NO. If left blank
-# NO is used.
-
-WARNINGS               = YES
-
-# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
-# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
-# automatically be disabled.
-
-WARN_IF_UNDOCUMENTED   = YES
-
-# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some
-# parameters in a documented function, or documenting parameters that
-# don't exist or using markup commands wrongly.
-
-WARN_IF_DOC_ERROR      = YES
-
-# This WARN_NO_PARAMDOC option can be abled to get warnings for
-# functions that are documented, but have no documentation for their parameters
-# or return value. If set to NO (the default) doxygen will only warn about
-# wrong or incomplete parameter documentation, but not about the absence of
-# documentation.
-
-WARN_NO_PARAMDOC       = NO
-
-# The WARN_FORMAT tag determines the format of the warning messages that
-# doxygen can produce. The string should contain the $file, $line, and $text
-# tags, which will be replaced by the file and line number from which the
-# warning originated and the warning text. Optionally the format may contain
-# $version, which will be replaced by the version of the file (if it could
-# be obtained via FILE_VERSION_FILTER)
-
-WARN_FORMAT            = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning
-# and error messages should be written. If left blank the output is written
-# to stderr.
-
-WARN_LOGFILE           =
-
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag can be used to specify the files and/or directories that contain
-# documented source files. You may enter file names like "myfile.cpp" or
-# directories like "/usr/src/myproject". Separate the files or directories
-# with spaces.
-
-INPUT                  = .. ../examples
-
-# This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
-# also the default input encoding. Doxygen uses libiconv (or the iconv built
-# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
-# the list of possible encodings.
-
-INPUT_ENCODING         = UTF-8
-
-# If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank the following patterns are tested:
-# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
-# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
-
-FILE_PATTERNS          =
-
-# The RECURSIVE tag can be used to turn specify whether or not subdirectories
-# should be searched for input files as well. Possible values are YES and NO.
-# If left blank NO is used.
-
-RECURSIVE              = NO
-
-# The EXCLUDE tag can be used to specify files and/or directories that should
-# excluded from the INPUT source files. This way you can easily exclude a
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-
-EXCLUDE                =
-
-# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
-# directories that are symbolic links (a Unix filesystem feature) are excluded
-# from the input.
-
-EXCLUDE_SYMLINKS       = NO
-
-# If the value of the INPUT tag contains directories, you can use the
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories. Note that the wildcards are matched
-# against the file with absolute path, so to exclude all test directories
-# for example use the pattern */test/*
-
-EXCLUDE_PATTERNS       =
-
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
-# (namespaces, classes, functions, etc.) that should be excluded from the
-# output. The symbol name can be a fully qualified name, a word, or if the
-# wildcard * is used, a substring. Examples: ANamespace, AClass,
-# AClass::ANamespace, ANamespace::*Test
-
-EXCLUDE_SYMBOLS        =
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or
-# directories that contain example code fragments that are included (see
-# the \include command).
-
-EXAMPLE_PATH           =
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank all files are included.
-
-EXAMPLE_PATTERNS       =
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude
-# commands irrespective of the value of the RECURSIVE tag.
-# Possible values are YES and NO. If left blank NO is used.
-
-EXAMPLE_RECURSIVE      = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or
-# directories that contain image that are included in the documentation (see
-# the \image command).
-
-IMAGE_PATH             =
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should
-# invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command <filter> <input-file>, where <filter>
-# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
-# input file. Doxygen will then use the output that the filter program writes
-# to standard output.
-# If FILTER_PATTERNS is specified, this tag will be
-# ignored.
-
-INPUT_FILTER           =
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis.
-# Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match.
-# The filters are a list of the form:
-# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
-# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
-# is applied to all files.
-
-FILTER_PATTERNS        =
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER) will be used to filter the input files when producing source
-# files to browse (i.e. when SOURCE_BROWSER is set to YES).
-
-FILTER_SOURCE_FILES    = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will
-# be generated. Documented entities will be cross-referenced with these sources.
-# Note: To get rid of all source code in the generated output, make sure also
-# VERBATIM_HEADERS is set to NO.
-
-SOURCE_BROWSER         = YES
-
-# Setting the INLINE_SOURCES tag to YES will include the body
-# of functions and classes directly in the documentation.
-
-INLINE_SOURCES         = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
-# doxygen to hide any special comment blocks from generated source code
-# fragments. Normal C and C++ comments will always remain visible.
-
-STRIP_CODE_COMMENTS    = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES
-# then for each documented function all documented
-# functions referencing it will be listed.
-
-REFERENCED_BY_RELATION = NO
-
-# If the REFERENCES_RELATION tag is set to YES
-# then for each documented function all documented entities
-# called/used by that function will be listed.
-
-REFERENCES_RELATION    = NO
-
-# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
-# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
-# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
-# link to the source code.
-# Otherwise they will link to the documentation.
-
-REFERENCES_LINK_SOURCE = YES
-
-# If the USE_HTAGS tag is set to YES then the references to source code
-# will point to the HTML generated by the htags(1) tool instead of doxygen
-# built-in source browser. The htags tool is part of GNU's global source
-# tagging system (see http://www.gnu.org/software/global/global.html). You
-# will need version 4.8.6 or higher.
-
-USE_HTAGS              = NO
-
-# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
-# will generate a verbatim copy of the header file for each class for
-# which an include is specified. Set to NO to disable this.
-
-VERBATIM_HEADERS       = YES
-
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
-# of all compounds will be generated. Enable this if the project
-# contains a lot of classes, structs, unions or interfaces.
-
-ALPHABETICAL_INDEX     = NO
-
-# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
-# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
-# in which this list will be split (can be a number in the range [1..20])
-
-COLS_IN_ALPHA_INDEX    = 5
-
-# In case all classes in a project start with a common prefix, all
-# classes will be put under the same header in the alphabetical index.
-# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
-# should be ignored while generating the index headers.
-
-IGNORE_PREFIX          =
-
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
-# generate HTML output.
-
-GENERATE_HTML          = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `html' will be used as the default path.
-
-HTML_OUTPUT            = html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
-# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
-# doxygen will generate files with .html extension.
-
-HTML_FILE_EXTENSION    = .html
-
-# The HTML_HEADER tag can be used to specify a personal HTML header for
-# each generated HTML page. If it is left blank doxygen will generate a
-# standard header.
-
-HTML_HEADER            =
-
-# The HTML_FOOTER tag can be used to specify a personal HTML footer for
-# each generated HTML page. If it is left blank doxygen will generate a
-# standard footer.
-
-HTML_FOOTER            =
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
-# style sheet that is used by each HTML page. It can be used to
-# fine-tune the look of the HTML output. If the tag is left blank doxygen
-# will generate a default style sheet. Note that doxygen will try to copy
-# the style sheet file to the HTML output directory, so don't put your own
-# stylesheet in the HTML output directory as well, or it will be erased!
-
-HTML_STYLESHEET        =
-
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
-# page will contain the date and time when the page was generated. Setting
-# this to NO can help when comparing the output of multiple runs.
-
-HTML_TIMESTAMP         = YES
-
-# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
-# files or namespaces will be aligned in HTML using tables. If set to
-# NO a bullet list will be used.
-
-HTML_ALIGN_MEMBERS     = YES
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
-# documentation will contain sections that can be hidden and shown after the
-# page has loaded. For this to work a browser that supports
-# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
-# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
-
-HTML_DYNAMIC_SECTIONS  = NO
-
-# If the GENERATE_DOCSET tag is set to YES, additional index files
-# will be generated that can be used as input for Apple's Xcode 3
-# integrated development environment, introduced with OSX 10.5 (Leopard).
-# To create a documentation set, doxygen will generate a Makefile in the
-# HTML output directory. Running make will produce the docset in that
-# directory and running "make install" will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
-# it at startup.
-# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.
-
-GENERATE_DOCSET        = NO
-
-# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
-# feed. A documentation feed provides an umbrella under which multiple
-# documentation sets from a single provider (such as a company or product suite)
-# can be grouped.
-
-DOCSET_FEEDNAME        = "Doxygen generated docs"
-
-# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
-# should uniquely identify the documentation set bundle. This should be a
-# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
-# will append .docset to the name.
-
-DOCSET_BUNDLE_ID       = org.doxygen.Project
-
-# If the GENERATE_HTMLHELP tag is set to YES, additional index files
-# will be generated that can be used as input for tools like the
-# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
-# of the generated HTML documentation.
-
-GENERATE_HTMLHELP      = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
-# be used to specify the file name of the resulting .chm file. You
-# can add a path in front of the file if the result should not be
-# written to the html output directory.
-
-CHM_FILE               =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
-# be used to specify the location (absolute path including file name) of
-# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
-# the HTML help compiler on the generated index.hhp.
-
-HHC_LOCATION           =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
-# controls if a separate .chi index file is generated (YES) or that
-# it should be included in the master .chm file (NO).
-
-GENERATE_CHI           = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
-# is used to encode HtmlHelp index (hhk), content (hhc) and project file
-# content.
-
-CHM_INDEX_ENCODING     =
-
-# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
-# controls whether a binary table of contents is generated (YES) or a
-# normal table of contents (NO) in the .chm file.
-
-BINARY_TOC             = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members
-# to the contents of the HTML help documentation and to the tree view.
-
-TOC_EXPAND             = NO
-
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER
-# are set, an additional index file will be generated that can be used as input for
-# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated
-# HTML documentation.
-
-GENERATE_QHP           = NO
-
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
-# be used to specify the file name of the resulting .qch file.
-# The path specified is relative to the HTML output folder.
-
-QCH_FILE               =
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#namespace
-
-QHP_NAMESPACE          = org.doxygen.Project
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#virtual-folders
-
-QHP_VIRTUAL_FOLDER     = doc
-
-# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add.
-# For more information please see
-# http://doc.trolltech.com/qthelpproject.html#custom-filters
-
-QHP_CUST_FILTER_NAME   =
-
-# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see
-# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>.
-
-QHP_CUST_FILTER_ATTRS  =
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's
-# filter section matches.
-# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>.
-
-QHP_SECT_FILTER_ATTRS  =
-
-# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
-# be used to specify the location of Qt's qhelpgenerator.
-# If non-empty doxygen will try to run qhelpgenerator on the generated
-# .qhp file.
-
-QHG_LOCATION           =
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
-#  will be generated, which together with the HTML files, form an Eclipse help
-#  plugin. To install this plugin and make it available under the help contents
-# menu in Eclipse, the contents of the directory containing the HTML and XML
-# files needs to be copied into the plugins directory of eclipse. The name of
-# the directory within the plugins directory should be the same as
-# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears.
-
-GENERATE_ECLIPSEHELP   = NO
-
-# A unique identifier for the eclipse help plugin. When installing the plugin
-# the directory name containing the HTML and XML files should also have
-# this name.
-
-ECLIPSE_DOC_ID         = org.doxygen.Project
-
-# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
-# top of each HTML page. The value NO (the default) enables the index and
-# the value YES disables it.
-
-DISABLE_INDEX          = NO
-
-# This tag can be used to set the number of enum values (range [1..20])
-# that doxygen will group on one line in the generated HTML documentation.
-
-ENUM_VALUES_PER_LINE   = 4
-
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information.
-# If the tag value is set to YES, a side panel will be generated
-# containing a tree-like index structure (just like the one that
-# is generated for HTML Help). For this to work a browser that supports
-# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
-# Windows users are probably better off using the HTML help feature.
-
-GENERATE_TREEVIEW      = NO
-
-# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
-# and Class Hierarchy pages using a tree view instead of an ordered list.
-
-USE_INLINE_TREES       = NO
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
-# used to set the initial width (in pixels) of the frame in which the tree
-# is shown.
-
-TREEVIEW_WIDTH         = 250
-
-# Use this tag to change the font size of Latex formulas included
-# as images in the HTML documentation. The default is 10. Note that
-# when you change the font size after a successful doxygen run you need
-# to manually remove any form_*.png images from the HTML output directory
-# to force them to be regenerated.
-
-FORMULA_FONTSIZE       = 10
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript
-# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should
-# typically be disabled. For large projects the javascript based search engine
-# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
-
-SEARCHENGINE           = YES
-
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index
-# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup
-# and does not have live searching capabilities.
-
-SERVER_BASED_SEARCH    = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
-# generate Latex output.
-
-GENERATE_LATEX         = NO
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `latex' will be used as the default path.
-
-LATEX_OUTPUT           = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked. If left blank `latex' will be used as the default command name.
-# Note that when enabling USE_PDFLATEX this option is only used for
-# generating bitmaps for formulas in the HTML output, but not in the
-# Makefile that is written to the output directory.
-
-LATEX_CMD_NAME         = latex
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
-# generate index for LaTeX. If left blank `makeindex' will be used as the
-# default command name.
-
-MAKEINDEX_CMD_NAME     = makeindex
-
-# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
-# LaTeX documents. This may be useful for small projects and may help to
-# save some trees in general.
-
-COMPACT_LATEX          = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used
-# by the printer. Possible values are: a4, a4wide, letter, legal and
-# executive. If left blank a4wide will be used.
-
-PAPER_TYPE             = a4wide
-
-# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
-# packages that should be included in the LaTeX output.
-
-EXTRA_PACKAGES         =
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
-# the generated latex document. The header should contain everything until
-# the first chapter. If it is left blank doxygen will generate a
-# standard header. Notice: only use this tag if you know what you are doing!
-
-LATEX_HEADER           =
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
-# is prepared for conversion to pdf (using ps2pdf). The pdf file will
-# contain links (just like the HTML output) instead of page references
-# This makes the output suitable for online browsing using a pdf viewer.
-
-PDF_HYPERLINKS         = YES
-
-# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
-# plain latex in the generated Makefile. Set this option to YES to get a
-# higher quality PDF documentation.
-
-USE_PDFLATEX           = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
-# command to the generated LaTeX files. This will instruct LaTeX to keep
-# running if errors occur, instead of asking the user for help.
-# This option is also used when generating formulas in HTML.
-
-LATEX_BATCHMODE        = NO
-
-# If LATEX_HIDE_INDICES is set to YES then doxygen will not
-# include the index chapters (such as File Index, Compound Index, etc.)
-# in the output.
-
-LATEX_HIDE_INDICES     = NO
-
-# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER.
-
-LATEX_SOURCE_CODE      = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
-# The RTF output is optimized for Word 97 and may not look very pretty with
-# other RTF readers or editors.
-
-GENERATE_RTF           = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `rtf' will be used as the default path.
-
-RTF_OUTPUT             = rtf
-
-# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
-# RTF documents. This may be useful for small projects and may help to
-# save some trees in general.
-
-COMPACT_RTF            = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
-# will contain hyperlink fields. The RTF file will
-# contain links (just like the HTML output) instead of page references.
-# This makes the output suitable for online browsing using WORD or other
-# programs which support those fields.
-# Note: wordpad (write) and others do not support links.
-
-RTF_HYPERLINKS         = NO
-
-# Load stylesheet definitions from file. Syntax is similar to doxygen's
-# config file, i.e. a series of assignments. You only have to provide
-# replacements, missing definitions are set to their default value.
-
-RTF_STYLESHEET_FILE    =
-
-# Set optional variables used in the generation of an rtf document.
-# Syntax is similar to doxygen's config file.
-
-RTF_EXTENSIONS_FILE    =
-
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
-# generate man pages
-
-GENERATE_MAN           = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `man' will be used as the default path.
-
-MAN_OUTPUT             = man
-
-# The MAN_EXTENSION tag determines the extension that is added to
-# the generated man pages (default is the subroutine's section .3)
-
-MAN_EXTENSION          = .3
-
-# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
-# then it will generate one additional man file for each entity
-# documented in the real man page(s). These additional files
-# only source the real man page, but without them the man command
-# would be unable to find the correct page. The default is NO.
-
-MAN_LINKS              = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES Doxygen will
-# generate an XML file that captures the structure of
-# the code including all documentation.
-
-GENERATE_XML           = NO
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `xml' will be used as the default path.
-
-XML_OUTPUT             = xml
-
-# The XML_SCHEMA tag can be used to specify an XML schema,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_SCHEMA             =
-
-# The XML_DTD tag can be used to specify an XML DTD,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_DTD                =
-
-# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
-# dump the program listings (including syntax highlighting
-# and cross-referencing information) to the XML output. Note that
-# enabling this will significantly increase the size of the XML output.
-
-XML_PROGRAMLISTING     = YES
-
-#---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
-# generate an AutoGen Definitions (see autogen.sf.net) file
-# that captures the structure of the code including all
-# documentation. Note that this feature is still experimental
-# and incomplete at the moment.
-
-GENERATE_AUTOGEN_DEF   = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES Doxygen will
-# generate a Perl module file that captures the structure of
-# the code including all documentation. Note that this
-# feature is still experimental and incomplete at the
-# moment.
-
-GENERATE_PERLMOD       = NO
-
-# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
-# the necessary Makefile rules, Perl scripts and LaTeX code to be able
-# to generate PDF and DVI output from the Perl module output.
-
-PERLMOD_LATEX          = NO
-
-# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
-# nicely formatted so it can be parsed by a human reader.
-# This is useful
-# if you want to understand what is going on.
-# On the other hand, if this
-# tag is set to NO the size of the Perl module output will be much smaller
-# and Perl will parse it just the same.
-
-PERLMOD_PRETTY         = YES
-
-# The names of the make variables in the generated doxyrules.make file
-# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
-# This is useful so different doxyrules.make files included by the same
-# Makefile don't overwrite each other's variables.
-
-PERLMOD_MAKEVAR_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
-# evaluate all C-preprocessor directives found in the sources and include
-# files.
-
-ENABLE_PREPROCESSING   = YES
-
-# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
-# names in the source code. If set to NO (the default) only conditional
-# compilation will be performed. Macro expansion can be done in a controlled
-# way by setting EXPAND_ONLY_PREDEF to YES.
-
-MACRO_EXPANSION        = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
-# then the macro expansion is limited to the macros specified with the
-# PREDEFINED and EXPAND_AS_DEFINED tags.
-
-EXPAND_ONLY_PREDEF     = NO
-
-# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
-# in the INCLUDE_PATH (see below) will be search if a #include is found.
-
-SEARCH_INCLUDES        = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by
-# the preprocessor.
-
-INCLUDE_PATH           =
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
-# patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will
-# be used.
-
-INCLUDE_FILE_PATTERNS  =
-
-# The PREDEFINED tag can be used to specify one or more macro names that
-# are defined before the preprocessor is started (similar to the -D option of
-# gcc). The argument of the tag is a list of macros of the form: name
-# or name=definition (no spaces). If the definition and the = are
-# omitted =1 is assumed. To prevent a macro definition from being
-# undefined via #undef or recursively expanded use the := operator
-# instead of the = operator.
-
-PREDEFINED             =
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
-# this tag can be used to specify a list of macro names that should be expanded.
-# The macro definition that is found in the sources will be used.
-# Use the PREDEFINED tag if you want to use a different macro definition.
-
-EXPAND_AS_DEFINED      =
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
-# doxygen's preprocessor will remove all function-like macros that are alone
-# on a line, have an all uppercase name, and do not end with a semicolon. Such
-# function macros are typically used for boiler-plate code, and will confuse
-# the parser if not removed.
-
-SKIP_FUNCTION_MACROS   = YES
-
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES option can be used to specify one or more tagfiles.
-# Optionally an initial location of the external documentation
-# can be added for each tagfile. The format of a tag file without
-# this location is as follows:
-#
-# TAGFILES = file1 file2 ...
-# Adding location for the tag files is done as follows:
-#
-# TAGFILES = file1=loc1 "file2 = loc2" ...
-# where "loc1" and "loc2" can be relative or absolute paths or
-# URLs. If a location is present for each tag, the installdox tool
-# does not have to be run to correct the links.
-# Note that each tag file must have a unique name
-# (where the name does NOT include the path)
-# If a tag file is not located in the directory in which doxygen
-# is run, you must also specify the path to the tagfile here.
-
-TAGFILES               =
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create
-# a tag file that is based on the input files it reads.
-
-GENERATE_TAGFILE       =
-
-# If the ALLEXTERNALS tag is set to YES all external classes will be listed
-# in the class index. If set to NO only the inherited external classes
-# will be listed.
-
-ALLEXTERNALS           = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
-# in the modules index. If set to NO, only the current project's groups will
-# be listed.
-
-EXTERNAL_GROUPS        = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script
-# interpreter (i.e. the result of `which perl').
-
-PERL_PATH              = /usr/bin/perl
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
-# or super classes. Setting the tag to NO turns the diagrams off. Note that
-# this option is superseded by the HAVE_DOT option below. This is only a
-# fallback. It is recommended to install and use dot, since it yields more
-# powerful graphs.
-
-CLASS_DIAGRAMS         = NO
-
-# You can define message sequence charts within doxygen comments using the \msc
-# command. Doxygen will then run the mscgen tool (see
-# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
-# documentation. The MSCGEN_PATH tag allows you to specify the directory where
-# the mscgen tool resides. If left empty the tool is assumed to be found in the
-# default search path.
-
-MSCGEN_PATH            =
-
-# If set to YES, the inheritance and collaboration graphs will hide
-# inheritance and usage relations if the target is undocumented
-# or is not a class.
-
-HIDE_UNDOC_RELATIONS   = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz, a graph visualization
-# toolkit from AT&T and Lucent Bell Labs. The other options in this section
-# have no effect if this option is set to NO (the default)
-
-HAVE_DOT               = NO
-
-# By default doxygen will write a font called FreeSans.ttf to the output
-# directory and reference it in all dot files that doxygen generates. This
-# font does not include all possible unicode characters however, so when you need
-# these (or just want a differently looking font) you can specify the font name
-# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
-# which can be done by putting it in a standard location or by setting the
-# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
-# containing the font.
-
-DOT_FONTNAME           = FreeSans
-
-# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
-# The default size is 10pt.
-
-DOT_FONTSIZE           = 10
-
-# By default doxygen will tell dot to use the output directory to look for the
-# FreeSans.ttf font (which doxygen will put there itself). If you specify a
-# different font using DOT_FONTNAME you can set the path where dot
-# can find it using this tag.
-
-DOT_FONTPATH           =
-
-# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect inheritance relations. Setting this tag to YES will force the
-# the CLASS_DIAGRAMS tag to NO.
-
-CLASS_GRAPH            = YES
-
-# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect implementation dependencies (inheritance, containment, and
-# class references variables) of the class with other documented classes.
-
-COLLABORATION_GRAPH    = YES
-
-# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for groups, showing the direct groups dependencies
-
-GROUP_GRAPHS           = YES
-
-# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
-# collaboration diagrams in a style similar to the OMG's Unified Modeling
-# Language.
-
-UML_LOOK               = NO
-
-# If set to YES, the inheritance and collaboration graphs will show the
-# relations between templates and their instances.
-
-TEMPLATE_RELATIONS     = NO
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
-# tags are set to YES then doxygen will generate a graph for each documented
-# file showing the direct and indirect include dependencies of the file with
-# other documented files.
-
-INCLUDE_GRAPH          = YES
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
-# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
-# documented header file showing the documented files that directly or
-# indirectly include this file.
-
-INCLUDED_BY_GRAPH      = YES
-
-# If the CALL_GRAPH and HAVE_DOT options are set to YES then
-# doxygen will generate a call dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable call graphs
-# for selected functions only using the \callgraph command.
-
-CALL_GRAPH             = NO
-
-# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
-# doxygen will generate a caller dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable caller
-# graphs for selected functions only using the \callergraph command.
-
-CALLER_GRAPH           = NO
-
-# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
-# will graphical hierarchy of all classes instead of a textual one.
-
-GRAPHICAL_HIERARCHY    = YES
-
-# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
-# then doxygen will show the dependencies a directory has on other directories
-# in a graphical way. The dependency relations are determined by the #include
-# relations between the files in the directories.
-
-DIRECTORY_GRAPH        = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot. Possible values are png, jpg, or gif
-# If left blank png will be used.
-
-DOT_IMAGE_FORMAT       = png
-
-# The tag DOT_PATH can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found in the path.
-
-DOT_PATH               =
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the
-# \dotfile command).
-
-DOTFILE_DIRS           =
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
-# nodes that will be shown in the graph. If the number of nodes in a graph
-# becomes larger than this value, doxygen will truncate the graph, which is
-# visualized by representing a node as a red box. Note that doxygen if the
-# number of direct children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
-# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-
-DOT_GRAPH_MAX_NODES    = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
-# graphs generated by dot. A depth value of 3 means that only nodes reachable
-# from the root by following a path via at most 3 edges will be shown. Nodes
-# that lay further from the root node will be omitted. Note that setting this
-# option to 1 or 2 may greatly reduce the computation time needed for large
-# code bases. Also note that the size of a graph can be further restricted by
-# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
-
-MAX_DOT_GRAPH_DEPTH    = 0
-
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not
-# seem to support this out of the box. Warning: Depending on the platform used,
-# enabling this option may lead to badly anti-aliased labels on the edges of
-# a graph (i.e. they become hard to read).
-
-DOT_TRANSPARENT        = NO
-
-# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
-# files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10)
-# support this, this feature is disabled by default.
-
-DOT_MULTI_TARGETS      = YES
-
-# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
-# generate a legend page explaining the meaning of the various boxes and
-# arrows in the dot generated graphs.
-
-GENERATE_LEGEND        = YES
-
-# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
-# remove the intermediate dot files that are used to generate
-# the various graphs.
-
-DOT_CLEANUP            = YES
diff --git a/resource/csdk/libcoap-4.1.1/doc/Makefile.in b/resource/csdk/libcoap-4.1.1/doc/Makefile.in
deleted file mode 100644 (file)
index df72d6a..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-# Makefile for libcoap
-#
-# Copyright (C) 2010 Olaf Bergmann <bergmann@tzi.org>
-# 
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
-
-# the library's version
-VERSION:=@PACKAGE_VERSION@
-
-# tools
-@SET_MAKE@
-SHELL = /bin/sh
-MKDIR = mkdir
-DOXYGEN= @DOXYGEN@
-
-top_builddir = @top_builddir@
-
-DISTDIR?=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@
-FILES:=Makefile.in Doxyfile.in html
-
-doc:   Doxyfile
-       $(DOXYGEN) $< >./doxygen.out 2>&1 
-
-clean:
-       @rm -rf html
-
-distclean:     clean
-       @rm -rf $(DISTDIR)
-       @rm -f *~ 
-
-dist:  doc
-       test -d $(DISTDIR)/doc || mkdir $(DISTDIR)/doc
-       cp -r $(FILES) $(DISTDIR)/doc
diff --git a/resource/csdk/libcoap-4.1.1/doc/makefile b/resource/csdk/libcoap-4.1.1/doc/makefile
deleted file mode 100644 (file)
index 5105c9d..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# Makefile for libcoap
-#
-# Copyright (C) 2010 Olaf Bergmann <bergmann@tzi.org>
-# 
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
-
-# the library's version
-VERSION:=4.1.1
-
-# tools
-
-SHELL = /bin/sh
-MKDIR = mkdir
-DOXYGEN= /usr/bin/doxygen
-
-top_builddir = ..
-
-DISTDIR?=$(top_builddir)/libcoap-4.1.1
-FILES:=Makefile.in Doxyfile.in html
-
-doc:   Doxyfile
-       @mkdir html
-       $(DOXYGEN) $< >./doxygen.out 2>&1 
-
-clean:
-       @rm -rf html doxygen.out
-
-distclean:     clean
-       @rm -rf $(DISTDIR)
-       @rm -f *~ 
-
-dist:  doc
-       test -d $(DISTDIR)/doc || mkdir $(DISTDIR)/doc
-       cp -r $(FILES) $(DISTDIR)/doc
diff --git a/resource/csdk/libcoap-4.1.1/encode.c b/resource/csdk/libcoap-4.1.1/encode.c
deleted file mode 100644 (file)
index b034b6b..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/* encode.c -- encoding and decoding of CoAP data types
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#ifndef NDEBUG
-#  include <stdio.h>
-#endif
-
-#include "config.h"
-#include "encode.h"
-
-/* Carsten suggested this when fls() is not available: */
-int coap_fls(unsigned int i) {
-  int n;
-  for (n = 0; i; n++)
-    i >>= 1;
-  return n;
-}
-
-unsigned int
-coap_decode_var_bytes(unsigned char *buf,unsigned int len) {
-  unsigned int i, n = 0;
-  for (i = 0; i < len; ++i)
-    n = (n << 8) + buf[i];
-
-  return n;
-}
-
-unsigned int
-coap_encode_var_bytes(unsigned char *buf, unsigned int val) {
-  unsigned int n, i;
-
-  for (n = 0, i = val; i && n < sizeof(val); ++n)
-    i >>= 8;
-
-  i = n;
-  while (i--) {
-    buf[i] = val & 0xff;
-    val >>= 8;
-  }
-
-  return n;
-}
-
diff --git a/resource/csdk/libcoap-4.1.1/encode.h b/resource/csdk/libcoap-4.1.1/encode.h
deleted file mode 100644 (file)
index bcc9e17..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/* encode.h -- encoding and decoding of CoAP data types
- *
- * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#ifndef _COAP_ENCODE_H_
-#define _COAP_ENCODE_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if (BSD >= 199103) || defined(WITH_CONTIKI)
-# include <string.h>
-#else
-#ifndef WITH_ARDUINO
-# include <strings.h>
-#endif
-#endif
-
-#define Nn 8  /* duplicate definition of N if built on sky motes */
-#define E 4
-#define HIBIT (1 << (Nn - 1))
-#define EMASK ((1 << E) - 1)
-#define MMASK ((1 << Nn) - 1 - EMASK)
-#define MAX_VALUE ( (1 << Nn) - (1 << E) ) * (1 << ((1 << E) - 1))
-
-#define COAP_PSEUDOFP_DECODE_8_4(r) (r < HIBIT ? r : (r & MMASK) << (r & EMASK))
-
-#ifndef HAVE_FLS
-/* include this only if fls() is not available */
-extern int coap_fls(unsigned int i);
-#else
-#define coap_fls(i) fls(i)
-#endif
-
-/* ls and s must be integer variables */
-#define COAP_PSEUDOFP_ENCODE_8_4_DOWN(v,ls) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (v >> ls) & MMASK) + ls)
-#define COAP_PSEUDOFP_ENCODE_8_4_UP(v,ls,s) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (s = (((v + ((1<<E<<ls)-1)) >> ls) & MMASK)), s == 0 ? HIBIT + ls + 1 : s + ls))
-
-/**
- * Decodes multiple-length byte sequences. buf points to an input byte
- * sequence of length len. Returns the decoded value.
- */
-unsigned int coap_decode_var_bytes(unsigned char *buf,unsigned int len);
-
-/**
- * Encodes multiple-length byte sequences. buf points to an output
- * buffer of sufficient length to store the encoded bytes. val is
- * the value to encode. Returns the number of bytes used to encode
- * val or 0 on error.
- */
-unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_ENCODE_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/examples/client.c b/resource/csdk/libcoap-4.1.1/examples/client.c
deleted file mode 100644 (file)
index 29b5922..0000000
+++ /dev/null
@@ -1,1177 +0,0 @@
-/* coap-client -- simple CoAP client
- *
- * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-#include <logger.h>
-
-#include "coap.h"
-
-int flags = 0;
-
-static unsigned char _token_data[8];
-str the_token = { 0, _token_data };
-
-#define MOD_NAME ("CoAP-Client")
-#define FLAGS_BLOCK 0x01
-
-static coap_list_t *optlist = NULL;
-/* Request URI.
- * TODO: associate the resources with transaction id and make it expireable */
-static coap_uri_t uri;
-static str proxy = { 0, NULL };
-static unsigned short proxy_port = COAP_DEFAULT_PORT;
-
-/* reading is done when this flag is set */
-static int ready = 0;
-
-static str output_file = { 0, NULL }; /* output file name */
-static FILE *file = NULL;      /* output file stream */
-
-static str payload = { 0, NULL }; /* optional payload to send */
-
-unsigned char msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */
-
-typedef unsigned char method_t;
-method_t method = 1;           /* the method we are using in our requests */
-
-coap_block_t block = { .num = 0, .m = 0, .szx = 6 };
-
-unsigned int wait_seconds = 90;        /* default timeout in seconds */
-coap_tick_t max_wait;          /* global timeout (changed by set_timeout()) */
-
-unsigned int obs_seconds = 30; /* default observe time */
-coap_tick_t obs_wait = 0;      /* timeout for current subscription */
-
-#define min(a,b) ((a) < (b) ? (a) : (b))
-
-static inline void
-set_timeout(coap_tick_t *timer, const unsigned int seconds) {
-  coap_ticks(timer);
-  *timer += seconds * COAP_TICKS_PER_SECOND;
-}
-
-int
-append_to_output(const unsigned char *data, size_t len) {
-  size_t written;
-
-  if (!file) {
-    if (!output_file.s || (output_file.length && output_file.s[0] == '-'))
-      file = stdout;
-    else {
-      if (!(file = fopen((char *)output_file.s, "w"))) {
-       perror("fopen");
-       return -1;
-      }
-    }
-  }
-
-  do {
-    written = fwrite(data, 1, len, file);
-    len -= written;
-    data += written;
-  } while ( written && len );
-  fflush(file);
-
-  return 0;
-}
-
-void
-close_output() {
-  if (file) {
-
-    /* add a newline before closing in case were writing to stdout */
-    if (!output_file.s || (output_file.length && output_file.s[0] == '-'))
-      fwrite("\n", 1, 1, file);
-
-    fflush(file);
-    fclose(file);
-  }
-}
-
-coap_pdu_t *
-new_ack( coap_context_t  *ctx, coap_queue_t *node ) {
-  coap_pdu_t *pdu = coap_new_pdu();
-  (void)ctx;
-
-  if (pdu) {
-    pdu->hdr->type = COAP_MESSAGE_ACK;
-    pdu->hdr->code = 0;
-    pdu->hdr->id = node->pdu->hdr->id;
-  }
-
-  return pdu;
-}
-
-coap_pdu_t *
-new_response( coap_context_t  *ctx, coap_queue_t *node, unsigned int code ) {
-  coap_pdu_t *pdu = new_ack(ctx, node);
-
-  if (pdu)
-    pdu->hdr->code = code;
-
-  return pdu;
-}
-
-coap_pdu_t *
-coap_new_request(coap_context_t *ctx, method_t m, coap_list_t *options ) {
-  coap_pdu_t *pdu;
-  coap_list_t *opt;
-
-  if ( ! ( pdu = coap_new_pdu() ) )
-    return NULL;
-
-  pdu->hdr->type = msgtype;
-  pdu->hdr->id = coap_new_message_id(ctx);
-  pdu->hdr->code = m;
-
-  pdu->hdr->token_length = the_token.length;
-  if ( !coap_add_token(pdu, the_token.length, the_token.s)) {
-    debug("cannot add token to request\n");
-  }
-  coap_show_pdu(pdu);
-
-  for (opt = options; opt; opt = opt->next) {
-    coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data),
-                   COAP_OPTION_LENGTH(*(coap_option *)opt->data),
-                   COAP_OPTION_DATA(*(coap_option *)opt->data));
-  }
-
-  if (payload.length) {
-    if ((flags & FLAGS_BLOCK) == 0)
-      coap_add_data(pdu, payload.length, payload.s);
-    else
-      coap_add_block(pdu, payload.length, payload.s, block.num, block.szx);
-  }
-
-  return pdu;
-}
-
-coap_tid_t
-clear_obs(coap_context_t *ctx, const coap_address_t *remote) {
-  coap_list_t *option;
-  coap_pdu_t *pdu;
-  coap_tid_t tid = COAP_INVALID_TID;
-
-  /* create bare PDU w/o any option  */
-  pdu = coap_new_request(ctx, COAP_REQUEST_GET, NULL);
-
-  if (pdu) {
-    /* FIXME: add token */
-    /* add URI components from optlist */
-    for (option = optlist; option; option = option->next ) {
-      switch (COAP_OPTION_KEY(*(coap_option *)option->data)) {
-      case COAP_OPTION_URI_HOST :
-      case COAP_OPTION_URI_PORT :
-      case COAP_OPTION_URI_PATH :
-      case COAP_OPTION_URI_QUERY :
-       coap_add_option ( pdu, COAP_OPTION_KEY(*(coap_option *)option->data),
-                         COAP_OPTION_LENGTH(*(coap_option *)option->data),
-                         COAP_OPTION_DATA(*(coap_option *)option->data) );
-       break;
-      default:
-       ;                       /* skip other options */
-      }
-    }
-
-    if (pdu->hdr->type == COAP_MESSAGE_CON)
-      tid = coap_send_confirmed(ctx, remote, pdu);
-    else
-      tid = coap_send(ctx, remote, pdu);
-
-    if (tid == COAP_INVALID_TID) {
-      debug("clear_obs: error sending new request");
-      coap_delete_pdu(pdu);
-    } else if (pdu->hdr->type != COAP_MESSAGE_CON)
-      coap_delete_pdu(pdu);
-  }
-  return tid;
-}
-
-int
-resolve_address(const str *server, struct sockaddr *dst) {
-
-  struct addrinfo *res, *ainfo;
-  struct addrinfo hints;
-  static char addrstr[256];
-  int error, len=-1;
-
-
-  memset(addrstr, 0, sizeof(addrstr));
-  if (server->length)
-    memcpy(addrstr, server->s, server->length);
-  else
-    memcpy(addrstr, "localhost", 9);
-
-  OC_LOG_V(DEBUG, MOD_NAME, "Line %d, server %s", __LINE__, addrstr);
-
-  memset ((char *)&hints, 0, sizeof(hints));
-  hints.ai_socktype = SOCK_DGRAM;
-  hints.ai_family = AF_UNSPEC;
-
-  error = getaddrinfo(addrstr, NULL, &hints, &res);
-
-  if (error != 0) {
-    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
-    return error;
-  }
-
-  for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
-    switch (ainfo->ai_family) {
-    case AF_INET6:
-    case AF_INET:
-      len = ainfo->ai_addrlen;
-      memcpy(dst, ainfo->ai_addr, len);
-      goto finish;
-    default:
-      ;
-    }
-  }
-
- finish:
-  freeaddrinfo(res);
-  return len;
-}
-
-static inline coap_opt_t *
-get_block(coap_pdu_t *pdu, coap_opt_iterator_t *opt_iter) {
-  coap_opt_filter_t f;
-
-  assert(pdu);
-
-  memset(f, 0, sizeof(coap_opt_filter_t));
-  coap_option_setb(f, COAP_OPTION_BLOCK1);
-  coap_option_setb(f, COAP_OPTION_BLOCK2);
-
-  coap_option_iterator_init(pdu, opt_iter, f);
-  return coap_option_next(opt_iter);
-}
-
-#define HANDLE_BLOCK1(Pdu)                                             \
-  ((method == COAP_REQUEST_PUT || method == COAP_REQUEST_POST) &&      \
-   ((flags & FLAGS_BLOCK) == 0) &&                                     \
-   ((Pdu)->hdr->code == COAP_RESPONSE_CODE(201) ||                     \
-    (Pdu)->hdr->code == COAP_RESPONSE_CODE(204)))
-
-inline int
-check_token(coap_pdu_t *received) {
-  return received->hdr->token_length == the_token.length &&
-    memcmp(received->hdr->token, the_token.s, the_token.length) == 0;
-}
-
-void
-message_handler(struct coap_context_t  *ctx,
-               const coap_address_t *remote,
-               coap_pdu_t *sent,
-               coap_pdu_t *received,
-               const coap_tid_t id) {
-
-  coap_pdu_t *pdu = NULL;
-  coap_opt_t *block_opt;
-  coap_opt_iterator_t opt_iter;
-  unsigned char buf[4];
-  coap_list_t *option;
-  size_t len;
-  unsigned char *databuf;
-  coap_tid_t tid;
-  (void)id;
-
-#ifndef NDEBUG
-  if (LOG_DEBUG <= coap_get_log_level()) {
-    debug("** process incoming %d.%02d response:\n",
-         (received->hdr->code >> 5), received->hdr->code & 0x1F);
-    coap_show_pdu(received);
-  }
-#endif
-
-  /* check if this is a response to our original request */
-  if (!check_token(received)) {
-    /* drop if this was just some message, or send RST in case of notification */
-    if (!sent && (received->hdr->type == COAP_MESSAGE_CON ||
-                 received->hdr->type == COAP_MESSAGE_NON))
-      coap_send_rst(ctx, remote, received);
-    return;
-  }
-
-  switch (received->hdr->type) {
-  case COAP_MESSAGE_CON:
-    /* acknowledge received response if confirmable (TODO: check Token) */
-    coap_send_ack(ctx, remote, received);
-    break;
-  case COAP_MESSAGE_RST:
-    info("got RST\n");
-    return;
-  default:
-    ;
-  }
-
-  /* output the received data, if any */
-  if (received->hdr->code == COAP_RESPONSE_CODE(205)) {
-
-    /* set obs timer if we have successfully subscribed a resource */
-    if (sent && coap_check_option(received, COAP_OPTION_SUBSCRIPTION, &opt_iter)) {
-      debug("observation relationship established, set timeout to %d\n", obs_seconds);
-      set_timeout(&obs_wait, obs_seconds);
-    }
-
-    /* Got some data, check if block option is set. Behavior is undefined if
-     * both, Block1 and Block2 are present. */
-    block_opt = get_block(received, &opt_iter);
-    if (!block_opt) {
-      /* There is no block option set, just read the data and we are done. */
-      if (coap_get_data(received, &len, &databuf))
-       append_to_output(databuf, len);
-    } else {
-      unsigned short blktype = opt_iter.type;
-
-      /* TODO: check if we are looking at the correct block number */
-      if (coap_get_data(received, &len, &databuf))
-       append_to_output(databuf, len);
-
-      if (COAP_OPT_BLOCK_MORE(block_opt)) {
-       /* more bit is set */
-       debug("found the M bit, block size is %u, block nr. %u\n",
-             COAP_OPT_BLOCK_SZX(block_opt), coap_opt_block_num(block_opt));
-
-       /* create pdu with request for next block */
-       pdu = coap_new_request(ctx, method, NULL); /* first, create bare PDU w/o any option  */
-       if ( pdu ) {
-         /* add URI components from optlist */
-         for (option = optlist; option; option = option->next ) {
-           switch (COAP_OPTION_KEY(*(coap_option *)option->data)) {
-           case COAP_OPTION_URI_HOST :
-           case COAP_OPTION_URI_PORT :
-           case COAP_OPTION_URI_PATH :
-           case COAP_OPTION_URI_QUERY :
-             coap_add_option ( pdu, COAP_OPTION_KEY(*(coap_option *)option->data),
-                               COAP_OPTION_LENGTH(*(coap_option *)option->data),
-                               COAP_OPTION_DATA(*(coap_option *)option->data) );
-             break;
-           default:
-             ;                 /* skip other options */
-           }
-         }
-
-         /* finally add updated block option from response, clear M bit */
-         /* blocknr = (blocknr & 0xfffffff7) + 0x10; */
-         debug("query block %d\n", (coap_opt_block_num(block_opt) + 1));
-         coap_add_option(pdu, blktype, coap_encode_var_bytes(buf,
-             ((coap_opt_block_num(block_opt) + 1) << 4) |
-              COAP_OPT_BLOCK_SZX(block_opt)), buf);
-
-         if (received->hdr->type == COAP_MESSAGE_CON)
-           tid = coap_send_confirmed(ctx, remote, pdu);
-         else
-           tid = coap_send(ctx, remote, pdu);
-
-         if (tid == COAP_INVALID_TID) {
-           debug("message_handler: error sending new request");
-            coap_delete_pdu(pdu);
-         } else {
-           set_timeout(&max_wait, wait_seconds);
-            if (received->hdr->type != COAP_MESSAGE_CON)
-              coap_delete_pdu(pdu);
-          }
-
-         return;
-       }
-      }
-    }
-  } else {                     /* no 2.05 */
-
-    /* check if an error was signaled and output payload if so */
-    if (COAP_RESPONSE_CLASS(received->hdr->code) >= 4) {
-      fprintf(stderr, "%d.%02d",
-             (received->hdr->code >> 5), received->hdr->code & 0x1F);
-      if (coap_get_data(received, &len, &databuf)) {
-      fprintf(stderr, " ");
-       while(len--)
-         fprintf(stderr, "%c", *databuf++);
-      }
-      fprintf(stderr, "\n");
-    }
-
-  }
-
-  /* finally send new request, if needed */
-  if (pdu && coap_send(ctx, remote, pdu) == COAP_INVALID_TID) {
-    debug("message_handler: error sending response");
-  }
-  coap_delete_pdu(pdu);
-
-  /* our job is done, we can exit at any time */
-  ready = coap_check_option(received, COAP_OPTION_SUBSCRIPTION, &opt_iter) == NULL;
-}
-
-void
-usage( const char *program, const char *version) {
-  const char *p;
-
-  p = strrchr( program, '/' );
-  if ( p )
-    program = ++p;
-
-  fprintf( stderr, "%s v%s -- a small CoAP implementation\n"
-          "(c) 2010-2013 Olaf Bergmann <bergmann@tzi.org>\n\n"
-          "usage: %s [-A type...] [-t type] [-b [num,]size] [-B seconds] [-e text]\n"
-          "\t\t[-g group] [-m method] [-N] [-o file] [-P addr[:port]] [-p port]\n"
-          "\t\t[-s duration] [-O num,text] [-T string] [-v num] URI\n\n"
-          "\tURI can be an absolute or relative coap URI,\n"
-          "\t-A type...\taccepted media types as comma-separated list of\n"
-          "\t\t\tsymbolic or numeric values\n"
-          "\t-t type\t\tcontent type for given resource for PUT/POST\n"
-          "\t-b [num,]size\tblock size to be used in GET/PUT/POST requests\n"
-          "\t       \t\t(value must be a multiple of 16 not larger than 1024)\n"
-          "\t       \t\tIf num is present, the request chain will start at\n"
-          "\t       \t\tblock num\n"
-          "\t-B seconds\tbreak operation after waiting given seconds\n"
-          "\t\t\t(default is %d)\n"
-          "\t-e text\t\tinclude text as payload (use percent-encoding for\n"
-          "\t\t\tnon-ASCII characters)\n"
-          "\t-f file\t\tfile to send with PUT/POST (use '-' for STDIN)\n"
-          "\t-g group\tjoin the given multicast group\n"
-          "\t-m method\trequest method (get|put|post|delete), default is 'get'\n"
-          "\t-N\t\tsend NON-confirmable message\n"
-          "\t-o file\t\toutput received data to this file (use '-' for STDOUT)\n"
-          "\t-p port\t\tlisten on specified port\n"
-          "\t-s duration\tsubscribe for given duration [s]\n"
-          "\t-v num\t\tverbosity level (default: 3)\n"
-          "\t-O num,text\tadd option num with contents text to request\n"
-          "\t-P addr[:port]\tuse proxy (automatically adds Proxy-Uri option to\n"
-          "\t\t\trequest)\n"
-          "\t-T token\tinclude specified token\n"
-          "\n"
-          "examples:\n"
-          "\tcoap-client -m get coap://[::1]/\n"
-          "\tcoap-client -m get coap://[::1]/.well-known/core\n"
-          "\tcoap-client -m get -T cafe coap://[::1]/time\n"
-          "\techo 1000 | coap-client -m put -T cafe coap://[::1]/time -f -\n"
-          ,program, version, program, wait_seconds);
-}
-
-int
-join( coap_context_t *ctx, char *group_name ){
-  struct ipv6_mreq mreq;
-  struct addrinfo   *reslocal = NULL, *resmulti = NULL, hints, *ainfo;
-  int result = -1;
-
-  /* we have to resolve the link-local interface to get the interface id */
-  memset(&hints, 0, sizeof(hints));
-  hints.ai_family = AF_INET6;
-  hints.ai_socktype = SOCK_DGRAM;
-
-  result = getaddrinfo("::", NULL, &hints, &reslocal);
-  if ( result < 0 ) {
-    fprintf(stderr, "join: cannot resolve link-local interface: %s\n",
-           gai_strerror(result));
-    goto finish;
-  }
-
-  /* get the first suitable interface identifier */
-  for (ainfo = reslocal; ainfo != NULL; ainfo = ainfo->ai_next) {
-    if ( ainfo->ai_family == AF_INET6 ) {
-      mreq.ipv6mr_interface =
-             ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_scope_id;
-      break;
-    }
-  }
-
-  memset(&hints, 0, sizeof(hints));
-  hints.ai_family = AF_INET6;
-  hints.ai_socktype = SOCK_DGRAM;
-
-  /* resolve the multicast group address */
-  result = getaddrinfo(group_name, NULL, &hints, &resmulti);
-
-  if ( result < 0 ) {
-    fprintf(stderr, "join: cannot resolve multicast address: %s\n",
-           gai_strerror(result));
-    goto finish;
-  }
-
-  for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
-    if ( ainfo->ai_family == AF_INET6 ) {
-      mreq.ipv6mr_multiaddr =
-       ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
-      break;
-    }
-  }
-
-  result = setsockopt( ctx->sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
-                      (char *)&mreq, sizeof(mreq) );
-  if ( result < 0 )
-    perror("join: setsockopt");
-
- finish:
-  freeaddrinfo(resmulti);
-  freeaddrinfo(reslocal);
-
-  return result;
-}
-
-int
-order_opts(void *a, void *b) {
-  if (!a || !b)
-    return a < b ? -1 : 1;
-
-  if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option *)b))
-    return -1;
-
-  return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option *)b);
-}
-
-
-coap_list_t *
-new_option_node(unsigned short key, unsigned int length, unsigned char *data) {
-  coap_option *option;
-  coap_list_t *node;
-
-  option = coap_malloc(sizeof(coap_option) + length);
-  if ( !option )
-    goto error;
-
-  COAP_OPTION_KEY(*option) = key;
-  COAP_OPTION_LENGTH(*option) = length;
-  memcpy(COAP_OPTION_DATA(*option), data, length);
-
-  /* we can pass NULL here as delete function since option is released automatically  */
-  node = coap_new_listnode(option, NULL);
-
-  if ( node )
-    return node;
-
- error:
-  perror("new_option_node: malloc");
-  coap_free( option );
-  return NULL;
-}
-
-typedef struct {
-  unsigned char code;
-  char *media_type;
-} content_type_t;
-
-void
-cmdline_content_type(char *arg, unsigned short key) {
-  static content_type_t content_types[] = {
-    {  0, "plain" },
-    {  0, "text/plain" },
-    { 40, "link" },
-    { 40, "link-format" },
-    { 40, "application/link-format" },
-    { 41, "xml" },
-    { 42, "binary" },
-    { 42, "octet-stream" },
-    { 42, "application/octet-stream" },
-    { 47, "exi" },
-    { 47, "application/exi" },
-    { 50, "json" },
-    { 50, "application/json" },
-    { 255, NULL }
-  };
-  coap_list_t *node;
-  unsigned char i, value[10];
-  int valcnt = 0;
-  unsigned char buf[2];
-  char *p, *q = arg;
-
-  while (q && *q) {
-    p = strchr(q, ',');
-
-    if (isdigit(*q)) {
-      if (p)
-       *p = '\0';
-      value[valcnt++] = atoi(q);
-    } else {
-      for (i=0; content_types[i].media_type &&
-            strncmp(q,content_types[i].media_type, p ? p-q : strlen(q)) != 0 ;
-          ++i)
-       ;
-
-      if (content_types[i].media_type) {
-       value[valcnt] = content_types[i].code;
-       valcnt++;
-      } else {
-       warn("W: unknown content-type '%s'\n",arg);
-      }
-    }
-
-    if (!p || key == COAP_OPTION_CONTENT_TYPE)
-      break;
-
-    q = p+1;
-  }
-
-  for (i = 0; i < valcnt; ++i) {
-    node = new_option_node(key, coap_encode_var_bytes(buf, value[i]), buf);
-    if (node)
-      coap_insert( &optlist, node, order_opts );
-  }
-}
-
-void
-cmdline_uri(char *arg) {
-  unsigned char portbuf[2];
-#define BUFSIZE 40
-  unsigned char _buf[BUFSIZE];
-  unsigned char *buf = _buf;
-  size_t buflen;
-  int res;
-
-  if (proxy.length) {          /* create Proxy-Uri from argument */
-    size_t len = strlen(arg);
-    while (len > 270) {
-      coap_insert(&optlist,
-                 new_option_node(COAP_OPTION_PROXY_URI,
-                                 270, (unsigned char *)arg),
-                 order_opts);
-      len -= 270;
-      arg += 270;
-    }
-
-    coap_insert(&optlist,
-               new_option_node(COAP_OPTION_PROXY_URI,
-                               len, (unsigned char *)arg),
-               order_opts);
-  } else {                     /* split arg into Uri-* options */
-    coap_split_uri((unsigned char *)arg, strlen(arg), &uri );
-
-    if (uri.port != COAP_DEFAULT_PORT) {
-      coap_insert( &optlist,
-                  new_option_node(COAP_OPTION_URI_PORT,
-                                  coap_encode_var_bytes(portbuf, uri.port),
-                                portbuf),
-                  order_opts);
-    }
-
-    if (uri.path.length) {
-      buflen = BUFSIZE;
-      res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
-
-      while (res--) {
-       coap_insert(&optlist, new_option_node(COAP_OPTION_URI_PATH,
-                                             COAP_OPT_LENGTH(buf),
-                                             COAP_OPT_VALUE(buf)),
-                   order_opts);
-
-       buf += COAP_OPT_SIZE(buf);
-      }
-    }
-
-    if (uri.query.length) {
-      buflen = BUFSIZE;
-      buf = _buf;
-      res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);
-
-      while (res--) {
-       coap_insert(&optlist, new_option_node(COAP_OPTION_URI_QUERY,
-                                             COAP_OPT_LENGTH(buf),
-                                             COAP_OPT_VALUE(buf)),
-                   order_opts);
-
-       buf += COAP_OPT_SIZE(buf);
-      }
-    }
-  }
-}
-
-int
-cmdline_blocksize(char *arg) {
-  unsigned short size;
-
- again:
-  size = 0;
-  while(*arg && *arg != ',')
-    size = size * 10 + (*arg++ - '0');
-
-  if (*arg == ',') {
-    arg++;
-    block.num = size;
-    goto again;
-  }
-
-  if (size)
-    block.szx = (coap_fls(size >> 4) - 1) & 0x07;
-
-  flags |= FLAGS_BLOCK;
-  return 1;
-}
-
-/* Called after processing the options from the commandline to set
- * Block1 or Block2 depending on method. */
-void
-set_blocksize() {
-  static unsigned char buf[4]; /* hack: temporarily take encoded bytes */
-  unsigned short opt;
-
-  if (method != COAP_REQUEST_DELETE) {
-    opt = method == COAP_REQUEST_GET ? COAP_OPTION_BLOCK2 : COAP_OPTION_BLOCK1;
-
-    coap_insert(&optlist, new_option_node(opt,
-                coap_encode_var_bytes(buf, (block.num << 4 | block.szx)), buf),
-               order_opts);
-  }
-}
-
-void
-cmdline_subscribe(char *arg) {
-  (void)arg;
-  obs_seconds = atoi(optarg);
-  coap_insert(&optlist, new_option_node(COAP_OPTION_SUBSCRIPTION, 0, NULL),
-             order_opts);
-}
-
-int
-cmdline_proxy(char *arg) {
-  char *proxy_port_str = strrchr((const char *)arg, ':'); /* explicit port ? */
-  if (proxy_port_str) {
-    char *ipv6_delimiter = strrchr((const char *)arg, ']');
-    if (!ipv6_delimiter) {
-      if (proxy_port_str == strchr((const char *)arg, ':')) {
-        /* host:port format - host not in ipv6 hexadecimal string format */
-        *proxy_port_str++ = '\0'; /* split */
-        proxy_port = atoi(proxy_port_str);
-      }
-    } else {
-      arg = strchr((const char *)arg, '[');
-      if (!arg) return 0;
-      arg++;
-      *ipv6_delimiter = '\0'; /* split */
-      if (ipv6_delimiter + 1 == proxy_port_str++) {
-        /* [ipv6 address]:port */
-        proxy_port = atoi(proxy_port_str);
-      }
-    }
-  }
-
-  proxy.length = strlen(arg);
-  if ( (proxy.s = coap_malloc(proxy.length + 1)) == NULL) {
-    proxy.length = 0;
-    return 0;
-  }
-
-  memcpy(proxy.s, arg, proxy.length+1);
-  return 1;
-}
-
-inline void
-cmdline_token(char *arg) {
-  strncpy((char *)the_token.s, arg, min(sizeof(_token_data), strlen(arg)));
-  the_token.length = strlen(arg);
-}
-
-void
-cmdline_option(char *arg) {
-  unsigned int num = 0;
-
-  while (*arg && *arg != ',') {
-    num = num * 10 + (*arg - '0');
-    ++arg;
-  }
-  if (*arg == ',')
-    ++arg;
-
-  coap_insert( &optlist, new_option_node(num,
-                                        strlen(arg),
-                                        (unsigned char *)arg), order_opts);
-}
-
-extern int  check_segment(const unsigned char *s, size_t length);
-extern void decode_segment(const unsigned char *seg, size_t length, unsigned char *buf);
-
-int
-cmdline_input(char *text, str *buf) {
-  int len;
-  len = check_segment((unsigned char *)text, strlen(text));
-
-  if (len < 0)
-    return 0;
-
-  buf->s = (unsigned char *)coap_malloc(len);
-  if (!buf->s)
-    return 0;
-
-  buf->length = len;
-  decode_segment((unsigned char *)text, strlen(text), buf->s);
-  return 1;
-}
-
-int
-cmdline_input_from_file(char *filename, str *buf) {
-  FILE *inputfile = NULL;
-  size_t len;
-  int result = 1;
-  struct stat statbuf;
-
-  if (!filename || !buf)
-    return 0;
-
-  if (filename[0] == '-' && !filename[1]) { /* read from stdin */
-    buf->length = 20000;
-    buf->s = (unsigned char *)coap_malloc(buf->length);
-    if (!buf->s)
-      return 0;
-
-    inputfile = stdin;
-  } else {
-    /* read from specified input file */
-    if (stat(filename, &statbuf) < 0) {
-      perror("cmdline_input_from_file: stat");
-      return 0;
-    }
-
-    buf->length = statbuf.st_size;
-    buf->s = (unsigned char *)coap_malloc(buf->length);
-    if (!buf->s)
-      return 0;
-
-    inputfile = fopen(filename, "r");
-    if ( !inputfile ) {
-      perror("cmdline_input_from_file: fopen");
-      coap_free(buf->s);
-      return 0;
-    }
-  }
-
-  len = fread(buf->s, 1, buf->length, inputfile);
-
-  if (len < buf->length) {
-    if (ferror(inputfile) != 0) {
-      perror("cmdline_input_from_file: fread");
-      coap_free(buf->s);
-      buf->length = 0;
-      buf->s = NULL;
-      result = 0;
-    } else {
-      buf->length = len;
-    }
-  }
-
-  if (inputfile != stdin)
-    fclose(inputfile);
-
-  return result;
-}
-
-method_t
-cmdline_method(char *arg) {
-  static char *methods[] =
-    { 0, "get", "post", "put", "delete", 0};
-  unsigned char i;
-
-  for (i=1; methods[i] && strcasecmp(arg,methods[i]) != 0 ; ++i)
-    ;
-
-  return i;         /* note that we do not prevent illegal methods */
-}
-
-coap_context_t *
-get_context(const char *node, const char *port) {
-  coap_context_t *ctx = NULL;
-  int s;
-  struct addrinfo hints;
-  struct addrinfo *result, *rp;
-
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
-  hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
-#ifndef __ANDROID__
-  hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL;
-#endif //__ANDROID__
-
-
-  OC_LOG_V(DEBUG, MOD_NAME, "Line %d, node %s, port %d", __LINE__, node, port);
-  s = getaddrinfo(node, port, &hints, &result);
-  if ( s != 0 ) {
-    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
-    return NULL;
-  }
-
-  /* iterate through results until success */
-  for (rp = result; rp != NULL; rp = rp->ai_next) {
-    coap_address_t addr;
-
-    if (rp->ai_addrlen <= sizeof(addr.addr)) {
-      coap_address_init(&addr);
-      addr.size = rp->ai_addrlen;
-      memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen);
-
-      ctx = coap_new_context(&addr);
-      if (ctx) {
-       /* TODO: output address:port for successful binding */
-       goto finish;
-      }
-    }
-  }
-
-  fprintf(stderr, "no context available for interface '%s'\n", node);
-
- finish:
-  freeaddrinfo(result);
-  return ctx;
-}
-
-int
-main(int argc, char **argv) {
-  coap_context_t  *ctx = NULL;
-  coap_address_t dst;
-  static char addr[INET6_ADDRSTRLEN];
-  void *addrptr = NULL;
-  fd_set readfds;
-  struct timeval tv;
-  int result;
-  coap_tick_t now;
-  coap_queue_t *nextpdu;
-  coap_pdu_t  *pdu;
-  static str server;
-  unsigned short port = COAP_DEFAULT_PORT;
-  char port_str[NI_MAXSERV] = "0";
-  int opt, res;
-  char *group = NULL;
-  coap_log_t log_level = LOG_WARNING;
-  coap_tid_t tid = COAP_INVALID_TID;
-
-  while ((opt = getopt(argc, argv, "Nb:e:f:g:m:p:s:t:o:v:A:B:O:P:T:")) != -1) {
-    switch (opt) {
-    case 'b' :
-      cmdline_blocksize(optarg);
-      break;
-    case 'B' :
-      wait_seconds = atoi(optarg);
-      break;
-    case 'e' :
-      if (!cmdline_input(optarg,&payload))
-       payload.length = 0;
-      break;
-    case 'f' :
-      if (!cmdline_input_from_file(optarg,&payload))
-       payload.length = 0;
-      break;
-    case 'g' :
-      group = optarg;
-      break;
-    case 'p' :
-      strncpy(port_str, optarg, NI_MAXSERV-1);
-      port_str[NI_MAXSERV - 1] = '\0';
-      break;
-    case 'm' :
-      method = cmdline_method(optarg);
-      break;
-    case 'N' :
-      msgtype = COAP_MESSAGE_NON;
-      break;
-    case 's' :
-      cmdline_subscribe(optarg);
-      break;
-    case 'o' :
-      output_file.length = strlen(optarg);
-      output_file.s = (unsigned char *)coap_malloc(output_file.length + 1);
-
-      if (!output_file.s) {
-       fprintf(stderr, "cannot set output file: insufficient memory\n");
-       exit(-1);
-      } else {
-       /* copy filename including trailing zero */
-       memcpy(output_file.s, optarg, output_file.length + 1);
-      }
-      break;
-    case 'A' :
-      cmdline_content_type(optarg,COAP_OPTION_ACCEPT);
-      break;
-    case 't' :
-      cmdline_content_type(optarg,COAP_OPTION_CONTENT_TYPE);
-      break;
-    case 'O' :
-      cmdline_option(optarg);
-      break;
-    case 'P' :
-      if (!cmdline_proxy(optarg)) {
-        fprintf(stderr, "error specifying proxy address\n");
-       exit(-1);
-      }
-      break;
-    case 'T' :
-      cmdline_token(optarg);
-      break;
-    case 'v' :
-      log_level = strtol(optarg, NULL, 10);
-      break;
-    default:
-      usage( argv[0], PACKAGE_VERSION );
-      exit( 1 );
-    }
-  }
-
-  coap_set_log_level(log_level);
-
-  if ( optind < argc )
-    cmdline_uri( argv[optind] );
-  else {
-    usage( argv[0], PACKAGE_VERSION );
-    exit( 1 );
-  }
-
-  if (proxy.length) {
-    server = proxy;
-    port = proxy_port;
-  } else {
-    server = uri.host;
-    port = uri.port;
-  }
-
-  /* resolve destination address where server should be sent */
-  res = resolve_address(&server, &dst.addr.sa);
-
-  if (res < 0) {
-    fprintf(stderr, "failed to resolve address\n");
-    exit(-1);
-  }
-
-  dst.size = res;
-  dst.addr.sin.sin_port = htons(port);
-
-  /* add Uri-Host if server address differs from uri.host */
-
-  switch (dst.addr.sa.sa_family) {
-  case AF_INET:
-    addrptr = &dst.addr.sin.sin_addr;
-
-    /* create context for IPv4 */
-    ctx = get_context("0.0.0.0", port_str);
-    break;
-  case AF_INET6:
-    addrptr = &dst.addr.sin6.sin6_addr;
-
-    /* create context for IPv6 */
-    ctx = get_context("::", port_str);
-    break;
-  default:
-    ;
-  }
-
-  if (!ctx) {
-    coap_log(LOG_EMERG, "cannot create context\n");
-    return -1;
-  }
-
-  coap_register_option(ctx, COAP_OPTION_BLOCK2);
-  coap_register_response_handler(ctx, message_handler);
-
-  /* join multicast group if requested at command line */
-  if (group)
-    join(ctx, group);
-
-  /* construct CoAP message */
-
-  if (!proxy.length && addrptr
-      && (inet_ntop(dst.addr.sa.sa_family, addrptr, addr, sizeof(addr)) != 0)
-      && (strlen(addr) != uri.host.length
-         || memcmp(addr, uri.host.s, uri.host.length) != 0)) {
-      /* add Uri-Host */
-
-    coap_insert(&optlist, new_option_node(COAP_OPTION_URI_HOST,
-                                         uri.host.length, uri.host.s),
-               order_opts);
-  }
-
-  /* set block option if requested at commandline */
-  if (flags & FLAGS_BLOCK)
-    set_blocksize();
-
-  if (! (pdu = coap_new_request(ctx, method, optlist)))
-    return -1;
-
-#ifndef NDEBUG
-  if (LOG_DEBUG <= coap_get_log_level()) {
-    debug("sending CoAP request:\n");
-    coap_show_pdu(pdu);
-  }
-#endif
-
-  if (pdu->hdr->type == COAP_MESSAGE_CON)
-    tid = coap_send_confirmed(ctx, &dst, pdu);
-  else
-    tid = coap_send(ctx, &dst, pdu);
-
-  if (pdu->hdr->type != COAP_MESSAGE_CON || tid == COAP_INVALID_TID)
-    coap_delete_pdu(pdu);
-
-  set_timeout(&max_wait, wait_seconds);
-  debug("timeout is set to %d seconds\n", wait_seconds);
-
-  while ( !(ready && coap_can_exit(ctx)) ) {
-    FD_ZERO(&readfds);
-    FD_SET( ctx->sockfd, &readfds );
-
-    nextpdu = coap_peek_next( ctx );
-
-    coap_ticks(&now);
-    while (nextpdu && nextpdu->t <= now - ctx->sendqueue_basetime) {
-      coap_retransmit( ctx, coap_pop_next( ctx ));
-      nextpdu = coap_peek_next( ctx );
-    }
-
-    if (nextpdu && nextpdu->t < min(obs_wait ? obs_wait : max_wait, max_wait) - now) {
-      /* set timeout if there is a pdu to send */
-      tv.tv_usec = ((nextpdu->t) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND;
-      tv.tv_sec = (nextpdu->t) / COAP_TICKS_PER_SECOND;
-    } else {
-      /* check if obs_wait fires before max_wait */
-      if (obs_wait && obs_wait < max_wait) {
-       tv.tv_usec = ((obs_wait - now) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND;
-       tv.tv_sec = (obs_wait - now) / COAP_TICKS_PER_SECOND;
-      } else {
-       tv.tv_usec = ((max_wait - now) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND;
-       tv.tv_sec = (max_wait - now) / COAP_TICKS_PER_SECOND;
-      }
-    }
-
-    result = select(ctx->sockfd + 1, &readfds, 0, 0, &tv);
-
-    if ( result < 0 ) {                /* error */
-      perror("select");
-    } else if ( result > 0 ) { /* read from socket */
-      if ( FD_ISSET( ctx->sockfd, &readfds ) ) {
-       coap_read( ctx, ctx->sockfd );  /* read received data */
-       coap_dispatch( ctx );   /* and dispatch PDUs from receivequeue */
-      }
-    } else { /* timeout */
-      coap_ticks(&now);
-      if (max_wait <= now) {
-       info("timeout\n");
-       break;
-      }
-      if (obs_wait && obs_wait <= now) {
-       debug("clear observation relationship\n");
-       clear_obs(ctx, &dst); /* FIXME: handle error case COAP_TID_INVALID */
-
-       /* make sure that the obs timer does not fire again */
-       obs_wait = 0;
-       obs_seconds = 0;
-      }
-    }
-  }
-
-  close_output();
-
-  coap_free_context( ctx );
-
-  return 0;
-}
diff --git a/resource/csdk/libcoap-4.1.1/examples/makefile b/resource/csdk/libcoap-4.1.1/examples/makefile
deleted file mode 100644 (file)
index 0d19887..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-VERSION:=4.1.1
-
-#other options are android, arduino
-PLATFORM=linux
-
-ROOT_DIR = ../..
-OCSOCK_DIR = $(ROOT_DIR)/ocsocket
-LOGGER_DIR = $(ROOT_DIR)/logger
-RANDOM_DIR = $(ROOT_DIR)/ocrandom
-OBJ_DIR = ./
-INC_DIRS = -I.. -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include -I$(RANDOM_DIR)/include
-
-ifeq ($(PLATFORM),android)
-    CXX=arm-linux-androideabi-g++
-    CC=arm-linux-androideabi-gcc
-    AR=arm-linux-androideabi-ar
-    RANLIB=arm-linux-androideabi-ranlib
-    CFLAGS_ANDROID =  -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16
-    LDFLAGS_ANDROID = -march=armv7-a -Wl,--fix-cortex-a8 -llog
-else ifeq ($(PLATFORM),linux)
-    CXX=g++
-    CC=gcc
-    AR=ar
-    RANLIB=ranlib
-else
-   $(error Wrong value for PLATFORM !!)
-endif
-
-DEP_LIBS = ../libcoap.a
-
-CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions \
-    -Wextra -Wno-variadic-macros -pedantic -std=gnu99 -DWITH_POSIX
-
-PROGRAMS = coap-server coap-client
-
-SOURCES:= client.c server.c
-
-OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
-
-all: $(PROGRAMS)
-
-%.o: %.c
-       $(CC) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) $< -o $@
-
-coap-client: client.o $(DEP_LIBS)
-       $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $^ -o $@
-
-coap-server: server.o $(DEP_LIBS)
-       $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $^ -o $@
-
-install: all
-       @echo "Installing for PLATFORM $(PLATFORM)"
-ifeq ($(PLATFORM),android)
-       adb push coap-client /data/local/tmp/
-       adb push coap-server /data/local/tmp/
-endif
-
-.PHONY: clean
-
-clean:
-       rm -f *.o $(PROGRAMS)
-
diff --git a/resource/csdk/libcoap-4.1.1/examples/rd.c b/resource/csdk/libcoap-4.1.1/examples/rd.c
deleted file mode 100644 (file)
index 271a78c..0000000
+++ /dev/null
@@ -1,705 +0,0 @@
-/* coap -- simple implementation of the Constrained Application Protocol (CoAP)
- *         as defined in draft-ietf-core-coap
- *
- * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-
-/**
- * @file rd.c
- * @brief CoRE resource directory
- *
- * @see http://tools.ietf.org/id/draft-shelby-core-resource-directory
- */
-
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-#include <sys/stat.h>
-#include <dirent.h>
-#include <errno.h>
-#include <signal.h>
-
-#include "config.h"
-#include "utlist.h"
-#include "resource.h"
-#include "coap.h"
-
-#define COAP_RESOURCE_CHECK_TIME 2
-
-#define RD_ROOT_STR   ((unsigned char *)"rd")
-#define RD_ROOT_SIZE  2
-
-#ifndef min
-#define min(a,b) ((a) < (b) ? (a) : (b))
-#endif
-
-typedef struct rd_t {
-  UT_hash_handle hh;   /**< hash handle (for internal use only) */
-  coap_key_t key;      /**< the actual key bytes for this resource */
-
-  size_t etag_len;             /**< actual length of @c etag */
-  unsigned char etag[8];       /**< ETag for current description */
-
-  str data;                    /**< points to the resource description  */
-} rd_t;
-
-rd_t *resources = NULL;
-
-inline rd_t *
-rd_new() {
-  rd_t *rd;
-  rd = (rd_t *)coap_malloc(sizeof(rd_t));
-  if (rd)
-    memset(rd, 0, sizeof(rd_t));
-
-  return rd;
-}      
-
-inline void
-rd_delete(rd_t *rd) {
-  if (rd) {
-    coap_free(rd->data.s);
-    coap_free(rd);
-  }
-}
-
-/* temporary storage for dynamic resource representations */
-static int quit = 0;
-
-/* SIGINT handler: set quit to 1 for graceful termination */
-void
-handle_sigint(int signum) {
-  quit = 1;
-}
-
-void 
-hnd_get_resource(coap_context_t  *ctx, struct coap_resource_t *resource, 
-             coap_address_t *peer, coap_pdu_t *request, str *token,
-             coap_pdu_t *response) {
-  rd_t *rd = NULL;
-  unsigned char buf[3];
-  
-  HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd);
-
-  response->hdr->code = COAP_RESPONSE_CODE(205);
-
-  coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
-         coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
-
-  if (rd && rd->etag_len)
-    coap_add_option(response, COAP_OPTION_ETAG, rd->etag_len, rd->etag);
-
-  if (rd && rd->data.s)
-    coap_add_data(response, rd->data.length, rd->data.s);
-}
-
-void 
-hnd_put_resource(coap_context_t  *ctx, struct coap_resource_t *resource, 
-                coap_address_t *peer, coap_pdu_t *request, str *token,
-                coap_pdu_t *response) {
-#if 1
-  response->hdr->code = COAP_RESPONSE_CODE(501);
-#else /* FIXME */
-  coap_opt_iterator_t opt_iter;
-  coap_opt_t *token, *etag;
-  coap_pdu_t *response;
-  size_t size = sizeof(coap_hdr_t);
-  int type = (request->hdr->type == COAP_MESSAGE_CON) 
-    ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
-  rd_t *rd = NULL;
-  unsigned char code;          /* result code */
-  unsigned char *data;
-  str tmp;
-
-  HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd);
-  if (rd) {
-    /* found resource object, now check Etag */
-    etag = coap_check_option(request, COAP_OPTION_ETAG, &opt_iter);
-    if (!etag || (COAP_OPT_LENGTH(etag) != rd->etag_len)
-       || memcmp(COAP_OPT_VALUE(etag), rd->etag, rd->etag_len) != 0) {
-      
-      if (coap_get_data(request, &tmp.length, &data)) {
-
-       tmp.s = (unsigned char *)coap_malloc(tmp.length);
-       if (!tmp.s) {
-         debug("hnd_put_rd: cannot allocate storage for new rd\n");
-         code = COAP_RESPONSE_CODE(503);
-         goto finish;
-       }
-
-       coap_free(rd->data.s);
-       rd->data.s = tmp.s;
-       rd->data.length = tmp.length;
-       memcpy(rd->data.s, data, rd->data.length);
-      }
-    }
-
-    if (etag) {
-      rd->etag_len = min(COAP_OPT_LENGTH(etag), sizeof(rd->etag));
-      memcpy(rd->etag, COAP_OPT_VALUE(etag), rd->etag_len);
-    }
-
-    code = COAP_RESPONSE_CODE(204);
-    /* FIXME: update lifetime */
-    
-    } else {
-    
-    code = COAP_RESPONSE_CODE(503);
-  }
-
-  finish:
-  /* FIXME: do not create a new response but use the old one instead */
-  response = coap_pdu_init(type, code, request->hdr->id, size);
-
-  if (!response) {
-    debug("cannot create response for message %d\n", request->hdr->id);
-    return;
-  }
-
-  if (request->hdr->token_length)
-    coap_add_token(response, request->hdr->token_length, request->hdr->token);
-
-  if (coap_send(ctx, peer, response) == COAP_INVALID_TID) {
-    debug("hnd_get_rd: cannot send response for message %d\n", 
-         request->hdr->id);
-  }
-  coap_delete_pdu(response);
-#endif
-}
-
-void 
-hnd_delete_resource(coap_context_t  *ctx, struct coap_resource_t *resource, 
-                   coap_address_t *peer, coap_pdu_t *request, str *token,
-                   coap_pdu_t *response) {
-  rd_t *rd = NULL;
-
-  HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd);
-  if (rd) {
-    HASH_DELETE(hh, resources, rd);
-    rd_delete(rd);
-  }
-  /* FIXME: link attributes for resource have been created dynamically
-   * using coap_malloc() and must be released. */
-  coap_delete_resource(ctx, resource->key);
-
-  response->hdr->code = COAP_RESPONSE_CODE(202);
-}
-
-void 
-hnd_get_rd(coap_context_t  *ctx, struct coap_resource_t *resource, 
-             coap_address_t *peer, coap_pdu_t *request, str *token,
-             coap_pdu_t *response) {
-  unsigned char buf[3];
-
-  response->hdr->code = COAP_RESPONSE_CODE(205);
-
-  coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
-         coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
-
-  coap_add_option(response, COAP_OPTION_MAXAGE,
-         coap_encode_var_bytes(buf, 0x2ffff), buf);
-}
-
-int
-parse_param(unsigned char *search, size_t search_len,
-           unsigned char *data, size_t data_len, str *result) {
-
-  if (result)
-    memset(result, 0, sizeof(str));
-
-  if (!search_len) 
-    return 0;
-  
-  while (search_len <= data_len) {
-
-    /* handle parameter if found */
-    if (memcmp(search, data, search_len) == 0) {
-      data += search_len;
-      data_len -= search_len;
-
-      /* key is only valid if we are at end of string or delimiter follows */
-      if (!data_len || *data == '=' || *data == '&') {
-       while (data_len && *data != '=') {
-         ++data; --data_len;
-       }
-      
-       if (data_len > 1 && result) {
-         /* value begins after '=' */
-         
-         result->s = ++data;
-         while (--data_len && *data != '&') {
-           ++data; result->length++;
-         }
-       }
-       
-       return 1;
-      }
-    }
-
-    /* otherwise proceed to next */
-    while (--data_len && *data++ != '&')
-      ;
-  }
-  
-  return 0;
-}
-
-void
-add_source_address(struct coap_resource_t *resource, coap_address_t *peer) {
-#define BUFSIZE 64
-  char *buf;
-  size_t n = 1;
-  
-  buf = (char *)coap_malloc(BUFSIZE);
-  if (!buf)    
-    return;
-
-  buf[0] = '"';
-
-  switch(peer->addr.sa.sa_family) {
-
-  case AF_INET:
-    /* FIXME */
-    break;
-
-  case AF_INET6:
-    n += snprintf(buf + n, BUFSIZE - n,
-                 "[%02x%02x:%02x%02x:%02x%02x:%02x%02x"        \
-                 ":%02x%02x:%02x%02x:%02x%02x:%02x%02x]",
-                 peer->addr.sin6.sin6_addr.s6_addr[0],
-                 peer->addr.sin6.sin6_addr.s6_addr[1],
-                 peer->addr.sin6.sin6_addr.s6_addr[2],
-                 peer->addr.sin6.sin6_addr.s6_addr[3],
-                 peer->addr.sin6.sin6_addr.s6_addr[4],
-                 peer->addr.sin6.sin6_addr.s6_addr[5],
-                 peer->addr.sin6.sin6_addr.s6_addr[6],
-                 peer->addr.sin6.sin6_addr.s6_addr[7],
-                 peer->addr.sin6.sin6_addr.s6_addr[8],
-                 peer->addr.sin6.sin6_addr.s6_addr[9],
-                 peer->addr.sin6.sin6_addr.s6_addr[10],
-                 peer->addr.sin6.sin6_addr.s6_addr[11],
-                 peer->addr.sin6.sin6_addr.s6_addr[12],
-                 peer->addr.sin6.sin6_addr.s6_addr[13],
-                 peer->addr.sin6.sin6_addr.s6_addr[14],
-                 peer->addr.sin6.sin6_addr.s6_addr[15]);    
-    
-    if (peer->addr.sin6.sin6_port != htons(COAP_DEFAULT_PORT)) {
-      n += 
-       snprintf(buf + n, BUFSIZE - n, ":%d", peer->addr.sin6.sin6_port);
-    }
-    break;
-  default:
-    ;
-  }
-
-  if (n < BUFSIZE)
-    buf[n++] = '"';
-
-  coap_add_attr(resource, (unsigned char *)"A", 1, (unsigned char *)buf, n, COAP_ATTR_FLAGS_RELEASE_VALUE);
-#undef BUFSIZE
-}
-
-
-rd_t *
-make_rd(coap_address_t *peer, coap_pdu_t *pdu) {    
-  rd_t *rd;
-  unsigned char *data;
-  coap_opt_iterator_t opt_iter;
-  coap_opt_t *etag;
-
-  rd = rd_new();
-  
-  if (!rd) {
-    debug("hnd_get_rd: cannot allocate storage for rd\n");
-    return NULL;
-  }
-
-  if (coap_get_data(pdu, &rd->data.length, &data)) {
-    rd->data.s = (unsigned char *)coap_malloc(rd->data.length);
-    if (!rd->data.s) {
-      debug("hnd_get_rd: cannot allocate storage for rd->data\n");
-      rd_delete(rd);
-      return NULL;
-    }
-    memcpy(rd->data.s, data, rd->data.length);
-  }
-
-  etag = coap_check_option(pdu, COAP_OPTION_ETAG, &opt_iter);
-  if (etag) {
-    rd->etag_len = min(COAP_OPT_LENGTH(etag), sizeof(rd->etag));
-    memcpy(rd->etag, COAP_OPT_VALUE(etag), rd->etag_len);
-  }
-
-  return rd;
-}
-
-void 
-hnd_post_rd(coap_context_t  *ctx, struct coap_resource_t *resource, 
-             coap_address_t *peer, coap_pdu_t *request, str *token,
-             coap_pdu_t *response) {
-  coap_resource_t *r;
-  coap_opt_iterator_t opt_iter;
-  coap_opt_t *query;
-#define LOCSIZE 68
-  unsigned char *loc;
-  size_t loc_size;
-  str h = {0, NULL}, ins = {0, NULL}, rt = {0, NULL}, lt = {0, NULL};          /* store query parameters */
-  unsigned char *buf;
-
-  loc = (unsigned char *)coap_malloc(LOCSIZE);
-  if (!loc) {
-    response->hdr->code = COAP_RESPONSE_CODE(500);
-    return;
-  }
-  memcpy(loc, RD_ROOT_STR, RD_ROOT_SIZE);
-
-  loc_size = RD_ROOT_SIZE;
-  loc[loc_size++] = '/';
-  
-  /* store query parameters for later use */
-  query = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
-  if (query) {
-    parse_param((unsigned char *)"h", 1, 
-               COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &h);
-    parse_param((unsigned char *)"ins", 3, 
-               COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &ins);
-    parse_param((unsigned char *)"lt", 2, 
-               COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &lt);
-    parse_param((unsigned char *)"rt", 2, 
-               COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &rt);
-  } 
-  
-  if (h.length) {              /* client has specified a node name */
-    memcpy(loc + loc_size, h.s, min(h.length, LOCSIZE - loc_size - 1));
-    loc_size += min(h.length, LOCSIZE - loc_size - 1);
-
-    if (ins.length && loc_size > 1) {
-      loc[loc_size++] = '-';
-      memcpy((char *)(loc + loc_size), 
-            ins.s, min(ins.length, LOCSIZE - loc_size - 1));
-      loc_size += min(ins.length, LOCSIZE - loc_size - 1);
-    }
-  } else {                     /* generate node identifier */
-    loc_size += 
-      snprintf((char *)(loc + loc_size), LOCSIZE - loc_size - 1, 
-              "%x", request->hdr->id);
-    
-    if (loc_size > 1) {
-      if (ins.length) {
-       loc[loc_size++] = '-';
-       memcpy((char *)(loc + loc_size), 
-              ins.s, min(ins.length, LOCSIZE - loc_size - 1));
-       loc_size += min(ins.length, LOCSIZE - loc_size - 1);
-      } else {
-       coap_tick_t now;
-       coap_ticks(&now);
-       
-       loc_size += 
-         snprintf((char *)(loc + loc_size), LOCSIZE - loc_size - 1, 
-                  "-%x", now);
-      }
-    }
-  }
-
-  /* TODO:
-   *   - use lt to check expiration
-   */
-  
-  r = coap_resource_init(loc, loc_size, COAP_RESOURCE_FLAGS_RELEASE_URI);
-  coap_register_handler(r, COAP_REQUEST_GET, hnd_get_resource);
-  coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_resource);
-  coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_resource);
-
-  if (ins.s) {
-    buf = (unsigned char *)coap_malloc(ins.length + 2);
-    if (buf) {
-      /* add missing quotes */
-      buf[0] = '"';
-      memcpy(buf + 1, ins.s, ins.length);
-      buf[ins.length + 1] = '"';
-      coap_add_attr(r, (unsigned char *)"ins", 3, buf, ins.length + 2, COAP_ATTR_FLAGS_RELEASE_VALUE);
-    }
-  }
-
-  if (rt.s) {
-    buf = (unsigned char *)coap_malloc(rt.length + 2);
-    if (buf) {
-      /* add missing quotes */
-      buf[0] = '"';
-      memcpy(buf + 1, rt.s, rt.length);
-      buf[rt.length + 1] = '"';
-      coap_add_attr(r, (unsigned char *)"rt", 2, buf, rt.length + 2, COAP_ATTR_FLAGS_RELEASE_VALUE);
-    }
-  }
-
-  add_source_address(r, peer);
-
-  {
-    rd_t *rd;
-    rd = make_rd(peer, request);
-    if (rd) {
-      coap_hash_path(loc, loc_size, rd->key);
-      HASH_ADD(hh, resources, key, sizeof(coap_key_t), rd);
-    } else {
-      /* FIXME: send error response and delete r */
-    }
-  }
-
-  coap_add_resource(ctx, r);
-
-
-  /* create response */
-
-  response->hdr->code = COAP_RESPONSE_CODE(201);
-
-  { /* split path into segments and add Location-Path options */
-    unsigned char _b[LOCSIZE];
-    unsigned char *b = _b;
-    size_t buflen = sizeof(_b);
-    int nseg;
-    
-    nseg = coap_split_path(loc, loc_size, b, &buflen);
-    while (nseg--) {
-      coap_add_option(response, COAP_OPTION_LOCATION_PATH,
-                     COAP_OPT_LENGTH(b), COAP_OPT_VALUE(b));
-      b += COAP_OPT_SIZE(b);
-    }
-  }
-}
-
-void
-init_resources(coap_context_t *ctx) {
-  coap_resource_t *r;
-
-  r = coap_resource_init(RD_ROOT_STR, RD_ROOT_SIZE, 0);
-  coap_register_handler(r, COAP_REQUEST_GET, hnd_get_rd);
-  coap_register_handler(r, COAP_REQUEST_POST, hnd_post_rd);
-
-  coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"40", 2, 0);
-  coap_add_attr(r, (unsigned char *)"rt", 2, (unsigned char *)"\"core-rd\"", 9, 0);
-  coap_add_attr(r, (unsigned char *)"ins", 2, (unsigned char *)"\"default\"", 9, 0);
-
-  coap_add_resource(ctx, r);
-
-}
-
-void
-usage( const char *program, const char *version) {
-  const char *p;
-
-  p = strrchr( program, '/' );
-  if ( p )
-    program = ++p;
-
-  fprintf( stderr, "%s v%s -- CoRE Resource Directory implementation\n"
-          "(c) 2011-2012 Olaf Bergmann <bergmann@tzi.org>\n\n"
-          "usage: %s [-A address] [-p port]\n\n"
-          "\t-A address\tinterface address to bind to\n"
-          "\t-p port\t\tlisten on specified port\n"
-          "\t-v num\t\tverbosity level (default: 3)\n",
-          program, version, program );
-}
-
-coap_context_t *
-get_context(const char *node, const char *port) {
-  coap_context_t *ctx = NULL;  
-  int s;
-  struct addrinfo hints;
-  struct addrinfo *result, *rp;
-
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
-  hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
-  hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
-  
-  s = getaddrinfo(node, port, &hints, &result);
-  if ( s != 0 ) {
-    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
-    return NULL;
-  } 
-
-  /* iterate through results until success */
-  for (rp = result; rp != NULL; rp = rp->ai_next) {
-    coap_address_t addr;
-
-    if (rp->ai_addrlen <= sizeof(addr.addr)) {
-      coap_address_init(&addr);
-      addr.size = rp->ai_addrlen;
-      memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen);
-
-      ctx = coap_new_context(&addr);
-      if (ctx) {
-       /* TODO: output address:port for successful binding */
-       goto finish;
-      }
-    }
-  }
-  
-  fprintf(stderr, "no context available for interface '%s'\n", node);
-
- finish:
-  freeaddrinfo(result);
-  return ctx;
-}
-
-int
-join(coap_context_t *ctx, char *group_name) {
-  struct ipv6_mreq mreq;
-  struct addrinfo   *reslocal = NULL, *resmulti = NULL, hints, *ainfo;
-  int result = -1;
-
-  /* we have to resolve the link-local interface to get the interface id */
-  memset(&hints, 0, sizeof(hints));
-  hints.ai_family = AF_INET6;
-  hints.ai_socktype = SOCK_DGRAM;
-
-  result = getaddrinfo("::", NULL, &hints, &reslocal);
-  if ( result < 0 ) {
-    perror("join: cannot resolve link-local interface");
-    goto finish;
-  }
-
-  /* get the first suitable interface identifier */
-  for (ainfo = reslocal; ainfo != NULL; ainfo = ainfo->ai_next) {
-    if ( ainfo->ai_family == AF_INET6 ) {
-      mreq.ipv6mr_interface =
-              ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_scope_id;
-      break;
-    }
-  }
-
-  memset(&hints, 0, sizeof(hints));
-  hints.ai_family = AF_INET6;
-  hints.ai_socktype = SOCK_DGRAM;
-
-  /* resolve the multicast group address */
-  result = getaddrinfo(group_name, NULL, &hints, &resmulti);
-
-  if ( result < 0 ) {
-    perror("join: cannot resolve multicast address");
-    goto finish;
-  }
-
-  for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
-    if ( ainfo->ai_family == AF_INET6 ) {
-      mreq.ipv6mr_multiaddr =
-        ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
-      break;
-    }
-  }
-
-  result = setsockopt( ctx->sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
-                       (char *)&mreq, sizeof(mreq) );
-  if ( result < 0 )
-    perror("join: setsockopt");
-
- finish:
-  freeaddrinfo(resmulti);
-  freeaddrinfo(reslocal);
-
-  return result;
-}
-
-int
-main(int argc, char **argv) {
-  coap_context_t  *ctx;
-  fd_set readfds;
-  struct timeval tv, *timeout;
-  int result;
-  coap_tick_t now;
-  coap_queue_t *nextpdu;
-  char addr_str[NI_MAXHOST] = "::";
-  char port_str[NI_MAXSERV] = "5683";
-  char *group = NULL;
-  int opt;
-  coap_log_t log_level = LOG_WARNING;
-
-  while ((opt = getopt(argc, argv, "A:g:p:v:")) != -1) {
-    switch (opt) {
-    case 'A' :
-      strncpy(addr_str, optarg, NI_MAXHOST-1);
-      addr_str[NI_MAXHOST - 1] = '\0';
-      break;
-    case 'g' :
-      group = optarg;
-      break;
-    case 'p' :
-      strncpy(port_str, optarg, NI_MAXSERV-1);
-      port_str[NI_MAXSERV - 1] = '\0';
-      break;
-    case 'v' :
-      log_level = strtol(optarg, NULL, 10);
-      break;
-    default:
-      usage( argv[0], PACKAGE_VERSION );
-      exit( 1 );
-    }
-  }
-
-  coap_set_log_level(log_level);
-
-  ctx = get_context(addr_str, port_str);
-  if (!ctx)
-    return -1;
-
-  if (group)
-    join(ctx, group);
-
-  init_resources(ctx);
-
-  signal(SIGINT, handle_sigint);
-
-  while ( !quit ) {
-    FD_ZERO(&readfds);
-    FD_SET( ctx->sockfd, &readfds );
-
-    nextpdu = coap_peek_next( ctx );
-
-    coap_ticks(&now);
-    while ( nextpdu && nextpdu->t <= now ) {
-      coap_retransmit( ctx, coap_pop_next( ctx ) );
-      nextpdu = coap_peek_next( ctx );
-    }
-
-    if ( nextpdu && nextpdu->t <= now + COAP_RESOURCE_CHECK_TIME ) {
-      /* set timeout if there is a pdu to send before our automatic timeout occurs */
-      tv.tv_usec = ((nextpdu->t - now) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND;
-      tv.tv_sec = (nextpdu->t - now) / COAP_TICKS_PER_SECOND;
-      timeout = &tv;
-    } else {
-      tv.tv_usec = 0;
-      tv.tv_sec = COAP_RESOURCE_CHECK_TIME;
-      timeout = &tv;
-    }
-    result = select( FD_SETSIZE, &readfds, 0, 0, timeout );
-
-    if ( result < 0 ) {                /* error */
-      if (errno != EINTR)
-       perror("select");
-    } else if ( result > 0 ) { /* read from socket */
-      if ( FD_ISSET( ctx->sockfd, &readfds ) ) {
-       coap_read( ctx );       /* read received data */
-       coap_dispatch( ctx );   /* and dispatch PDUs from receivequeue */
-      }
-    } else {                   /* timeout */
-      /* coap_check_resource_list( ctx ); */
-    }
-  }
-
-  coap_free_context( ctx );
-
-  return 0;
-}
diff --git a/resource/csdk/libcoap-4.1.1/examples/server.c b/resource/csdk/libcoap-4.1.1/examples/server.c
deleted file mode 100644 (file)
index ee4d73f..0000000
+++ /dev/null
@@ -1,490 +0,0 @@
-/* coap -- simple implementation of the Constrained Application Protocol (CoAP)
- *         as defined in draft-ietf-core-coap
- *
- * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-#include <sys/stat.h>
-#include <dirent.h>
-#include <errno.h>
-#include <signal.h>
-
-#include "config.h"
-#include "resource.h"
-#include "coap.h"
-#include <logger.h>
-#include <ocsocket.h>
-
-#define COAP_RESOURCE_CHECK_TIME 2
-
-#define MOD_NAME ("CoAP-Server")
-static uint8_t coap_wellknown_addr[] = {224,0,1,187};
-static short coap_def_port = 5683;
-
-#ifndef min
-#define min(a,b) ((a) < (b) ? (a) : (b))
-#endif
-
-/* temporary storage for dynamic resource representations */
-static int quit = 0;
-
-/* changeable clock base (see handle_put_time()) */
-static time_t my_clock_base = 0;
-
-struct coap_resource_t *time_resource = NULL;
-
-#ifndef WITHOUT_ASYNC
-/* This variable is used to mimic long-running tasks that require
- * asynchronous responses. */
-static coap_async_state_t *async = NULL;
-#endif /* WITHOUT_ASYNC */
-
-/* SIGINT handler: set quit to 1 for graceful termination */
-void
-handle_sigint(int signum) {
-  (void)signum;
-  quit = 1;
-}
-
-#define INDEX "This is a test server made with libcoap (see http://libcoap.sf.net)\n" \
-             "Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>\n\n"
-
-void
-hnd_get_index(coap_context_t  *ctx, struct coap_resource_t *resource,
-             coap_address_t *peer, coap_pdu_t *request, str *token,
-             coap_pdu_t *response) {
-  unsigned char buf[3];
-  (void)ctx;
-  (void)resource;
-  (void)peer;
-  (void)request;
-  (void)token;
-
-  response->hdr->code = COAP_RESPONSE_CODE(205);
-
-  coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
-         coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf);
-
-  coap_add_option(response, COAP_OPTION_MAXAGE,
-         coap_encode_var_bytes(buf, 0x2ffff), buf);
-
-  coap_add_data(response, strlen(INDEX), (unsigned char *)INDEX);
-}
-
-void
-hnd_get_time(coap_context_t  *ctx, struct coap_resource_t *resource,
-            coap_address_t *peer, coap_pdu_t *request, str *token,
-            coap_pdu_t *response) {
-  coap_opt_iterator_t opt_iter;
-  coap_opt_t *option;
-  unsigned char buf[40];
-  size_t len;
-  time_t now;
-  coap_tick_t t;
-  coap_subscription_t *subscription;
-
-  /* FIXME: return time, e.g. in human-readable by default and ticks
-   * when query ?ticks is given. */
-
-  /* if my_clock_base was deleted, we pretend to have no such resource */
-  response->hdr->code =
-    my_clock_base ? COAP_RESPONSE_CODE(205) : COAP_RESPONSE_CODE(404);
-
-  if (request != NULL &&
-      coap_check_option(request, COAP_OPTION_OBSERVE, &opt_iter)) {
-    subscription = coap_add_observer(resource, peer, token);
-    if (subscription) {
-      subscription->non = request->hdr->type == COAP_MESSAGE_NON;
-      coap_add_option(response, COAP_OPTION_OBSERVE, 0, NULL);
-    }
-  }
-  if (resource->dirty == 1)
-    coap_add_option(response, COAP_OPTION_OBSERVE,
-                   coap_encode_var_bytes(buf, ctx->observe), buf);
-
-
-  if (my_clock_base)
-    coap_add_option(response, COAP_OPTION_CONTENT_FORMAT,
-                   coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf);
-
-  coap_add_option(response, COAP_OPTION_MAXAGE,
-         coap_encode_var_bytes(buf, 0x01), buf);
-
-  if (my_clock_base) {
-
-    /* calculate current time */
-    coap_ticks(&t);
-    now = my_clock_base + (t / COAP_TICKS_PER_SECOND);
-
-    if (request != NULL
-       && (option = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter))
-       && memcmp(COAP_OPT_VALUE(option), "ticks",
-                 min(5, COAP_OPT_LENGTH(option))) == 0) {
-      /* output ticks */
-      len = snprintf((char *)buf,
-          min(sizeof(buf), response->max_size - response->length),
-                    "%u", (unsigned int)now);
-      coap_add_data(response, len, buf);
-
-    } else {                   /* output human-readable time */
-      struct tm *tmp;
-      tmp = gmtime(&now);
-      len = strftime((char *)buf,
-                    min(sizeof(buf), response->max_size - response->length),
-                    "%b %d %H:%M:%S", tmp);
-      coap_add_data(response, len, buf);
-    }
-  }
-}
-
-void
-hnd_put_time(coap_context_t  *ctx, struct coap_resource_t *resource,
-            coap_address_t *peer, coap_pdu_t *request, str *token,
-            coap_pdu_t *response) {
-  coap_tick_t t;
-  size_t size;
-  unsigned char *data;
-  (void)ctx;
-  (void)peer;
-  (void)token;
-
-  /* FIXME: re-set my_clock_base to clock_offset if my_clock_base == 0
-   * and request is empty. When not empty, set to value in request payload
-   * (insist on query ?ticks). Return Created or Ok.
-   */
-
-  /* if my_clock_base was deleted, we pretend to have no such resource */
-  response->hdr->code =
-    my_clock_base ? COAP_RESPONSE_CODE(204) : COAP_RESPONSE_CODE(201);
-
-  resource->dirty = 1;
-
-  coap_get_data(request, &size, &data);
-
-  if (size == 0)               /* re-init */
-    my_clock_base = clock_offset;
-  else {
-    my_clock_base = 0;
-    coap_ticks(&t);
-    while(size--)
-      my_clock_base = my_clock_base * 10 + *data++;
-    my_clock_base -= t / COAP_TICKS_PER_SECOND;
-  }
-}
-
-void
-hnd_delete_time(coap_context_t  *ctx, struct coap_resource_t *resource,
-             coap_address_t *peer, coap_pdu_t *request, str *token,
-             coap_pdu_t *response) {
-  (void)ctx;
-  (void)resource;
-  (void)peer;
-  (void)request;
-  (void)token;
-  (void)response;
-  my_clock_base = 0;           /* mark clock as "deleted" */
-
-  /* type = request->hdr->type == COAP_MESSAGE_CON  */
-  /*   ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON; */
-}
-
-#ifndef WITHOUT_ASYNC
-void
-hnd_get_async(coap_context_t  *ctx, struct coap_resource_t *resource,
-             coap_address_t *peer, coap_pdu_t *request, str *token,
-             coap_pdu_t *response) {
-  coap_opt_iterator_t opt_iter;
-  coap_opt_t *option;
-  unsigned long delay = 5;
-  size_t size;
-  (void)resource;
-  (void)token;
-
-  if (async) {
-    if (async->id != request->hdr->id) {
-      coap_opt_filter_t f;
-      coap_option_filter_clear(f);
-      response->hdr->code = COAP_RESPONSE_CODE(503);
-    }
-    return;
-  }
-
-  option = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
-  if (option) {
-    unsigned char *p = COAP_OPT_VALUE(option);
-
-    delay = 0;
-    for (size = COAP_OPT_LENGTH(option); size; --size, ++p)
-      delay = delay * 10 + (*p - '0');
-  }
-
-  async = coap_register_async(ctx, peer, request,
-                             COAP_ASYNC_SEPARATE | COAP_ASYNC_CONFIRM,
-                             (void *)(COAP_TICKS_PER_SECOND * delay));
-}
-
-void
-check_async(coap_context_t  *ctx, coap_tick_t now) {
-  coap_pdu_t *response;
-  coap_async_state_t *tmp;
-
-  size_t size = sizeof(coap_hdr_t) + 8;
-
-  if (!async || now < async->created + (unsigned long)async->appdata)
-    return;
-
-  response = coap_pdu_init(async->flags & COAP_ASYNC_CONFIRM
-                          ? COAP_MESSAGE_CON
-                          : COAP_MESSAGE_NON,
-                          COAP_RESPONSE_CODE(205), 0, size);
-  if (!response) {
-    debug("check_async: insufficient memory, we'll try later\n");
-    async->appdata =
-      (void *)((unsigned long)async->appdata + 15 * COAP_TICKS_PER_SECOND);
-    return;
-  }
-
-  response->hdr->id = coap_new_message_id(ctx);
-
-  if (async->tokenlen)
-    coap_add_token(response, async->tokenlen, async->token);
-
-  coap_add_data(response, 4, (unsigned char *)"done");
-
-  if (coap_send(ctx, &async->peer, response) == COAP_INVALID_TID) {
-    debug("check_async: cannot send response for message %d\n",
-         response->hdr->id);
-  }
-  coap_delete_pdu(response);
-  coap_remove_async(ctx, async->id, &tmp);
-  coap_free_async(async);
-  async = NULL;
-}
-#endif /* WITHOUT_ASYNC */
-
-void
-init_resources(coap_context_t *ctx) {
-  coap_resource_t *r;
-
-  r = coap_resource_init(NULL, 0, 0);
-  coap_register_handler(r, COAP_REQUEST_GET, hnd_get_index);
-
-  coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"0", 1, 0);
-  coap_add_attr(r, (unsigned char *)"title", 5, (unsigned char *)"\"General Info\"", 14, 0);
-  coap_add_resource(ctx, r);
-
-  /* store clock base to use in /time */
-  my_clock_base = clock_offset;
-
-  r = coap_resource_init((unsigned char *)"time", 4, 0);
-  coap_register_handler(r, COAP_REQUEST_GET, hnd_get_time);
-  coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_time);
-  coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_time);
-
-  coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"0", 1, 0);
-  coap_add_attr(r, (unsigned char *)"title", 5, (unsigned char *)"\"Internal Clock\"", 16, 0);
-  coap_add_attr(r, (unsigned char *)"rt", 2, (unsigned char *)"\"Ticks\"", 7, 0);
-  r->observable = 1;
-  coap_add_attr(r, (unsigned char *)"if", 2, (unsigned char *)"\"clock\"", 7, 0);
-
-  coap_add_resource(ctx, r);
-  time_resource = r;
-
-#ifndef WITHOUT_ASYNC
-  r = coap_resource_init((unsigned char *)"async", 5, 0);
-  coap_register_handler(r, COAP_REQUEST_GET, hnd_get_async);
-
-  coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"0", 1, 0);
-  coap_add_resource(ctx, r);
-#endif /* WITHOUT_ASYNC */
-}
-
-void
-usage( const char *program, const char *version) {
-  const char *p;
-
-  p = strrchr( program, '/' );
-  if ( p )
-    program = ++p;
-
-  fprintf( stderr, "%s v%s -- a small CoAP implementation\n"
-          "(c) 2010,2011 Olaf Bergmann <bergmann@tzi.org>\n\n"
-          "usage: %s [-A address] [-p port]\n\n"
-          "\t-A address\tinterface address to bind to\n"
-          "\t-p port\t\tlisten on specified port\n"
-          "\t-v num\t\tverbosity level (default: 3)\n",
-          program, version, program );
-}
-
-coap_context_t *
-get_context(const char *node, const char *port) {
-  coap_context_t *ctx = NULL;
-  int s;
-  struct addrinfo hints;
-  struct addrinfo *result, *rp;
-  OCDevAddr mcast_addr;
-
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
-  hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
-  hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
-
-  s = getaddrinfo(node, port, &hints, &result);
-  if ( s != 0 ) {
-    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
-    return NULL;
-  }
-
-  /* iterate through results until success */
-  for (rp = result; rp != NULL; rp = rp->ai_next) {
-    coap_address_t addr;
-
-    if (rp->ai_addrlen <= sizeof(addr.addr)) {
-      coap_address_init(&addr);
-      addr.size = rp->ai_addrlen;
-      memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen);
-      OC_LOG_BUFFER(DEBUG, MOD_NAME, (uint8_t *)&addr, addr.size + 4 );
-
-      ctx = coap_new_context(&addr);
-      if (ctx) {
-       /* TODO: output address:port for successful binding */
-        OCBuildIPv4Address(coap_wellknown_addr[0], coap_wellknown_addr[1],
-            coap_wellknown_addr[2], coap_wellknown_addr[3], coap_def_port, &mcast_addr);
-        if (coap_join_wellknown_group(ctx, (coap_address_t*)&mcast_addr) != 0) {
-            OC_LOG(ERROR, MOD_NAME, PCF("Unable to join to wellknown multicast group") );
-        }
-        goto finish;
-      }
-    }
-  }
-
-  fprintf(stderr, "no context available for interface '%s'\n", node);
-
- finish:
-  freeaddrinfo(result);
-  return ctx;
-}
-
-int
-main(int argc, char **argv) {
-  coap_context_t  *ctx;
-  fd_set readfds;
-  struct timeval tv, *timeout;
-  int result;
-  coap_tick_t now;
-  coap_queue_t *nextpdu;
-  char addr_str[NI_MAXHOST] = "::";
-  char port_str[NI_MAXSERV] = "5683";
-  int opt;
-  coap_log_t log_level = LOG_WARNING;
-
-  while ((opt = getopt(argc, argv, "A:p:v:")) != -1) {
-    switch (opt) {
-    case 'A' :
-      strncpy(addr_str, optarg, NI_MAXHOST-1);
-      addr_str[NI_MAXHOST - 1] = '\0';
-      break;
-    case 'p' :
-      strncpy(port_str, optarg, NI_MAXSERV-1);
-      port_str[NI_MAXSERV - 1] = '\0';
-      break;
-    case 'v' :
-      log_level = strtol(optarg, NULL, 10);
-      break;
-    default:
-      usage( argv[0], PACKAGE_VERSION );
-      exit( 1 );
-    }
-  }
-
-  coap_set_log_level(log_level);
-
-  ctx = get_context(addr_str, port_str);
-  if (!ctx)
-    return -1;
-
-  init_resources(ctx);
-
-  signal(SIGINT, handle_sigint);
-
-  while ( !quit ) {
-    FD_ZERO(&readfds);
-    FD_SET( ctx->sockfd, &readfds );
-    if (ctx->sockfd_wellknown != -1) {
-        FD_SET( ctx->sockfd_wellknown, &readfds );
-    }
-
-
-    nextpdu = coap_peek_next( ctx );
-
-    coap_ticks(&now);
-    while (nextpdu && nextpdu->t <= now - ctx->sendqueue_basetime) {
-      coap_retransmit( ctx, coap_pop_next( ctx ) );
-      nextpdu = coap_peek_next( ctx );
-    }
-
-    if ( nextpdu && nextpdu->t <= COAP_RESOURCE_CHECK_TIME ) {
-      /* set timeout if there is a pdu to send before our automatic timeout occurs */
-      tv.tv_usec = ((nextpdu->t) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND;
-      tv.tv_sec = (nextpdu->t) / COAP_TICKS_PER_SECOND;
-      timeout = &tv;
-    } else {
-      tv.tv_usec = 0;
-      tv.tv_sec = COAP_RESOURCE_CHECK_TIME;
-      timeout = &tv;
-    }
-    result = select( FD_SETSIZE, &readfds, 0, 0, timeout );
-
-    if ( result < 0 ) {                /* error */
-      if (errno != EINTR)
-       perror("select");
-    } else if ( result > 0 ) { /* read from unicast socket */
-      if ( FD_ISSET( ctx->sockfd, &readfds ) ) {
-       coap_read( ctx, ctx->sockfd );  /* read received data */
-       coap_dispatch( ctx );   /* and dispatch PDUs from receivequeue */
-      }
-
-      if (ctx->sockfd_wellknown != -1) {
-        if ( FD_ISSET( ctx->sockfd_wellknown, &readfds ) ) {  /* read from multicast socket */
-
-       OC_LOG(DEBUG, MOD_NAME, PCF("Device Discovery request at well-known address !!"));
-       coap_read( ctx, ctx->sockfd_wellknown );        /* read received data */
-       TODO("Do we need to call coap_dispatch separately for unicast and multicast sockets")
-       coap_dispatch( ctx );   /* and dispatch PDUs from receivequeue */
-      }
-     }
-    } else {                   /* timeout */
-      if (time_resource) {
-       time_resource->dirty = 1;
-      }
-    }
-
-#ifndef WITHOUT_ASYNC
-    /* check if we have to send asynchronous responses */
-    check_async(ctx, now);
-#endif /* WITHOUT_ASYNC */
-
-#ifndef WITHOUT_OBSERVE
-    /* check if we have to send observe notifications */
-    coap_check_notify(ctx);
-#endif /* WITHOUT_OBSERVE */
-  }
-
-  coap_free_context( ctx );
-
-  return 0;
-}
diff --git a/resource/csdk/libcoap-4.1.1/examples/tiny.c b/resource/csdk/libcoap-4.1.1/examples/tiny.c
deleted file mode 100644 (file)
index 0583c28..0000000
+++ /dev/null
@@ -1,149 +0,0 @@
-/* tiny -- tiny sender
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <limits.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-
-#include "../coap.h"
-
-static coap_tid_t id;
-
-coap_pdu_t *
-make_pdu( unsigned int value ) {
-  coap_pdu_t *pdu;
-  unsigned char enc;
-  static unsigned char buf[20];
-  int len, ls;
-
-  if ( ! ( pdu = coap_new_pdu() ) )
-    return NULL;
-
-  pdu->hdr->type = COAP_MESSAGE_NON;
-  pdu->hdr->code = COAP_REQUEST_POST;
-  pdu->hdr->id = htons(id++);
-
-  enc = COAP_PSEUDOFP_ENCODE_8_4_DOWN(value,ls);
-  coap_add_data( pdu, 1, &enc);
-
-  len = snprintf((char *)buf, sizeof(buf), "%u", COAP_PSEUDOFP_DECODE_8_4(enc));
-  if ( len > 0 ) {
-    coap_add_data( pdu, len, buf );
-  }
-
-  return pdu;
-}
-
-void
-usage( const char *program ) {
-  const char *p;
-
-  p = strrchr( program, '/' );
-  if ( p )
-    program = ++p;
-
-  fprintf( stderr, "%s -- tiny fake sensor\n"
-          "(c) 2010 Olaf Bergmann <bergmann@tzi.org>\n\n"
-          "usage: %s [group address]\n"
-          "\n\nSends some fake sensor values to specified multicast group\n",
-          program, program );
-}
-
-coap_context_t *
-get_context(const char *node, const char *port) {
-  coap_context_t *ctx = NULL;  
-  int s;
-  struct addrinfo hints;
-  struct addrinfo *result, *rp;
-
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
-  hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
-  hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL;
-  
-  s = getaddrinfo(node, port, &hints, &result);
-  if ( s != 0 ) {
-    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
-    return NULL;
-  } 
-
-  /* iterate through results until success */
-  for (rp = result; rp != NULL; rp = rp->ai_next) {
-    ctx = coap_new_context(rp->ai_addr, rp->ai_addrlen);
-    if (ctx) {
-      /* TODO: output address:port for successful binding */
-      goto finish;
-    }
-  }
-  
-  fprintf(stderr, "no context available for interface '%s'\n", node);
-
- finish:
-  freeaddrinfo(result);
-  return ctx;
-}
-
-int
-main(int argc, char **argv) {
-  coap_context_t  *ctx;
-  struct timeval tv;
-  coap_pdu_t  *pdu;
-  struct sockaddr_in6 dst;
-  int hops = 16;
-
-  if ( argc > 1 && strncmp(argv[1], "-h", 2) == 0 ) {
-    usage( argv[0] );
-    exit( 1 );
-  }
-
-  ctx = get_context("::", NULL);
-  if ( !ctx )
-    return -1;
-
-  id = rand() & INT_MAX;
-
-  memset(&dst, 0, sizeof(struct sockaddr_in6 ));
-  dst.sin6_family = AF_INET6;
-  inet_pton( AF_INET6, argc > 1 ? argv[1] : "::1", &dst.sin6_addr );
-  dst.sin6_port = htons( COAP_DEFAULT_PORT );
-
-  if ( IN6_IS_ADDR_MULTICAST(&dst.sin6_addr) ) {
-    /* set socket options for multicast */
-
-    if ( setsockopt( ctx->sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
-                    (char *)&hops, sizeof(hops) ) < 0 )
-      perror("setsockopt: IPV6_MULTICAST_HOPS");
-
-  }
-
-  while ( 1 ) {
-
-    if (! (pdu = make_pdu( rand() & 0xfff ) ) )
-      return -1;
-
-    coap_send( ctx, (struct sockaddr *)&dst, sizeof(dst), pdu );
-    coap_delete_pdu(pdu);
-
-    tv.tv_sec = 5; tv.tv_usec = 0;
-
-    select( 0, 0, 0, 0, &tv );
-
-  }
-
-  coap_free_context( ctx );
-
-  return 0;
-}
diff --git a/resource/csdk/libcoap-4.1.1/hashkey.c b/resource/csdk/libcoap-4.1.1/hashkey.c
deleted file mode 100644 (file)
index 828b519..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/* hashkey.c -- definition of hash key type and helper functions
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#include "hashkey.h"
-
-/* Caution: When changing this, update COAP_DEFAULT_WKC_HASHKEY
- * accordingly (see int coap_hash_path());
- */
-void
-coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h) {
-  size_t j;
-
-  while (len--) {
-    j = sizeof(coap_key_t)-1;
-  
-    while (j) {
-      h[j] = ((h[j] << 7) | (h[j-1] >> 1)) + h[j];
-      --j;
-    }
-
-    h[0] = (h[0] << 7) + h[0] + *s++;
-  }
-}
-
diff --git a/resource/csdk/libcoap-4.1.1/hashkey.h b/resource/csdk/libcoap-4.1.1/hashkey.h
deleted file mode 100644 (file)
index abce9ac..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/* hashkey.h -- definition of hash key type and helper functions
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-/** 
- * @file hashkey.h
- * @brief definition of hash key type and helper functions
- */
-
-#ifndef _COAP_HASHKEY_H_
-#define _COAP_HASHKEY_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "str.h"
-
-typedef unsigned char coap_key_t[4];
-
-#ifndef coap_hash
-/** 
- * Calculates a fast hash over the given string @p s of length @p len
- * and stores the result into @p h. Depending on the exact
- * implementation, this function cannot be used as one-way function to
- * check message integrity or simlar.
- * 
- * @param s   The string used for hash calculation.
- * @param len The length of @p s.
- * @param h   The result buffer to store the calculated hash key.
- */
-void coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h);
-
-#define coap_hash(String,Length,Result) \
-  coap_hash_impl((String),(Length),(Result))
-
-/* This is used to control the pre-set hash-keys for resources. */
-#define __COAP_DEFAULT_HASH
-#else
-#undef __COAP_DEFAULT_HASH
-#endif /* coap_hash */
-
-/** 
- * Calls coap_hash() with given @c str object as parameter.
- * 
- * @param Str Must contain a pointer to a coap string object.
- * @param H   A coap_key_t object to store the result.
- * 
- * @hideinitializer
- */
-#define coap_str_hash(Str,H) {                 \
-    assert(Str);                               \
-    memset((H), 0, sizeof(coap_key_t));                \
-    coap_hash((H), (Str)->s, (Str)->length);   \
-  }
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_HASHKEY_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/makefile b/resource/csdk/libcoap-4.1.1/makefile
deleted file mode 100644 (file)
index ddf4fec..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
-# default to release build
-# default to build for linux
-BUILD   := release
-#other options are arduinomega, arduinodue
-PLATFORM=linux
-#other options are arduino
-PLATFORM_TYPE=linux
-# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
-ARDUINOWIFI := 0
-
-ifeq ($(ROOT_DIR), )
-       ROOT_DIR = ..
-endif
-ifeq ($(PLATFORM), "")
-       PLATFORM := "linux"
-endif
-
-OCSOCK_DIR    = $(ROOT_DIR)/ocsocket
-OC_LOG_DIR    = $(ROOT_DIR)/../oc_logger
-LOGGER_DIR    = $(ROOT_DIR)/logger
-RANDOM_DIR    = $(ROOT_DIR)/ocrandom
-STACK_DIR     = $(ROOT_DIR)/stack
-OCMALLOC_DIR  = $(ROOT_DIR)/ocmalloc
-EXTLIBS_DIR   = $(ROOT_DIR)/../../extlibs
-TINYDTLS_DIR  = $(EXTLIBS_DIR)/tinydtls
-INC_DIRS      = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include -I$(RANDOM_DIR)/include \
-                -I$(OCMALLOC_DIR)/include -I$(OC_LOG_DIR)/include -I$(STACK_DIR)/include
-
-# Note for Arduino: The CC flag is set to the C++ compiler since Arduino build 
-# includes Time.h header file which has C++ style definitions.
-ifeq ($(PLATFORM),android)
-    CXX=arm-linux-androideabi-g++
-    CC=arm-linux-androideabi-gcc
-    AR=arm-linux-androideabi-ar
-    RANLIB=arm-linux-androideabi-ranlib
-    CFLAGS_PLATFORM =  -DWITH_POSIX -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16
-    LDFLAGS_PLATFORM = -march=armv7-a -Wl,--fix-cortex-a8 -llog
-else ifeq ($(PLATFORM),linux)
-    PLATFORM_TYPE:=linux
-    CXX=g++
-    CC=gcc
-    AR=ar
-    RANLIB=ranlib
-    CFLAGS_PLATFORM = -std=gnu99 -DWITH_POSIX
-else ifeq ($(PLATFORM),arduinomega)
-    PLATFORM_TYPE:=arduino
-    include $(ROOT_DIR)/local.properties
-    include $(ROOT_DIR)/$(PLATFORM).properties
-    CC=$(ARDUINO_TOOLS_DIR)/avr-g++
-else ifeq ($(PLATFORM),arduinodue)
-    PLATFORM_TYPE:=arduino
-    include $(ROOT_DIR)/local.properties
-    include $(ROOT_DIR)/$(PLATFORM).properties
-    CC=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-g++
-else
-   $(error Wrong value for PLATFORM !!)
-endif
-
-ifeq ($(PLATFORM_TYPE),arduino)
-    ifeq ($(ARDUINOWIFI),1)
-        SOURCES += ocsocket_arduino_wifi.c
-        ARDUINO_SHIELD_TYPE := "/wifi_shield"
-    else
-        SOURCES += ocsocket_arduino.c
-        ARDUINO_SHIELD_TYPE := "/ethernet_shield"
-    endif
-    SOURCESCPP:= Time.cpp
-    OBJECTSCPP:= $(patsubst %.cpp, %.o, $(SOURCESCPP))
-    VPATH := $(SDIR_ARD_TIME)
-else
-    SOURCES += ocsocket.c
-endif
-
-OUT_DIR          := ./$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
-OBJ_DIR          := $(OUT_DIR)/obj
-
-CC_FLAGS.debug := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions -pedantic \
--DTB_LOG
-CC_FLAGS.release := -Os -Wall -ffunction-sections -fdata-sections -fno-exceptions
-
-SOURCES+= pdu.c net.c debug.c encode.c uri.c coap_list.c hashkey.c \
-          str.c option.c async.c subscribe.c block.c logger.c ocrandom.c ocmalloc.c \
-                 oc_logger.c oc_console_logger.c
-VPATH += $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src:$(RANDOM_DIR)/src:$(OCMALLOC_DIR)/src\
-         :$(OC_LOG_DIR)/c
-
-ifeq ($(PLATFORM),linux)
-ifneq ($(wildcard $(TINYDTLS_DIR)/libtinydtls.a),)
-    $(info "Building libcoap with DTLS support")
-       SOURCES += netdtls.c
-       VPATH += sec
-       NETDTLS_DIR   = sec
-       INC_DIRS += -I$(TINYDTLS_DIR) -I$(NETDTLS_DIR) -I.
-       CC_FLAGS.debug += -DWITH_DTLS
-       CC_FLAGS.release += -DWITH_DTLS
-endif
-endif
-
-OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
-
-all: prep_dirs libcoap.a
-
-prep_dirs:
-       -mkdir -p $(PLATFORM)
-       -mkdir -p $(OUT_DIR)
-       -mkdir -p $(OBJ_DIR)
-
-%.o: %.c
-       $(CC) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-
-%.o: %.cpp
-       $(CXX) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-
-libcoap.a: $(OBJECTS) $(OBJECTSCPP)
-       $(AR) rcs $(OUT_DIR)/$@ $(addprefix $(OBJ_DIR)/,$^)
-       $(RANLIB) $(OUT_DIR)/$@
-
-.PHONY: clean
-
-clean: legacy_clean
-       -rm -rf linux
-       -rm -rf arduinomega
-       -rm -rf arduinodue
-
-legacy_clean:
-       rm -f *.o libcoap.a
-       rm -rf release
-       rm -rf debug
-
diff --git a/resource/csdk/libcoap-4.1.1/mem.h b/resource/csdk/libcoap-4.1.1/mem.h
deleted file mode 100644 (file)
index 2b0d27d..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/* mem.h -- CoAP memory handling
- *          Currently, this is just a dummy for malloc/free
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#ifndef _COAP_MEM_H_
-#define _COAP_MEM_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "ocmalloc.h"
-
-#define coap_malloc(size)  OCMalloc(size)
-#define coap_free(ptr)     OCFree(ptr)
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_MEM_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/net.c b/resource/csdk/libcoap-4.1.1/net.c
deleted file mode 100644 (file)
index d36b0e2..0000000
+++ /dev/null
@@ -1,1642 +0,0 @@
-/* net.c -- CoAP network interface
- *
- * Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-
-#include <ctype.h>
-#include <stdio.h>
-#ifdef HAVE_LIMITS_H
-#include <limits.h>
-#endif
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#elif HAVE_SYS_UNISTD_H
-#include <sys/unistd.h>
-#endif
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-#ifdef WITH_LWIP
-#include <lwip/pbuf.h>
-#include <lwip/udp.h>
-#include <lwip/timers.h>
-#endif
-
-#include "debug.h"
-#include "mem.h"
-#include "str.h"
-#include "async.h"
-#include "option.h"
-#include "encode.h"
-#include "block.h"
-#include "net.h"
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-
-#include <ocsocket.h>
-#include <logger.h>
-#if defined(WITH_DTLS)
-#include "netdtls.h"
-#endif /* WITH_DTLS */
-
-#define MOD_NAME ("net.c")
-
-time_t clock_offset;
-
-static inline coap_queue_t *
-coap_malloc_node() {
-    return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t));
-}
-
-static inline void
-coap_free_node(coap_queue_t *node) {
-    coap_free(node);
-}
-#endif /* WITH_POSIX || WITH_ARDUINO */
-#ifdef WITH_LWIP
-
-#include <lwip/memp.h>
-
-static void coap_retransmittimer_execute(void *arg);
-static void coap_retransmittimer_restart(coap_context_t *ctx);
-
-static inline coap_queue_t *
-coap_malloc_node() {
-    return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
-}
-
-static inline void
-coap_free_node(coap_queue_t *node) {
-    memp_free(MEMP_COAP_NODE, node);
-}
-
-#endif /* WITH_LWIP */
-#ifdef WITH_CONTIKI
-# ifndef DEBUG
-#  define DEBUG DEBUG_PRINT
-# endif /* DEBUG */
-
-#include "memb.h"
-#include "net/uip-debug.h"
-
-clock_time_t clock_offset;
-
-#define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
-#define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
-
-void coap_resources_init();
-void coap_pdu_resources_init();
-
-unsigned char initialized = 0;
-coap_context_t the_coap_context;
-
-MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT);
-
-PROCESS(coap_retransmit_process, "message retransmit process");
-
-static inline coap_queue_t *
-coap_malloc_node() {
-    return (coap_queue_t *)memb_alloc(&node_storage);
-}
-
-static inline void
-coap_free_node(coap_queue_t *node) {
-    memb_free(&node_storage, node);
-}
-#endif /* WITH_CONTIKI */
-#ifdef WITH_LWIP
-
-/** Callback to udp_recv when using lwIP. Gets called by lwIP on arriving
- * packages, places a reference in context->pending_package, and calls
- * coap_read to process the package. Thus, coap_read needs not be called in
- * lwIP main loops. (When modifying this for thread-like operation, ie. if you
- * remove the coap_read call from this, make sure that coap_read gets a chance
- * to run before this callback is entered the next time.)
- */
-static void received_package(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
-{
-    struct coap_context_t *context = (coap_context_t *)arg;
-
-    LWIP_ASSERT("pending_package was not cleared.", context->pending_package == NULL);
-
-    context->pending_package = p; /* we don't free it, coap_read has to do that */
-    context->pending_address.addr = addr->addr; /* FIXME: this has to become address-type independent, probably there'll be an lwip function for that */
-    context->pending_port = port;
-
-    coap_read(context, -1); /* we want to read from unicast socket */
-}
-
-#endif /* WITH_LWIP */
-
-unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) {
-    unsigned int result = 0;
-    coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
-
-    if (ctx->sendqueue) {
-        /* delta < 0 means that the new time stamp is before the old. */
-        if (delta <= 0) {
-            ctx->sendqueue->t -= delta;
-        } else {
-            /* This case is more complex: The time must be advanced forward,
-             * thus possibly leading to timed out elements at the queue's
-             * start. For every element that has timed out, its relative
-             * time is set to zero and the result counter is increased. */
-
-            coap_queue_t *q = ctx->sendqueue;
-            coap_tick_t t = 0;
-            while (q && (t + q->t < (coap_tick_t) delta)) {
-                t += q->t;
-                q->t = 0;
-                result++;
-                q = q->next;
-            }
-
-            /* finally adjust the first element that has not expired */
-            if (q) {
-                q->t = (coap_tick_t) delta - t;
-            }
-        }
-    }
-
-    /* adjust basetime */
-    ctx->sendqueue_basetime += delta;
-
-    return result;
-}
-
-int coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
-    coap_queue_t *p, *q;
-    if (!queue || !node)
-        return 0;
-
-    /* set queue head if empty */
-    if (!*queue) {
-        *queue = node;
-        return 1;
-    }
-
-    /* replace queue head if PDU's time is less than head's time */
-    q = *queue;
-    if (node->t < q->t) {
-        node->next = q;
-        *queue = node;
-        q->t -= node->t; /* make q->t relative to node->t */
-        return 1;
-    }
-
-    /* search for right place to insert */
-    do {
-        node->t -= q->t; /* make node-> relative to q->t */
-        p = q;
-        q = q->next;
-    } while (q && q->t <= node->t);
-
-    /* insert new item */
-    if (q) {
-        q->t -= node->t; /* make q->t relative to node->t */
-    }
-    node->next = q;
-    p->next = node;
-    return 1;
-}
-
-int coap_delete_node(coap_queue_t *node) {
-    if (!node)
-        return 0;
-
-    coap_delete_pdu(node->pdu);
-    coap_free_node(node);
-
-    return 1;
-}
-
-void coap_delete_all(coap_queue_t *queue) {
-    if (!queue)
-        return;
-
-    coap_delete_all(queue->next);
-    coap_delete_node(queue);
-}
-
-coap_queue_t *
-coap_new_node() {
-    coap_queue_t *node;
-    node = coap_malloc_node();
-
-    if (!node) {
-#ifndef NDEBUG
-        coap_log(LOG_WARNING, "coap_new_node: malloc\n");
-#endif
-        return NULL;
-    }
-
-    memset(node, 0, sizeof *node);
-    return node;
-}
-
-coap_queue_t *
-coap_peek_next(coap_context_t *context) {
-    if (!context || !context->sendqueue)
-        return NULL;
-
-    return context->sendqueue;
-}
-
-coap_queue_t *
-coap_pop_next(coap_context_t *context) {
-    coap_queue_t *next;
-
-    if (!context || !context->sendqueue)
-        return NULL;
-
-    next = context->sendqueue;
-    context->sendqueue = context->sendqueue->next;
-    if (context->sendqueue) {
-        context->sendqueue->t += next->t;
-    }
-    next->next = NULL;
-    return next;
-}
-
-#ifdef COAP_DEFAULT_WKC_HASHKEY
-/** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */
-#define is_wkc(Key)                         \
-  (memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0)
-#else
-/* Implements a singleton to store a hash key for the .wellknown/core
- * resources. */
-int
-is_wkc(coap_key_t k) {
-    static coap_key_t wkc;
-    static unsigned char _initialized = 0;
-    if (!_initialized) {
-        _initialized = coap_hash_path((unsigned char *)COAP_DEFAULT_URI_WELLKNOWN,
-                sizeof(COAP_DEFAULT_URI_WELLKNOWN) - 1, wkc);
-    }
-    return memcmp(k, wkc, sizeof(coap_key_t)) == 0;
-}
-#endif
-
-coap_context_t *
-coap_new_context(uint8_t ipAddr[], uint16_t port) {
-
-    OCDevAddr devAddr;
-    coap_address_t* listen_addr;
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-    coap_context_t *c = (coap_context_t*)coap_malloc( sizeof( coap_context_t ) );
-    //int reuse = 1;
-#endif /* WITH_POSIX || WITH_ARDUINO */
-#ifdef WITH_LWIP
-    coap_context_t *c = memp_malloc(MEMP_COAP_CONTEXT);
-#endif /* WITH_LWIP */
-#ifdef WITH_CONTIKI
-    coap_context_t *c;
-
-    if (initialized)
-    return NULL;
-#endif /* WITH_CONTIKI */
-
-    OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
-            &devAddr);
-
-    listen_addr = (coap_address_t*) &devAddr;
-
-    if (!listen_addr) {
-        coap_free(c);
-        coap_log(LOG_EMERG, "no listen address specified\n");
-        return NULL;
-    }
-
-    coap_clock_init();
-#ifdef WITH_LWIP
-    prng_init(LWIP_RAND());
-#else /* WITH_LWIP */
-    prng_init((unsigned long)listen_addr ^ clock_offset);
-#endif /* WITH_LWIP */
-
-#ifndef WITH_CONTIKI
-    if (!c) {
-#ifndef NDEBUG
-        coap_log(LOG_EMERG, "coap_init: malloc:\n");
-#endif
-        return NULL;
-    }
-#endif /* not WITH_CONTIKI */
-#ifdef WITH_CONTIKI
-    coap_resources_init();
-    coap_pdu_resources_init();
-
-    c = &the_coap_context;
-    initialized = 1;
-#endif /* WITH_CONTIKI */
-
-    memset(c, 0, sizeof(coap_context_t));
-
-    /* set well-known sockfd to uninitialize value  */
-    c->sockfd_wellknown = -1;
-
-    /* initialize message id */
-    prng((unsigned char * )&c->message_id, sizeof(unsigned short));
-
-    /* register the critical options that we know */
-    coap_register_option(c, COAP_OPTION_IF_MATCH);
-    coap_register_option(c, COAP_OPTION_URI_HOST);
-    coap_register_option(c, COAP_OPTION_IF_NONE_MATCH);
-    coap_register_option(c, COAP_OPTION_URI_PORT);
-    coap_register_option(c, COAP_OPTION_URI_PATH);
-    coap_register_option(c, COAP_OPTION_URI_QUERY);
-    coap_register_option(c, COAP_OPTION_ACCEPT);
-    coap_register_option(c, COAP_OPTION_PROXY_URI);
-    coap_register_option(c, COAP_OPTION_PROXY_SCHEME);
-    coap_register_option(c, COAP_OPTION_BLOCK2);
-    coap_register_option(c, COAP_OPTION_BLOCK1);
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-    if (OCInitUDP((OCDevAddr *)listen_addr,
-                    (int32_t *)&(c->sockfd), OC_SOCKET_REUSEADDR) != ERR_SUCCESS) {
-        coap_free( c);
-        return NULL;
-    }
-
-#if defined(WITH_DTLS)
-    if (coap_dtls_init(c, ipAddr) != 0) {
-        coap_free( c);
-        return NULL;
-    }
-#else
-    /* set dtls socket file descriptor to uninitialize value  */
-    c->sockfd_dtls = -1;
-#endif /* WITH_DTLS */
-    return c;
-
-#endif /* WITH_POSIX || WITH_ARDUINO */
-#ifdef WITH_CONTIKI
-    c->conn = udp_new(NULL, 0, NULL);
-    udp_bind(c->conn, listen_addr->port);
-
-    process_start(&coap_retransmit_process, (char *)c);
-
-    PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
-#ifndef WITHOUT_OBSERVE
-    etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
-#endif /* WITHOUT_OBSERVE */
-    /* the retransmit timer must be initialized to some large value */
-    etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
-    PROCESS_CONTEXT_END(&coap_retransmit_process);
-    return c;
-#endif /* WITH_CONTIKI */
-#ifdef WITH_LWIP
-    c->pcb = udp_new();
-    /* hard assert: this is not expected to fail dynamically */
-    LWIP_ASSERT("Failed to allocate PCB for CoAP", c->pcb != NULL);
-
-    udp_recv(c->pcb, received_package, (void*)c);
-    udp_bind(c->pcb, &listen_addr->addr, listen_addr->port);
-
-    c->timer_configured = 0;
-
-    return c;
-#endif
-    return NULL;
-}
-
-void coap_free_context(coap_context_t *context) {
-    if (!context)
-        return;
-
-    coap_delete_all(context->recvqueue);
-    coap_delete_all(context->sendqueue);
-
-#ifdef WITH_LWIP
-    context->sendqueue = NULL;
-    coap_retransmittimer_restart(context);
-#endif
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-    /* coap_delete_list(context->subscriptions); */
-    OCClose( context->sockfd );
-    if (context->sockfd_wellknown != -1) {
-        OCClose( context->sockfd_wellknown );
-    }
-#if defined(WITH_DTLS)
-    coap_dtls_deinit( context );
-#endif /* WITH_DTLS */
-    coap_free( context );
-#endif
-#ifdef WITH_LWIP
-    udp_remove(context->pcb);
-    memp_free(MEMP_COAP_CONTEXT, context);
-#endif
-#ifdef WITH_CONTIKI
-    memset(&the_coap_context, 0, sizeof(coap_context_t));
-    initialized = 0;
-#endif /* WITH_CONTIKI */
-}
-
-int coap_join_wellknown_group(coap_context_t *ctx,
-        const coap_address_t *multicast_addr) {
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-    if (OCInitUDPMulticast((OCDevAddr *)multicast_addr,
-                    (int32_t *)&(ctx->sockfd_wellknown)) != ERR_SUCCESS) {
-        return 1;
-    }
-    return 0;
-#endif
-    return 0;
-}
-
-int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu,
-        coap_opt_filter_t unknown) {
-
-    coap_opt_iterator_t opt_iter;
-    int ok = 1;
-
-    coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
-
-    while (coap_option_next(&opt_iter)) {
-
-        /* The following condition makes use of the fact that
-         * coap_option_getb() returns -1 if type exceeds the bit-vector
-         * filter. As the vector is supposed to be large enough to hold
-         * the largest known option, we know that everything beyond is
-         * bad.
-         */
-        if ((opt_iter.type & 0x01)
-                && coap_option_getb(ctx->known_options, opt_iter.type) < 1) {
-            debug("unknown critical option %d\n", opt_iter.type);
-
-            ok = 0;
-
-            /* When opt_iter.type is beyond our known option range,
-             * coap_option_setb() will return -1 and we are safe to leave
-             * this loop. */
-            if (coap_option_setb(unknown, opt_iter.type) == -1)
-                break;
-        }
-    }
-
-    return ok;
-}
-
-void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu,
-        coap_tid_t *id) {
-    coap_key_t h;
-
-    memset(h, 0, sizeof(coap_key_t));
-
-    /* Compare the complete address structure in case of IPv4. For IPv6,
-     * we need to look at the transport address only. */
-
-#ifdef WITH_POSIX
-    switch (peer->addr.sa.sa_family) {
-        case AF_INET:
-        coap_hash((const unsigned char *)&peer->addr.sa, peer->size, h);
-        break;
-        case AF_INET6:
-        coap_hash((const unsigned char *)&peer->addr.sin6.sin6_port,
-                sizeof(peer->addr.sin6.sin6_port), h);
-        coap_hash((const unsigned char *)&peer->addr.sin6.sin6_addr,
-                sizeof(peer->addr.sin6.sin6_addr), h);
-        break;
-        default:
-        return;
-    }
-#endif
-
-#ifdef WITH_ARDUINO
-    coap_hash((const unsigned char *)peer->addr, peer->size, h);
-#endif /* WITH_ARDUINO */
-
-#if defined(WITH_LWIP) || defined(WITH_CONTIKI)
-    /* FIXME: with lwip, we can do better */
-    coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h);
-    coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h);
-#endif /* WITH_LWIP || WITH_CONTIKI */
-
-    coap_hash((const unsigned char * )&pdu->hdr->id, sizeof(unsigned short), h);
-
-    *id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]);
-}
-
-coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst,
-        coap_pdu_t *request, coap_send_flags_t flag) {
-    coap_pdu_t *response;
-    coap_tid_t result = COAP_INVALID_TID;
-
-    if (request && request->hdr->type == COAP_MESSAGE_CON) {
-        response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->id,
-                sizeof(coap_pdu_t));
-        if (response) {
-            result = coap_send(context, dst, response, flag, NULL);
-            coap_delete_pdu(response);
-        }
-    }
-    return result;
-}
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-/* releases space allocated by PDU if free_pdu is set */
-int
-coap_send_impl(coap_context_t *context,
-        const coap_address_t *dst,
-        coap_pdu_t *pdu) {
-
-    int bytes_written = -1;
-
-    if ( !context || !dst || !pdu )
-    return bytes_written;
-
-    bytes_written = OCSendTo( context->sockfd, (uint8_t*)(pdu->hdr), pdu->length, 0,
-            (OCDevAddr*)dst);
-    debug("bytes_written %d\n", (int)bytes_written);
-
-    return bytes_written;
-}
-#endif /* WITH_POSIX || WITH_ARDUINO */
-#ifdef WITH_CONTIKI
-/* releases space allocated by PDU if free_pdu is set */
-coap_tid_t
-coap_send_impl(coap_context_t *context,
-        const coap_address_t *dst,
-        coap_pdu_t *pdu) {
-    coap_tid_t id = COAP_INVALID_TID;
-
-    if ( !context || !dst || !pdu )
-    return id;
-
-    /* FIXME: is there a way to check if send was successful? */
-    uip_udp_packet_sendto(context->conn, pdu->hdr, pdu->length,
-            &dst->addr, dst->port);
-
-    coap_transaction_id(dst, pdu, &id);
-
-    return id;
-}
-#endif /* WITH_CONTIKI */
-#ifdef WITH_LWIP
-coap_tid_t
-coap_send_impl(coap_context_t *context,
-        const coap_address_t *dst,
-        coap_pdu_t *pdu) {
-    coap_tid_t id = COAP_INVALID_TID;
-    struct pbuf *p;
-    uint8_t err;
-    char *data_backup;
-
-    if ( !context || !dst || !pdu )
-    {
-        return id;
-    }
-
-    data_backup = pdu->data;
-
-    /* FIXME: we can't check this here with the existing infrastructure, but we
-     * should actually check that the pdu is not held by anyone but us. the
-     * respective pbuf is already exclusively owned by the pdu. */
-
-    p = pdu->pbuf;
-    LWIP_ASSERT("The PDU header is not where it is expected", pdu->hdr == p->payload + sizeof(coap_pdu_t));
-
-    err = pbuf_header(p, -sizeof(coap_pdu_t));
-    if (err)
-    {
-        debug("coap_send_impl: pbuf_header failed\n");
-        pbuf_free(p);
-        return id;
-    }
-
-    coap_transaction_id(dst, pdu, &id);
-
-    pbuf_realloc(p, pdu->length);
-
-    udp_sendto(context->pcb, p,
-            &dst->addr, dst->port);
-
-    pbuf_header(p, -(ptrdiff_t)((uint8_t*)pdu - (uint8_t*)p->payload) - sizeof(coap_pdu_t)); /* FIXME hack around udp_sendto not restoring; see http://lists.gnu.org/archive/html/lwip-users/2013-06/msg00008.html. for udp over ip over ethernet, this was -42; as we're doing ppp too, this has to be calculated generically */
-
-    err = pbuf_header(p, sizeof(coap_pdu_t));
-    LWIP_ASSERT("Cannot undo pbuf_header", err == 0);
-
-    /* restore destroyed pdu data */
-    LWIP_ASSERT("PDU not restored", p->payload == pdu);
-    pdu->max_size = p->tot_len - sizeof(coap_pdu_t); /* reduced after pbuf_realloc */
-    pdu->hdr = p->payload + sizeof(coap_pdu_t);
-    pdu->max_delta = 0; /* won't be used any more */
-    pdu->length = pdu->max_size;
-    pdu->data = data_backup;
-    pdu->pbuf = p;
-
-    return id;
-}
-#endif /* WITH_LWIP */
-
-coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request,
-        const coap_address_t *dst, unsigned char code, coap_opt_filter_t opts,
-        coap_send_flags_t flag) {
-    coap_pdu_t *response;
-    coap_tid_t result = COAP_INVALID_TID;
-
-    assert(request);
-    assert(dst);
-
-    response = coap_new_error_response(request, code, opts);
-    if (response) {
-        result = coap_send(context, dst, response, flag, NULL);
-        coap_delete_pdu(response);
-    }
-
-    return result;
-}
-
-coap_tid_t coap_send_message_type(coap_context_t *context,
-        const coap_address_t *dst, coap_pdu_t *request,
-        coap_send_flags_t flag, unsigned char type) {
-    coap_pdu_t *response;
-    coap_tid_t result = COAP_INVALID_TID;
-
-    if (request) {
-        response = coap_pdu_init(type, 0, request->hdr->id, sizeof(coap_pdu_t));
-        if (response) {
-            result = coap_send(context, dst, response, flag, NULL);
-            coap_delete_pdu(response);
-        }
-    }
-    return result;
-}
-
-coap_tid_t coap_send(coap_context_t *context,
-        const coap_address_t *dst, coap_pdu_t *pdu, coap_send_flags_t flag,
-        uint8_t *cache_flag)
-{
-    coap_queue_t *node = NULL;
-    coap_tick_t now;
-    coap_tid_t tid;
-    int bytesWritten;
-    unsigned int r;
-
-    if (!context)
-        return COAP_INVALID_TID;
-    if(!(flag & SEND_RETX)){
-        coap_transaction_id(dst, pdu, &tid);
-    }
-    if((flag & SEND_NOW) || (flag & SEND_RETX))
-    {
-        goto sending;
-    }
-
-    node = coap_new_node();
-    if (!node) {
-        debug("coap_send: insufficient memory\n");
-        return COAP_INVALID_TID;
-    }
-
-    prng((unsigned char * )&r, sizeof(r));
-    /* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
-    if(flag & SEND_NOW_CON) {
-        node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND
-                + (COAP_DEFAULT_RESPONSE_TIMEOUT >> 1)
-                * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
-    }
-    else
-    {
-        node->timeout = MAX_MULTICAST_DELAY_SEC * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
-        node->delayedResNeeded = 1;
-    }
-
-    if (flag & SEND_SECURE_PORT) {
-        node->secure = 1;
-    }
-
-    memcpy(&node->remote, dst, sizeof(coap_address_t));
-    node->pdu = pdu;
-    node->id = tid;
-
-    /* Set timer for pdu retransmission. If this is the first element in
-     * the retransmission queue, the base time is set to the current
-     * time and the retransmission time is node->timeout. If there is
-     * already an entry in the sendqueue, we must check if this node is
-     * to be retransmitted earlier. Therefore, node->timeout is first
-     * normalized to the base time and then inserted into the queue with
-     * an adjusted relative time.
-     */
-
-    coap_ticks(&now);
-    if (context->sendqueue == NULL)
-    {
-        node->t = node->timeout;
-        context->sendqueue_basetime = now;
-    }
-    else
-    {
-        /* make node->t relative to context->sendqueue_basetime */
-        node->t = (now - context->sendqueue_basetime) + node->timeout;
-    }
-    coap_insert_node(&context->sendqueue, node);
-
-    #ifdef WITH_LWIP
-        if (node == context->sendqueue)
-            /* don't bother with timer stuff if there are earlier retransmits */
-            coap_retransmittimer_restart(context);
-    #endif
-
-    #ifdef WITH_CONTIKI
-    { /* (re-)initialize retransmission timer */
-        coap_queue_t *nextpdu;
-
-        nextpdu = coap_peek_next(context);
-        assert(nextpdu); /* we have just inserted a node */
-
-        /* must set timer within the context of the retransmit process */
-        PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
-        etimer_set(&context->retransmit_timer, nextpdu->t);
-        PROCESS_CONTEXT_END(&coap_retransmit_process);
-    }
-    #endif /* WITH_CONTIKI */
-
-    if(flag & SEND_NOW_CON)
-    {
-        goto sending;
-    }
-    return tid;
-
-    sending:
-        OC_LOG_V(DEBUG, MOD_NAME, PCF("sending 0x%x"), flag);
-#if defined(WITH_DTLS)
-        // A secure packet is first encrypted by DTLS library and then send
-        // over the network.
-        if (flag & SEND_SECURE_PORT) {
-            bytesWritten = coap_dtls_encrypt(context, (OCDevAddr*)dst,
-                            pdu, &node, tid, cache_flag);
-        } else {
-            bytesWritten = coap_send_impl(context, dst, pdu);
-        }
-#else
-        bytesWritten = coap_send_impl(context, dst, pdu);
-#endif /* WITH_DTLS */
-        if(bytesWritten > 0) {
-            return tid;
-        }
-        debug("coap_send_impl: error sending pdu\n");
-        coap_free_node(node);
-        return COAP_INVALID_TID;
-}
-
-coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node) {
-    coap_tid_t tid = COAP_INVALID_TID;
-    coap_send_flags_t flag;
-
-    if (!context || !node)
-        return COAP_INVALID_TID;
-
-    /* re-initialize timeout when maximum number of retransmissions are not reached yet */
-    if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) {
-        node->retransmit_cnt++;
-        node->t = node->timeout << node->retransmit_cnt;
-        coap_insert_node(&context->sendqueue, node);
-#ifdef WITH_LWIP
-        if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
-        coap_retransmittimer_restart(context);
-#endif
-
-        debug("** retransmission #%d of transaction %d\n", node->retransmit_cnt,
-            ntohs(node->pdu->hdr->id));
-        flag = (coap_send_flags_t)(SEND_RETX | (node->secure ? SEND_SECURE_PORT : 0));
-        tid = coap_send(context, (coap_address_t *)&(node->remote),node->pdu, flag, NULL);
-        return (tid == COAP_INVALID_TID)? COAP_INVALID_TID : node->id;
-    }
-
-    /* no more retransmissions, remove node from system */
-
-#ifndef WITH_CONTIKI
-    debug("** removed transaction %d\n", ntohs(node->id));
-#endif
-
-    // deletion of node will happen in ocoap since we still need the info node has
-    return COAP_INVALID_TID;
-}
-
-/**
- * Checks if @p opt fits into the message that ends with @p maxpos.
- * This function returns @c 1 on success, or @c 0 if the option @p opt
- * would exceed @p maxpos.
- */
-static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos) {
-    if (opt && opt < maxpos) {
-        if (((*opt & 0x0f) < 0x0f) || (opt + 1 < maxpos))
-            return opt + COAP_OPT_SIZE(opt) < maxpos;
-    }
-    return 0;
-}
-
-int coap_read(coap_context_t *ctx, int sockfd) {
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-    static char buf[COAP_MAX_PDU_SIZE];
-#endif
-#if defined(WITH_LWIP) || defined(WITH_CONTIKI)
-    char *buf;
-#endif
-  char *pbuf = buf;
-  coap_hdr_t *pdu;
-  int bytes_read = -1;
-
-  coap_address_t src, dst;
-  coap_queue_t *node;
-  unsigned char delayedResNeeded = 0;
-
-#ifdef WITH_CONTIKI
-    pbuf = uip_appdata;
-#endif /* WITH_CONTIKI */
-#ifdef WITH_LWIP
-    LWIP_ASSERT("No package pending", ctx->pending_package != NULL);
-    LWIP_ASSERT("Can only deal with contiguous PBUFs to read the initial details", ctx->pending_package->tot_len == ctx->pending_package->len);
-    pbuf = ctx->pending_package->payload;
-#endif /* WITH_LWIP */
-
-    coap_address_init(&src);
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-  bytes_read = OCRecvFrom( sockfd, (uint8_t*)pbuf, sizeof(buf), 0,
-              (OCDevAddr*)&src);
-
-  // Set the delayed response flag for responding to multicast requests
-  if (sockfd == ctx->sockfd_wellknown && bytes_read > 0) {
-      delayedResNeeded = 1;
-  }
-#if defined(WITH_DTLS)
-  // Perform the DTLS decryption if packet is coming on secure port
-  if (sockfd == ctx->sockfd_dtls && bytes_read > 0) {
-      if (coap_dtls_decrypt(ctx, (OCDevAddr*)&src, (uint8_t*)pbuf, bytes_read,
-            (uint8_t**)&pbuf, &bytes_read) < 0) {
-            bytes_read = -1;
-      }
-  }
-#endif /* WITH_DTLS */
-
-  pdu = (coap_hdr_t *) pbuf;
-#endif /* WITH_POSIX || WITH_ARDUINO */
-#ifdef WITH_CONTIKI
-    if(uip_newdata()) {
-        uip_ipaddr_copy(&src.addr, &UIP_IP_BUF->srcipaddr);
-        src.port = UIP_UDP_BUF->srcport;
-        uip_ipaddr_copy(&dst.addr, &UIP_IP_BUF->destipaddr);
-        dst.port = UIP_UDP_BUF->destport;
-
-        bytes_read = uip_datalen();
-        ((char *)uip_appdata)[bytes_read] = 0;
-        PRINTF("Server received %d bytes from [", (int)bytes_read);
-        PRINT6ADDR(&src.addr);
-        PRINTF("]:%d\n", uip_ntohs(src.port));
-    }
-#endif /* WITH_CONTIKI */
-#ifdef WITH_LWIP
-    /* FIXME: use lwip address operation functions */
-    src.addr.addr = ctx->pending_address.addr;
-    src.port = ctx->pending_port;
-    bytes_read = ctx->pending_package->tot_len;
-#endif /* WITH_LWIP */
-
-    if (bytes_read < 0) {
-        warn("coap_read: recvfrom\n");
-        goto error_early;
-    }
-
-    if ((size_t) bytes_read < sizeof(coap_hdr_t)) {
-        debug("coap_read: discarded invalid frame\n");
-        goto error_early;
-    }
-
-    if (pdu->version != COAP_DEFAULT_VERSION) {
-        debug("coap_read: unknown protocol version\n");
-        goto error_early;
-    }
-
-    node = coap_new_node();
-    if (!node)
-        goto error_early;
-
-#ifdef WITH_LWIP
-    node->pdu = coap_pdu_from_pbuf(ctx->pending_package);
-    ctx->pending_package = NULL;
-#else
-    node->pdu = coap_pdu_init(0, 0, 0, bytes_read);
-#endif
-    if (!node->pdu)
-        goto error;
-
-    coap_ticks(&node->t);
-    memcpy(&node->local, &dst, sizeof(coap_address_t));
-    memcpy(&node->remote, &src, sizeof(coap_address_t));
-
-    if (!coap_pdu_parse((unsigned char *) pbuf, bytes_read, node->pdu)) {
-        warn("discard malformed PDU");
-        goto error;
-    }
-
-    //set the delayed response flag
-    node->delayedResNeeded = delayedResNeeded;
-
-    //set the secure flag on the received packet
-#if defined(WITH_DTLS)
-    node->secure = (sockfd == ctx->sockfd_dtls) ? 1 : 0;
-#else
-    node->secure = 0;
-#endif /* WITH_DTLS */
-
-    /* and add new node to receive queue */
-    coap_transaction_id(&node->remote, node->pdu, &node->id);
-    coap_insert_node(&ctx->recvqueue, node);
-
-#ifndef NDEBUG
-    if (LOG_DEBUG <= coap_get_log_level()) {
-#ifndef INET6_ADDRSTRLEN
-#define INET6_ADDRSTRLEN 40
-#endif
-        unsigned char addr[INET6_ADDRSTRLEN + 8];
-
-        if (coap_print_addr(&src, addr, INET6_ADDRSTRLEN + 8))
-            debug("** received %d bytes from %s:\n", (int )bytes_read, addr);
-
-        coap_show_pdu(node->pdu);
-    }
-#endif
-
-    return bytes_read;
-
-    error:
-    /* FIXME: send back RST? */
-    coap_delete_node(node);
-    return bytes_read;
-    error_early:
-#ifdef WITH_LWIP
-    /* even if there was an error, clean up */
-    pbuf_free(ctx->pending_package);
-    ctx->pending_package = NULL;
-#endif
-    return bytes_read;
-}
-
-int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id,
-        coap_queue_t **node) {
-    coap_queue_t *p, *q;
-
-    if (!queue || !*queue)
-        return 0;
-    debug("*** looking for transaction %u == %u\n", id, (*queue)->id);
-
-    /* replace queue head if PDU's time is less than head's time */
-    if (id == (*queue)->id) { /* found transaction */
-        *node = *queue;
-        *queue = (*queue)->next;
-        if (*queue) { /* adjust relative time of new queue head */
-            (*queue)->t += (*node)->t;
-        }
-        (*node)->next = NULL;
-        /* coap_delete_node( q ); */
-        debug("*** removed transaction %u\n", id);
-        return 1;
-    }
-
-    /* search transaction to remove (only first occurence will be removed) */
-    q = *queue;
-    do {
-        p = q;
-        q = q->next;
-    } while (q && id != q->id);
-
-    if (q) { /* found transaction */
-        p->next = q->next;
-        if (p->next) { /* must update relative time of p->next */
-            p->next->t += q->t;
-        }
-        q->next = NULL;
-        *node = q;
-        /* coap_delete_node( q ); */
-        debug("*** removed transaction %u\n", id);
-        return 1;
-    }
-
-    return 0;
-
-}
-
-static inline int token_match(const unsigned char *a, size_t alen,
-        const unsigned char *b, size_t blen) {
-    return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
-}
-
-void coap_cancel_all_messages(coap_context_t *context,
-        const coap_address_t *dst, const unsigned char *token,
-        size_t token_length) {
-    /* cancel all messages in sendqueue that are for dst
-     * and use the specified token */
-    coap_queue_t *p, *q;
-
-    debug("cancel_all_messages\n");
-    while (context->sendqueue
-            && coap_address_equals(dst, &context->sendqueue->remote)
-            && token_match(token, token_length,
-                    context->sendqueue->pdu->hdr->token,
-                    context->sendqueue->pdu->hdr->token_length)) {
-        q = context->sendqueue;
-        context->sendqueue = q->next;
-        debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
-        coap_delete_node(q);
-    }
-
-    if (!context->sendqueue)
-        return;
-
-    p = context->sendqueue;
-    q = p->next;
-
-    /* when q is not NULL, it does not match (dst, token), so we can skip it */
-    while (q) {
-        if (coap_address_equals(dst, &q->remote)
-                && token_match(token, token_length, q->pdu->hdr->token,
-                        q->pdu->hdr->token_length)) {
-            p->next = q->next;
-            debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
-            coap_delete_node(q);
-            q = p->next;
-        } else {
-            p = q;
-            q = q->next;
-        }
-    }
-}
-
-coap_queue_t *
-coap_find_transaction(coap_queue_t *queue, coap_tid_t id) {
-    while (queue && queue->id != id)
-        queue = queue->next;
-
-    return queue;
-}
-
-coap_pdu_t *
-coap_new_error_response(coap_pdu_t *request, unsigned char code,
-        coap_opt_filter_t opts) {
-    coap_opt_iterator_t opt_iter;
-    coap_pdu_t *response;
-    size_t size = sizeof(coap_hdr_t) + request->hdr->token_length;
-    int type;
-    coap_opt_t *option;
-    unsigned short opt_type = 0; /* used for calculating delta-storage */
-
-#if COAP_ERROR_PHRASE_LENGTH > 0
-  const char *phrase = coap_response_phrase(code);
-
-    /* Need some more space for the error phrase and payload start marker */
-    if (phrase)
-        size += strlen(phrase) + 1;
-#endif
-
-    assert(request);
-
-    /* cannot send ACK if original request was not confirmable */
-    type = request->hdr->type == COAP_MESSAGE_CON ?
-            COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
-
-    /* Estimate how much space we need for options to copy from
-     * request. We always need the Token, for 4.02 the unknown critical
-     * options must be included as well. */
-    coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */
-
-    coap_option_iterator_init(request, &opt_iter, opts);
-
-    /* Add size of each unknown critical option. As known critical
-     options as well as elective options are not copied, the delta
-     value might grow.
-     */
-    while ((option = coap_option_next(&opt_iter))) {
-        unsigned short delta = opt_iter.type - opt_type;
-        /* calculate space required to encode (opt_iter.type - opt_type) */
-        if (delta < 13) {
-            size++;
-        } else if (delta < 269) {
-            size += 2;
-        } else {
-            size += 3;
-        }
-
-        /* add coap_opt_length(option) and the number of additional bytes
-         * required to encode the option length */
-
-        size += coap_opt_length(option);
-        switch (*option & 0x0f) {
-        case 0x0e:
-            size++;
-            /* fall through */
-            continue;
-        case 0x0d:
-            size++;
-            break;
-        default:
-            ;
-        }
-
-        opt_type = opt_iter.type;
-    }
-
-    /* Now create the response and fill with options and payload data. */
-    response = coap_pdu_init(type, code, request->hdr->id, size);
-    if (response) {
-        /* copy token */
-        if (!coap_add_token(response, request->hdr->token_length,
-                request->hdr->token)) {
-            debug("cannot add token to error response\n");
-            coap_delete_pdu(response);
-            return NULL;
-        }
-
-        /* copy all options */
-        coap_option_iterator_init(request, &opt_iter, opts);
-        while ((option = coap_option_next(&opt_iter)))
-            coap_add_option(response, opt_iter.type, COAP_OPT_LENGTH(option),
-                    COAP_OPT_VALUE(option));
-
-#if COAP_ERROR_PHRASE_LENGTH > 0
-        /* note that diagnostic messages do not need a Content-Format option. */
-        if (phrase)
-            coap_add_data(response, strlen(phrase), (unsigned char *) phrase);
-#endif
-    }
-
-    return response;
-}
-
-
-#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
-
-#define WANT_WKC(Pdu,Key)                   \
-  (((Pdu)->hdr->code == COAP_REQUEST_GET) && is_wkc(Key))
-
-/************************************************************************************************
- * Following code will be moved to newer handle_request in the future and kept for reference
- ************************************************************************************************/
-#if 0
-void
-handle_request(coap_context_t *context, coap_queue_t *node) {
-    coap_method_handler_t h = NULL;
-    coap_pdu_t *response = NULL;
-    coap_opt_filter_t opt_filter;
-    coap_resource_t *resource;
-    coap_key_t key;
-
-    coap_option_filter_clear(opt_filter);
-
-    /* try to find the resource from the request URI */
-    coap_hash_request_uri(node->pdu, key);
-    resource = coap_get_resource_from_key(context, key);
-
-    if (!resource) {
-        /* The resource was not found. Check if the request URI happens to
-         * be the well-known URI. In that case, we generate a default
-         * response, otherwise, we return 4.04 */
-
-        switch(node->pdu->hdr->code) {
-
-            case COAP_REQUEST_GET:
-            if (is_wkc(key)) { /* GET request for .well-known/core */
-                info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
-                response = wellknown_response(context, node->pdu);
-
-            } else { /* GET request for any another resource, return 4.04 */
-
-                debug("GET for unknown resource 0x%02x%02x%02x%02x, return 4.04\n",
-                        key[0], key[1], key[2], key[3]);
-                response =
-                coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(404),
-                        opt_filter);
-            }
-            break;
-
-            default: /* any other request type */
-
-            debug("unhandled request for unknown resource 0x%02x%02x%02x%02x\r\n",
-                    key[0], key[1], key[2], key[3]);
-            if (!coap_is_mcast(&node->local))
-            response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405),
-                    opt_filter);
-        }
-
-        if (response && coap_send(context, &node->remote, response) == COAP_INVALID_TID) {
-            warn("cannot send response for transaction %u\n", node->id);
-        }
-        coap_delete_pdu(response);
-
-        return;
-    }
-
-    /* the resource was found, check if there is a registered handler */
-    if ((size_t)node->pdu->hdr->code - 1 <
-            sizeof(resource->handler)/sizeof(coap_method_handler_t))
-    h = resource->handler[node->pdu->hdr->code - 1];
-
-    if (h) {
-        debug("call custom handler for resource 0x%02x%02x%02x%02x\n",
-                key[0], key[1], key[2], key[3]);
-        response = coap_pdu_init(node->pdu->hdr->type == COAP_MESSAGE_CON
-                ? COAP_MESSAGE_ACK
-                : COAP_MESSAGE_NON,
-                0, node->pdu->hdr->id, COAP_MAX_PDU_SIZE);
-
-        /* Implementation detail: coap_add_token() immediately returns 0
-         if response == NULL */
-        if (coap_add_token(response, node->pdu->hdr->token_length,
-                        node->pdu->hdr->token)) {
-            str token = {node->pdu->hdr->token_length, node->pdu->hdr->token};
-
-            h(context, resource, &node->remote,
-                    node->pdu, &token, response);
-            if (response->hdr->type != COAP_MESSAGE_NON ||
-                    (response->hdr->code >= 64
-                            && !coap_is_mcast(&node->local))) {
-                if (coap_send(context, &node->remote, response) == COAP_INVALID_TID) {
-                    debug("cannot send response for message %d\n", node->pdu->hdr->id);
-                }
-            }
-
-            coap_delete_pdu(response);
-        } else {
-            warn("cannot generate response\r\n");
-        }
-    } else {
-        if (WANT_WKC(node->pdu, key)) {
-            debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
-            response = wellknown_response(context, node->pdu);
-        } else
-        response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405),
-                opt_filter);
-
-        if (!response || (coap_send(context, &node->remote, response)
-                        == COAP_INVALID_TID)) {
-            debug("cannot send response for transaction %u\n", node->id);
-        }
-        coap_delete_pdu(response);
-    }
-}
-#endif
-static void handle_request(coap_context_t *context, coap_queue_t *rcvd) {
-    /* Call application-specific reponse handler when available.  If
-     * not, we must acknowledge confirmable messages. */
-    if (context->request_handler) {
-        context->request_handler(context, rcvd);
-    } else {
-        coap_send_flags_t flag = SEND_NOW;
-        flag = (coap_send_flags_t)(flag | (rcvd->secure ? SEND_SECURE_PORT : 0));
-        /* send ACK if rcvd is confirmable (i.e. a separate response) */
-        coap_send_ack(context, &rcvd->remote, rcvd->pdu, flag);
-    }
-}
-
-static void handle_response(coap_context_t *context, coap_queue_t *rcvd) {
-    /* Call application-specific reponse handler when available.  If
-     * not, we must acknowledge confirmable messages. */
-    if (context->response_handler) {
-        context->response_handler(context, rcvd);
-    } else {
-        coap_send_flags_t flag = SEND_NOW;
-        flag = (coap_send_flags_t)(flag | (rcvd->secure ? SEND_SECURE_PORT : 0));
-        /* send ACK if rcvd is confirmable (i.e. a separate response) */
-        coap_send_ack(context, &rcvd->remote, rcvd->pdu, flag);
-    }
-}
-
-static void handle_ack_rst(coap_context_t *context, uint8_t msgType, coap_queue_t *sent) {
-    /* Call application-specific reponse handler when available.  If
-     * not, we must acknowledge confirmable messages. */
-    if (context->ack_rst_handler) {
-        context->ack_rst_handler(context, msgType, sent);
-    }
-}
-
-static inline int
-#ifdef __GNUC__
-handle_locally(coap_context_t *context __attribute__ ((unused)),
-        coap_queue_t *node __attribute__ ((unused))) {
-#else /* not a GCC */
-    handle_locally(coap_context_t *context, coap_queue_t *node) {
-#endif /* GCC */
-        /* this function can be used to check if node->pdu is really for us */
-        return 1;
-    }
-
-    void coap_dispatch(coap_context_t *context) {
-        coap_queue_t *rcvd = NULL, *sent = NULL;
-        coap_pdu_t *response;
-        coap_opt_filter_t opt_filter;
-
-        if (!context)
-            return;
-
-        memset(opt_filter, 0, sizeof(coap_opt_filter_t));
-
-        while (context->recvqueue) {
-            rcvd = context->recvqueue;
-
-            /* remove node from recvqueue */
-            context->recvqueue = context->recvqueue->next;
-            rcvd->next = NULL;
-
-            if (rcvd->pdu->hdr->version != COAP_DEFAULT_VERSION) {
-                debug("dropped packet with unknown version %u\n",
-                        rcvd->pdu->hdr->version);
-                goto cleanup;
-            }
-
-            switch (rcvd->pdu->hdr->type) {
-            case COAP_MESSAGE_ACK:
-                /* find transaction in sendqueue to stop retransmission */
-                if(coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent)){
-                    handle_ack_rst(context, COAP_MESSAGE_ACK, sent);
-                }
-
-                //delete empty messages, this is ACK only message no piggybacked response
-                if (rcvd->pdu->hdr->code == 0)
-                    goto cleanup;
-                break;
-
-            case COAP_MESSAGE_NON: /* check for unknown critical options */
-                if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
-                        == 0)
-                    goto cleanup;
-                break;
-
-            case COAP_MESSAGE_CON: /* check for unknown critical options */
-                if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
-                        == 0) {
-                    /* FIXME: send response only if we have received a request. Otherwise,
-                     * send RST. */
-                    response = coap_new_error_response(rcvd->pdu,
-                            COAP_RESPONSE_CODE(402), opt_filter);
-                    if (!response)
-                        warn("coap_dispatch: cannot create error reponse\n");
-                    else {
-                        coap_send_flags_t flag = SEND_NOW;
-                        flag = (coap_send_flags_t)(flag | rcvd->secure ? SEND_SECURE_PORT : 0);
-                        if (coap_send(context, &rcvd->remote, response, flag, NULL)
-                                == COAP_INVALID_TID) {
-                            warn("coap_dispatch: error sending reponse\n");
-                        }
-                        coap_delete_pdu(response);
-                    }
-                    goto cleanup;
-                }
-                break;
-
-            case COAP_MESSAGE_RST:
-                /* find transaction in sendqueue to stop retransmission */
-                if(coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent)){
-                    handle_ack_rst(context, COAP_MESSAGE_RST, sent);
-                }
-                goto cleanup;
-                break;
-
-            default:
-                debug(
-                        "TODO: Need to handle other message types in coap_dispatch");
-            }
-
-            /************************************************************************************************
-             * Following code will be replaced at different parts of the stack
-             ************************************************************************************************/
-#if 0
-            switch (rcvd->pdu->hdr->type) {
-                case COAP_MESSAGE_ACK:
-                /* find transaction in sendqueue to stop retransmission */
-                coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
-
-                if (rcvd->pdu->hdr->code == 0)
-                goto cleanup;
-
-                /* FIXME: if sent code was >= 64 the message might have been a
-                 * notification. Then, we must flag the observer to be alive
-                 * by setting obs->fail_cnt = 0. */
-                if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->code) == 2) {
-                    const str token = {sent->pdu->hdr->token_length,
-                        sent->pdu->hdr->token};
-                    coap_touch_observer(context, &sent->remote, &token);
-                }
-                break;
-
-                case COAP_MESSAGE_RST:
-                /* We have sent something the receiver disliked, so we remove
-                 * not only the transaction but also the subscriptions we might
-                 * have. */
-
-                coap_log(LOG_ALERT, "got RST for message %u\n",
-                        ntohs(rcvd->pdu->hdr->id));
-
-                /* find transaction in sendqueue to stop retransmission */
-                coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
-
-                if (sent)
-                coap_handle_rst(context, sent);
-                goto cleanup;
-
-                case COAP_MESSAGE_NON: /* check for unknown critical options */
-                if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
-                        == 0)
-                goto cleanup;
-                break;
-
-                case COAP_MESSAGE_CON: /* check for unknown critical options */
-                if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
-                        == 0) {
-
-                    /* FIXME: send response only if we have received a request. Otherwise,
-                     * send RST. */
-                    response = coap_new_error_response(rcvd->pdu,
-                            COAP_RESPONSE_CODE(402), opt_filter);
-
-                    if (!response)
-                    warn("coap_dispatch: cannot create error reponse\n");
-                    else {
-                        if (coap_send(context, &rcvd->remote,
-                                        response) == COAP_INVALID_TID) {
-                            warn("coap_dispatch: error sending reponse\n");
-                        }
-                        coap_delete_pdu(response);
-                    }
-
-                    goto cleanup;
-                }
-                break;
-            }
-#endif
-
-            /* Pass message to upper layer if a specific handler was
-             * registered for a request that should be handled locally. */
-            if (handle_locally(context, rcvd)) {
-                if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->hdr)){
-                    handle_request(context, rcvd);
-                }
-                else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->hdr)){
-                    handle_response(context, rcvd);
-                }
-                else {
-                    coap_send_flags_t flag;
-                    flag = (coap_send_flags_t)(SEND_NOW |
-                            (rcvd->secure ? SEND_SECURE_PORT : 0));
-                    debug("dropped message with invalid code\n");
-                    coap_send_message_type(context, &rcvd->remote, rcvd->pdu,
-                            flag, COAP_MESSAGE_RST);
-                }
-            }
-
-            // we should not retry responses.....
-            cleanup:
-                coap_delete_node(sent);
-                sent = NULL;
-                coap_delete_node(rcvd);
-                rcvd = NULL;
-        }
-    }
-
-    int coap_can_exit(coap_context_t *context) {
-        return !context
-                || (context->recvqueue == NULL && context->sendqueue == NULL);
-    }
-
-#ifdef WITH_CONTIKI
-
-    /*---------------------------------------------------------------------------*/
-    /* CoAP message retransmission */
-    /*---------------------------------------------------------------------------*/
-    PROCESS_THREAD(coap_retransmit_process, ev, data)
-    {
-        coap_tick_t now;
-        coap_queue_t *nextpdu;
-
-        PROCESS_BEGIN();
-
-        debug("Started retransmit process\r\n");
-
-        while(1) {
-            PROCESS_YIELD();
-            if (ev == PROCESS_EVENT_TIMER) {
-                if (etimer_expired(&the_coap_context.retransmit_timer)) {
-
-                    nextpdu = coap_peek_next(&the_coap_context);
-
-                    coap_ticks(&now);
-                    while (nextpdu && nextpdu->t <= now) {
-                        coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
-                        nextpdu = coap_peek_next(&the_coap_context);
-                    }
-
-                    /* need to set timer to some value even if no nextpdu is available */
-                    etimer_set(&the_coap_context.retransmit_timer,
-                            nextpdu ? nextpdu->t - now : 0xFFFF);
-                }
-#ifndef WITHOUT_OBSERVE
-                if (etimer_expired(&the_coap_context.notify_timer)) {
-                    coap_check_notify(&the_coap_context);
-                    etimer_reset(&the_coap_context.notify_timer);
-                }
-#endif /* WITHOUT_OBSERVE */
-            }
-        }
-
-        PROCESS_END();
-    }
-    /*---------------------------------------------------------------------------*/
-
-#endif /* WITH_CONTIKI */
-
-#ifdef WITH_LWIP
-    /* FIXME: retransmits that are not required any more due to incoming packages
-     * do *not* get cleared at the moment, the wakeup when the transmission is due
-     * is silently accepted. this is mainly due to the fact that the required
-     * checks are similar in two places in the code (when receiving ACK and RST)
-     * and that they cause more than one patch chunk, as it must be first checked
-     * whether the sendqueue item to be dropped is the next one pending, and later
-     * the restart function has to be called. nothing insurmountable, but it can
-     * also be implemented when things have stabilized, and the performance
-     * penality is minimal
-     *
-     * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
-     * */
-
-    static void coap_retransmittimer_execute(void *arg)
-    {
-        coap_context_t *ctx = (coap_context_t*)arg;
-        coap_tick_t now;
-        coap_tick_t elapsed;
-        coap_queue_t *nextinqueue;
-
-        ctx->timer_configured = 0;
-
-        coap_ticks(&now);
-
-        elapsed = now - ctx->sendqueue_basetime; /* that's positive for sure, and unless we haven't been called for a complete wrapping cycle, did not wrap */
-
-        nextinqueue = coap_peek_next(ctx);
-        while (nextinqueue != NULL)
-        {
-            if (nextinqueue->t > elapsed) {
-                nextinqueue->t -= elapsed;
-                break;
-            } else {
-                elapsed -= nextinqueue->t;
-                coap_retransmit(ctx, coap_pop_next(ctx));
-                nextinqueue = coap_peek_next(ctx);
-            }
-        }
-
-        ctx->sendqueue_basetime = now;
-
-        coap_retransmittimer_restart(ctx);
-    }
-
-    static void coap_retransmittimer_restart(coap_context_t *ctx)
-    {
-        coap_tick_t now, elapsed, delay;
-
-        if (ctx->timer_configured)
-        {
-            sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
-            ctx->timer_configured = 0;
-        }
-        if (ctx->sendqueue != NULL)
-        {
-            coap_ticks(&now);
-            elapsed = now - ctx->sendqueue_basetime;
-            if (ctx->sendqueue->t >= elapsed) {
-                delay = ctx->sendqueue->t - elapsed;
-            } else {
-                /* a strange situation, but not completely impossible.
-                 *
-                 * this happens, for example, right after
-                 * coap_retransmittimer_execute, when a retransmission
-                 * was *just not yet* due, and the clock ticked before
-                 * our coap_ticks was called.
-                 *
-                 * not trying to retransmit anything now, as it might
-                 * cause uncontrollable recursion; let's just try again
-                 * with the next main loop run.
-                 * */
-                delay = 0;
-            }
-            sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
-            ctx->timer_configured = 1;
-        }
-    }
-#endif
diff --git a/resource/csdk/libcoap-4.1.1/net.h b/resource/csdk/libcoap-4.1.1/net.h
deleted file mode 100644 (file)
index cec3f0a..0000000
+++ /dev/null
@@ -1,545 +0,0 @@
-/* net.h -- CoAP network interface
- *
- * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#ifndef _COAP_NET_H_
-#define _COAP_NET_H_
-
-#ifdef WITH_ARDUINO
-#include "Time.h"
-#endif /* WITH_ARDUINO */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "config.h"
-
-#ifdef HAVE_ASSERT_H
-#include <assert.h>
-#else
-#ifndef assert
-#warning "assertions are disabled"
-#  define assert(x)
-#endif
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_TIME_H
-#include <time.h>
-#endif
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-
-#ifdef WITH_LWIP
-#include <lwip/ip_addr.h>
-#endif
-
-#include "option.h"
-#include "address.h"
-#include "prng.h"
-#include "pdu.h"
-#include "coap_time.h"
-
-typedef enum {
-    SEND_NOW            = (1 << 0), // Flag used when sending non-confirmable,
-                                    // ACK and RESET coap pdus, Automatically set in SendCoAPPdu
-                                    // Do not use in upper stack APIs
-    SEND_NOW_CON        = (1 << 1), // Flag used when sending confirmable coap pdu,
-                                    // Automatically set in SendCoAPPdu,
-                                    // Do not use in upper stack APIs
-    SEND_DELAYED        = (1 << 2), // Flag used to delay the transmission of coap pdu
-    SEND_RETX           = (1 << 3), // Flag used to retransmit a confirmable pdu
-    SEND_SECURE_PORT    = (1 << 4)  // Flag used to indicate that PDU needs to
-                                    // be transmitted on secure port
-} coap_send_flags_t;
-
-struct coap_queue_t;
-
-typedef struct coap_queue_t {
-  struct coap_queue_t *next;
-
-  coap_tick_t t;            /**< when to send PDU for the next time */
-  unsigned char retransmit_cnt; /**< retransmission counter, will be removed when zero */
-  unsigned int timeout;     /**< the randomized timeout value */
-
-  coap_address_t local;     /**< local address */
-  coap_address_t remote;    /**< remote address */
-  coap_tid_t id;        /**< unique transaction id */
-
-  coap_pdu_t *pdu;      /**< the CoAP PDU to send */
-
-  unsigned char delayedResNeeded;  /**< delayed response flag */
-  unsigned char secure;      /**< rx/tx will use secure channel (DTLS) */
-} coap_queue_t;
-
-/** Adds node to given queue, ordered by node->t. */
-int coap_insert_node(coap_queue_t **queue, coap_queue_t *node);
-
-/** Destroys specified node. */
-int coap_delete_node(coap_queue_t *node);
-
-/** Removes all items from given queue and frees the allocated storage. */
-void coap_delete_all(coap_queue_t *queue);
-
-/** Creates a new node suitable for adding to the CoAP sendqueue. */
-coap_queue_t *coap_new_node();
-
-struct coap_resource_t;
-struct coap_context_t;
-#ifndef WITHOUT_ASYNC
-struct coap_async_state_t;
-#endif
-
-struct coap_dtls_context_t;
-
-/** Message handler for requests that is used as call-back in coap_context_t */
-typedef void (*coap_request_handler_t)(struct coap_context_t  *,
-        const coap_queue_t * rcvd);
-
-/** Message handler for responses that is used as call-back in coap_context_t */
-typedef void (*coap_response_handler_t)(struct coap_context_t  *,
-        const coap_queue_t * rcvd);
-
-/** Message handler for ack and rst that is used as call-back in coap_context_t */
-typedef void (*coap_ack_rst_handler_t)(struct coap_context_t  *, uint8_t msgType,
-        const coap_queue_t * sent);
-
-#define COAP_MID_CACHE_SIZE 3
-typedef struct {
-  unsigned char flags[COAP_MID_CACHE_SIZE];
-  coap_key_t item[COAP_MID_CACHE_SIZE];
-} coap_mid_cache_t;
-
-/** The CoAP stack's global state is stored in a coap_context_t object */
-typedef struct coap_context_t {
-  coap_opt_filter_t known_options;
-#ifndef WITH_CONTIKI
-  struct coap_resource_t *resources; /**< hash table or list of known resources */
-#endif /* WITH_CONTIKI */
-#ifndef WITHOUT_ASYNC
-  /** list of asynchronous transactions */
-  struct coap_async_state_t *async_state;
-#endif /* WITHOUT_ASYNC */
-  /**
-   * The time stamp in the first element of the sendqeue is relative
-   * to sendqueue_basetime. */
-  coap_tick_t sendqueue_basetime;
-  coap_queue_t *sendqueue, *recvqueue;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-  int sockfd;           /**< send/receive socket */
-  int sockfd_wellknown; /**< well-known discovery socket */
-  int sockfd_dtls;      /**< secure communication happens on this socket */
-  /** dtls interface */
-  struct coap_dtls_context_t *coap_dtls_ctx;
-#endif /* WITH_POSIX || WITH_ARDUINO */
-#ifdef WITH_CONTIKI
-  struct uip_udp_conn *conn;    /**< uIP connection object */
-
-  struct etimer retransmit_timer; /**< fires when the next packet must be sent */
-  struct etimer notify_timer;     /**< used to check resources periodically */
-#endif /* WITH_CONTIKI */
-#ifdef WITH_LWIP
-  struct udp_pcb *pcb; /**< the underlying lwIP UDP PCB */
-  struct pbuf *pending_package; /**< pbuf containing the last received package if not handled yet. This is only used to pass the package from the udp_recv callback into the coap_read function, which frees the pbuf and clears this field. */
-  ip_addr_t pending_address; /**< the address associated with pending_package */
-  u16_t pending_port; /**< the port associated with pending_package */
-
-  uint8_t timer_configured; /**< Set to 1 when a retransmission is scheduled using lwIP timers for this context, otherwise 0. */
-#endif /* WITH_LWIP */
-
-  /**
-   * The last message id that was used is stored in this field.  The
-   * initial value is set by coap_new_context() and is usually a
-   * random value. A new message id can be created with
-   * coap_new_message_id().
-   */
-  unsigned short message_id;
-
-  /**
-   * The next value to be used for Observe. This field is global for
-   * all resources and will be updated when notifications are created.
-   */
-  unsigned int observe;
-
-  coap_request_handler_t request_handler;
-  coap_response_handler_t response_handler;
-  coap_ack_rst_handler_t ack_rst_handler;
-} coap_context_t;
-
-/**
- * Registers a new message handler that is called whenever a request
- * was received that matches an ongoing transaction.
- *
- * @param context The context to register the handler for.
- * @param handler The response handler to register.
- */
-static inline void
-coap_register_request_handler(coap_context_t *context,
-                   coap_request_handler_t handler) {
-  context->request_handler = handler;
-}
-
-/**
- * Registers a new message handler that is called whenever a response
- * was received that matches an ongoing transaction.
- *
- * @param context The context to register the handler for.
- * @param handler The response handler to register.
- */
-static inline void
-coap_register_response_handler(coap_context_t *context,
-                   coap_response_handler_t handler) {
-  context->response_handler = handler;
-}
-
-/**
- * Registers a new message handler that is called whenever ack or rst
- * was received that matches an ongoing transaction.
- *
- * @param context The context to register the handler for.
- * @param handler The handler to register.
- */
-static inline void
-coap_register_ack_rst_handler(coap_context_t *context,
-                   coap_ack_rst_handler_t handler) {
-  context->ack_rst_handler = handler;
-}
-
-/**
- * Registers the option type @p type with the given context object @p
- * ctx.
- *
- * @param ctx  The context to use.
- * @param type The option type to register.
- */
-inline static void
-coap_register_option(coap_context_t *ctx, unsigned char type) {
-  coap_option_setb(ctx->known_options, type);
-}
-
-
-/**
- * Set sendqueue_basetime in the given context object @p ctx to @p
- * now. This function returns the number of elements in the queue
- * head that have timed out.
- */
-unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now);
-
-/** Returns the next pdu to send without removing from sendqeue. */
-coap_queue_t *coap_peek_next( coap_context_t *context );
-
-/** Returns the next pdu to send and removes it from the sendqeue. */
-coap_queue_t *coap_pop_next( coap_context_t *context );
-
-/** Creates a new coap_context_t object that will hold the CoAP stack status.  */
-coap_context_t *coap_new_context(uint8_t ipAddr[], uint16_t port);
-
-/** Joins the CoAP stack to well-known multicast address.  */
-int coap_join_wellknown_group(coap_context_t *context,
-                const coap_address_t *multicast_addr);
-
-/**
- * Returns a new message id and updates @p context->message_id
- * accordingly. The message id is returned in network byte order
- * to make it easier to read in tracing tools.
- *
- * @param context the current coap_context_t object
- * @return incremented message id in network byte order
- */
-static inline unsigned short
-coap_new_message_id(coap_context_t *context) {
-    ++(context->message_id);
-#ifdef WITH_ARDUINO
-  return ((context->message_id << 8) | ((context->message_id >> 8) & (0xFF)));
-#elif WITH_CONTIKI
-  return uip_htons(context->message_id);
-#else
-  return htons(context->message_id);
-#endif
-}
-
-/* CoAP stack context must be released with coap_free_context() */
-void coap_free_context( coap_context_t *context );
-
-/**
- * Sends a confirmed CoAP message to given destination. The memory
- * that is allocated by pdu will not be released by
- * coap_send_confirmed(). The caller must release the memory.
- *
- * @param context The CoAP context to use.
- * @param dst     The address to send to.
- * @param pdu     The CoAP PDU to send.
- * @return The message id of the sent message or @c COAP_INVALID_TID on error.
- */
-coap_tid_t coap_send_confirmed(coap_context_t *context,
-                   const coap_address_t *dst,
-                   coap_pdu_t *pdu);
-
-/**
- * Creates a new ACK PDU with specified error @p code. The options
- * specified by the filter expression @p opts will be copied from the
- * original request contained in @p request.  Unless @c
- * SHORT_ERROR_RESPONSE was defined at build time, the textual reason
- * phrase for @p code will be added as payload, with Content-Type @c
- * 0.  This function returns a pointer to the new response message, or
- * @c NULL on error. The storage allocated for the new message must be
- * relased with coap_free().
- *
- * @param request Specification of the received (confirmable) request.
- * @param code The error code to set.
- * @param opts An option filter that specifies which options to copy
- *             from the original request in @p node.
- *
- * @return A pointer to the new message or @c NULL on error.
- */
-coap_pdu_t *coap_new_error_response(coap_pdu_t *request,
-                    unsigned char code,
-                    coap_opt_filter_t opts);
-/**
- * Sends a CoAP message to given destination. The memory
- * that is allocated by pdu will be released by coap_send().
- *
- * @param context       The CoAP context to use.
- * @param dst           The address to send to.
- * @param pdu           The CoAP PDU to send.
- * @param flag          The flag indicating how the message will be send
- * @param cache_flag    When DTLS library determines that a secure session does
- *                      not exist with the peer yet, it caches the 'pdu pointer'
- *                      so that it can be sent later and 'coap_send' sets this
- *                      variable to TRUE to instruct the caller of this method
- *                      to not delete the 'pdu'.
- * @return The message id of the sent message or @c COAP_INVALID_TID on error.
- */
-coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst,
-                 coap_pdu_t *pdu,
-                 coap_send_flags_t flags,
-                 uint8_t *cache_flag);
-
-/**
- * Sends an error response with code @p code for request @p request to
- * @p dst.  @p opts will be passed to coap_new_error_response() to
- * copy marked options from the request. This function returns the
- * transaction id if the message was sent, or @c COAP_INVALID_TID
- * otherwise.
- *
- * @param context The context to use.
- * @param request The original request to respond to.
- * @param dst     The remote peer that sent the request.
- * @param code    The reponse code.
- * @param opts    A filter that specifies the options to copy from the
- *                @p request.
- *
- * @return The transaction id if the message was sent, or @c
- * COAP_INVALID_TID otherwise.
- */
-coap_tid_t coap_send_error(coap_context_t *context,
-               coap_pdu_t *request,
-               const coap_address_t *dst,
-               unsigned char code,
-               coap_opt_filter_t opts,
-               coap_send_flags_t flag);
-
-/**
- * Helper funktion to create and send a message with @p type (usually
- * ACK or RST).  This function returns @c COAP_INVALID_TID when the
- * message was not sent, a valid transaction id otherwise.
- *
- * @param context The CoAP context.
- * @param dst Where to send the context.
- * @param request The request that should be responded to.
- * @param type Which type to set
- * @param flag options for sending the message
- * @return transaction id on success or @c COAP_INVALID_TID otherwise.
- */
-coap_tid_t
-coap_send_message_type(coap_context_t *context,
-               const coap_address_t *dst,
-               coap_pdu_t *request,
-               coap_send_flags_t flag,
-               unsigned char type);
-/**
- * Sends an ACK message with code @c 0 for the specified @p request to
- * @p dst. This function returns the corresponding transaction id if
- * the message was sent or @c COAP_INVALID_TID on error.
- *
- * @param context The context to use.
- * @param dst     The destination address.
- * @param request The request to be acknowledged.
- * @param flag    Options for sending the acknowledgement.
- *
- * @return The transaction id if ACK was sent or @c COAP_INVALID_TID
- * on error.
- */
-coap_tid_t coap_send_ack(coap_context_t *context,
-             const coap_address_t *dst,
-             coap_pdu_t *request,
-             coap_send_flags_t flag);
-
-/**
- * Sends an RST message with code @c 0 for the specified @p request to
- * @p dst. This function returns the corresponding transaction id if
- * the message was sent or @c COAP_INVALID_TID on error.
- *
- * @param context The context to use.
- * @param dst     The destination address.
- * @param request The request to be reset.
- * @param flag    Options for sending the reset message.
- *
- * @return The transaction id if RST was sent or @c COAP_INVALID_TID
- * on error.
- */
-static inline coap_tid_t
-coap_send_rst(coap_context_t *context,
-          const coap_address_t *dst,
-          coap_pdu_t *request,
-          coap_send_flags_t flag) {
-  return coap_send_message_type(context, dst, request, flag, COAP_MESSAGE_RST);
-}
-
-/** Handles retransmissions of confirmable messages */
-coap_tid_t coap_retransmit( coap_context_t *context, coap_queue_t *node);
-
-/**
- * Reads data from the network and tries to parse as CoAP PDU. On success, 0 is returned
- * and a new node with the parsed PDU is added to the receive queue in the specified context
- * object.
- */
-int coap_read( coap_context_t *context, int sockfd );
-
-/**
- * Calculates a unique transaction id from given arguments @p peer and
- * @p pdu. The id is returned in @p id.
- *
- * @param peer The remote party who sent @p pdu.
- * @param pdu  The message that initiated the transaction.
- * @param id   Set to the new id.
- */
-void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu,
-             coap_tid_t *id);
-
-/**
- * This function removes the element with given @p id from the list
- * given list. If @p id was found, @p node is updated to point to the
- * removed element. Note that the storage allocated by @p node is
- * @b not released. The caller must do this manually using
- * coap_delete_node(). This function returns @c 1 if the element with
- * id @p id was found, @c 0 otherwise. For a return value of @c 0,
- * the contents of @p node is undefined.
- *
- * @param queue The queue to search for @p id.
- * @param id    The node id to look for.
- * @param node  If found, @p node is updated to point to the
- *   removed node. You must release the storage pointed to by
- *   @p node manually.
- *
- * @return @c 1 if @p id was found, @c 0 otherwise.
- */
-int coap_remove_from_queue(coap_queue_t **queue,
-               coap_tid_t id,
-               coap_queue_t **node);
-
-/**
- * Removes the transaction identified by @p id from given @p queue.
- * This is a convenience function for coap_remove_from_queue() with
- * automatic deletion of the removed node.
- *
- * @param queue The queue to search for @p id.
- * @param id    The transaction id.
- *
- * @return @c 1 if node was found, removed and destroyed, @c 0 otherwise.
- */
-inline static int
-coap_remove_transaction(coap_queue_t **queue, coap_tid_t id) {
-  coap_queue_t *node;
-  if (!coap_remove_from_queue(queue, id, &node))
-    return 0;
-
-  coap_delete_node(node);
-  return 1;
-}
-
-/**
- * Retrieves transaction from queue.
- * @queue The transaction queue to be searched
- * @id Unique key of the transaction to find.
- * @return A pointer to the transaction object or NULL if not found
- */
-coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_tid_t id);
-
-/**
- * Cancels all outstanding messages for peer @p dst that have the
- * specified token.
- *
- * @param context The context in use
- * @param dst     Destination address of the messages to remove.
- * @param token   Message token
- * @param token_length Actual length of @p token
- */
-void coap_cancel_all_messages(coap_context_t *context,
-                  const coap_address_t *dst,
-                  const unsigned char *token,
-                  size_t token_length);
-
-/** Dispatches the PDUs from the receive queue in given context. */
-void coap_dispatch( coap_context_t *context );
-
-/** Returns 1 if there are no messages to send or to dispatch in the context's queues. */
-int coap_can_exit( coap_context_t *context );
-
-/**
- * Returns the current value of an internal tick counter. The counter
- * counts \c COAP_TICKS_PER_SECOND ticks every second.
- */
-void coap_ticks(coap_tick_t *);
-
-/**
- * Verifies that @p pdu contains no unknown critical options. Options
- * must be registered at @p ctx, using the function
- * coap_register_option(). A basic set of options is registered
- * automatically by coap_new_context(). This function returns @c 1 if
- * @p pdu is ok, @c 0 otherwise. The given filter object @p unknown
- * will be updated with the unknown options. As only @c COAP_MAX_OPT
- * options can be signalled this way, remaining options must be
- * examined manually.
- *
- * @code
-  coap_opt_filter_t f = COAP_OPT_NONE;
-  coap_opt_iterator_t opt_iter;
-
-  if (coap_option_check_critical(ctx, pdu, f) == 0) {
-    coap_option_iterator_init(pdu, &opt_iter, f);
-
-    while (coap_option_next(&opt_iter)) {
-      if (opt_iter.type & 0x01) {
-    ... handle unknown critical option in opt_iter ...
-      }
-    }
-  }
- * @endcode
- *
- * @param ctx      The context where all known options are registered.
- * @param pdu      The PDU to check.
- * @param unknown  The output filter that will be updated to indicate the
- *                 unknown critical options found in @p pdu.
- *
- * @return @c 1 if everything was ok, @c 0 otherwise.
- */
-int coap_option_check_critical(coap_context_t *ctx,
-                   coap_pdu_t *pdu,
-                   coap_opt_filter_t unknown);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_NET_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/option.c b/resource/csdk/libcoap-4.1.1/option.c
deleted file mode 100644 (file)
index a03fc9e..0000000
+++ /dev/null
@@ -1,407 +0,0 @@
-/*
- * option.c -- helpers for handling options in CoAP PDUs
- *
- * Copyright (C) 2010-2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-
-#include "config.h"
-
-#if defined(HAVE_ASSERT_H) && !defined(assert)
-# include <assert.h>
-#endif
-
-#include <stdio.h>
-#include <string.h>
-
-#include "option.h"
-#include "debug.h"
-
-coap_opt_t *
-options_start(coap_pdu_t *pdu) {
-
-  if (pdu && pdu->hdr && 
-      (pdu->hdr->token + pdu->hdr->token_length 
-       < (unsigned char *)pdu->hdr + pdu->length)) {
-
-    coap_opt_t *opt = pdu->hdr->token + pdu->hdr->token_length;
-    return (*opt == COAP_PAYLOAD_START) ? NULL : opt;
-  
-  } else 
-    return NULL;
-}
-
-size_t
-coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *result) {
-
-  const coap_opt_t *opt_start = opt; /* store where parsing starts  */
-
-  assert(opt); assert(result);
-
-#define ADVANCE_OPT(o,e,step) if ((e) < step) {                        \
-    debug("cannot advance opt past end\n");                    \
-    return 0;                                                  \
-  } else {                                                     \
-    (e) -= step;                                               \
-    (o) = ((unsigned char *)(o)) + step;                       \
-  }
-
-  if (length < 1)
-    return 0;
-
-  result->delta = (*opt & 0xf0) >> 4;
-  result->length = *opt & 0x0f;
-
-  switch(result->delta) {
-  case 15:
-    if (*opt != COAP_PAYLOAD_START)
-      debug("ignored reserved option delta 15\n");
-    return 0;
-  case 14:
-    /* Handle two-byte value: First, the MSB + 269 is stored as delta value.
-     * After that, the option pointer is advanced to the LSB which is handled
-     * just like case delta == 13. */
-    ADVANCE_OPT(opt,length,1);
-    result->delta = ((*opt & 0xff) << 8) + 269;
-    if (result->delta < 269) {
-      debug("delta too large\n");
-      return 0;
-    }
-    /* fall through */
-  case 13:
-    ADVANCE_OPT(opt,length,1);
-    result->delta += *opt & 0xff;
-    break;
-    
-  default:
-    ;
-  }
-
-  switch(result->length) {
-  case 15:
-    debug("found reserved option length 15\n");
-    return 0;
-  case 14:
-    /* Handle two-byte value: First, the MSB + 269 is stored as delta value.
-     * After that, the option pointer is advanced to the LSB which is handled
-     * just like case delta == 13. */
-    ADVANCE_OPT(opt,length,1);
-    result->length = ((*opt & 0xff) << 8) + 269;
-    /* fall through */
-  case 13:
-    ADVANCE_OPT(opt,length,1);
-    result->length += *opt & 0xff;
-    break;
-    
-  default:
-    ;
-  }
-
-  ADVANCE_OPT(opt,length,1);
-  /* opt now points to value, if present */
-
-  result->value = (unsigned char *)opt;
-  if (length < result->length) {
-    debug("invalid option length\n");
-    return 0;
-  }
-
-#undef ADVANCE_OPT
-
-  return (opt + result->length) - opt_start;
-}
-
-coap_opt_iterator_t *
-coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
-                         const coap_opt_filter_t filter) {
-  assert(pdu); 
-  assert(pdu->hdr);
-  assert(oi);
-  
-  memset(oi, 0, sizeof(coap_opt_iterator_t));
-
-  oi->next_option = (unsigned char *)pdu->hdr + sizeof(coap_hdr_t)
-    + pdu->hdr->token_length;
-  if ((unsigned char *)pdu->hdr + pdu->length <= oi->next_option) {
-    oi->bad = 1;
-    return NULL;
-  }
-
-  assert((sizeof(coap_hdr_t) + pdu->hdr->token_length) <= pdu->length);
-
-  oi->length = pdu->length - (sizeof(coap_hdr_t) + pdu->hdr->token_length);
-
-  if (filter) {
-    memcpy(oi->filter, filter, sizeof(coap_opt_filter_t));
-    oi->filtered = 1;
-  }
-  return oi;
-}
-
-static inline int
-opt_finished(coap_opt_iterator_t *oi) {
-  assert(oi);
-
-  if (oi->bad || oi->length == 0 || 
-      !oi->next_option || *oi->next_option == COAP_PAYLOAD_START) {
-    oi->bad = 1;
-  }
-
-  return oi->bad;
-}
-
-coap_opt_t *
-coap_option_next(coap_opt_iterator_t *oi) {
-  coap_option_t option;
-  coap_opt_t *current_opt = NULL;
-  size_t optsize;
-  int b;                  /* to store result of coap_option_getb() */
-
-  assert(oi);
-
-  if (opt_finished(oi))
-    return NULL;
-
-  while (1) {
-    /* oi->option always points to the next option to deliver; as
-     * opt_finished() filters out any bad conditions, we can assume that
-     * oi->option is valid. */
-    current_opt = oi->next_option;
-    
-    /* Advance internal pointer to next option, skipping any option that
-     * is not included in oi->filter. */
-    optsize = coap_opt_parse(oi->next_option, oi->length, &option);
-    if (optsize) {
-      assert(optsize <= oi->length);
-      
-      oi->next_option += optsize;
-      oi->length -= optsize;
-      
-      oi->type += option.delta;
-    } else {                   /* current option is malformed */
-      oi->bad = 1;
-      return NULL;
-    }
-
-    /* Exit the while loop when:
-     *   - no filtering is done at all
-     *   - the filter matches for the current option
-     *   - the filter is too small for the current option number 
-     */
-    if (!oi->filtered ||
-       (b = coap_option_getb(oi->filter, oi->type)) > 0)
-      break;
-    else if (b < 0) {          /* filter too small, cannot proceed */
-      oi->bad = 1;
-      return NULL;
-    }
-  }
-
-  return current_opt;
-}
-
-coap_opt_t *
-coap_check_option(coap_pdu_t *pdu, unsigned char type, 
-                 coap_opt_iterator_t *oi) {
-  coap_opt_filter_t f;
-  
-  coap_option_filter_clear(f);
-  coap_option_setb(f, type);
-
-  coap_option_iterator_init(pdu, oi, f);
-
-  return coap_option_next(oi);
-}
-
-unsigned short
-coap_opt_delta(const coap_opt_t *opt) {
-  unsigned short n;
-
-  n = (*opt++ & 0xf0) >> 4;
-
-  switch (n) {
-  case 15: /* error */
-    warn("coap_opt_delta: illegal option delta\n");
-
-    /* This case usually should not happen, hence we do not have a
-     * proper way to indicate an error. */
-    return 0;
-  case 14: 
-    /* Handle two-byte value: First, the MSB + 269 is stored as delta value.
-     * After that, the option pointer is advanced to the LSB which is handled
-     * just like case delta == 13. */
-    n = ((*opt++ & 0xff) << 8) + 269;
-    /* fall through */
-  case 13:
-    n += *opt & 0xff;
-    break;
-  default: /* n already contains the actual delta value */
-    ;
-  }
-
-  return n;
-}
-
-unsigned short
-coap_opt_length(const coap_opt_t *opt) {
-  unsigned short length;
-
-  length = *opt & 0x0f;
-  switch (*opt & 0xf0) {
-  case 0xf0:
-    debug("illegal option delta\n");
-    return 0;
-  case 0xe0:
-    ++opt;
-    /* fall through to skip another byte */
-  case 0xd0:
-    ++opt;
-    /* fall through to skip another byte */
-  default:
-    ++opt;
-  }
-
-  switch (length) {
-  case 0x0f:
-    debug("illegal option length\n");
-    return 0;
-  case 0x0e:
-    length = (*opt++ << 8) + 269;
-    /* fall through */
-  case 0x0d:
-    length += *opt++;
-    break;
-  default:
-    ;
-  }
-  return length;
-}
-
-unsigned char *
-coap_opt_value(coap_opt_t *opt) {
-  size_t ofs = 1;
-
-  switch (*opt & 0xf0) {
-  case 0xf0:
-    debug("illegal option delta\n");
-    return 0;
-  case 0xe0:
-    ++ofs;
-    /* fall through */
-  case 0xd0:
-    ++ofs;
-    break;
-  default:
-    ;
-  }
-
-  switch (*opt & 0x0f) {
-  case 0x0f:
-    debug("illegal option length\n");
-    return 0;
-  case 0x0e:
-    ++ofs;
-    /* fall through */
-  case 0x0d:
-    ++ofs;
-    break;
-  default:
-    ;
-  }
-
-  return (unsigned char *)opt + ofs;
-}
-
-size_t
-coap_opt_size(const coap_opt_t *opt) {
-  coap_option_t option;
-
-  /* we must assume that opt is encoded correctly */
-  return coap_opt_parse(opt, (size_t)-1, &option);
-}
-
-size_t
-coap_opt_setheader(coap_opt_t *opt, size_t maxlen, 
-                  unsigned short delta, size_t length) {
-  size_t skip = 0;
-
-  assert(opt);
-
-  if (maxlen == 0)             /* need at least one byte */
-    return 0;
-
-  if (delta < 13) {
-    opt[0] = delta << 4;
-  } else if (delta < 270) {
-    if (maxlen < 2) {
-      debug("insufficient space to encode option delta %d", delta);
-      return 0;
-    }
-
-    opt[0] = 0xd0;
-    opt[++skip] = delta - 13;
-  } else {
-    if (maxlen < 3) {
-      debug("insufficient space to encode option delta %d", delta);
-      return 0;
-    }
-
-    opt[0] = 0xe0;
-    opt[++skip] = ((delta - 269) >> 8) & 0xff;
-    opt[++skip] = (delta - 269) & 0xff;    
-  }
-    
-  if (length < 13) {
-    opt[0] |= length & 0x0f;
-  } else if (length < 270) {
-    if (maxlen < skip + 1) {
-      debug("insufficient space to encode option length %d", length);
-      return 0;
-    }
-    
-    opt[0] |= 0x0d;
-    opt[++skip] = length - 13;
-  } else {
-    if (maxlen < skip + 2) {
-      debug("insufficient space to encode option delta %d", delta);
-      return 0;
-    }
-
-    opt[0] |= 0x0e;
-    opt[++skip] = ((length - 269) >> 8) & 0xff;
-    opt[++skip] = (length - 269) & 0xff;    
-  }
-
-  return skip + 1;
-}
-
-size_t
-coap_opt_encode(coap_opt_t *opt, size_t maxlen, unsigned short delta,
-               const unsigned char *val, size_t length) {
-  size_t l = 1;
-
-  l = coap_opt_setheader(opt, maxlen, delta, length);
-  assert(l <= maxlen);
-  
-  if (!l) {
-    debug("coap_opt_encode: cannot set option header\n");
-    return 0;
-  }
-  
-  maxlen -= l;
-  opt += l;
-
-  if (maxlen < length) {
-    debug("coap_opt_encode: option too large for buffer\n");
-    return 0;
-  }
-
-  if (val)                     /* better be safe here */
-    memcpy(opt, val, length);
-
-  return l + length;
-}
-
diff --git a/resource/csdk/libcoap-4.1.1/option.h b/resource/csdk/libcoap-4.1.1/option.h
deleted file mode 100644 (file)
index 34cb31f..0000000
+++ /dev/null
@@ -1,345 +0,0 @@
-/*
- * option.h -- helpers for handling options in CoAP PDUs
- *
- * Copyright (C) 2010-2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-/**
- * @file option.h
- * @brief helpers for handling options in CoAP PDUs
- */
-
-#ifndef _OPTION_H_
-#define _OPTION_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "bits.h"
-#include "pdu.h"
-
-/** 
- * Use byte-oriented access methods here because sliding a complex
- * struct coap_opt_t over the data buffer may cause bus error on
- * certain platforms.
- */ 
-typedef unsigned char coap_opt_t;
-#define PCHAR(p) ((coap_opt_t *)(p))
-
-/** Representation of CoAP options. */
-typedef struct {
-  unsigned short delta;
-  size_t length;
-  unsigned char *value;
-} coap_option_t;
-
-/**
- * Parses the option pointed to by @p opt into @p result. This
- * function returns the number of bytes that have been parsed, or @c 0
- * on error. An error is signaled when illegal delta or length values
- * are encountered or when option parsing would result in reading past
- * the option (i.e. beyond opt + length). 
- *
- * @param opt    The beginning of the option to parse.
- * @param length The maximum length of @p opt.
- * @param result A pointer to the coap_option_t structure that is
- *               filled with actual values iff coap_opt_parse() > 0.
- * @return The number of bytes parsed or @c 0 on error.
- */
-size_t coap_opt_parse(const coap_opt_t *opt, size_t length, 
-                     coap_option_t *result);
-
-/**
- * Returns the size of the given option, taking into account a
- * possible option jump.
- *
- * @param opt An option jump or the beginning of the option.
- * @return The number of bytes between @p opt and the end of
- *         the option starting at @p opt. In case of an error,
- *         this function returns @c 0 as options need at least
- *         one byte storage space.
- */
-size_t coap_opt_size(const coap_opt_t *opt);
-
-/** @deprecated { Use coap_opt_size() instead. } */
-#define COAP_OPT_SIZE(opt) coap_opt_size(opt)
-
-/**
- * Calculates the beginning of the PDU's option section.
- * 
- * @param pdu The PDU containing the options.
- * @return A pointer to the first option if available, or @c NULL otherwise.
- */
-coap_opt_t *options_start(coap_pdu_t *pdu);
-
-/**
- * Interprets @p opt as pointer to a CoAP option and advances to
- * the next byte past this option.
- * @hideinitializer
- */
-#define options_next(opt) \
-  ((coap_opt_t *)((unsigned char *)(opt) + COAP_OPT_SIZE(opt)))
-
-/**
- * @defgroup opt_filter Option Filters
- * @{
- */
-
-/** 
- * Fixed-size bit-vector we use for option filtering. It is large
- * enough to hold the highest option number known at build time (20 in
- * the core spec).
- */
-typedef unsigned char coap_opt_filter_t[(COAP_MAX_OPT >> 3) + 1];
-
-/** Pre-defined filter that includes all options. */
-#define COAP_OPT_ALL NULL
-
-/** 
- * Clears filter @p f.
- * 
- * @param f The filter to clear.
- */
-static inline void
-coap_option_filter_clear(coap_opt_filter_t f) {
-  memset(f, 0, sizeof(coap_opt_filter_t));
-}
-
-/** 
- * Sets the corresponding bit for @p type in @p filter. This function
- * returns @c 1 if bit was set or @c -1 on error (i.e. when the given
- * type does not fit in the filter).
- * 
- * @param filter The filter object to change.
- * @param type   The type for which the bit should be set. 
- * 
- * @return @c 1 if bit was set, @c -1 otherwise.
- */
-inline static int
-coap_option_setb(coap_opt_filter_t filter, unsigned short type) {
-  return bits_setb((uint8_t *)filter, sizeof(coap_opt_filter_t), type);
-}
-
-/**
-* Sets the entire range of vendor specific options in the filter
-*/
-inline static int
-coap_option_setbVendor(coap_opt_filter_t filter)
-{
-    if ((COAP_VENDOR_OPT_START >> 3) > sizeof(coap_opt_filter_t))
-    {
-        return -1;
-    }
-    memset((uint8_t *)filter + (COAP_VENDOR_OPT_START >> 3), 0xFF,
-            sizeof(coap_opt_filter_t) - (COAP_VENDOR_OPT_START >> 3));
-    return 1;
-}
-
-/** 
- * Clears the corresponding bit for @p type in @p filter. This function
- * returns @c 1 if bit was cleared or @c -1 on error (i.e. when the given
- * type does not fit in the filter).
- * 
- * @param filter The filter object to change.
- * @param type   The type for which the bit should be cleared. 
- * 
- * @return @c 1 if bit was set, @c -1 otherwise.
- */
-inline static int
-coap_option_clrb(coap_opt_filter_t filter, unsigned short type) {
-  return bits_clrb((uint8_t *)filter, sizeof(coap_opt_filter_t), type);
-}
-
-/** 
- * Gets the corresponding bit for @p type in @p filter. This function
- * returns @c 1 if the bit is set @c 0 if not, or @c -1 on error (i.e.
- * when the given type does not fit in the filter).
- * 
- * @param filter The filter object to read bit from..
- * @param type   The type for which the bit should be read.
- * 
- * @return @c 1 if bit was set, @c 0 if not, @c -1 on error.
- */
-inline static int
-coap_option_getb(const coap_opt_filter_t filter, unsigned short type) {
-  return bits_getb((uint8_t *)filter, sizeof(coap_opt_filter_t), type);
-}
-
-/** 
- * Iterator to run through PDU options. This object must be
- * initialized with coap_option_iterator_init(). Call
- * coap_option_next() to walk through the list of options until
- * coap_option_next() returns @c NULL.
- *
- * @code
- * coap_opt_t *option;
- * coap_opt_iterator_t opt_iter;
- * coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
- *
- * while ((option = coap_option_next(&opt_iter))) {
- *   ... do something with option ...
- * }
- * @endcode
- */
-typedef struct {
-  size_t length;               /**< remaining length of PDU */
-  unsigned short type;         /**< decoded option type */
-  unsigned int bad:1;          /**< iterator object is ok if not set */
-  unsigned int filtered:1;     /**< denotes whether or not filter is used */
-  coap_opt_t *next_option;     /**< pointer to the unparsed next option */
-  coap_opt_filter_t filter;    /**< option filter */
-} coap_opt_iterator_t;
-
-/** 
- * Initializes the given option iterator @p oi to point to the
- * beginning of the @p pdu's option list. This function returns @p oi
- * on success, @c NULL otherwise (i.e. when no options exist).
- * Note that a length check on the option list must be performed before
- * coap_option_iterator_init() is called.
- * 
- * @param pdu  The PDU the options of which should be walked through.
- * @param oi   An iterator object that will be initilized.
- * @param filter An optional option type filter. 
- *               With @p type != @c COAP_OPT_ALL, coap_option_next() 
- *               will return only options matching this bitmask. 
- *               Fence-post options @c 14, @c 28, @c 42, ... are always
- *               skipped.
- * 
- * @return The iterator object @p oi on success, @c NULL otherwise.
- */
-coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu,
-     coap_opt_iterator_t *oi, const coap_opt_filter_t filter);
-
-/** 
- * Updates the iterator @p oi to point to the next option. This
- * function returns a pointer to that option or @c NULL if no more
- * options exist. The contents of @p oi will be updated. In
- * particular, @c oi->n specifies the current option's ordinal number
- * (counted from @c 1), @c oi->type is the option's type code, and @c
- * oi->option points to the beginning of the current option
- * itself. When advanced past the last option, @c oi->option will be
- * @c NULL.
- * 
- * Note that options are skipped whose corresponding bits in the
- * filter specified with coap_option_iterator_init() are @c 0. Options
- * with type codes that do not fit in this filter hence will always be
- * returned.
- * 
- * @param oi The option iterator to update.
- * 
- * @return The next option or @c NULL if no more options exist.
- */
-coap_opt_t *coap_option_next(coap_opt_iterator_t *oi);
-
-/** 
- * Retrieves the first option of type @p type from @p pdu. @p oi must
- * point to a coap_opt_iterator_t object that will be initialized by
- * this function to filter only options with code @p type. This
- * function returns the first option with this type, or @c NULL if not
- * found.
- * 
- * @param pdu  The PDU to parse for options.
- * @param type The option type code to search for.
- * @param oi   An iterator object to use.
- * 
- * @return A pointer to the first option of type @p type, or @c NULL 
- *         if not found.
- */
-coap_opt_t *coap_check_option(coap_pdu_t *pdu, 
-                             unsigned char type, 
-                             coap_opt_iterator_t *oi);
-
-/**
- * Encodes the given delta and length values into @p opt. This
- * function returns the number of bytes that were required to encode
- * @p delta and @p length or @c 0 on error. Note that the result
- * indicates by how many bytes @p opt must be advanced to encode the
- * option value.
- *
- * @param opt    The option buffer space where @p delta and @p length are 
- *               written
- * @param maxlen The maximum length of @p opt
- * @param delta The actual delta value to encode.
- * @param length The actual length value to encode.
- * @return The number of bytes used or @c 0 on error.
- */
-size_t coap_opt_setheader(coap_opt_t *opt, size_t maxlen, 
-                         unsigned short delta, size_t length);
-
-/**
- * Encodes option with given @p delta into @p opt. This function returns
- * the number of bytes written to @p opt or @c 0 on error. This happens
- * especially when @p opt does not provide sufficient space to store
- * the option value, delta, and option jumps when required.
- *
- * @param opt   The option buffer space where @p val is written
- * @param n     Maximum length of @p opt.
- * @param delta The option delta.
- * @param val   The option value to copy into @p opt.
- * @param len   The actual length of @p val.
- * @return The number of bytes that have been written to @p opt or
- *         @c 0 on error. The return value will always be less than @p n.
- */
-size_t coap_opt_encode(coap_opt_t *opt, size_t n, unsigned short delta,
-                      const unsigned char *val, size_t length);
-
-/**
- * Decodes the delta value of the next option. This function returns
- * the number of bytes read or @c 0 on error. The caller of this
- * function must ensure that it does not read over the boundaries
- * of @p opt (e.g. by calling coap_opt_check_delta().
- *
- * @param opt The option to examine
- * @return The number of bytes read or @c 0 on error.
- */
-unsigned short coap_opt_delta(const coap_opt_t *opt);
-
-/** @deprecated { Use coap_opt_delta() instead. } */
-#define COAP_OPT_DELTA(opt) coap_opt_delta(opt)
-
-/** @deprecated { Use coap_opt_encode() instead. } */
-#define COAP_OPT_SETDELTA(opt,val)                     \
-  coap_opt_encode((opt), COAP_MAX_PDU_SIZE, (val), NULL, 0)
-
-/**
- * Returns the length of the given option. @p opt must point to an
- * option jump or the beginning of the option. This function returns
- * @c 0 when @p opt is not an option or the actual length of @p opt
- * (which can be @c 0 as well).
- *
- * @note {The rationale for using @c 0 in case of an error is that in
- * most contexts, the result of this function is used to skip the next
- * coap_opt_length() bytes. }
- *
- * @param opt  The option whose length should be returned.
- * @return The option's length or @c 0 when undefined.
- */
-unsigned short coap_opt_length(const coap_opt_t *opt);
-
-/** @deprecated { Use coap_opt_length() instead. } */
-#define COAP_OPT_LENGTH(opt) coap_opt_length(opt)
-
-/**
- * Returns a pointer to the value of the given option. @p opt must
- * point to an option jump or the beginning of the option. This 
- * function returns @c NULL if @p opt is not a valid option.
- *
- * @param opt  The option whose value should be returned.
- * @return A pointer to the option value or @c NULL on error.
- */
-unsigned char *coap_opt_value(coap_opt_t *opt);
-
-/** @deprecated { Use coap_opt_value() instead. } */
-#define COAP_OPT_VALUE(opt) coap_opt_value((coap_opt_t *)opt)
-
-/** @} */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _OPTION_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/pdu.c b/resource/csdk/libcoap-4.1.1/pdu.c
deleted file mode 100644 (file)
index 109e289..0000000
+++ /dev/null
@@ -1,406 +0,0 @@
-/* pdu.c -- CoAP message structure
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-
-#if defined(HAVE_ASSERT_H) && !defined(assert)
-#include <assert.h>
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-#include "debug.h"
-#include "pdu.h"
-#include "option.h"
-#include "encode.h"
-
-#ifdef WITH_CONTIKI
-#include "memb.h"
-
-typedef unsigned char _pdu[sizeof(coap_pdu_t) + COAP_MAX_PDU_SIZE];
-
-MEMB(pdu_storage, _pdu, COAP_PDU_MAXCNT);
-
-void
-coap_pdu_resources_init() {
-  memb_init(&pdu_storage);
-}
-#else /* WITH_CONTIKI */
-#include "mem.h"
-#endif /* WITH_CONTIKI */
-
-void
-coap_pdu_clear(coap_pdu_t *pdu, size_t size) {
-  assert(pdu);
-
-  memset(pdu, 0, sizeof(coap_pdu_t) + size);
-  pdu->max_size = size;
-  pdu->hdr = (coap_hdr_t *)((unsigned char *)pdu + sizeof(coap_pdu_t));
-  pdu->hdr->version = COAP_DEFAULT_VERSION;
-
-  /* data is NULL unless explicitly set by coap_add_data() */
-  pdu->length = sizeof(coap_hdr_t);
-}
-
-#ifdef WITH_LWIP
-coap_pdu_t *
-coap_pdu_from_pbuf(struct pbuf *pbuf)
-{
-  LWIP_ASSERT("Can only deal with contiguous PBUFs", pbuf->tot_len == pbuf->len);
-  LWIP_ASSERT("coap_read needs to receive an exclusive copy of the incoming pbuf", pbuf->ref == 1);
-
-  void *data = pbuf->payload;
-  coap_pdu_t *result;
-
-  u8_t header_error = pbuf_header(pbuf, sizeof(coap_pdu_t));
-  LWIP_ASSERT("CoAP PDU header does not fit in existing header space", header_error == 0);
-
-  result = (coap_pdu_t *)pbuf->payload;
-
-  memset(result, 0, sizeof(coap_pdu_t));
-
-  result->max_size = pbuf->tot_len - sizeof(coap_pdu_t);
-  result->length = pbuf->tot_len - sizeof(coap_pdu_t);
-  result->hdr = data;
-  result->pbuf = pbuf;
-
-  return result;
-}
-#endif
-
-coap_pdu_t *
-coap_pdu_init(unsigned char type, unsigned char code,
-             unsigned short id, size_t size) {
-  coap_pdu_t *pdu;
-#ifdef WITH_LWIP
-    struct pbuf *p;
-#endif
-
-  assert(size <= COAP_MAX_PDU_SIZE);
-  /* Size must be large enough to fit the header. */
-  if (size < sizeof(coap_hdr_t) || size > COAP_MAX_PDU_SIZE)
-    return NULL;
-
-  /* size must be large enough for hdr */
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-  pdu = (coap_pdu_t *)coap_malloc(sizeof(coap_pdu_t) + size);
-#endif
-#ifdef WITH_CONTIKI
-  pdu = (coap_pdu_t *)memb_alloc(&pdu_storage);
-#endif
-#ifdef WITH_LWIP
-  p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM);
-  if (p != NULL) {
-    u8_t header_error = pbuf_header(p, sizeof(coap_pdu_t));
-    /* we could catch that case and allocate larger memory in advance, but then
-     * again, we'd run into greater trouble with incoming packages anyway */
-    LWIP_ASSERT("CoAP PDU header does not fit in transport header", header_error == 0);
-    pdu = p->payload;
-  } else {
-    pdu = NULL;
-  }
-#endif
-  if (pdu) {
-    coap_pdu_clear(pdu, size);
-    pdu->hdr->id = id;
-    pdu->hdr->type = type;
-    pdu->hdr->code = code;
-#ifdef WITH_LWIP
-    pdu->pbuf = p;
-#endif
-  }
-  return pdu;
-}
-
-
-void
-coap_delete_pdu(coap_pdu_t *pdu) {
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-  coap_free( pdu );
-#endif
-#ifdef WITH_LWIP
-  if (pdu != NULL) /* accepting double free as the other implementation accept that too */
-    pbuf_free(pdu->pbuf);
-#endif
-#ifdef WITH_CONTIKI
-  memb_free(&pdu_storage, pdu);
-#endif
-}
-
-int
-coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data) {
-  const size_t HEADERLENGTH = len + 4;
-  /* must allow for pdu == NULL as callers may rely on this */
-  if (!pdu || len > 8 || pdu->max_size < HEADERLENGTH)
-    return 0;
-
-  pdu->hdr->token_length = len;
-  if (len)
-    memcpy(pdu->hdr->token, data, len);
-  pdu->max_delta = 0;
-  pdu->length = HEADERLENGTH;
-  pdu->data = NULL;
-
-  return 1;
-}
-
-/** @FIXME de-duplicate code with coap_add_option_later */
-size_t
-coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const unsigned char *data) {
-  size_t optsize;
-  coap_opt_t *opt;
-
-  assert(pdu);
-  pdu->data = NULL;
-
-  if (type < pdu->max_delta) {
-    warn("coap_add_option: options are not in correct order\n");
-    return 0;
-  }
-
-  opt = (unsigned char *)pdu->hdr + pdu->length;
-
-  /* encode option and check length */
-  optsize = coap_opt_encode(opt, pdu->max_size - pdu->length,
-                           type - pdu->max_delta, data, len);
-
-  if (!optsize) {
-    warn("coap_add_option: cannot add option\n");
-    /* error */
-    return 0;
-  } else {
-    pdu->max_delta = type;
-    pdu->length += optsize;
-  }
-
-  return optsize;
-}
-
-/** @FIXME de-duplicate code with coap_add_option */
-unsigned char*
-coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len) {
-  size_t optsize;
-  coap_opt_t *opt;
-
-  assert(pdu);
-  pdu->data = NULL;
-
-  if (type < pdu->max_delta) {
-    warn("coap_add_option: options are not in correct order\n");
-    return NULL;
-  }
-
-  opt = (unsigned char *)pdu->hdr + pdu->length;
-
-  /* encode option and check length */
-  optsize = coap_opt_encode(opt, pdu->max_size - pdu->length,
-                           type - pdu->max_delta, NULL, len);
-
-  if (!optsize) {
-    warn("coap_add_option: cannot add option\n");
-    /* error */
-    return NULL;
-  } else {
-    pdu->max_delta = type;
-    pdu->length += optsize;
-  }
-
-  return ((unsigned char*)opt) + optsize - len;
-}
-
-int
-coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data) {
-  assert(pdu);
-  assert(pdu->data == NULL);
-
-  if (len == 0)
-    return 1;
-
-  if (pdu->length + len + 1 > pdu->max_size) {
-    warn("coap_add_data: cannot add: data too large for PDU\n");
-    assert(pdu->data == NULL);
-    return 0;
-  }
-
-  pdu->data = (unsigned char *)pdu->hdr + pdu->length;
-  *pdu->data = COAP_PAYLOAD_START;
-  pdu->data++;
-
-  memcpy(pdu->data, data, len);
-  pdu->length += len + 1;
-  return 1;
-}
-
-int
-coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data) {
-  assert(pdu);
-  assert(len);
-  assert(data);
-
-  if (pdu->data) {
-    *len = (unsigned char *)pdu->hdr + pdu->length - pdu->data;
-    *data = pdu->data;
-  } else {                     /* no data, clear everything */
-    *len = 0;
-    *data = NULL;
-  }
-
-  return *data != NULL;
-}
-
-#ifndef SHORT_ERROR_RESPONSE
-typedef struct {
-  unsigned char code;
-  const char *phrase;
-} error_desc_t;
-
-/* if you change anything here, make sure, that the longest string does not
- * exceed COAP_ERROR_PHRASE_LENGTH. */
-error_desc_t coap_error[] = {
-  { COAP_RESPONSE_CODE(65),  "2.01 Created" },
-  { COAP_RESPONSE_CODE(66),  "2.02 Deleted" },
-  { COAP_RESPONSE_CODE(67),  "2.03 Valid" },
-  { COAP_RESPONSE_CODE(68),  "2.04 Changed" },
-  { COAP_RESPONSE_CODE(69),  "2.05 Content" },
-  { COAP_RESPONSE_CODE(400), "Bad Request" },
-  { COAP_RESPONSE_CODE(401), "Unauthorized" },
-  { COAP_RESPONSE_CODE(402), "Bad Option" },
-  { COAP_RESPONSE_CODE(403), "Forbidden" },
-  { COAP_RESPONSE_CODE(404), "Not Found" },
-  { COAP_RESPONSE_CODE(405), "Method Not Allowed" },
-  { COAP_RESPONSE_CODE(408), "Request Entity Incomplete" },
-  { COAP_RESPONSE_CODE(413), "Request Entity Too Large" },
-  { COAP_RESPONSE_CODE(415), "Unsupported Media Type" },
-  { COAP_RESPONSE_CODE(500), "Internal Server Error" },
-  { COAP_RESPONSE_CODE(501), "Not Implemented" },
-  { COAP_RESPONSE_CODE(502), "Bad Gateway" },
-  { COAP_RESPONSE_CODE(503), "Service Unavailable" },
-  { COAP_RESPONSE_CODE(504), "Gateway Timeout" },
-  { COAP_RESPONSE_CODE(505), "Proxying Not Supported" },
-  { 0, NULL }                  /* end marker */
-};
-
-const char *
-coap_response_phrase(unsigned char code) {
-  int i;
-  for (i = 0; coap_error[i].code; ++i) {
-    if (coap_error[i].code == code)
-      return coap_error[i].phrase;
-  }
-  return NULL;
-}
-#endif
-
-/**
- * Advances *optp to next option if still in PDU. This function
- * returns the number of bytes opt has been advanced or @c 0
- * on error.
- */
-static size_t
-next_option_safe(coap_opt_t **optp, size_t *length) {
-  coap_option_t option;
-  size_t optsize;
-
-  assert(optp); assert(*optp);
-  assert(length);
-
-  optsize = coap_opt_parse(*optp, *length, &option);
-  if (optsize) {
-    assert(optsize <= *length);
-
-    *optp += optsize;
-    *length -= optsize;
-  }
-
-  return optsize;
-}
-
-int
-coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu) {
-  coap_opt_t *opt;
-
-  assert(data);
-  assert(pdu);
-
-  if (pdu->max_size < length) {
-    debug("insufficient space to store parsed PDU\n");
-    return 0;
-  }
-
-  if (length < sizeof(coap_hdr_t)) {
-    debug("discarded invalid PDU\n");
-  }
-
-  pdu->hdr->version = data[0] >> 6;
-  pdu->hdr->type = (data[0] >> 4) & 0x03;
-  pdu->hdr->token_length = data[0] & 0x0f;
-  pdu->hdr->code = data[1];
-  pdu->data = NULL;
-
-  /* sanity checks */
-  if (pdu->hdr->code == 0) {
-    if (length != sizeof(coap_hdr_t) || pdu->hdr->token_length) {
-      debug("coap_pdu_parse: empty message is not empty\n");
-      goto discard;
-    }
-  }
-
-  if (length < sizeof(coap_hdr_t) + pdu->hdr->token_length
-      || pdu->hdr->token_length > 8) {
-    debug("coap_pdu_parse: invalid Token\n");
-    goto discard;
-  }
-
-  /* Copy message id in network byte order, so we can easily write the
-   * response back to the network. */
-  memcpy(&pdu->hdr->id, data + 2, 2);
-
-  /* append data (including the Token) to pdu structure */
-  memcpy(pdu->hdr + 1, data + sizeof(coap_hdr_t), length - sizeof(coap_hdr_t));
-  pdu->length = length;
-
-  /* Finally calculate beginning of data block and thereby check integrity
-   * of the PDU structure. */
-
-  /* skip header + token */
-  length -= (pdu->hdr->token_length + sizeof(coap_hdr_t));
-  opt = (unsigned char *)(pdu->hdr + 1) + pdu->hdr->token_length;
-
-  while (length && *opt != COAP_PAYLOAD_START) {
-
-    if (!next_option_safe(&opt, (size_t *)&length)) {
-      debug("coap_pdu_parse: drop\n");
-      goto discard;
-    }
-  }
-
-  /* end of packet or start marker */
-  if (length) {
-    assert(*opt == COAP_PAYLOAD_START);
-    opt++; length--;
-
-    if (!length) {
-      debug("coap_pdu_parse: message ending in payload start marker\n");
-      goto discard;
-    }
-
-    debug("set data to %p (pdu ends at %p)\n", (unsigned char *)opt,
-         (unsigned char *)pdu->hdr + pdu->length);
-    pdu->data = (unsigned char *)opt;
-  }
-
-  return 1;
-
- discard:
-  return 0;
-}
diff --git a/resource/csdk/libcoap-4.1.1/pdu.h b/resource/csdk/libcoap-4.1.1/pdu.h
deleted file mode 100644 (file)
index 8b76776..0000000
+++ /dev/null
@@ -1,377 +0,0 @@
-/* pdu.h -- CoAP message structure
- *
- * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#ifndef _PDU_H_
-#define _PDU_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "config.h"
-#include "coap_list.h"
-#include "uri.h"
-
-#ifdef WITH_LWIP
-#include <lwip/pbuf.h>
-#endif
-
-/* pre-defined constants that reflect defaults for CoAP */
-// This value is based on the DEFAULT_LEISURE (5 seconds) defined in RFC 7252
-#define MAX_MULTICAST_DELAY_SEC (5)
-
-/* response timeout in seconds, this can not be less that the delays between calls to OCProcess*/
-#define COAP_DEFAULT_RESPONSE_TIMEOUT  2
-#define COAP_DEFAULT_MAX_RETRANSMIT    4 /* max number of retransmissions */
-#define COAP_DEFAULT_PORT           5683 /* CoAP default UDP port */
-#define COAP_DEFAULT_MAX_AGE          60 /* default maximum object lifetime in seconds */
-#ifndef COAP_MAX_PDU_SIZE
-#ifdef WITH_ARDUINO
-#define COAP_MAX_PDU_SIZE           320 /* maximum size of a CoAP PDU for embedded platforms*/
-#else
-#define COAP_MAX_PDU_SIZE           1400 /* maximum size of a CoAP PDU for big platforms*/
-#endif
-#endif /* COAP_MAX_PDU_SIZE */
-
-#define COAP_DEFAULT_VERSION           1 /* version of CoAP supported */
-#define COAP_DEFAULT_SCHEME        "coap" /* the default scheme for CoAP URIs */
-
-/** well-known resources URI */
-#define COAP_DEFAULT_URI_WELLKNOWN ".well-known/core"
-
-#ifdef __COAP_DEFAULT_HASH
-/* pre-calculated hash key for the default well-known URI */
-#define COAP_DEFAULT_WKC_HASHKEY   "\345\130\144\245"
-#endif
-
-/* CoAP message types */
-
-#define COAP_MESSAGE_CON               0 /* confirmable message (requires ACK/RST) */
-#define COAP_MESSAGE_NON               1 /* non-confirmable message (one-shot message) */
-#define COAP_MESSAGE_ACK               2 /* used to acknowledge confirmable messages */
-#define COAP_MESSAGE_RST               3 /* indicates error in received messages */
-
-/* CoAP request methods */
-
-#define COAP_REQUEST_GET       1
-#define COAP_REQUEST_POST      2
-#define COAP_REQUEST_PUT       3
-#define COAP_REQUEST_DELETE    4
-
-/* CoAP option types (be sure to update check_critical when adding options */
-
-#define COAP_OPTION_IF_MATCH      1 /* C, opaque, 0-8 B, (none) */
-#define COAP_OPTION_URI_HOST      3 /* C, String, 1-255 B, destination address */
-#define COAP_OPTION_ETAG          4 /* E, opaque, 1-8 B, (none) */
-#define COAP_OPTION_IF_NONE_MATCH 5 /* empty, 0 B, (none) */
-#define COAP_OPTION_URI_PORT      7 /* C, uint, 0-2 B, destination port */
-#define COAP_OPTION_LOCATION_PATH 8 /* E, String, 0-255 B, - */
-#define COAP_OPTION_URI_PATH     11 /* C, String, 0-255 B, (none) */
-#define COAP_OPTION_CONTENT_FORMAT 12 /* E, uint, 0-2 B, (none) */
-#define COAP_OPTION_CONTENT_TYPE COAP_OPTION_CONTENT_FORMAT
-#define COAP_OPTION_MAXAGE       14 /* E, uint, 0--4 B, 60 Seconds */
-#define COAP_OPTION_URI_QUERY    15 /* C, String, 1-255 B, (none) */
-#define COAP_OPTION_ACCEPT       17 /* C, uint,   0-2 B, (none) */
-#define COAP_OPTION_LOCATION_QUERY 20 /* E, String,   0-255 B, (none) */
-#define COAP_OPTION_PROXY_URI    35 /* C, String, 1-1034 B, (none) */
-#define COAP_OPTION_PROXY_SCHEME 39 /* C, String, 1-255 B, (none) */
-#define COAP_OPTION_SIZE2        28 /* E, uint, 0-4 B, (none) */
-#define COAP_OPTION_SIZE1        60 /* E, uint, 0-4 B, (none) */
-
-/* option types from draft-ietf-coap-observe-09 */
-
-#define COAP_OPTION_OBSERVE       6 /* E, empty/uint, 0 B/0-3 B, (none) */
-#define COAP_OPTION_SUBSCRIPTION  COAP_OPTION_OBSERVE
-
-/* selected option types from draft-core-block-04 */
-
-#define COAP_OPTION_BLOCK2       23 /* C, uint, 0--3 B, (none) */
-#define COAP_OPTION_BLOCK1       27 /* C, uint, 0--3 B, (none) */
-
-#define COAP_VENDOR_OPT_START    (2048)
-/**< the highest option number we know
- * COAP_MAX_OPT has to be larger than COAP_VENDOR_OPT_START
- * however, we should keep in mind that COAP_MAX_OPT
- * impacts the size of option filter as its size is about
- * ceil(COAP_MAX_OPT>>3)
- * Default is 3000 (just a nice round number)
- */
-#define COAP_MAX_OPT             (3000)
-
-/* CoAP result codes (HTTP-Code / 100 * 40 + HTTP-Code % 100) */
-
-/* As of draft-ietf-core-coap-04, response codes are encoded to base
- * 32, i.e.  the three upper bits determine the response class while
- * the remaining five fine-grained information specific to that class.
- */
-#define COAP_RESPONSE_CODE(N) (((N)/100 << 5) | (N)%100)
-
-/* Determines the class of response code C */
-#define COAP_RESPONSE_CLASS(C) (((C) >> 5) & 0xFF)
-
-#ifndef SHORT_ERROR_RESPONSE
-/**
- * Returns a human-readable response phrase for the specified CoAP
- * response @p code. This function returns @c NULL if not found.
- *
- * @param code The response code for which the literal phrase should
- * be retrieved.
- *
- * @return A zero-terminated string describing the error, or @c NULL
- * if not found.
- */
-const char *coap_response_phrase(unsigned char code);
-
-#define COAP_ERROR_PHRASE_LENGTH 32 /**< maximum length of error phrase */
-
-#else
-#define coap_response_phrase(x) ((char *)NULL)
-
-#define COAP_ERROR_PHRASE_LENGTH 0 /**< maximum length of error phrase */
-#endif /* SHORT_ERROR_RESPONSE */
-
-/* The following definitions exist for backwards compatibility */
-#if 0 /* this does not exist any more */
-#define COAP_RESPONSE_100      40 /* 100 Continue */
-#endif
-#define COAP_RESPONSE_200      COAP_RESPONSE_CODE(200)  /* 2.00 OK */
-#define COAP_RESPONSE_201      COAP_RESPONSE_CODE(201)  /* 2.01 Created */
-#define COAP_RESPONSE_202      COAP_RESPONSE_CODE(202)  /* 2.02 Deleted */
-#define COAP_RESPONSE_304      COAP_RESPONSE_CODE(203)  /* 2.03 Valid */
-#define COAP_RESPONSE_400      COAP_RESPONSE_CODE(400)  /* 4.00 Bad Request */
-#define COAP_RESPONSE_403      COAP_RESPONSE_CODE(403)  /* 4.03 Forbidden */
-#define COAP_RESPONSE_404      COAP_RESPONSE_CODE(404)  /* 4.04 Not Found */
-#define COAP_RESPONSE_405      COAP_RESPONSE_CODE(405)  /* 4.05 Method Not Allowed */
-#define COAP_RESPONSE_415      COAP_RESPONSE_CODE(415)  /* 4.15 Unsupported Media Type */
-#define COAP_RESPONSE_500      COAP_RESPONSE_CODE(500)  /* 5.00 Internal Server Error */
-#define COAP_RESPONSE_501      COAP_RESPONSE_CODE(501)  /* 5.01 Not Implemented */
-#define COAP_RESPONSE_503      COAP_RESPONSE_CODE(503)  /* 5.03 Service Unavailable */
-#define COAP_RESPONSE_504      COAP_RESPONSE_CODE(504)  /* 5.04 Gateway Timeout */
-#if 0  /* these response codes do not have a valid code any more */
-#  define COAP_RESPONSE_X_240    240   /* Token Option required by server */
-#  define COAP_RESPONSE_X_241    241   /* Uri-Authority Option required by server */
-#endif
-#define COAP_RESPONSE_X_242    COAP_RESPONSE_CODE(402)  /* Critical Option not supported */
-
-/* CoAP media type encoding */
-
-#define COAP_MEDIATYPE_TEXT_PLAIN                     0 /* text/plain (UTF-8) */
-#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT       40 /* application/link-format */
-#define COAP_MEDIATYPE_APPLICATION_XML               41 /* application/xml */
-#define COAP_MEDIATYPE_APPLICATION_OCTET_STREAM      42 /* application/octet-stream */
-#define COAP_MEDIATYPE_APPLICATION_RDF_XML           43 /* application/rdf+xml */
-#define COAP_MEDIATYPE_APPLICATION_EXI               47 /* application/exi  */
-#define COAP_MEDIATYPE_APPLICATION_JSON              50 /* application/json  */
-
-/* Note that identifiers for registered media types are in the range 0-65535. We
- * use an unallocated type here and hope for the best. */
-#define COAP_MEDIATYPE_ANY                         0xff /* any media type */
-
-/* CoAP transaction id */
-/*typedef unsigned short coap_tid_t; */
-typedef int coap_tid_t;
-#define COAP_INVALID_TID -1
-
-#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-pedantic"
-#endif
-#ifdef WORDS_BIGENDIAN
-typedef struct {
-  unsigned int version:2;      /* protocol version */
-  unsigned int type:2;         /* type flag */
-  unsigned int token_length:4; /* length of Token */
-  unsigned int code:8;         /* request method (value 1--10) or response code (value 40-255) */
-  unsigned short id;           /* message id */
-  __extension__ unsigned char token[0];        /* the actual token, if any */
-} coap_hdr_t;
-#else
-typedef struct {
-  unsigned int token_length:4; /* length of Token */
-  unsigned int type:2;         /* type flag */
-  unsigned int version:2;      /* protocol version */
-  unsigned int code:8;         /* request method (value 1--10) or response code (value 40-255) */
-  unsigned short id;           /* transaction id (network byte order!) */
-  __extension__ unsigned char token[0];        /* the actual token, if any */
-} coap_hdr_t;
-#endif
-#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
-#pragma GCC diagnostic pop
-#endif
-
-#define COAP_MESSAGE_IS_EMPTY(MSG)    ((MSG)->code == 0)
-#define COAP_MESSAGE_IS_REQUEST(MSG)  (!COAP_MESSAGE_IS_EMPTY(MSG)     \
-                                      && ((MSG)->code < 32))
-#define COAP_MESSAGE_IS_RESPONSE(MSG) ((MSG)->code >= 64 && (MSG)->code <= 191)
-
-#define COAP_OPT_LONG 0x0F     /* OC == 0b1111 indicates that the option list in a
-                                * CoAP message is limited by 0b11110000 marker */
-
-#define COAP_OPT_END 0xF0      /* end marker */
-
-#define COAP_PAYLOAD_START 0xFF        /* payload marker */
-
-/**
- * Structures for more convenient handling of options. (To be used with ordered
- * coap_list_t.) The option's data will be added to the end of the coap_option
- * structure (see macro COAP_OPTION_DATA).
- */
-typedef struct {
-  unsigned short key;          /* the option key (no delta coding) */
-  unsigned int length;
-} coap_option;
-
-#define COAP_OPTION_KEY(option) (option).key
-#define COAP_OPTION_LENGTH(option) (option).length
-#define COAP_OPTION_DATA(option) ((unsigned char *)&(option) + sizeof(coap_option))
-
-/** Header structure for CoAP PDUs */
-
-typedef struct {
-  size_t max_size;     /**< allocated storage for options and data */
-
-  coap_hdr_t *hdr;
-  unsigned short max_delta;    /**< highest option number */
-  unsigned short length;       /**< PDU length (including header, options, data)  */
-  unsigned char *data;         /**< payload */
-
-#ifdef WITH_LWIP
-  struct pbuf *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */
-#endif
-
-} coap_pdu_t;
-
-/** Options in coap_pdu_t are accessed with the macro COAP_OPTION. */
-#define COAP_OPTION(node) ((coap_option *)(node)->options)
-
-#ifdef WITH_LWIP
-/**
- * Creates a CoAP PDU from an lwIP @p pbuf, whose reference is passed on to
- * this function.
- *
- * The pbuf is checked for being contiguous, for having enough head space for
- * the PDU struct (which is located directly in front of the data, overwriting
- * the old other headers), and for having only one reference. The reference is
- * stored in the PDU and will be freed when the PDU is freed.
- *
- * (For now, these are errors; in future, a new pbuf might be allocated, the
- * data copied and the passed pbuf freed).
- *
- * This behaves like coap_pdu_init(0, 0, 0, pbuf->tot_len), and afterwards
- * copying the contents of the pbuf to the pdu.
- *
- * @return A pointer to the new PDU object or @c NULL on error.
- */
-coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf);
-#endif
-
-/**
- * Creates a new CoAP PDU of given @p size (must be large enough to hold the
- * basic CoAP message header (coap_hdr_t). The function returns a pointer to
- * the node coap_pdu_t object on success, or @c NULL on error. The storage
- * allocated for the result must be released with coap_delete_pdu().
- *
- * @param type The type of the PDU (one of COAP_MESSAGE_CON,
- *             COAP_MESSAGE_NON, COAP_MESSAGE_ACK, COAP_MESSAGE_RST).
- * @param code The message code.
- * @param id   The message id to set or COAP_INVALID_TID if unknown.
- * @param size The number of bytes to allocate for the actual message.
- *
- * @return A pointer to the new PDU object or @c NULL on error.
- */
-coap_pdu_t *
-coap_pdu_init(unsigned char type, unsigned char code,
-             unsigned short id, size_t size);
-
-/**
- * Clears any contents from @p pdu and resets @c version field, @c
- * length and @c data pointers. @c max_size is set to @p size, any
- * other field is set to @c 0. Note that @p pdu must be a valid
- * pointer to a coap_pdu_t object created e.g. by coap_pdu_init().
- */
-void coap_pdu_clear(coap_pdu_t *pdu, size_t size);
-
-/**
- * Creates a new CoAP PDU. The object is created on the heap and must be released
- * using coap_delete_pdu();
- *
- * @deprecated This function allocates the maximum storage for each
- * PDU. Use coap_pdu_init() instead.
- */
-coap_pdu_t *coap_new_pdu();
-
-void coap_delete_pdu(coap_pdu_t *);
-
-/**
- * Parses @p data into the CoAP PDU structure given in @p result. This
- * function returns @c 0 on error or a number greater than zero on
- * success.
- *
- * @param data   The raw data to parse as CoAP PDU
- * @param length The actual size of @p data
- * @param result The PDU structure to fill. Note that the structure must
- *               provide space for at least @p length bytes to hold the
- *               entire CoAP PDU.
- * @return A value greater than zero on success or @c 0 on error.
- */
-int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *result);
-
-/**
- * Adds token of length @p len to @p pdu. Adding the token destroys
- * any following contents of the pdu. Hence options and data must be
- * added after coap_add_token() has been called. In @p pdu, length is
- * set to @p len + @c 4, and max_delta is set to @c 0.  This funtion
- * returns @c 0 on error or a value greater than zero on success.
- *
- * @param pdu  The PDU where the token is to be added.
- * @param len  The length of the new token.
- * @param data The token to add.
- * @return A value greater than zero on success, or @c 0 on error.
- */
-int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data);
-
-/**
- * Adds option of given type to pdu that is passed as first
- * parameter. coap_add_option() destroys the PDU's data, so
- * coap_add_data() must be called after all options have been added.
- * As coap_add_token() destroys the options following the token,
- * the token must be added before coap_add_option() is called.
- * This function returns the number of bytes written or @c 0 on error.
- */
-size_t coap_add_option(coap_pdu_t *pdu, unsigned short type,
-                       unsigned int len, const unsigned char *data);
-
-/**
- * Adds option of given type to pdu that is passed as first
- * parameter, but does not write a value. It works like coap_add_option with
- * respect to calling sequence (i.e. after token and before data).
- * This function returns a memory address to which the option data has to be
- * written before the PDU can be sent, or @c NULL on error.
- */
-unsigned char *coap_add_option_later(coap_pdu_t *pdu, unsigned short type,
-                                     unsigned int len);
-
-/**
- * Adds given data to the pdu that is passed as first parameter. Note
- * that the PDU's data is destroyed by coap_add_option(). coap_add_data()
- * must be called only once per PDU, otherwise the result is undefined.
- */
-int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data);
-
-/**
- * Retrieves the length and data pointer of specified PDU. Returns 0 on error
- * or 1 if *len and *data have correct values. Note that these values are
- * destroyed with the pdu.
- */
-int coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _PDU_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/prng.h b/resource/csdk/libcoap-4.1.1/prng.h
deleted file mode 100644 (file)
index 50479c9..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/* prng.h -- Pseudo Random Numbers
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-/** 
- * @file prng.h
- * @brief Pseudo Random Numbers
- */
-
-#ifndef _COAP_PRNG_H_
-#define _COAP_PRNG_H_
-
-#include "config.h"
-#include <ocrandom.h>
-
-/** 
- * @defgroup prng Pseudo Random Numbers
- * @{
- */
-
-#ifndef WITH_CONTIKI
-#include <stdlib.h>
-
-/**
- * Fills \p buf with \p len random bytes. This is the default
- * implementation for prng().  You might want to change prng() to use
- * a better PRNG on your specific platform.
- */
-static inline int
-coap_prng_impl(unsigned char *buf, size_t len) {
-#if 0
-  while (len--)
-    *buf++ = rand() & 0xFF;
-#endif
-  OCFillRandomMem(buf, len);
-  return 1;
-}
-#else /* WITH_CONTIKI */
-#include <string.h>
-
-/**
- * Fills \p buf with \p len random bytes. This is the default
- * implementation for prng().  You might want to change prng() to use
- * a better PRNG on your specific platform.
- */
-static inline int
-contiki_prng_impl(unsigned char *buf, size_t len) {
-  unsigned short v = random_rand();
-  while (len > sizeof(v)) {
-    memcpy(buf, &v, sizeof(v));
-    len -= sizeof(v);
-    buf += sizeof(v);
-    v = random_rand();
-  }
-
-  memcpy(buf, &v, len);
-  return 1;
-}
-
-#define prng(Buf,Length) contiki_prng_impl((Buf), (Length))
-#define prng_init(Value) random_init((unsigned short)(Value))
-#endif /* WITH_CONTIKI */
-
-#ifndef prng
-/** 
- * Fills \p Buf with \p Length bytes of random data. 
- * 
- * @hideinitializer
- */
-#define prng(Buf,Length) coap_prng_impl((Buf), (Length))
-#endif
-
-#ifndef prng_init
-/** 
- * Called to set the PRNG seed. You may want to re-define this to
- * allow for a better PRNG.
- *
- * @hideinitializer
- */
-#define prng_init(Value) OCSeedRandom()//srand((unsigned long)(Value))
-#endif
-
-/** @} */
-
-#endif /* _COAP_PRNG_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/resource.c b/resource/csdk/libcoap-4.1.1/resource.c
deleted file mode 100644 (file)
index f723274..0000000
+++ /dev/null
@@ -1,869 +0,0 @@
-/* resource.c -- generic resource handling
- *
- * Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-#include "net.h"
-#include "debug.h"
-#include "resource.h"
-#include "subscribe.h"
-
-#ifdef WITH_LWIP
-#include "utlist.h"
-/* mem.h is only needed for the string free calls for
- * COAP_ATTR_FLAGS_RELEASE_NAME / COAP_ATTR_FLAGS_RELEASE_VALUE /
- * COAP_RESOURCE_FLAGS_RELEASE_URI. not sure what those lines should actually
- * do on lwip. */
-#include "mem.h"
-
-#include <lwip/memp.h>
-
-#define COAP_MALLOC_TYPE(Type) \
-  ((coap_##Type##_t *)memp_malloc(MEMP_COAP_##Type))
-#define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
-
-#endif
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-#include "utlist.h"
-#include "mem.h"
-
-#define COAP_MALLOC_TYPE(Type) \
-  ((coap_##Type##_t *)coap_malloc(sizeof(coap_##Type##_t)))
-#define COAP_FREE_TYPE(Type, Object) coap_free(Object)
-
-#endif /* WITH_POSIX || WITH_ARDUINO */
-#ifdef WITH_CONTIKI
-#include "memb.h"
-
-MEMB(resource_storage, coap_resource_t, COAP_MAX_RESOURCES);
-MEMB(attribute_storage, coap_attr_t, COAP_MAX_ATTRIBUTES);
-MEMB(subscription_storage, coap_subscription_t, COAP_MAX_SUBSCRIBERS);
-
-void
-coap_resources_init() {
-  memb_init(&resource_storage);
-  memb_init(&attribute_storage);
-  memb_init(&subscription_storage);
-}
-
-static inline coap_subscription_t *
-coap_malloc_subscription() {
-  return memb_alloc(&subscription_storage);
-}
-
-static inline void
-coap_free_subscription(coap_subscription_t *subscription) {
-  memb_free(&subscription_storage, subscription);
-}
-#endif /* WITH_CONTIKI */
-
-#define min(a,b) ((a) < (b) ? (a) : (b))
-
-/* Helper functions for conditional output of character sequences into
- * a given buffer. The first Offset characters are skipped.
- */
-
-/**
- * Adds Char to Buf if Offset is zero. Otherwise, Char is not written
- * and Offset is decremented.
- */
-#define PRINT_WITH_OFFSET(Buf,Offset,Char)        \
-  if ((Offset) == 0) {                    \
-    (*(Buf)++) = (Char);                \
-  } else {                        \
-    (Offset)--;                        \
-  }                            \
-
-/**
- * Adds Char to Buf if Offset is zero and Buf is less than Bufend.
- */
-#define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) {        \
-    if ((Buf) < (Bufend)) {                        \
-      PRINT_WITH_OFFSET(Buf,Offset,Char);                \
-    }                                    \
-    (Result)++;                                \
-  }
-
-/**
- * Copies at most Length characters of Str to Buf. The first Offset
- * characters are skipped. Output may be truncated to Bufend - Buf
- * characters.
- */
-#define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) {    \
-    size_t i;                                \
-    for (i = 0; i < (Length); i++) {                    \
-      PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \
-    }                                    \
-  }
-
-int
-match(const str *text, const str *pattern, int match_prefix, int match_substring) {
-  assert(text); assert(pattern);
-
-  if (text->length < pattern->length)
-    return 0;
-
-  if (match_substring) {
-    unsigned char *next_token = text->s;
-    size_t remaining_length = text->length;
-    while (remaining_length) {
-      size_t token_length;
-      unsigned char *token = next_token;
-      next_token = (unsigned char *)memchr(token, ' ', remaining_length);
-
-      if (next_token) {
-        token_length = next_token - token;
-        remaining_length -= (token_length + 1);
-        next_token++;
-      } else {
-        token_length = remaining_length;
-        remaining_length = 0;
-      }
-
-      if ((match_prefix || pattern->length == token_length) &&
-            memcmp(token, pattern->s, pattern->length) == 0)
-        return 1;
-    }
-    return 0;
-  }
-
-  return (match_prefix || pattern->length == text->length) &&
-    memcmp(text->s, pattern->s, pattern->length) == 0;
-}
-
-/**
- * Prints the names of all known resources to @p buf. This function
- * sets @p buflen to the number of bytes actually written and returns
- * @c 1 on succes. On error, the value in @p buflen is undefined and
- * the return value will be @c 0.
- *
- * @param context The context with the resource map.
- * @param buf     The buffer to write the result.
- * @param buflen  Must be initialized to the maximum length of @p buf and will be
- *                set to the length of the well-known response on return.
- * @param offset  The offset in bytes where the output shall start and is
- *                shifted accordingly with the characters that have been
- *                processed. This parameter is used to support the block
- *                option.
- * @param query_filter A filter query according to <a href="http://tools.ietf.org/html/draft-ietf-core-link-format-11#section-4.1">Link Format</a>
- *
- * @return COAP_PRINT_STATUS_ERROR on error. Otherwise, the lower 28 bits are
- *         set to the number of bytes that have actually been written to
- *         @p buf. COAP_PRINT_STATUS_TRUNC is set when the output has been
- *         truncated.
- */
-#if defined(__GNUC__) && defined(WITHOUT_QUERY_FILTER)
-coap_print_status_t
-print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
-        size_t offset,
-        coap_opt_t *query_filter __attribute__ ((unused))) {
-#else /* not a GCC */
-coap_print_status_t
-print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
-        size_t offset, coap_opt_t *query_filter) {
-#endif /* GCC */
-  coap_resource_t *r;
-  unsigned char *p = buf;
-  const unsigned char *bufend = buf + *buflen;
-  size_t left, written = 0;
-  coap_print_status_t result;
-  const size_t old_offset = offset;
-  int subsequent_resource = 0;
-#ifndef COAP_RESOURCES_NOHASH
-  coap_resource_t *tmp;
-#endif
-#ifndef WITHOUT_QUERY_FILTER
-  str resource_param = { 0, NULL }, query_pattern = { 0, NULL };
-  int flags = 0; /* MATCH_SUBSTRING, MATCH_PREFIX, MATCH_URI */
-#define MATCH_URI       0x01
-#define MATCH_PREFIX    0x02
-#define MATCH_SUBSTRING 0x04
-  static const str _rt_attributes[] = {
-    {2, (unsigned char *)"rt"},
-    {2, (unsigned char *)"if"},
-    {3, (unsigned char *)"rel"},
-    {0, NULL}};
-#endif /* WITHOUT_QUERY_FILTER */
-
-#ifdef WITH_CONTIKI
-  int i;
-#endif /* WITH_CONTIKI */
-
-#ifndef WITHOUT_QUERY_FILTER
-  /* split query filter, if any */
-  if (query_filter) {
-    resource_param.s = COAP_OPT_VALUE(query_filter);
-    while (resource_param.length < COAP_OPT_LENGTH(query_filter)
-       && resource_param.s[resource_param.length] != '=')
-      resource_param.length++;
-
-    if (resource_param.length < COAP_OPT_LENGTH(query_filter)) {
-      const str *rt_attributes;
-      if (resource_param.length == 4 &&
-      memcmp(resource_param.s, "href", 4) == 0)
-    flags |= MATCH_URI;
-
-      for (rt_attributes = _rt_attributes; rt_attributes->s; rt_attributes++) {
-        if (resource_param.length == rt_attributes->length &&
-            memcmp(resource_param.s, rt_attributes->s, rt_attributes->length) == 0) {
-          flags |= MATCH_SUBSTRING;
-          break;
-        }
-      }
-
-      /* rest is query-pattern */
-      query_pattern.s =
-    COAP_OPT_VALUE(query_filter) + resource_param.length + 1;
-
-      assert((resource_param.length + 1) <= COAP_OPT_LENGTH(query_filter));
-      query_pattern.length =
-    COAP_OPT_LENGTH(query_filter) - (resource_param.length + 1);
-
-     if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) {
-       query_pattern.s++;
-       query_pattern.length--;
-      }
-
-      if (query_pattern.length &&
-      query_pattern.s[query_pattern.length-1] == '*') {
-    query_pattern.length--;
-    flags |= MATCH_PREFIX;
-      }
-    }
-  }
-#endif /* WITHOUT_QUERY_FILTER */
-
-#ifndef WITH_CONTIKI
-
-#ifdef COAP_RESOURCES_NOHASH
-  LL_FOREACH(context->resources, r) {
-#else
-  HASH_ITER(hh, context->resources, r, tmp) {
-#endif
-#else /* WITH_CONTIKI */
-  r = (coap_resource_t *)resource_storage.mem;
-  for (i = 0; i < resource_storage.num; ++i, ++r) {
-    if (!resource_storage.count[i])
-      continue;
-#endif /* WITH_CONTIKI */
-
-#ifndef WITHOUT_QUERY_FILTER
-    if (resource_param.length) { /* there is a query filter */
-
-      if (flags & MATCH_URI) {    /* match resource URI */
-    if (!match(&r->uri, &query_pattern, (flags & MATCH_PREFIX) != 0, (flags & MATCH_SUBSTRING) != 0))
-      continue;
-      } else {            /* match attribute */
-    coap_attr_t *attr;
-        str unquoted_val;
-    attr = coap_find_attr(r, resource_param.s, resource_param.length);
-        if (!attr) continue;
-        if (attr->value.s[0] == '"') {          /* if attribute has a quoted value, remove double quotes */
-          unquoted_val.length = attr->value.length - 2;
-          unquoted_val.s = attr->value.s + 1;
-        } else {
-          unquoted_val = attr->value;
-        }
-    if (!(match(&unquoted_val, &query_pattern,
-                    (flags & MATCH_PREFIX) != 0,
-                    (flags & MATCH_SUBSTRING) != 0)))
-      continue;
-      }
-    }
-#endif /* WITHOUT_QUERY_FILTER */
-
-    if (!subsequent_resource) {    /* this is the first resource  */
-      subsequent_resource = 1;
-    } else {
-      PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written);
-    }
-
-    left = bufend - p; /* calculate available space */
-    result = coap_print_link(r, p, &left, &offset);
-
-    if (result & COAP_PRINT_STATUS_ERROR) {
-      break;
-    }
-
-    /* coap_print_link() returns the number of characters that
-     * where actually written to p. Now advance to its end. */
-    p += COAP_PRINT_OUTPUT_LENGTH(result);
-    written += left;
-  }
-
-  *buflen = written;
-  result = p - buf;
-  if (result + old_offset - offset < *buflen) {
-    result |= COAP_PRINT_STATUS_TRUNC;
-  }
-  return result;
-}
-
-coap_resource_t *
-coap_resource_init(const unsigned char *uri, size_t len, int flags) {
-  coap_resource_t *r;
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-  r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
-#endif
-#ifdef WITH_LWIP
-  r = (coap_resource_t *)memp_malloc(MEMP_COAP_RESOURCE);
-#endif
-#ifdef WITH_CONTIKI
-  r = (coap_resource_t *)memb_alloc(&resource_storage);
-#endif
-  if (r) {
-    memset(r, 0, sizeof(coap_resource_t));
-
-#ifdef WITH_CONTIKI
-    LIST_STRUCT_INIT(r, link_attr);
-#endif /* WITH_CONTIKI */
-    LIST_STRUCT_INIT(r, subscribers);
-
-    r->uri.s = (unsigned char *)uri;
-    r->uri.length = len;
-
-    coap_hash_path(r->uri.s, r->uri.length, r->key);
-
-    r->flags = flags;
-  } else {
-    debug("coap_resource_init: no memory left\n");
-  }
-
-  return r;
-}
-
-coap_attr_t *
-coap_add_attr(coap_resource_t *resource,
-          const unsigned char *name, size_t nlen,
-          const unsigned char *val, size_t vlen,
-              int flags) {
-  coap_attr_t *attr;
-
-  if (!resource || !name)
-    return NULL;
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-  attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
-#endif
-#ifdef WITH_LWIP
-  attr = (coap_attr_t *)memp_malloc(MEMP_COAP_RESOURCEATTR);
-#endif
-#ifdef WITH_CONTIKI
-  attr = (coap_attr_t *)memb_alloc(&attribute_storage);
-#endif
-
-  if (attr) {
-    attr->name.length = nlen;
-    attr->value.length = val ? vlen : 0;
-
-    attr->name.s = (unsigned char *)name;
-    attr->value.s = (unsigned char *)val;
-
-    attr->flags = flags;
-
-    /* add attribute to resource list */
-#ifndef WITH_CONTIKI
-    LL_PREPEND(resource->link_attr, attr);
-#else /* WITH_CONTIKI */
-    list_add(resource->link_attr, attr);
-#endif /* WITH_CONTIKI */
-  } else {
-    debug("coap_add_attr: no memory left\n");
-  }
-
-  return attr;
-}
-
-coap_attr_t *
-coap_find_attr(coap_resource_t *resource,
-           const unsigned char *name, size_t nlen) {
-  coap_attr_t *attr;
-
-  if (!resource || !name)
-    return NULL;
-
-#ifndef WITH_CONTIKI
-  LL_FOREACH(resource->link_attr, attr) {
-#else /* WITH_CONTIKI */
-  for (attr = list_head(resource->link_attr); attr;
-       attr = list_item_next(attr)) {
-#endif /* WITH_CONTIKI */
-    if (attr->name.length == nlen &&
-    memcmp(attr->name.s, name, nlen) == 0)
-      return attr;
-  }
-
-  return NULL;
-}
-
-void
-coap_delete_attr(coap_attr_t *attr) {
-  if (!attr)
-    return;
-  if (attr->flags & COAP_ATTR_FLAGS_RELEASE_NAME)
-    coap_free(attr->name.s);
-  if (attr->flags & COAP_ATTR_FLAGS_RELEASE_VALUE)
-    coap_free(attr->value.s);
-#ifdef POSIX
-  coap_free(attr);
-#endif
-#ifdef WITH_LWIP
-  memp_free(MEMP_COAP_RESOURCEATTR, attr);
-#endif
-#ifdef WITH_CONTIKI
-  /* FIXME it looks like this was never implemented */
-#endif
-}
-
-void
-coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key) {
-  coap_opt_iterator_t opt_iter;
-  coap_opt_filter_t filter;
-  coap_opt_t *option;
-
-  memset(key, 0, sizeof(coap_key_t));
-
-  coap_option_filter_clear(filter);
-  coap_option_setb(filter, COAP_OPTION_URI_PATH);
-
-  coap_option_iterator_init((coap_pdu_t *)request, &opt_iter, filter);
-  while ((option = coap_option_next(&opt_iter)))
-    coap_hash(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), key);
-}
-
-void
-coap_add_resource(coap_context_t *context, coap_resource_t *resource) {
-#ifndef WITH_CONTIKI
-#ifdef COAP_RESOURCES_NOHASH
-  LL_PREPEND(context->resources, resource);
-#else
-  HASH_ADD(hh, context->resources, key, sizeof(coap_key_t), resource);
-#endif
-#endif /* WITH_CONTIKI */
-}
-
-int
-coap_delete_resource(coap_context_t *context, coap_key_t key) {
-  coap_resource_t *resource;
-  coap_attr_t *attr, *tmp;
-#ifdef WITH_CONTIKI
-  coap_subscription_t *obs;
-#endif
-
-  if (!context)
-    return 0;
-
-  resource = coap_get_resource_from_key(context, key);
-
-  if (!resource)
-    return 0;
-
-#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
-#ifdef COAP_RESOURCES_NOHASH
-  LL_DELETE(context->resources, resource);
-#else
-  HASH_DELETE(hh, context->resources, resource);
-#endif
-
-  /* delete registered attributes */
-  LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
-
-  if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
-    coap_free(resource->uri.s);
-
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
-  coap_free(resource);
-#endif
-#ifdef WITH_LWIP
-  memp_free(MEMP_COAP_RESOURCE, resource);
-#endif
-#else /* not (WITH_POSIX || WITH_LWIP || WITH_ARDUINO) */
-  /* delete registered attributes */
-  while ( (attr = list_pop(resource->link_attr)) )
-    memb_free(&attribute_storage, attr);
-
-  /* delete subscribers */
-  while ( (obs = list_pop(resource->subscribers)) ) {
-    /* FIXME: notify observer that its subscription has been removed */
-    memb_free(&subscription_storage, obs);
-  }
-
-  memb_free(&resource_storage, resource);
-#endif /* WITH_CONTIKI */
-
-  return 1;
-}
-
-coap_resource_t *
-coap_get_resource_from_key(coap_context_t *context, coap_key_t key) {
-#ifndef WITH_CONTIKI
-  coap_resource_t *resource;
-#ifdef COAP_RESOURCES_NOHASH
-  resource = NULL;
-  LL_FOREACH(context->resources, resource) {
-    /* if you think you can outspart the compiler and speed things up by (eg by
-     * casting to uint32* and comparing alues), increment this counter: 1 */
-    if (memcmp(key, resource->key, sizeof(coap_key_t)) == 0)
-        return resource;
-  }
-  return NULL;
-#else
-  HASH_FIND(hh, context->resources, key, sizeof(coap_key_t), resource);
-
-  return resource;
-#endif
-#else /* WITH_CONTIKI */
-  int i;
-  coap_resource_t *ptr2;
-
-  /* the search function is basically taken from memb.c */
-  ptr2 = (coap_resource_t *)resource_storage.mem;
-  for (i = 0; i < resource_storage.num; ++i) {
-    if (resource_storage.count[i] &&
-    (memcmp(ptr2->key, key, sizeof(coap_key_t)) == 0))
-      return (coap_resource_t *)ptr2;
-    ++ptr2;
-  }
-
-  return NULL;
-#endif /* WITH_CONTIKI */
-}
-
-coap_print_status_t
-coap_print_link(const coap_resource_t *resource,
-        unsigned char *buf, size_t *len, size_t *offset) {
-  unsigned char *p = buf;
-  const unsigned char *bufend = buf + *len;
-  coap_attr_t *attr;
-  coap_print_status_t result = 0;
-  const size_t old_offset = *offset;
-
-  *len = 0;
-  PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len);
-  PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len);
-
-  COPY_COND_WITH_OFFSET(p, bufend, *offset,
-            resource->uri.s, resource->uri.length, *len);
-
-  PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len);
-
-#ifndef WITH_CONTIKI
-  LL_FOREACH(resource->link_attr, attr) {
-#else /* WITH_CONTIKI */
-  for (attr = list_head(resource->link_attr); attr;
-       attr = list_item_next(attr)) {
-#endif /* WITH_CONTIKI */
-
-    PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len);
-
-    COPY_COND_WITH_OFFSET(p, bufend, *offset,
-              attr->name.s, attr->name.length, *len);
-
-    if (attr->value.s) {
-      PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len);
-
-      COPY_COND_WITH_OFFSET(p, bufend, *offset,
-                attr->value.s, attr->value.length, *len);
-    }
-
-  }
-  if (resource->observable) {
-    COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len);
-  }
-
-  result = p - buf;
-  if (result + old_offset - *offset < *len) {
-    result |= COAP_PRINT_STATUS_TRUNC;
-  }
-
-  return result;
-}
-
-#ifndef WITHOUT_OBSERVE
-coap_subscription_t *
-coap_find_observer(coap_resource_t *resource, const coap_address_t *peer,
-             const str *token) {
-  coap_subscription_t *s;
-
-  assert(resource);
-  assert(peer);
-
-  for (s = (coap_subscription_t*)list_head(resource->subscribers); s;
-        s = (coap_subscription_t*)list_item_next(s)) {
-    if (coap_address_equals(&s->subscriber, peer)
-    && (!token || (token->length == s->token_length
-               && memcmp(token->s, s->token, token->length) == 0)))
-      return s;
-  }
-
-  return NULL;
-}
-
-coap_subscription_t *
-coap_add_observer(coap_resource_t *resource,
-          const coap_address_t *observer,
-          const str *token) {
-  coap_subscription_t *s;
-
-  assert(observer);
-
-  /* Check if there is already a subscription for this peer. */
-  s = coap_find_observer(resource, observer, token);
-
-  /* We are done if subscription was found. */
-  if (s)
-    return s;
-
-  /* s points to a different subscription, so we have to create
-   * another one. */
-  s = COAP_MALLOC_TYPE(subscription);
-
-  if (!s)
-    return NULL;
-
-  coap_subscription_init(s);
-  memcpy(&s->subscriber, observer, sizeof(coap_address_t));
-
-  if (token && token->length) {
-    s->token_length = token->length;
-    memcpy(s->token, token->s, min(s->token_length, 8));
-  }
-
-  /* add subscriber to resource */
-  list_add(resource->subscribers, s);
-
-  return s;
-}
-
-void
-coap_touch_observer(coap_context_t *context, const coap_address_t *observer,
-            const str *token) {
-  coap_resource_t *r;
-  coap_subscription_t *s;
-
-#ifndef WITH_CONTIKI
-#ifdef COAP_RESOURCES_NOHASH
-  LL_FOREACH(context->resources, r) {
-#else
-  coap_resource_t *tmp;
-  HASH_ITER(hh, context->resources, r, tmp) {
-#endif
-    s = coap_find_observer(r, observer, token);
-    if (s) {
-      s->fail_cnt = 0;
-    }
-  }
-#else /* WITH_CONTIKI */
-  r = (coap_resource_t *)resource_storage.mem;
-  for (i = 0; i < resource_storage.num; ++i, ++r) {
-    if (resource_storage.count[i]) {
-      s = coap_find_observer(r, observer, token);
-      if (s) {
-    s->fail_cnt = 0;
-      }
-    }
-  }
-#endif /* WITH_CONTIKI */
-}
-
-void
-coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer,
-             const str *token) {
-  coap_subscription_t *s;
-
-  s = coap_find_observer(resource, observer, token);
-
-  if (s) {
-    list_remove(resource->subscribers, s);
-
-    COAP_FREE_TYPE(subscription,s);
-  }
-}
-
-static void
-coap_notify_observers(coap_context_t *context, coap_resource_t *r) {
-  coap_method_handler_t h;
-  coap_subscription_t *obs;
-  str token;
-  coap_pdu_t *response;
-
-  if (r->observable && (r->dirty || r->partiallydirty)) {
-    r->partiallydirty = 0;
-
-    /* retrieve GET handler, prepare response */
-    h = r->handler[COAP_REQUEST_GET - 1];
-    assert(h);        /* we do not allow subscriptions if no
-             * GET handler is defined */
-
-    for (obs = (coap_subscription_t*)list_head(r->subscribers); obs;
-            obs = (coap_subscription_t*)list_item_next(obs)) {
-      if (r->dirty == 0 && obs->dirty == 0)
-        /* running this resource due to partiallydirty, but this observation's notification was already enqueued */
-        continue;
-
-      coap_tid_t tid = COAP_INVALID_TID;
-      obs->dirty = 0;
-      /* initialize response */
-      response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE);
-      if (!response) {
-        obs->dirty = 1;
-        r->partiallydirty = 1;
-    debug("coap_check_notify: pdu init failed, resource stays partially dirty\n");
-    continue;
-      }
-
-      if (!coap_add_token(response, obs->token_length, obs->token)) {
-        obs->dirty = 1;
-        r->partiallydirty = 1;
-    debug("coap_check_notify: cannot add token, resource stays partially dirty\n");
-    coap_delete_pdu(response);
-    continue;
-      }
-
-      token.length = obs->token_length;
-      token.s = obs->token;
-
-      response->hdr->id = coap_new_message_id(context);
-      if (obs->non && obs->non_cnt < COAP_OBS_MAX_NON) {
-    response->hdr->type = COAP_MESSAGE_NON;
-      } else {
-    response->hdr->type = COAP_MESSAGE_CON;
-      }
-      /* fill with observer-specific data */
-      h(context, r, &obs->subscriber, NULL, &token, response);
-
-      if (response->hdr->type == COAP_MESSAGE_CON) {
-    tid = coap_send(context, &obs->subscriber, response, SEND_NOW_CON);
-    obs->non_cnt = 0;
-      } else {
-    tid = coap_send(context, &obs->subscriber, response, SEND_NOW);
-    obs->non_cnt++;
-      }
-
-      if (COAP_INVALID_TID == tid || response->hdr->type != COAP_MESSAGE_CON)
-    coap_delete_pdu(response);
-      if (COAP_INVALID_TID == tid)
-      {
-    debug("coap_check_notify: sending failed, resource stays partially dirty\n");
-        obs->dirty = 1;
-        r->partiallydirty = 1;
-      }
-
-    }
-
-    /* Increment value for next Observe use. */
-    context->observe++;
-  }
-  r->dirty = 0;
-}
-
-void
-coap_check_notify(coap_context_t *context) {
-  coap_resource_t *r;
-#ifndef WITH_CONTIKI
-
-#ifdef COAP_RESOURCES_NOHASH
-  LL_FOREACH(context->resources, r) {
-#else
-  coap_resource_t *tmp;
-  HASH_ITER(hh, context->resources, r, tmp) {
-#endif
-    coap_notify_observers(context, r);
-  }
-#else /* WITH_CONTIKI */
-  int i;
-
-  r = (coap_resource_t *)resource_storage.mem;
-  for (i = 0; i < resource_storage.num; ++i, ++r) {
-    if (resource_storage.count[i]) {
-      coap_notify_observers(context, r);
-    }
-  }
-#endif /* WITH_CONTIKI */
-}
-
-/**
- * Checks the failure counter for (peer, token) and removes peer from
- * the list of observers for the given resource when COAP_OBS_MAX_FAIL
- * is reached.
- *
- * @param context  The CoAP context to use
- * @param resource The resource to check for (peer, token)
- * @param peer     The observer's address
- * @param token    The token that has been used for subscription.
- */
-static void
-coap_remove_failed_observers(coap_context_t *context,
-                 coap_resource_t *resource,
-                 const coap_address_t *peer,
-                 const str *token) {
-  coap_subscription_t *obs;
-
-  for (obs = (coap_subscription_t*)list_head(resource->subscribers); obs;
-       obs = (coap_subscription_t*)list_item_next(obs)) {
-    if (coap_address_equals(peer, &obs->subscriber) &&
-    token->length == obs->token_length &&
-    memcmp(token->s, obs->token, token->length) == 0) {
-
-      /* count failed notifies and remove when
-       * COAP_MAX_FAILED_NOTIFY is reached */
-      if (obs->fail_cnt < COAP_OBS_MAX_FAIL)
-    obs->fail_cnt++;
-      else {
-    list_remove(resource->subscribers, obs);
-    obs->fail_cnt = 0;
-
-#ifndef NDEBUG
-    if (LOG_DEBUG <= coap_get_log_level()) {
-#ifndef INET6_ADDRSTRLEN
-#define INET6_ADDRSTRLEN 40
-#endif
-      unsigned char addr[INET6_ADDRSTRLEN+8];
-
-      if (coap_print_addr(&obs->subscriber, addr, INET6_ADDRSTRLEN+8))
-        debug("** removed observer %s\n", addr);
-    }
-#endif
-    coap_cancel_all_messages(context, &obs->subscriber,
-                 obs->token, obs->token_length);
-
-    COAP_FREE_TYPE(subscription, obs);
-      }
-    }
-    break;            /* break loop if observer was found */
-  }
-}
-
-void
-coap_handle_failed_notify(coap_context_t *context,
-              const coap_address_t *peer,
-              const str *token) {
-  coap_resource_t *r;
-
-#ifndef WITH_CONTIKI
-
-#ifdef COAP_RESOURCES_NOHASH
-  LL_FOREACH(context->resources, r) {
-#else
-  coap_resource_t *tmp;
-  HASH_ITER(hh, context->resources, r, tmp) {
-#endif
-    coap_remove_failed_observers(context, r, peer, token);
-  }
-#else /* WITH_CONTIKI */
-  int i;
-
-  r = (coap_resource_t *)resource_storage.mem;
-  for (i = 0; i < resource_storage.num; ++i, ++r) {
-    if (resource_storage.count[i]) {
-      coap_remove_failed_observers(context, r, peer, token);
-    }
-  }
-#endif /* WITH_CONTIKI */
-}
-#endif /* WITHOUT_NOTIFY */
diff --git a/resource/csdk/libcoap-4.1.1/resource.h b/resource/csdk/libcoap-4.1.1/resource.h
deleted file mode 100644 (file)
index ede32f5..0000000
+++ /dev/null
@@ -1,332 +0,0 @@
-/* resource.h -- generic resource handling
- *
- * Copyright (C) 2010,2011,2014 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-/** 
- * @file resource.h
- * @brief generic resource handling
- */
-
-#ifndef _COAP_RESOURCE_H_
-#define _COAP_RESOURCE_H_
-
-#include "config.h"
-#include "t_list.h"
-#include "async.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if defined(HAVE_ASSERT_H) && !defined(assert)
-# include <assert.h>
-#endif
-
-#ifndef COAP_RESOURCE_CHECK_TIME
-/** The interval in seconds to check if resources have changed. */
-#define COAP_RESOURCE_CHECK_TIME 2
-#endif /* COAP_RESOURCE_CHECK_TIME */
-
-#ifndef WITH_CONTIKI
-#  ifdef COAP_RESOURCES_NOHASH
-#    include "utlist.h"
-#  else
-#    include "uthash.h"
-#  endif
-#else /* WITH_CONTIKI */
-#endif /* WITH_CONTIKI */
-#include "hashkey.h"
-#include "str.h"
-#include "pdu.h"
-#include "net.h"
-#include "subscribe.h"
-
-/** Definition of message handler function (@sa coap_resource_t). */
-typedef void (*coap_method_handler_t)
-  (coap_context_t  *, struct coap_resource_t *, coap_address_t *, coap_pdu_t *,
-   str * /* token */, coap_pdu_t * /* response */);
-
-#define COAP_ATTR_FLAGS_RELEASE_NAME  0x1
-#define COAP_ATTR_FLAGS_RELEASE_VALUE 0x2
-
-typedef struct coap_attr_t {
-  struct coap_attr_t *next;
-  str name;
-  str value;
-  int flags;
-} coap_attr_t;
-
-#define COAP_RESOURCE_FLAGS_RELEASE_URI 0x1
-
-typedef struct coap_resource_t {
-  unsigned int dirty:1;              /**< set to 1 if resource has changed */
-  unsigned int partiallydirty:1; /**< set to 1 if some subscribers have not yet been notified of the last change */
-  unsigned int observable:1; /**< can be observed */
-  unsigned int cacheable:1;   /**< can be cached */
-
-  /** 
-   * Used to store handlers for the four coap methods @c GET, @c POST,
-   * @c PUT, and @c DELETE. coap_dispatch() will pass incoming
-   * requests to the handler that corresponds to its request method or
-   * generate a 4.05 response if no handler is available.
-   */
-  coap_method_handler_t handler[4];
-
-  coap_key_t key;      /**< the actual key bytes for this resource */
-
-#ifndef WITH_CONTIKI
-#ifdef COAP_RESOURCES_NOHASH
-  struct coap_resource_t *next;
-#else
-  UT_hash_handle hh;
-#endif
-#endif /* WITH_CONTIKI */
-
-#ifndef WITH_CONTIKI
-  coap_attr_t *link_attr; /**< attributes to be included with the link format */
-#else /* WITH_CONTIKI */
-  LIST_STRUCT(link_attr); /**< attributes to be included with the link format */
-#endif /* WITH_CONTIKI */
-  LIST_STRUCT(subscribers); /**< list of observers for this resource */
-
-
-  /**
-   * Request URI for this resource. This field will point into the
-   * static memory. */
-  str uri;
-  int flags;
-
-} coap_resource_t;
-
-/** 
- * Creates a new resource object and initializes the link field to the
- * string of length @p len.  This function returns the
- * new coap_resource_t object.
- * 
- * @param uri    The URI path of the new resource.
- * @param len    The length of @p uri.
- * @param flags  Flags for memory management (in particular release of memory)
- * 
- * @return A pointer to the new object or @c NULL on error.
- */
-coap_resource_t *coap_resource_init(const unsigned char *uri, size_t len, int flags);
-
-/**
- * Registers the given @p resource for @p context. The resource must
- * have been created by coap_resource_init(), the storage allocated
- * for the resource will be released by coap_delete_resource().
- * 
- * @param context  The context to use.
- * @param resource The resource to store.
- */
-void coap_add_resource(coap_context_t *context, coap_resource_t *resource);
-
-/** 
- * Deletes a resource identified by @p key. The storage allocated for
- * that resource is freed.
- * 
- * @param context  The context where the resources are stored.
- * @param key      The unique key for the resource to delete.
- * 
- * @return @c 1 if the resource was found (and destroyed), @c 0 otherwise.
- */
-int coap_delete_resource(coap_context_t *context, coap_key_t key);
-
-/** 
- * Registers a new attribute with the given @p resource. As the
- * attributes str fields will point to @p name and @p val the 
- * caller must ensure that these pointers are valid during the
- * attribute's lifetime.
- * 
- * @param resource  The resource to register the attribute with.
- * @param name      The attribute's name.
- * @param nlen      Length of @p name.
- * @param val       The attribute's value or @c NULL if none.
- * @param vlen      Length of @p val if specified.
- * @param flags     Flags for memory management (in particular release of memory)
- *
- * @return A pointer to the new attribute or @c NULL on error.
- */
-coap_attr_t *coap_add_attr(coap_resource_t *resource,
-                           const unsigned char *name, size_t nlen,
-                           const unsigned char *val, size_t vlen,
-                           int flags);
-
-/**
- * Returns @p resource's coap_attr_t object with given @p name if
- * found, @c NULL otherwise.
- *
- * @param resource  The resource to search for attribute @p name.
- * @param name      Name of the requested attribute.
- * @param nlen      Actual length of @p name.
- * @return The first attribute with specified @p name or @c NULL if
- *         none was found.
- */
-coap_attr_t *coap_find_attr(coap_resource_t *resource, 
-                           const unsigned char *name, size_t nlen);
-
-/** 
- * Deletes an attribute
- * 
- * @param attr  Pointer to a previously created attribute
- * 
- */
-void coap_delete_attr(coap_attr_t *attr);
-
-/**
- * Status word to encode the result of conditional print or copy
- * operations such as coap_print_link(). The lower 28 bits of
- * coap_print_status_t are used to encode the number of characters
- * that has actually been printed, bits 28 to 31 encode the status.
- * When COAP_PRINT_STATUS_ERROR is set, an error occurred during
- * output. In this case, the other bits are undefined.
- * COAP_PRINT_STATUS_TRUNC indicates that the output is truncated,
- * i.e. the printing would have exceeded the current buffer.
- */
-typedef unsigned int coap_print_status_t;
-
-#define COAP_PRINT_STATUS_MASK  0xF0000000u
-#define COAP_PRINT_OUTPUT_LENGTH(v) ((v) & ~COAP_PRINT_STATUS_MASK)
-#define COAP_PRINT_STATUS_ERROR 0x80000000u
-#define COAP_PRINT_STATUS_TRUNC 0x40000000u
-
-/** 
- * Writes a description of this resource in link-format to given text
- * buffer. @p len must be initialized to the maximum length of @p buf
- * and will be set to the number of characters actually written if
- * successful.  This function returns @c 1 on success or @c 0 on
- * error.
- * 
- * @param resource The resource to describe.
- * @param buf      The output buffer to write the description to.
- * @param len      Must be initialized to the length of @p buf and 
- *                 will be set to the length of the printed link description.
- * @param offset   The offset within the resource description where to
- *                 start writing into @p buf. This is useful for dealing
- *                 with the Block2 option. @p offset is updated during
- *                 output as it is consumed.
- * 
- * @return If COAP_PRINT_STATUS_ERROR is set, an error occured. Otherwise,
- *         the lower 28 bits will indicate the number of characters that
- *         have actually been output into @p buffer. The flag
- *         COAP_PRINT_STATUS_TRUNC indicates that the output has been
- *         truncated. 
- */
-coap_print_status_t coap_print_link(const coap_resource_t *resource, 
-                   unsigned char *buf, size_t *len, size_t *offset);
-
-/** 
- * Registers the specified @p handler as message handler for the request type
- * @p method 
- * 
- * @param resource The resource for which the handler shall be registered.
- * @param method   The CoAP request method to handle. 
- * @param handler  The handler to register with @p resource.
- */
-static inline void
-coap_register_handler(coap_resource_t *resource, 
-                     unsigned char method, coap_method_handler_t handler) {
-  assert(resource);
-  assert(method > 0 && (size_t)(method-1) < sizeof(resource->handler)/sizeof(coap_method_handler_t));
-  resource->handler[method-1] = handler;
-}
-
-/** 
- * Returns the resource identified by the unique string @p key. If no
- * resource was found, this function returns @c NULL.
- * 
- * @param context  The context to look for this resource.
- * @param key      The unique key of the resource.
- * 
- * @return A pointer to the resource or @c NULL if not found.
- */
-coap_resource_t *coap_get_resource_from_key(coap_context_t *context, 
-                                           coap_key_t key);
-
-/** 
- * Calculates the hash key for the resource requested by the
- * Uri-Options of @p request.  This function calls coap_hash() for
- * every path segment. 
- * 
- * @param request The requesting pdu.
- * @param key     The resulting hash is stored in @p key
- */
-void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key);
-
-/** 
- * @addtogroup observe 
- */
-
-/**
- * Adds the specified peer as observer for @p resource. The
- * subscription is identified by the given @p token. This function
- * returns the registered subscription information if the @p observer
- * has been added, or @c NULL on error.
- *
- * @param resource The observed resource.
- * @param observer The remote peer that wants to received status updates.
- * @param token The token that identifies this subscription.
- * @param token_length The actual length of @p token. Must be @c 0 when
- *        @p token is @c NULL.
- * @return A pointer to the added/updated subscription information or 
- *        @c NULL on error.
- */
-coap_subscription_t *coap_add_observer(coap_resource_t *resource, 
-                                      const coap_address_t *observer,
-                                      const str *token);
-
-/**
- * Returns a subscription object for given @p peer.
- *
- * @param resource The observed resource.
- * @param peer The address to search for.
- * @param token The token that identifies this subscription or @c NULL for any
- *              token.
- * @return A valid subscription if exists or @c NULL otherwise.
- */
-coap_subscription_t *coap_find_observer(coap_resource_t *resource, 
-                                       const coap_address_t *peer,
-                                       const str *token);
-
-/**
- * Marks an observer as alive.
- *
- * @param context  The CoAP context to use
- * @param observer The transport address of the observer
- * @param token    The corresponding token that has been used for 
- *   the subscription
- */
-void coap_touch_observer(coap_context_t *context, 
-                        const coap_address_t *observer,
-                        const str *token);
-
-/**
- * Removes any subscription for @p observer from @p resource and releases
- * the allocated storage.
- *
- * @param resource The observed resource.
- * @param observer The observer's address.
- * @param token    The token that identifies this subscription or @c NULL for any
- *                 token.
- */
-void coap_delete_observer(coap_resource_t *resource, 
-                         const coap_address_t *observer, 
-                         const str *token);
-
-/** 
- * Checks for all known resources, if they are dirty and notifies
- * subscribed observers.
- */
-void coap_check_notify(coap_context_t *context);
-
-/** @} */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _COAP_RESOURCE_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/sec/netdtls.c b/resource/csdk/libcoap-4.1.1/sec/netdtls.c
deleted file mode 100644 (file)
index e90e64b..0000000
+++ /dev/null
@@ -1,548 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "netdtls.h"
-#include "dtls.h"
-#include "alert.h"
-#include "debug.h"
-#include "logger.h"
-#include "mem.h"
-#include "ocsecurityconfig.h"
-
-#define MOD_NAME ("netdtls.c")
-
-#define get_dtls_ctx(coap_ctx) (coap_ctx->coap_dtls_ctx->dtls_ctx)
-
-extern void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo);
-
-/**
- * An internal method to invoke tinyDTLS library 'dtls_write' method.
- * Return value from this method will indicate if data was successfully sent
- * to peer OR a new DTLS handshake session was invoked OR some error happened
- * while processing.
- *
- */
-static dtls_ret coap_dtls_encrypt_internal(coap_context_t *ctx, OCDevAddr* dst,
-            uint8_t *pt, uint16_t ptLen) {
-    int ret;
-    if (ptLen == 0)
-        return DTLS_OK;
-
-    ret = dtls_write(get_dtls_ctx(ctx), (session_t*)dst, pt, ptLen);
-    if (ret == 0) {
-        // A new DTLS session was initiated by tinyDTLS library
-        return DTLS_SESSION_INITIATED;
-    }
-
-    if (ret == ptLen) {
-        // tinyDTLS library successfully encrypted the data and
-        // sent it to the peer.
-        return DTLS_OK;
-    }
-
-    return DTLS_FAIL;
-}
-
-/**
- * An internal method to invoke tinyDTLS library 'dtls_handle_message' method
- * to decrypt packet received on secure port.
- * Return value from this method will indicate if a valid application pdu was
- * decypted OR a DTLS handshake message was received OR some error happened
- * while processing.
- *
- */
-static dtls_ret coap_dtls_decrypt_internal(coap_context_t *ctx, OCDevAddr* src,
-            uint8_t* ct, int ctLen, uint8_t** pt, int* ptLen) {
-    dtls_ret ret = DTLS_FAIL;
-    pt_info_t ptinfo;
-
-    ptinfo.pt =NULL;
-    ptinfo.ptlen = 0;
-    ctx->coap_dtls_ctx->pt_info = &ptinfo;
-
-    if (dtls_handle_message(get_dtls_ctx(ctx), (session_t*)src, ct, ctLen) == 0) {
-        ret = DTLS_HS_MSG;
-        if (ptinfo.pt && ptinfo.ptlen) {
-            *pt = ptinfo.pt;
-            *ptLen = ptinfo.ptlen;
-            ret = DTLS_OK;
-        }
-    }
-    return ret;
-}
-
-
-/**
- * If tinyDTLS library starts a new DTLS handshake session with a peer, the pdu
- * which was requested by application to encrypt will need to be cached until
- * DTLS session is established. This method caches the pdu in cachedqueue.
- *
- */
-static int coap_cache_pdu(coap_context_t *ctx,
-        coap_queue_t* existing_node,
-        OCDevAddr *dst,
-        coap_pdu_t *pdu,
-        coap_tid_t tid)
-{
-    coap_queue_t *node;
-    coap_tick_t  now;
-
-    if (!ctx)
-        return -1;
-    /* Create a new node for caching the PDU in cachedqueue until
-     * DTLS session is established with peer.
-     */
-    node = coap_new_node();
-    if (!node) {
-        OC_LOG(DEBUG, MOD_NAME, PCF("Unable to allocate memory"));
-        return -1;
-    }
-
-    memcpy(&node->remote, dst, sizeof(coap_address_t));
-    node->pdu = pdu;
-    node->id = tid;
-    node->secure = 1;
-
-    coap_ticks(&now);
-    node->t = now + (COAP_DEFAULT_RESPONSE_TIMEOUT *2) * COAP_TICKS_PER_SECOND;
-
-    if (existing_node) {
-        node->timeout = existing_node->timeout;
-        node->delayedResNeeded = existing_node->delayedResNeeded;
-    }
-
-    // Add the node in cachedqueue list
-    // TODO : Do we need to add some limits on how many packets can be cached ?
-    if (ctx->coap_dtls_ctx->cachedqueue) {
-        coap_queue_t *p = ctx->coap_dtls_ctx->cachedqueue;
-        while(p->next != NULL) {
-            p = p->next;
-        }
-        p->next = node;
-    } else {
-        ctx->coap_dtls_ctx->cachedqueue = node;
-    }
-
-    return 0;
-}
-
-/**
- * Once a DTLS session is established and cached pdu is send, this pdu needs to
- * be saved in 'sendqueue' if this is a CON pdu for re-transmission purposes.
- *
- */
-static void save_cached_con_pdu(coap_context_t *ctx,
-        coap_queue_t *node)
-{
-    coap_tick_t now;
-
-    coap_ticks(&now);
-    if (ctx->sendqueue == NULL)
-    {
-        node->t = node->timeout;
-        ctx->sendqueue_basetime = now;
-    }
-    else
-    {
-        /* make node->t relative to context->sendqueue_basetime */
-        node->t = (now - ctx->sendqueue_basetime) + node->timeout;
-    }
-
-    node->delayedResNeeded = 0;
-    node->next = NULL;
-    coap_insert_node(&ctx->sendqueue, node);
-}
-
-/**
- * Once a DTLS session is established, this method is invoked to retrieve any
- * pdu's available in cachedqueue to be sent to the peer.
- *
- */
-static coap_queue_t* get_cached_pdu( coap_context_t *ctx,
-        const coap_address_t *dst)
-{
-    coap_queue_t *node, *prev;
-
-    node = ctx->coap_dtls_ctx->cachedqueue;
-    prev = NULL;
-    while(node) {
-        if (coap_address_equals(dst, &node->remote)) {
-            //disconnect the node from cachedqueue
-            if (node == ctx->coap_dtls_ctx->cachedqueue)
-                ctx->coap_dtls_ctx->cachedqueue = node->next;
-            else if (node->next == NULL)
-                prev->next = NULL;
-            else
-                prev->next = node->next;
-
-            node->next = NULL;
-            return node;
-        }
-        prev = node;
-        node = node->next;
-    }
-    return NULL;
-}
-
-/**
- * Once a DTLS session is established, this method takes care of sending
- * pdu's available in cachedqueue to the peer.
- *
- */
-static void coap_send_cached_pdu( coap_context_t *ctx,
-        const coap_address_t *dst )
-{
-    coap_queue_t *node;
-
-    if (!ctx)
-        return ;
-
-    for (;(node=get_cached_pdu(ctx, dst));) {
-        OC_LOG(DEBUG, MOD_NAME, PCF("Sending cached PDU"));
-        OC_LOG_BUFFER(DEBUG, MOD_NAME, (uint8_t*)node->pdu->hdr, node->pdu->length);
-        // Send this PDU to DTLS library for encryption
-        dtls_ret ret = coap_dtls_encrypt_internal(ctx, (OCDevAddr*)dst,
-                (uint8_t*)node->pdu->hdr, node->pdu->length);
-        if (ret == DTLS_OK) {
-            OC_LOG(DEBUG, MOD_NAME, PCF("coap_send_cached_pdu: successully send cached pdu"));
-        } else {
-            OC_LOG(DEBUG, MOD_NAME, PCF("coap_send_cached_pdu: sending cached pdu failed."));
-            //TODO Notify application that packet send failed.
-        }
-
-        /* Add cache node in sendqueue if it is CON pdu,
-         * as it may be needed for retransmission
-         * else, delete it
-         */
-        if (node->pdu->hdr->type == COAP_MESSAGE_CON) {
-            save_cached_con_pdu(ctx, node);
-        } else {
-            coap_delete_node(node);
-        }
-    }
-}
-
-
-/**
- * This is the tinyDTLS 'read' callback.
- * It is invoked by tinyDTLS to provide the decrypted pdu.
- *
- */
-static int read_decrypted_payload(dtls_context_t *dtls_ctx,
-            session_t *session,
-            uint8_t *buf,
-            size_t len )
-{
-    if (!dtls_ctx)
-        return -1;
-
-    coap_dtls_context_t* coap_dtls_ctx =
-        ((coap_context_t*)dtls_get_app_data(dtls_ctx))->coap_dtls_ctx;
-
-    if (coap_dtls_ctx && coap_dtls_ctx->pt_info) {
-        coap_dtls_ctx->pt_info->pt = buf;
-        coap_dtls_ctx->pt_info->ptlen = len;
-        return len;
-    }
-
-    return -1;
-}
-
-/**
- * This is the tinyDTLS 'write' callback.
- * It is invoked by tinyDTLS to send encrypted data or handshake message to peer.
- *
- */
-static int send_secure_data(dtls_context_t *dtls_ctx,
-        session_t *session,
-        uint8_t* buf,
-        size_t buflen)
-{
-    if (!dtls_ctx)
-        return -1;
-
-    return OCSendTo( ((coap_context_t*)dtls_get_app_data(dtls_ctx))->sockfd_dtls,
-            buf, buflen, 0, (OCDevAddr*)session);
-}
-
-
-/**
- * This is the tinyDTLS 'event' callback.
- * It is invoked by tinyDTLS to notify any DTLS events or alerts.
- *
- */
-static int handle_secure_event(dtls_context_t *dtls_ctx,
-        session_t *session,
-        dtls_alert_level_t level,
-        unsigned short code)
-{
-    if (!dtls_ctx)
-        return -1;
-
-    OC_LOG_V(DEBUG, MOD_NAME, "level %d, code %u", level, code);
-
-    //Notify stack of any errors/connection state changes to upper layer
-    //application
-    if (!level && (code == DTLS_EVENT_CONNECTED))
-    {
-        coap_send_cached_pdu( (coap_context_t*)dtls_get_app_data(dtls_ctx),
-            (coap_address_t*)session);
-    }
-    return 0;
-}
-
-/**
- * This is the tinyDTLS 'get_psk_info' callback.
- * It is invoked by tinyDTLS to retrieve identity/credentials.
- * This is currently a test version using stationary keys.
- *
- */
-static int get_psk_credentials(dtls_context_t *ctx,
-              const session_t *session,
-              dtls_credentials_type_t type,
-              const unsigned char *desc, size_t desc_len,
-              unsigned char *result, size_t result_len)
-{
-    int ret = -1;
-    OCDtlsPskCredsBlob *creds_blob = NULL;
-
-    //Retrieve the credentials blob from security module
-    OCGetDtlsPskCredentials(&creds_blob);
-
-    if (!creds_blob)
-        return ret;
-
-    if ((type == DTLS_PSK_HINT) || (type == DTLS_PSK_IDENTITY)) {
-        if (DTLS_PSK_ID_LEN <= result_len){
-            memcpy(result, creds_blob->identity, DTLS_PSK_ID_LEN);
-            ret = DTLS_PSK_ID_LEN;
-        }
-    }
-
-    if ((type == DTLS_PSK_KEY) && (desc) && (desc_len == DTLS_PSK_PSK_LEN)) {
-        //Check if we have the credentials for the device with which we
-        //are trying to perform a handshake
-        for (int i =0; i < creds_blob->num; i++) {
-            if (memcmp(desc, creds_blob->creds[i].id, DTLS_PSK_ID_LEN) == 0)
-            {
-                memcpy(result, creds_blob->creds[i].psk, DTLS_PSK_PSK_LEN);
-                ret = DTLS_PSK_PSK_LEN;
-            }
-        }
-    }
-
-    return ret;
-}
-
-
-/**
- * Open secure port and initialize tinyDTLS library.
- *
- * @param ctx - handle to global coap_context_t.
- *
- * @param ipAddr - ip address.
- *
- * @return A value less than zero on error, greater or
- *           equal otherwise.
- */
-int coap_dtls_init(coap_context_t *ctx, uint8_t ipAddr[]) {
-
-    int ret = -1;
-    coap_dtls_context_t *coap_dtls_ctx = NULL;
-    OCDevAddr dev_addr;
-
-    if (!ctx)
-        goto exit;
-
-    coap_dtls_ctx =
-        (coap_dtls_context_t*)coap_malloc(sizeof(coap_dtls_context_t));
-
-    if (!coap_dtls_ctx)
-        goto exit;
-    memset(coap_dtls_ctx, 0, sizeof(coap_dtls_ctx));
-    ctx->sockfd_dtls = -1;
-
-    OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3],
-                                        COAP_DTLS_DEFAULT_PORT, &dev_addr);
-    if (OCInitUDP((OCDevAddr *)&dev_addr, (int32_t *)&(ctx->sockfd_dtls), 0) != ERR_SUCCESS) {
-        OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3],
-                                        COAP_DTLS_RANDOM_PORT, &dev_addr);
-        if (OCInitUDP((OCDevAddr *)&dev_addr, (int32_t *)&(ctx->sockfd_dtls), 0) != ERR_SUCCESS) {
-            goto exit;
-        }
-    }
-
-    // Initialize clock, crypto and other global vars in tinyDTLS library
-    dtls_init();
-
-    coap_dtls_ctx->dtls_ctx = dtls_new_context(ctx);
-    if (!coap_dtls_ctx->dtls_ctx)
-        goto exit;
-
-    coap_dtls_ctx->callbacks.write = send_secure_data;
-    coap_dtls_ctx->callbacks.read  = read_decrypted_payload;
-    coap_dtls_ctx->callbacks.event = handle_secure_event;
-    coap_dtls_ctx->callbacks.get_psk_info = get_psk_credentials;
-
-    dtls_set_handler(coap_dtls_ctx->dtls_ctx, &(coap_dtls_ctx->callbacks));
-    ctx->coap_dtls_ctx = coap_dtls_ctx;
-    ret = 0;
-
-exit:
-    if (ret == -1) {
-        coap_dtls_deinit(ctx);
-    }
-    return ret;
-}
-
-
-/**
- * Closes secure port and de-inits tinyDTLS library.
- *
- * @param ctx - handle to global coap_context_t.
- *
- */
-void coap_dtls_deinit(coap_context_t *ctx) {
-
-    if (!ctx || !ctx->coap_dtls_ctx)
-        return;
-
-    coap_dtls_context_t *coap_dtls_ctx = ctx->coap_dtls_ctx;
-
-    coap_delete_all(coap_dtls_ctx->cachedqueue);
-
-    dtls_free_context(coap_dtls_ctx->dtls_ctx);
-    coap_dtls_ctx->dtls_ctx = NULL;
-
-    if (ctx->sockfd_dtls != -1)
-        OCClose(ctx->sockfd_dtls);
-
-    coap_free(coap_dtls_ctx);
-    ctx->coap_dtls_ctx = NULL;
-}
-
-
-/**
- * Performs DTLS encryption of the CoAP PDU. If a
- * DTLS session does not exist yet with the @dst,
- * a DTLS handshake will be started. In case where
- * a new DTLS handshake is started, pdu info is
- * cached to be send when session setup is finished.
- *
- * @param ctx    - handle to global coap_context_t.
- * @param dst    - address of the receiver of the pdu.
- * @param pdu    - pointer to CoAP pdu.
- * @param node   - address of the node holding pdu.
- * @param tid    - tid of the pdu.
- * @param cached - output variable to indicate if pdu
- *                  is cached and inform the caller to
- *                  NOT free the memory holding pdu.
- *
- * @return A value less than zero on error, greater or
- *           equal otherwise.
- */
-int coap_dtls_encrypt(coap_context_t *ctx,
-            OCDevAddr *dst,
-            coap_pdu_t *pdu,
-            coap_queue_t **node,
-            coap_tid_t tid,
-            uint8_t *cache_flag) {
-    OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_encrypt"));
-
-    if (!dst || !pdu)
-        return -1;
-
-    dtls_ret ret = coap_dtls_encrypt_internal( ctx, dst,
-            (uint8_t*)pdu->hdr, pdu->length);
-
-    if (ret == DTLS_SESSION_INITIATED) {
-        OC_LOG(DEBUG, MOD_NAME, PCF("Initiated new DTLS session"));
-        if (cache_flag && coap_cache_pdu(ctx, *node, dst, pdu, tid) == 0) {
-            /* Delete the node from sendqueue list as it has been
-             * added in cachedqueue list. It will be added
-             * again in sendqueue list when DTLS session is established
-             */
-            if (*node) {
-                coap_queue_t* removed_node = NULL;
-                coap_remove_from_queue(&(ctx->sendqueue),
-                   (*node)->id, &removed_node);
-                if (removed_node == *node) {
-                    coap_free(*node);
-                    *node = NULL;
-                    OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_encrypt -- Removed correct node"));
-                }
-            }
-            *cache_flag = 1;
-        }
-        return pdu->length;
-    }
-
-    if (ret == DTLS_OK) {
-        OC_LOG(DEBUG, MOD_NAME, PCF("Encrypted App PDU and send to peer"));
-        return pdu->length;
-    }
-    return -1;
-}
-
-
-/**
- * Performs DTLS decryption of the CoAP PDU received on
- * secure port. This method performs in-place decryption
- * of the cipher-text buffer. If a DTLS handshake message
- * is received or decryption failure happens, this method
- * returns -1. If a valid CoAP pdu is received, it returns the
- * length of the decrypted pdu.
- *
- * @param ctx    - handle to global coap_context_t.
- * @param src    - address of the sender of the pdu.
- * @param ct     - pointer to the cipher text buffer.
- * @param ctlen  - length of the ciphertext buffer.
- * @param pt     - output variable to store the starting address
- *                  of decrypted plaintext.
- * @param ptlen  - output variable to store the length of
- *                  decrypted plaintext.
- *
- * @return A value less than zero on error, greater or
- *           equal otherwise.
- */
-int coap_dtls_decrypt(coap_context_t *ctx,
-            OCDevAddr* src,
-            uint8_t* ct,
-            int ctlen,
-            uint8_t** pt,
-            int* ptlen) {
-    OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_decrypt"));
-
-    if (!src || !ct || !pt || !ptlen)
-        return -1;
-
-    dtls_ret ret = coap_dtls_decrypt_internal(ctx, src, ct, ctlen,
-            pt, ptlen);
-
-    if (ret == DTLS_OK)
-        return *ptlen;
-
-    if (ret == DTLS_HS_MSG)
-        OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_decrypt : Handshake msg recvd "));
-    if (ret == DTLS_FAIL)
-        OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_decrypt : Decryption failure "));
-
-    return -1;
-}
diff --git a/resource/csdk/libcoap-4.1.1/sec/netdtls.h b/resource/csdk/libcoap-4.1.1/sec/netdtls.h
deleted file mode 100644 (file)
index 1348bba..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef _NET_DTLS_H
-#define _NET_DTLS_H
-
-#include "net.h"
-#include "address.h"
-#include "pdu.h"
-#include "dtls.h"
-
-#define COAP_DTLS_DEFAULT_PORT  5684
-#define COAP_DTLS_RANDOM_PORT   0
-
-/**
- * Data structure for holding the tinyDTLS interface
- * related info.
- */
-typedef struct coap_dtls_context_t {
-    coap_queue_t *cachedqueue;          /**< pdu's are cached until DTLS session is formed */
-    struct dtls_context_t *dtls_ctx;    /**< pointer to tinyDTLS context */
-    struct pt_info_t *pt_info;          /**< used by callback during
-                                             decryption to hold address/length */
-    dtls_handler_t callbacks;           /**< pointer to callbacks needed by tinyDTLS */
-}coap_dtls_context_t;
-
-/**
- * Data structure for holding the decrypted data address
- * and length provided by tinyDTLS callback interface.
- */
-typedef struct pt_info_t {
-    uint8_t *pt;
-    uint16_t ptlen;
-}pt_info_t;
-
-/**
- * Declares DTLS errors and return values. Currently used internally only.
- */
-typedef enum
-{
-    DTLS_OK = 0,
-    DTLS_FAIL,
-    DTLS_SESSION_INITIATED,
-    DTLS_HS_MSG
-} dtls_ret;
-
-/**
- * Open secure port and initialize tinyDTLS library.
- *
- * @param ctx - handle to global coap_context_t.
- *
- * @param ipAddr - ip address.
- *
- * @return A value less than zero on error, greater or
- *           equal otherwise.
- */
-int coap_dtls_init(coap_context_t *ctx, uint8_t ipAddr[]);
-
-/**
- * Closes secure port and de-inits tinyDTLS library.
- *
- * @param ctx - handle to global coap_context_t.
- *
- */
-void coap_dtls_deinit(coap_context_t *ctx);
-
-/**
- * Performs DTLS encryption of the CoAP PDU. If a
- * DTLS session does not exist yet with the @dst,
- * a DTLS handshake will be started. In case where
- * a new DTLS handshake is started, pdu info is
- * cached to be send when session setup is finished.
- *
- * @param ctx    - handle to global coap_context_t.
- * @param dst    - address of the receiver of the pdu.
- * @param pdu    - pointer to CoAP pdu.
- * @param node   - address of the node holding pdu.
- * @param tid    - tid of the pdu.
- * @param cache_flag - output variable to indicate if pdu
- *                  is cached and inform the caller to
- *                  NOT free the memory holding pdu.
- *
- * @return A value less than zero on error, greater or
- *           equal otherwise.
- */
-int coap_dtls_encrypt(coap_context_t *ctx,
-            OCDevAddr* dst,
-            coap_pdu_t *pdu,
-            coap_queue_t **node,
-            coap_tid_t tid,
-            uint8_t *cache_flag);
-
-/**
- * Performs DTLS decryption of the CoAP PDU received on
- * secure port. This method performs in-place decryption
- * of the cipher-text buffer. If a DTLS handshake message
- * is received or decryption failure happens, this method
- * returns -1. If a valid application PDU is decrypted, it
- * returns the length of the decrypted pdu.
- *
- * @param ctx    - handle to global coap_context_t.
- * @param src    - address of the sender of the pdu.
- * @param ct     - pointer to the cipher text buffer.
- * @param ctlen  - length of the ciphertext buffer.
- * @param pt     - output variable to store the starting address
- *                  of decrypted plaintext.
- * @param ptlen  - output variable to store the length of
- *                  decrypted plaintext.
- *
- * @return A value less than zero on error, greater or
- *           equal otherwise.
- */
-int coap_dtls_decrypt(coap_context_t *ctx,
-            OCDevAddr* src,
-            uint8_t* ct,
-            int ctlen,
-            uint8_t** pt,
-            int* ptlen);
-
-#endif //_NET_DTLS_H
-
diff --git a/resource/csdk/libcoap-4.1.1/str.c b/resource/csdk/libcoap-4.1.1/str.c
deleted file mode 100644 (file)
index e251bc4..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-/* str.c -- strings to be used in the CoAP library
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-
-#include <stdio.h>
-
-#include "debug.h"
-#include "mem.h"
-#include "str.h"
-
-str *coap_new_string(size_t size) {
-  str *s = (str*)coap_malloc(sizeof(str) + size + 1);
-  if ( !s ) {
-#ifndef NDEBUG
-    coap_log(LOG_CRIT, "coap_new_string: malloc\n");
-#endif
-    return NULL;
-  }
-
-  memset(s, 0, sizeof(str));
-  s->s = ((unsigned char *)s) + sizeof(str);
-  return s;
-}
-
-void coap_delete_string(str *s) {
-  coap_free(s);
-}
-
diff --git a/resource/csdk/libcoap-4.1.1/str.h b/resource/csdk/libcoap-4.1.1/str.h
deleted file mode 100644 (file)
index 7c10ce8..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/* str.h -- strings to be used in the CoAP library
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#ifndef _COAP_STR_H_
-#define _COAP_STR_H_
-
-#include <string.h>
-
-typedef struct {
-  size_t length;               /* length of string */
-  unsigned char *s;            /* string data */
-} str;
-
-#define COAP_SET_STR(st,l,v) { (st)->length = (l), (st)->s = (v); }
-
-/**
- * Returns a new string object with at least size bytes storage
- * allocated.  The string must be released using coap_delete_string();
- */
-str *coap_new_string(size_t size);
-
-/** Deletes the given string and releases any memory allocated. */
-void coap_delete_string(str *);
-
-#endif /* _COAP_STR_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/subscribe.c b/resource/csdk/libcoap-4.1.1/subscribe.c
deleted file mode 100644 (file)
index d683419..0000000
+++ /dev/null
@@ -1,401 +0,0 @@
-/* subscribe.c -- subscription handling for CoAP
- *                see draft-ietf-coap-observe-09
- *
- * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-#include "config.h"
-
-#if defined(HAVE_ASSERT_H) && !defined(assert)
-# include <assert.h>
-#endif
-
-#include <stdio.h>
-#include <limits.h>
-#ifdef HAVE_ARPA_INET_H
-# include <arpa/inet.h>
-#endif
-
-/* #include "resource.h" */
-
-#include "mem.h"
-#include "encode.h"
-#include "debug.h"
-#include "subscribe.h"
-
-void
-coap_subscription_init(coap_subscription_t *s) {
-  assert(s);
-  memset(s, 0, sizeof(coap_subscription_t));
-}
-
-#if 0
-#define HMASK (ULONG_MAX >> 1)
-
-void
-notify(coap_context_t *context, coap_resource_t *res,
-       coap_subscription_t *sub, unsigned int duration, int code) {
-#if 0
-  coap_pdu_t *pdu;
-  int ls, finished=0;
-  unsigned char ct, d;
-  unsigned int length;
-#ifndef NDEBUG
-  char addr[INET6_ADDRSTRLEN];
-#endif
-
-  if ( !context || !res || !sub || !(pdu = coap_new_pdu()) )
-    return;
-
-  pdu->hdr->type = COAP_MESSAGE_CON;
-  pdu->hdr->id = rand();       /* use a random transaction id */
-  pdu->hdr->code = code;
-
-  /* FIXME: content-type and data (how about block?) */
-  if (res->uri->host.length)
-    coap_add_option (pdu, COAP_OPTION_URI_HOST,
-                    res->uri->host.length,
-                    res->uri->host.s );
-
-  if (res->uri->path.length)
-    coap_add_option (pdu, COAP_OPTION_URI_PATH,
-                    res->uri->path.length,
-                    res->uri->path.s);
-
-  d = COAP_PSEUDOFP_ENCODE_8_4_DOWN(duration, ls);
-
-  coap_add_option ( pdu, COAP_OPTION_SUBSCRIPTION, 1, &d );
-
-  if (sub->token.length) {
-    coap_add_option (pdu, COAP_OPTION_TOKEN,
-                    sub->token.length,
-                    sub->token.s);
-  }
-
-  if (res->uri->query.length)
-    coap_add_option (pdu, COAP_OPTION_URI_QUERY,
-                    res->uri->query.length,
-                    res->uri->query.s );
-
-  if (res->data) {
-    length = (unsigned char *)pdu->hdr + COAP_MAX_PDU_SIZE - pdu->data;
-    ct = res->mediatype;
-    res->data(res->uri, &ct, 0, pdu->data, &length, &finished);
-    pdu->length += length;
-
-    /* TODO: add block option if not finished */
-    /* TODO: add mediatype */
-  }
-
-#ifndef NDEBUG
-  if ( inet_ntop(sub->subscriber.addr.sa.sa_family, 
-                &sub->subscriber.addr, addr, sizeof(addr)) ) {
-    debug("*** notify for %s to [%s]\n", res->uri->path.s, addr);
-  }
-#endif
-  if (pdu && coap_send_confirmed(context,
-                                &sub->subscriber.addr.sa,
-                                sub->subscriber.size, pdu) 
-      == COAP_INVALID_TID) {
-#ifndef NDEBUG
-    debug("coap_check_resource_list: error sending notification\n");
-#endif
-    coap_delete_pdu(pdu);
-  }
-#endif
-}
-
-void
-coap_check_resource_list(coap_context_t *context) {
-  coap_resource_t *res, *tmp;
-  coap_list_t *sub;
-  coap_key_t key;
-  time_t now;
-
-  if ( !context || !context->resources /* || !context->subscribers */)
-    return;
-
-  time(&now);                  /* FIXME: use coap_ticks() */
-
-  HASH_ITER(hh, context->resources, res, tmp) {
-    if (res->dirty) {
-      debug("FIXME: notify subscribers\n");
-#if 0
-      key = coap_uri_hash( COAP_RESOURCE(res)->uri ) ;
-
-      /* is subscribed? */
-      for (sub = context->subscriptions; sub; sub = sub->next) {
-       if ( COAP_SUBSCRIPTION(sub)->resource == key ) {
-         /* notify subscriber */
-         notify(context, COAP_RESOURCE(res), COAP_SUBSCRIPTION(sub),
-                COAP_SUBSCRIPTION(sub)->expires - now, COAP_RESPONSE_200);
-       }
-
-      }
-
-      COAP_RESOURCE(res)->dirty = 0;
-#endif
-    }
-  }
-}
-
-#if 0
-coap_resource_t *
-coap_get_resource_from_key(coap_context_t *ctx, coap_key_t key) {
-  coap_list_t *node;
-
-  if (ctx) {
-    /* TODO: use hash table for resources with key to access */
-    for (node = ctx->resources; node; node = node->next) {
-      printf("check %ux\n", coap_uri_hash(COAP_RESOURCE(node)->uri));
-      if ( key == coap_uri_hash(COAP_RESOURCE(node)->uri) ) {
-       printf("found\n");
-       return COAP_RESOURCE(node);
-      }
-    }
-  }
-
-  printf("not found\n");
-  return NULL;
-}
-
-coap_resource_t *
-coap_get_resource(coap_context_t *ctx, coap_uri_t *uri) {
-#ifndef NDEBUG
-  int i;
-  printf("search resource %ux", coap_uri_hash(uri));
-  for (i=0; i < uri->path.length; ++i) {
-    printf(" %02x", uri->path.s[i]);
-  }
-  printf("\n");
-#endif
-  return uri ? coap_get_resource_from_key(ctx, coap_uri_hash(uri)) : NULL;
-}
-#endif
-
-void
-coap_check_subscriptions(coap_context_t *context) {
-  time_t now;
-  coap_list_t *node;
-#ifndef NDEBUG
-  char addr[INET6_ADDRSTRLEN];
-#endif
-
-  if ( !context )
-    return;
-
-  time(&now);
-
-  node = context->subscriptions;
-  while ( node && COAP_SUBSCRIPTION(node)->expires < now ) {
-#ifndef NDEBUG
-    if (inet_ntop(COAP_SUBSCRIPTION(node)->subscriber.addr.sa.sa_family,
-                 &COAP_SUBSCRIPTION(node)->subscriber.addr,
-                 addr, sizeof(addr))) {
-      
-      debug("** removed expired subscription from [%s]\n", addr);
-    }
-#endif
-#if 0
-    notify(context,
-          coap_get_resource_from_key(context, COAP_SUBSCRIPTION(node)->resource),
-          COAP_SUBSCRIPTION(node),
-          0, COAP_RESPONSE_400);
-#endif
-    context->subscriptions = node->next;
-    coap_delete(node);
-    node = context->subscriptions;
-  }
-}
-
-void
-coap_free_resource(void *res) {
-  if ( res ) {
-#if 0
-    coap_free(((coap_resource_t *)res)->uri);
-    coap_delete_string(((coap_resource_t *)res)->name);
-#endif
-  }
-}
-
-#if 0
-/**
- * Deletes the resource that is identified by key. Returns 1 if the resource was
- * removed, 0 on error (e.g. if no such resource exists).
- */
-int
-coap_delete_resource(coap_context_t *context, coap_key_t key) {
-  coap_list_t *prev, *node;
-
-  if (!context || key == COAP_INVALID_HASHKEY)
-    return 0;
-
-  for (prev = NULL, node = context->resources; node;
-       prev = node, node = node->next) {
-    if (coap_uri_hash(COAP_RESOURCE(node)->uri) == key) {
-#ifndef NDEBUG
-      debug("removed key %lu (%s)\n",key,COAP_RESOURCE(node)->uri->path.s);
-#endif
-      if (!prev)
-       context->resources = node->next;
-      else
-       prev->next = node->next;
-
-      coap_delete(node);
-      return 1;
-    }
-  }
-  return 0;
-}
-#endif
-
-coap_subscription_t *
-coap_new_subscription(coap_context_t *context, const coap_uri_t *resource,
-                     const struct sockaddr *addr, socklen_t addrlen, time_t expiry) {
-  coap_subscription_t *result;
-
-  if ( !context || !resource || !addr
-       || !(result = coap_malloc(sizeof(coap_subscription_t))))
-    return NULL;
-
-  result->resource = coap_uri_hash(resource);
-  result->expires = expiry;
-  memcpy(&result->subscriber.addr.sa, addr, addrlen);
-
-  memset(&result->token, 0, sizeof(str));
-
-  return result;
-
-}
-
-coap_list_t *
-coap_list_push_first(coap_list_t **list, void *data, void (*delete_func)(void *) ) {
-  coap_list_t *node;
-  node = coap_new_listnode(data, delete_func);
-  if ( !node || !list )
-    return NULL;
-
-  if ( !*list ) {
-    *list = node;
-  } else {
-    node->next = *list;
-    *list = node;
-  }
-
-  return node;
-}
-
-int
-_order_subscription(void *a, void *b) {
-  if ( !a || !b )
-    return a < b ? -1 : 1;
-
-  return ((coap_subscription_t *)a)->expires < ((coap_subscription_t *)b)->expires ? -1 : 1;
-}
-
-coap_key_t
-coap_subscription_hash(coap_subscription_t *subscription) {
-  if ( !subscription )
-    return COAP_INVALID_HASHKEY;
-
-  return _hash2( subscription->resource, (unsigned char *)&subscription->subscriber,
-                sizeof(subscription->subscriber) );
-}
-
-coap_key_t
-coap_add_subscription(coap_context_t *context,
-                     coap_subscription_t *subscription) {
-  coap_list_t *node;
-  if ( !context || !subscription )
-    return COAP_INVALID_HASHKEY;
-
-  if ( !(node = coap_new_listnode(subscription, NULL)) )
-    return COAP_INVALID_HASHKEY;
-
-  if ( !coap_insert(&context->subscriptions, node, _order_subscription ) ) {
-    coap_free( node ); /* do not call coap_delete(), so subscription object will survive */
-    return COAP_INVALID_HASHKEY;
-  }
-
-  return coap_subscription_hash(subscription);
-}
-
-coap_subscription_t *
-coap_find_subscription(coap_context_t *context,
-                      coap_key_t hashkey,
-                      struct sockaddr *addr,
-                      str *token) {
-#if 0
-  coap_list_t *node;
-#endif
-
-  if (!context || !addr || hashkey == COAP_INVALID_HASHKEY)
-    return NULL;
-
-  /* FIXME: I do not like the way subscriptions work right now. To be fixed. */
-
-#if 0
-  for (node = context->subscriptions; node; node = node->next) {
-    if (COAP_SUBSCRIPTION(node)->resource == hashkey) {
-
-      if (token) {        /* do not proceed if tokens do not match */
-       if (token->length != COAP_SUBSCRIPTION(node)->token.length ||
-           memcmp(token->s, COAP_SUBSCRIPTION(node)->token.s,
-                  token->length) != 0)
-         continue;
-      }
-
-      if (subscriber->sin6_port == COAP_SUBSCRIPTION(node)->subscriber.sin6_port
-         && memcmp(&subscriber->sin6_addr,
-                   &COAP_SUBSCRIPTION(node)->subscriber.sin6_addr,
-                   sizeof(struct in6_addr)) == 0)
-       return COAP_SUBSCRIPTION(node);
-    }
-  }
-#endif
-  return NULL;
-}
-
-int
-coap_delete_subscription(coap_context_t *context,
-                        coap_key_t key,
-                        struct sockaddr *addr) {
-#if 0
-  coap_list_t *prev, *node;
-#endif
-
-  if (!context || !addr || key == COAP_INVALID_HASHKEY)
-    return 0;
-
-  /* FIXME: I do not like the way subscriptions work right now. To be fixed. */
-
-#if 0
-  for (prev = NULL, node = context->subscriptions; node;
-       prev = node, node = node->next) {
-    if (COAP_SUBSCRIPTION(node)->resource == key) {
-      if (subscriber->sin6_port == COAP_SUBSCRIPTION(node)->subscriber.sin6_port
-         && memcmp(&subscriber->sin6_addr,
-                   &COAP_SUBSCRIPTION(node)->subscriber.sin6_addr,
-                   sizeof(struct in6_addr)) == 0) {
-
-       if (!prev) {
-         context->subscriptions = node->next;
-         coap_free(COAP_SUBSCRIPTION(node)->token.s);
-         coap_delete(node);
-       } else {
-         prev->next = node->next;
-         coap_free(COAP_SUBSCRIPTION(node)->token.s);
-         coap_delete(node);
-       }
-       return 1;
-      }
-    }
-  }
-#endif
-
-  return 0;
-}
-#endif
diff --git a/resource/csdk/libcoap-4.1.1/subscribe.h b/resource/csdk/libcoap-4.1.1/subscribe.h
deleted file mode 100644 (file)
index 7eda74f..0000000
+++ /dev/null
@@ -1,200 +0,0 @@
-/* subscribe.h -- subscription handling for CoAP
- *                see draft-hartke-coap-observe-03
- *
- * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use. 
- */
-
-
-#ifndef _COAP_SUBSCRIBE_H_
-#define _COAP_SUBSCRIBE_H_
-
-#include "config.h"
-#include "address.h"
-
-/** 
- * @defgroup observe Resource observation
- * @{
- */
-
-#ifndef COAP_OBS_MAX_NON
-/**
- * Number of notifications that may be sent non-confirmable before a
- * confirmable message is sent to detect if observers are alive. The
- * maximum allowed value here is @c 15.
- */
-#define COAP_OBS_MAX_NON   5
-#endif /* COAP_OBS_MAX_NON */
-
-#ifndef COAP_OBS_MAX_FAIL
-/**
- * Number of confirmable notifications that may fail (i.e. time out
- * without being ACKed) before an observer is removed. The maximum
- * value for COAP_OBS_MAX_FAIL is @c 3.
- */
-#define COAP_OBS_MAX_FAIL  3
-#endif /* COAP_OBS_MAX_FAIL */
-
-/** Subscriber information */
-typedef struct coap_subscription_t {
-  struct coap_subscription_t *next; /**< next element in linked list */
-  coap_address_t subscriber;       /**< address and port of subscriber */
-
-  unsigned int non:1;          /**< send non-confirmable notifies if @c 1  */
-  unsigned int non_cnt:4;      /**< up to 15 non-confirmable notifies allowed */
-  unsigned int fail_cnt:2;     /**< up to 3 confirmable notifies can fail */
-  unsigned int dirty:1;         /**< set if the notification temporarily could not be sent (in that case, the resource's partiallydirty flag is set too) */
-
-  size_t token_length;         /**< actual length of token */
-  unsigned char token[8];      /**< token used for subscription */
-  /* @todo CON/NON flag, block size */
-} coap_subscription_t;
-
-void coap_subscription_init(coap_subscription_t *);
-
-#if 0
-#include "uthash.h"
-#include "uri.h"
-#include "list.h"
-#include "pdu.h"
-#include "net.h"
-
-#if 0
-typedef unsigned long coap_key_t;
-
-/** Used to indicate that a hashkey is invalid. */
-#define COAP_INVALID_HASHKEY ((coap_key_t)-1)
-
-typedef struct {
-  coap_uri_t *uri;             /* unique identifier; memory is released by coap_delete_resource() */
-  UT_hash_handle hh;           /**< hash handle (for internal use only) */
-  str *name;                   /* display name of the resource */
-  unsigned char mediatype;     /* media type for resource representation */
-  unsigned int dirty:1;                /* set to 1 if resource has changed */
-  unsigned int writable:1;     /* set to 1 if resource can be changed using PUT */
-
-  /* cache-control */
-  unsigned char etag[4];        /* version identifier for this resource
-                                * (zero terminated, first byte is zero if not set). */
-  unsigned int maxage;         /* maximum cache time (zero means no Max-age option) */
-
-  /**
-   * Callback function that copies the resource representation into the provided data
-   * buffer (PDU payload). finished is set to 1 to indicate that this was the last block
-   * of buflen data for this resource representation, 0 means that data is not finished
-   * and a subsequent call with offset updated by buflen would yield more data (i.e.
-   * the M-bit of CoAP's block option must be set if offset and buflen are selected
-   * accordingly.
-   * When called, buflen must be set to the maximum length of buf that is to be filled
-   * with the mediatype representation of the resource identified by uri.
-   * The mediatype must be set to the requested mediatype of COAP_MEDIATYPE_ANY if
-   * none was given. On return, the mediatype will be set to the type that is
-   * actually used.
-   * The return value indicates the result code that should be used in a response to
-   * this function.
-   */
-  int (*data)(coap_uri_t *uri, unsigned char *mediatype, unsigned int offset, unsigned char *buf, unsigned int *buflen, int *finished);
-} coap_resource_t;
-#endif
-
-typedef struct {
-  coap_key_t resource;         /* hash key for subscribed resource */
-  time_t expires;              /* expiry time of subscription */
-
-  coap_address_t subscriber;   /**< subscriber's address */
-
-  str token;                   /**< subscription token */
-} coap_subscription_t;
-
-#define COAP_RESOURCE(node) ((coap_resource_t *)(node)->data)
-#define COAP_SUBSCRIPTION(node) ((coap_subscription_t *)(node)->data)
-
-/** Checks subscribed resources for updates and notifies subscribers of changes. */
-void coap_check_resource_list(coap_context_t *context);
-
-/** Removes expired subscriptions. */
-void coap_check_subscriptions(coap_context_t *context);
-
-#if 0
-/**
- * Adds specified resource to the resource observation list. Returns a
- * unique key for the resource. The alloceted memory is released when
- * the resource is destroyed with coap_delete_resource().
- */
-coap_key_t coap_add_resource(coap_context_t *context, coap_resource_t *);
-
-/**
- * Deletes the resource that is identified by key. Returns 1 if the resource was
- * removed, 0 on error (e.g. if no such resource exists).
- */
-int coap_delete_resource(coap_context_t *context, coap_key_t key);
-#endif
-/**
- * Creates a new subscription object filled with the given data. The storage
- * allocated for this object must be released using coap_free(). */
-coap_subscription_t *coap_new_subscription(coap_context_t *context,
-                                          const coap_uri_t *resource,
-                                          const struct sockaddr *subscriber,
-                                          socklen_t addrlen,
-                                          time_t expiry);
-
-/**
- * Adds the given subsription object to the observer list.
- * @param context The CoAP context
- * @param subscription A new subscription oobject created with coap_new_subscription()
- * @return A unique hash key for this resource or COAP_INVALID_HASHKEY on error.
- * The storage allocated for the subscription object is released when it is
- * removed from the subscription list, unless the function has returned
- * COAP_INVALID_HASHKEY. In this case, the storage must be released by the
- * caller of this function.
-*/
-coap_key_t coap_add_subscription(coap_context_t *context,
-                                coap_subscription_t *subscription);
-
-/**
- * Returns the subscription from subscriber for the resource identified
- * by hashkey. When token is not NULL the subscription must have the
- * same token.
- * @param context The CoAP context
- * @param hashkey The unique key that identifies the subscription
- * @param subscriber The subscriber's transport address
- * @param token If not NULL, this specifies a token given by the
- *              subscriber to identify its subscription.
- * @return The requested subscription object or NULL when not found.
- */
-coap_subscription_t * coap_find_subscription(coap_context_t *context,
-                                            coap_key_t hashkey,
-                                            struct sockaddr *subscriber,
-                                            str *token);
-/**
- * Removes a subscription from the subscription list stored in context and
- * releases the storage that was allocated for this subscription.
- * @param context The CoAP context.
- * @param haskey The unique key that identifies the subscription to remove.
- * @return 1 if a subscription was removed, 0 otherwise.
- */
-int coap_delete_subscription(coap_context_t *context,
-                            coap_key_t hashkey,
-                            struct sockaddr *subscriber);
-
-/** Returns a unique hash for the specified URI or COAP_INVALID_HASHKEY on error. */
-coap_key_t coap_uri_hash(const coap_uri_t *uri);
-
-
-/** Returns a unique hash for the specified subscription or COAP_INVALID_HASHKEY on error. */
-coap_key_t coap_subscription_hash(coap_subscription_t *subscription);
-#if 0
-/** Returns the resource identified by key or NULL if not found. */
-coap_resource_t *coap_get_resource_from_key(coap_context_t *ctx, coap_key_t key);
-
-/** Returns the resource identified by uri or NULL if not found. */
-coap_resource_t *coap_get_resource(coap_context_t *ctx, coap_uri_t *uri);
-#endif
-
-#endif
-
-/** @} */
-
-#endif /* _COAP_SUBSCRIBE_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/t_list.h b/resource/csdk/libcoap-4.1.1/t_list.h
deleted file mode 100644 (file)
index ebbd70f..0000000
+++ /dev/null
@@ -1,146 +0,0 @@
-/* t_list -- tinydtls lists
- *
- * Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * Permission is hereby granted, free of charge, to any person
- * obtaining a copy of this software and associated documentation
- * files (the "Software"), to deal in the Software without
- * restriction, including without limitation the rights to use, copy,
- * modify, merge, publish, distribute, sublicense, and/or sell copies
- * of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
- * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
- * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-/**
- * @file t_list.h
- * @brief Wrappers for list structures and functions
- */
-
-#ifndef _DTLS_LIST_H_
-#define _DTLS_LIST_H_
-
-#ifndef WITH_CONTIKI
-#include "uthash.h"
-#include "utlist.h"
-
-/* We define list structures and utility functions to be compatible
- * with Contiki list structures. The Contiki list API is part of the
- * Contiki operating system, and therefore the following licensing
- * terms apply (taken from contiki/core/lib/list.h):
- *
- * Copyright (c) 2004, Swedish Institute of Computer Science.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the Institute nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * This file is part of the Contiki operating system.
- *
- * Author: Adam Dunkels <adam@sics.se>
- *
- * $ Id: list.h,v 1.5 2010/09/13 13:31:00 adamdunkels Exp $
- */
-
-typedef void **list_t;
-struct list {
-  struct list *next;
-};
-
-#define LIST_CONCAT(s1, s2) s1##s2
-
-#define LIST_STRUCT(name)                      \
-  void *LIST_CONCAT(name, _list);              \
-  list_t name
-
-#define LIST_STRUCT_INIT(struct_ptr, name)  {                          \
-    (struct_ptr)->name = &((struct_ptr)->LIST_CONCAT(name,_list));     \
-    (struct_ptr)->LIST_CONCAT(name,_list) = NULL;                      \
-  }
-
-static inline void *
-list_head(list_t the_list) {
-  return *the_list;
-}
-
-static inline void 
-list_remove(list_t the_list, void *item) {
-  if (list_head(the_list))
-    LL_DELETE(*(struct list **)the_list, (struct list *)item);
-}
-
-static inline void 
-list_add(list_t the_list, void *item) {
-  list_remove(the_list, item);
-  LL_APPEND(*(struct list **)the_list, (struct list *)item);
-}
-
-static inline void 
-list_push(list_t the_list, void *item) {
-  LL_PREPEND(*(struct list **)the_list, (struct list *)item);
-}
-
-static inline void *
-list_pop(list_t the_list) {
-  struct list *l;
-  l = (struct list*)*the_list;
-  if(l)
-    list_remove(the_list, l);
-  
-  return l;
-}
-
-static inline void
-list_insert(list_t the_list, void *previtem, void *newitem) {
-  if(previtem == NULL) {
-    list_push(the_list, newitem);
-  } else {
-    ((struct list *)newitem)->next = ((struct list *)previtem)->next;
-    ((struct list *)previtem)->next = (struct list*)newitem;
-  } 
-}
-
-static inline void *
-list_item_next(void *item)
-{
-  return item == NULL? NULL: ((struct list *)item)->next;
-}
-
-#else /* WITH_CONTIKI */
-#include "list.h"
-#endif /* WITH_CONTIKI */
-
-#endif /* _DTLS_LIST_H_ */
-
diff --git a/resource/csdk/libcoap-4.1.1/uri.c b/resource/csdk/libcoap-4.1.1/uri.c
deleted file mode 100644 (file)
index 96624c5..0000000
+++ /dev/null
@@ -1,529 +0,0 @@
-/* uri.c -- helper functions for URI treatment
- *
- * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#include "config.h"
-
-#if defined(HAVE_ASSERT_H) && !defined(assert)
-# include <assert.h>
-#endif
-
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-
-#include "mem.h"
-#include "debug.h"
-#include "pdu.h"
-#include "option.h"
-#include "uri.h"
-
-/**
- * A length-safe version of strchr(). This function returns a pointer
- * to the first occurrence of @p c  in @p s, or @c NULL if not found.
- *
- * @param s   The string to search for @p c.
- * @param len The length of @p s.
- * @param c   The character to search.
- *
- * @return A pointer to the first occurence of @p c, or @c NULL
- * if not found.
- */
-static inline unsigned char *
-strnchr(unsigned char *s, size_t len, unsigned char c) {
-  while (len && *s++ != c)
-    --len;
-
-  return len ? s : NULL;
-}
-
-int
-coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri) {
-  unsigned char *p, *q;
-  int secure = 0, res = 0;
-
-  if (!str_var || !uri)
-    return -1;
-
-  memset(uri, 0, sizeof(coap_uri_t));
-  uri->port = COAP_DEFAULT_PORT;
-
-  /* search for scheme */
-  p = str_var;
-  if (*p == '/') {
-    q = p;
-    goto path;
-  }
-
-  q = (unsigned char *)COAP_DEFAULT_SCHEME;
-  while (len && *q && tolower(*p) == *q) {
-    ++p; ++q; --len;
-  }
-
-  /* If q does not point to the string end marker '\0', the schema
-   * identifier is wrong. */
-  if (*q) {
-    res = -1;
-    goto error;
-  }
-
-  /* There might be an additional 's', indicating the secure version: */
-  if (len && (secure = tolower(*p) == 's')) {
-    ++p; --len;
-    uri->secure = 1;
-  }
-
-  q = (unsigned char *)"://";
-  while (len && *q && tolower(*p) == *q) {
-    ++p; ++q; --len;
-  }
-
-  if (*q) {
-    res = -2;
-    goto error;
-  }
-
-  /* p points to beginning of Uri-Host */
-  q = p;
-  if (len && *p == '[') {   /* IPv6 address reference */
-    ++p;
-
-    while (len && *q != ']') {
-      ++q; --len;
-    }
-
-    if (!len || *q != ']' || p == q) {
-      res = -3;
-      goto error;
-    }
-
-    COAP_SET_STR(&uri->host, q - p, p);
-    ++q; --len;
-  } else {          /* IPv4 address or FQDN */
-    while (len && *q != ':' && *q != '/' && *q != '?') {
-      *q = tolower(*q);
-      ++q;
-      --len;
-    }
-
-    if (p == q) {
-      res = -3;
-      goto error;
-    }
-
-    COAP_SET_STR(&uri->host, q - p, p);
-  }
-
-  /* check for Uri-Port */
-  if (len && *q == ':') {
-    p = ++q;
-    --len;
-
-    while (len && isdigit(*q)) {
-      ++q;
-      --len;
-    }
-
-    if (p < q) {        /* explicit port number given */
-      int uri_port = 0;
-
-      while (p < q)
-    uri_port = uri_port * 10 + (*p++ - '0');
-
-      uri->port = uri_port;
-    }
-  }
-
- path:       /* at this point, p must point to an absolute path */
-
-  if (!len)
-    goto end;
-
-  if (*q == '/') {
-    p = ++q;
-    --len;
-
-    while (len && *q != '?') {
-      ++q;
-      --len;
-    }
-
-    if (p < q) {
-      COAP_SET_STR(&uri->path, q - p, p);
-      p = q;
-    }
-  }
-
-  /* Uri_Query */
-  if (len && *p == '?') {
-    ++p;
-    --len;
-    COAP_SET_STR(&uri->query, len, p);
-    len = 0;
-  }
-
-  end:
-  return len ? -1 : 0;
-
-  error:
-  return res;
-}
-
-/**
- * Calculates decimal value from hexadecimal ASCII character given in
- * @p c. The caller must ensure that @p c actually represents a valid
- * heaxdecimal character, e.g. with isxdigit(3).
- *
- * @hideinitializer
- */
-#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F))
-
-/**
- * Decodes percent-encoded characters while copying the string @p seg
- * of size @p length to @p buf. The caller of this function must
- * ensure that the percent-encodings are correct (i.e. the character
- * '%' is always followed by two hex digits. and that @p buf provides
- * sufficient space to hold the result. This function is supposed to
- * be called by make_decoded_option() only.
- *
- * @param seg     The segment to decode and copy.
- * @param length  Length of @p seg.
- * @param buf     The result buffer.
- */
-void
-decode_segment(const unsigned char *seg, size_t length, unsigned char *buf) {
-
-  while (length--) {
-
-    if (*seg == '%') {
-      *buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]);
-
-      seg += 2; length -= 2;
-    } else {
-      *buf = *seg;
-    }
-
-    ++buf; ++seg;
-  }
-}
-
-/**
- * Runs through the given path (or query) segment and checks if
- * percent-encodings are correct. This function returns @c -1 on error
- * or the length of @p s when decoded.
- */
-int
-check_segment(const unsigned char *s, size_t length) {
-
-  size_t n = 0;
-
-  while (length) {
-    if (*s == '%') {
-      if (length < 2 || !(isxdigit(s[1]) && isxdigit(s[2])))
-    return -1;
-
-      s += 2;
-      length -= 2;
-    }
-
-    ++s; ++n; --length;
-  }
-
-  return n;
-}
-
-/**
- * Writes a coap option from given string @p s to @p buf. @p s should
- * point to a (percent-encoded) path or query segment of a coap_uri_t
- * object.  The created option will have type @c 0, and the length
- * parameter will be set according to the size of the decoded string.
- * On success, this function returns the option's size, or a value
- * less than zero on error. This function must be called from
- * coap_split_path_impl() only.
- *
- * @param s       The string to decode.
- * @param length  The size of the percent-encoded string @p s.
- * @param buf     The buffer to store the new coap option.
- * @param buflen  The maximum size of @p buf.
- *
- * @return The option's size, or @c -1 on error.
- *
- * @bug This function does not split segments that are bigger than 270
- * bytes.
- */
-int
-make_decoded_option(const unsigned char *s, size_t length,
-            unsigned char *buf, size_t buflen) {
-  int res;
-  size_t written;
-
-  if (!buflen) {
-    debug("make_decoded_option(): buflen is 0!\n");
-    return -1;
-  }
-
-  res = check_segment(s, length);
-  if (res < 0)
-    return -1;
-
-  /* write option header using delta 0 and length res */
-  written = coap_opt_setheader(buf, buflen, 0, res);
-
-  assert(written <= buflen);
-
-  if (!written)         /* encoding error */
-    return -1;
-
-  buf += written;       /* advance past option type/length */
-  buflen -= written;
-
-  if (buflen < (size_t)res) {
-    debug("buffer too small for option\n");
-    return -1;
-  }
-
-  decode_segment(s, length, buf);
-
-  return written + res;
-}
-
-
-#ifndef min
-#define min(a,b) ((a) < (b) ? (a) : (b))
-#endif
-
-typedef void (*segment_handler_t)(unsigned char *, size_t, void *);
-
-/**
- * Splits the given string into segments. You should call one of the
- * macros coap_split_path() or coap_split_query() instead.
- *
- * @param parse_iter The iterator used for tokenizing.
- * @param h      A handler that is called with every token.
- * @param data   Opaque data that is passed to @p h when called.
- *
- * @return The number of characters that have been parsed from @p s.
- */
-size_t
-coap_split_path_impl(coap_parse_iterator_t *parse_iter,
-             segment_handler_t h, void *data) {
-  unsigned char *seg;
-  size_t length;
-
-  assert(parse_iter);
-  assert(h);
-
-  length = parse_iter->n;
-
-  while ( (seg = coap_parse_next(parse_iter)) ) {
-
-    /* any valid path segment is handled here: */
-    h(seg, parse_iter->segment_length, data);
-  }
-
-  return length - (parse_iter->n - parse_iter->segment_length);
-}
-
-struct cnt_str {
-  str buf;
-  int n;
-};
-
-void
-write_option(unsigned char *s, size_t len, void *data) {
-  struct cnt_str *state = (struct cnt_str *)data;
-  int res;
-  assert(state);
-
-  /* skip empty segments and those that consist of only one or two dots */
-  if (memcmp(s, "..", min(len,2)) == 0)
-    return;
-
-  res = make_decoded_option(s, len, state->buf.s, state->buf.length);
-  if (res > 0) {
-    state->buf.s += res;
-    state->buf.length -= res;
-    state->n++;
-  }
-}
-
-int
-coap_split_path(const unsigned char *s, size_t length,
-        unsigned char *buf, size_t *buflen) {
-  struct cnt_str tmp = { { *buflen, buf }, 0 };
-  coap_parse_iterator_t pi;
-
-  coap_parse_iterator_init((unsigned char *)s, length,
-               '/', (unsigned char *)"?#", 2, &pi);
-  coap_split_path_impl(&pi, write_option, &tmp);
-
-  *buflen = *buflen - tmp.buf.length;
-  return tmp.n;
-}
-
-int
-coap_split_query(const unsigned char *s, size_t length,
-        unsigned char *buf, size_t *buflen) {
-  struct cnt_str tmp = { { *buflen, buf }, 0 };
-  coap_parse_iterator_t pi;
-
-  coap_parse_iterator_init((unsigned char *)s, length,
-               '&', (unsigned char *)"#", 1, &pi);
-
-  coap_split_path_impl(&pi, write_option, &tmp);
-
-  *buflen = tmp.buf.length;
-  return tmp.n;
-}
-
-#define URI_DATA(uriobj) ((unsigned char *)(uriobj) + sizeof(coap_uri_t))
-
-coap_uri_t *
-coap_new_uri(const unsigned char *uri, unsigned int length) {
-  unsigned char *result;
-
-  result = (unsigned char*)coap_malloc(length + 1 + sizeof(coap_uri_t));
-
-  if (!result)
-    return NULL;
-
-  memcpy(URI_DATA(result), uri, length);
-  URI_DATA(result)[length] = '\0'; /* make it zero-terminated */
-
-  if (coap_split_uri(URI_DATA(result), length, (coap_uri_t *)result) < 0) {
-    coap_free(result);
-    return NULL;
-  }
-  return (coap_uri_t *)result;
-}
-
-coap_uri_t *
-coap_clone_uri(const coap_uri_t *uri) {
-  coap_uri_t *result;
-
-  if ( !uri )
-    return  NULL;
-
-  result = (coap_uri_t *)coap_malloc( uri->query.length + uri->host.length +
-                      uri->path.length + sizeof(coap_uri_t) + 1);
-
-  if ( !result )
-    return NULL;
-
-  memset( result, 0, sizeof(coap_uri_t) );
-
-  result->port = uri->port;
-
-  if ( uri->host.length ) {
-    result->host.s = URI_DATA(result);
-    result->host.length = uri->host.length;
-
-    memcpy(result->host.s, uri->host.s, uri->host.length);
-  }
-
-  if ( uri->path.length ) {
-    result->path.s = URI_DATA(result) + uri->host.length;
-    result->path.length = uri->path.length;
-
-    memcpy(result->path.s, uri->path.s, uri->path.length);
-  }
-
-  if ( uri->query.length ) {
-    result->query.s = URI_DATA(result) + uri->host.length + uri->path.length;
-    result->query.length = uri->query.length;
-
-    memcpy(result->query.s, uri->query.s, uri->query.length);
-  }
-
-  return result;
-}
-
-/* hash URI path segments */
-
-/* The function signature of coap_hash() is different from
- * segment_handler_t hence we use this wrapper as safe typecast. */
-static inline void
-hash_segment(unsigned char *s, size_t len, void *data) {
-  coap_hash(s, len, (unsigned char*)data);
-}
-
-int
-coap_hash_path(const unsigned char *path, size_t len, coap_key_t key) {
-  coap_parse_iterator_t pi;
-
-  if (!path)
-    return 0;
-
-  memset(key, 0, sizeof(coap_key_t));
-
-  coap_parse_iterator_init((unsigned char *)path, len,
-               '/', (unsigned char *)"?#", 2, &pi);
-  coap_split_path_impl(&pi, hash_segment, key);
-
-  return 1;
-}
-
-/* iterator functions */
-
-coap_parse_iterator_t *
-coap_parse_iterator_init(unsigned char *s, size_t n,
-             unsigned char separator,
-             unsigned char *delim, size_t dlen,
-             coap_parse_iterator_t *pi) {
-  assert(pi);
-  assert(separator);
-
-  pi->separator = separator;
-  pi->delim = delim;
-  pi->dlen = dlen;
-  pi->pos = s;
-  pi->n = n;
-  pi->segment_length = 0;
-
-  return pi;
-}
-
-unsigned char *
-coap_parse_next(coap_parse_iterator_t *pi) {
-  unsigned char *p;
-
-  if (!pi)
-    return NULL;
-
-  /* proceed to the next segment */
-  pi->n -= pi->segment_length;
-  pi->pos += pi->segment_length;
-  pi->segment_length = 0;
-
-  /* last segment? */
-  if (!pi->n || strnchr(pi->delim, pi->dlen, *pi->pos)) {
-    pi->pos = NULL;
-    return NULL;
-  }
-
-  /* skip following separator (the first segment might not have one) */
-  if (*pi->pos == pi->separator) {
-    ++pi->pos;
-    --pi->n;
-  }
-
-  p = pi->pos;
-
-  while (pi->segment_length < pi->n && *p != pi->separator &&
-     !strnchr(pi->delim, pi->dlen, *p)) {
-    ++p;
-    ++pi->segment_length;
-  }
-
-  if (!pi->n) {
-    pi->pos = NULL;
-    pi->segment_length = 0;
-  }
-
-  return pi->pos;
-}
-
diff --git a/resource/csdk/libcoap-4.1.1/uri.h b/resource/csdk/libcoap-4.1.1/uri.h
deleted file mode 100644 (file)
index 31ee386..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-/* uri.h -- helper functions for URI treatment
- *
- * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
- *
- * This file is part of the CoAP library libcoap. Please see
- * README for terms of use.
- */
-
-#ifndef _COAP_URI_H_
-#define _COAP_URI_H_
-
-#include "hashkey.h"
-#include "str.h"
-
-/** Representation of parsed URI. Components may be filled from a
- * string with coap_split_uri() and can be used as input for
- * option-creation functions. */
-typedef struct {
-  str host;         /**< host part of the URI */
-  unsigned short port;      /**< The port in host byte order */
-  str path;         /**< Beginning of the first path segment.
-                   Use coap_split_path() to create Uri-Path options */
-  str query;            /**<  The query part if present */
-  unsigned char secure; /**< uses coaps URI schema */
-} coap_uri_t;
-
-/**
- * Creates a new coap_uri_t object from the specified URI. Returns the new
- * object or NULL on error. The memory allocated by the new coap_uri_t
- * must be released using coap_free().
- * @param uri The URI path to copy.
- * @para length The length of uri.
- *
- * @return New URI object or NULL on error.
- */
-coap_uri_t *coap_new_uri(const unsigned char *uri, unsigned int length);
-
-/**
- * Clones the specified coap_uri_t object. Thie function allocates sufficient
- * memory to hold the coap_uri_t structure and its contents. The object must
- * be released with coap_free(). */
-coap_uri_t *coap_clone_uri(const coap_uri_t *uri);
-
-/**
- * Calculates a hash over the given path and stores the result in
- * @p key. This function returns @c 0 on error or @c 1 on success.
- *
- * @param path The URI path to generate hash for.
- * @param len  The length of @p path.
- * @param key  The output buffer.
- *
- * @return @c 1 if @p key was set, @c 0 otherwise.
- */
-int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key);
-
-/**
- * @defgroup uri_parse URI Parsing Functions
- *
- * CoAP PDUs contain normalized URIs with their path and query split into
- * multiple segments. The functions in this module help splitting strings.
- * @{
- */
-
-/**
- * Iterator to for tokenizing a URI path or query. This structure must
- * be initialized with coap_parse_iterator_init(). Call
- * coap_parse_next() to walk through the tokens.
- *
- * @code
- * unsigned char *token;
- * coap_parse_iterator_t pi;
- * coap_parse_iterator_init(uri.path.s, uri.path.length, '/', "?#", 2, &pi);
- *
- * while ((token = coap_parse_next(&pi))) {
- *   ... do something with token ...
- * }
- * @endcode
- */
-typedef struct {
-  size_t n;         /**< number of remaining characters in buffer */
-  unsigned char separator;  /**< segment separators */
-  unsigned char *delim;     /**< delimiters where to split the string */
-  size_t dlen;          /**< length of separator */
-  unsigned char *pos;       /**< current position in buffer */
-  size_t segment_length;    /**< length of current segment */
-} coap_parse_iterator_t;
-
-/**
- * Initializes the given iterator @p pi.
- *
- * @param s         The string to tokenize.
- * @param n         The length of @p s.
- * @param separator The separator character that delimits tokens.
- * @param delim     A set of characters that delimit @s.
- * @param dlen      The length of @p delim.
- * @param pi        The iterator object to initialize.
- *
- * @return The initialized iterator object @p pi.
- */
-coap_parse_iterator_t *
-coap_parse_iterator_init(unsigned char *s, size_t n,
-             unsigned char separator,
-             unsigned char *delim, size_t dlen,
-             coap_parse_iterator_t *pi);
-
-/**
- * Updates the iterator @p pi to point to the next token. This
- * function returns a pointer to that token or @c NULL if no more
- * tokens exist. The contents of @p pi will be updated. In particular,
- * @c pi->segment_length specifies the length of the current token, @c
- * pi->pos points to its beginning.
- *
- * @param pi The iterator to update.
- *
- * @return The next token or @c NULL if no more tokens exist.
- */
-unsigned char *coap_parse_next(coap_parse_iterator_t *pi);
-
-/**
- * Parses a given string into URI components. The identified syntactic
- * components are stored in the result parameter @p uri. Optional URI
- * components that are not specified will be set to { 0, 0 }, except
- * for the port which is set to @c COAP_DEFAULT_PORT. This function
- * returns @p 0 if parsing succeeded, a value less than zero
- * otherwise.
- *
- * @param str_var The string to split up.
- * @param len     The actual length of @p str_var
- * @param uri     The coap_uri_t object to store the result.
- * @return @c 0 on success, or < 0 on error.
- *
- * @note The host name part will be converted to lower case by this
- * function.
- */
-int
-coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri);
-
-/**
- * Splits the given URI path into segments. Each segment is preceded
- * by an option pseudo-header with delta-value 0 and the actual length
- * of the respective segment after percent-decoding.
- *
- * @param s      The path string to split.
- * @param length The actual length of @p s.
- * @param buf    Result buffer for parsed segments.
- * @param buflen Maximum length of @p buf. Will be set to the actual number
- * of bytes written into buf on success.
- *
- * @return The number of segments created or @c -1 on error.
- */
-int coap_split_path(const unsigned char *s, size_t length,
-            unsigned char *buf, size_t *buflen);
-
-/**
- * Splits the given URI query into segments. Each segment is preceded
- * by an option pseudo-header with delta-value 0 and the actual length
- * of the respective query term.
- *
- * @param s      The query string to split.
- * @param length The actual length of @p s.
- * @param buf    Result buffer for parsed segments.
- * @param buflen Maximum length of @p buf. Will be set to the actual number
- * of bytes written into buf on success.
- *
- * @return The number of segments created or @c -1 on error.
- *
- * @bug This function does not reserve additional space for delta > 12.
- */
-int coap_split_query(const unsigned char *s, size_t length,
-             unsigned char *buf, size_t *buflen);
-
-/** @} */
-
-#endif /* _COAP_URI_H_ */
diff --git a/resource/csdk/libcoap-4.1.1/uthash.h b/resource/csdk/libcoap-4.1.1/uthash.h
deleted file mode 100644 (file)
index d2da6e5..0000000
+++ /dev/null
@@ -1,977 +0,0 @@
-/*
-Copyright (c) 2003-2010, Troy D. Hanson     http://uthash.sourceforge.net
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright
-      notice, this list of conditions and the following disclaimer.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef UTHASH_H
-#define UTHASH_H
-
-#include <string.h>   /* memcmp,strlen */
-#include <stddef.h>   /* ptrdiff_t */
-
-#include "ocmalloc.h"
-
-/* These macros use decltype or the earlier __typeof GNU extension.
-   As decltype is only available in newer compilers (VS2010 or gcc 4.3+
-   when compiling c++ source) this code uses whatever method is needed
-   or, for VS2008 where neither is available, uses casting workarounds. */
-#ifdef _MSC_VER         /* MS compiler */
-#if _MSC_VER >= 1600 && defined(__cplusplus)  /* VS2010 or newer in C++ mode */
-#define DECLTYPE(x) (decltype(x))
-#else                   /* VS2008 or older (or VS2010 in C mode) */
-#define NO_DECLTYPE
-#define DECLTYPE(x)
-#endif
-#else                   /* GNU, Sun and other compilers */
-#define DECLTYPE(x) (__typeof(x))
-#endif
-
-#ifdef NO_DECLTYPE
-#define DECLTYPE_ASSIGN(dst,src)                                                 \
-do {                                                                             \
-  char **_da_dst = (char**)(&(dst));                                             \
-  *_da_dst = (char*)(src);                                                       \
-} while(0)
-#else
-#define DECLTYPE_ASSIGN(dst,src)                                                 \
-do {                                                                             \
-  (dst) = DECLTYPE(dst)(src);                                                    \
-} while(0)
-#endif
-
-/* a number of the hash function use uint32_t which isn't defined on win32 */
-#ifdef _MSC_VER
-typedef unsigned int uint32_t;
-#else
-#include <inttypes.h>   /* uint32_t */
-#endif
-
-#define UTHASH_VERSION 1.9.3
-
-#ifndef uthash_fatal
-#define uthash_fatal(msg) exit(-1)        /* fatal error (out of memory,etc) */
-#endif
-
-#define uthash_malloc(sz)      OCMalloc(sz)
-#define uthash_free(ptr,sz)    OCFree(ptr)
-
-#define uthash_noexpand_fyi(tbl)          /* can be defined to log noexpand  */
-#define uthash_expand_fyi(tbl)            /* can be defined to log expands   */
-
-/* initial number of buckets */
-#define HASH_INITIAL_NUM_BUCKETS 32      /* initial number of buckets        */
-#define HASH_INITIAL_NUM_BUCKETS_LOG2 5  /* lg2 of initial number of buckets */
-#define HASH_BKT_CAPACITY_THRESH 10      /* expand when bucket count reaches */
-
-/* calculate the element whose hash handle address is hhe */
-#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho)))
-
-#define HASH_FIND(hh,head,keyptr,keylen,out)                                     \
-do {                                                                             \
-  unsigned _hf_bkt,_hf_hashv;                                                    \
-  out=NULL;                                                                      \
-  if (head) {                                                                    \
-     HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt);   \
-     if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) {                           \
-       HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ],  \
-                        keyptr,keylen,out);                                      \
-     }                                                                           \
-  }                                                                              \
-} while (0)
-
-#ifdef HASH_BLOOM
-#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM)
-#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0)
-#define HASH_BLOOM_MAKE(tbl)                                                     \
-do {                                                                             \
-  (tbl)->bloom_nbits = HASH_BLOOM;                                               \
-  (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN);                 \
-  if (!((tbl)->bloom_bv))  { uthash_fatal( "out of memory"); }                   \
-  memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN);                                \
-  (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE;                                       \
-} while (0);
-
-#define HASH_BLOOM_FREE(tbl)                                                     \
-do {                                                                             \
-  uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN);                              \
-} while (0);
-
-#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8)))
-#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8)))
-
-#define HASH_BLOOM_ADD(tbl,hashv)                                                \
-  HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
-
-#define HASH_BLOOM_TEST(tbl,hashv)                                               \
-  HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
-
-#else
-#define HASH_BLOOM_MAKE(tbl)
-#define HASH_BLOOM_FREE(tbl)
-#define HASH_BLOOM_ADD(tbl,hashv)
-#define HASH_BLOOM_TEST(tbl,hashv) (1)
-#endif
-
-#define HASH_MAKE_TABLE(hh,head)                                                 \
-do {                                                                             \
-  (head)->hh.tbl = (UT_hash_table*)uthash_malloc(                                \
-                  sizeof(UT_hash_table));                                        \
-  if (!((head)->hh.tbl))  { uthash_fatal( "out of memory"); }                    \
-  memset((head)->hh.tbl, 0, sizeof(UT_hash_table));                              \
-  (head)->hh.tbl->tail = &((head)->hh);                                          \
-  (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS;                        \
-  (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2;              \
-  (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head);                    \
-  (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc(                      \
-          HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket));               \
-  if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); }             \
-  memset((head)->hh.tbl->buckets, 0,                                             \
-          HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket));               \
-  HASH_BLOOM_MAKE((head)->hh.tbl);                                               \
-  (head)->hh.tbl->signature = HASH_SIGNATURE;                                    \
-} while(0)
-
-#define HASH_ADD(hh,head,fieldname,keylen_in,add)                                \
-        HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add)
-
-#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add)                            \
-do {                                                                             \
- unsigned _ha_bkt;                                                               \
- (add)->hh.next = NULL;                                                          \
- (add)->hh.key = (char*)keyptr;                                                  \
- (add)->hh.keylen = keylen_in;                                                   \
- if (!(head)) {                                                                  \
-    head = (add);                                                                \
-    (head)->hh.prev = NULL;                                                      \
-    HASH_MAKE_TABLE(hh,head);                                                    \
- } else {                                                                        \
-    (head)->hh.tbl->tail->next = (add);                                          \
-    (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail);         \
-    (head)->hh.tbl->tail = &((add)->hh);                                         \
- }                                                                               \
- (head)->hh.tbl->num_items++;                                                    \
- (add)->hh.tbl = (head)->hh.tbl;                                                 \
- HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets,                         \
-         (add)->hh.hashv, _ha_bkt);                                              \
- HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh);                   \
- HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv);                                 \
- HASH_EMIT_KEY(hh,head,keyptr,keylen_in);                                        \
- HASH_FSCK(hh,head);                                                             \
-} while(0)
-
-#define HASH_TO_BKT( hashv, num_bkts, bkt )                                      \
-do {                                                                             \
-  bkt = ((hashv) & ((num_bkts) - 1));                                            \
-} while(0)
-
-/* delete "delptr" from the hash table.
- * "the usual" patch-up process for the app-order doubly-linked-list.
- * The use of _hd_hh_del below deserves special explanation.
- * These used to be expressed using (delptr) but that led to a bug
- * if someone used the same symbol for the head and deletee, like
- *  HASH_DELETE(hh,users,users);
- * We want that to work, but by changing the head (users) below
- * we were forfeiting our ability to further refer to the deletee (users)
- * in the patch-up process. Solution: use scratch space to
- * copy the deletee pointer, then the latter references are via that
- * scratch pointer rather than through the repointed (users) symbol.
- */
-#define HASH_DELETE(hh,head,delptr)                                              \
-do {                                                                             \
-    unsigned _hd_bkt;                                                            \
-    struct UT_hash_handle *_hd_hh_del;                                           \
-    if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) )  {         \
-        uthash_free((head)->hh.tbl->buckets,                                     \
-                    (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \
-        HASH_BLOOM_FREE((head)->hh.tbl);                                         \
-        uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                      \
-        head = NULL;                                                             \
-    } else {                                                                     \
-        _hd_hh_del = &((delptr)->hh);                                            \
-        if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) {     \
-            (head)->hh.tbl->tail =                                               \
-                (UT_hash_handle*)((char*)((delptr)->hh.prev) +                   \
-                (head)->hh.tbl->hho);                                            \
-        }                                                                        \
-        if ((delptr)->hh.prev) {                                                 \
-            ((UT_hash_handle*)((char*)((delptr)->hh.prev) +                      \
-                    (head)->hh.tbl->hho))->next = (delptr)->hh.next;             \
-        } else {                                                                 \
-            DECLTYPE_ASSIGN(head,(delptr)->hh.next);                             \
-        }                                                                        \
-        if (_hd_hh_del->next) {                                                  \
-            ((UT_hash_handle*)((char*)_hd_hh_del->next +                         \
-                    (head)->hh.tbl->hho))->prev =                                \
-                    _hd_hh_del->prev;                                            \
-        }                                                                        \
-        HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt);   \
-        HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del);        \
-        (head)->hh.tbl->num_items--;                                             \
-    }                                                                            \
-    HASH_FSCK(hh,head);                                                          \
-} while (0)
-
-
-/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */
-#define HASH_FIND_STR(head,findstr,out)                                          \
-    HASH_FIND(hh,head,findstr,strlen(findstr),out)
-#define HASH_ADD_STR(head,strfield,add)                                          \
-    HASH_ADD(hh,head,strfield,strlen(add->strfield),add)
-#define HASH_FIND_INT(head,findint,out)                                          \
-    HASH_FIND(hh,head,findint,sizeof(int),out)
-#define HASH_ADD_INT(head,intfield,add)                                          \
-    HASH_ADD(hh,head,intfield,sizeof(int),add)
-#define HASH_FIND_PTR(head,findptr,out)                                          \
-    HASH_FIND(hh,head,findptr,sizeof(void *),out)
-#define HASH_ADD_PTR(head,ptrfield,add)                                          \
-    HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
-#define HASH_DEL(head,delptr)                                                    \
-    HASH_DELETE(hh,head,delptr)
-
-/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined.
- * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined.
- */
-#ifdef HASH_DEBUG
-#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0)
-#define HASH_FSCK(hh,head)                                                       \
-do {                                                                             \
-    unsigned _bkt_i;                                                             \
-    unsigned _count, _bkt_count;                                                 \
-    char *_prev;                                                                 \
-    struct UT_hash_handle *_thh;                                                 \
-    if (head) {                                                                  \
-        _count = 0;                                                              \
-        for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) {       \
-            _bkt_count = 0;                                                      \
-            _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head;                      \
-            _prev = NULL;                                                        \
-            while (_thh) {                                                       \
-               if (_prev != (char*)(_thh->hh_prev)) {                            \
-                   HASH_OOPS("invalid hh_prev %p, actual %p\n",                  \
-                    _thh->hh_prev, _prev );                                      \
-               }                                                                 \
-               _bkt_count++;                                                     \
-               _prev = (char*)(_thh);                                            \
-               _thh = _thh->hh_next;                                             \
-            }                                                                    \
-            _count += _bkt_count;                                                \
-            if ((head)->hh.tbl->buckets[_bkt_i].count !=  _bkt_count) {          \
-               HASH_OOPS("invalid bucket count %d, actual %d\n",                 \
-                (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count);              \
-            }                                                                    \
-        }                                                                        \
-        if (_count != (head)->hh.tbl->num_items) {                               \
-            HASH_OOPS("invalid hh item count %d, actual %d\n",                   \
-                (head)->hh.tbl->num_items, _count );                             \
-        }                                                                        \
-        /* traverse hh in app order; check next/prev integrity, count */         \
-        _count = 0;                                                              \
-        _prev = NULL;                                                            \
-        _thh =  &(head)->hh;                                                     \
-        while (_thh) {                                                           \
-           _count++;                                                             \
-           if (_prev !=(char*)(_thh->prev)) {                                    \
-              HASH_OOPS("invalid prev %p, actual %p\n",                          \
-                    _thh->prev, _prev );                                         \
-           }                                                                     \
-           _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh);                    \
-           _thh = ( _thh->next ?  (UT_hash_handle*)((char*)(_thh->next) +        \
-                                  (head)->hh.tbl->hho) : NULL );                 \
-        }                                                                        \
-        if (_count != (head)->hh.tbl->num_items) {                               \
-            HASH_OOPS("invalid app item count %d, actual %d\n",                  \
-                (head)->hh.tbl->num_items, _count );                             \
-        }                                                                        \
-    }                                                                            \
-} while (0)
-#else
-#define HASH_FSCK(hh,head)
-#endif
-
-/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to
- * the descriptor to which this macro is defined for tuning the hash function.
- * The app can #include <unistd.h> to get the prototype for write(2). */
-#ifdef HASH_EMIT_KEYS
-#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                                   \
-do {                                                                             \
-    unsigned _klen = fieldlen;                                                   \
-    write(HASH_EMIT_KEYS, &_klen, sizeof(_klen));                                \
-    write(HASH_EMIT_KEYS, keyptr, fieldlen);                                     \
-} while (0)
-#else
-#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)
-#endif
-
-/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */
-#ifdef HASH_FUNCTION
-#define HASH_FCN HASH_FUNCTION
-#else
-#define HASH_FCN HASH_JEN
-#endif
-
-/* The Bernstein hash function, used in Perl prior to v5.6 */
-#define HASH_BER(key,keylen,num_bkts,hashv,bkt)                                  \
-do {                                                                             \
-  unsigned _hb_keylen=keylen;                                                    \
-  char *_hb_key=(char*)(key);                                                    \
-  (hashv) = 0;                                                                   \
-  while (_hb_keylen--)  { (hashv) = ((hashv) * 33) + *_hb_key++; }               \
-  bkt = (hashv) & (num_bkts-1);                                                  \
-} while (0)
-
-
-/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at
- * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */
-#define HASH_SAX(key,keylen,num_bkts,hashv,bkt)                                  \
-do {                                                                             \
-  unsigned _sx_i;                                                                \
-  char *_hs_key=(char*)(key);                                                    \
-  hashv = 0;                                                                     \
-  for(_sx_i=0; _sx_i < keylen; _sx_i++)                                          \
-      hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i];                     \
-  bkt = hashv & (num_bkts-1);                                                    \
-} while (0)
-
-#define HASH_FNV(key,keylen,num_bkts,hashv,bkt)                                  \
-do {                                                                             \
-  unsigned _fn_i;                                                                \
-  char *_hf_key=(char*)(key);                                                    \
-  hashv = 2166136261UL;                                                          \
-  for(_fn_i=0; _fn_i < keylen; _fn_i++)                                          \
-      hashv = (hashv * 16777619) ^ _hf_key[_fn_i];                               \
-  bkt = hashv & (num_bkts-1);                                                    \
-} while(0);
-
-#define HASH_OAT(key,keylen,num_bkts,hashv,bkt)                                  \
-do {                                                                             \
-  unsigned _ho_i;                                                                \
-  char *_ho_key=(char*)(key);                                                    \
-  hashv = 0;                                                                     \
-  for(_ho_i=0; _ho_i < keylen; _ho_i++) {                                        \
-      hashv += _ho_key[_ho_i];                                                   \
-      hashv += (hashv << 10);                                                    \
-      hashv ^= (hashv >> 6);                                                     \
-  }                                                                              \
-  hashv += (hashv << 3);                                                         \
-  hashv ^= (hashv >> 11);                                                        \
-  hashv += (hashv << 15);                                                        \
-  bkt = hashv & (num_bkts-1);                                                    \
-} while(0)
-
-#define HASH_JEN_MIX(a,b,c)                                                      \
-do {                                                                             \
-  a -= b; a -= c; a ^= ( c >> 13 );                                              \
-  b -= c; b -= a; b ^= ( a << 8 );                                               \
-  c -= a; c -= b; c ^= ( b >> 13 );                                              \
-  a -= b; a -= c; a ^= ( c >> 12 );                                              \
-  b -= c; b -= a; b ^= ( a << 16 );                                              \
-  c -= a; c -= b; c ^= ( b >> 5 );                                               \
-  a -= b; a -= c; a ^= ( c >> 3 );                                               \
-  b -= c; b -= a; b ^= ( a << 10 );                                              \
-  c -= a; c -= b; c ^= ( b >> 15 );                                              \
-} while (0)
-
-#define HASH_JEN(key,keylen,num_bkts,hashv,bkt)                                  \
-do {                                                                             \
-  unsigned _hj_i,_hj_j,_hj_k;                                                    \
-  char *_hj_key=(char*)(key);                                                    \
-  hashv = 0xfeedbeef;                                                            \
-  _hj_i = _hj_j = 0x9e3779b9;                                                    \
-  _hj_k = keylen;                                                                \
-  while (_hj_k >= 12) {                                                          \
-    _hj_i +=    (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 )                      \
-        + ( (unsigned)_hj_key[2] << 16 )                                         \
-        + ( (unsigned)_hj_key[3] << 24 ) );                                      \
-    _hj_j +=    (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 )                      \
-        + ( (unsigned)_hj_key[6] << 16 )                                         \
-        + ( (unsigned)_hj_key[7] << 24 ) );                                      \
-    hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 )                         \
-        + ( (unsigned)_hj_key[10] << 16 )                                        \
-        + ( (unsigned)_hj_key[11] << 24 ) );                                     \
-                                                                                 \
-     HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                          \
-                                                                                 \
-     _hj_key += 12;                                                              \
-     _hj_k -= 12;                                                                \
-  }                                                                              \
-  hashv += keylen;                                                               \
-  switch ( _hj_k ) {                                                             \
-     case 11: hashv += ( (unsigned)_hj_key[10] << 24 );                          \
-     case 10: hashv += ( (unsigned)_hj_key[9] << 16 );                           \
-     case 9:  hashv += ( (unsigned)_hj_key[8] << 8 );                            \
-     case 8:  _hj_j += ( (unsigned)_hj_key[7] << 24 );                           \
-     case 7:  _hj_j += ( (unsigned)_hj_key[6] << 16 );                           \
-     case 6:  _hj_j += ( (unsigned)_hj_key[5] << 8 );                            \
-     case 5:  _hj_j += _hj_key[4];                                               \
-     case 4:  _hj_i += ( (unsigned)_hj_key[3] << 24 );                           \
-     case 3:  _hj_i += ( (unsigned)_hj_key[2] << 16 );                           \
-     case 2:  _hj_i += ( (unsigned)_hj_key[1] << 8 );                            \
-     case 1:  _hj_i += _hj_key[0];                                               \
-  }                                                                              \
-  HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                             \
-  bkt = hashv & (num_bkts-1);                                                    \
-} while(0)
-
-/* The Paul Hsieh hash function */
-#undef get16bits
-#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__)             \
-  || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
-#define get16bits(d) (*((const uint16_t *) (d)))
-#endif
-
-#if !defined (get16bits)
-#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)             \
-                       +(uint32_t)(((const uint8_t *)(d))[0]) )
-#endif
-#define HASH_SFH(key,keylen,num_bkts,hashv,bkt)                                  \
-do {                                                                             \
-  char *_sfh_key=(char*)(key);                                                   \
-  uint32_t _sfh_tmp, _sfh_len = keylen;                                          \
-                                                                                 \
-  int _sfh_rem = _sfh_len & 3;                                                   \
-  _sfh_len >>= 2;                                                                \
-  hashv = 0xcafebabe;                                                            \
-                                                                                 \
-  /* Main loop */                                                                \
-  for (;_sfh_len > 0; _sfh_len--) {                                              \
-    hashv    += get16bits (_sfh_key);                                            \
-    _sfh_tmp       = (get16bits (_sfh_key+2) << 11) ^ hashv;                     \
-    hashv     = (hashv << 16) ^ _sfh_tmp;                                        \
-    _sfh_key += 2*sizeof (uint16_t);                                             \
-    hashv    += hashv >> 11;                                                     \
-  }                                                                              \
-                                                                                 \
-  /* Handle end cases */                                                         \
-  switch (_sfh_rem) {                                                            \
-    case 3: hashv += get16bits (_sfh_key);                                       \
-            hashv ^= hashv << 16;                                                \
-            hashv ^= _sfh_key[sizeof (uint16_t)] << 18;                          \
-            hashv += hashv >> 11;                                                \
-            break;                                                               \
-    case 2: hashv += get16bits (_sfh_key);                                       \
-            hashv ^= hashv << 11;                                                \
-            hashv += hashv >> 17;                                                \
-            break;                                                               \
-    case 1: hashv += *_sfh_key;                                                  \
-            hashv ^= hashv << 10;                                                \
-            hashv += hashv >> 1;                                                 \
-  }                                                                              \
-                                                                                 \
-    /* Force "avalanching" of final 127 bits */                                  \
-    hashv ^= hashv << 3;                                                         \
-    hashv += hashv >> 5;                                                         \
-    hashv ^= hashv << 4;                                                         \
-    hashv += hashv >> 17;                                                        \
-    hashv ^= hashv << 25;                                                        \
-    hashv += hashv >> 6;                                                         \
-    bkt = hashv & (num_bkts-1);                                                  \
-} while(0);
-
-#ifdef HASH_USING_NO_STRICT_ALIASING
-/* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads.
- * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error.
- * So MurmurHash comes in two versions, the faster unaligned one and the slower
- * aligned one. We only use the faster one on CPU's where we know it's safe.
- *
- * Note the preprocessor built-in defines can be emitted using:
- *
- *   gcc -m64 -dM -E - < /dev/null                  (on gcc)
- *   cc -## a.c (where a.c is a simple test file)   (Sun Studio)
- */
-#if (defined(__i386__) || defined(__x86_64__))
-#define HASH_MUR HASH_MUR_UNALIGNED
-#else
-#define HASH_MUR HASH_MUR_ALIGNED
-#endif
-
-/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */
-#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt)                        \
-do {                                                                             \
-  const unsigned int _mur_m = 0x5bd1e995;                                        \
-  const int _mur_r = 24;                                                         \
-  hashv = 0xcafebabe ^ keylen;                                                   \
-  char *_mur_key = (char *)(key);                                                \
-  uint32_t _mur_tmp, _mur_len = keylen;                                          \
-                                                                                 \
-  for (;_mur_len >= 4; _mur_len-=4) {                                            \
-    _mur_tmp = *(uint32_t *)_mur_key;                                            \
-    _mur_tmp *= _mur_m;                                                          \
-    _mur_tmp ^= _mur_tmp >> _mur_r;                                              \
-    _mur_tmp *= _mur_m;                                                          \
-    hashv *= _mur_m;                                                             \
-    hashv ^= _mur_tmp;                                                           \
-    _mur_key += 4;                                                               \
-  }                                                                              \
-                                                                                 \
-  switch(_mur_len)                                                               \
-  {                                                                              \
-    case 3: hashv ^= _mur_key[2] << 16;                                          \
-    case 2: hashv ^= _mur_key[1] << 8;                                           \
-    case 1: hashv ^= _mur_key[0];                                                \
-            hashv *= _mur_m;                                                     \
-  };                                                                             \
-                                                                                 \
-  hashv ^= hashv >> 13;                                                          \
-  hashv *= _mur_m;                                                               \
-  hashv ^= hashv >> 15;                                                          \
-                                                                                 \
-  bkt = hashv & (num_bkts-1);                                                    \
-} while(0)
-
-/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */
-#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt)                          \
-do {                                                                             \
-  const unsigned int _mur_m = 0x5bd1e995;                                        \
-  const int _mur_r = 24;                                                         \
-  hashv = 0xcafebabe ^ (keylen);                                                 \
-  char *_mur_key = (char *)(key);                                                \
-  uint32_t _mur_len = keylen;                                                    \
-  int _mur_align = (int)_mur_key & 3;                                            \
-                                                                                 \
-  if (_mur_align && (_mur_len >= 4)) {                                           \
-    unsigned _mur_t = 0, _mur_d = 0;                                             \
-    switch(_mur_align) {                                                         \
-      case 1: _mur_t |= _mur_key[2] << 16;                                       \
-      case 2: _mur_t |= _mur_key[1] << 8;                                        \
-      case 3: _mur_t |= _mur_key[0];                                             \
-    }                                                                            \
-    _mur_t <<= (8 * _mur_align);                                                 \
-    _mur_key += 4-_mur_align;                                                    \
-    _mur_len -= 4-_mur_align;                                                    \
-    int _mur_sl = 8 * (4-_mur_align);                                            \
-    int _mur_sr = 8 * _mur_align;                                                \
-                                                                                 \
-    for (;_mur_len >= 4; _mur_len-=4) {                                          \
-      _mur_d = *(unsigned *)_mur_key;                                            \
-      _mur_t = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);                        \
-      unsigned _mur_k = _mur_t;                                                  \
-      _mur_k *= _mur_m;                                                          \
-      _mur_k ^= _mur_k >> _mur_r;                                                \
-      _mur_k *= _mur_m;                                                          \
-      hashv *= _mur_m;                                                           \
-      hashv ^= _mur_k;                                                           \
-      _mur_t = _mur_d;                                                           \
-      _mur_key += 4;                                                             \
-    }                                                                            \
-    _mur_d = 0;                                                                  \
-    if(_mur_len >= _mur_align) {                                                 \
-      switch(_mur_align) {                                                       \
-        case 3: _mur_d |= _mur_key[2] << 16;                                     \
-        case 2: _mur_d |= _mur_key[1] << 8;                                      \
-        case 1: _mur_d |= _mur_key[0];                                           \
-      }                                                                          \
-      unsigned _mur_k = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);               \
-      _mur_k *= _mur_m;                                                          \
-      _mur_k ^= _mur_k >> _mur_r;                                                \
-      _mur_k *= _mur_m;                                                          \
-      hashv *= _mur_m;                                                           \
-      hashv ^= _mur_k;                                                           \
-      _mur_k += _mur_align;                                                      \
-      _mur_len -= _mur_align;                                                    \
-                                                                                 \
-      switch(_mur_len)                                                           \
-      {                                                                          \
-        case 3: hashv ^= _mur_key[2] << 16;                                      \
-        case 2: hashv ^= _mur_key[1] << 8;                                       \
-        case 1: hashv ^= _mur_key[0];                                            \
-                hashv *= _mur_m;                                                 \
-      }                                                                          \
-    } else {                                                                     \
-      switch(_mur_len)                                                           \
-      {                                                                          \
-        case 3: _mur_d ^= _mur_key[2] << 16;                                     \
-        case 2: _mur_d ^= _mur_key[1] << 8;                                      \
-        case 1: _mur_d ^= _mur_key[0];                                           \
-        case 0: hashv ^= (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);              \
-        hashv *= _mur_m;                                                         \
-      }                                                                          \
-    }                                                                            \
-                                                                                 \
-    hashv ^= hashv >> 13;                                                        \
-    hashv *= _mur_m;                                                             \
-    hashv ^= hashv >> 15;                                                        \
-  } else {                                                                       \
-    for (;_mur_len >= 4; _mur_len-=4) {                                          \
-      unsigned _mur_k = *(unsigned*)_mur_key;                                    \
-      _mur_k *= _mur_m;                                                          \
-      _mur_k ^= _mur_k >> _mur_r;                                                \
-      _mur_k *= _mur_m;                                                          \
-      hashv *= _mur_m;                                                           \
-      hashv ^= _mur_k;                                                           \
-      _mur_key += 4;                                                             \
-    }                                                                            \
-    switch(_mur_len)                                                             \
-    {                                                                            \
-      case 3: hashv ^= _mur_key[2] << 16;                                        \
-      case 2: hashv ^= _mur_key[1] << 8;                                         \
-      case 1: hashv ^= _mur_key[0];                                              \
-      hashv *= _mur_m;                                                           \
-    }                                                                            \
-                                                                                 \
-    hashv ^= hashv >> 13;                                                        \
-    hashv *= _mur_m;                                                             \
-    hashv ^= hashv >> 15;                                                        \
-  }                                                                              \
-  bkt = hashv & (num_bkts-1);                                                    \
-} while(0)
-#endif  /* HASH_USING_NO_STRICT_ALIASING */
-
-/* key comparison function; return 0 if keys equal */
-#define HASH_KEYCMP(a,b,len) memcmp(a,b,len)
-
-/* iterate over items in a known bucket to find desired item */
-#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out)                       \
-do {                                                                             \
- if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head));          \
- else out=NULL;                                                                  \
- while (out) {                                                                   \
-    if (out->hh.keylen == keylen_in) {                                           \
-        if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break;             \
-    }                                                                            \
-    if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \
-    else out = NULL;                                                             \
- }                                                                               \
-} while(0)
-
-/* add an item to a bucket  */
-#define HASH_ADD_TO_BKT(head,addhh)                                              \
-do {                                                                             \
- head.count++;                                                                   \
- (addhh)->hh_next = head.hh_head;                                                \
- (addhh)->hh_prev = NULL;                                                        \
- if (head.hh_head) { (head).hh_head->hh_prev = (addhh); }                        \
- (head).hh_head=addhh;                                                           \
- if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH)             \
-     && (addhh)->tbl->noexpand != 1) {                                           \
-       HASH_EXPAND_BUCKETS((addhh)->tbl);                                        \
- }                                                                               \
-} while(0)
-
-/* remove an item from a given bucket */
-#define HASH_DEL_IN_BKT(hh,head,hh_del)                                          \
-    (head).count--;                                                              \
-    if ((head).hh_head == hh_del) {                                              \
-      (head).hh_head = hh_del->hh_next;                                          \
-    }                                                                            \
-    if (hh_del->hh_prev) {                                                       \
-        hh_del->hh_prev->hh_next = hh_del->hh_next;                              \
-    }                                                                            \
-    if (hh_del->hh_next) {                                                       \
-        hh_del->hh_next->hh_prev = hh_del->hh_prev;                              \
-    }
-
-/* Bucket expansion has the effect of doubling the number of buckets
- * and redistributing the items into the new buckets. Ideally the
- * items will distribute more or less evenly into the new buckets
- * (the extent to which this is true is a measure of the quality of
- * the hash function as it applies to the key domain).
- *
- * With the items distributed into more buckets, the chain length
- * (item count) in each bucket is reduced. Thus by expanding buckets
- * the hash keeps a bound on the chain length. This bounded chain
- * length is the essence of how a hash provides constant time lookup.
- *
- * The calculation of tbl->ideal_chain_maxlen below deserves some
- * explanation. First, keep in mind that we're calculating the ideal
- * maximum chain length based on the *new* (doubled) bucket count.
- * In fractions this is just n/b (n=number of items,b=new num buckets).
- * Since the ideal chain length is an integer, we want to calculate
- * ceil(n/b). We don't depend on floating point arithmetic in this
- * hash, so to calculate ceil(n/b) with integers we could write
- *
- *      ceil(n/b) = (n/b) + ((n%b)?1:0)
- *
- * and in fact a previous version of this hash did just that.
- * But now we have improved things a bit by recognizing that b is
- * always a power of two. We keep its base 2 log handy (call it lb),
- * so now we can write this with a bit shift and logical AND:
- *
- *      ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)
- *
- */
-#define HASH_EXPAND_BUCKETS(tbl)                                                 \
-do {                                                                             \
-    unsigned _he_bkt;                                                            \
-    unsigned _he_bkt_i;                                                          \
-    struct UT_hash_handle *_he_thh, *_he_hh_nxt;                                 \
-    UT_hash_bucket *_he_new_buckets, *_he_newbkt;                                \
-    _he_new_buckets = (UT_hash_bucket*)uthash_malloc(                            \
-             2 * tbl->num_buckets * sizeof(struct UT_hash_bucket));              \
-    if (!_he_new_buckets) { uthash_fatal( "out of memory"); }                    \
-    memset(_he_new_buckets, 0,                                                   \
-            2 * tbl->num_buckets * sizeof(struct UT_hash_bucket));               \
-    tbl->ideal_chain_maxlen =                                                    \
-       (tbl->num_items >> (tbl->log2_num_buckets+1)) +                           \
-       ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0);                    \
-    tbl->nonideal_items = 0;                                                     \
-    for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++)                \
-    {                                                                            \
-        _he_thh = tbl->buckets[ _he_bkt_i ].hh_head;                             \
-        while (_he_thh) {                                                        \
-           _he_hh_nxt = _he_thh->hh_next;                                        \
-           HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt);            \
-           _he_newbkt = &(_he_new_buckets[ _he_bkt ]);                           \
-           if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) {                \
-             tbl->nonideal_items++;                                              \
-             _he_newbkt->expand_mult = _he_newbkt->count /                       \
-                                        tbl->ideal_chain_maxlen;                 \
-           }                                                                     \
-           _he_thh->hh_prev = NULL;                                              \
-           _he_thh->hh_next = _he_newbkt->hh_head;                               \
-           if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev =               \
-                _he_thh;                                                         \
-           _he_newbkt->hh_head = _he_thh;                                        \
-           _he_thh = _he_hh_nxt;                                                 \
-        }                                                                        \
-    }                                                                            \
-    uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \
-    tbl->num_buckets *= 2;                                                       \
-    tbl->log2_num_buckets++;                                                     \
-    tbl->buckets = _he_new_buckets;                                              \
-    tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ?         \
-        (tbl->ineff_expands+1) : 0;                                              \
-    if (tbl->ineff_expands > 1) {                                                \
-        tbl->noexpand=1;                                                         \
-        uthash_noexpand_fyi(tbl);                                                \
-    }                                                                            \
-    uthash_expand_fyi(tbl);                                                      \
-} while(0)
-
-
-/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */
-/* Note that HASH_SORT assumes the hash handle name to be hh.
- * HASH_SRT was added to allow the hash handle name to be passed in. */
-#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)
-#define HASH_SRT(hh,head,cmpfcn)                                                 \
-do {                                                                             \
-  unsigned _hs_i;                                                                \
-  unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize;               \
-  struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail;            \
-  if (head) {                                                                    \
-      _hs_insize = 1;                                                            \
-      _hs_looping = 1;                                                           \
-      _hs_list = &((head)->hh);                                                  \
-      while (_hs_looping) {                                                      \
-          _hs_p = _hs_list;                                                      \
-          _hs_list = NULL;                                                       \
-          _hs_tail = NULL;                                                       \
-          _hs_nmerges = 0;                                                       \
-          while (_hs_p) {                                                        \
-              _hs_nmerges++;                                                     \
-              _hs_q = _hs_p;                                                     \
-              _hs_psize = 0;                                                     \
-              for ( _hs_i = 0; _hs_i  < _hs_insize; _hs_i++ ) {                  \
-                  _hs_psize++;                                                   \
-                  _hs_q = (UT_hash_handle*)((_hs_q->next) ?                      \
-                          ((void*)((char*)(_hs_q->next) +                        \
-                          (head)->hh.tbl->hho)) : NULL);                         \
-                  if (! (_hs_q) ) break;                                         \
-              }                                                                  \
-              _hs_qsize = _hs_insize;                                            \
-              while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) {           \
-                  if (_hs_psize == 0) {                                          \
-                      _hs_e = _hs_q;                                             \
-                      _hs_q = (UT_hash_handle*)((_hs_q->next) ?                  \
-                              ((void*)((char*)(_hs_q->next) +                    \
-                              (head)->hh.tbl->hho)) : NULL);                     \
-                      _hs_qsize--;                                               \
-                  } else if ( (_hs_qsize == 0) || !(_hs_q) ) {                   \
-                      _hs_e = _hs_p;                                             \
-                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
-                              ((void*)((char*)(_hs_p->next) +                    \
-                              (head)->hh.tbl->hho)) : NULL);                     \
-                      _hs_psize--;                                               \
-                  } else if ((                                                   \
-                      cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \
-                             DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \
-                             ) <= 0) {                                           \
-                      _hs_e = _hs_p;                                             \
-                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
-                              ((void*)((char*)(_hs_p->next) +                    \
-                              (head)->hh.tbl->hho)) : NULL);                     \
-                      _hs_psize--;                                               \
-                  } else {                                                       \
-                      _hs_e = _hs_q;                                             \
-                      _hs_q = (UT_hash_handle*)((_hs_q->next) ?                  \
-                              ((void*)((char*)(_hs_q->next) +                    \
-                              (head)->hh.tbl->hho)) : NULL);                     \
-                      _hs_qsize--;                                               \
-                  }                                                              \
-                  if ( _hs_tail ) {                                              \
-                      _hs_tail->next = ((_hs_e) ?                                \
-                            ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL);          \
-                  } else {                                                       \
-                      _hs_list = _hs_e;                                          \
-                  }                                                              \
-                  _hs_e->prev = ((_hs_tail) ?                                    \
-                     ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL);              \
-                  _hs_tail = _hs_e;                                              \
-              }                                                                  \
-              _hs_p = _hs_q;                                                     \
-          }                                                                      \
-          _hs_tail->next = NULL;                                                 \
-          if ( _hs_nmerges <= 1 ) {                                              \
-              _hs_looping=0;                                                     \
-              (head)->hh.tbl->tail = _hs_tail;                                   \
-              DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list));      \
-          }                                                                      \
-          _hs_insize *= 2;                                                       \
-      }                                                                          \
-      HASH_FSCK(hh,head);                                                        \
- }                                                                               \
-} while (0)
-
-/* This function selects items from one hash into another hash.
- * The end result is that the selected items have dual presence
- * in both hashes. There is no copy of the items made; rather
- * they are added into the new hash through a secondary hash
- * hash handle that must be present in the structure. */
-#define HASH_SELECT(hh_dst, dst, hh_src, src, cond)                              \
-do {                                                                             \
-  unsigned _src_bkt, _dst_bkt;                                                   \
-  void *_last_elt=NULL, *_elt;                                                   \
-  UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL;                         \
-  ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst));                 \
-  if (src) {                                                                     \
-    for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) {     \
-      for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head;                \
-          _src_hh;                                                               \
-          _src_hh = _src_hh->hh_next) {                                          \
-          _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh);                       \
-          if (cond(_elt)) {                                                      \
-            _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho);               \
-            _dst_hh->key = _src_hh->key;                                         \
-            _dst_hh->keylen = _src_hh->keylen;                                   \
-            _dst_hh->hashv = _src_hh->hashv;                                     \
-            _dst_hh->prev = _last_elt;                                           \
-            _dst_hh->next = NULL;                                                \
-            if (_last_elt_hh) { _last_elt_hh->next = _elt; }                     \
-            if (!dst) {                                                          \
-              DECLTYPE_ASSIGN(dst,_elt);                                         \
-              HASH_MAKE_TABLE(hh_dst,dst);                                       \
-            } else {                                                             \
-              _dst_hh->tbl = (dst)->hh_dst.tbl;                                  \
-            }                                                                    \
-            HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt);    \
-            HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh);            \
-            (dst)->hh_dst.tbl->num_items++;                                      \
-            _last_elt = _elt;                                                    \
-            _last_elt_hh = _dst_hh;                                              \
-          }                                                                      \
-      }                                                                          \
-    }                                                                            \
-  }                                                                              \
-  HASH_FSCK(hh_dst,dst);                                                         \
-} while (0)
-
-#define HASH_CLEAR(hh,head)                                                      \
-do {                                                                             \
-  if (head) {                                                                    \
-    uthash_free((head)->hh.tbl->buckets,                                         \
-                (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket));      \
-    uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                          \
-    (head)=NULL;                                                                 \
-  }                                                                              \
-} while(0)
-
-#ifdef NO_DECLTYPE
-#define HASH_ITER(hh,head,el,tmp)                                                \
-for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL);       \
-  el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL))
-#else
-#define HASH_ITER(hh,head,el,tmp)                                                \
-for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL);                 \
-  el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL))
-#endif
-
-/* obtain a count of items in the hash */
-#define HASH_COUNT(head) HASH_CNT(hh,head)
-#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0)
-
-typedef struct UT_hash_bucket {
-   struct UT_hash_handle *hh_head;
-   unsigned count;
-
-   /* expand_mult is normally set to 0. In this situation, the max chain length
-    * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
-    * the bucket's chain exceeds this length, bucket expansion is triggered).
-    * However, setting expand_mult to a non-zero value delays bucket expansion
-    * (that would be triggered by additions to this particular bucket)
-    * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.
-    * (The multiplier is simply expand_mult+1). The whole idea of this
-    * multiplier is to reduce bucket expansions, since they are expensive, in
-    * situations where we know that a particular bucket tends to be overused.
-    * It is better to let its chain length grow to a longer yet-still-bounded
-    * value, than to do an O(n) bucket expansion too often.
-    */
-   unsigned expand_mult;
-
-} UT_hash_bucket;
-
-/* random signature used only to find hash tables in external analysis */
-#define HASH_SIGNATURE 0xa0111fe1
-#define HASH_BLOOM_SIGNATURE 0xb12220f2
-
-typedef struct UT_hash_table {
-   UT_hash_bucket *buckets;
-   unsigned num_buckets, log2_num_buckets;
-   unsigned num_items;
-   struct UT_hash_handle *tail; /* tail hh in app order, for fast append    */
-   ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */
-
-   /* in an ideal situation (all buckets used equally), no bucket would have
-    * more than ceil(#items/#buckets) items. that's the ideal chain length. */
-   unsigned ideal_chain_maxlen;
-
-   /* nonideal_items is the number of items in the hash whose chain position
-    * exceeds the ideal chain maxlen. these items pay the penalty for an uneven
-    * hash distribution; reaching them in a chain traversal takes >ideal steps */
-   unsigned nonideal_items;
-
-   /* ineffective expands occur when a bucket doubling was performed, but
-    * afterward, more than half the items in the hash had nonideal chain
-    * positions. If this happens on two consecutive expansions we inhibit any
-    * further expansion, as it's not helping; this happens when the hash
-    * function isn't a good fit for the key domain. When expansion is inhibited
-    * the hash will still work, albeit no longer in constant time. */
-   unsigned ineff_expands, noexpand;
-
-   uint32_t signature; /* used only to find hash tables in external analysis */
-#ifdef HASH_BLOOM
-   uint32_t bloom_sig; /* used only to test bloom exists in external analysis */
-   uint8_t *bloom_bv;
-   char bloom_nbits;
-#endif
-
-} UT_hash_table;
-
-typedef struct UT_hash_handle {
-   struct UT_hash_table *tbl;
-   void *prev;                       /* prev element in app order      */
-   void *next;                       /* next element in app order      */
-   struct UT_hash_handle *hh_prev;   /* previous hh in bucket order    */
-   struct UT_hash_handle *hh_next;   /* next hh in bucket order        */
-   void *key;                        /* ptr to enclosing struct's key  */
-   unsigned keylen;                  /* enclosing struct's key len     */
-   unsigned hashv;                   /* result of hash-fcn(key)        */
-} UT_hash_handle;
-
-#endif /* UTHASH_H */
diff --git a/resource/csdk/libcoap-4.1.1/utlist.h b/resource/csdk/libcoap-4.1.1/utlist.h
deleted file mode 100644 (file)
index 35fc9db..0000000
+++ /dev/null
@@ -1,490 +0,0 @@
-/*
-Copyright (c) 2007-2010, Troy D. Hanson   http://uthash.sourceforge.net
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright
-      notice, this list of conditions and the following disclaimer.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef UTLIST_H
-#define UTLIST_H
-
-#define UTLIST_VERSION 1.9.1
-
-/* 
- * This file contains macros to manipulate singly and doubly-linked lists.
- *
- * 1. LL_ macros:  singly-linked lists.
- * 2. DL_ macros:  doubly-linked lists.
- * 3. CDL_ macros: circular doubly-linked lists.
- *
- * To use singly-linked lists, your structure must have a "next" pointer.
- * To use doubly-linked lists, your structure must "prev" and "next" pointers.
- * Either way, the pointer to the head of the list must be initialized to NULL.
- * 
- * ----------------.EXAMPLE -------------------------
- * struct item {
- *      int id;
- *      struct item *prev, *next;
- * }
- *
- * struct item *list = NULL:
- *
- * int main() {
- *      struct item *item;
- *      ... allocate and populate item ...
- *      DL_APPEND(list, item);
- * }
- * --------------------------------------------------
- *
- * For doubly-linked lists, the append and delete macros are O(1)
- * For singly-linked lists, append and delete are O(n) but prepend is O(1)
- * The sort macro is O(n log(n)) for all types of single/double/circular lists.
- */
-
-/* These macros use decltype or the earlier __typeof GNU extension.
-   As decltype is only available in newer compilers (VS2010 or gcc 4.3+
-   when compiling c++ code), this code uses whatever method is needed
-   or, for VS2008 where neither is available, uses casting workarounds. */
-#ifdef _MSC_VER            /* MS compiler */
-#if _MSC_VER >= 1600 && __cplusplus  /* VS2010 and newer in C++ mode */
-#define LDECLTYPE(x) decltype(x)
-#else                     /* VS2008 or older (or VS2010 in C mode) */
-#define NO_DECLTYPE
-#define LDECLTYPE(x) char*
-#endif
-#else                      /* GNU, Sun and other compilers */
-#define LDECLTYPE(x) __typeof(x)
-#endif
-
-/* for VS2008 we use some workarounds to get around the lack of decltype,
- * namely, we always reassign our tmp variable to the list head if we need
- * to dereference its prev/next pointers, and save/restore the real head.*/
-#ifdef NO_DECLTYPE
-#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); }
-#define _NEXT(elt,list) ((char*)((list)->next))
-#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); }
-#define _PREV(elt,list) ((char*)((list)->prev))
-#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); }
-#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; }
-#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); }
-#else 
-#define _SV(elt,list)
-#define _NEXT(elt,list) ((elt)->next)
-#define _NEXTASGN(elt,list,to) ((elt)->next)=(to)
-#define _PREV(elt,list) ((elt)->prev)
-#define _PREVASGN(elt,list,to) ((elt)->prev)=(to)
-#define _RS(list)
-#define _CASTASGN(a,b) (a)=(b)
-#endif
-
-/******************************************************************************
- * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort    *
- * Unwieldy variable names used here to avoid shadowing passed-in variables.  *
- *****************************************************************************/
-#define LL_SORT(list, cmp)                                                                     \
-do {                                                                                           \
-  LDECLTYPE(list) _ls_p;                                                                       \
-  LDECLTYPE(list) _ls_q;                                                                       \
-  LDECLTYPE(list) _ls_e;                                                                       \
-  LDECLTYPE(list) _ls_tail;                                                                    \
-  LDECLTYPE(list) _ls_oldhead;                                                                 \
-  LDECLTYPE(list) _tmp;                                                                        \
-  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
-  if (list) {                                                                                  \
-    _ls_insize = 1;                                                                            \
-    _ls_looping = 1;                                                                           \
-    while (_ls_looping) {                                                                      \
-      _CASTASGN(_ls_p,list);                                                                   \
-      _CASTASGN(_ls_oldhead,list);                                                             \
-      list = NULL;                                                                             \
-      _ls_tail = NULL;                                                                         \
-      _ls_nmerges = 0;                                                                         \
-      while (_ls_p) {                                                                          \
-        _ls_nmerges++;                                                                         \
-        _ls_q = _ls_p;                                                                         \
-        _ls_psize = 0;                                                                         \
-        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
-          _ls_psize++;                                                                         \
-          _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list);                               \
-          if (!_ls_q) break;                                                                   \
-        }                                                                                      \
-        _ls_qsize = _ls_insize;                                                                \
-        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
-          if (_ls_psize == 0) {                                                                \
-            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
-          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
-            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
-          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
-            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
-          } else {                                                                             \
-            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
-          }                                                                                    \
-          if (_ls_tail) {                                                                      \
-            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
-          } else {                                                                             \
-            _CASTASGN(list,_ls_e);                                                             \
-          }                                                                                    \
-          _ls_tail = _ls_e;                                                                    \
-        }                                                                                      \
-        _ls_p = _ls_q;                                                                         \
-      }                                                                                        \
-      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list);                            \
-      if (_ls_nmerges <= 1) {                                                                  \
-        _ls_looping=0;                                                                         \
-      }                                                                                        \
-      _ls_insize *= 2;                                                                         \
-    }                                                                                          \
-  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
-} while (0)
-
-#define DL_SORT(list, cmp)                                                                     \
-do {                                                                                           \
-  LDECLTYPE(list) _ls_p;                                                                       \
-  LDECLTYPE(list) _ls_q;                                                                       \
-  LDECLTYPE(list) _ls_e;                                                                       \
-  LDECLTYPE(list) _ls_tail;                                                                    \
-  LDECLTYPE(list) _ls_oldhead;                                                                 \
-  LDECLTYPE(list) _tmp;                                                                        \
-  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
-  if (list) {                                                                                  \
-    _ls_insize = 1;                                                                            \
-    _ls_looping = 1;                                                                           \
-    while (_ls_looping) {                                                                      \
-      _CASTASGN(_ls_p,list);                                                                   \
-      _CASTASGN(_ls_oldhead,list);                                                             \
-      list = NULL;                                                                             \
-      _ls_tail = NULL;                                                                         \
-      _ls_nmerges = 0;                                                                         \
-      while (_ls_p) {                                                                          \
-        _ls_nmerges++;                                                                         \
-        _ls_q = _ls_p;                                                                         \
-        _ls_psize = 0;                                                                         \
-        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
-          _ls_psize++;                                                                         \
-          _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list);                               \
-          if (!_ls_q) break;                                                                   \
-        }                                                                                      \
-        _ls_qsize = _ls_insize;                                                                \
-        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
-          if (_ls_psize == 0) {                                                                \
-            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
-          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
-            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
-          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
-            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
-          } else {                                                                             \
-            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
-          }                                                                                    \
-          if (_ls_tail) {                                                                      \
-            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
-          } else {                                                                             \
-            _CASTASGN(list,_ls_e);                                                             \
-          }                                                                                    \
-          _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list);                          \
-          _ls_tail = _ls_e;                                                                    \
-        }                                                                                      \
-        _ls_p = _ls_q;                                                                         \
-      }                                                                                        \
-      _CASTASGN(list->prev, _ls_tail);                                                         \
-      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list);                            \
-      if (_ls_nmerges <= 1) {                                                                  \
-        _ls_looping=0;                                                                         \
-      }                                                                                        \
-      _ls_insize *= 2;                                                                         \
-    }                                                                                          \
-  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
-} while (0)
-
-#define CDL_SORT(list, cmp)                                                                    \
-do {                                                                                           \
-  LDECLTYPE(list) _ls_p;                                                                       \
-  LDECLTYPE(list) _ls_q;                                                                       \
-  LDECLTYPE(list) _ls_e;                                                                       \
-  LDECLTYPE(list) _ls_tail;                                                                    \
-  LDECLTYPE(list) _ls_oldhead;                                                                 \
-  LDECLTYPE(list) _tmp;                                                                        \
-  LDECLTYPE(list) _tmp2;                                                                       \
-  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
-  if (list) {                                                                                  \
-    _ls_insize = 1;                                                                            \
-    _ls_looping = 1;                                                                           \
-    while (_ls_looping) {                                                                      \
-      _CASTASGN(_ls_p,list);                                                                   \
-      _CASTASGN(_ls_oldhead,list);                                                             \
-      list = NULL;                                                                             \
-      _ls_tail = NULL;                                                                         \
-      _ls_nmerges = 0;                                                                         \
-      while (_ls_p) {                                                                          \
-        _ls_nmerges++;                                                                         \
-        _ls_q = _ls_p;                                                                         \
-        _ls_psize = 0;                                                                         \
-        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
-          _ls_psize++;                                                                         \
-          _SV(_ls_q,list);                                                                     \
-          if (_NEXT(_ls_q,list) == _ls_oldhead) {                                              \
-            _ls_q = NULL;                                                                      \
-          } else {                                                                             \
-            _ls_q = _NEXT(_ls_q,list);                                                         \
-          }                                                                                    \
-          _RS(list);                                                                           \
-          if (!_ls_q) break;                                                                   \
-        }                                                                                      \
-        _ls_qsize = _ls_insize;                                                                \
-        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
-          if (_ls_psize == 0) {                                                                \
-            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
-            if (_ls_q == _ls_oldhead) { _ls_q = NULL; }                                        \
-          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
-            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
-            if (_ls_p == _ls_oldhead) { _ls_p = NULL; }                                        \
-          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
-            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
-            if (_ls_p == _ls_oldhead) { _ls_p = NULL; }                                        \
-          } else {                                                                             \
-            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
-            if (_ls_q == _ls_oldhead) { _ls_q = NULL; }                                        \
-          }                                                                                    \
-          if (_ls_tail) {                                                                      \
-            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
-          } else {                                                                             \
-            _CASTASGN(list,_ls_e);                                                             \
-          }                                                                                    \
-          _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list);                          \
-          _ls_tail = _ls_e;                                                                    \
-        }                                                                                      \
-        _ls_p = _ls_q;                                                                         \
-      }                                                                                        \
-      _CASTASGN(list->prev,_ls_tail);                                                          \
-      _CASTASGN(_tmp2,list);                                                                   \
-      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list);                           \
-      if (_ls_nmerges <= 1) {                                                                  \
-        _ls_looping=0;                                                                         \
-      }                                                                                        \
-      _ls_insize *= 2;                                                                         \
-    }                                                                                          \
-  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
-} while (0)
-
-/******************************************************************************
- * singly linked list macros (non-circular)                                   *
- *****************************************************************************/
-#define LL_PREPEND(head,add)                                                                   \
-do {                                                                                           \
-  (add)->next = head;                                                                          \
-  head = add;                                                                                  \
-} while (0)
-
-#define LL_APPEND(head,add)                                                                    \
-do {                                                                                           \
-  LDECLTYPE(head) _tmp;                                                                        \
-  (add)->next=NULL;                                                                            \
-  if (head) {                                                                                  \
-    _tmp = head;                                                                               \
-    while (_tmp->next) { _tmp = _tmp->next; }                                                  \
-    _tmp->next=(add);                                                                          \
-  } else {                                                                                     \
-    (head)=(add);                                                                              \
-  }                                                                                            \
-} while (0)
-
-#define LL_DELETE(head,del)                                                                    \
-do {                                                                                           \
-  LDECLTYPE(head) _tmp;                                                                        \
-  if ((head) == (del)) {                                                                       \
-    (head)=(head)->next;                                                                       \
-  } else {                                                                                     \
-    _tmp = head;                                                                               \
-    while (_tmp->next && (_tmp->next != (del))) {                                              \
-      _tmp = _tmp->next;                                                                       \
-    }                                                                                          \
-    if (_tmp->next) {                                                                          \
-      _tmp->next = ((del)->next);                                                              \
-    }                                                                                          \
-  }                                                                                            \
-} while (0)
-
-/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */
-#define LL_APPEND_VS2008(head,add)                                                             \
-do {                                                                                           \
-  if (head) {                                                                                  \
-    (add)->next = head;     /* use add->next as a temp variable */                             \
-    while ((add)->next->next) { (add)->next = (add)->next->next; }                             \
-    (add)->next->next=(add);                                                                   \
-  } else {                                                                                     \
-    (head)=(add);                                                                              \
-  }                                                                                            \
-  (add)->next=NULL;                                                                            \
-} while (0)
-
-#define LL_DELETE_VS2008(head,del)                                                             \
-do {                                                                                           \
-  if ((head) == (del)) {                                                                       \
-    (head)=(head)->next;                                                                       \
-  } else {                                                                                     \
-    char *_tmp = (char*)(head);                                                                \
-    while (head->next && (head->next != (del))) {                                              \
-      head = head->next;                                                                       \
-    }                                                                                          \
-    if (head->next) {                                                                          \
-      head->next = ((del)->next);                                                              \
-    }                                                                                          \
-    {                                                                                          \
-      char **_head_alias = (char**)&(head);                                                    \
-      *_head_alias = _tmp;                                                                     \
-    }                                                                                          \
-  }                                                                                            \
-} while (0)
-#ifdef NO_DECLTYPE
-#undef LL_APPEND
-#define LL_APPEND LL_APPEND_VS2008
-#undef LL_DELETE
-#define LL_DELETE LL_DELETE_VS2008
-#endif
-/* end VS2008 replacements */
-
-#define LL_FOREACH(head,el)                                                                    \
-    for(el=head;el;el=el->next)
-
-#define LL_FOREACH_SAFE(head,el,tmp)                                                           \
-  for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp)
-
-#define LL_SEARCH_SCALAR(head,out,field,val)                                                   \
-do {                                                                                           \
-    LL_FOREACH(head,out) {                                                                     \
-      if ((out)->field == (val)) break;                                                        \
-    }                                                                                          \
-} while(0) 
-
-#define LL_SEARCH(head,out,elt,cmp)                                                            \
-do {                                                                                           \
-    LL_FOREACH(head,out) {                                                                     \
-      if ((cmp(out,elt))==0) break;                                                            \
-    }                                                                                          \
-} while(0) 
-
-/******************************************************************************
- * doubly linked list macros (non-circular)                                   *
- *****************************************************************************/
-#define DL_PREPEND(head,add)                                                                   \
-do {                                                                                           \
- (add)->next = head;                                                                           \
- if (head) {                                                                                   \
-   (add)->prev = (head)->prev;                                                                 \
-   (head)->prev = (add);                                                                       \
- } else {                                                                                      \
-   (add)->prev = (add);                                                                        \
- }                                                                                             \
- (head) = (add);                                                                               \
-} while (0)
-
-#define DL_APPEND(head,add)                                                                    \
-do {                                                                                           \
-  if (head) {                                                                                  \
-      (add)->prev = (head)->prev;                                                              \
-      (head)->prev->next = (add);                                                              \
-      (head)->prev = (add);                                                                    \
-      (add)->next = NULL;                                                                      \
-  } else {                                                                                     \
-      (head)=(add);                                                                            \
-      (head)->prev = (head);                                                                   \
-      (head)->next = NULL;                                                                     \
-  }                                                                                            \
-} while (0);
-
-#define DL_DELETE(head,del)                                                                    \
-do {                                                                                           \
-  if ((del)->prev == (del)) {                                                                  \
-      (head)=NULL;                                                                             \
-  } else if ((del)==(head)) {                                                                  \
-      (del)->next->prev = (del)->prev;                                                         \
-      (head) = (del)->next;                                                                    \
-  } else {                                                                                     \
-      (del)->prev->next = (del)->next;                                                         \
-      if ((del)->next) {                                                                       \
-          (del)->next->prev = (del)->prev;                                                     \
-      } else {                                                                                 \
-          (head)->prev = (del)->prev;                                                          \
-      }                                                                                        \
-  }                                                                                            \
-} while (0);
-
-
-#define DL_FOREACH(head,el)                                                                    \
-    for(el=head;el;el=el->next)
-
-/* this version is safe for deleting the elements during iteration */
-#define DL_FOREACH_SAFE(head,el,tmp)                                                           \
-  for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp)
-
-/* these are identical to their singly-linked list counterparts */
-#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR
-#define DL_SEARCH LL_SEARCH
-
-/******************************************************************************
- * circular doubly linked list macros                                         *
- *****************************************************************************/
-#define CDL_PREPEND(head,add)                                                                  \
-do {                                                                                           \
- if (head) {                                                                                   \
-   (add)->prev = (head)->prev;                                                                 \
-   (add)->next = (head);                                                                       \
-   (head)->prev = (add);                                                                       \
-   (add)->prev->next = (add);                                                                  \
- } else {                                                                                      \
-   (add)->prev = (add);                                                                        \
-   (add)->next = (add);                                                                        \
- }                                                                                             \
-(head)=(add);                                                                                  \
-} while (0)
-
-#define CDL_DELETE(head,del)                                                                   \
-do {                                                                                           \
-  if ( ((head)==(del)) && ((head)->next == (head))) {                                          \
-      (head) = 0L;                                                                             \
-  } else {                                                                                     \
-     (del)->next->prev = (del)->prev;                                                          \
-     (del)->prev->next = (del)->next;                                                          \
-     if ((del) == (head)) (head)=(del)->next;                                                  \
-  }                                                                                            \
-} while (0);
-
-#define CDL_FOREACH(head,el)                                                                   \
-    for(el=head;el;el=(el->next==head ? 0L : el->next)) 
-
-#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2)                                                    \
-  for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL);                                        \
-      (el) && ((tmp2)=(el)->next, 1);                                                          \
-      ((el) = (((el)==(tmp1)) ? 0L : (tmp2))))
-
-#define CDL_SEARCH_SCALAR(head,out,field,val)                                                  \
-do {                                                                                           \
-    CDL_FOREACH(head,out) {                                                                    \
-      if ((out)->field == (val)) break;                                                        \
-    }                                                                                          \
-} while(0) 
-
-#define CDL_SEARCH(head,out,elt,cmp)                                                           \
-do {                                                                                           \
-    CDL_FOREACH(head,out) {                                                                    \
-      if ((cmp(out,elt))==0) break;                                                            \
-    }                                                                                          \
-} while(0) 
-
-#endif /* UTLIST_H */
-
diff --git a/resource/csdk/logger/makefile b/resource/csdk/logger/makefile
deleted file mode 100644 (file)
index a266fd2..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=release`
-# default to release build
-BUILD := release
-PLATFORM := linux
-
-ROOT_DIR = ..
-
-# You must create the file "local.properties" on your local machine which contains any local paths, etc
-# local_settings.mk should NOT be committed to repo
-include $(ROOT_DIR)/local.properties
-# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties
-#  Example:
-#  GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
-
-# NOTE:  to run app, make sure that LD_LIBRARY_PATH env variable
-#        contains $(GTEST_DIR)/lib/.libs
-                                
-CC := gcc
-CXX    := g++
-
-PROG := loggertest
-
-SRC_DIR := ./src
-TEST_DIR:= ./test
-INC_DIR := ./include
-
-CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -DTB_LOG
-CC_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c99 -fpic 
-CC_FLAGS := $(CC_FLAGS.$(BUILD))
-
-CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -DTB_LOG
-CXX_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c++0x -fpic 
-CXX_FLAGS := $(CXX_FLAGS.$(BUILD))
-
-INC    := -I$(SRC_DIR)  
-INC += -I$(TEST_DIR)
-INC += -I$(INC_DIR)
-INC += -I$(GTEST_DIR)/include
-
-
-# using make's computed variables to select object and bin folders
-# depending on the build type
-OBJ_DIR.debug := ./obj/debug
-OBJ_DIR.release := ./obj/release
-OBJ_DIR := $(OBJ_DIR.$(BUILD))
-
-BIN_DIR.debug := ./bin/debug
-BIN_DIR.release := ./bin/release
-BIN_DIR := $(BIN_DIR.$(BUILD))
-
-C_FILES := $(wildcard $(SRC_DIR)/*.c)
-#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp)
-CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp)
-OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o)))
-H_FILES := $(wildcard $(TEST_DIR)/*.h)
-H_FILES += $(wildcard $(INC_DIR)/*.h)
-LD_FLAGS := -L/usr/lib
-LD_FLAGS += -L$(GTEST_DIR)/lib/.libs
-
-
-LIBS := -lpthread
-LIBS += -lgtest
-LIBS += -lgtest_main
-
-
-all: $(PROG)
-       
-$(PROG): $(OBJ_FILES)  
-       $(CXX) -o $@ $^ $(LD_FLAGS) $(LIBS)     
-       mv ./$(PROG) ./$(BIN_DIR)
-
-#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(SRC_DIR)/%.h $(H_FILES)
-#      $(CC) $(CC_FLAGS) $(INC) -c -o $@ $<
-
-$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES)
-       $(CC) $(CC_FLAGS) $(INC) -c -o $@ $<
-
-$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES)
-       $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $<
-
-       
-.PHONY: clean
-clean :
-       rm -rf ./obj/debug/*
-       rm -rf ./obj/release/*
-       rm -rf ./lib/debug/*
-       rm -rf ./lib/release/*
-       rm -rf ./bin/debug/*
-       rm -rf ./bin/release/*
-       rm -rf ./test/tst_*.txt
-
-
-.PHONY: print_vars
-
-print_vars:
-       @echo ""
-       @echo 'BUILD     = '$(value BUILD)
-       @echo 'INC       = '$(value INC)
-       @echo 'CPP_FILES = '$(value CPP_FILES)
-       @echo 'LIBS      = '$(value LIBS)
-       
-
index ad9afd2..b642464 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1b, Real-time extensions
+// (IEEE Std 1003.1b-1993) specification
+//
+// For this specific file, see use of clock_gettime,
+// Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
+// and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif
+
+// Platform check can be extended to check and/or define more, or could be
+// moved into a config.h
+#if !defined(__ARDUINO__) && !defined(ARDUINO)
+#define HAVE_UNISTD_H 1
+#endif
+
+// Pull in _POSIX_TIMERS feature test macro to check for
+// clock_gettime() support.
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+
+// if we have unistd.h, we're a Unix system
+#include <time.h>
+#include <sys/time.h>
+#endif
 
 #include "logger.h"
 #include "string.h"
@@ -33,7 +60,7 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;  // Show 16 bytes, 2
 // Convert LogLevel to platform-specific severity level.  Store in PROGMEM on Arduino
 #ifdef __ANDROID__
     static android_LogPriority LEVEL[] = {ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
-#elif defined __linux__
+#elif defined(__linux__) || defined(__APPLE__)
     static const char * LEVEL[] __attribute__ ((unused)) = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
 #elif defined ARDUINO
     #include <stdarg.h>
@@ -70,7 +97,7 @@ void OCLogInit() {
 }
 
 void OCLogShutdown() {
-#ifdef __linux__
+#if defined(__linux__) || defined(__APPLE__)
     if (logCtx && logCtx->destroy)
     {
         logCtx->destroy(logCtx);
@@ -99,6 +126,34 @@ void OCLogv(LogLevel level, const char * tag, const char * format, ...) {
     OCLog(level, tag, buffer);
 }
 
+static void osalGetTime(int *min,int *sec, int *ms)
+{
+    if (min && sec && ms)
+    {
+#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
+        struct timespec when = {};
+        clockid_t clk = CLOCK_REALTIME;
+#ifdef CLOCK_REALTIME_COARSE
+        clk = CLOCK_REALTIME_COARSE;
+#endif
+        if (!clock_gettime(clk, &when))
+        {
+            *min = (when.tv_sec / 60) % 60;
+            *sec = when.tv_sec % 60;
+            *ms = when.tv_nsec / 1000000;
+        }
+#else
+        struct timeval now;
+        if (!gettimeofday(&now, NULL))
+        {
+            *min = (now.tv_sec / 60) % 60;
+            *sec = now.tv_sec % 60;
+            *ms = now.tv_usec * 1000;
+        }
+#endif
+    }
+}
+
 /**
  * Output a log string with the specified priority level.
  * Only defined for Linux and Android
@@ -112,19 +167,24 @@ void OCLog(LogLevel level, const char * tag, const char * logStr) {
         return;
     }
 
-    #ifdef __ANDROID__
-        __android_log_write(LEVEL[level], tag, logStr);
-    #elif defined __linux__
-        if (logCtx && logCtx->write_level)
-        {
-            logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
+#ifdef __ANDROID__
+    __android_log_write(LEVEL[level], tag, logStr);
+#elif defined(__linux__) || defined(__APPLE__)
+    if (logCtx && logCtx->write_level)
+    {
+        logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
+    }
+    else
+    {
 
-        }
-        else
-        {
-            printf("%s: %s: %s\n", LEVEL[level], tag, logStr);
-        }
-    #endif
+        int min = 0;
+        int sec = 0;
+        int ms = 0;
+        osalGetTime(&min,&sec,&ms);
+
+        printf("%02d:%02d.%03d %s: %s: %s\n", min, sec, ms, LEVEL[level], tag, logStr);
+    }
+#endif
 }
 
 /**
@@ -350,3 +410,4 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
 #endif
 
 
+
diff --git a/resource/csdk/makefile b/resource/csdk/makefile
deleted file mode 100644 (file)
index ca77f30..0000000
+++ /dev/null
@@ -1,206 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
-# default to release build
-# default to build for linux
-BUILD   := release
-PLATFORM := linux
-
-# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
-ARDUINOWIFI := 0
-
-ifeq ($(ROOT_DIR), )
-ROOT_DIR       = ./
-endif
-
-PLATFORM_TYPE = linux
-
-ifeq ($(PLATFORM),linux)
-    CXX=g++
-    CC=gcc
-    AR=ar
-    RANLIB=ranlib
-    CFLAGS_PLATFORM = -DWITH_POSIX -std=c99
-    PLATFORM_TYPE=linux
-else ifeq ($(PLATFORM),arduinomega)
-    include local.properties
-    include $(PLATFORM).properties
-    CC=$(ARDUINO_TOOLS_DIR)/avr-g++
-    ifeq ($(wildcard $(ARDUINO_DIR)/libraries/Time/Time/),)
-        $(error Arduino Time library needs to be moved from <ARDUINO_DIR>/libraries/Time \
-        to <ARDUINO_DIR>/libraries/Time/Time. You may need to create \
-        <ARDUINO_DIR>/libraries/Time/Time directory. Please refer to the wiki or readme \
-        for more information)
-    endif
-    PLATFORM_TYPE=arduino
-else ifeq ($(PLATFORM),arduinodue)
-    include local.properties
-    include $(PLATFORM).properties
-    CC=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-g++
-    PLATFORM_TYPE=arduino
-else
-    $(error Wrong value for PLATFORM !!)
-endif
-
-ifeq ($(PLATFORM_TYPE),arduino)
-    ifeq ($(ARDUINOWIFI),0)
-    ARDUINO_SHIELD_TYPE := "/ethernet_shield"
-    else ifeq ($(ARDUINOWIFI), 1)
-    ARDUINO_SHIELD_TYPE := "/wifi_shield"
-    endif
-    PLATFORM_SPECIFIC_BACKOUT:= ../../../../
-else
-    PLATFORM_SPECIFIC_BACKOUT := ../../../
-endif
-
-ifeq ($(OUT_DIR), )
-OUT_DIR        = $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
-endif
-
-ifeq ($(OBJ_DIR), )
-OBJ_DIR        = $(OUT_DIR)/obj
-endif
-
-OCLOGGER_DIR   = logger
-OC_LOG_DIR      = ../oc_logger
-OCRANDOM_DIR   = ocrandom
-OCSOCKET_DIR   = ocsocket
-LCOAP_DIR      = libcoap-4.1.1
-OCCOAP_DIR     = occoap
-OCTBSTACK_DIR  = stack
-OCMALLOC_DIR   = ocmalloc
-EXTLIBS_DIR    = ../../extlibs
-CJSON_DIR      = $(EXTLIBS_DIR)/cjson
-TINYDTLS_DIR   = $(EXTLIBS_DIR)/tinydtls
-
-OCCOAP_SRC     = $(OCCOAP_DIR)/src
-OCTBSTACK_SRC  = $(OCTBSTACK_DIR)/src
-OCMALLOC_SRC   = $(OCMALLOC_DIR)/src
-CJSON_SRC      = $(CJSON_DIR)
-
-OCLOGGER_INC   = $(OCLOGGER_DIR)/include
-OC_LOG_INC     = $(OC_LOG_DIR)/include
-OCRANDOM_INC   = $(OCRANDOM_DIR)/include
-OCSOCKET_INC   = $(OCSOCKET_DIR)/include
-LCOAP_INC      = $(LCOAP_DIR)
-OCCOAP_INC     = $(OCCOAP_DIR)/include
-OCTBSTACK_INC  = $(OCTBSTACK_DIR)/include
-OCMALLOC_INC   = $(OCMALLOC_DIR)/include
-CJSON_INC      = $(CJSON_DIR)
-
-INC_DIRS       := -I$(OCLOGGER_INC)
-INC_DIRS       += -I$(OC_LOG_INC)
-INC_DIRS       += -I$(OCRANDOM_INC)
-INC_DIRS       += -I$(OCSOCKET_INC)
-INC_DIRS       += -I$(LCOAP_INC)
-INC_DIRS       += -I$(OCCOAP_INC)
-INC_DIRS       += -I$(OCMALLOC_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)/internal
-INC_DIRS       += -I$(CJSON_INC)
-
-CC_FLAGS.debug         := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic -DTB_LOG
-CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
-
-CFLAGS         += $(CC_FLAGS.$(BUILD)) $(INC_DIRS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM)
-LDLIBS         += -lcoap
-
-CJSON_SOURCES          := $(CJSON_SRC)/cJSON.c
-
-OCCOAP_SOURCES         := $(OCCOAP_SRC)/occoap.c
-OCCOAP_SOURCES         += $(OCCOAP_SRC)/occoaphelper.c
-
-OCTBSTACK_SOURCES      := $(OCTBSTACK_SRC)/ocstack.c
-OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/occlientcb.c
-OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/ocresource.c
-OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/ocobserve.c
-OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/ocserverrequest.c
-OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/occollection.c
-OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/oicgroup.c
-OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/ocsecurity.c
-
-SOURCES                        := $(CJSON_SOURCES)
-SOURCES                        += $(OCCOAP_SOURCES)
-SOURCES                        += $(OCTBSTACK_SOURCES)
-
-all:   make_lcoap objdirs obj_build liboctbstack.a
-
-buildScript_all: objdirs obj_build liboctbstack.a
-
-make_lcoap:
-       $(MAKE) -C $(LCOAP_DIR) "BUILD=$(BUILD)" "PLATFORM=$(PLATFORM)" "ARDUINOWIFI=$(ARDUINOWIFI)"
-
-objdirs:
-       mkdir -p $(PLATFORM)
-       mkdir -p $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
-       mkdir -p $(OUT_DIR)
-       mkdir -p $(OBJ_DIR)
-
-obj_build:
-       @echo "Building $@"
-       # Output all *.o files to $(OUT_DIR)/$(BUILD)/$(OBJ_DIR)
-       $(foreach source,$(SOURCES), $(CC) $(CFLAGS) $(source) -o $(patsubst %.c, %.o, $(patsubst %, $(OBJ_DIR)/%, $(notdir $(source))));)
-
-liboctbstack.a: obj_build
-       @echo "Building $@"
-       # Unpackage libcoap.a to $(OBJ_DIR)/$(BUILD). The output objects from OCStack and OCCoap are already at this location
-       @cd $(OBJ_DIR) && $(AR) -x $(PLATFORM_SPECIFIC_BACKOUT)$(LCOAP_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/libcoap.a
-       # Repackage all the objects at this location into a single archive. This is OCStack, OCCoap, and LibCoap (LibCoap contains OCRandom, OCLogger, and OCSocket.).
-       $(AR) -r $(OUT_DIR)/$@ $(OBJ_DIR)/*.o
-
-    ifeq ($(PLATFORM),linux)
-     ifneq ($(wildcard $(TINYDTLS_DIR)/libtinydtls.a),)
-                       $(info "Building liboctbstack with DTLS support")
-                       mkdir -p $(OBJ_DIR)/tinydtls
-                       @cd $(OBJ_DIR)/tinydtls && $(AR) -x ../$(PLATFORM_SPECIFIC_BACKOUT)$(TINYDTLS_DIR)/libtinydtls.a
-                       $(AR) -q $(OUT_DIR)/$@ $(OBJ_DIR)/tinydtls/*.o
-     endif
-    endif
-
-.PHONY: clean print_vars
-
-clean: legacy_clean
-       -rm -rf linux
-       -rm -rf arduinomega
-       -rm -rf arduinodue
-
-deepclean: legacy_deepclean
-       -rm -rf linux
-       -rm -rf arduinomega
-       -rm -rf arduinodue
-
-legacy_clean:
-       @echo "Cleaning all."
-       rm -f $(OBJ_DIR)/$(BUILD)/*.o
-       rm -f $(ROOT_DIR)/$(BUILD)/liboctbstack.a
-       rm -rf $(OBJ_DIR)
-       rm -rf release
-       rm -rf debug
-
-legacy_deepclean:
-       @echo "Deep-Cleaning all."
-       rm -f $(OBJ_DIR)/$(BUILD)/*.o
-       rm -f $(ROOT_DIR)/liboctbstack.a
-       rm -rf $(OBJ_DIR)
-       $(MAKE) clean -C $(LCOAP_DIR)
-       rm -rf release
-       rm -rf debug
diff --git a/resource/csdk/occoap/README.txt b/resource/csdk/occoap/README.txt
deleted file mode 100644 (file)
index 20e7013..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-#==============================================================================
-# NOTICE - Transition to SCONS
-#==============================================================================
-
-The IoTivity build system is transitioning to SCONS. Although the 
-makefiles are still available (until v1.0) and some developers are 
-still using them, they are currently no longer supported. To learn more 
-about building using SCONS see Readme.scons.txt in the repository root 
-directory. The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
-#==============================================================================
-# Build instructions for Linux
-#==============================================================================
-
-In ./occoap directory
-clean ==> make clean
-build ==> make
-
-#==============================================================================
-# Unit test instructions for Linux
-#==============================================================================
-
-After building (make), run
-./occoap/bin/debug/occoaptest
-
-
diff --git a/resource/csdk/occoap/include/occoap.h b/resource/csdk/occoap/include/occoap.h
deleted file mode 100644 (file)
index 31ab9f0..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-//******************************************************************
-///
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef OCCOAP_H_
-#define OCCOAP_H_
-
-//-----------------------------------------------------------------------------
-// Includes
-//-----------------------------------------------------------------------------
-#include "ocstack.h"
-#include "occoaptoken.h"
-#include "ocstackinternal.h"
-#include "occoaphelper.h"
-#include <stdint.h>
-
-//-----------------------------------------------------------------------------
-// Function Prototypes
-//-----------------------------------------------------------------------------
-
-uint32_t GetTime(float afterSeconds);
-
-/**
- * Initialize the CoAP client or server with the its IPv4 address and CoAP port
- *
- * @param ipAddr
- *     IP Address of host device
- * @param port
- *     Port of host device
- * @param mode
- *     Host device is client, server, or client-server
- *
- * @return
- *   0   - success
- *   TBD - TBD error
- */
-OCStackResult OCInitCoAP(const char *address, uint16_t port, OCMode mode);
-
-/**
- * Discover OC resources
- *
- * @param method          - method to perform on the resource
- * @param qos             - CON or NON requests
- * @param token           - pointer to the token data structure
- * @param Uri             - URI of the resource to interact with
- * @param payload         - CoAP PDU payload
- * @param options         - The address of an array containing the vendor specific
- *                          header options to be sent with the request
- * @param numOptions      - The number of header options to be included
- * @return
- *   0   - success
- *   TBD - TBD error
- */
-OCStackResult OCDoCoAPResource(OCMethod method, OCQualityOfService qos, OCCoAPToken * token,
-        const char *Uri, const char *payload, OCHeaderOption * options, uint8_t numOptions);
-
-/**
- * Send a response to a request.
- *
- * @param response - pointer to OCServerProtocolResponse that contains all request and
- *                   response info necessary to send the response to the client
- * @return
- *     OC_STACK_OK               - No errors; Success
- *     OC_STACK_ERROR            - Error sending response
- */
-OCStackResult OCDoCoAPResponse(OCServerProtocolResponse *response);
-
-/**
- * Stop the CoAP client or server processing
- *
- * @return 0 - success, else - TBD error
- */
-OCStackResult OCStopCoAP();
-
-/**
- * Called in main loop of CoAP client or server.  Allows low-level CoAP processing of
- * send, receive, timeout, discovery, callbacks, etc.
- *
- * @return 0 - success, else - TBD error
- */
-OCStackResult OCProcessCoAP();
-
-/**
- * This method is called to generate a token of MAX_TOKEN_LENGTH.
- * This token is used to co-relate client requests with server responses.
- *
- */
-void OCGenerateCoAPToken(OCCoAPToken * token);
-
-/**
- * Retrieve the end-point info where resource is being hosted.
- * Currently, this method only provides the IP port with which the socket
- * is bound. This internal method may be extended in future to retrieve
- * more info (such as IP address, transport technology) about the hosting end-point.
- *
- * @param resPtr    - pointer to the resource
- * @param info      - pointer to 16-bit integer to hold port number
- * @return 0 - success, else - TBD error
- */
-OCStackResult OCGetResourceEndPointInfo (OCResource *resPtr, void *info);
-
-#endif /* OCCOAP_H_ */
diff --git a/resource/csdk/occoap/include/occoaphelper.h b/resource/csdk/occoap/include/occoaphelper.h
deleted file mode 100644 (file)
index 8e36776..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-
-#ifndef OCCOAPHELPER_H_
-#define OCCOAPHELPER_H_
-
-//-----------------------------------------------------------------------------
-// Includes
-//-----------------------------------------------------------------------------
-#ifndef WITH_ARDUINO
-#include <unistd.h>
-#endif
-#include <limits.h>
-#include <ctype.h>
-#include "coap.h"
-#include "ocstack.h"
-#include "occoaptoken.h"
-#include "ocstackinternal.h"
-
-/**
- * The Max Size of the buffer that is used to parse uri and query
- * individually.
- */
-#define MAX_URI_QUERY_BUF_SIZE ((MAX_URI_LENGTH) >= (MAX_QUERY_LENGTH) ?\
-                            (MAX_URI_LENGTH) : (MAX_QUERY_LENGTH))
-
-#define COAP_WK_IPAddr_0 (224)
-#define COAP_WK_IPAddr_1 (0)
-#define COAP_WK_IPAddr_2 (1)
-#define COAP_WK_IPAddr_3 (187)
-
-// checks if optionID is within vendor specific range
-OCStackResult isVendorSpecific(uint16_t optionID);
-
-// Convert OCStack code to CoAP code
-uint8_t OCToCoAPResponseCode(OCStackResult result);
-
-//Convert OCQualityOfService to coap NON vs CON
-uint8_t OCToCoAPQoS(OCQualityOfService qos, uint8_t * ipAddr);
-
-// Convert CoAP code to OCStack code
-OCStackResult CoAPToOCResponseCode(uint8_t coapCode);
-
-// Internal function to generate a coap pdu based on passed parameters
-coap_pdu_t *
-GenerateCoAPPdu(uint8_t msgType, uint8_t code, unsigned short id,
-        OCCoAPToken * token, unsigned char * payloadJSON,
-        coap_list_t *options);
-
-// Internal function to send a coap pdu, it also handles NON and CON
-OCStackResult
-SendCoAPPdu(coap_context_t * gCoAPCtx, coap_address_t* dst, coap_pdu_t * pdu,
-        coap_send_flags_t flag);
-
-// Call back function used by libcoap to order option in coap pdu
-int OrderOptions(void *a, void *b);
-
-// Internal function to create an option node for coap pdu
-coap_list_t *
-CreateNewOptionNode(unsigned short key, unsigned int length,
-        unsigned char *data);
-
-// Internal function to retrieve Uri and Query from received coap pdu
-OCStackResult ParseCoAPPdu(coap_pdu_t * pdu, unsigned char * uriBuf,
-        unsigned char * queryBuf, uint32_t * observeOption,
-        uint32_t * maxAgeOption,
-        uint8_t * numVendorSpecificHeaderOptions,
-        OCHeaderOption * vendorSpecificHeaderOptions,
-        coap_block_t * block1, coap_block_t * block2,
-        uint16_t * size1, uint16_t * size2,
-        unsigned char * payload);
-
-// Internal function to retrieve a Token from received coap pdu
-void RetrieveOCCoAPToken(const coap_pdu_t * pdu, OCCoAPToken * rcvdToken);
-
-// Internal function to create OCResponse struct at the client from a received coap pdu
-OCStackResult FormOCResponse(OCResponse * * responseLoc, ClientCB * cbNode,
-        uint8_t TTL, OCClientResponse * clientResponse);
-
-// Internal function to create OCClientResponse struct at the client from a received coap pdu
-OCStackResult FormOCClientResponse(OCClientResponse * clientResponse,
-        OCStackResult result, OCDevAddr * remote, uint32_t seqNum,
-        const unsigned char * resJSONPayload);
-
-// Internal function to handle the queued pdus in the send queue
-void HandleSendQueue(coap_context_t * gCoAPCtx);
-
-// Internal function to form the standard response option list
-OCStackResult FormOptionList(coap_list_t * * optListLoc, uint8_t * addMediaType,
-        uint32_t * addMaxAge, uint32_t * observeOptionPtr,
-        uint16_t * addPortNumber, uint8_t uriLength, unsigned char * uri,
-        uint8_t queryLength, unsigned char * query, OCHeaderOption * vendorSpecificHeaderOptions,
-        uint8_t numVendorSpecificHeaderOptions);
-
-// Internal function to retransmit a queue
-OCStackResult ReTXCoAPQueue(coap_context_t * ctx, coap_queue_t * queue);
-
-// Internal function called when sending/retransmission fails
-OCStackResult HandleFailedCommunication(coap_context_t * ctx, coap_queue_t * queue);
-#endif /* OCCOAPHELPER_H_ */
diff --git a/resource/csdk/occoap/include/occoaptoken.h b/resource/csdk/occoap/include/occoaptoken.h
deleted file mode 100644 (file)
index db171a7..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-
-#ifndef OCCOAPTOKEN_H_
-#define OCCOAPTOKEN_H_
-
-#include <stddef.h>
-
-#define MAX_TOKEN_LENGTH (8)
-
-typedef struct {
-    uint8_t token[MAX_TOKEN_LENGTH];
-    size_t tokenLength;
-} OCCoAPToken;
-
-#endif
diff --git a/resource/csdk/occoap/makefile b/resource/csdk/occoap/makefile
deleted file mode 100644 (file)
index a9f6cd4..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=release`
-# default to release build
-BUILD := release
-
-# You must create the file "local.properties" on your local machine which contains any local paths, etc
-# local_settings.mk should NOT be committed to repo
-include ./local.properties
-# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties
-#  Example:
-#  GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
-
-# NOTE:  to run app, make sure that LD_LIBRARY_PATH env variable
-#        contains $(GTEST_DIR)/lib/.libs
-                                
-CC := gcc
-CXX    := g++
-
-PROG := occoaptest
-
-#SRC_DIR := ./src
-TEST_DIR:= ./test
-#INC_DIR := ./include
-#LOG_DIR := ../logger
-#STACK_DIR := ../stack
-
-CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -DTB_LOG
-CC_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c99 -fpic 
-CC_FLAGS := $(CC_FLAGS.$(BUILD))
-
-CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -DTB_LOG
-CXX_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c++0x -fpic 
-CXX_FLAGS := $(CXX_FLAGS.$(BUILD))
-
-#INC   := -I$(SRC_DIR)  
-#INC += -I$(TEST_DIR)
-#INC += -I$(INC_DIR)
-#INC += -I$(LOG_DIR)/include
-#INC += -I$(STACK_DIR)/include
-INC += -I$(GTEST_DIR)/include
-
-
-# using make's computed variables to select object and bin folders
-# depending on the build type
-OBJ_DIR.debug := ./obj/debug
-OBJ_DIR.release := ./obj/release
-OBJ_DIR := $(OBJ_DIR.$(BUILD))
-
-BIN_DIR.debug := ./bin/debug
-BIN_DIR.release := ./bin/release
-BIN_DIR := $(BIN_DIR.$(BUILD))
-
-#C_FILES := $(wildcard $(LOG_DIR)/src/*.c)
-#C_FILES += $(wildcard $(SRC_DIR)/*.c)
-#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp)
-CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp)
-#CPP_FILES += $(wildcard $(LOG_DIR)/src/*.c)
-OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o)))
-H_FILES := $(wildcard $(TEST_DIR)/*.h)
-#H_FILES += $(wildcard $(INC_DIR)/*.h)
-#H_FILES += $(wildcard $(LOG_DIR)/include/*.h)
-LD_FLAGS := -L/usr/lib
-LD_FLAGS += -L$(GTEST_DIR)/lib/.libs
-
-
-LIBS := -lgtest
-LIBS += -lgtest_main
-LIBS += -lpthread
-
-
-all: $(PROG)
-       mkdir -p ./$(OBJ_DIR)
-       mkdir -p ./$(BIN_DIR)
-       
-$(PROG): $(OBJ_FILES)
-       $(CXX) -o $@ $^ $(LD_FLAGS) $(LIBS)     
-       mkdir -p ./$(BIN_DIR)
-       mv ./$(PROG) ./$(BIN_DIR)
-
-#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(SRC_DIR)/%.h $(H_FILES)
-#      $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $<
-
-#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(INC_DIR)/%.h $(H_FILES)
-#      $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $<
-
-$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES)
-       mkdir -p ./$(OBJ_DIR)
-       $(CC) $(CC_FLAGS) $(INC) -c -o $@ $<    
-               
-$(OBJ_DIR)/%.o: $(LOG_DIR)/src/%.c $(LOG_DIR)/include/%.h $(H_FILES)
-       mkdir -p ./$(OBJ_DIR)
-       $(CC) $(CC_FLAGS) $(INC) -c -o $@ $<    
-
-$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES)
-       mkdir -p ./$(OBJ_DIR)
-       $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $<  
-       
-.PHONY: clean
-clean :
-       rm -rf ./obj/debug/*
-       rm -rf ./obj/release/*
-       rm -rf ./lib/*
-       rm -rf ./bin/debug/*
-       rm -rf ./bin/release/*
-
-
-.PHONY: print_vars
-
-print_vars:
-       @echo ""
-       @echo 'BUILD     = '$(value BUILD)
-       @echo 'INC       = '$(value INC)
-       @echo 'CPP_FILES = '$(value CPP_FILES)
-       @echo 'C_FILES   = '$(value C_FILES)
-       @echo 'LIBS      = '$(value LIBS)
-       @echo 'OBJ_FILES = '$(value OBJ_FILES)
-       @echo 'SRC_DIR   = '$(value SRC_DIR)
-       
-       
-
diff --git a/resource/csdk/occoap/src/occoap.c b/resource/csdk/occoap/src/occoap.c
deleted file mode 100644 (file)
index 427ebf0..0000000
+++ /dev/null
@@ -1,964 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-//=============================================================================
-// Includes
-//=============================================================================
-#define _POSIX_C_SOURCE 200112L
-#include <string.h>
-#include "occoap.h"
-#include "ocstackconfig.h"
-#include "occlientcb.h"
-#include "ocobserve.h"
-#include "logger.h"
-#include "ocmalloc.h"
-#include <coap.h>
-
-#ifndef WITH_ARDUINO
-#include <unistd.h>
-#endif
-#include <limits.h>
-#include <ctype.h>
-
-//=============================================================================
-// Macros
-//=============================================================================
-#define TAG    PCF("OCCoAP")
-#define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
-            {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
-#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg); goto exit;} }
-
-//=============================================================================
-// Defines
-//=============================================================================
-#define COAP_BLOCK_FILL_VALUE   (0xFF)
-
-//=============================================================================
-// Private Variables
-//=============================================================================
-
-static coap_context_t *gCoAPCtx = NULL;
-
-//=============================================================================
-// Helper Functions
-//=============================================================================
-
-//generate a coap token
-void OCGenerateCoAPToken(OCCoAPToken * token)
-{
-    if (token)
-    {
-        token->tokenLength = MAX_TOKEN_LENGTH;
-        OCFillRandomMem((uint8_t*)token->token, token->tokenLength);
-    }
-}
-
-//This function is called back by libcoap when ack or rst are received
-static void HandleCoAPAckRst(struct coap_context_t * ctx, uint8_t msgType,
-        const coap_queue_t * sentQueue){
-
-    // silence warnings
-    (void) ctx;
-    coap_pdu_t * sentPdu = sentQueue->pdu;
-    OCStackResult result = OC_STACK_ERROR;
-    uint32_t observationOption = OC_OBSERVE_NO_OPTION;
-    // {{0}} to eliminate warning for known compiler bug 53119
-    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119
-    OCCoAPToken sentToken = {{0}};
-
-    result = ParseCoAPPdu(sentPdu, NULL, NULL, &observationOption, NULL, NULL, NULL,
-            NULL, NULL, NULL, NULL, NULL);
-    VERIFY_SUCCESS(result, OC_STACK_OK);
-
-    // fill OCCoAPToken structure
-    RetrieveOCCoAPToken(sentPdu, &sentToken);
-
-    if(msgType == COAP_MESSAGE_RST)
-    {
-        if(myStackMode != OC_CLIENT)
-        {
-            result = OCStackFeedBack(&sentToken, OC_OBSERVER_NOT_INTERESTED);
-            if(result == OC_STACK_OK)
-            {
-                OC_LOG_V(DEBUG, TAG,
-                        "Received RST, removing all queues associated with Token %d bytes",
-                        sentToken.tokenLength);
-                OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength);
-                coap_cancel_all_messages(ctx, &sentQueue->remote, sentToken.token,
-                        sentToken.tokenLength);
-            }
-        }
-    }
-    else if(observationOption != OC_OBSERVE_NO_OPTION && msgType == COAP_MESSAGE_ACK)
-    {
-        OC_LOG_V(DEBUG, TAG, "Received ACK, for Token %d bytes",sentToken.tokenLength);
-        OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength);
-        // now the observer is still interested
-        if(myStackMode != OC_CLIENT)
-        {
-            OCStackFeedBack(&sentToken, OC_OBSERVER_STILL_INTERESTED);
-        }
-    }
-exit:
-    return;
-}
-
-//This function is called back by libcoap when a request is received
-static void HandleCoAPRequests(struct coap_context_t *ctx,
-        const coap_queue_t * rcvdRequest)
-{
-    // silence warnings
-    (void) ctx;
-    OCServerProtocolRequest protocolRequest = {(OCMethod)0};
-    coap_block_t rcvdBlock1;
-    coap_block_t rcvdBlock2;
-    memset(&rcvdBlock1, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t));
-    memset(&rcvdBlock2, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t));
-    uint16_t rcvdSize1 = 0;
-    coap_pdu_t * rcvdPdu = rcvdRequest->pdu;
-    coap_pdu_t * sendPdu = NULL;
-    coap_send_flags_t sendFlag;
-    OCStackResult result = OC_STACK_ERROR;
-    OCStackResult requestResult = OC_STACK_ERROR;
-
-    if(myStackMode == OC_CLIENT)
-    {
-        //TODO: should the client be responding to requests?
-        return;
-    }
-
-    protocolRequest.observationOption = OC_OBSERVE_NO_OPTION;
-    protocolRequest.qos = (rcvdPdu->hdr->type == COAP_MESSAGE_CON) ?
-            OC_HIGH_QOS : OC_LOW_QOS;
-    protocolRequest.coapID = rcvdPdu->hdr->id;
-    protocolRequest.delayedResNeeded = rcvdRequest->delayedResNeeded;
-    protocolRequest.secured = rcvdRequest->secure;
-
-    // fill OCCoAPToken structure
-    RetrieveOCCoAPToken(rcvdPdu, &protocolRequest.requestToken);
-    OC_LOG_V(INFO, TAG, " Token received %d bytes",
-            protocolRequest.requestToken.tokenLength);
-    OC_LOG_BUFFER(INFO, TAG, protocolRequest.requestToken.token,
-            protocolRequest.requestToken.tokenLength);
-
-    // fill OCDevAddr
-    memcpy(&protocolRequest.requesterAddr, (OCDevAddr *) &rcvdRequest->remote,
-            sizeof(OCDevAddr));
-
-    // Retrieve Uri and Query from received coap pdu
-    result =  ParseCoAPPdu(rcvdPdu, protocolRequest.resourceUrl,
-            protocolRequest.query,
-            &(protocolRequest.observationOption), NULL,
-            &(protocolRequest.numRcvdVendorSpecificHeaderOptions),
-            protocolRequest.rcvdVendorSpecificHeaderOptions,
-            &rcvdBlock1, &rcvdBlock2, &rcvdSize1, NULL,
-            protocolRequest.reqJSONPayload);
-    VERIFY_SUCCESS(result, OC_STACK_OK);
-
-    switch (rcvdPdu->hdr->code)
-    {
-        case COAP_REQUEST_GET:
-        {
-            protocolRequest.method = OC_REST_GET;
-            break;
-        }
-        case COAP_REQUEST_POST:
-        {
-            protocolRequest.method = OC_REST_POST;
-            break;
-        }
-        case COAP_REQUEST_DELETE:
-        {
-            protocolRequest.method = OC_REST_DELETE;
-            break;
-        }
-        case COAP_REQUEST_PUT:
-        {
-            protocolRequest.method = OC_REST_PUT;
-            break;
-        }
-        default:
-        {
-            OC_LOG_V(ERROR, TAG, "Received CoAP method %d not supported",
-                    rcvdPdu->hdr->code);
-            goto exit;
-        }
-    }
-
-    if(rcvdBlock1.szx != 7)
-    {
-        protocolRequest.reqPacketSize = 1 << (rcvdBlock1.szx + 4);
-        protocolRequest.reqMorePacket = rcvdBlock1.m;
-        protocolRequest.reqPacketNum  = rcvdBlock1.num;
-    }
-    else
-    {
-        // No block1 received
-        rcvdSize1 = strlen((const char *)protocolRequest.reqJSONPayload)+1;
-        protocolRequest.reqTotalSize = rcvdSize1;
-    }
-
-    if(rcvdBlock2.szx != 7)
-    {
-        protocolRequest.resPacketSize = 1 << (rcvdBlock2.szx + 4);
-        protocolRequest.resPacketNum  = rcvdBlock2.num;
-    }
-
-    requestResult = HandleStackRequests(&protocolRequest);
-
-    if(requestResult == OC_STACK_VIRTUAL_DO_NOT_HANDLE ||
-            requestResult == OC_STACK_OK ||
-            requestResult == OC_STACK_RESOURCE_CREATED ||
-            requestResult == OC_STACK_RESOURCE_DELETED ||
-            requestResult == OC_STACK_INVALID_DEVICE_INFO)
-    {
-        goto exit;
-    }
-    else if(requestResult == OC_STACK_NO_MEMORY ||
-            requestResult == OC_STACK_ERROR ||
-            requestResult == OC_STACK_NOTIMPL ||
-            requestResult == OC_STACK_NO_RESOURCE ||
-            requestResult == OC_STACK_RESOURCE_ERROR)
-    {
-        // TODO: should we send an error also when we receive a non-secured request to a secure resource?
-        // TODO: should we consider some sort of error response
-        OC_LOG(DEBUG, TAG, PCF("We should send some sort of error message"));
-        // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
-        sendPdu = GenerateCoAPPdu((rcvdPdu->hdr->type == COAP_MESSAGE_CON)? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
-                OCToCoAPResponseCode(requestResult), rcvdPdu->hdr->id,
-                &protocolRequest.requestToken, NULL, NULL);
-        VERIFY_NON_NULL(sendPdu);
-        coap_show_pdu(sendPdu);
-        sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0);
-        if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu,
-                sendFlag)
-                != OC_STACK_OK){
-            OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
-        }
-        goto exit;
-    }
-    else if(requestResult == OC_STACK_SLOW_RESOURCE)
-    {
-        if(rcvdPdu->hdr->type == COAP_MESSAGE_CON)
-        {
-            // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
-            sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0, rcvdPdu->hdr->id,
-                    NULL, NULL, NULL);
-            VERIFY_NON_NULL(sendPdu);
-            coap_show_pdu(sendPdu);
-
-            sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0);
-            if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu,
-                    sendFlag)
-                    != OC_STACK_OK){
-                OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
-            }
-        }
-        else
-        {
-            goto exit;
-        }
-    }
-exit:
-    return;
-}
-
-uint32_t GetTime(float afterSeconds)
-{
-    coap_tick_t now;
-    coap_ticks(&now);
-    return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
-}
-
-//This function is called back by libcoap when a response is received
-static void HandleCoAPResponses(struct coap_context_t *ctx,
-        const coap_queue_t * rcvdResponse) {
-    OCResponse * response = NULL;
-    OCCoAPToken rcvdToken;
-    OCClientResponse clientResponse = {0};
-    ClientCB * cbNode = NULL;
-    unsigned char bufRes[MAX_RESPONSE_LENGTH] = {0};
-    uint32_t sequenceNumber = OC_OBSERVE_NO_OPTION;
-    uint32_t maxAge = 0;
-    OCStackResult result = OC_STACK_ERROR;
-    coap_pdu_t * sendPdu = NULL;
-    coap_pdu_t * recvPdu = NULL;
-    unsigned char rcvdUri[MAX_URI_LENGTH] = { 0 };
-    uint8_t isObserveNotification = 0;
-    #ifdef WITH_PRESENCE
-    char * resourceTypeName = NULL;
-    uint8_t remoteIpAddr[4];
-    uint16_t remotePortNu;
-    unsigned char fullUri[MAX_URI_LENGTH] = { 0 };
-    uint8_t isPresenceNotification = 0;
-    uint8_t isMulticastPresence = 0;
-    uint32_t lowerBound;
-    uint32_t higherBound;
-    char * tok = NULL;
-    #endif
-    coap_block_t rcvdBlock1 = {COAP_BLOCK_FILL_VALUE};
-    coap_block_t rcvdBlock2 = {COAP_BLOCK_FILL_VALUE};
-    uint16_t rcvdSize2 = 0;
-
-    VERIFY_NON_NULL(ctx);
-    VERIFY_NON_NULL(rcvdResponse);
-    recvPdu = rcvdResponse->pdu;
-
-    result = ParseCoAPPdu(recvPdu, rcvdUri, NULL, &sequenceNumber, &maxAge,
-            &clientResponse.numRcvdVendorSpecificHeaderOptions,
-            clientResponse.rcvdVendorSpecificHeaderOptions,
-            &rcvdBlock1, &rcvdBlock2, NULL, &rcvdSize2, bufRes);
-
-    VERIFY_SUCCESS(result, OC_STACK_OK);
-
-    OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u", sequenceNumber);
-    OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", maxAge);
-    OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
-
-    if(sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
-    {
-        isObserveNotification = 1;
-        OC_LOG(INFO, TAG, PCF("Received an observe notification"));
-    }
-
-    #ifdef WITH_PRESENCE
-    if(!strcmp((char *)rcvdUri, (char *)OC_PRESENCE_URI)){
-        char* tokSavePtr;
-
-        isPresenceNotification = 1;
-        OC_LOG(INFO, TAG, PCF("Received a presence notification"));
-        tok = strtok_r((char *)bufRes, "[:]}", &tokSavePtr);
-        bufRes[strlen((char *)bufRes)] = ':';
-        tok = strtok_r(NULL, "[:]}", &tokSavePtr);
-        bufRes[strlen((char *)bufRes)] = ':';
-        VERIFY_NON_NULL(tok);
-        sequenceNumber = (uint32_t )atol(tok);
-        OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", sequenceNumber);
-        tok = strtok_r(NULL, "[:]}", &tokSavePtr);
-        VERIFY_NON_NULL(tok);
-        maxAge = (uint32_t )atol(tok);
-        OC_LOG_V(DEBUG, TAG, "The received TTL is %u", maxAge);
-        tok = strtok_r(NULL, "[:]}", &tokSavePtr);
-        if(tok) {
-            bufRes[strlen((char *)bufRes)] = ':';
-            resourceTypeName = (char *)OCMalloc(strlen(tok));
-            if(!resourceTypeName)
-            {
-                goto exit;
-            }
-            strcpy(resourceTypeName, tok);
-            OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
-                    resourceTypeName);
-        }
-        bufRes[strlen((char *)bufRes)] = ']';
-    }
-    #endif
-
-    // fill OCCoAPToken structure
-    RetrieveOCCoAPToken(recvPdu, &rcvdToken);
-    OC_LOG_V(INFO, TAG,"Received a pdu with Token", rcvdToken.tokenLength);
-    OC_LOG_BUFFER(INFO, TAG, rcvdToken.token, rcvdToken.tokenLength);
-
-    // fill OCClientResponse structure
-    result = FormOCClientResponse(&clientResponse, CoAPToOCResponseCode(recvPdu->hdr->code),
-            (OCDevAddr *) &(rcvdResponse->remote), sequenceNumber, bufRes);
-    VERIFY_SUCCESS(result, OC_STACK_OK);
-
-    cbNode = GetClientCB(&rcvdToken, NULL, NULL);
-
-    #ifdef WITH_PRESENCE
-    // Check if the application subscribed for presence
-    if(!cbNode)
-    {
-        // get the address of the remote
-        OCDevAddrToIPv4Addr((OCDevAddr *) &(rcvdResponse->remote), remoteIpAddr,
-                remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
-        OCDevAddrToPort((OCDevAddr *) &(rcvdResponse->remote), &remotePortNu);
-        snprintf((char *)fullUri, sizeof(fullUri), "coap://%d.%d.%d.%d:%d%s",
-                remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3],
-                remotePortNu,rcvdUri);
-        cbNode = GetClientCB(NULL, NULL, fullUri);
-    }
-
-    // Check if application subscribed for multicast presence
-    if(!cbNode)
-    {
-        snprintf((char *)fullUri, sizeof(fullUri), "%s%s", OC_MULTICAST_IP, rcvdUri);
-        cbNode = GetClientCB(NULL, NULL, fullUri);
-        isMulticastPresence = 1;
-        isPresenceNotification = 0;
-    }
-    #endif
-
-    // fill OCResponse structure
-    result = FormOCResponse(&response, cbNode, maxAge, &clientResponse);
-    VERIFY_SUCCESS(result, OC_STACK_OK);
-
-    if(cbNode)
-    {
-        if(!isObserveNotification)
-        {
-            #ifdef WITH_PRESENCE
-            if(!isPresenceNotification)
-            {
-            #endif
-                OC_LOG(INFO, TAG, PCF("Received a regular response"));
-                if(recvPdu->hdr->type == COAP_MESSAGE_CON)
-                {
-                    sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0,
-                            recvPdu->hdr->id, NULL, NULL, NULL);
-                    VERIFY_NON_NULL(sendPdu);
-                    result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote,
-                            sendPdu,
-                            (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
-                }
-            #ifdef WITH_PRESENCE
-            }
-            #endif
-        }
-        if(isObserveNotification)
-        {
-            OC_LOG(INFO, TAG, PCF("Received an observe notification"));
-            if(recvPdu->hdr->type == COAP_MESSAGE_CON)
-            {
-                sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0,
-                        recvPdu->hdr->id, NULL, NULL, NULL);
-                VERIFY_NON_NULL(sendPdu);
-                result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote,
-                        sendPdu,
-                        (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
-            }
-            //TODO: check the standard for methods to detect wrap around condition
-            if(cbNode->method == OC_REST_OBSERVE &&
-                    (clientResponse.sequenceNumber <= cbNode->sequenceNumber ||
-                            (clientResponse.sequenceNumber > cbNode->sequenceNumber &&
-                                    clientResponse.sequenceNumber == (MAX_SEQUENCE_NUMBER))))
-            {
-                OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
-                        Ignoring Incoming:%d  Against Current:%d.",
-                        clientResponse.sequenceNumber, cbNode->sequenceNumber);
-                goto exit;
-            }
-            if(clientResponse.sequenceNumber > cbNode->sequenceNumber){
-                cbNode->sequenceNumber = clientResponse.sequenceNumber;
-            }
-        }
-        else
-        {
-            #ifdef WITH_PRESENCE
-            if(isPresenceNotification)
-            {
-                OC_LOG(INFO, TAG, PCF("Received a presence notification"));
-                if(!cbNode->presence)
-                {
-                    cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
-                    VERIFY_NON_NULL(cbNode->presence);
-                    cbNode->presence->timeOut = NULL;
-                    cbNode->presence->timeOut = (uint32_t *)
-                            OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
-                    if(!(cbNode->presence->timeOut)){
-                        OCFree(cbNode->presence);
-                        goto exit;
-                    }
-                }
-                if(maxAge == 0)
-                {
-                    OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
-                    response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
-                    if(cbNode->presence)
-                    {
-                        OCFree(cbNode->presence->timeOut);
-                        OCFree(cbNode->presence);
-                        cbNode->presence = NULL;
-                    }
-                }
-                else
-                {
-                    OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
-                    cbNode->presence->TTL = maxAge;
-                    for(int index = 0; index < PresenceTimeOutSize; index++)
-                    {
-                        lowerBound = GetTime(((float)(PresenceTimeOut[index])
-                                /(float)100)*(float)cbNode->presence->TTL);
-                        higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
-                                /(float)100)*(float)cbNode->presence->TTL);
-                        cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
-                        OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout  %d", lowerBound);
-                        OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
-                        OC_LOG_V(DEBUG, TAG, "----------------timeOut entry  %d", cbNode->presence->timeOut[index]);
-                    }
-                    cbNode->presence->TTLlevel = 0;
-                    OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
-                    if(cbNode->sequenceNumber == clientResponse.sequenceNumber)
-                    {
-                        OC_LOG(INFO, TAG, PCF("===============No presence change"));
-                        goto exit;
-                    }
-                    OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
-                    cbNode->sequenceNumber = clientResponse.sequenceNumber;;
-                }
-
-                // Ensure that a filter is actually applied.
-                if(resourceTypeName && response->cbNode->filterResourceType)
-                {
-                    if(!findResourceType(response->cbNode->filterResourceType, resourceTypeName))
-                    {
-                        goto exit;
-                    }
-                }
-            }
-            else if(isMulticastPresence)
-            {
-                // Check if the same nonce for a given host
-                OCMulticastNode* mcNode = NULL;
-                unsigned char senderUri[MAX_URI_LENGTH] = { 0 };
-                snprintf((char *)senderUri, sizeof(senderUri), "%d.%d.%d.%d:%d",
-                    remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3],
-                    remotePortNu);
-                mcNode = GetMCPresenceNode(senderUri);
-
-                if(maxAge == 0)
-                {
-                    OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
-                    response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
-                    if(cbNode->presence)
-                    {
-                        OCFree(cbNode->presence->timeOut);
-                        OCFree(cbNode->presence);
-                        cbNode->presence = NULL;
-                    }
-                }
-                else if(mcNode != NULL)
-                {
-                    if(mcNode->nonce == clientResponse.sequenceNumber)
-                    {
-                        OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
-                        goto exit;
-                    }
-                    mcNode->nonce = clientResponse.sequenceNumber;
-                }
-                else
-                {
-                    uint32_t uriLen = strlen((char*)senderUri);
-                    unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
-                    if(uri)
-                    {
-                        memcpy(uri, senderUri, (uriLen + 1));
-                    }
-                    else
-                    {
-                        OC_LOG(INFO, TAG,
-                            PCF("===============No Memory for URI to store in the presence node"));
-                        goto exit;
-                    }
-                    result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
-                                                clientResponse.sequenceNumber);
-                    if(result == OC_STACK_NO_MEMORY)
-                    {
-                        OC_LOG(INFO, TAG,
-                            PCF("===============No Memory for Multicast Presence Node"));
-                        goto exit;
-                    }
-                }
-
-                // Ensure that a filter is actually applied.
-                if(resourceTypeName && response->cbNode->filterResourceType)
-                {
-                    if(!findResourceType(response->cbNode->filterResourceType, resourceTypeName))
-                    {
-                        goto exit;
-                    }
-                }
-            }
-            #endif
-        }
-        HandleStackResponses(response);
-    }
-    else if(!cbNode && isObserveNotification)
-    {
-        OC_LOG(INFO, TAG, PCF("Received an observe notification, but I do not have callback \
-                 ------------ sending RESET"));
-        sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0,
-                recvPdu->hdr->id, NULL, NULL, NULL);
-        VERIFY_NON_NULL(sendPdu);
-        result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu,
-                     (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
-        VERIFY_SUCCESS(result, OC_STACK_OK);
-    }
-    #ifdef WITH_PRESENCE
-    else if(!cbNode && isPresenceNotification)
-    {
-        OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
-                     ------------ ignoring"));
-    }
-    #endif
-    else
-    {
-        OC_LOG(INFO, TAG, PCF("Received a response, but I do not have callback. \
-                 ------------ sending RESET"));
-        sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0,
-                recvPdu->hdr->id, NULL, NULL, NULL);
-        VERIFY_NON_NULL(sendPdu);
-        result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu,
-                    (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
-        VERIFY_SUCCESS(result, OC_STACK_OK);
-    }
-    exit:
-        OCFree(resourceTypeName);
-        OCFree(response);
-}
-
-//=============================================================================
-// Functions
-//=============================================================================
-
-/**
- * Initialize the CoAP client or server with its IPv4 address and CoAP port
- *
- * @param ipAddr
- *     IP Address of host device
- * @param port
- *     Port of host device
- * @param mode
- *     Host device is client, server, or client-server
- *
- * @return
- *   0   - success
- *   TBD - TBD error
- */
-OCStackResult OCInitCoAP(const char *address, uint16_t port, OCMode mode) {
-
-    OCStackResult ret = OC_STACK_ERROR;
-
-    TODO ("Below should go away and be replaced by OC_LOG");
-    coap_log_t log_level = (coap_log_t)(LOG_DEBUG + 1);
-    OCDevAddr mcastAddr;
-    uint8_t ipAddr[4] = { 0 };
-    uint16_t parsedPort = 0;
-
-    OC_LOG(INFO, TAG, PCF("Entering OCInitCoAP"));
-
-    coap_set_log_level(log_level);
-
-    if (address)
-    {
-        if (!ParseIPv4Address((unsigned char *) address, ipAddr, &parsedPort))
-        {
-            ret = OC_STACK_ERROR;
-            goto exit;
-        }
-
-        OC_LOG_V(INFO, TAG, "Parsed IP Address %d.%d.%d.%d",
-                               ipAddr[0],ipAddr[1],ipAddr[2],ipAddr[3]);
-    }
-
-    gCoAPCtx = coap_new_context(ipAddr, port);
-    VERIFY_NON_NULL(gCoAPCtx);
-
-    // To allow presence notification work we need to init socket gCoAPCtx->sockfd_wellknown
-    // for servers as well as clients
-    OCBuildIPv4Address(COAP_WK_IPAddr_0, COAP_WK_IPAddr_1, COAP_WK_IPAddr_2,
-            COAP_WK_IPAddr_3, COAP_DEFAULT_PORT, &mcastAddr);
-    VERIFY_SUCCESS(
-            coap_join_wellknown_group(gCoAPCtx,
-                    (coap_address_t* )&mcastAddr), 0);
-
-    coap_register_request_handler(gCoAPCtx, HandleCoAPRequests);
-    coap_register_response_handler(gCoAPCtx, HandleCoAPResponses);
-    coap_register_ack_rst_handler(gCoAPCtx, HandleCoAPAckRst);
-
-    ret = OC_STACK_OK;
-
-exit:
-    if (ret != OC_STACK_OK)
-    {
-        OCStopCoAP();
-    }
-    return ret;
-}
-
-/**
- * Discover OC resources
- *
- * @param method          - method to perform on the resource
- * @param qos             - Quality of Service the request will be sent on
- * @param token           - token which will added to the request
- * @param Uri             - URI of the resource to interact with
- * @param payload         - the request payload to be added to the request before sending
- *                          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
- * @return
- *   0   - success
- *   TBD - TBD error
- */
-OCStackResult OCDoCoAPResource(OCMethod method, OCQualityOfService qos, OCCoAPToken * token,
-                     const char *Uri, const char *payload, OCHeaderOption * options, uint8_t numOptions)
-{
-
-    OCStackResult ret = OC_STACK_ERROR;
-    coap_pdu_t *pdu = NULL;
-    coap_uri_t uri;
-    OCDevAddr dst;
-    uint8_t ipAddr[4] = { 0 };
-    uint16_t port = 0;
-    coap_list_t *optList = NULL;
-    uint8_t coapMsgType;
-    uint8_t coapMethod;
-    uint32_t observeOption;
-    coap_send_flags_t flag = (coap_send_flags_t)0;
-
-    OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResource"));
-
-    if (Uri) {
-        OC_LOG_V(INFO, TAG, "URI = %s", Uri);
-        VERIFY_SUCCESS(coap_split_uri((unsigned char * )Uri, strlen(Uri), &uri), OC_STACK_OK);
-
-        // Generate the destination address
-        if (uri.host.length && ParseIPv4Address(uri.host.s, ipAddr, &port)) {
-            OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], uri.port,
-                    &dst);
-        } else {
-            goto exit;
-        }
-
-        VERIFY_SUCCESS(FormOptionList(&optList, NULL, NULL, NULL,
-                (uint16_t*)&uri.port, uri.path.length, uri.path.s, uri.query.length,
-                uri.query.s, options, numOptions), OC_STACK_OK);
-
-        //TODO : Investigate the scenario where there will be no uri for OCDoCoAPResource
-        flag = (coap_send_flags_t) (uri.secure ? SEND_SECURE_PORT : 0);
-        OC_LOG_V(DEBUG, TAG, "uri.host.s %s", uri.host.s);
-        OC_LOG_V(DEBUG, TAG, "uri.path.s %s", uri.path.s);
-        OC_LOG_V(DEBUG, TAG, "uri.port %d", uri.port);
-        OC_LOG_V(DEBUG, TAG, "uri.query.s %s", uri.query.s);
-        OC_LOG_V(DEBUG, TAG, "secure uri %d", uri.secure);
-    }
-
-    coapMsgType = OCToCoAPQoS(qos, ipAddr);
-
-    // Decide method type
-    switch (method) {
-        case OC_REST_GET:
-        #ifdef WITH_PRESENCE
-        case OC_REST_PRESENCE:
-        #endif
-            coapMethod = COAP_REQUEST_GET;
-            break;
-        case OC_REST_PUT:
-            coapMethod = COAP_REQUEST_PUT;
-            break;
-        case OC_REST_POST:
-            coapMethod = COAP_REQUEST_POST;
-            break;
-        case OC_REST_DELETE:
-            coapMethod = COAP_REQUEST_DELETE;
-            break;
-        case OC_REST_OBSERVE_ALL:
-        case OC_REST_OBSERVE:
-        case OC_REST_CANCEL_OBSERVE:
-            coapMethod = COAP_REQUEST_GET;
-            observeOption = (method == OC_REST_CANCEL_OBSERVE)?
-                    OC_OBSERVE_DEREGISTER:OC_OBSERVE_REGISTER;
-            coap_insert(&optList, CreateNewOptionNode(COAP_OPTION_OBSERVE,
-                        sizeof(observeOption), (uint8_t *)&observeOption), OrderOptions);
-            break;
-        default:
-            coapMethod = OC_REST_NOMETHOD;
-            OC_LOG(FATAL, TAG, PCF("OCDoCoAPResource only supports GET, PUT, & OBSERVE methods"));
-            break;
-    }
-
-    VERIFY_NON_NULL(gCoAPCtx);
-    pdu = GenerateCoAPPdu(coapMsgType, coapMethod,
-            coap_new_message_id(gCoAPCtx), token,
-            (unsigned char*) payload, optList);
-    VERIFY_NON_NULL(pdu);
-
-    ret = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &dst, pdu, flag);
-
-exit:
-    if (ret!= OC_STACK_OK)
-    {
-        OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
-    }
-    return ret;
-}
-
-OCStackResult OCDoCoAPResponse(OCServerProtocolResponse *response)
-{
-    OCStackResult result = OC_STACK_ERROR;
-    coap_pdu_t * sendPdu = NULL;
-    coap_list_t *optList = NULL;
-    uint8_t msgType = COAP_MESSAGE_NON;
-    uint8_t mediaType = COAP_MEDIATYPE_APPLICATION_JSON;
-    uint32_t maxAge = 0x2ffff;
-    coap_send_flags_t sendFlag = (coap_send_flags_t)0;
-
-    //uint32_t observeOption = OC_OBSERVE_NO_OPTION;
-    //OCStackResult responseResult;
-
-    OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResponse"));
-
-    if(response->notificationFlag && response->qos == OC_HIGH_QOS)
-    {
-        msgType = COAP_MESSAGE_CON;
-    }
-    else if(response->notificationFlag && response->qos != OC_HIGH_QOS)
-    {
-        msgType = COAP_MESSAGE_NON;
-    }
-    else if(!response->notificationFlag && !response->slowFlag && response->qos == OC_HIGH_QOS)
-    {
-        msgType = COAP_MESSAGE_ACK;
-    }
-    else if(!response->notificationFlag && response->slowFlag && response->qos == OC_HIGH_QOS)
-    {
-        msgType = COAP_MESSAGE_CON;
-    }
-    else if(!response->notificationFlag)
-    {
-        msgType = COAP_MESSAGE_NON;
-    }
-
-    if(response->coapID == 0)
-    {
-        response->coapID = coap_new_message_id(gCoAPCtx);
-    }
-
-    if (response->observationOption != OC_OBSERVE_NO_OPTION)
-    {
-        result = FormOptionList(&optList, &mediaType, &maxAge,
-                &response->observationOption, NULL,
-                strlen((char *)response->resourceUri), response->resourceUri,
-                0, NULL,
-                response->sendVendorSpecificHeaderOptions,
-                response->numSendVendorSpecificHeaderOptions);
-    }
-    else
-    {
-        result = FormOptionList(&optList, &mediaType, &maxAge,
-                NULL, NULL,
-                strlen((char *)response->resourceUri), response->resourceUri,
-                0, NULL,
-                response->sendVendorSpecificHeaderOptions,
-                response->numSendVendorSpecificHeaderOptions);
-    }
-    VERIFY_SUCCESS(result, OC_STACK_OK);
-
-    sendPdu = GenerateCoAPPdu(msgType, OCToCoAPResponseCode(response->result),
-            response->coapID, response->requestToken, (unsigned char *)response->payload,
-            optList);
-
-    VERIFY_NON_NULL(sendPdu);
-    coap_show_pdu(sendPdu);
-
-    sendFlag = (coap_send_flags_t)(response->delayedResNeeded ? SEND_DELAYED : 0);
-    sendFlag = (coap_send_flags_t)( sendFlag | (response->secured ? SEND_SECURE_PORT : 0));
-
-    if (SendCoAPPdu(gCoAPCtx, (coap_address_t *) (response->requesterAddr), sendPdu, sendFlag)
-            != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, TAG, PCF("A problem occurred in sending a pdu"));
-        return OC_STACK_ERROR;
-    }
-
-    return OC_STACK_OK;
-
-exit:
-    OC_LOG(ERROR, TAG, PCF("Error formatting server response"));
-    return OC_STACK_ERROR;
-}
-
-
-/**
- * Stop the CoAP client or server processing
- *
- * @return 0 - success, else - TBD error
- */
-OCStackResult OCStopCoAP() {
-    OC_LOG(INFO, TAG, PCF("Entering OCStopCoAP"));
-    coap_free_context(gCoAPCtx);
-    gCoAPCtx = NULL;
-    return OC_STACK_OK;
-}
-
-/**
- * Called in main loop of CoAP client or server.  Allows low-level CoAP processing of
- * send, receive, timeout, discovery, callbacks, etc.
- *
- * @return 0 - success, else - TBD error
- */
-OCStackResult OCProcessCoAP() {
-
-    OC_LOG(INFO, TAG, PCF("Entering OCProcessCoAP"));
-    int read = 0;
-    read = coap_read(gCoAPCtx, gCoAPCtx->sockfd);
-    if(read > 0) {
-        OC_LOG(INFO, TAG, PCF("This is a Unicast<============"));
-    }
-    if (-1 != gCoAPCtx->sockfd_wellknown) {
-        read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_wellknown);
-        if(read > 0)
-        {
-            OC_LOG(INFO, TAG, PCF("This is a Multicast<==========="));
-        }
-    }
-    if (-1 != gCoAPCtx->sockfd_dtls) {
-        read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_dtls);
-        if(read > 0)
-        {
-            OC_LOG(INFO, TAG, PCF("This is a Secure packet<==========="));
-        }
-    }
-    coap_dispatch(gCoAPCtx);
-
-    HandleSendQueue(gCoAPCtx);
-
-    return OC_STACK_OK;
-}
-
-
-/**
- * Retrieve the info about the end-point where resource is being hosted.
- * Currently, this method only provides the IP port with which the socket
- * is bound.
- *
- * @return 0 - success, else - TBD error
- */
-OCStackResult OCGetResourceEndPointInfo (OCResource *resPtr, void *info) {
-
-    OCStackResult result = OC_STACK_ERROR;
-    int sfd;
-    OC_LOG(INFO, TAG, PCF("Entering OCGetResourceEndPointInfo"));
-    VERIFY_NON_NULL(resPtr);
-    VERIFY_NON_NULL(info);
-
-    sfd = (resPtr->resourceProperties & OC_SECURE) ? gCoAPCtx->sockfd_dtls :
-            gCoAPCtx->sockfd;
-
-    if (OCGetSocketInfo(sfd, (uint16_t*)info) == ERR_SUCCESS)
-        result = OC_STACK_OK;
-exit:
-    return result;
-}
-
-
diff --git a/resource/csdk/occoap/src/occoaphelper.c b/resource/csdk/occoap/src/occoaphelper.c
deleted file mode 100644 (file)
index 1727c26..0000000
+++ /dev/null
@@ -1,714 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-//-----------------------------------------------------------------------------
-// Includes
-//-----------------------------------------------------------------------------
-#include "occoaphelper.h"
-#include "ocstackconfig.h"
-#include "logger.h"
-#include "coap_time.h"
-#include "ocmalloc.h"
-
-//-----------------------------------------------------------------------------
-// Macros
-//-----------------------------------------------------------------------------
-#define TAG    PCF("OCCoAPHelper")
-#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg); goto exit;} }
-
-//=============================================================================
-// Helper Functions
-//=============================================================================
-
-OCStackResult isVendorSpecific(uint16_t optionID)
-{
-    if(optionID >= COAP_VENDOR_OPT_START && optionID <= COAP_MAX_OPT)
-    {
-        return OC_STACK_OK;
-    }
-    return OC_STACK_INVALID_OPTION;
-}
-
-// Convert OCStack code to CoAP code
-uint8_t OCToCoAPResponseCode(OCStackResult result)
-{
-    uint8_t ret;
-    switch(result)
-    {
-        case OC_STACK_OK :
-            ret = COAP_RESPONSE_200;
-            break;
-
-        case OC_STACK_RESOURCE_CREATED:
-            ret = COAP_RESPONSE_201;
-            break;
-
-        case OC_STACK_RESOURCE_DELETED:
-            ret = COAP_RESPONSE_202;
-            break;
-
-        case OC_STACK_INVALID_QUERY :
-            ret = COAP_RESPONSE_400;
-            break;
-
-        case OC_STACK_RESOURCE_ERROR:
-            return COAP_RESPONSE_403;
-            break;
-
-        case OC_STACK_NO_RESOURCE :
-            ret = COAP_RESPONSE_404;
-            break;
-
-        case OC_STACK_INVALID_METHOD :
-            ret = COAP_RESPONSE_405;
-            break;
-
-        case OC_STACK_NOTIMPL :
-            ret = COAP_RESPONSE_501;
-            break;
-
-        default:
-            ret = COAP_RESPONSE_500;
-    }
-    return ret;
-}
-
-uint8_t OCToCoAPQoS(OCQualityOfService qos, uint8_t * ipAddr)
-{
-    if(ipAddr[0] == COAP_WK_IPAddr_0 && ipAddr[1] == COAP_WK_IPAddr_1 &&
-            ipAddr[2] == COAP_WK_IPAddr_2 && ipAddr[3] == COAP_WK_IPAddr_3)
-    {
-        return COAP_MESSAGE_NON;
-    }
-    switch (qos)
-    {
-        case OC_HIGH_QOS:
-            return COAP_MESSAGE_CON;
-            break;
-        case OC_MEDIUM_QOS:
-        case OC_LOW_QOS:
-        case OC_NA_QOS:
-        default:
-            return COAP_MESSAGE_NON;
-            break;
-    }
-}
-// Convert CoAP code to OCStack code
-OCStackResult CoAPToOCResponseCode(uint8_t coapCode)
-{
-    OCStackResult ret;
-    int decimal;
-    switch(coapCode)
-    {
-        case COAP_RESPONSE_200 :
-            ret = OC_STACK_OK;
-            break;
-
-        case COAP_RESPONSE_201 :
-            ret = OC_STACK_RESOURCE_CREATED;
-            break;
-
-        case COAP_RESPONSE_202 :
-            ret = OC_STACK_RESOURCE_DELETED;
-            break;
-
-        case COAP_RESPONSE_400 :
-            ret = OC_STACK_INVALID_QUERY;
-            break;
-
-        case COAP_RESPONSE_403 :
-            ret = OC_STACK_RESOURCE_ERROR;
-            break;
-
-        case COAP_RESPONSE_404 :
-            ret = OC_STACK_NO_RESOURCE;
-            break;
-
-        case COAP_RESPONSE_405 :
-            ret = OC_STACK_INVALID_METHOD;
-            break;
-
-        case COAP_RESPONSE_501 :
-            ret = OC_STACK_NOTIMPL;
-            break;
-
-        default:
-            decimal = ((coapCode >> 5) * 100) + (coapCode & 31);
-            if (decimal >= 200 && decimal <= 231)
-            {
-                ret = OC_STACK_OK;
-            }
-            else
-            {
-                ret = OC_STACK_ERROR;
-            }
-    }
-    return ret;
-}
-
-// Retrieve Uri and Query from received coap pdu
-OCStackResult ParseCoAPPdu(coap_pdu_t * pdu, unsigned char * uriBuf,
-        unsigned char * queryBuf, uint32_t * observeOption,
-        uint32_t * maxAgeOption,
-        uint8_t * numVendorSpecificHeaderOptions,
-        OCHeaderOption * vendorSpecificHeaderOptions,
-        coap_block_t * block1, coap_block_t * block2,
-        uint16_t * size1, uint16_t * size2,
-        unsigned char * payload)
-{
-    coap_opt_filter_t filter;
-    coap_opt_iterator_t opt_iter;
-    coap_opt_t *option = NULL;
-    size_t optLen = 0;
-    unsigned char * optVal = NULL;
-    size_t uriBufLen = 0;
-    size_t queryBufLen = 0;
-    unsigned char * payloadLoc = NULL;
-    size_t payloadLength = 0;
-
-    coap_option_filter_clear(filter);
-    if(uriBuf)
-    {
-        coap_option_setb(filter, COAP_OPTION_URI_PATH);
-    }
-    if(queryBuf)
-    {
-        coap_option_setb(filter, COAP_OPTION_URI_QUERY);
-    }
-    if(observeOption)
-    {
-        coap_option_setb(filter, COAP_OPTION_OBSERVE);
-    }
-    if(maxAgeOption)
-    {
-        coap_option_setb(filter, COAP_OPTION_MAXAGE);
-    }
-    if(block1)
-    {
-        coap_option_setb(filter, COAP_OPTION_BLOCK1);
-    }
-    if(block2)
-    {
-        coap_option_setb(filter, COAP_OPTION_BLOCK2);
-    }
-    if(size1)
-    {
-        coap_option_setb(filter, COAP_OPTION_SIZE1);
-    }
-    if(size2)
-    {
-        coap_option_setb(filter, COAP_OPTION_SIZE2);
-    }
-    if(vendorSpecificHeaderOptions)
-    {
-        coap_option_setbVendor(filter);
-    }
-    if(payload)
-    {
-        coap_get_data(pdu, &payloadLength, &payloadLoc);
-        memcpy(payload, payloadLoc, payloadLength);
-    }
-    coap_option_iterator_init(pdu, &opt_iter, filter);
-
-    while ((option = coap_option_next(&opt_iter)))
-    {
-        optLen = COAP_OPT_LENGTH(option);
-        optVal = COAP_OPT_VALUE(option);
-        switch(opt_iter.type)
-        {
-        case COAP_OPTION_URI_PATH:
-            if (uriBufLen + 1 + optLen < MAX_URI_LENGTH)
-            {
-                //we still have room in the buffer
-                uriBuf[uriBufLen++] = '/';
-                memcpy(uriBuf + uriBufLen, optVal, optLen);
-                uriBufLen += optLen;
-            }
-            else
-            {
-                return OC_STACK_NO_MEMORY;
-            }
-            break;
-        case COAP_OPTION_URI_QUERY:
-            if (queryBufLen + 1 + optLen < MAX_QUERY_LENGTH)
-            {
-                //we still have room in the buffer
-                memcpy(queryBuf + queryBufLen, optVal, optLen);
-                queryBufLen += optLen;
-                queryBuf[queryBufLen++] = '&';
-            }
-            else
-            {
-                // TODO: we should check that resources do not have long uri
-                // at the resource creation
-                return OC_STACK_NO_MEMORY;
-            }
-            break;
-        case COAP_OPTION_OBSERVE:
-            memcpy(observeOption, optVal, optLen);
-            OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing the observe option %u",
-                    *observeOption);
-            break;
-        case COAP_OPTION_MAXAGE:
-            memcpy(maxAgeOption, optVal, optLen);
-            OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing the max age option %u",
-                    *maxAgeOption);
-            break;
-        case COAP_OPTION_BLOCK1:
-            block1->szx = COAP_OPT_BLOCK_SZX(option);
-            block1->num = coap_opt_block_num(option);
-            block1->m = 0;
-            if(COAP_OPT_BLOCK_MORE(option))
-            {
-                block1->m = 1;
-            }
-            OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing block1 %u:%u:%u",
-                    block1->num, block1->m, block1->szx);
-            break;
-        case COAP_OPTION_BLOCK2:
-            block2->szx = COAP_OPT_BLOCK_SZX(option);
-            block2->num = coap_opt_block_num(option);
-            block2->m = 0;
-            if(COAP_OPT_BLOCK_MORE(option))
-            {
-                block2->m = 1;
-            }
-            OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing block2 %u:%u:%u",
-                    block1->num, block1->m, block1->szx);
-            break;
-        case COAP_OPTION_SIZE1:
-            break;
-        case COAP_OPTION_SIZE2:
-            break;
-        default:
-            if(*numVendorSpecificHeaderOptions >= MAX_HEADER_OPTIONS ||
-                    optLen > MAX_HEADER_OPTION_DATA_LENGTH)
-            {
-                return OC_STACK_NO_MEMORY;
-            }
-            vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].protocolID = OC_COAP_ID;
-            vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionID = opt_iter.type;
-            vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionLength = optLen;
-            memcpy(vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionData, optVal, optLen);
-            OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing vendor specific option %u",
-                    vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionID);
-            OC_LOG_BUFFER(DEBUG, TAG, vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionData,
-                    vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionLength);
-            (*numVendorSpecificHeaderOptions)++;
-        }
-    }
-
-    if(uriBuf)
-    {
-        uriBuf[uriBufLen] = '\0';
-    }
-    // delete last '&' in the query
-    if(queryBuf)
-    {
-        queryBuf[queryBufLen?queryBufLen-1:queryBufLen] = '\0';
-    }
-
-    OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^The final parsed uri is %s", uriBuf);
-    OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^The final parsed query is %s", queryBuf);
-    return OC_STACK_OK;
-}
-
-// Retrieve the token from the PDU
-void RetrieveOCCoAPToken(const coap_pdu_t * pdu, OCCoAPToken * rcvdToken)
-{
-    if (pdu && rcvdToken)
-    {
-        rcvdToken->tokenLength = pdu->hdr->token_length;
-        memcpy(rcvdToken->token, pdu->hdr->token,
-            rcvdToken->tokenLength);
-    }
-}
-
-OCStackResult FormOCResponse(OCResponse * * responseLoc, ClientCB * cbNode,
-        uint8_t TTL, OCClientResponse * clientResponse)
-{
-    OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
-    if (!response)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-    response->cbNode = cbNode;
-    response->TTL = TTL;
-    response->clientResponse = clientResponse;
-
-    *responseLoc = response;
-    return OC_STACK_OK;
-}
-
-OCStackResult FormOCClientResponse(OCClientResponse * clientResponse,
-        OCStackResult result, OCDevAddr * remote, uint32_t seqNum,
-        const unsigned char * resJSONPayload)
-{
-    clientResponse->sequenceNumber = seqNum;
-    clientResponse->result = result;
-    clientResponse->addr = remote;
-    clientResponse->resJSONPayload = resJSONPayload;
-
-    return OC_STACK_OK;
-}
-
-OCStackResult FormOptionList(coap_list_t * * optListLoc, uint8_t * addMediaType,
-        uint32_t * addMaxAge, uint32_t * observeOptionPtr,
-        uint16_t * addPortNumber, uint8_t uriLength, unsigned char * uri,
-        uint8_t queryLength, unsigned char * query,
-        OCHeaderOption * vendorSpecificHeaderOptions,
-        uint8_t numVendorSpecificHeaderOptions)
-{
-    coap_list_t * optNode = NULL;
-    int res;
-    size_t buflen;
-    unsigned char _buf[MAX_URI_QUERY_BUF_SIZE];
-    unsigned char *buf = _buf;
-
-    if(addMediaType)
-    {
-        optNode = CreateNewOptionNode(COAP_OPTION_CONTENT_TYPE,
-                sizeof(*addMediaType), addMediaType);
-        VERIFY_NON_NULL(optNode);
-        coap_insert(optListLoc, optNode, OrderOptions);
-    }
-
-    if(addMaxAge)
-    {
-        optNode = CreateNewOptionNode(COAP_OPTION_MAXAGE,
-                sizeof(*addMaxAge), (uint8_t *)addMaxAge);
-        VERIFY_NON_NULL(optNode);
-        coap_insert(optListLoc, optNode, OrderOptions);
-    }
-
-    if(observeOptionPtr)
-    {
-        optNode = CreateNewOptionNode(COAP_OPTION_OBSERVE,
-                sizeof(*observeOptionPtr), (uint8_t *)observeOptionPtr);
-
-        VERIFY_NON_NULL(optNode);
-        coap_insert(optListLoc, optNode, OrderOptions);
-    }
-    if(addPortNumber && *addPortNumber != COAP_DEFAULT_PORT)
-    {
-        optNode = CreateNewOptionNode(COAP_OPTION_URI_PORT,
-                sizeof(*addPortNumber), (uint8_t *)addPortNumber);
-        VERIFY_NON_NULL(optNode);
-        coap_insert(optListLoc, optNode, OrderOptions);
-    }
-
-    if(uri && uriLength)
-    {
-        buf = _buf;
-        buflen = MAX_URI_QUERY_BUF_SIZE;
-        res = coap_split_path(uri, uriLength, buf, &buflen);
-        while (res--) {
-            optNode = CreateNewOptionNode(COAP_OPTION_URI_PATH,
-                    COAP_OPT_LENGTH(buf), COAP_OPT_VALUE(buf));
-            VERIFY_NON_NULL(optNode);
-            coap_insert(optListLoc, optNode, OrderOptions);
-            buf += COAP_OPT_SIZE(buf);
-        }
-    }
-
-    if(query && queryLength)
-    {
-        buf = _buf;
-        buflen = MAX_URI_QUERY_BUF_SIZE;
-        res = coap_split_query(query, queryLength, buf, &buflen);
-        while (res--) {
-            optNode = CreateNewOptionNode(COAP_OPTION_URI_QUERY,
-                    COAP_OPT_LENGTH(buf), COAP_OPT_VALUE(buf));
-            VERIFY_NON_NULL(optNode);
-            coap_insert(optListLoc, optNode, OrderOptions);
-            buf += COAP_OPT_SIZE(buf);
-        }
-    }
-
-    // make sure that options are valid
-    if(vendorSpecificHeaderOptions && numVendorSpecificHeaderOptions)
-    {
-        uint8_t i = 0;
-        for( i = 0; i < numVendorSpecificHeaderOptions; i++)
-        {
-            if(vendorSpecificHeaderOptions[i].protocolID == OC_COAP_ID)
-            {
-                if(isVendorSpecific(vendorSpecificHeaderOptions[i].optionID)
-                        == OC_STACK_OK &&
-                        vendorSpecificHeaderOptions[i].optionLength <=
-                        MAX_HEADER_OPTION_DATA_LENGTH)
-                {
-                    OC_LOG_V(INFO, TAG, " Adding option %d with",
-                            vendorSpecificHeaderOptions[i].optionID);
-                    OC_LOG_BUFFER(INFO, TAG, vendorSpecificHeaderOptions[i].optionData,
-                            vendorSpecificHeaderOptions[i].optionLength);
-                    optNode = CreateNewOptionNode(vendorSpecificHeaderOptions[i].optionID,
-                            vendorSpecificHeaderOptions[i].optionLength,
-                            vendorSpecificHeaderOptions[i].optionData);
-                    VERIFY_NON_NULL(optNode);
-                    coap_insert(optListLoc, optNode, OrderOptions);
-                }
-                else
-                {
-                    coap_delete_list(*optListLoc);
-                    return OC_STACK_INVALID_OPTION;
-                }
-            }
-        }
-    }
-
-    return OC_STACK_OK;
-    exit:
-        coap_delete_list(*optListLoc);
-        return OC_STACK_NO_MEMORY;
-}
-
-//Send a coap pdu
-OCStackResult
-SendCoAPPdu(coap_context_t * gCoAPCtx, coap_address_t* dst, coap_pdu_t * pdu,
-        coap_send_flags_t flag)
-{
-    coap_tid_t tid = COAP_INVALID_TID;
-    OCStackResult res = OC_STACK_COMM_ERROR;
-    uint8_t cache = 0;
-
-    if (!(flag & SEND_DELAYED))
-    {
-        flag = (coap_send_flags_t)( flag |
-            ((pdu->hdr->type == COAP_MESSAGE_CON) ? SEND_NOW_CON : SEND_NOW));
-    }
-
-    tid = coap_send(gCoAPCtx, dst, pdu, flag, &cache);
-    OC_LOG_V(INFO, TAG, "TID %d", tid);
-    if(tid != COAP_INVALID_TID)
-    {
-        OC_LOG(INFO, TAG, PCF("Sending a pdu with Token:"));
-        OC_LOG_BUFFER(INFO,TAG, pdu->hdr->token, pdu->hdr->token_length);
-        res = OC_STACK_OK;
-    }
-
-    if (( (pdu->hdr->type != COAP_MESSAGE_CON) && (!(flag & SEND_DELAYED)) && (!cache))
-        || (tid == COAP_INVALID_TID))
-    {
-        OC_LOG(INFO, TAG, PCF("Deleting PDU"));
-        coap_delete_pdu(pdu);
-    }
-    else
-    {
-        OC_LOG(INFO, TAG, PCF("Keeping PDU, we will handle the retry/delay of this pdu"));
-    }
-
-    return res;
-}
-
-//generate a coap message
-coap_pdu_t *
-GenerateCoAPPdu(uint8_t msgType, uint8_t code, unsigned short id,
-        OCCoAPToken * token, unsigned char * payloadJSON,
-        coap_list_t *options)
-{
-    coap_pdu_t *pdu;
-    coap_list_t *opt;
-
-    if(token)
-    {
-        pdu = coap_pdu_init(msgType, code, id, COAP_MAX_PDU_SIZE);
-        VERIFY_NON_NULL(pdu);
-        pdu->hdr->token_length = token->tokenLength;
-         if (!coap_add_token(pdu, token->tokenLength, token->token))
-         {
-            OC_LOG(FATAL, TAG, PCF("coap_add_token failed"));
-        }
-    }
-    else
-    {
-        pdu = coap_pdu_init(msgType, code, id, sizeof(coap_pdu_t));
-        VERIFY_NON_NULL(pdu);
-    }
-
-    for (opt = options; opt; opt = opt->next)
-    {
-        coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
-                COAP_OPTION_LENGTH(*(coap_option *) opt->data),
-                COAP_OPTION_DATA(*(coap_option *) opt->data));
-    }
-
-    if (payloadJSON)
-    {
-        coap_add_data(pdu, strlen((const char *) payloadJSON) + 1,
-                (unsigned char*) payloadJSON);
-    }
-
-    // display the pdu for debugging purposes
-    coap_show_pdu(pdu);
-
-    // clean up
-    coap_delete_list(options);
-    return pdu;
-
-    exit:
-    coap_delete_list(options);
-    return NULL;
-}
-
-//a function to help in ordering coap options
-int OrderOptions(void *a, void *b)
-{
-    if (!a || !b)
-    {
-        return a < b ? -1 : 1;
-    }
-
-    if (COAP_OPTION_KEY(*(coap_option *)a)
-            < COAP_OPTION_KEY(*(coap_option *)b) )
-    {
-        return -1;
-    }
-
-    return COAP_OPTION_KEY(*(coap_option *)a)
-            == COAP_OPTION_KEY(*(coap_option *)b) ;
-}
-
-//a function to create a coap option
-coap_list_t *
-CreateNewOptionNode(unsigned short key, unsigned int length, unsigned char *data)
-{
-    coap_option *option = NULL;
-    coap_list_t *node;
-
-    VERIFY_NON_NULL(data);
-    option = (coap_option *)coap_malloc(sizeof(coap_option) + length);
-    VERIFY_NON_NULL(option);
-
-    COAP_OPTION_KEY(*option) = key;
-    COAP_OPTION_LENGTH(*option) = length;
-    memcpy(COAP_OPTION_DATA(*option), data, length);
-
-    /* we can pass NULL here as delete function since option is released automatically  */
-    node = coap_new_listnode(option, NULL);
-
-    if (node)
-    {
-        return node;
-    }
-
-exit:
-    OC_LOG(ERROR,TAG, PCF("new_option_node: malloc: was not created"));
-    coap_free(option);
-    return NULL;
-}
-
-OCStackResult ReTXCoAPQueue(coap_context_t * ctx, coap_queue_t * queue)
-{
-    coap_tid_t tid = COAP_INVALID_TID;
-    OCStackResult result = OC_STACK_ERROR;
-    tid = coap_retransmit( ctx, queue);
-    if(tid == COAP_INVALID_TID)
-    {
-        OC_LOG_V(DEBUG, TAG, "Retransmission Failed TID %d",
-                queue->id);
-        result = OC_STACK_COMM_ERROR;
-    }
-    else
-    {
-        OC_LOG_V(DEBUG, TAG, "Retransmission TID %d, this is attempt %d",
-                queue->id, queue->retransmit_cnt);
-        result = OC_STACK_OK;
-    }
-    return result;
-}
-
-OCStackResult HandleFailedCommunication(coap_context_t * ctx, coap_queue_t * queue)
-{
-    //TODO: this function should change to only use OCStackFeedBack
-    OCResponse * response = NULL;
-    ClientCB * cbNode = NULL;
-    OCClientResponse clientResponse;
-    OCCoAPToken token;
-    OCStackResult result = OC_STACK_OK;
-
-    RetrieveOCCoAPToken(queue->pdu, &token);
-
-    cbNode = GetClientCB(&token, NULL, NULL);
-    if(!cbNode)
-    {
-        goto observation;
-    }
-    result = FormOCClientResponse(&clientResponse, OC_STACK_COMM_ERROR,
-            (OCDevAddr *) &(queue->remote), 0, NULL);
-    if(result != OC_STACK_OK)
-    {
-        goto observation;
-    }
-    result = FormOCResponse(&response, cbNode, 0, &clientResponse);
-    if(result != OC_STACK_OK)
-    {
-        goto observation;
-    }
-    HandleStackResponses(response);
-
-observation:
-    result = OCStackFeedBack(&token, OC_OBSERVER_FAILED_COMM);
-    if(result == OC_STACK_OK)
-    {
-        coap_cancel_all_messages(ctx, &queue->remote, token.token, token.tokenLength);
-    }
-    OCFree(response);
-    return result;
-}
-
-// a function to handle the send queue in the passed context
-void HandleSendQueue(coap_context_t * ctx)
-{
-    coap_tick_t now;
-    coap_queue_t *nextQueue = NULL;
-
-    coap_ticks(&now);
-    nextQueue = coap_peek_next( ctx );
-    while (nextQueue && nextQueue->t <= now - ctx->sendqueue_basetime)
-    {
-        nextQueue = coap_pop_next( ctx );
-        if((uint8_t)nextQueue->delayedResNeeded)
-        {
-            OC_LOG_V(DEBUG, TAG, "Sending Delayed response TID %d",
-                    nextQueue->id);
-            if(SendCoAPPdu(ctx, &nextQueue->remote, nextQueue->pdu,
-                 (coap_send_flags_t)(nextQueue->secure ? SEND_SECURE_PORT : 0))
-                    == OC_STACK_COMM_ERROR)
-            {
-                OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
-                HandleFailedCommunication(ctx, nextQueue);
-            }
-            nextQueue->pdu = NULL;
-            coap_delete_node(nextQueue);
-        }
-        else
-        {
-            OC_LOG_V(DEBUG, TAG, "Retrying a CON pdu TID %d",nextQueue->id);
-            if(ReTXCoAPQueue(ctx, nextQueue) == OC_STACK_COMM_ERROR)
-            {
-                OC_LOG(DEBUG, TAG, PCF("A problem occurred in retransmitting a pdu"));
-                HandleFailedCommunication(ctx, nextQueue);
-                coap_delete_node(nextQueue);
-            }
-        }
-        nextQueue = coap_peek_next( ctx );
-    }
-}
diff --git a/resource/csdk/occoap/test/occoaptests.cpp b/resource/csdk/occoap/test/occoaptests.cpp
deleted file mode 100644 (file)
index 5a319e2..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-//=============================================================================
-// Includes
-//=============================================================================
-/*extern "C" {
-    #include "occoap.h"
-    #include "logger.h"
-}*/
-
-#include "gtest/gtest.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <iostream>
-#include <stdint.h>
-using namespace std;
-
-//=============================================================================
-// Private Variables
-//=============================================================================
-static const char TAG[] = "TestHarness";
-
-//=============================================================================
-// Callback function
-//=============================================================================
-/*void discoverServicesAsync(const char *Url) {
-    OC_LOG_V(INFO, TAG, "Entering discoverServicesAsync.  URL = %s", Url);
-}*/
-
-//=============================================================================
-// Tests
-//=============================================================================
-TEST(OCCoapTest, General) {
-    EXPECT_EQ(0, 0);
-}
diff --git a/resource/csdk/ocmalloc/test/linux/makefile b/resource/csdk/ocmalloc/test/linux/makefile
deleted file mode 100644 (file)
index 31dd9a0..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD   := release
-PLATFORM := linux
-CC      := g++
-
-ifeq ($(ROOT_DIR), )
-ROOT_DIR       = $(PWD)/../../..
-endif
-
-# You must create the file "local.properties" on your local machine which contains any local paths, etc
-# local.properties should NOT be committed to repo
-include $(ROOT_DIR)/local.properties
-# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties
-#  Example:
-#  GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
-
-# NOTE:  to run app, make sure that LD_LIBRARY_PATH env variable
-#        contains $(GTEST_DIR)/lib/.libs
-
-OUT_DIR          := $(PWD)/$(BUILD)
-OBJ_DIR          := $(OUT_DIR)/obj
-
-
-OUT_DIR          := $(PWD)
-
-OCLOGGER_DIR   = $(ROOT_DIR)/logger
-OCMALLOC_DIR   = $(ROOT_DIR)/ocmalloc
-OCRANDOM_DIR   = $(ROOT_DIR)/ocrandom
-OCSOCKET_DIR   = $(ROOT_DIR)/ocsocket
-LCOAP_DIR              = $(ROOT_DIR)/libcoap-4.1.1
-OCCOAP_DIR             = $(ROOT_DIR)/occoap
-OCTBSTACK_DIR  = $(ROOT_DIR)/stack
-
-OCLOGGER_INC   = $(OCLOGGER_DIR)/include
-OCMALLOC_INC   = $(OCMALLOC_DIR)/include
-OCRANDOM_INC   = $(OCRANDOM_DIR)/include
-OCSOCKET_INC   = $(OCSOCKET_DIR)/include
-LCOAP_INC              = $(LCOAP_DIR)
-OCCOAP_INC             = $(OCCOAP_DIR)/include
-OCTBSTACK_INC  = $(OCTBSTACK_DIR)/include
-
-INC_DIRS       := -I$(OCLOGGER_INC)
-INC_DIRS       += -I$(OCMALLOC_INC)
-INC_DIRS       += -I$(OCRANDOM_INC)
-INC_DIRS       += -I$(OCSOCKET_INC)
-INC_DIRS       += -I$(LCOAP_INC)
-INC_DIRS       += -I$(OCCOAP_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)/internal
-INC_DIRS  += -I$(GTEST_DIR)/include
-
-CC_FLAGS.debug      := -g -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \
-                        -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG
-CC_FLAGS.release    := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \
-                        -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD)
-
-LDLIBS         += -loctbstack -lpthread
-CPPFLAGS       += $(CC_FLAGS.$(BUILD)) $(LDLIBS) $(GTEST_DIR)/lib/.libs/libgtest.a \
-                          $(GTEST_DIR)/lib/.libs/libgtest_main.a
-
-SOURCES := unittest.cpp
-
-OBJECTS:= $(patsubst %.c, $(OBJ_DIR)/%.o, $(SOURCES))
-
-PROGRAMS := unittest
-
-all:   prep_dirs $(OBJECTS) $(PROGRAMS)
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-       -mkdir -p $(OBJ_DIR)
-
-$(OBJ_DIR)/%.o: %.cpp
-       $(CC) -c $(CPPFLAGS) $< -o $@
-
-unittest: $(OBJ_DIR)/unittest.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-.PHONY: clean
-
-clean: legacy_clean
-       -rm -rf release
-       -rm -rf debug
-
-legacy_clean:
-       rm -f *.o $(PROGRAMS)
index d516520..c4d219e 100644 (file)
@@ -36,6 +36,17 @@ extern "C" {
 #define ANALOG_IN (10)
 #endif
 
+#define UUID_SIZE (16)
+// The characters are 36 long, 37 for the null-term
+#define UUID_STRING_SIZE (37)
+
+typedef enum
+{
+    RAND_UUID_OK = 0,
+    RAND_UUID_INVALID_PARAM = -1,
+    RAND_UUID_READ_ERROR = -2,
+    RAND_UUID_CONVERT_ERROR = -3
+} OCRandomUuidResult;
 /**
  * Seed the random number generator. Seeding depends on platform.
  * Android and Linux uses current time. Arduino uses Analog reading on pin ANALOG_IN
@@ -73,6 +84,46 @@ void OCFillRandomMem(uint8_t * location, uint16_t len);
  */
 uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound);
 
+/**
+ * Generate a Uniformly Unique Identifier based on RFC4122 and
+ * provide it as a 16 byte byte-array
+ *
+ * @param[out] uuid
+ *               the 16 byte array to fill with the UUID data
+ *               of a new UUID
+ *
+ * @retval RAND_UUID_OK for success, otherwise an error value
+ */
+OCRandomUuidResult OCGenerateUuid(uint8_t uuid[UUID_SIZE]);
+
+/**
+ * Generate a Uniformly Unique Identifier based on RFC4122 and
+ * provide it as a C style string.
+ *
+ * @param[out] uuidString
+ *               a 37-byte length string to fill with the string
+ *               representation of a new UUID.  Size is 32 chars
+ *               for the hex data, 4 for '-' characters, and 1
+ *               for the NULL terminator
+ *
+ * @retval RAND_UUID_OK for success, otherwise an error value
+ */
+OCRandomUuidResult OCGenerateUuidString(char uuidString[UUID_STRING_SIZE]);
+
+/**
+ * Convert a UUID generated by OCGenerateUuid to a C style string
+ * based on RFC 4122
+ *
+ * @param[in]  uuid
+ *              The 16 byte array filled with UUID data by OCGenerateUuid
+ * @param[out] uuidString
+ *              a 37 byte length string to fill with the string
+ *              representation of the passed UUID.
+ * @retval RAND_UUID_OK for success, otherwise an error value
+ */
+OCRandomUuidResult OCConvertUuidToString(const uint8_t uuid[UUID_SIZE],
+        char uuidString[UUID_STRING_SIZE]);
+
 #ifdef __cplusplus
 }
 #endif
index 8c2d0a4..dd03cd9 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 
-#if defined(__ANDROID__) || defined(__linux__)
+#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
 #include "fcntl.h"
 #include "unistd.h"
 #endif
 #include "ocrandom.h"
+#include <stdio.h>
+
+#if !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#include <uuid/uuid.h>
+#endif
 
 #ifdef ARDUINO
 #include "Arduino.h"
@@ -62,7 +67,7 @@ uint8_t GetRandomBit() {
 #endif
 
 int8_t OCSeedRandom() {
-#if defined(__ANDROID__) || defined(__linux__)
+#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
     int32_t fd = open("/dev/urandom", O_RDONLY);
     if (fd > 0) {
         uint32_t randomSeed;
@@ -109,7 +114,7 @@ uint32_t OCGetRandom() {
 }
 
 uint8_t OCGetRandomByte(void) {
-#if defined(__ANDROID__) || defined(__linux__)
+#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
     return rand() & 0x00FF;
 #elif defined ARDUINO
     return random(256) & 0x00FF;
@@ -132,3 +137,148 @@ uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound){
     result = ((float)OCGetRandom()/((float)(0xFFFFFFFF))*(float)diff) + (float) base;
     return result;
 }
+
+#if defined(__ANDROID__)
+uint8_t parseUuidChar(char c)
+{
+    if(isdigit(c))
+    {
+        return c - '0';
+    }
+    else
+    {
+        return c - 'a' + 10;
+    }
+}
+uint8_t parseUuidPart(const char *c)
+{
+    return (parseUuidChar(c[0])<<4) + parseUuidChar(c[1]);
+}
+#endif
+
+OCRandomUuidResult OCGenerateUuid(uint8_t uuid[UUID_SIZE])
+{
+    if(!uuid)
+    {
+        return RAND_UUID_INVALID_PARAM;
+    }
+#if defined(__ANDROID__)
+    char uuidString[UUID_STRING_SIZE];
+    int8_t ret = OCGenerateUuidString(uuidString);
+
+    if(ret < 0)
+    {
+        return ret;
+    }
+
+    uuid[ 0] = parseUuidPart(&uuidString[0]);
+    uuid[ 1] = parseUuidPart(&uuidString[2]);
+    uuid[ 2] = parseUuidPart(&uuidString[4]);
+    uuid[ 3] = parseUuidPart(&uuidString[6]);
+
+    uuid[ 4] = parseUuidPart(&uuidString[9]);
+    uuid[ 5] = parseUuidPart(&uuidString[11]);
+
+    uuid[ 6] = parseUuidPart(&uuidString[14]);
+    uuid[ 7] = parseUuidPart(&uuidString[16]);
+
+    uuid[ 8] = parseUuidPart(&uuidString[19]);
+    uuid[ 9] = parseUuidPart(&uuidString[21]);
+
+    uuid[10] = parseUuidPart(&uuidString[24]);
+    uuid[11] = parseUuidPart(&uuidString[26]);
+    uuid[12] = parseUuidPart(&uuidString[28]);
+    uuid[13] = parseUuidPart(&uuidString[30]);
+    uuid[14] = parseUuidPart(&uuidString[32]);
+    uuid[15] = parseUuidPart(&uuidString[34]);
+
+    return RAND_UUID_OK;
+#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+    // note: uuid_t is typedefed as unsigned char[16] on linux/apple
+    uuid_generate(uuid);
+    return RAND_UUID_OK;
+#else
+    // Fallback for all platforms is filling the array with random data
+    OCFillRandomMem(uuid, UUID_SIZE);
+    return RAND_UUID_OK;
+#endif
+}
+
+OCRandomUuidResult OCGenerateUuidString(char uuidString[UUID_STRING_SIZE])
+{
+    if(!uuidString)
+    {
+        return RAND_UUID_INVALID_PARAM;
+    }
+#if defined(__ANDROID__)
+    int32_t fd = open("/proc/sys/kernel/random/uuid", O_RDONLY);
+    if(fd > 0)
+    {
+        ssize_t readResult = read(fd, uuidString, UUID_STRING_SIZE - 1);
+        close(fd);
+        if(readResult < 0)
+        {
+            return RAND_UUID_READ_ERROR;
+        }
+        else if(readResult < UUID_STRING_SIZE - 1)
+        {
+            uuidString[0] = '\0';
+            return RAND_UUID_READ_ERROR;
+        }
+
+        uuidString[UUID_STRING_SIZE - 1] = '\0';
+        for(char* p = uuidString; *p; ++p)
+        {
+            *p = tolower(*p);
+        }
+        return RAND_UUID_OK;
+    }
+    else
+    {
+        close(fd);
+        return RAND_UUID_READ_ERROR;
+    }
+#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+    uint8_t uuid[UUID_SIZE];
+    int8_t ret = OCGenerateUuid(uuid);
+
+    if(ret != 0)
+    {
+        return ret;
+    }
+
+    uuid_unparse_lower(uuid, uuidString);
+    return RAND_UUID_OK;
+
+#else
+    uint8_t uuid[UUID_SIZE];
+    OCGenerateUuid(uuid);
+
+    return OCConvertUuidToString(uuid, uuidString);
+#endif
+}
+
+OCRandomUuidResult OCConvertUuidToString(const uint8_t uuid[UUID_SIZE],
+                                         char uuidString[UUID_STRING_SIZE])
+{
+    if (uuid == NULL || uuidString == NULL)
+    {
+        return RAND_UUID_INVALID_PARAM;
+    }
+
+
+    int ret = snprintf(uuidString, UUID_STRING_SIZE,
+            "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+            uuid[0], uuid[1], uuid[2], uuid[3],
+            uuid[4], uuid[5], uuid[6], uuid[7],
+            uuid[8], uuid[9], uuid[10], uuid[11],
+            uuid[12], uuid[13], uuid[14], uuid[15]
+            );
+
+    if (ret != UUID_STRING_SIZE - 1)
+    {
+        return RAND_UUID_CONVERT_ERROR;
+    }
+
+    return RAND_UUID_OK;
+}
diff --git a/resource/csdk/ocrandom/test/SConscript b/resource/csdk/ocrandom/test/SConscript
new file mode 100644 (file)
index 0000000..ab221cd
--- /dev/null
@@ -0,0 +1,72 @@
+#******************************************************************
+#
+# 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
+randomtest_env = env.Clone()
+
+src_dir = randomtest_env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+randomtest_env.PrependUnique(CPPPATH = [
+        '../include',
+               '../../logger/include',
+               '../../ocmalloc/include',
+               '../../../oc_logger/include',
+               '../../../../extlibs/gtest/gtest-1.7.0/include'
+               ])
+
+randomtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+randomtest_env.AppendUnique(LIBS = ['-lpthread'])
+randomtest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+randomtest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
+randomtest_env.PrependUnique(LIBS = ['m',
+                                    'octbstack',
+                                    'uuid',
+                                    'gtest',
+                                    'gtest_main'])
+
+
+if env.get('LOGGING'):
+       randomtest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+randomtests = randomtest_env.Program('randomtests', ['linux/randomtest.cpp'])
+
+Alias("test", [randomtests])
+
+env.AppendTarget('test')
+if env.get('TEST') == '1':
+       target_os = env.get('TARGET_OS')
+       if target_os == 'linux':
+               out_dir = env.get('BUILD_DIR')
+               result_dir = env.get('BUILD_DIR') + '/test_out/'
+               if not os.path.isdir(result_dir):
+                       os.makedirs(result_dir)
+               randomtest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
+               randomtest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+               randomtest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
+               ut = randomtest_env.Command ('ut', None, 'valgrind -q --leak-check=full --xml=yes --xml-file=resource_csdk_random_test.memcheck ' + out_dir + 'resource/csdk/ocrandom/test/randomtests')
+               AlwaysBuild ('ut')
diff --git a/resource/csdk/ocrandom/test/android/makefile b/resource/csdk/ocrandom/test/android/makefile
deleted file mode 100644 (file)
index 6f3f564..0000000
+++ /dev/null
@@ -1,130 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=release`
-# default to debug build
-BUILD := debug
-
-# You must create the file "local.propertiessudo" on your local machine which contains any local paths, etc
-# local_settings.mk should NOT be committed to repo
-include ../../local.properties
-# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties
-#  Example:
-# GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
-
-GTEST_DIR := $(GTEST_DIR_ANDROID)
-
-# NOTE:  to run app, make sure that LD_LIBRARY_PATH env variable
-#        contains $(GTEST_DIR)/lib/.libs
-
-CC := $(ANDROID_NDK)/arm-linux-androideabi-gcc
-CXX    := $(ANDROID_NDK)/arm-linux-androideabi-g++
-
-PROG := randomtest
-
-SRC_DIR := ../../src
-TEST_DIR:= ../../test/android
-INC_DIR := ../../include
-
-#CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -D TB_LOG
-CC_FLAGS.debug := -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -D TB_LOG
-#CC_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c99 -fpic 
-CC_FLAGS := $(CC_FLAGS.$(BUILD))
-
-#CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -D TB_LOG
-CXX_FLAGS.debug := -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -D TB_LOG
-#CXX_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -fpic 
-CXX_FLAGS := $(CXX_FLAGS.$(BUILD))
-
-CFLAGS_ANDROID :=  -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -DGTEST_HAS_PTHREAD=0
-
-INC    := -I$(SRC_DIR)  
-INC += -I$(TEST_DIR)
-INC += -I$(INC_DIR)
-INC += -I$(GTEST_DIR)/include
-
-
-# using make's computed variables to select object and bin folders
-# depending on the build type
-OBJ_DIR.debug := ./obj/debug
-OBJ_DIR.release := ./obj/release
-OBJ_DIR := $(OBJ_DIR.$(BUILD))
-
-BIN_DIR.debug := ./bin/debug
-BIN_DIR.release := ./bin/release
-BIN_DIR := $(BIN_DIR.$(BUILD))
-
-C_FILES := $(wildcard $(SRC_DIR)/*.c)
-#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp)
-CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp)
-OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o)))
-H_FILES := $(wildcard $(TEST_DIR)/*.h)
-H_FILES += $(wildcard $(INC_DIR)/*.h)
-LD_FLAGS := -L/usr/lib
-LD_FLAGS += -L$(GTEST_DIR)/lib/.libs
-LDFLAGS_ANDROID := -march=armv7-a -Wl,--fix-cortex-a8
-
-#LIBS := -lpthread
-#LIBS := -lgtest
-#LIBS += -lgtest_main
-
-LIBS = $(GTEST_DIR)/lib/.libs/libgtest.a $(GTEST_DIR)/lib/.libs/libgtest_main.a
-#LIBS = libgtest.a libgtest_main.a
-
-all: $(PROG)
-       
-$(PROG): $(OBJ_FILES)  
-       mkdir -p $(BIN_DIR)
-       $(CXX) -o $@ $^ $(LD_FLAGS) $(LDFLAGS_ANDROID) $(LIBS)  
-       mv ./$(PROG) ./$(BIN_DIR)
-
-$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES)
-       mkdir -p $(OBJ_DIR)
-       $(CC) $(CC_FLAGS) $(CFLAGS_ANDROID) $(INC) -c -o $@ $<
-
-$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES)
-       mkdir -p $(OBJ_DIR)
-       $(CXX) $(CXX_FLAGS) $(CFLAGS_ANDROID) $(INC) -c -o $@ $<
-
-install: all
-#      adb remount
-       adb push $(BIN_DIR)/$(PROG) /data/local/tmp
-       
-.PHONY: clean
-clean :
-       rm -rf ./obj/debug/*
-       rm -rf ./obj/release/*
-       rm -rf ./lib/debug/*
-       rm -rf ./lib/release/*
-       rm -rf ./bin/debug/*
-       rm -rf ./bin/release/*
-       rm -rf ./test/tst_*.txt
-
-
-.PHONY: print_vars
-
-print_vars:
-       @echo ""
-       @echo 'BUILD     = '$(value BUILD)
-       @echo 'INC       = '$(value INC)
-       @echo 'CPP_FILES = '$(value CPP_FILES)
-       @echo 'LIBS      = '$(value LIBS)
-       
-
index 6dd8e7f..9f22173 100644 (file)
@@ -63,3 +63,43 @@ TEST(RandomGeneration,OCFillRandomMem) {
     EXPECT_EQ((uint8_t )0, array[ARR_SIZE - 1]);
 }
 
+TEST(RandomGeneration, OCGenerateUuid)
+{
+    EXPECT_EQ(RAND_UUID_INVALID_PARAM, OCGenerateUuid(NULL));
+
+    uint8_t uuid[16] = {};
+
+    EXPECT_EQ(RAND_UUID_OK, OCGenerateUuid(uuid));
+
+    EXPECT_FALSE(uuid[0] == '0' && uuid[1] == '0' &&
+                 uuid[2] == '0' && uuid[3] == '0' &&
+                 uuid[4] == '0' && uuid[5] == '0' &&
+                 uuid[6] == '0' && uuid[7] == '0' &&
+                 uuid[8] == '0' && uuid[9] == '0' &&
+                 uuid[10] == '0' && uuid[11] == '0' &&
+                 uuid[12] == '0' && uuid[13] == '0' &&
+                 uuid[14] == '0' && uuid[15] == '0');
+}
+
+TEST(RandomGeneration, OCGenerateUuidString)
+{
+    EXPECT_EQ(RAND_UUID_INVALID_PARAM, OCGenerateUuidString(NULL));
+
+    char uuidString[37] ={};
+
+    EXPECT_EQ(RAND_UUID_OK, OCGenerateUuidString(uuidString));
+    EXPECT_EQ(0, uuidString[36]);
+    EXPECT_EQ('-', uuidString[8]);
+    EXPECT_EQ('-', uuidString[13]);
+    EXPECT_EQ('-', uuidString[18]);
+    EXPECT_EQ('-', uuidString[23]);
+
+    for(int i = 0; i < 36; ++i)
+    {
+        EXPECT_TRUE(
+                i == 8 || i == 13 || i == 18 || i == 23 ||
+                (uuidString[i] >= 'a' && uuidString[i] <= 'f') ||
+                (uuidString[i] >= '0' && uuidString[i] <= '9'))
+                << "UUID Character out of range: "<< uuidString[i];
+    }
+}
diff --git a/resource/csdk/ocrandom/test/arduino/makefile b/resource/csdk/ocrandom/test/arduino/makefile
deleted file mode 100644 (file)
index c0713e0..0000000
+++ /dev/null
@@ -1,161 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# Override with `make BUILD=release`
-# default to debug build
-BUILD := debug
-PLATFORM := arduinomega
-
-# You must create the file "local.propertiessudo" on your local machine which contains any local paths, etc
-# local_settings.mk should NOT be committed to repo
-ROOT_DIR = ../../..
-include $(ROOT_DIR)/local.properties
-
-# Compilers                   
-CC := avr-gcc
-CXX    := avr-g++
-AR := avr-ar
-OBJCopy := avr-objcopy
-
-# Name of testing application
-PROG := randomtest
-C_COMPONENTS_DIR := ocrandom
-
-# Folders that contain C source code
-C_SRC_DIR := $(foreach d, $(C_COMPONENTS_DIR),../../../$d/src)
-
-#Folders that contain C source code related to arduino
-C_SRC_DIR_ARDUINO := $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-
-#Folders that contain CPP source code
-CPP_SRC_DIR := ../../test/arduino
-
-#Folders that contain CPP source code related to arduino
-CPP_SRC_DIR_ARDUINO := $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-
-# Folders that contain Headers
-TEMP_INC_DIR := $(foreach d, $(C_COMPONENTS_DIR),../../../$d/include)
-TEMP_INC_DIR2 := $(foreach d, $(CXX_COMPONENTS_DIR),../../../$d/include)
-INC_DIR := $(TEMP_INC_DIR) $(TEMP_INC_DIR2)
-INC_DIR += $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-INC_DIR += $(ARDUINO_DIR)/hardware/arduino/variants/mega
-INC_CMD = $(foreach d, $(INC_DIR), -I$d)
-
-# Compiler flags specific to arduino
-ARDUINO_FLAGS = -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -MMD
-
-# Compiler flags
-CC_FLAGS.debug := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -std=c99 -DATMEGA2560 -DTB_LOG
-CC_FLAGS.release := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -std=c99 -DATMEGA2560
-CC_FLAGS := $(CC_FLAGS.$(BUILD))
-
-CXX_FLAGS.debug := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 -DTB_LOG
-CXX_FLAGS.release := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560
-CXX_FLAGS := $(CXX_FLAGS.$(BUILD))
-
-# using make's computed variables to select object and bin folders
-# depending on the build type
-OBJ_DIR.debug := ./obj/debug
-OBJ_DIR.release := ./obj/release
-OBJ_DIR := $(OBJ_DIR.$(BUILD))
-
-BIN_DIR.debug := ./bin/debug
-BIN_DIR.release := ./bin/release
-BIN_DIR := $(BIN_DIR.$(BUILD))
-
-C_FILES := $(shell find $(C_SRC_DIR) -maxdepth 1 -name '*.c')
-CPP_FILES := $(shell find $(CPP_SRC_DIR) -maxdepth 1 -name '*.cpp')
-OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o)))
-
-C_FILES_ARDUINO := $(shell find $(C_SRC_DIR_ARDUINO) -maxdepth 1 -name '*.c')
-CPP_FILES_ARDUINO := $(shell find $(CPP_SRC_DIR_ARDUINO) -maxdepth 1 -name '*.cpp')
-OBJ_FILES_ARDUINO := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES_ARDUINO:.cpp=.o) $(C_FILES_ARDUINO:.c=.o)))
-
-all: $(BIN_DIR)/$(PROG).hex
-
-$(BIN_DIR)/core.a: $(OBJ_FILES_ARDUINO)
-       mkdir -p $(BIN_DIR)
-       $(AR) rcs $@ $^
-       #mv ./core.a ./$(BIN_DIR)
-       @echo ""
-       @echo 'done making core.a'
-
-$(OBJ_DIR)/%.o: $(CPP_SRC_DIR_ARDUINO)/%.cpp
-       mkdir -p $(OBJ_DIR)
-       $(CXX) $(CXX_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@
-
-$(OBJ_DIR)/%.o: $(CPP_SRC_DIR)/%.cpp
-       mkdir -p $(OBJ_DIR)
-       $(CXX) $(CXX_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@
-
-$(OBJ_DIR)/%.o: $(C_SRC_DIR_ARDUINO)/%.c
-       mkdir -p $(OBJ_DIR)
-       $(CC) $(CC_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@
-
-$(OBJ_DIR)/%.o: $(C_SRC_DIR)/%.c
-       mkdir -p $(OBJ_DIR)
-       $(CXX) $(CXX_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@
-
-$(BIN_DIR)/$(PROG).elf: $(OBJ_FILES) $(BIN_DIR)/core.a
-       #$(CC) -Os -Wl,--gc-sections,--relax $(ARDUINO_FLAGS) $< $(BIN_DIR)/core.a -lm -o $@
-       #$(CC) -Os -Wl,--gc-sections,--relax $(ARDUINO_FLAGS) $(OBJ_FILES) $(OBJ_FILES_ARDUINO) -lm -o $@
-       $(CC) -Os -Wl,--gc-sections,--relax $(ARDUINO_FLAGS) $(OBJ_FILES) $(BIN_DIR)/core.a -lm -o $@
-       @echo ""
-       @echo 'done making elf'
-
-$(BIN_DIR)/$(PROG).hex: $(BIN_DIR)/$(PROG).elf
-       $(OBJCopy) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(BIN_DIR)/$(PROG).eep
-       $(OBJCopy) -O ihex -R .eeprom $< $@
-       @echo ""
-       @echo 'done making hex'
-
-install: all
-       #$(ARDUINO_DIR)/hardware/tools/avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/ttyACM0 -b115200 -D -Uflash:w:$(BIN_DIR)/$(PROG).hex:i
-       avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/ttyACM0 -b115200 -D -Uflash:w:$(BIN_DIR)/$(PROG).hex:i
-
-.PHONY: clean
-clean :
-       rm -rf ./obj/debug/*
-       rm -rf ./obj/release/*
-       rm -rf ./lib/debug/*
-       rm -rf ./lib/release/*
-       rm -rf ./bin/debug/*
-       rm -rf ./bin/release/*
-       rm -rf ./test/tst_*.txt
-       rm -fr $(BIN_DIR)
-       rm -fr $(OBJ_DIR)
-
-
-.PHONY: print_vars
-print_vars:
-       @echo ""
-       @echo 'BUILD                = '$(value BUILD)
-       @echo 'C_SRC_DIR            = '$(value C_SRC_DIR)
-       @echo 'C_SRC_DIR_ARDUINO    = '$(value C_SRC_DIR_ARDUINO)
-       @echo 'CPP_SRC_DIR          = '$(CPP_SRC_DIR)
-       @echo 'CPP_SRC_DIR_ARDUINO  = '$(value CPP_SRC_DIR_ARDUINO)
-       @echo 'INC_DIR              = '$(INC_DIR)
-       @echo 'H_FILES              = '$(H_FILES)
-       @echo 'C_FILES              = '$(C_FILES)
-       @echo 'CPP_FILES            = '$(CPP_FILES)
-       @echo 'C_FILES_ARDUINO      = '$(C_FILES_ARDUINO)
-       @echo 'CPP_FILES_ARDUINO    = '$(CPP_FILES_ARDUINO)
-       @echo 'OBJ_FILES            = '$(OBJ_FILES)
-       @echo 'OBJ_FILES_ARDUINO    = '$(OBJ_FILES_ARDUINO)
diff --git a/resource/csdk/ocrandom/test/linux/makefile b/resource/csdk/ocrandom/test/linux/makefile
deleted file mode 100644 (file)
index d5a92ff..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=release`
-# default to debug build
-BUILD := debug
-PLATFORM := linux
-
-# You must create the file "local.propertiessudo" on your local machine which contains any local paths, etc
-# local_settings.mk should NOT be committed to repo
-ROOT_DIR = ../../..
-include $(ROOT_DIR)/local.properties
-# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties
-#  Example:
-#  GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
-
-# NOTE:  to run app, make sure that LD_LIBRARY_PATH env variable
-#        contains $(GTEST_DIR)/lib/.libs
-                                
-CC := gcc
-CXX    := g++
-
-PROG := randomtest
-
-SRC_DIR := ../../src
-TEST_DIR:= ../../test/linux
-INC_DIR := ../../include
-
-CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -D TB_LOG
-CC_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c99 -fpic 
-CC_FLAGS := $(CC_FLAGS.$(BUILD))
-
-CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -D TB_LOG
-CXX_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -fpic 
-CXX_FLAGS := $(CXX_FLAGS.$(BUILD))
-
-INC    := -I$(SRC_DIR)  
-INC += -I$(TEST_DIR)
-INC += -I$(INC_DIR)
-INC += -I$(GTEST_DIR)/include
-
-
-# using make's computed variables to select object and bin folders
-# depending on the build type
-OBJ_DIR.debug := ./obj/debug
-OBJ_DIR.release := ./obj/release
-OBJ_DIR := $(OBJ_DIR.$(BUILD))
-
-BIN_DIR.debug := ./bin/debug
-BIN_DIR.release := ./bin/release
-BIN_DIR := $(BIN_DIR.$(BUILD))
-
-C_FILES := $(wildcard $(SRC_DIR)/*.c)
-#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp)
-CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp)
-OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o)))
-H_FILES := $(wildcard $(TEST_DIR)/*.h)
-H_FILES += $(wildcard $(INC_DIR)/*.h)
-LD_FLAGS := -L/usr/lib
-LD_FLAGS += -L$(GTEST_DIR)/lib/.libs
-
-
-LIBS := -lpthread
-LIBS += -lgtest
-LIBS += -lgtest_main
-
-
-all: $(PROG)
-       
-$(PROG): $(OBJ_FILES)  
-       mkdir -p $(BIN_DIR)
-       $(CXX) -o $@ $^ $(LD_FLAGS) $(LIBS)     
-#      $(CXX) -o $@ $^ $(GTEST_DIR)/make/gtest_main.a -lpthread
-       mv ./$(PROG) ./$(BIN_DIR)
-
-#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(SRC_DIR)/%.h $(H_FILES)
-#      $(CC) $(CC_FLAGS) $(INC) -c -o $@ $<
-
-$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES)
-       mkdir -p $(OBJ_DIR)
-       $(CC) $(CC_FLAGS) $(INC) -c -o $@ $<
-
-$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES)
-       mkdir -p $(OBJ_DIR)
-       $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $<
-
-       
-.PHONY: clean
-clean :
-       rm -rf ./obj/debug/*
-       rm -rf ./obj/release/*
-       rm -rf ./lib/debug/*
-       rm -rf ./lib/release/*
-       rm -rf ./bin/debug/*
-       rm -rf ./bin/release/*
-       rm -rf ./test/tst_*.txt
-
-
-.PHONY: print_vars
-
-print_vars:
-       @echo ""
-       @echo 'BUILD     = '$(value BUILD)
-       @echo 'INC       = '$(value INC)
-       @echo 'CPP_FILES = '$(value CPP_FILES)
-       @echo 'LIBS      = '$(value LIBS)
-       
-
index 46fde03..98a1d5c 100644 (file)
@@ -64,3 +64,43 @@ TEST(RandomGeneration,OCFillRandomMem) {
     EXPECT_EQ((uint8_t )0, array[ARR_SIZE - 1]);
 }
 
+TEST(RandomGeneration, OCGenerateUuid)
+{
+    EXPECT_EQ(RAND_UUID_INVALID_PARAM, OCGenerateUuid(NULL));
+
+    uint8_t uuid[16] = {};
+
+    EXPECT_EQ(RAND_UUID_OK, OCGenerateUuid(uuid));
+
+    EXPECT_FALSE(uuid[0] == '0' && uuid[1] == '0' &&
+                 uuid[2] == '0' && uuid[3] == '0' &&
+                 uuid[4] == '0' && uuid[5] == '0' &&
+                 uuid[6] == '0' && uuid[7] == '0' &&
+                 uuid[8] == '0' && uuid[9] == '0' &&
+                 uuid[10] == '0' && uuid[11] == '0' &&
+                 uuid[12] == '0' && uuid[13] == '0' &&
+                 uuid[14] == '0' && uuid[15] == '0');
+}
+
+TEST(RandomGeneration, OCGenerateUuidString)
+{
+    EXPECT_EQ(RAND_UUID_INVALID_PARAM, OCGenerateUuidString(NULL));
+
+    char uuidString[37] = {};
+
+    EXPECT_EQ(RAND_UUID_OK, OCGenerateUuidString(uuidString));
+    EXPECT_EQ('\0', uuidString[36]);
+    EXPECT_EQ('-', uuidString[8]);
+    EXPECT_EQ('-', uuidString[13]);
+    EXPECT_EQ('-', uuidString[18]);
+    EXPECT_EQ('-', uuidString[23]);
+
+    for(int i = 0; i < 36; ++i)
+    {
+        EXPECT_TRUE(
+                i == 8 || i == 13 || i == 18 || i == 23 ||
+                (uuidString[i] >= 'a' && uuidString[i] <= 'f') ||
+                (uuidString[i] >= '0' && uuidString[i] <= '9'))
+                << "UUID Character out of range: "<< uuidString[i];
+    }
+}
diff --git a/resource/csdk/ocsocket/README.txt b/resource/csdk/ocsocket/README.txt
deleted file mode 100644 (file)
index 61dc001..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
--------------------------------------------------------------------------------
-  NOTICE - Transition to SCONS
--------------------------------------------------------------------------------
-
-The IoTivity build system is transitioning to SCONS. Although the 
-makefiles are still available (until v1.0) and some developers are 
-still using them, they are currently no longer supported. To learn more 
-about building using SCONS see Readme.scons.txt in the repository root 
-directory. The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
--------------------------------------------------------------------------------
-
-To compile for Linux or Android, include ocsocket.c and ocsocket.h in your project.
-Look at the Makefile in ocsocket/test/linux and ocsocket/test/android for compilation dependencies.
-
-To compile for Arduino, include ocsocket_arduino.cpp and ocsocket.h in your project.
-Look at the Makefile in ocsocket/test/arduino for compilation dependencies.
-Note: Patch your Arduino Ethernet Shield library for arduino/libraries/Ethernet/utility/socket.cpp
-to fix recvfrom issue.
-
-Place appropriate local.properties file under test directory to provide local path for \
-GTEST libraries/header files to compile tests.
-
-#Sample local.properties file
-GTEST_LINUX_DIR = /home/gtest-1.7.0
-GTEST_ANDROID_DIR = /home/gtest-1.7.0_android/gtest-1.7.0
-ARDUINO_DIR = /usr/share/arduino
diff --git a/resource/csdk/ocsocket/include/ocsocket.h b/resource/csdk/ocsocket/include/ocsocket.h
deleted file mode 100644 (file)
index 9bad9ed..0000000
+++ /dev/null
@@ -1,321 +0,0 @@
-//******************************************************************
-///
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef _OCSOCKET_H
-#define _OCSOCKET_H
-
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**@mainpage
- *
- * This module is a part of Open Communication Thin-Block SDK.
- */
-
-
-/**@defgroup socket Socket Interface
- *
- * This Socket interface  needs to be implemented for every platform on
- * which CCF TB stack is expected to run. If some functionality is not
- * available on a platform, implement the method by returning error
- * ERR_NOT_IMPLEMENTED.
- */
-
-#define ERR_SUCCESS          (0)
-#define ERR_INVALID_INPUT    (-900)
-#define ERR_UNKNOWN          (-901)
-#define ERR_NOT_IMPLEMENTED  (-903)
-
-
-/** This would need to be modified for specific platforms and specific
- *  technologies
- */
-#define DEV_ADDR_SIZE_MAX (16)
-
-/**
- *IPv4 or IPv6 addresses
- */
-#ifndef AF_INET
-#define AF_INET (2)
-#endif //AF_INET
-
-#ifndef AF_INET6
-#define AF_INET6 (10)
-#endif //AF_INET6
-
-
-/**
- * Data structure to encapsulate IPv4/IPv6/Contiki/lwIP device addresses
- *
-*/
-#pragma pack(push, 1)
-typedef struct OCDevAddr {
-    uint32_t     size;                    /**< length of the address stored in addr field. */
-    uint8_t      addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
-}OCDevAddr;
-#pragma pack(pop)
-
-//-- OCInitNetworkStack -----------------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to perform any platform specific network
- * initialization. Optional to implement.
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCInitNetworkStack();
-
-typedef enum
-{
-    OC_SOCKET_NOOPTION = 0,
-    OC_SOCKET_REUSEADDR
-} OC_SOCKET_OPTION;
-
-//-- OCInitUDP -----------------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to create a new platform specific UDP socket and binds
- * it to the address provided.
- *
- * @param[in] ipAddr
- *              device address with which the new socket will be bind.
- * @param[out] sockfd
- *              reference to the new socket.
- * @param[in] sockoption
- *              specifies which socket option to be used.
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t* sockfd, OC_SOCKET_OPTION sockoption);
-
-
-
-//-- OCInitUDPMulticast --------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to create a new platform specific UDP socket for
- * multicast and and binds it to the address provided.
- *
- * @param[in] ipmcastaddr
- *              multicast address to which IGMP membership be added.
- * @param[out] sockfd
- *              reference to the new socket.
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCInitUDPMulticast(OCDevAddr* ipmcastaddr, int32_t* sockfd);
-
-
-
-//-- OCSendTo -------------------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to transmit a UDP datagram to another endpoint.
- *
- * @param[in] sockfd
- *              socket to be used for sending the datagram.
- * @param[in] buf
- *              datagram buffer.
- * @param[in] bufLen
- *              length of above buffer.
- * @param[in] flags
- *              flags to be used for sending datagram.
- * @param[in] addr
- *              endpoint to which datagram needs to be send.
- *
- * @retval On Success, it returns the number of bytes send, otherwise
- *          some negative value.
- */
-//------------------------------------------------------------------------
-int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * addr);
-
-
-//-- OCRecvFrom ------------------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to retrieve a UDP datagram from the socket.
- *
- * @param[in] sockfd
- *              socket to be used for retrieving the datagram.
- * @param[in] buf
- *              datagram buffer.
- * @param[in] bufLen
- *              length of above buffer.
- * @param[in] flags
- *              flags to be used for receiving datagram.
- * @param[out] addr
- *              endpoint from which datagram has been received.
- *
- * @retval On Success, it returns the number of bytes read from the socket,
- *          otherwise some negative value.
- */
-//------------------------------------------------------------------------
-int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * addr);
-
-//-- OCClose ---------------------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to close the platform specific socket and release any
- * system resources associated with it.
- *
- * @param[in] sockfd
- *              socket to be closed.
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCClose(int32_t sockfd);
-
-
-//Utility methods
-//-- OCBuildIPv4Address -------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to create the IPv4 dev_addr structure.
- *
- * @param[in]  a first byte of IPv4 address.
- * @param[in]  b second byte of IPv4 address.
- * @param[in]  c third byte of IPv4 address.
- * @param[in]  d fourth byte of IPv4 address.
- * @param[in]  port port number.
- * @param[out] ipAddr
- *              dev_addr to be filled with above data.
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
-            uint16_t port, OCDevAddr *ipAddr);
-
-
-//-- OCGetInterfaceAddress ------------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to retrieved the IPv4/IPv6 address of the local interface.
- * If no interface name is provided, this API retrieves the IP address of
- * the default interface.
- *
- * @note currently, only IPv4(AF_INET) is supported for addrType argument.
- *
- * @param[in]  ifName
- *              interface whose address needs to be retrieved.
- * @param[in]  ifNameLen
- *              length of the interface name
- * @param[in]  addrType
- *              IPv4 or IPv6
- * @param[out] addrv4
- *              IPv4 address in a.b.c.d format
- * @param[in]  addrLen
- *              size of the buffer at addrv4. Should be at least 16 bytes for an
- *              IPv4 address.
- *
- * @retval 0 for Success, otherwise some error value
- */
-//-------------------------------------------------------------------------------
-int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType,
-             uint8_t *addrv4,  uint32_t addrLen);
-
-
-//-- OCDevAddrToString ----------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to convert the OCDevAddr to string format
- *
- * @param[in]   addr
- *               OCDevAddr address.
- * @param[out]  stringAddress the target string where the address
- *               is to be stored. Memory for this parameter is
- *               allocated by the caller.
- *
- * Note: The length of stringAddress may not exceed DEV_ADDR_SIZE_MAX
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCDevAddrToString(OCDevAddr *addr, char *stringAddress);
-
-
-//-- OCDevAddrToIPv4Addr -------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to retrieved the IPv4 address from OCDev address
- * data structure.
- *
- * @param[in]  ipAddr
- *              OCDevAddr address.
- * @param[out]  a first byte of IPv4 address.
- * @param[out]  b second byte of IPv4 address.
- * @param[out]  c third byte of IPv4 address.
- * @param[out]  d fourth byte of IPv4 address.
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
-            uint8_t *c, uint8_t *d );
-
-
-//-- OCDevAddrToPort -------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to retrieve the port number from OCDev address
- * data structure.
- *
- * @param[in]  ipAddr
- *              OCDevAddr address.
- * @param[out] port
- *              port number
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port);
-
-
-//-- OCGetSocketInfo -----------------------------------------------------
-/** @ingroup ocsocket
- *
- * This method is used to retrieve the port number to which the @p sockfd
- * is bound.
- *
- * @param[in]  sockfd
- *              socket whose port needs to be retrieved
- * @param[out] port
- *              port number
- *
- * @retval 0 for Success, otherwise some error value
- */
-//------------------------------------------------------------------------
-int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port);
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-#endif //_OCSOCKET_H
diff --git a/resource/csdk/ocsocket/src/ocsocket.c b/resource/csdk/ocsocket/src/ocsocket.c
deleted file mode 100644 (file)
index fb4b700..0000000
+++ /dev/null
@@ -1,433 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <math.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <net/if.h>
-#include <errno.h>
-
-#ifdef __ANDROID__
-#include <sys/ioctl.h>
-#else
-#include <ifaddrs.h>
-#endif
-
-#include <logger.h>
-#include <ocsocket.h>
-
-/// Module Name
-#define MOD_NAME ("ocsocket")
-
-/// Macro to verify the validity of input argument
-#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, MOD_NAME, #arg " is NULL"); return ERR_INVALID_INPUT;} }
-
-/// Builds a socket interface address using IP address and port number
-int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port, OCDevAddr *ipAddr)
-{
-    struct sockaddr_in *sa;
-    uint32_t ip = a;
-
-    VERIFY_NON_NULL(ipAddr);
-    memset(ipAddr, 0, sizeof(OCDevAddr));
-
-    ip <<= 8;
-    ip |= b;
-    ip <<= 8;
-    ip |= c;
-    ip <<= 8;
-    ip |= d;
-
-    ipAddr->size = sizeof(struct sockaddr_in);
-    sa = (struct sockaddr_in*)ipAddr->addr;
-    sa->sin_family = AF_INET;
-    sa->sin_addr.s_addr = htonl(ip);
-    sa->sin_port = htons(port);
-
-    return ERR_SUCCESS;
-}
-
-#ifdef __ANDROID__
-/// Retrieves the IP address assigned to specified wireless interface
-int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType,
-             uint8_t *addr,  uint32_t addrLen)
-{
-    int32_t ret = ERR_UNKNOWN;
-    int32_t sfd = 0xFFFFFFFF;
-    struct ifreq ifr;
-
-    VERIFY_NON_NULL(addr);
-    VERIFY_NON_NULL(ifName);
-    if (ifNameLen > (IFNAMSIZ - 1) ) {
-        return ERR_INVALID_INPUT;
-    }
-    if (addrType != AF_INET) {
-        return ERR_INVALID_INPUT;
-    }
-
-    sfd = socket(addrType, SOCK_DGRAM, 0);
-    if (sfd < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "socket API ret val %d", sfd);
-        goto exit;
-    }
-
-    ifr.ifr_addr.sa_family = addrType;
-
-    strncpy(ifr.ifr_name, (const char*)ifName, ifNameLen);
-
-    if (ioctl(sfd, SIOCGIFADDR, &ifr) != 0) {
-        OC_LOG(FATAL, MOD_NAME, "ioctl call failed");
-        goto exit;
-    }
-
-    strncpy((char *)addr,
-            inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr),
-            addrLen);
-    ret = ERR_SUCCESS;
-
-exit:
-    if (sfd >= 0) {
-        close(sfd);
-    }
-    return ret;
-}
-
-#else
-/// Retrieves the IP address assigned to specified wireless interface
-int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType,
-             uint8_t *addr,  uint32_t addrLen)
-{
-    struct ifaddrs *myaddrs = NULL, *ifa = NULL;
-    int32_t ret = ERR_UNKNOWN;
-
-    VERIFY_NON_NULL(addr);
-
-    if (addrType != AF_INET) {
-        return ERR_INVALID_INPUT;
-    }
-
-    if(getifaddrs(&myaddrs) != 0) {
-        goto exit;
-    }
-
-    for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
-        if (ifa->ifa_addr == NULL)
-            continue;
-        if (!(ifa->ifa_flags & IFF_UP))
-            continue;
-        if (!(ifa->ifa_flags & IFF_RUNNING))
-            continue;
-
-        if (ifName && ifa->ifa_name) {
-           if(strncmp((const char*)ifName, ifa->ifa_name, ifNameLen) != 0)
-            continue;
-        }
-
-        switch (ifa->ifa_addr->sa_family)
-        {
-            case AF_INET:
-                {
-                    struct sockaddr_in *s4 = (struct sockaddr_in *)ifa->ifa_addr;
-                    if(inet_ntop(AF_INET, &(s4->sin_addr), (char *)addr, addrLen))
-                        ret = ERR_SUCCESS;
-                    goto exit;
-                }
-
-            default:
-                continue;
-        }
-    }
-
-exit:
-    if (myaddrs) {
-        freeifaddrs(myaddrs);
-    }
-    return ret;
-}
-#endif //__ANDROID__
-
-/// Creates a BSD socket and binds it specified port for UDP
-int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t *sockfd, OC_SOCKET_OPTION sockoption)
-{
-    int32_t ret = ERR_UNKNOWN;
-    int32_t sfd = 0xFFFFFFFF;
-    int set_option_on = 1;
-
-    VERIFY_NON_NULL(ipAddr);
-    VERIFY_NON_NULL(sockfd);
-
-    OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ );
-    //Create a datagram socket on which to recv/send.
-    sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
-    if (sfd < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "socket API ret val %d", sfd);
-        goto exit;
-    }
-
-    if(OC_SOCKET_REUSEADDR == sockoption)
-    {
-        if ((ret = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on,
-                    sizeof(set_option_on))) < 0) {
-            OC_LOG_V(FATAL, MOD_NAME, "setsockopt API failed with errno %s",
-                    strerror(errno));
-            goto exit;
-        }
-    }
-
-    if ((ret = bind(sfd, (struct sockaddr*)ipAddr->addr, ipAddr->size)) < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "bind API failed with errno %s", strerror(errno));
-        goto exit;
-    }
-
-    *sockfd = sfd;
-    ret = ERR_SUCCESS;
-
-exit:
-    if ((ret != ERR_SUCCESS) && (sfd >= 0)) {
-        close(sfd);
-    }
-
-    OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ );
-    return ret;
-}
-
-
-
-/// Creates a BSD socket and binds the specified port for UDP multicast.
-int32_t OCInitUDPMulticast(OCDevAddr* ipmcastaddr, int32_t* sockfd)
-{
-    int32_t ret = ERR_UNKNOWN;
-    int32_t sfd = 0xFFFFFFFF;
-    char loopch=1;
-    int set_option_on = 1;
-
-    VERIFY_NON_NULL(ipmcastaddr);
-    VERIFY_NON_NULL(sockfd);
-
-    OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ );
-    //Create a datagram socket on which to recv/send.
-    sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
-    if (sfd < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "socket API ret val %d", sfd);
-        goto exit;
-
-    }
-
-    if ((ret = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on,
-                sizeof(set_option_on))) < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "setsockopt API for SO_REUSEADDR failed with errno %s", strerror(errno));
-        goto exit;
-    }
-
-    // bind to multicast port
-    struct sockaddr_in sa = {0};
-    struct sockaddr_in *sin;
-
-    sin = (struct sockaddr_in *)(ipmcastaddr->addr);
-    sa.sin_family = AF_INET;
-    sa.sin_addr.s_addr = sin->sin_addr.s_addr;
-    sa.sin_port = sin->sin_port;
-
-    if ((ret = bind(sfd, (struct sockaddr*)&sa, sizeof(sa))) < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "bind API failed with errno %s", strerror(errno));
-        goto exit;
-    }
-
-    // add membership to receiving socket
-    struct ip_mreq mreq = {{0}};
-    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
-    mreq.imr_multiaddr.s_addr = sin->sin_addr.s_addr;
-    if ((ret = setsockopt(sfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq))) < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "setsockopt API for IP_ADD_MEMBERSHIP failed with errno %s", strerror(errno));
-        goto exit;
-    }
-
-    //Enable loopback so we can receive our own datagrams.
-    if ((ret = setsockopt(sfd, IPPROTO_IP, IP_MULTICAST_LOOP,
-                (char *)&loopch, sizeof(loopch))) < 0) {
-        OC_LOG_V(FATAL, MOD_NAME, "setsockopt API for IP_MULTICAST_LOOP failed with errno %s", strerror(errno));
-        goto exit;
-    }
-
-    ret = ERR_SUCCESS;
-
-exit:
-    if (ret == ERR_SUCCESS) {
-        *sockfd = sfd;
-    } else {
-        close(sfd);
-    }
-
-    OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ );
-    return ret;
-}
-
-
-
-/// Send data to requested end-point using UDP socket
-int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * ipAddr)
-{
-    int32_t ret;
-
-    VERIFY_NON_NULL(buf);
-    VERIFY_NON_NULL(ipAddr);
-
-    OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ );
-    ret = sendto(sockfd, buf, bufLen, flags,
-            (struct sockaddr*)ipAddr->addr, ipAddr->size);
-
-    OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ );
-    return ret;
-}
-
-
-/// Retrieve any available data from UDP socket. This is a non-blocking call.
-int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * ipAddr)
-{
-    int32_t ret = 0;
-
-    VERIFY_NON_NULL(buf);
-    VERIFY_NON_NULL(ipAddr);
-
-    struct timeval timeout;
-    timeout.tv_sec = 0;
-    timeout.tv_usec = 5000;
-    fd_set reads;
-
-    OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ );
-
-    FD_ZERO(&reads);
-    FD_SET(sockfd, &reads);
-    ret = select(sockfd + 1, &reads, NULL, NULL, &timeout);
-    if( ret < 0) {
-        OC_LOG(FATAL, MOD_NAME, "select API failed");
-        return ret;
-    }
-    if (!FD_ISSET(sockfd, &reads)) {
-        OC_LOG(DEBUG, MOD_NAME, "No data to read");
-        return ERR_SUCCESS;
-    }
-
-    // Read available data.
-    ret = recvfrom(sockfd, buf, bufLen, flags,
-            (struct sockaddr*)ipAddr->addr, (socklen_t*)&(ipAddr->size));
-    if (ret < 1) {
-        OC_LOG(FATAL, MOD_NAME, "OCRecvFrom ERR");
-    }
-    OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ );
-    return ret;
-}
-
-
-/// Close the socket and release all system resources.
-int32_t OCClose(int32_t sockfd)
-{
-    return (close(sockfd));
-}
-
-//convert OCDevAddr to String
-int32_t OCDevAddrToString(OCDevAddr* addr, char* stringAddress)
-{
-    uint8_t a;
-    uint8_t b;
-    uint8_t c;
-    uint8_t d;
-
-    if(OCDevAddrToIPv4Addr(addr, &a, &b, &c, &d) == 0)
-    {
-        if (!stringAddress)
-        {
-            return ERR_INVALID_INPUT;
-        }
-
-        snprintf(stringAddress, DEV_ADDR_SIZE_MAX, "%u.%u.%u.%u",
-                a, b, c, d);
-        return ERR_SUCCESS;
-    }
-    else
-    {
-        return ERR_INVALID_INPUT;
-    }
-}
-
-/// Retrieve the IPv4 address embedded inside OCDev address data structure
-int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
-            uint8_t *c, uint8_t *d )
-{
-    struct sockaddr_in *sa;
-    uint32_t ip;
-
-    if ( !ipAddr || !a || !b || !c || !d ) {
-        OC_LOG(FATAL, MOD_NAME, "Invalid argument");
-        return ERR_INVALID_INPUT;
-    }
-
-    sa = (struct sockaddr_in*)ipAddr->addr;
-    ip = ntohl(sa->sin_addr.s_addr);
-    *d = *((uint8_t*)&ip + 0);
-    *c = *((uint8_t*)&ip + 1);
-    *b = *((uint8_t*)&ip + 2);
-    *a = *((uint8_t*)&ip + 3);
-
-    return ERR_SUCCESS;
-}
-
-
-/// Retrieve the IPv4 address embedded inside OCDev address data structure
-int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
-{
-    struct sockaddr_in *sa;
-    if ( !ipAddr || !port ) {
-        OC_LOG(FATAL, MOD_NAME, "Invalid argument");
-        return ERR_INVALID_INPUT;
-    }
-
-    sa = (struct sockaddr_in*)ipAddr->addr;
-    *port = ntohs(sa->sin_port);
-
-    return ERR_SUCCESS;
-}
-
-/// Retrieve the port to which socket is bound
-int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port)
-{
-    int32_t ret = ERR_SUCCESS;
-
-    struct sockaddr_in sa;
-    socklen_t salen = sizeof(sa);
-    if (getsockname(sockfd, (struct sockaddr*)&sa, &salen) == 0) {
-        *port = ntohs(sa.sin_port);
-    } else {
-        OC_LOG_V(FATAL, MOD_NAME, "getsockname API failed with errno \
-            %s", strerror(errno));
-        ret = ERR_UNKNOWN;
-    }
-    return ret;
-}
diff --git a/resource/csdk/ocsocket/src/ocsocket_arduino.cpp b/resource/csdk/ocsocket/src/ocsocket_arduino.cpp
deleted file mode 100644 (file)
index ed51f79..0000000
+++ /dev/null
@@ -1,268 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <Arduino.h>
-#include <Ethernet.h>
-#include <socket.h>
-#include <w5100.h>
-#include <ocsocket.h>
-#include <EthernetUdp.h>
-#include <IPAddress.h>
-#include <logger.h>
-
-/// Ensures the literal string to be stored in Flash memory
-#define PCF(str) ((PROGMEM const char *)(F(str)))
-
-/// Module Name
-#define MOD_NAME PCF("ocsocket")
-
-/// Macro to verify the validity of input argument
-#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, MOD_NAME, "%s is NULL", #arg); \
-         return ERR_INVALID_INPUT;} }
-
-/// Length of the IP address decimal notation string
-#define IPNAMESIZE (16)
-
-/// IPv4 address representation for Arduino Ethernet Shield
-typedef struct {
-    uint32_t size;  /// size of IP address and port bytes
-    uint8_t a;
-    uint8_t b;
-    uint8_t c;
-    uint8_t d;
-    uint16_t port;
-} ArduinoAddr;
-
-
-/// Builds a socket interface address using IP address and port number
-int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port, OCDevAddr *ipAddr)
-{
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    VERIFY_NON_NULL(ardAddr);
-
-    memset(ardAddr, 0, sizeof(ArduinoAddr));
-
-    ardAddr->size =  sizeof(ArduinoAddr) - sizeof(ardAddr->size);
-    ardAddr-> a = a;
-    ardAddr-> b = b;
-    ardAddr-> c = c;
-    ardAddr-> d = d;
-    ardAddr-> port = port;
-
-    return ERR_SUCCESS;
-}
-
-
-/// Retrieves the IP address assigned to Arduino Ethernet shield
-int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType,
-             uint8_t *addr,  uint32_t addrLen)
-{
-    //TODO : Fix this for scenarios when this API is invoked when device is not connected
-    uint8_t rawIPAddr[4];
-    VERIFY_NON_NULL(addr);
-    if (addrLen < IPNAMESIZE) {
-        OC_LOG(FATAL, MOD_NAME, PCF("OCGetInterfaceAddress: addrLen MUST be atleast 16"));
-        return ERR_INVALID_INPUT;
-    }
-
-    if (addrType != AF_INET) {
-        return ERR_INVALID_INPUT;
-    }
-    W5100.getIPAddress(rawIPAddr);
-    snprintf((char *)addr, addrLen, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]);
-
-    OC_LOG_BUFFER(INFO, MOD_NAME, addr, addrLen);
-
-    return ERR_SUCCESS;
-}
-
-/// Retrieves a empty socket and bind it for UDP with the input port
-int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t* sockfd, OC_SOCKET_OPTION sockoption)
-{
-    uint8_t state;
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    VERIFY_NON_NULL(ardAddr);
-    VERIFY_NON_NULL(sockfd);
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP Begin"));
-    //Is any socket available to work with ?
-    *sockfd = -1;
-    for (int i = 0; i < MAX_SOCK_NUM; i++) {
-        state = W5100.readSnSR(i);
-        if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT) {
-            *sockfd = i;
-            break;
-        }
-    }
-
-    if ( *sockfd == -1) {
-        return ERR_UNKNOWN;
-    }
-
-    //Create a datagram socket on which to recv/send.
-    if (!socket(*sockfd, SnMR::UDP, ardAddr->port, 0)) {
-        return ERR_UNKNOWN;
-    }
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP End"));
-    return ERR_SUCCESS;
-}
-
-
-
-/// Retrieves a empty socket and bind it for UDP with the input multicast ip address/port
-int32_t OCInitUDPMulticast(OCDevAddr* ipMcastMacAddr, int32_t* sockfd)
-{
-    uint8_t state;
-    uint8_t mcastMacAddr[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00};
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipMcastMacAddr;
-
-    VERIFY_NON_NULL(ardAddr);
-    VERIFY_NON_NULL(sockfd);
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDPMulticast Begin"));
-    //Is any socket available to work with ?
-    *sockfd = -1;
-    for (int i = 0; i < MAX_SOCK_NUM; i++) {
-        state = W5100.readSnSR(i);
-        if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT) {
-            *sockfd = i;
-            break;
-        }
-    }
-
-    if ( *sockfd == -1) {
-        return ERR_UNKNOWN;
-    }
-
-    //Calculate Multicast MAC address
-    mcastMacAddr[3] = ardAddr->b & 0x7F;
-    mcastMacAddr[4] = ardAddr->c;
-    mcastMacAddr[5] = ardAddr->d;
-    W5100.writeSnDIPR(*sockfd, (uint8_t*)&(ardAddr->a));
-    W5100.writeSnDHAR(*sockfd, mcastMacAddr);
-    W5100.writeSnDPORT(*sockfd, ardAddr->port);
-
-    //Create a datagram socket on which to recv/send.
-    if (!socket(*sockfd, SnMR::UDP, ardAddr->port, SnMR::MULTI)) {
-        return ERR_UNKNOWN;
-    }
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDPMulticast End"));
-    return ERR_SUCCESS;
-}
-
-
-/// Send data to requested end-point using UDP socket
-int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * ipAddr)
-{
-    int32_t ret;
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    VERIFY_NON_NULL(buf);
-    VERIFY_NON_NULL(ardAddr);
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCSendTo Begin"));
-    ret = sendto( sockfd, buf, bufLen, (uint8_t*)&(ardAddr->a), ardAddr->port);
-    OC_LOG_V(DEBUG, MOD_NAME, "OCSendTo RetVal %d", ret);
-    return ret;
-}
-
-
-/// Retrieve any available data from UDP socket. This is a non-blocking call.
-int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * ipAddr)
-{
-    /**Bug : When there are multiple UDP packets in Wiznet buffer, W5100.getRXReceivedSize
-     * will not return correct length of the first packet.
-     * Fix : Use the patch provided for arduino/libraries/Ethernet/utility/socket.cpp
-     */
-    int32_t ret = 0;
-    uint16_t recvLen;
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    VERIFY_NON_NULL(buf);
-    VERIFY_NON_NULL(ardAddr);
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom Begin"));
-    recvLen = W5100.getRXReceivedSize(sockfd);
-    if (recvLen == 0) {
-        return recvLen;
-    }
-
-    // Read available data.
-    ret = recvfrom(sockfd, buf, bufLen, (uint8_t*)&(ardAddr->a), (uint16_t*)&(ardAddr->port));
-    ardAddr->size =  sizeof(ArduinoAddr) - sizeof(ardAddr->size);
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom End"));
-    return ret;
-}
-
-
-/// Close the socket and release all system resources.
-int32_t OCClose(int32_t sockfd)
-{
-    close(sockfd);
-    return ERR_SUCCESS;
-}
-
-
-/// Retrieve the IPv4 address embedded inside OCDev address data structure
-int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
-            uint8_t *c, uint8_t *d )
-{
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    if ( !ardAddr || !a || !b || !c || !d ) {
-        OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument"));
-        return ERR_INVALID_INPUT;
-    }
-
-    *a = ardAddr->a;
-    *b = ardAddr->b;
-    *c = ardAddr->c;
-    *d = ardAddr->d;
-
-    return ERR_SUCCESS;
-}
-
-
-/// Retrieve the IPv4 address embedded inside OCDev address data structure
-int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
-{
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    if ( !ardAddr || !port ) {
-        OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument"));
-        return ERR_INVALID_INPUT;
-    }
-
-    *port = ardAddr->port;
-
-    return ERR_SUCCESS;
-}
-
-/// Retrieve the port to which socket is bound
-int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port)
-{
-    return ERR_NOT_IMPLEMENTED;
-}
diff --git a/resource/csdk/ocsocket/src/ocsocket_arduino_wifi.cpp b/resource/csdk/ocsocket/src/ocsocket_arduino_wifi.cpp
deleted file mode 100644 (file)
index 37f5fe9..0000000
+++ /dev/null
@@ -1,306 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <logger.h>
-#include <ocsocket.h>
-#include <Arduino.h>
-#include <IPAddress.h>
-#include <WiFi.h>
-#include <utility/server_drv.h>
-#include <utility/wifi_drv.h>
-
-/// Module Name
-#define MOD_NAME PCF("ocsocket")
-
-/// Macro to verify the validity of input argument
-#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, MOD_NAME, "%s is NULL", #arg); \
-         return ERR_INVALID_INPUT;} }
-
-/// Length of the IP address decimal notation string
-#define IPNAMESIZE (16)
-
-/// This is the max buffer size between Arduino and WiFi Shield
-#define ARDUINO_WIFI_SPI_RECV_BUFFERSIZE (64)
-
-// Start offsets based on end of received data buffer
-#define WIFI_RECBUF_IPADDR_OFFSET  (6)
-#define WIFI_RECBUF_PORT_OFFSET    (2)
-
-#define WIFI_RECBUF_IPADDR_SIZE    (WIFI_RECBUF_IPADDR_OFFSET - WIFI_RECBUF_PORT_OFFSET)
-#define WIFI_RECBUF_PORT_SIZE      (WIFI_RECBUF_PORT_OFFSET - 0)
-#define WIFI_RECBUF_FOOTER_SIZE    (WIFI_RECBUF_IPADDR_SIZE + WIFI_RECBUF_PORT_SIZE)
-
-
-/// IPv4 address representation for Arduino Ethernet Shield
-typedef struct {
-    uint32_t size;  /// size of IP address and port bytes
-    uint8_t a;
-    uint8_t b;
-    uint8_t c;
-    uint8_t d;
-    uint16_t port;
-} ArduinoAddr;
-
-
-/// Builds a socket interface address using IP address and port number
-int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port, OCDevAddr *ipAddr)
-{
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    VERIFY_NON_NULL(ardAddr);
-
-    memset(ardAddr, 0, sizeof(ArduinoAddr));
-
-    ardAddr->size =  sizeof(ArduinoAddr) - sizeof(ardAddr->size);
-    ardAddr-> a = a;
-    ardAddr-> b = b;
-    ardAddr-> c = c;
-    ardAddr-> d = d;
-    ardAddr-> port = port;
-
-    return ERR_SUCCESS;
-}
-
-
-/// Retrieves the IP address assigned to Arduino Ethernet shield
-int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType,
-             uint8_t *addr,  uint32_t addrLen)
-{
-    WiFiClass WiFi;
-
-    VERIFY_NON_NULL(addr);
-    if (addrLen < IPNAMESIZE) {
-        OC_LOG(FATAL, MOD_NAME, PCF("OCGetInterfaceAddress: addrLen MUST be at least 16"));
-        return ERR_INVALID_INPUT;
-    }
-
-    if (addrType != AF_INET) {
-        return ERR_INVALID_INPUT;
-    }
-
-    IPAddress ip = WiFi.localIP();
-    snprintf((char *)addr, addrLen, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
-
-    OC_LOG_BUFFER(INFO, MOD_NAME, addr, addrLen);
-
-    return ERR_SUCCESS;
-}
-
-/// Retrieves a empty socket and bind it for UDP with the input port
-int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t* sockfd, OC_SOCKET_OPTION sockoption)
-{
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-    uint8_t sock;
-
-    VERIFY_NON_NULL(ardAddr);
-    VERIFY_NON_NULL(sockfd);
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP Begin"));
-    //Is any socket available to work with ?
-    *sockfd = -1;
-
-    sock = WiFiClass::getSocket();
-    if (sock != NO_SOCKET_AVAIL)
-    {
-        ServerDrv::startServer(ardAddr->port, sock, UDP_MODE);
-        WiFiClass::_server_port[sock] = ardAddr->port;
-        *sockfd = (int32_t)sock;
-    }
-
-    if (*sockfd == -1)
-    {
-        return ERR_UNKNOWN;
-    }
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP End"));
-    return ERR_SUCCESS;
-}
-
-
-
-/// Currently WiFi shield does NOT support multicast.
-int32_t OCInitUDPMulticast(OCDevAddr* ipMcastMacAddr, int32_t* sockfd)
-{
-    return OCInitUDP(ipMcastMacAddr, sockfd, OC_SOCKET_REUSEADDR);
-}
-
-
-/// Send data to requested end-point using UDP socket
-int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * ipAddr)
-{
-    int32_t ret = 0;
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-    uint32_t ip;
-    uint16_t rem, send;
-
-    VERIFY_NON_NULL(buf);
-    VERIFY_NON_NULL(ardAddr);
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCSendTo Begin"));
-
-    if (sockfd >= MAX_SOCK_NUM)
-    {
-        OC_LOG(ERROR, MOD_NAME, PCF("Invalid sockfd"));
-        return -1;
-    }
-
-    memcpy((uint8_t*)&ip, (uint8_t*)&(ardAddr->a), sizeof(ip));
-    ServerDrv::startClient(ip, ardAddr->port, (uint8_t)sockfd, UDP_MODE);
-
-    rem = bufLen;
-    do
-    {
-        send = (rem > ARDUINO_WIFI_SPI_RECV_BUFFERSIZE ) ? ARDUINO_WIFI_SPI_RECV_BUFFERSIZE : rem;
-        if (!ServerDrv::insertDataBuf((uint8_t)sockfd, buf, (uint16_t)send))
-        {
-            OC_LOG(ERROR, MOD_NAME, PCF("insertDataBuf error"));
-            ret = -1;
-            break;
-        }
-        rem = rem - send;
-        buf = buf + send;
-    }while(rem > 0);
-
-    if (ret != -1)
-    {
-        if (!ServerDrv::sendUdpData((uint8_t)sockfd))
-        {
-            OC_LOG(ERROR, MOD_NAME, PCF("sendUdpData error"));
-            ret = -1;
-        }
-        else
-        {
-            ret = bufLen;
-        }
-    }
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCSendTo End"));
-    return ret;
-}
-
-
-/// Retrieve any available data from UDP socket. This is a non-blocking call.
-int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags,
-            OCDevAddr * ipAddr)
-{
-
-    uint16_t recvLen;
-    uint16_t size = 0;
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    VERIFY_NON_NULL(buf);
-    VERIFY_NON_NULL(ardAddr);
-
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom Begin"));
-    if (sockfd >= MAX_SOCK_NUM)
-    {
-        OC_LOG(ERROR, MOD_NAME, PCF("Invalid sockfd"));
-        return -1;
-    }
-
-    recvLen = (int32_t)ServerDrv::availData((uint8_t)sockfd);
-    if (recvLen == 0)
-    {
-        return recvLen;
-    }
-
-    // Make sure buf is large enough for received data
-    if ((uint32_t)recvLen > bufLen)
-    {
-        OC_LOG(ERROR, MOD_NAME, PCF("Receive buffer too small"));
-        return -1;
-    }
-
-    if (!ServerDrv::getDataBuf((uint8_t)sockfd, buf, &size))
-    {
-        OC_LOG(ERROR, MOD_NAME, PCF("getDataBuf error"));
-        return -1;
-    }
-
-    // Read IP Address and Port from end of receive buffer
-    memcpy(&(ardAddr->a), &buf[size - WIFI_RECBUF_IPADDR_OFFSET], WIFI_RECBUF_IPADDR_SIZE);
-    // Change the endianness of the port number
-    *((uint8_t*)&(ardAddr->port)) = buf[size - (WIFI_RECBUF_PORT_OFFSET-1)];
-    *((uint8_t*)&(ardAddr->port) + 1) = buf[size - (WIFI_RECBUF_PORT_OFFSET)];
-
-    size -= WIFI_RECBUF_FOOTER_SIZE;
-
-    ardAddr->size =  sizeof(ArduinoAddr) - sizeof(ardAddr->size);
-    OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom End"));
-    return (int32_t)size;
-}
-
-
-/// Close the socket and release all system resources.
-int32_t OCClose(int32_t sockfd)
-{
-    if (sockfd >= MAX_SOCK_NUM)
-    {
-        OC_LOG(ERROR, MOD_NAME, PCF("Invalid sockfd"));
-        return -1;
-    }
-    ServerDrv::stopClient(sockfd);
-
-    WiFiClass::_server_port[sockfd] = 0;
-    WiFiClass::_state[sockfd] = NA_STATE;
-
-    return ERR_SUCCESS;
-}
-
-
-/// Retrieve the IPv4 address embedded inside OCDev address data structure
-int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
-            uint8_t *c, uint8_t *d )
-{
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    if ( !ardAddr || !a || !b || !c || !d ) {
-        OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument"));
-        return ERR_INVALID_INPUT;
-    }
-
-    *a = ardAddr->a;
-    *b = ardAddr->b;
-    *c = ardAddr->c;
-    *d = ardAddr->d;
-
-    return ERR_SUCCESS;
-}
-
-
-/// Retrieve the IPv4 address embedded inside OCDev address data structure
-int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
-{
-    ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr;
-
-    if ( !ardAddr || !port ) {
-        OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument"));
-        return ERR_INVALID_INPUT;
-    }
-
-    *port = ardAddr->port;
-
-    return ERR_SUCCESS;
-}
-
-/// Retrieve the port to which socket is bound
-int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port)
-{
-    return ERR_NOT_IMPLEMENTED;
-}
diff --git a/resource/csdk/ocsocket/test/android/makefile b/resource/csdk/ocsocket/test/android/makefile
deleted file mode 100644 (file)
index f68574d..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-# //******************************************************************
-# //
-# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // Licensed under the Apache License, Version 2.0 (the "License");
-# // you may not use this file except in compliance with the License.
-# // You may obtain a copy of the License at
-# //
-# //      http://www.apache.org/licenses/LICENSE-2.0
-# //
-# // Unless required by applicable law or agreed to in writing, software
-# // distributed under the License is distributed on an "AS IS" BASIS,
-# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# // See the License for the specific language governing permissions and
-# // limitations under the License.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-include ../local.properties
-
-ROOT_DIR = ../../..
-OCSOCK_DIR = $(ROOT_DIR)/ocsocket
-LOGGER_DIR = $(ROOT_DIR)/logger
-BIN_DIR = $(OCSOCK_DIR)/bin/android/
-OBJ_DIR = $(OCSOCK_DIR)/obj/android/
-INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include
-
-CXX=arm-linux-androideabi-g++
-CC=arm-linux-androideabi-gcc
-CFLAGS_ANDROID =  -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -DGTEST_HAS_PTHREAD=0
-LDFLAGS_ANDROID = -march=armv7-a -Wl,--fix-cortex-a8 -llog
-
-DEP_LIBS = $(GTEST_ANDROID_DIR)/lib/.libs/libgtest_main.a $(GTEST_ANDROID_DIR)/lib/.libs/libgtest.a
-
-CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -DTB_LOG
-
-TEST_APP = ocsocket_gtest
-
-COBJ = ocsocket.o logger.o
-
-VPATH = $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src
-
-all: $(TEST_APP)
-       mkdir -p $(BIN_DIR)
-       cp $(TEST_APP) $(BIN_DIR)
-       mkdir -p $(OBJ_DIR)
-       cp *.o $(OBJ_DIR)
-
-%.o: %.c
-       $(CXX) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) $< -o $@
-
-$(TEST_APP).o: $(TEST_APP).cpp
-       $(CXX) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) -I$(GTEST_ANDROID_DIR)/include -o $@ $<
-
-$(TEST_APP): $(TEST_APP).o $(DEP_LIBS) $(COBJ)
-       $(CXX) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $^ -o $@
-
-install: all
-#      adb remount
-       adb push $(BIN_DIR)$(TEST_APP) /data/local/tmp/
-
-.PHONY: clean
-
-clean:
-       rm -f *.o $(TEST_APP) recv
-       rm -fr $(BIN_DIR)
-       rm -fr $(OBJ_DIR)
-
diff --git a/resource/csdk/ocsocket/test/android/ocsocket_gtest.cpp b/resource/csdk/ocsocket/test/android/ocsocket_gtest.cpp
deleted file mode 100644 (file)
index 1c90e0b..0000000
+++ /dev/null
@@ -1,289 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#include <gtest/gtest.h>
-#include <ocsocket.h>
-#include <logger.h>
-
-#define MOD_NAME ("ocsocket_test")
-#define TEST_PORT_NUM (8888)
-
-unsigned char buf1[] = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, 0x6f, 0x67,
-  0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05,
-  0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01
-};
-unsigned int buf1_len = sizeof(buf1);
-
-
-unsigned char buf2[] = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-};
-
-unsigned int buf2_len = sizeof(buf2);
-
-
-TEST(BuildIPv4, Positive) {
-    OCDevAddr ipaddr;
-    EXPECT_EQ(ERR_SUCCESS, OCBuildIPv4Address(224,0,0,251,5353, &ipaddr));
-}
-
-
-TEST(BuildIPv4, InvalidInput) {
-    EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(24,24,24,24,2424, NULL));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(-24,24,-24,24,2424, NULL));
-}
-
-
-TEST(DevAddrToIPv4Addr, Positive) {
-    OCDevAddr ipaddr;
-    uint8_t  a,b,c,d;
-    uint16_t port;
-    OCBuildIPv4Address(1,2,3,4,5353, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCDevAddrToIPv4Addr(&ipaddr, &a, &b, &c, &d ));
-    EXPECT_TRUE((a == 1) && (b == 2) && (c == 3) && (d ==4));
-    EXPECT_EQ(ERR_SUCCESS, OCDevAddrToPort(&ipaddr, &port ));
-    EXPECT_TRUE(port == 5353);
-}
-
-
-TEST(DevAddrToIPv4Addr, InvalidInput) {
-    OCDevAddr ipaddr;
-    uint8_t  a,b,c,d;
-    uint16_t port;
-    OCBuildIPv4Address(1,2,3,4,5353, &ipaddr);
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, &a, &b, &c, &d ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(&ipaddr, NULL, &b, &c, &d ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, NULL, &b, &c, &d ));
-
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, &port ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(&ipaddr, NULL ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, NULL ));
-}
-
-
-TEST(GetInterfaceAddress, Positive) {
-    uint8_t addr[20];
-    uint8_t ifname[] = "wlan0";
-    EXPECT_EQ(ERR_SUCCESS, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)));
-    OC_LOG_V(INFO, MOD_NAME, "IPv4 Address: %s\n", addr);
-    //On Android, it is MUST to provide interface name
-    //EXPECT_EQ(0, get_ipv4addr( NULL, 0, addr, sizeof(addr)));
-}
-
-TEST(GetInterfaceAddress, Negative) {
-    uint8_t addr[20];
-    uint8_t ifname[] = "ethxx";
-    EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( NULL, 0, AF_INET, addr, sizeof(addr)));
-    EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, NULL, sizeof(addr)));
-    EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, 0));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname),  AF_INET6, addr, sizeof(addr)));
-}
-
-TEST(InitUDP, Positive) {
-    OCDevAddr ipaddr;
-    int32_t  sockfd;
-    uint8_t addr[20];
-    uint8_t ifname[] = "wlan0";
-    uint8_t a,b,c,d;
-
-    OCBuildIPv4Address(0,0,0,0, 0, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    OCClose(sockfd);
-
-    OCBuildIPv4Address(0,0,0,0, 5678, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    OCClose(sockfd);
-
-    OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-    sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d);
-    OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    OCClose(sockfd);
-}
-
-
-TEST(InitUDP, Negative) {
-    OCDevAddr ipaddr;
-    int32_t  sockfd;
-
-    OCBuildIPv4Address(0,0,0,0, 0, &ipaddr);
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(NULL, &sockfd));
-
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(&ipaddr, NULL));
-}
-
-
-
-TEST(InitUDPMulticast, Positive) {
-    OCDevAddr ipaddr1;
-    int32_t sfd;
-
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDPMulticast(&ipaddr1, &sfd));
-    OCClose(sfd);
-}
-
-
-TEST(InitUDPMulticast, Negative) {
-    OCDevAddr ipaddr1;
-    int32_t sfd;
-
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(NULL, &sfd));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(&ipaddr1, NULL));
-}
-
-
-TEST(SendToRecvfromUnicast, Positive) {
-    OCDevAddr ipaddr1, ipaddr2, ipaddr3;
-    int32_t  ssfd, rsfd;
-    uint8_t addr[20];
-    uint8_t ifname[] = "wlan0";
-    uint8_t a,b,c,d;
-    //uint8_t tmp1[512];
-
-
-    OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-    sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d);
-
-    //Create sending socket
-    OCBuildIPv4Address(a, b, c, d, 0, &ipaddr1);
-    OCInitUDP(&ipaddr1, &ssfd);
-
-    //Create receiving socket...i.e. bind to the specific port
-    OCBuildIPv4Address(a,b,c, d+1, TEST_PORT_NUM, &ipaddr2);
-    OCInitUDP(&ipaddr2, &rsfd);
-
-    //Test 1 -- Send 40 bytes
-    //Send the packet to ipaddr2(myself:TEST_PORT_NUM)
-    EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr2));
-    //Receive the packet
-    ipaddr3.size = sizeof(ipaddr3.addr);
-    //EXPECT_EQ(buf1_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    //EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len));
-
-    //Test 2 -- Send 1 byte
-    //Send the packet to ipaddr2(myself:TEST_PORT_NUM)
-    EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr2));
-    //Receive the packet
-    ipaddr3.size = sizeof(ipaddr3.addr);
-    //EXPECT_EQ( 1, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    //EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1));
-
-    //Test 3 -- Send 320 byte
-    //Send the packet to ipaddr2(myself:TEST_PORT_NUM)
-    EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr2));
-    //Receive the packet
-    ipaddr3.size = sizeof(ipaddr3.addr);
-    //EXPECT_EQ(buf2_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    //EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len));
-
-    OCClose(ssfd);
-    OCClose(rsfd);
-}
-
-
-
-TEST(SendToRecvfromMulticast, Positive) {
-    OCDevAddr ipaddr1, ipaddr2, ipaddr3, ipaddr4;
-    int32_t  ssfd;
-    uint8_t tmp1[512];
-
-    //Create sending socket
-    OCBuildIPv4Address(0,0,0,0, 5353, &ipaddr1);
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr2); //address to which MEMBERSHIP needs to be added
-    OCInitUDPMulticast(&ipaddr2, &ssfd);
-
-    //build the multicast address to which we need to send the datagram
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr3);
-
-    //Test 1 -- Send 40 bytes
-    EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr3));
-    //Receive the packet
-    ipaddr4.size = sizeof(ipaddr4.addr);
-    EXPECT_EQ(buf1_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len));
-
-    //Test 2 -- Send 1 byte
-    EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr3));
-    //Receive the packet
-    ipaddr4.size = sizeof(ipaddr4.addr);
-    EXPECT_EQ( 1, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1));
-
-    //Test 3 -- Send 320 byte
-    EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr3));
-    //Receive the packet
-    ipaddr4.size = sizeof(ipaddr4.addr);
-    EXPECT_EQ(buf2_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len));
-
-    OCClose(ssfd);
-}
-
diff --git a/resource/csdk/ocsocket/test/arduino/makefile b/resource/csdk/ocsocket/test/arduino/makefile
deleted file mode 100644 (file)
index 682a5a8..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-BUILD := release
-PLATFORM := arduinomega
-ARDUINO_PORT := /dev/ttyACM0
-
-# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
-ARDUINOWIFI := 0
-
-ifeq ($(ARDUINOWIFI),0)
-       APP_NAME := ocsocket_test
-       OCSOCKET_CPPOBJ = ocsocket_arduino.o
-else
-       APP_NAME := ocsocket_wifi_test
-       OCSOCKET_CPPOBJ = ocsocket_arduino_wifi.o
-endif
-
-OBJ_DIR := ./bin
-
-ROOT_DIR = ../../..
-
-include $(ROOT_DIR)/local.properties
-include $(ROOT_DIR)/$(PLATFORM).properties
-
-
-#include directories
-OCSOCK_DIR = $(ROOT_DIR)/ocsocket
-LOGGER_DIR = $(ROOT_DIR)/logger
-INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include
-
-VPATH := $(SDIR_ARD_PLATFORM):$(LOGGER_DIR)/src:$(OCSOCK_DIR)/src 
-
-CFLAGS := -Os -Wall -c -DTB_LOG
-
-all: core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-
-core.a: $(PLATFORM_OBJS)
-       $(AR) rcs $@ $^
-       $(RANLIB) $@
-
-#logger needs to be compiled using C++ compiler
-logger.o: logger.c
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@
-
-%.o: %.c
-       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@
-
-%.o: %.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@
-
-$(APP_NAME).elf: $(APP_NAME).o $(OCSOCKET_CPPOBJ) logger.o core.a
-       $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $^ -lm -o $@
-
-$(APP_NAME).hex: $(APP_NAME).elf
-       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(APP_NAME).eep
-       $(AVR_OBJCOPY) -O ihex -R .eeprom $< $@
-
-install: all
-       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i
-
-.PHONY: clean
-
-clean:
-       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
-       @rm -rf $(OBJ_DIR)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/resource/csdk/ocsocket/test/arduino/ocsocket_test.cpp b/resource/csdk/ocsocket/test/arduino/ocsocket_test.cpp
deleted file mode 100644 (file)
index 1271143..0000000
+++ /dev/null
@@ -1,339 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <SPI.h>
-#include <Ethernet.h>
-#include <ocsocket.h>
-#include <logger.h>
-
-//Mac address of my ethernet shield
-static uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0F, 0x2B, 0x72 };
-//IP address of the peer whom I wish to send some data
-static uint8_t PEER_IP_ADDR[] = {192, 168, 1, 125};
-static uint8_t MULTICAST_IP_ADDR[] = {224, 0, 1, 187};
-
-//Set below to 0 to disable multicast testing
-//#define MCAST_TESTING_EN 1
-
-#define TEST_NUM_PKTS (20)
-#define TEST_PORT_NUM (8888)
-#define MAX_BUF_SIZE  (256)
-
-unsigned char TEST_BUF[] = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-};
-unsigned int TEST_BUF_LEN = sizeof(TEST_BUF);
-
-#define PCF(str) ((PROGMEM const char *)(F(str)))
-
-#define MOD_NAME PCF("ocsocket_test")
-
-#define VERIFY_SUCCESS(op, res) { if (op == res) {OC_LOG(DEBUG, MOD_NAME, PCF(#op " SUCCEEDED"));} \
-     else {OC_LOG(FATAL, MOD_NAME, PCF(#op "!!!!  FAILED FAILED FAILED !!!!"));} }
-
-
-//OCGetInterfaceAddress tests
-void test10() {
-    char strAddr[16] = "";
-    VERIFY_SUCCESS(OCGetInterfaceAddress(NULL, 0, AF_INET, (uint8_t*)strAddr, 16), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("My IP address :"));
-    OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)strAddr, sizeof(strAddr));
-    delay(15000);
-    VERIFY_SUCCESS(OCGetInterfaceAddress(NULL, 0, AF_INET, NULL, 16), ERR_INVALID_INPUT);
-    VERIFY_SUCCESS(OCGetInterfaceAddress(NULL, 0, AF_INET, (uint8_t*)strAddr, 10), ERR_INVALID_INPUT);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test10 - Completed"));
-}
-
-//OCBuildIPv4Address tests
-void test20() {
-    OCDevAddr ipAddr;
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, NULL), ERR_INVALID_INPUT);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test20 - Completed"));
-}
-
-
-void test30() {
-
-    OCDevAddr ipAddr;
-    uint8_t a, b, c, d;
-    uint16_t port;
-    VERIFY_SUCCESS(OCBuildIPv4Address( 1, 2, 3, 4, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCDevAddrToIPv4Addr( &ipAddr, &a, &b, &c, &d), ERR_SUCCESS);
-    if ((a != 1) || (b != 2) || (c !=3) || (d !=4)) {
-        OC_LOG(DEBUG, MOD_NAME, PCF("test30 - Failed !!!"));
-        return;
-    }
-
-    VERIFY_SUCCESS(OCDevAddrToPort( &ipAddr, &port), ERR_SUCCESS);
-    if (port != TEST_PORT_NUM) {
-        OC_LOG(DEBUG, MOD_NAME, PCF("test30 - Failed !!!"));
-        return;
-    }
-    VERIFY_SUCCESS(OCDevAddrToIPv4Addr( NULL, &a, &b, &c, &d), ERR_INVALID_INPUT);
-    VERIFY_SUCCESS(OCDevAddrToPort( &ipAddr, NULL), ERR_INVALID_INPUT);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test30 - Completed"));
-}
-
-//OCInitUDP tests
-void test40() {
-    OCDevAddr ipAddr;
-    int32_t sfd1, sfd2, sfd3, sfd4, sfd5;
-
-    //We should be able to successfully open 4 sockets.
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd1), ERR_SUCCESS);
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 1, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd2), ERR_SUCCESS);
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 2, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd3), ERR_SUCCESS);
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 3, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd4), ERR_SUCCESS);
-
-    //5th socket creation call should FAIL
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 4, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd5), ERR_UNKNOWN);
-
-    VERIFY_SUCCESS(OCClose( sfd4), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd5), ERR_SUCCESS);
-
-    VERIFY_SUCCESS(OCClose( sfd1), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCClose( sfd2), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCClose( sfd3), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCClose( sfd5), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test40 - Completed"));
-}
-
-
-//OCInitUDPMulticast tests
-void test50() {
-    OCDevAddr ipAddr;
-    int32_t sfd1, sfd2;
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( MULTICAST_IP_ADDR[0], MULTICAST_IP_ADDR[1],
-                MULTICAST_IP_ADDR[2], MULTICAST_IP_ADDR[3], TEST_PORT_NUM, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDPMulticast( &ipAddr, &sfd1), ERR_SUCCESS);
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 1, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd2), ERR_SUCCESS);
-
-    VERIFY_SUCCESS(OCClose( sfd1), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCClose( sfd2), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test50 - Completed"));
-}
-
-
-//OCSendTo -- Unicast tests
-void test60() {
-    OCDevAddr ipAddr, peerAddr;
-    int32_t sfd;
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCBuildIPv4Address(PEER_IP_ADDR[0], PEER_IP_ADDR[0],
-                PEER_IP_ADDR[0], PEER_IP_ADDR[0], TEST_PORT_NUM, &peerAddr), ERR_SUCCESS);
-
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd), ERR_SUCCESS);
-    for (int i = 2; i < 300; ) {
-        VERIFY_SUCCESS(OCSendTo(sfd, TEST_BUF, i, 0, &peerAddr), i);
-        i = i + 12;
-
-        delay(100);
-    }
-    VERIFY_SUCCESS(OCClose( sfd), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test60 - Completed"));
-}
-
-
-//OCSendTo -- Multicast tests
-void test70() {
-    OCDevAddr ipAddrMcast;
-    int32_t sfd;
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( MULTICAST_IP_ADDR[0], MULTICAST_IP_ADDR[1],
-                MULTICAST_IP_ADDR[2], MULTICAST_IP_ADDR[3], TEST_PORT_NUM, &ipAddrMcast), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDPMulticast( &ipAddrMcast, &sfd), ERR_SUCCESS);
-    for (int i = 2; i < 300; ) {
-        VERIFY_SUCCESS(OCSendTo(sfd, TEST_BUF, i, 0, &ipAddrMcast), i);
-        i = i + 12;
-
-        delay(100);
-    }
-    VERIFY_SUCCESS(OCClose( sfd), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test70 - Completed"));
-}
-
-
-
-//End to End - Unicast Send/Recv test
-//Start sample app 'sendrecv' on different Linux box.
-void test80() {
-    OCDevAddr ipAddr, peerAddr;
-    int32_t sfd;
-    int32_t recvLen;
-    uint8_t buf[MAX_BUF_SIZE];
-    uint8_t pktrecv = 0;
-
-    //Unicast
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd), ERR_SUCCESS);
-
-    do {
-        recvLen = OCRecvFrom(sfd, buf, MAX_BUF_SIZE, 0, &peerAddr);
-        if (recvLen > 0) {
-            pktrecv++;
-            OC_LOG(DEBUG, MOD_NAME, PCF("Rcvd data from :"));
-            OC_LOG_BUFFER(INFO, MOD_NAME, peerAddr.addr, peerAddr.size);
-            OC_LOG(DEBUG, MOD_NAME, PCF("Data Length :"));
-            OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)&recvLen, sizeof(recvLen));
-
-            VERIFY_SUCCESS(OCSendTo(sfd, buf, recvLen, 0, &peerAddr), recvLen);
-        } else {
-            OC_LOG(DEBUG, MOD_NAME, PCF("No data received"));
-        }
-        delay(500); //delay  secs
-    } while (pktrecv < TEST_NUM_PKTS);
-
-    VERIFY_SUCCESS(OCClose(sfd), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test80 - Completed"));
-}
-
-
-//End to End - Multicast Send/Recv test
-//Start sample app 'sendrecv' on different Linux box.
-void test90() {
-    OCDevAddr ipAddrMcast, peerAddr;
-    int32_t sfd;
-    int32_t recvLen;
-    uint8_t buf[MAX_BUF_SIZE];
-    uint8_t pktrecv = 0;
-
-    //Multicast
-    VERIFY_SUCCESS(OCBuildIPv4Address( MULTICAST_IP_ADDR[0], MULTICAST_IP_ADDR[1],
-                MULTICAST_IP_ADDR[2], MULTICAST_IP_ADDR[3], TEST_PORT_NUM, &ipAddrMcast), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDPMulticast( &ipAddrMcast, &sfd), ERR_SUCCESS);
-
-    do {
-
-        recvLen = OCRecvFrom(sfd, buf, MAX_BUF_SIZE, 0, &peerAddr);
-        if (recvLen > 0) {
-            pktrecv++;
-            OC_LOG(DEBUG, MOD_NAME, PCF("Rcvd data from :"));
-            OC_LOG_BUFFER(INFO, MOD_NAME, peerAddr.addr, peerAddr.size);
-            OC_LOG(DEBUG, MOD_NAME, PCF("Data Length :"));
-            OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)&recvLen, sizeof(recvLen));
-
-            VERIFY_SUCCESS(OCSendTo(sfd, buf, recvLen, 0, &ipAddrMcast), recvLen);
-        } else {
-            OC_LOG(DEBUG, MOD_NAME, PCF("No data received"));
-        }
-        delay(500); //delay  secs
-    } while (pktrecv < TEST_NUM_PKTS);
-
-    VERIFY_SUCCESS(OCClose(sfd), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("test90 - Completed"));
-}
-
-
-
-//End to End - 'Simultaneous' Unicast-Multicast Send/Recv test
-//This tests if Arduino Wiznet shield can open 2 independent sockets listening on same port:
-//  one for unicast traffic and another for multicast traffic.
-//Start sample app 'sendrecv' on different Linux box.
-void test100() {
-    //TBD
-    //TBD
-    //TBD
-}
-
-
-
-
-
-void setup() {
-
-    Serial.begin(115200);
-
-    Serial.println("Trying to get an IP address using DHCP");
-    if (Ethernet.begin(ETHERNET_MAC) == 0) {
-        Serial.println("Failed to configure Ethernet using DHCP");
-    }
-}
-
-void loop() {
-    test10();
-    test20();
-    test30();
-    test40();
-    test50();
-    test60(); //SendTo --Unicast
-    test70(); //SendTo --Multicast
-    test80(); //End-to-End  --Unicast
-    delay(5000);
-    test90(); //End-to-End  --Multicast
-
-    do {
-        OC_LOG(DEBUG, MOD_NAME, PCF("All tests Completed"));
-        delay(10000);
-    } while (1);
-}
-
-
diff --git a/resource/csdk/ocsocket/test/arduino/ocsocket_wifi_test.cpp b/resource/csdk/ocsocket/test/arduino/ocsocket_wifi_test.cpp
deleted file mode 100644 (file)
index 0138afb..0000000
+++ /dev/null
@@ -1,204 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <ocsocket.h>
-#include <logger.h>
-#include <SPI.h>
-#include <WiFi.h>
-#include <WiFiUdp.h>
-
-/// WiFi Shield firmware with Intel patches
-static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
-
-/// IP address of the peer whom I wish to send/recv some data
-static uint8_t PEER_IP_ADDR[] = {192, 168, 1, 132};
-
-/// Port number of the peer whom I wish to send/recv some data
-#define TEST_PORT_NUM (4097)
-
-/// Max buffer size
-#define MAX_BUF_SIZE  (1024)
-
-/// Some test bytes to send to the peer
-unsigned char TEST_BUF[] = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-};
-unsigned int TEST_BUF_LEN = sizeof(TEST_BUF);
-
-#define MOD_NAME PCF("ocsocket_test")
-
-#define VERIFY_SUCCESS(op, res) { if (op == res) {OC_LOG(DEBUG, MOD_NAME, PCF(#op " SUCCEEDED"));} \
-     else {OC_LOG(FATAL, MOD_NAME, PCF(#op "!!!!  FAILED FAILED FAILED !!!!"));} }
-
-/// WiFi network info and credentials
-char ssid[] = "mDNSAP";
-char pass[] = "letmein9";
-int status = WL_IDLE_STATUS;
-
-//Start sample app 'sendrecv' on different Linux box.
-void SendReceiveTest()
-{
-    Serial.println("entering SendReceiveTest...");
-    OCDevAddr ipAddr, peerAddr, recvAddr;
-    int32_t sfd;
-    int32_t recvLen;
-    uint8_t buf[MAX_BUF_SIZE];
-    uint16_t recvPort;
-
-    VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCBuildIPv4Address(PEER_IP_ADDR[0], PEER_IP_ADDR[1],
-                PEER_IP_ADDR[2], PEER_IP_ADDR[3], TEST_PORT_NUM, &peerAddr), ERR_SUCCESS);
-    VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("Peer Addr :"));
-    OC_LOG_BUFFER(INFO, MOD_NAME, peerAddr.addr, peerAddr.size);
-    for (int i = 0; i < 300; i++)
-    {
-
-        OC_LOG_V(DEBUG, MOD_NAME, "--------------------- i --------------- %d", i);
-        VERIFY_SUCCESS(OCSendTo(sfd, TEST_BUF, i + 10, 0, &peerAddr), i+10);
-
-        delay(2000);
-        recvLen = OCRecvFrom(sfd, buf, MAX_BUF_SIZE, 0, &recvAddr);
-        if (recvLen > 0)
-        {
-            OC_LOG(DEBUG, MOD_NAME, PCF("Rcvd data from :"));
-            OC_LOG_BUFFER(INFO, MOD_NAME, recvAddr.addr, recvAddr.size);
-            OCDevAddrToPort(&recvAddr, &recvPort);
-            OC_LOG_V(DEBUG, MOD_NAME, "Recv Data from Port %hu", recvPort);
-            OC_LOG(DEBUG, MOD_NAME, PCF("Data Length :"));
-            OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)&recvLen, sizeof(recvLen));
-            OC_LOG(DEBUG, MOD_NAME, PCF("Data :"));
-            if (recvLen < 255)
-            {
-                OC_LOG_BUFFER(INFO, MOD_NAME, buf, recvLen);
-            }
-            else
-            {
-                int idx = 0;
-                int rem = recvLen;
-                do {
-                    if (rem > 255)
-                    {
-                        OC_LOG_BUFFER(INFO, MOD_NAME, buf + idx, 255);
-                        rem = rem - 255;
-                    }
-                    else
-                    {
-                        OC_LOG_BUFFER(INFO, MOD_NAME, buf + idx, rem);
-                        rem = 0;
-                    }
-                    idx = idx + 255;
-                }while(rem > 0);
-            }
-
-        }
-    }
-    VERIFY_SUCCESS(OCClose( sfd), ERR_SUCCESS);
-    OC_LOG(DEBUG, MOD_NAME, PCF("WifiTest - Completed"));
-
-}
-void setup()
-{
-    Serial.begin(115200);
-    Serial.println("WiFi test starting...");
-
-    // check for the presence of the shield:
-    if (WiFi.status() == WL_NO_SHIELD)
-    {
-      Serial.println("WiFi shield not present");
-      // don't continue:
-      while(true);
-    }
-
-    Serial.print("WiFi version: ");
-    Serial.println(WiFi.firmwareVersion());
-
-    if (strcmp(WiFi.firmwareVersion(), INTEL_WIFI_SHIELD_FW_VER) != 0)
-    {
-        Serial.println("!!!!! Upgrade WiFi Shield Firmware version !!!!!!");
-    }
-
-    // attempt to connect to Wifi network:
-    while ( status != WL_CONNECTED) {
-      Serial.print("Attempting to connect to SSID: ");
-      Serial.println(ssid);
-      status = WiFi.begin(ssid,pass);
-
-      // wait 10 seconds for connection:
-      delay(10000);
-    }
-    Serial.println("Connected to wifi");
-
-    IPAddress ip = WiFi.localIP();
-    Serial.print("IP Address: ");
-    Serial.println(ip);
-}
-
-void loop() {
-    Serial.println("entering loop...");
-    SendReceiveTest();
-    delay(5000);
-
-    do {
-        OC_LOG(DEBUG, MOD_NAME, PCF("All tests Completed"));
-        delay(10000);
-    } while (1);
-}
-
-
diff --git a/resource/csdk/ocsocket/test/linux/makefile b/resource/csdk/ocsocket/test/linux/makefile
deleted file mode 100644 (file)
index adf6abc..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-PLATFORM := linux
-
-ROOT_DIR = ../../..
-include $(ROOT_DIR)/local.properties
-
-OCSOCK_DIR = $(ROOT_DIR)/ocsocket
-OC_LOG_DIR    = $(ROOT_DIR)/../oc_logger
-LOGGER_DIR = $(ROOT_DIR)/logger
-BIN_DIR = $(OCSOCK_DIR)/bin/linux/
-OBJ_DIR = $(OCSOCK_DIR)/obj/linux/
-INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include -I$(OC_LOG_DIR)/include
-
-CXX = g++
-CC = gcc
-
-CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -DTB_LOG
-DEP_LIBS = $(GTEST_LINUX_DIR)/lib/.libs/libgtest_main.a $(GTEST_LINUX_DIR)/lib/.libs/libgtest.a
-VPATH = $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src
-
-TEST_APP = ocsocket_gtest
-COBJ = logger.o ocsocket.o 
-
-all: $(TEST_APP)
-       mkdir -p $(BIN_DIR)
-       cp $(TEST_APP) $(BIN_DIR)
-       mkdir -p $(OBJ_DIR)
-       cp *.o $(OBJ_DIR)
-
-%.o: %.c
-       $(CC) -c $(CFLAGS) $(INC_DIRS) $< -o $@
-
-$(TEST_APP).o: $(TEST_APP).cpp
-       $(CXX) -c $(CFLAGS) -pthread $(INC_DIRS)  -I$(GTEST_LINUX_DIR)/include -o $@ $<
-
-$(TEST_APP): $(TEST_APP).o $(DEP_LIBS) $(COBJ)
-       $(CXX) -Os -Wl,--gc-sections $^ -lpthread -o $@
-
-.PHONY: clean
-
-clean:
-       rm -f *.o $(TEST_APP)
-       rm -fr $(BIN_DIR)
-       rm -fr $(OBJ_DIR)
-
-
diff --git a/resource/csdk/ocsocket/test/linux/ocsocket_gtest.cpp b/resource/csdk/ocsocket/test/linux/ocsocket_gtest.cpp
deleted file mode 100644 (file)
index b6c9872..0000000
+++ /dev/null
@@ -1,318 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#include <gtest/gtest.h>
-#include <ocsocket.h>
-#include <logger.h>
-
-#define MOD_NAME ("ocsocket_test")
-
-#define TEST_PORT_NUM (8888)
-
-unsigned char buf1[] = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, 0x6f, 0x67,
-  0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05,
-  0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01
-};
-unsigned int buf1_len = sizeof(buf1);
-
-
-unsigned char buf2[] = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f,
-  0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74,
-  0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f,
-  0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01,
-};
-unsigned int buf2_len = sizeof(buf2);
-
-TEST(BuildIPv4, Positive) {
-    OCDevAddr ipaddr;
-    EXPECT_EQ(ERR_SUCCESS, OCBuildIPv4Address(224,0,0,251,5353, &ipaddr));
-}
-
-
-TEST(BuildIPv4, InvalidInput) {
-    EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(24,24,24,24,2424, NULL));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(-24,24,-24,24,2424, NULL));
-}
-
-TEST(DevAddrToIPv4Addr, Positive) {
-    OCDevAddr ipaddr;
-    uint8_t  a,b,c,d;
-    uint16_t port;
-    OCBuildIPv4Address(1,2,3,4,5353, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCDevAddrToIPv4Addr(&ipaddr, &a, &b, &c, &d ));
-    EXPECT_TRUE((a == 1) && (b == 2) && (c == 3) && (d ==4));
-    EXPECT_EQ(ERR_SUCCESS, OCDevAddrToPort(&ipaddr, &port ));
-    EXPECT_TRUE(port == 5353);
-}
-
-
-TEST(DevAddrToIPv4Addr, InvalidInput) {
-    OCDevAddr ipaddr;
-    uint8_t  a,b,c,d;
-    uint16_t port;
-    OCBuildIPv4Address(1,2,3,4,5353, &ipaddr);
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, &a, &b, &c, &d ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(&ipaddr, NULL, &b, &c, &d ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, NULL, &b, &c, &d ));
-
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, &port ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(&ipaddr, NULL ));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, NULL ));
-}
-
-
-
-
-TEST(GetInterfaceAddress, Positive) {
-    uint8_t addr[20];
-    uint8_t ifname[] = "eth0";
-    EXPECT_EQ(ERR_SUCCESS, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET,  addr, sizeof(addr)));
-    printf("IPv4 Address: %s\n", addr);
-    EXPECT_EQ(ERR_SUCCESS, OCGetInterfaceAddress( NULL, 0,  AF_INET, addr, sizeof(addr)));
-    printf("IPv4 Address: %s\n", addr);
-}
-
-TEST(GetInterfaceAddress, Negative) {
-    uint8_t addr[20];
-    uint8_t ifname[] = "ethxx";
-    EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname),  AF_INET, addr, sizeof(addr)));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname),  AF_INET, NULL, sizeof(addr)));
-    EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname),  AF_INET, addr, 0));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname),  AF_INET6, addr, sizeof(addr)));
-}
-
-TEST(InitUDP, Positive) {
-    OCDevAddr ipaddr;
-    int32_t  sockfd;
-    uint8_t addr[20];
-    uint8_t ifname[] = "eth0";
-    uint8_t a,b,c,d;
-
-    OCBuildIPv4Address(0,0,0,0, 0, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    OCClose(sockfd);
-
-    OCBuildIPv4Address(0,0,0,0, 5678, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    OCClose(sockfd);
-
-    OCGetInterfaceAddress( ifname, sizeof(ifname),  AF_INET, addr, sizeof(addr));
-    sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d);
-    OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    OCClose(sockfd);
-}
-
-
-TEST(InitUDP, Negative) {
-    OCDevAddr ipaddr;
-    int32_t  sockfd;
-
-    OCBuildIPv4Address(0,0,0,0, 0, &ipaddr);
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(NULL, &sockfd));
-
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(&ipaddr, NULL));
-}
-
-
-
-TEST(InitUDPMulticast, Positive) {
-    OCDevAddr ipaddr1;
-    int32_t sfd;
-
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDPMulticast(&ipaddr1, &sfd));
-    OCClose(sfd);
-}
-
-
-TEST(InitUDPMulticast, Negative) {
-    OCDevAddr ipaddr1;
-    int32_t sfd;
-
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(NULL, &sfd));
-    EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(&ipaddr1, NULL));
-}
-
-
-TEST(SendToRecvfromUnicast, Positive) {
-    OCDevAddr ipaddr1, ipaddr2, ipaddr3;
-    int32_t  ssfd, rsfd;
-    uint8_t addr[20];
-    uint8_t ifname[] = "eth0";
-    uint8_t a,b,c,d;
-    uint8_t tmp1[512];
-
-    //Create sending socket
-    OCBuildIPv4Address(0,0,0,0, 0, &ipaddr1);
-    OCInitUDP(&ipaddr1, &ssfd);
-
-    //Create receiving socket...i.e. bind to the specific port
-    OCBuildIPv4Address(0,0,0,0, TEST_PORT_NUM, &ipaddr2);
-    OCInitUDP(&ipaddr2, &rsfd);
-
-    //Since this is a Unit test, we will attempt to send message to ourself at a specific port
-    OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-    sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d);
-    OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr2);
-
-    //Test 1 -- Send 40 bytes
-    //Send the packet to ipaddr2(myself:TEST_PORT_NUM)
-    EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr2));
-    //Receive the packet
-    ipaddr3.size = sizeof(ipaddr3.addr);
-    EXPECT_EQ(buf1_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len));
-
-    //Test 2 -- Send 1 byte
-    //Send the packet to ipaddr2(myself:TEST_PORT_NUM)
-    EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr2));
-    //Receive the packet
-    ipaddr3.size = sizeof(ipaddr3.addr);
-    EXPECT_EQ( 1, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1));
-
-    //Test 3 -- Send 320 byte
-    //Send the packet to ipaddr2(myself:TEST_PORT_NUM)
-    EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr2));
-    //Receive the packet
-    ipaddr3.size = sizeof(ipaddr3.addr);
-    EXPECT_EQ(buf2_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len));
-
-    OCClose(ssfd);
-    OCClose(rsfd);
-}
-
-
-TEST(SendToRecvfromMulticast, Positive) {
-    OCDevAddr ipaddr1, ipaddr2, ipaddr3, ipaddr4;
-    int32_t  ssfd;
-    uint8_t tmp1[512];
-
-    //Create sending socket
-    OCBuildIPv4Address(0,0,0,0, 5353, &ipaddr1);
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr2); //address to which MEMBERSHIP needs to be added
-    OCInitUDPMulticast(&ipaddr2, &ssfd);
-
-    //build the multicast address to which we need to send the datagram
-    OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr3);
-
-    //Test 1 -- Send 40 bytes
-    EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr3));
-    //Receive the packet
-    ipaddr4.size = sizeof(ipaddr4.addr);
-    EXPECT_EQ(buf1_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len));
-
-    //Test 2 -- Send 1 byte
-    EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr3));
-    //Receive the packet
-    ipaddr4.size = sizeof(ipaddr4.addr);
-    EXPECT_EQ( 1, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1));
-
-    //Test 3 -- Send 320 byte
-    EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr3));
-    //Receive the packet
-    ipaddr4.size = sizeof(ipaddr4.addr);
-    EXPECT_EQ(buf2_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr3));
-    //Compare the received buffer with send buffer
-    EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len));
-
-    OCClose(ssfd);
-}
-
-TEST(GetSocketInfo, Positive) {
-    OCDevAddr ipaddr;
-    int32_t  sockfd;
-    uint8_t addr[20];
-    uint8_t ifname[] = "eth0";
-    uint16_t port;
-    uint8_t a,b,c,d;
-
-    OCBuildIPv4Address(0,0,0,0, 0, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    EXPECT_EQ(ERR_SUCCESS, OCGetSocketInfo(sockfd, &port));
-    OC_LOG_V(DEBUG, MOD_NAME, "Port %d", port);
-    OCClose(sockfd);
-
-    OCBuildIPv4Address(0,0,0,0, 5678, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    EXPECT_EQ(ERR_SUCCESS, OCGetSocketInfo(sockfd, &port));
-    OC_LOG_V(DEBUG, MOD_NAME, "Port %d", port);
-    EXPECT_TRUE(port == 5678);
-    OCClose(sockfd);
-
-    OCGetInterfaceAddress( ifname, sizeof(ifname),  AF_INET, addr, sizeof(addr));
-    sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d);
-    OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr);
-    EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd));
-    EXPECT_EQ(ERR_SUCCESS, OCGetSocketInfo(sockfd, &port));
-    OC_LOG_V(DEBUG, MOD_NAME, "Port %d", port);
-    EXPECT_TRUE(port == TEST_PORT_NUM);
-    OCClose(sockfd);
-}
diff --git a/resource/csdk/ocsocket/test/makefile b/resource/csdk/ocsocket/test/makefile
deleted file mode 100644 (file)
index 8d6598e..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-all: 
-       $(MAKE) -C android all
-       $(MAKE) -C linux all
-       $(MAKE) -C arduino all
-
-install: all
-       $(MAKE) -C android install
-       $(MAKE) -C arduino install
-
-.PHONY: clean
-
-clean:
-       $(MAKE) -C android clean
-       $(MAKE) -C linux clean
-       $(MAKE) -C arduino clean
-
diff --git a/resource/csdk/ocsocket/test/sendrecv.cpp b/resource/csdk/ocsocket/test/sendrecv.cpp
deleted file mode 100644 (file)
index e657d6b..0000000
+++ /dev/null
@@ -1,226 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <math.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <net/if.h>
-
-#include <ifaddrs.h>
-#include <linux/if_link.h>
-
-#include <signal.h>
-
-//static uint8_t MULTICAST_IP_ADDR[] = {224, 0, 1, 187};
-//static uint32_t TEST_PORT_NUM = 8888;
-
-
-#define MAX_BUF (1024)
-uint8_t g_bfr[] = {
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA,
-    };
-uint32_t g_bfrlen = sizeof(g_bfr);
-
-int multicast_test(int argc, char* argv[])
-{
-    int32_t sfd;
-    char loopch=0;
-    int set_option_on = 1;
-    struct sockaddr_in mcastsock = {0}, peer;
-    uint8_t recvbuf[MAX_BUF];
-    uint32_t len, bufLen, fromlen;
-
-    printf("Running multicast tests\n");
-
-    bufLen = atoi(argv[4]);
-    if (bufLen > g_bfrlen) {
-        printf("Warning: Input buffer provided too big. Trimming to supported size\n");
-        bufLen = g_bfrlen;
-    }
-
-    //Create a datagram socket on which to send.
-    sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
-    if (sfd < 0) {
-        printf("Error in opening datagram socket");
-        return -1;
-    }
-
-    //Initialize the group sockaddr structure with a
-    mcastsock.sin_family = AF_INET;
-    mcastsock.sin_addr.s_addr = inet_addr(argv[2]);
-    mcastsock.sin_port = htons(atoi(argv[3]));
-
-    //Disable loopback so you do not receive your own datagrams.
-    if (setsockopt(sfd, IPPROTO_IP, IP_MULTICAST_LOOP,
-                (char *)&loopch, sizeof(loopch)) < 0) {
-        //printf("setting IP_MULTICAST_LOOP:");
-        close(sfd);
-        return -1;
-    }
-
-    //Play nice with other processes who may be listening at this
-    //port/IP address combination
-    if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on,
-                sizeof(set_option_on)) < 0) {
-        //printf("setting SO_REUSEADDR:");
-        close(sfd);
-        return -1;
-    }
-
-    if (bind(sfd, (sockaddr*)&mcastsock, sizeof(mcastsock)) < 0) {
-        printf("bind returns error");
-        close(sfd);
-        return -1;
-    }
-
-    struct ip_mreq mreq = {0};
-    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
-    mreq.imr_multiaddr.s_addr = mcastsock.sin_addr.s_addr;
-    if ((setsockopt(sfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq))) < 0) {
-        printf("multicast -- adding membership failed");
-        close(sfd);
-        return -1;
-    }
-
-    do {
-        len = sendto(sfd, g_bfr,  bufLen, 0,
-                (struct sockaddr*)&mcastsock, sizeof(mcastsock));
-        if (len > 0) {
-            printf ("Send %d bytes to %s\n", len, inet_ntoa(mcastsock.sin_addr));
-        }
-
-        fromlen = sizeof(peer);
-        len = recvfrom(sfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&peer, &fromlen);
-        if (len > 0) {
-            printf("Rcvd %d bytes from %s\n", len, inet_ntoa(peer.sin_addr));
-        }
-
-        sleep(1);
-    } while (true);
-
-    close(sfd);
-    return 0;
-}
-
-
-
-
-int unicast_test(int argc, char* argv[])
-{
-    int32_t sfd;
-    struct sockaddr_in sa, peer;
-    uint8_t recvbuf[MAX_BUF];
-    uint32_t len, bufLen, fromlen;
-
-    printf("Running unicast tests\n");
-
-    bufLen = atoi(argv[4]);
-    if (bufLen > g_bfrlen) {
-        printf("Warning: Input buffer provided too big. Trimming to supported size\n");
-        bufLen = g_bfrlen;
-    }
-
-    sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
-    if (sfd < 0) {
-        printf("socket API ret val %d\n", sfd);
-        return -1;
-    }
-
-    sa.sin_family = AF_INET;
-    sa.sin_addr.s_addr = INADDR_ANY;
-    sa.sin_port = htons(atoi(argv[3]));
-
-    if (bind(sfd, (struct sockaddr*)&sa, sizeof(sa)) < 0) {
-        printf("bin API ret val %d\n", sfd);
-        close(sfd);
-        return -1;
-    }
-
-    peer.sin_family = AF_INET;
-    inet_aton(argv[2], &peer.sin_addr);
-    peer.sin_port = htons(atoi(argv[3]));
-
-    do {
-        len = sendto(sfd, g_bfr,  bufLen, 0,
-                (struct sockaddr*)&peer, sizeof(peer));
-
-        if (len > 0) {
-            printf ("Send %d bytes to %s\n", len, inet_ntoa(peer.sin_addr));
-        }
-
-        fromlen = sizeof(peer);
-        len = recvfrom(sfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&peer, &fromlen);
-        if (len > 0) {
-            printf("Rcvd %d bytes from %s\n", len, inet_ntoa(peer.sin_addr));
-        }
-
-        sleep(1);
-    } while(true);
-
-    close(sfd);
-    return 0;
-}
-
-
-
-
-int main(int argc, char * argv[])
-{
-
-    if (argc < 5) {
-        printf("Usage: sendrecv <u|m> <ipAddr 192.168.1.107 | 224.0.1.187> <portnum 8888> <pkt_size 200>\n");
-        return -1;
-    }
-
-    if (argv[1][0] == 'u') {
-        unicast_test(argc, argv);
-    } else {
-        multicast_test(argc, argv);
-    }
-
-    return 0;
-}
diff --git a/resource/csdk/ocsocket/test/sendrecv_README.txt b/resource/csdk/ocsocket/test/sendrecv_README.txt
deleted file mode 100644 (file)
index 2c45530..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-sendrecv.cpp is a test application for verifying the end to end test for Arduino/Android platforms.
-To compile: 
-    g++ -o sendrecv sendrecv.cpp
diff --git a/resource/csdk/security/include/internal/ocsecurityinternal.h b/resource/csdk/security/include/internal/ocsecurityinternal.h
new file mode 100644 (file)
index 0000000..d080546
--- /dev/null
@@ -0,0 +1,52 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OC_SECURITY_INTERNAL_H
+#define OC_SECURITY_INTERNAL_H
+
+#include "ocsecurityconfig.h"
+
+/**
+ * This callback is used by lower stack (i.e. CA layer) to retrieve PSK
+ * credentials from RI security layer.
+ *
+ * Note: When finished, caller should initialize memory to zeroes and
+ * invoke OCFree to delete @p credInfo.
+ *
+ * @param credInfo
+ *     binary blob containing PSK credentials
+ *
+ * @retval none
+ */
+#ifdef __WITH_DTLS__
+void GetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo);
+#endif //__WITH_DTLS__
+
+
+/**
+ * This internal API removes/clears the global variable holding the security
+ * config data. This needs to be invoked when OIC stack is shutting down.
+ *
+ * @retval none
+ */
+void DeinitOCSecurityInfo();
+
+#endif //OC_SECURITY_INTERNAL_H
+
diff --git a/resource/csdk/security/include/ocsecurity.h b/resource/csdk/security/include/ocsecurity.h
new file mode 100644 (file)
index 0000000..1d1b3e4
--- /dev/null
@@ -0,0 +1,50 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OC_SECURITY_H
+#define OC_SECURITY_H
+
+#include "ocstack.h"
+#include "ocsecurityconfig.h"
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ * Provides the Security Configuration data to OC stack.
+ *
+ * @param cfgData
+ *     binary blob containing config data
+ * @param len
+ *     length of binary blob
+ *
+ * @retval OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult OCSecSetConfigData(const OCSecConfigData *cfgData,
+                size_t len);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif //OC_SECURITY_H
+
diff --git a/resource/csdk/security/include/ocsecurityconfig.h b/resource/csdk/security/include/ocsecurityconfig.h
new file mode 100644 (file)
index 0000000..fa5d164
--- /dev/null
@@ -0,0 +1,103 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OC_SECURITY_CONFIG_H
+#define OC_SECURITY_CONFIG_H
+
+#include <stdint.h>
+
+#define DTLS_PSK_ID_LEN 16
+#define DTLS_PSK_PSK_LEN 16
+
+#define OCSecConfigVer_1 1 /**< Initial version supporting PSK Credentials */
+#define OCSecConfigVer_CurrentVersion OCSecConfigVer_1
+
+typedef enum{
+    OC_BLOB_TYPE_PSK = 1,   /**< Security blob holding PSK data */
+} OCBlobType;
+
+
+/**
+ * Credentials of a peer device. Includes identity and the associated PSK.
+ */
+typedef struct
+{
+    unsigned char id[DTLS_PSK_ID_LEN];      /**< identity of the peer device */
+    unsigned char psk[DTLS_PSK_PSK_LEN];    /**< psk of the peer device */
+} OCDtlsPskCreds;
+
+
+/**
+ * Binary blob containing device identity and the credentials for all devices
+ * trusted by this device.
+ */
+typedef struct
+{
+    unsigned char identity[DTLS_PSK_ID_LEN]; /**< identity of self */
+    uint32_t num;                            /**< number of credentials in this blob */
+    OCDtlsPskCreds creds[1];                 /**< list of credentials. Size of this
+                                                 array is determined by 'num' variable. */
+} OCDtlsPskCredsBlob;
+
+
+/**
+ * Generic definition of a security blob. A security blob can contain
+ * info of various types, such as : PSK info, certificates,
+ * access control lists(ACL) etc.
+ */
+typedef struct
+{
+    uint16_t  type;     /**< Type of blob */
+    uint16_t  len;   /**< length of blob data */
+    uint8_t   val[1];   /**< A variable size array holding blob data */
+} OCSecBlob;
+
+
+/**
+ * This structure defines the security related configuration data for
+ * Iotivity applications.
+ */
+typedef struct
+{
+   uint16_t    version;  /**< version of the config data */
+   uint16_t    numBlob;  /**< number of security blobs in this config data */
+   uint8_t     blob[1];  /**< A variable size array holding a blob */
+} OCSecConfigData;
+
+/**
+ * Interprets @p blob as pointer to a OCSecBlob and advances to
+ * the next blob in the OCSecConfigData
+ */
+#define config_data_next_blob(blob) \
+            ((OCSecBlob*)((blob)->val + (blob)->len));
+
+/**
+ * Configuration data for security will be stored in below fashion in a
+ * flat file on persistent storage.
+ *
+ *  --------------------------------------------------------------
+ *  | OCSecConfigData| OCSecBlob #1 | OCSecBlob #2 | OCSecBlob #3|
+ *  --------------------------------------------------------------
+ */
+
+#endif //OC_SECURITY_CONFIG_H
+
+
+
diff --git a/resource/csdk/security/src/ocsecurity.c b/resource/csdk/security/src/ocsecurity.c
new file mode 100644 (file)
index 0000000..3dfe6e0
--- /dev/null
@@ -0,0 +1,237 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "ocstack.h"
+#include "ocmalloc.h"
+#include "ocsecurity.h"
+#include "ocsecurityconfig.h"
+#include "cainterface.h"
+#include <string.h>
+
+static OCSecConfigData* secConfigData;
+static int secConfigDataLen;
+
+
+/**
+ * This internal API removes/clears the global variable holding the security
+ * config data. This needs to be invoked when OIC stack is shutting down.
+ *
+ * @retval none
+ */
+void DeinitOCSecurityInfo()
+{
+    if (secConfigData)
+    {
+        // Initialize sensitive data to zeroes before freeing.
+        memset(secConfigData, 0, secConfigDataLen);
+
+        OCFree(secConfigData);
+        secConfigData = NULL;
+    }
+}
+
+/**
+ * This internal callback is used by lower stack (i.e. CA layer) to
+ * retrieve PSK credentials from RI security layer.
+ *
+ * Note: When finished, caller should initialize memory to zeroes and
+ * invoke OCFree to delete @p credInfo.
+ *
+ * @param credInfo
+ *     binary blob containing PSK credentials
+ *
+ * @retval none
+ */
+#ifdef __WITH_DTLS__
+void GetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+{
+    // CA layer interface publishes security data structures ONLY if
+    // stack is compiled in SECURED mode
+    CADtlsPskCredsBlob_t * caBlob = NULL;
+    if(secConfigData && credInfo)
+    {
+        unsigned int i = 0;
+        OCSecBlob * osb = (OCSecBlob*)secConfigData->blob;
+        for ( ;(i<secConfigData->numBlob) && osb; i++)
+        {
+            if (osb->type == OC_BLOB_TYPE_PSK)
+            {
+                caBlob = (CADtlsPskCredsBlob_t *)OCCalloc(sizeof(CADtlsPskCredsBlob_t), 1);
+                if (caBlob)
+                {
+                    OCDtlsPskCredsBlob * ocBlob = (OCDtlsPskCredsBlob *)osb->val;
+
+                    memcpy(caBlob->identity, ocBlob->identity, sizeof(caBlob->identity));
+                    caBlob->num = ocBlob->num;
+                    caBlob->creds =
+                        (OCDtlsPskCreds*) OCMalloc(caBlob->num * sizeof(OCDtlsPskCreds));
+                    if (caBlob->creds)
+                    {
+                        memcpy(caBlob->creds, ocBlob->creds,
+                                caBlob->num * sizeof(OCDtlsPskCreds));
+                        *credInfo = caBlob;
+                        // We copied the credential blob in the CA data structure.
+                        // Let's get out of here.
+                        return;
+                    }
+                }
+                break;
+            }
+            osb = config_data_next_blob(osb);
+        }
+    }
+
+    // Clear memory if any memory allocation failed above
+    if(caBlob)
+    {
+        OCFree(caBlob->creds);
+        OCFree(caBlob);
+    }
+}
+#endif //__WITH_DTLS__
+
+
+/**
+ * This method validates the sanctity of OCDtlsPskCredsBlob.
+ *
+ * @param secBlob
+ *     binary blob containing PSK credentials
+ *
+ * @retval OC_STACK_OK for Success, otherwise some error value
+ */
+static
+OCStackResult ValidateBlobTypePSK(const OCSecBlob *secBlob)
+{
+    OCDtlsPskCredsBlob *pskCredsBlob;
+    uint16_t validLen;
+
+    if(!secBlob || secBlob->len == 0)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    pskCredsBlob = (OCDtlsPskCredsBlob *)secBlob->val;
+
+    //calculate the expected length of PSKCredsBlob
+    if(pskCredsBlob->num >= 1)
+    {
+        validLen = sizeof(OCDtlsPskCredsBlob) +
+            (pskCredsBlob->num - 1) * sizeof(OCDtlsPskCredsBlob);
+    }
+    else
+    {
+        validLen = sizeof(OCDtlsPskCredsBlob);
+    }
+
+    if(secBlob->len != validLen)
+        return OC_STACK_INVALID_PARAM;
+
+    return OC_STACK_OK;
+}
+
+
+/**
+ * This method validates the sanctity of configuration data provided
+ * by application to OC stack.
+ *
+ * @param cfgdata
+ *     binary blob containing credentials and other config data
+ * @param len
+ *     length of binary blob
+ *
+ * @retval OC_STACK_OK for Success, otherwise some error value
+ */
+static
+OCStackResult ValidateSecConfigData(const OCSecConfigData *cfgData,
+                size_t len)
+{
+    OCStackResult ret = OC_STACK_OK;
+    unsigned int i = 0;
+    OCSecBlob * osb = NULL;
+
+    if (!cfgData || (len == 0))
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if (cfgData->version != OCSecConfigVer_CurrentVersion)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    osb = (OCSecBlob*)cfgData->blob;
+    for ( ;(i<cfgData->numBlob) && osb; i++)
+    {
+        if (osb->type == OC_BLOB_TYPE_PSK)
+        {
+            ret = ValidateBlobTypePSK(osb);
+        }
+        else
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        if (ret != OC_STACK_OK)
+        {
+            return ret;
+        }
+        osb = config_data_next_blob(osb);
+    }
+
+    return ret;
+}
+
+
+
+/**
+ * Provides the Security configuration data to OC stack.
+ *
+ * @param cfgdata
+ *     binary blob containing credentials and other config data
+ * @param len
+ *     length of binary blob
+ *
+ * @retval OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult OCSecSetConfigData(const OCSecConfigData *cfgData,
+                size_t len)
+{
+    // Validate the data inside blob before consuming
+    if (cfgData && ValidateSecConfigData(cfgData, len) == OC_STACK_OK)
+    {
+        // Remove existing blob
+        DeinitOCSecurityInfo();
+        // Allocate storage for new blob
+        secConfigData = (OCSecConfigData*)OCMalloc(len);
+        if (secConfigData)
+        {
+            memcpy(secConfigData, cfgData, len);
+            secConfigDataLen = len;
+            return OC_STACK_OK;
+        }
+
+        return OC_STACK_NO_MEMORY;
+    }
+
+    return OC_STACK_INVALID_PARAM;
+}
+
+
+
index 67c58a9..15a7862 100644 (file)
 #ifndef OC_CLIENT_CB
 #define OC_CLIENT_CB
 
-#include <ocstack.h>
-#include <occoaptoken.h>
-#include <ocresource.h>
+#include "ocstack.h"
 
-typedef struct OCPresence {
+#include "ocresource.h"
+#include "cacommon.h"
+
+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 resourcetype_t OCResourceType;
 
 typedef struct ClientCB {
     // callback method defined in application address space
@@ -49,7 +52,9 @@ typedef struct ClientCB {
     // callback method to delete context data
     OCClientContextDeleter deleteCallback;
     //  when a response is recvd with this token, above callback will be invoked
-    OCCoAPToken token;
+    CAToken_t token;
+    // a response is recvd with this token length
+    uint8_t tokenLength;
     // Invocation handle tied to original call to OCDoResource()
     OCDoHandle handle;
     // This is used to determine if all responses should be consumed or not.
@@ -58,46 +63,57 @@ 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;
     OCResourceType * filterResourceType;
     #endif
+    // The connectivity type on which the request was sent on.
+    OCConnectivityType conType;
+    // The TTL for this callback. Holds the time till when this callback can
+    // still be used. TTL is set to 0 when the callback is for presence and observe.
+    // Presence has ttl mechanism in the "presence" member of this struct and observes
+    // can be explicitly cancelled.
+    uint32_t TTL;
     // next node in this list
     struct ClientCB    *next;
 } 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
  *              the resourceType associated with a presence request.
- *
+ * @param[in] conType
+ *              the connectivity type on which the associated request for this clientCB was sent on.
+ * @param[in] ttl
+ *              time to live in coap_ticks for the callback.
  * @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,
-        OCCoAPToken * token, OCDoHandle *handle, OCMethod method,
-        unsigned char * requestUri, unsigned char * resourceType);
+OCStackResult
+AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
+             CAToken_t token, uint8_t tokenLength,
+             OCDoHandle *handle, OCMethod method,
+             char * requestUri, char * resourceTypeName, OCConnectivityType conType, uint32_t ttl);
 
-//-- DeleteClientCB -----------------------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to remove a callback node from cbList.
@@ -105,14 +121,12 @@ OCStackResult 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.
@@ -121,37 +135,37 @@ 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(OCCoAPToken * token, OCDoHandle handle, unsigned char * requestUri);
-
+ClientCB* GetClientCB(const CAToken_t token, uint8_t tokenLength,
+        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
  *      OC_STACK_ERROR with invalid parameters
  *      OC_STACK_NO_MEMORY when out of memory
  */
-OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceTypeName);
+#ifdef WITH_PRESENCE
+OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, 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
@@ -160,7 +174,6 @@ void DeleteClientCBList();
  * @param[in] cbNode
  *              address to client callback node.
  */
-//------------------------------------------------------------------------
 void FindAndDeleteClientCB(ClientCB * cbNode);
 
 /** @ingroup ocstack
@@ -174,7 +187,7 @@ void FindAndDeleteClientCB(ClientCB * cbNode);
  *              The resulting node from making this call. Null if doesn't exist.
  */
 //------------------------------------------------------------------------
-OCMulticastNode* GetMCPresenceNode(unsigned char * uri);
+OCMulticastNode* GetMCPresenceNode(const char * uri);
 
 /** @ingroup ocstack
  *
@@ -190,6 +203,7 @@ OCMulticastNode* GetMCPresenceNode(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 ba87306..fc76777 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, per
+// https://tools.ietf.org/html/draft-ietf-core-observe-16
 #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 {
+/**
+ * This information is stored for each registered observer.
+ */
+typedef struct ResourceObserver
+{
     // Observation Identifier for request
     OCObservationId observeId;
     // URI of observed resource
-    unsigned char *resUri;
+    char *resUri;
     // Query
-    unsigned char *query;
-    // CoAP token for the observe request
-    OCCoAPToken token;
+    char *query;
+    //token for the observe request
+    CAToken_t token;
+    //token length for the observe request
+    uint8_t tokenLength;
     // Resource handle
     OCResource *resource;
-    // IP address & port of client registered for observe
-    OCDevAddr *addr;
+    //TODO bundle it in Endpoint structure(address, uri, type, secured)
+    /** Remote Endpoint address **/
+    CAAddress_t addressInfo;
+    /** Connectivity of the endpoint**/
+    CATransportType_t connectivityType;
     // Quality of service of the request
     OCQualityOfService qos;
     // number of times the server failed to reach the observer
@@ -54,33 +63,148 @@ typedef struct ResourceObserver {
 } ResourceObserver;
 
 #ifdef WITH_PRESENCE
+/**
+ * Create an observe response and send to all observers in the observe list.
+ *
+ * @param method RESTful method.
+ * @param resPtr Observed resource.
+ * @param maxAge Time To Live (in seconds) of observation.
+ * @param resourceType Resource type.  Allows resource type name to be added to response.
+ * @param qos Quality of service of resource.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
         OCResourceType *resourceType, OCQualityOfService qos);
 #else
+/**
+ * Create an observe response and send to all observers in the observe list.
+ *
+ * @param method RESTful method.
+ * @param resPtr Observed resource.
+ * @param maxAge Time To Live (in seconds) of observation.
+ * @param qos Quality of service of resource.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge,
         OCQualityOfService qos);
 #endif
+
+/**
+ * Notify specific observers with updated value of representation.
+ *
+ * @param resource Observed resource
+ * @param obsIdList List of observation ids that need to be notified.
+ * @param numberOfIds Number of observation ids included in obsIdList.
+ * @param notificationJSONPayload - JSON encoded payload to send in notification.
+ * @param maxAge Time To Live (in seconds) of observation.
+ * @param qos Desired quality of service of the observation notifications.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult SendListObserverNotification (OCResource * resource,
         OCObservationId  *obsIdList, uint8_t numberOfIds,
-        unsigned char *notificationJSONPayload, uint32_t maxAge,
+        const char *notificationJSONPayload, uint32_t maxAge,
         OCQualityOfService qos);
 
+/**
+ * Delete all observers in the observe list.
+ */
 void DeleteObserverList();
 
+/**
+ * Create a unique observation ID.
+ *
+ * @param observationId Pointer to generated ID.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult GenerateObserverId (OCObservationId *observationId);
 
+/**
+ * Add observer for a resource.
+ *
+ * @param resUri Resource URI string.
+ * @param query Query string.
+ * @param obsId Observation ID.
+ * @param token Request token.
+ * @param tokenLength Length of token.
+ * @param resHandle Resource handle.
+ * @param qos Quality of service of observation.
+ * @param addressInfo Address of observer.
+ * @param connectivityType Connection type.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult AddObserver (const char         *resUri,
                            const char         *query,
                            OCObservationId    obsId,
-                           OCCoAPToken        *token,
-                           OCDevAddr          *addr,
+                           CAToken_t          token,
+                           uint8_t            tokenLength,
                            OCResource         *resHandle,
-                           OCQualityOfService qos);
+                           OCQualityOfService qos,
+                           const CAAddress_t  *addressInfo,
+                           CATransportType_t connectivityType);
 
-OCStackResult DeleteObserverUsingToken (OCCoAPToken * token);
+/**
+ * Delete observer with specified token from list of observers.
+ * Free memory that was allocated for the observer in the list.
+ *
+ * @param token Token to search for.
+ * @param tokenLength Length of token.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+ OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength);
 
-ResourceObserver* GetObserverUsingToken (const OCCoAPToken * token);
+/**
+ * Search the list of observers for the specified token.
+ *
+ * @param token Token to search for.
+ * @param tokenLength Length of token.
+ *
+ * @return Pointer to found observer.
+ */
+ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength);
 
+/**
+ * Search the list of observers for the specified observe ID.
+ *
+ * @param observeId Observer ID to search for
+ *
+ * @return Pointer to found observer.
+ */
 ResourceObserver* GetObserverUsingId (const OCObservationId observeId);
 
+/**
+ * Add observe header option to a request.
+ *
+ * @param caHdrOpt Target request CA header option.
+ * @param ocHdrOpt Pointer to existing options.
+ * @param numOptions Number of existing options.
+ * @param observeFlag Register/de-register observation.  Should be either
+ *                      ::OC_OBSERVE_REGISTER or ::OC_OBSERVE_DEREGISTER.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+OCStackResult
+CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
+                           OCHeaderOption *ocHdrOpt,
+                           uint8_t numOptions,
+                           uint8_t observeFlag);
+
+/**
+ * Copy the observe option from a received request
+ *
+ * @param observationOption Pointer to observe option value.  Should be either
+ *  ::OC_OBSERVE_REGISTER, ::OC_OBSERVE_DEREGISTER, or ::OC_OBSERVE_NO_OPTION if observe not found.
+ *
+ * @param options Options in received request.  Observe option is removed if found.
+ * @param numOptions Number of options in the received request.  Decremented if observe option is
+ *                     extracted.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+OCStackResult
+GetObserveHeaderOption (uint32_t * observationOption,
+                        CAHeaderOption_t *options,
+                        uint8_t * numOptions);
+
 #endif //OC_OBSERVE_H
+
index bbd652b..acd6de4 100644 (file)
@@ -21,6 +21,9 @@
 #ifndef OCRESOURCE_H_
 #define OCRESOURCE_H_
 
+#include "ocstackconfig.h"
+#include "occlientcb.h"
+
 #define OC_OBSERVER_NOT_INTERESTED       (0)
 #define OC_OBSERVER_STILL_INTERESTED     (1)
 #define OC_OBSERVER_FAILED_COMM          (2)
@@ -74,17 +77,17 @@ typedef struct ocaction {
 } OCAction;
 
 // following structure will be created in occollection.
-typedef struct ocactionset {
-
+typedef struct ocactionset
+{
     struct ocactionset *next;
 
     char *actionsetName;
+    long int timesteps;
+    unsigned int type;
 
     OCAction* head;
 } OCActionSet;
 
-
-
 typedef struct resourcetype_t {
     struct resourcetype_t *next; // linked list; for multiple types on resource
 
index f56769c..a946686 100644 (file)
 #include "ocstackinternal.h"
 #include "ocserverrequest.h"
 
-#define OC_RSRVD_OC                     "oc"
-#define OC_RSRVD_PAYLOAD                "payload"
-#define OC_RSRVD_HREF                   "href"
-#define OC_RSRVD_RESOURCE_TYPE          "rt"
-#define OC_RSRVD_RESOURCE_TYPE_PRESENCE "core.presence"
-#define OC_RSRVD_INTERFACE              "if"
-#define OC_RSRVD_DEVICE_ID              "di"
-#define OC_RSRVD_DEVICE_NAME            "dn"
-#define OC_RSRVD_INTERFACE_DEFAULT      "oc.mi.def"
-#define OC_RSRVD_INTERFACE_LL           "oc.mi.ll"
-#define OC_RSRVD_INTERFACE_BATCH        "oc.mi.b"
-#define OC_RSRVD_INTERFACE_GROUP        "oc.mi.c"
-
-
-#define OC_RSRVD_OBSERVABLE             "obs"
-#define OC_RSRVD_SECURE                 "sec"
-#define OC_RSRVD_HOSTING_PORT           "port"
-
+/**
+ * Common JSON string components used by the stack to build JSON strings.
+ * These details are exposed in ocstackconfig.h file in the form of documentation.
+ * Remember to update the documentation there if these are changed.
+ */
 #define OC_JSON_PREFIX                     "{\"oc\":["
 #define OC_JSON_PREFIX_LEN                 (sizeof(OC_JSON_PREFIX) - 1)
 #define OC_JSON_SUFFIX                     "]}"
 #define OC_JSON_SUFFIX_LEN                 (sizeof(OC_JSON_SUFFIX) - 1)
 #define OC_JSON_SEPARATOR                  ','
+#define OC_JSON_SEPARATOR_STR              ","
 
+/**
+ * Static values for various JSON attributes.
+ */
 #define OC_RESOURCE_OBSERVABLE   1
 #define OC_RESOURCE_SECURE       1
 
-typedef enum {
+/**
+ * The type of query a request/response message is.
+ */
+typedef enum
+{
     STACK_RES_DISCOVERY_NOFILTER = 0,
     STACK_RES_DISCOVERY_IF_FILTER,
     STACK_RES_DISCOVERY_RT_FILTER,
@@ -60,7 +55,11 @@ typedef enum {
     STACK_DEVICE_DISCOVERY_DN_FILTER
 } StackQueryTypes;
 
-typedef enum {
+/**
+ * The type of handling required to handle a request.
+ */
+typedef enum
+{
     OC_RESOURCE_VIRTUAL = 0,
     OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER,
     OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER,
@@ -70,28 +69,77 @@ typedef enum {
     OC_RESOURCE_NOT_SPECIFIED
 } ResourceHandling;
 
+/**
+ * Default entity handler (ie. callback) to be used for resources with
+ * no entity handler.
+ */
 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
         OCEntityHandlerRequest * request);
 
-const char * GetVirtualResourceUri( OCVirtualResources resource);
+/**
+ * Get string value associated with a virtual resource type.
+ */
+const char * GetVirtualResourceUri(OCVirtualResources resource);
+
+/**
+ * Find and retrieve pointer to a resource associated with a specific resource
+ * URI.
+ */
 OCResource *FindResourceByUri(const char* resourceUri);
-uint8_t IsVirtualResource(const char* resourceUri);
 
-OCStackResult DetermineResourceHandling (OCServerRequest *request,
+/**
+ * Returns true if the specificed resource URI aligns with a pre-existing
+ * virtual resource; returns false otherwise.
+ */
+bool IsVirtualResource(const char* resourceUri);
+
+/**
+ * Parameter @ref handling returns by-reference the type of resource handling
+ * required by the internal stack based on the specified @ref request.
+ */
+OCStackResult DetermineResourceHandling (const OCServerRequest *request,
                                          ResourceHandling *handling,
                                          OCResource **resource);
 
-OCStackResult
-ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request);
-
-OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo);
-
+/**
+ * Processes the specified @ref request based on the type of resource handling
+ * @ref resHandling.
+ */
+OCStackResult ProcessRequest(ResourceHandling resHandling,
+                             OCResource *resource,
+                             OCServerRequest *request);
+
+/**
+ * Internal API used to save all of the platform's information for use in platform
+ * discovery requests.
+ */
+OCStackResult SavePlatformInfo(OCPlatformInfo info);
+
+/**
+ * Internal API used to clear the platform information.
+ */
+void DeletePlatformInfo();
+
+/**
+ * Internal API used to clear the device information.
+ */
 void DeleteDeviceInfo();
 
-OCStackResult
-BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
-                        char *filterValue, char * out, uint16_t *remaining);
-
+/**
+ * Prepares a JSON string for response.
+ */
+OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
+                                           uint8_t filterOn,
+                                           const char *filterValue,
+                                           char * out,
+                                           uint16_t *remaining,
+                                           CATransportType_t connType);
+
+/**
+ * A helper function that Maps an @ref OCEntityHandlerResult type to an
+ * @ref OCStackResult type.
+ */
 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult);
 
 #endif //OC_RESOURCEHANDLER_H
+
index e96ed51..7909399 100644 (file)
 #ifndef OC_SERVER_REQUEST_H
 #define OC_SERVER_REQUEST_H
 
-#include "occoap.h"
-
+#include "cacommon.h"
+#include "cainterface.h"
 /**
  * The signature of the internal call back functions to handle responses from entity handler
  */
 typedef OCStackResult (* OCEHResponseHandler)(OCEntityHandlerResponse * ehResponse);
-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;
@@ -46,11 +45,14 @@ typedef struct OCServerRequest {
     OCStackResult observeResult;
     uint8_t numResponses;
     OCEHResponseHandler ehResponseHandler;
-    //////////////////////////////////////////////////////////
-    // IP address & port of client registered for observe   //These
-    OCDevAddr requesterAddr;                                //Members
-    // CoAP token for the observe request                   //Might
-    OCCoAPToken requestToken;                               //Be
+    /** Remote Endpoint address **/
+    CAAddress_t addressInfo;
+    /** Connectivity of the endpoint**/
+    CATransportType_t connectivityType;
+    // token for the request
+    CAToken_t requestToken;
+    // token length the request
+    uint8_t tokenLength;
     // The ID of CoAP pdu                                   //Kept in
     uint16_t coapID;                                        //CoAP
     uint8_t delayedResNeeded;
@@ -65,46 +67,135 @@ 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;
 
-OCServerRequest * GetServerRequestUsingToken (const OCCoAPToken token);
+/**
+ * Handler function for sending a response from a single resource
+ *
+ * @param ehResponse - pointer to the response from the resource
+ *
+ * @return
+ *     OCStackResult
+ */
+OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse);
 
+/**
+ * Handler function for sending a response from multiple resources, such as a collection.
+ * Aggregates responses from multiple resource until all responses are received then sends the
+ * concatenated response
+ *
+ * TODO: Need to add a timeout in case a (remote?) resource does not respond
+ *
+ * @param ehResponse - pointer to the response from the resource
+ *
+ * @return
+ *     OCStackResult
+ */
+OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse);
+
+/**
+ * Get a server request from the server request list using the specified token.
+ *
+ * @param token - token of server request
+ * @param tokenLength - length of token
+ *
+ * @return
+ *     OCServerRequest*
+ */
+OCServerRequest * GetServerRequestUsingToken (const CAToken_t token, uint8_t tokenLength);
+
+/**
+ * Get a server request from the server request list using the specified handle
+ *
+ * @param handle - handle of server request
+ * @return
+ *     OCServerRequest*
+ */
 OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle);
 
+/**
+ * Get a server response from the server response list using the specified handle
+ *
+ * @param handle - handle of server response
+ *
+ * @return
+ *     OCServerResponse*
+ */
 OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle);
 
+/**
+ * Add a server request to the server request list
+ *
+ * @param request - initialized server request that is created by this function
+ * @param coapID - ID of CoAP pdu
+ * @param delayedResNeeded - delayed response required 0=no 1=yes
+ * @param secured - secure endpoint 0=no 1=yes
+ * @param notificationFlag - //TODO: remove - does not appear to be used any longer
+ * @param method - RESTful method
+ * @param numRcvdVendorSpecificHeaderOptions - number of received vendor specific header options
+ * @param observationOption - value of observation option
+ * @param qos - request QOS
+ * @param query - request query
+ * @param rcvdVendorSpecificHeaderOptions - received vendor specific header options
+ * @param reqJSONPayload - request JSON payload
+ * @param requestToken - request token
+ * @param tokenLength - request token length
+ * @param resourceUrl - URL of resource
+ * @param reqTotalSize - total size of the request
+ * @param addressInfo - CA Address
+ * @param connectivityType - connection type
+ *
+ * @return
+ *     OCStackResult
+ */
 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, OCCoAPToken * requestToken,
-        OCDevAddr * requesterAddr, unsigned char * resourceUrl, uint32_t reqTotalSize);
-
-OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle);
+        char * reqJSONPayload, CAToken_t requestToken,
+        uint8_t tokenLength,
+        char * resourceUrl, size_t reqTotalSize,
+        CAAddress_t *addressInfo, CATransportType_t connectivityType);
 
-// Internal function to create OCEntityHandlerRequest at the server from a received coap pdu
+/**
+ * Form the OCEntityHandlerRequest struct that is passed to a resource's entity handler
+ *
+ * @param entityHandlerRequest - pointer to the OCEntityHandlerRequest struct that is created
+ * @param request          - request handle
+ * @param method           - RESTful method
+ * @param resource         - resource handle
+ * @param queryBuf         - resource query of request
+ * @param bufReqPayload    - JSON payload of request
+ * @param numVendorOptions - number of vendor options
+ * @param vendorOptions    - vendor options
+ * @param observeAction    - observe action flag
+ * @param observeID        - observe ID
+ *
+ * @return
+ *     OCStackResult
+ */
 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);
 
+/**
+ * Find a server request in the server request list and delete
+ *
+ * @param serverRequest - server request to find and delete
+ */
 void FindAndDeleteServerRequest(OCServerRequest * serverRequest);
 
-void DeleteServerRequest(OCServerRequest * serverRequest);
-
-void FindAndDeleteServerResponse(OCServerResponse * serverResponse);
-
-void DeleteServerResponse(OCServerResponse * serverResponse);
-
 #endif //OC_SERVER_REQUEST_H
+
index 2a4d8f6..83989a5 100644 (file)
 //-----------------------------------------------------------------------------
 // Includes
 //-----------------------------------------------------------------------------
+#include <stdbool.h>
 #include "ocstack.h"
 #include "ocstackconfig.h"
-#include "occoaptoken.h"
 #include "occlientcb.h"
 #include <logger.h>
 #include <ocrandom.h>
 
+#include "cacommon.h"
+#include "cainterface.h"
+
 #ifdef __cplusplus
 extern "C" {
 #endif // __cplusplus
@@ -51,40 +54,37 @@ extern OCDeviceEntityHandler defaultDeviceHandler;
 #define OC_COAP_SCHEME "coap://"
 #define OC_OFFSET_SEQUENCE_NUMBER (4) // the first outgoing sequence number will be 5
 
-typedef struct {
-    // Observe option field
-    uint32_t option;
-    // IP address & port of client registered for observe
-    OCDevAddr *subAddr;
-    // CoAP token for the observe request
-    OCCoAPToken *token;
-    // The result of the observe request
-    OCStackResult result;
-} OCObserveReq;
-
-// following structure will be created in occoap and passed up the stack on the server side
-typedef struct {
+/**
+ * This structure will be created in occoap and passed up the stack on the server side.
+ */
+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
     uint8_t numRcvdVendorSpecificHeaderOptions;
     OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
+
+    /** Remote Endpoint address **/
     //////////////////////////////////////////////////////////
-    // TODO: Consider moving these member to CoAP
-    // IP address & port of client registered for observe
-    OCDevAddr requesterAddr;
-    // CoAP token for the observe request
-    OCCoAPToken requestToken;
+    // TODO: bundle this up as endpoint
+    CAAddress_t addressInfo;
+    /** Connectivity of the endpoint**/
+    CATransportType_t connectivityType;
+
+    //token for the observe request
+    CAToken_t requestToken;
+    uint8_t tokenLength; //token length
     // The ID of CoAP pdu
     uint16_t coapID;
     uint8_t delayedResNeeded;
@@ -95,68 +95,142 @@ typedef struct {
     uint16_t reqPacketSize;
     uint32_t resPacketNum;
     uint16_t resPacketSize;
-    uint32_t reqTotalSize;
+    size_t reqTotalSize;
 } OCServerProtocolRequest;
 
+/**
+ * This structure will be created in occoap and passed up the stack on the client side.
+ */
 typedef struct
 {
-    // Observe option field
-    uint32_t observationOption;
-    // qos is indicating if the request is CON or NON
-    OCQualityOfService qos;
-    // Allow the entity handler to pass a result with the response
-    OCStackResult result;
-    // IP address & port of client registered for observe
-    OCDevAddr *requesterAddr;
-    // CoAP token for the observe request
-    OCCoAPToken *requestToken;
-    // The ID of CoAP pdu
-    uint16_t coapID;
-    // Flag indicating that response is to be delayed before sending
-    uint8_t delayedResNeeded;
-    uint8_t secured;
-    uint8_t slowFlag;
-    uint8_t notificationFlag;
-    // this is the pointer to server payload data to be transferred
-    unsigned 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;
-} OCServerProtocolResponse;
-
-// following structure will be created in occoap and passed up the stack on the client side
-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 TTL;
+    uint32_t maxAge;
+    // This is the Uri of the resource. (ex. "coap://192.168.1.1/a/led")
+    char * fullUri;
+    // This is the relative Uri of the resource. (ex. "/a/led")
+    char * rcvdUri;
+    // This is the received payload.
+    char * bufRes;
+
+    // This is the token received OTA.
+    CAToken_t rcvdToken;
+
     // this structure will be passed to client
     OCClientResponse * clientResponse;
 } OCResponse;
 
+/**
+ * This typedef is to represent our Server Instance identification.
+ */
+typedef uint8_t ServerID[16];
+
 //-----------------------------------------------------------------------------
 // Internal function prototypes
 //-----------------------------------------------------------------------------
-OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status);
+
+
+OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status);
+
 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest);
-void HandleStackResponses(OCResponse * response);
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
+
+OCStackResult SendDirectStackResponse(const CARemoteEndpoint_t* endPoint, const uint16_t coapID,
+        const CAResponseResult_t responseResult, const CAMessageType_t type,
+        const uint8_t numOptions, const CAHeaderOption_t *options,
+        CAToken_t token, uint8_t tokenLength);
+
+
 #ifdef WITH_PRESENCE
+/**
+ * Notify Presence subscribers that a resource has been modified.
+ *
+ * @param resourceType Handle to the resourceType linked list of resource
+ *                     that was modified.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult SendPresenceNotification(OCResourceType *resourceType);
-#endif
 
+/**
+ * Send Stop Notification to Presence subscribers.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+OCStackResult SendStopNotification();
+#endif // WITH_PRESENCE
+bool ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
+
+/**
+ * Bind a resource interface to a resource.
+ *
+ * @param resource Target resource.
+ * @param resourceInterfaceName Resource interface.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
                                             const char *resourceInterfaceName);
-
+/**
+ * Bind a resourcetype to a resource.
+ *
+ * @param resource Target resource.
+ * @param resourceTypeName Name of resource type.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
 OCStackResult BindResourceTypeToResource(OCResource* resource,
                                             const char *resourceTypeName);
-OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName);
+
+// Converts a CAResult_t type to a OCStackResult type.
+/**
+ * Converts a CAResult_t type to a OCStackResult type.
+ *
+ * @param caResult CAResult_t value to convert
+ * @return OCStackResult that was converted from the input CAResult_t value.
+ */
+OCStackResult CAResultToOCResult(CAResult_t caResult);
+
+/**
+ * Get a byte representation of the server instance ID.
+ * The memory is managed internal to this function, so freeing it externally will
+ * result in a runtime error
+ *
+ * Note: This will NOT seed the RNG, so it must be called after the RNG is seeded.
+ * This is done automatically during the OCInit process,
+ * so ensure that this call is done after that.
+ *
+ * @return A uint8_t representation the server instance ID.
+ */
+const uint8_t* OCGetServerInstanceID(void);
+
+/**
+ * Get a string representation the server instance ID.
+ * The memory is managed internal to this function, so freeing externally will result
+ * in a runtime error
+ * Note: This will NOT seed the RNG, so it must be called after the RNG is seeded.
+ * This is done automatically during the OCInit process,
+ * so ensure that this call is done after that.
+ *
+ * @return A string representation  the server instance ID.
+ */
+const char* OCGetServerInstanceIDString(void);
+
+/**
+ * Map OCQualityOfService to CAMessageType.
+ *
+ * @param qos Input qos.
+ * @return CA message type for a given qos.
+ */
+CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos);
 
 #ifdef WITH_PRESENCE
+/**
+ * Enable/disable a resource property.
+ *
+ * @param inputProperty Pointer to resource property.
+ * @param resourceProperties Property to be enabled/disabled.
+ * @param enable 0:disable, 1:enable.
+ *
+ * @return OCStackResult that was converted from the input CAResult_t value.
+ */
 //TODO: should the following function be public?
 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
         OCResourceProperty resourceProperties, uint8_t enable);
@@ -167,3 +241,4 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
 #endif // __cplusplus
 
 #endif /* OCSTACKINTERNAL_H_ */
+
index 2493fba..3b0c784 100644 (file)
 #ifndef OIC_GROUP_H
 #define OIC_GROUP_H
 
-#include "ocstack.h"
 #include "ocstackinternal.h"
+#include "ocstack.h"
+#include "ocresource.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
 
 void AddCapability(OCCapability** head, OCCapability* node);
 
 void AddAction(OCAction** head, OCAction* node);
 
-void AddActionSet(OCActionSet **head, OCActionSet* node);
+OCStackResult AddActionSet(OCActionSet **head, OCActionSet* node);
 
 void DeleteCapability(OCCapability *del);
 
@@ -40,18 +45,25 @@ OCStackResult DeleteActionSets(OCResource** resource);
 
 OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actionsetName);
 
-OCStackResult GetActionSetFromString(OCResource **resource, unsigned char *request, char** method,
-        char **actionsetName);
+OCStackResult ExtractKeyValueFromRequest(char *request, char **key, char **value);
+
+OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc);
 
-OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc);
+OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc);
 
 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
         OCClientResponse* clientResponse);
 
 void ActionSetCD(void *context);
 
+
 OCStackResult
 BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHandlerFlag flag*/,
         OCResource *resource, OCEntityHandlerRequest *ehRequest);
 
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
 #endif // OIC_GROUP_H
diff --git a/resource/csdk/stack/include/ocsecurity.h b/resource/csdk/stack/include/ocsecurity.h
deleted file mode 100644 (file)
index 0d71086..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef OC_SECURITY_H
-#define OC_SECURITY_H
-
-#include "ocstack.h"
-#include "ocsecurityconfig.h"
-#include <stdio.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-/**
- * Provides the DTLS PSK credetials blob to OC stack.
- *
- * @param credInfo
- *     binary blob containing credentials
- * @param len
- *     length of binary blob
- *
- * @retval OC_STACK_OK for Success, otherwise some error value
- */
-OCStackResult OCSetDtlsPskCredentials(const OCDtlsPskCredsBlob *credInfo,
-                size_t len);
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-#endif //OC_SECURITY_H
diff --git a/resource/csdk/stack/include/ocsecurityconfig.h b/resource/csdk/stack/include/ocsecurityconfig.h
deleted file mode 100644 (file)
index eaa06b4..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef OC_SECURITY_CONFIG_H
-#define OC_SECURITY_CONFIG_H
-
-#include <stdint.h>
-
-#define DTLS_PSK_ID_LEN 16
-#define DTLS_PSK_PSK_LEN 16
-
-#define DtlsPskCredsBlobVer_1 1 /**< Credentials stored in plaintext */
-#define DtlsPskCredsBlobVer_CurrentVersion DtlsPskCredsBlobVer_1
-
-/**
- * Credentials for a device. Includes identity and the associated PSK.
- */
-typedef struct
-{
-   unsigned char id[DTLS_PSK_ID_LEN];
-   unsigned char psk[DTLS_PSK_PSK_LEN];
-} OCDtlsPskCreds;
-
-
-/**
- * Binary blob containing device identity and the credentials for all devices
- * trusted by this device.
- */
-typedef struct
-{
-   uint16_t blobVer;                        /**< version of the blob */
-   uint16_t reserved;                       /**< reserved for future use */
-   unsigned char identity[DTLS_PSK_ID_LEN]; /**< identity of self */
-   uint32_t num;                            /**< number of credentials in this blob */
-   OCDtlsPskCreds creds[1];                 /**< list of credentials. Size of this
-                                                 array is determined by 'num' variable. */
-} OCDtlsPskCredsBlob;
-
-
-#endif //OC_SECURITY_CONFIG_H
-
-
index 8be0d12..73bcd8c 100644 (file)
 #ifndef OCSTACK_H_
 #define OCSTACK_H_
 
-#include "ocsocket.h"
-#include "ocstackconfig.h"
+#include <stdint.h>
+#include "octypes.h"
 
 #ifdef __cplusplus
 extern "C" {
 #endif // __cplusplus
 #define WITH_PRESENCE
-//-----------------------------------------------------------------------------
-// Defines
-//-----------------------------------------------------------------------------
-
-//TODO: May want to refactor this in upcoming sprints.
-//Don't want to expose to application layer that lower level stack is using CoAP.
-#define OC_WELL_KNOWN_QUERY                  "coap://224.0.1.187:5683/oc/core"
-#define OC_EXPLICIT_DEVICE_DISCOVERY_URI     "coap://224.0.1.187:5683/oc/core?rt=core.led"
-#define OC_MULTICAST_PREFIX                  "coap://224.0.1.187:5683"
-#define OC_MULTICAST_IP                      "coap://224.0.1.187"
-
 #define USE_RANDOM_PORT (0)
-#ifdef WITH_PRESENCE
-#define OC_DEFAULT_PRESENCE_TTL (60)
-#define OC_PRESENCE_URI                      "/oc/presence"
-extern uint8_t PresenceTimeOutSize; // length of PresenceTimeOut - 1
-extern uint32_t PresenceTimeOut[];
-#endif
-//-----------------------------------------------------------------------------
-// Typedefs
-//-----------------------------------------------------------------------------
-
-/**
- * OC Virtual resources supported by every OC device
- */
-typedef enum {
-    OC_WELL_KNOWN_URI= 0,       // "/oc/core"
-    OC_DEVICE_URI,              // "/oc/core/d"
-    OC_RESOURCE_TYPES_URI,      // "/oc/core/d/type"
-    #ifdef WITH_PRESENCE
-    OC_PRESENCE,                // "/oc/presence"
-    #endif
-    OC_MAX_VIRTUAL_RESOURCES    // Max items in the list
-} OCVirtualResources;
-
-/**
- * Standard RESTful HTTP Methods
- */
-typedef enum {
-    OC_REST_NOMETHOD    = 0,
-    OC_REST_GET         = (1 << 0),     // Read
-    OC_REST_PUT         = (1 << 1),     // Write
-    OC_REST_POST        = (1 << 2),     // Update
-    OC_REST_DELETE      = (1 << 3),     // Delete
-    // Register observe request for most up date notifications ONLY.
-    OC_REST_OBSERVE     = (1 << 4),
-    // Register observe request for all notifications, including stale notifications.
-    OC_REST_OBSERVE_ALL = (1 << 5),
-    // Deregister observation, intended for internal use
-    OC_REST_CANCEL_OBSERVE = (1 << 6),
-    #ifdef WITH_PRESENCE
-    // Subscribe for all presence notifications of a particular resource.
-    OC_REST_PRESENCE    = (1 << 7)
-    #endif
-} OCMethod;
-
-/**
- * Host Mode of Operation
- */
-typedef enum {
-    OC_CLIENT = 0,
-    OC_SERVER,
-    OC_CLIENT_SERVER
-} OCMode;
-
-extern OCMode myStackMode;
-/**
- * Quality of Service
- */
-typedef enum {
-    OC_LOW_QOS = 0,
-    OC_MEDIUM_QOS,
-    OC_HIGH_QOS,
-    OC_NA_QOS // No Quality is defined, let the stack decide
-} OCQualityOfService;
-
-/**
- * Resource Properties
- *
- * OC_ACTIVE       - When this bit is set, the resource is initialized, otherwise the resource
- *                   is 'inactive'. 'inactive' signifies that the resource has been marked for
- *                   deletion or is already deleted.
- * OC_DISCOVERABLE - When this bit is set, the resource is allowed to be discovered by clients.
- * OC_OBSERVABLE   - When this bit is set, the resource is allowed to be observed by clients.
- * OC_SLOW         - When this bit is set, the resource has been marked as 'slow'. 'slow' signifies
- *                   that responses from this resource can expect delays in processing its
- *                   requests from clients.
- * OC_SECURE       - When this bit is set, the resource is a secure resource.
- */
-typedef enum {
-    OC_ACTIVE       = (1 << 0),
-    OC_DISCOVERABLE = (1 << 1),
-    OC_OBSERVABLE   = (1 << 2),
-    OC_SLOW         = (1 << 3),
-    OC_SECURE       = (1 << 4)
-} OCResourceProperty;
-
-/**
- * Transport Protocol IDs
- */
-typedef enum {
-    OC_INVALID_ID   = (1 << 0),
-    OC_COAP_ID      = (1 << 1)
-} OCTransportProtocolID;
-
-/**
- * Declares Stack Results & Errors
- */
-typedef enum {
-    /* Success status code - START HERE */
-    OC_STACK_OK = 0,
-    OC_STACK_RESOURCE_CREATED,
-    OC_STACK_RESOURCE_DELETED,
-    OC_STACK_CONTINUE,
-    /* Success status code - END HERE */
-    /* Error status code - START HERE */
-    OC_STACK_INVALID_URI,
-    OC_STACK_INVALID_QUERY,
-    OC_STACK_INVALID_IP,
-    OC_STACK_INVALID_PORT,
-    OC_STACK_INVALID_CALLBACK,
-    OC_STACK_INVALID_METHOD,
-    OC_STACK_INVALID_PARAM,
-    OC_STACK_INVALID_OBSERVE_PARAM,
-    OC_STACK_NO_MEMORY,
-    OC_STACK_COMM_ERROR,
-    OC_STACK_NOTIMPL,
-    OC_STACK_NO_RESOURCE,               /* resource not found */
-    OC_STACK_RESOURCE_ERROR,            /* ex: not supported method or interface */
-    OC_STACK_SLOW_RESOURCE,
-    OC_STACK_NO_OBSERVERS,              /* resource has no registered observers */
-    OC_STACK_OBSERVER_NOT_FOUND,
-    #ifdef WITH_PRESENCE
-    OC_STACK_PRESENCE_STOPPED,
-    OC_STACK_PRESENCE_TIMEOUT,
-    OC_STACK_PRESENCE_DO_NOT_HANDLE,
-    #endif
-    OC_STACK_VIRTUAL_DO_NOT_HANDLE,
-    OC_STACK_INVALID_OPTION,
-    OC_STACK_MALFORMED_RESPONSE,        /* the remote reply contained malformed data */
-    OC_STACK_PERSISTENT_BUFFER_REQUIRED,
-    OC_STACK_INVALID_REQUEST_HANDLE,
-    OC_STACK_INVALID_DEVICE_INFO,
-    OC_STACK_ERROR
-    /* Error status code - END HERE */
-} OCStackResult;
-
-/**
- * Handle to an @ref OCDoResource invocation.
- */
-typedef void * OCDoHandle;
-
-/**
- * Handle to an OCResource object owned by the OCStack.
- */
-typedef void * OCResourceHandle;
-
-typedef void * OCRequestHandle;
-typedef void * OCResponseHandle;
-
-/**
- * Unique identifier for each observation request. Used when observations are
- * registered or deregistering. Used by entity handler to signal specific
- * observers to be notified of resource changes.
- * There can be maximum of 256 observations per server.
- */
-typedef uint8_t OCObservationId;
-
-/**
- * Action associated with observation
- */
-typedef enum {
-    OC_OBSERVE_REGISTER = 0,
-    OC_OBSERVE_DEREGISTER = 1,
-    OC_OBSERVE_NO_OPTION = 2
-} OCObserveAction;
-
-typedef struct {
-    // Action associated with observation request
-    OCObserveAction action;
-    // Identifier for observation being registered/deregistered
-    OCObservationId obsId;
-} OCObservationInfo;
-
-/**
- * Possible returned values from entity handler
- */
-typedef enum {
-    OC_EH_OK = 0,
-    OC_EH_ERROR,
-    OC_EH_RESOURCE_CREATED,
-    OC_EH_RESOURCE_DELETED,
-    OC_EH_SLOW,
-    OC_EH_FORBIDDEN
-} OCEntityHandlerResult;
-
-// following structure will be used to define the vendor specific header options to be included
-// in communication packets
-
-typedef struct OCHeaderOption {
-    // The protocol ID this option applies to
-    OCTransportProtocolID protocolID;
-    // The header option ID which will be added to communication packets
-    uint16_t optionID;
-    // its length   191
-    uint16_t optionLength;
-    // pointer to its data
-    uint8_t optionData[MAX_HEADER_OPTION_DATA_LENGTH];
-} 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.
- */
-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;
-    // Information associated with observation - valid only when OCEntityHandler
-    // flag includes OC_OBSERVE_FLAG
-    OCObservationInfo obsInfo;
-    // An array of the received vendor specific header options
-    uint8_t numRcvdVendorSpecificHeaderOptions;
-    OCHeaderOption * rcvdVendorSpecificHeaderOptions;
-    // reqJSON is retrieved from the payload of the received request PDU
-    unsigned char * reqJSONPayload;
-}OCEntityHandlerRequest;
-
-/**
- * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
- */
-typedef struct {
-    // Address of remote server
-    OCDevAddr * addr;
-    // the is the result of our stack, OCStackResult should contain coap/other error codes;
-    OCStackResult result;
-    // 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;
-    // An array of the received vendor specific header options
-    uint8_t numRcvdVendorSpecificHeaderOptions;
-    OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
-}OCClientResponse;
-
-/**
- * Following structure describes the device properties. All non-Null properties will be included
- * in a device discovery request.
- */
-typedef struct
-{
-    char *deviceName;
-    char *hostName;
-    char *deviceUUID;
-    char *contentType;
-    char *version;
-    char *manufacturerName;
-    char *manufacturerUrl;
-    char *modelNumber;
-    char *dateOfManufacture;
-    char *platformVersion;
-    char *firmwareVersion;
-    char *supportUrl;
-} OCDeviceInfo;
-
-typedef struct
-{
-    // Request handle is passed to server via the entity handler for each incoming request.
-    // Stack assigns when request is received, server sets to indicate what request response is for
-    OCRequestHandle requestHandle;
-    // New handle for tracking block (or slow) response.  Stack assigns, server uses for subsequent calls
-    OCResponseHandle  *responseHandle;
-    // Resource handle
-    OCResourceHandle resourceHandle;
-    // 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;
-    // 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];
-    // Server sets to true for persistent response buffer, false for non-persistent response buffer
-    uint8_t persistentBufferFlag;
-} OCEntityHandlerResponse;
-
-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 {
-    OC_STACK_DELETE_TRANSACTION = 0,
-    OC_STACK_KEEP_TRANSACTION
-} OCStackApplicationResult;
-
-//-----------------------------------------------------------------------------
-// Callback function definitions
-//-----------------------------------------------------------------------------
-
-/**
- * Client applications implement this callback to consume responses received from Servers.
- */
-typedef OCStackApplicationResult (* OCClientResponseHandler)(void *context, OCDoHandle handle,
-    OCClientResponse * clientResponse);
-
-/**
- * Client applications using a context pointer implement this callback to delete the
- * context upon removal of the callback/context pointer from the internal callback-list
- */
-typedef void (* OCClientContextDeleter)(void *context);
-
-/*
- * This info is passed from application to OC Stack when initiating a request to Server
- */
-typedef struct {
-    void *context;
-    OCClientResponseHandler cb;
-    OCClientContextDeleter cd;
-} OCCallbackData;
-
-/**
- * Application server implementations must implement this callback to consume requests OTA.
- * Entity handler callback needs to fill the resPayload of the entityHandlerRequest.
- */
-typedef OCEntityHandlerResult (*OCEntityHandler)
-(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest);
-
-/**
- * Device Entity handler need to use this call back instead of OCEntityHandler
- */
-typedef OCEntityHandlerResult (*OCDeviceEntityHandler)
-(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, char* uri);
 
 //-----------------------------------------------------------------------------
 // Function prototypes
@@ -379,15 +38,13 @@ typedef OCEntityHandlerResult (*OCDeviceEntityHandler)
  * Initialize the OC Stack.  Must be called prior to starting the stack.
  *
  * @param ipAddr
- *     IP Address of host device
+ *     IP Address of host device. Deprecated parameter.
  * @param port
- *     Port of host device
+ *     Port of host device. Deprecated parameter.
  * @param mode
- *     Host device is client, server, or client-server
+ *     Host device is client, server, or client-server.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack init error
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
 
@@ -399,9 +56,7 @@ OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
  * OCNotifyAllObservers() to notify all client observers that the respective resource is being
  * deleted.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack not initialized
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCStop();
 
@@ -409,9 +64,7 @@ OCStackResult OCStop();
  * Called in main loop of OC client or server.  Allows low-level processing of
  * stack services.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCProcess();
 
@@ -419,37 +72,38 @@ OCStackResult OCProcess();
  * Discover or Perform requests on a specified resource (specified by that Resource's respective
  * URI).
  *
- * @param handle             - @ref OCDoHandle to refer to the request sent out on behalf of
- *                             calling this API.
- * @param method             - @ref OCMethod to perform on the resource
- * @param requiredUri        - URI of the resource to interact with
- * @param referenceUri       - URI of the reference resource
- * @param request            - JSON encoded request
- * @param qos                - quality of service. Note that if this API is called on a uri with
- *                             the well-known multicast IP address, the qos will be forced to
- *                             OC_LOW_QOS
- *                             since it is impractical to send other QOS levels on such addresses.
- * @param clientApplicationCB- asynchronous callback function that is invoked
- *                             by the stack when discovery or resource interaction is complete
- * @param options            - The address of an array containing the vendor specific
- *                             header options to be sent with the request
- * @param numOptions         - Number of header options to be included
+ * @param handle             @ref OCDoHandle to refer to the request sent out on behalf of
+ *                           calling this API. This handle can be used to cancel this operation
+ *                           via the OCCancel API.
+ *                           Note: This reference is handled internally, and
+ *                           should not be free'd by the consumer.  A NULL handle is permitted
+ *                           in the event where the caller has no use for the return value.
+ * @param method             @ref OCMethod to perform on the resource.
+ * @param requiredUri        URI of the resource to interact with.
+ * @param referenceUri       URI of the reference resource.
+ * @param request            JSON encoded request.
+ * @param conType            @ref OCConnectivityType type of connectivity indicating the
+ *                           interface. Example: ::OC_WIFI, ::OC_ETHERNET, ::OC_ALL.
+ * @param qos                Quality of service. Note that if this API is called on a uri with
+ *                           the well-known multicast IP address, the qos will be forced to
+ *                           ::OC_LOW_QOS
+ *                           since it is impractical to send other QOS levels on such addresses.
+ * @param 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.
+ * @param numOptions         Number of header options to be included.
  *
  * Note: Presence subscription amendments (ie. adding additional resource type filters by calling
  * this API again) require the use of the same base URI as the original request to successfully
  * amend the presence filters.
  *
- * @return
- *     OC_STACK_OK               - no errors
- *     OC_STACK_INVALID_CALLBACK - invalid callback function pointer
- *     OC_STACK_INVALID_METHOD   - invalid resource method
- *     OC_STACK_INVALID_URI      - invalid required or reference URI
- *     OC_STACK_INVALID_QUERY    - number of resource types specified for filtering presence
- *                                 notifications exceeds @ref MAX_PRESENCE_FILTERS.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char  *requiredUri, const char  *referenceUri,
-                const char *request, OCQualityOfService qos, OCCallbackData *cbData, OCHeaderOption * options,
-                uint8_t numOptions);
+OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
+            const char *referenceUri, const char *request, OCConnectivityType conType,
+            OCQualityOfService qos, OCCallbackData *cbData,
+            OCHeaderOption * options, uint8_t numOptions);
 
 /**
  * Cancel a request associated with a specific @ref OCDoResource invocation.
@@ -460,9 +114,7 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char  *req
  *                 explicit observe cancellation
  * @param numOptions- Number of header options to be included
  *
- * @return
- *     OC_STACK_OK               - No errors; Success
- *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
         uint8_t numOptions);
@@ -476,11 +128,13 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
  * 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.
  *
- * @param ttl - Time To Live in seconds
+ * @param ttl Time To Live in seconds.
  * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
  *
- * @return
- *     OC_STACK_OK      - No errors; Success
+ *       If ttl is greater than OC_MAX_PRESENCE_TTL_SECONDS, then the ttl will be set to
+ *       OC_MAX_PRESENCE_TTL_SECONDS.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCStartPresence(const uint32_t ttl);
 
@@ -492,8 +146,7 @@ OCStackResult OCStartPresence(const uint32_t ttl);
  * Server can call this function when it is terminating, going offline, or when going
  * away from network.
  *
- * @return
- *     OC_STACK_OK      - No errors; Success
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 
 OCStackResult OCStopPresence();
@@ -501,15 +154,13 @@ OCStackResult OCStopPresence();
 
 
 /**
- * Set default device entity handler
+ * Set default device entity handler.
  *
- * @param entityHandler - entity handler function that is called by ocstack to handle requests for
- *                        any undefined resources or default actions.
- *                        if NULL is passed it removes the device default entity handler.
+ * @param entityHandler Entity handler function that is called by ocstack 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
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler);
 
@@ -528,19 +179,33 @@ OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandle
 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
 
 /**
- * Create a resource.
+ * Set platform information.
+ *
+ * @param platformInfo - Structure passed by the server application containing
+ *                     the platform information.
  *
- * @param handle - pointer to handle to newly created resource.  Set by ocstack.  Used to refer to resource
- * @param resourceTypeName - name of resource type.  Example: "core.led"
- * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
- * @param uri - URI of the resource.  Example:  "/a/led"
- * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
- *                        NULL for default entity handler
- * @param resourceProperties - properties supported by resource.  Example: OC_DISCOVERABLE|OC_OBSERVABLE
  *
  * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_INVALID_PARAM   - invalid paramerter
+ *     OC_STACK_ERROR           - stack process error
+ */
+OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
+
+/**
+ * Create a resource.
+ *
+ * @param handle Pointer to handle to newly created resource.  Set by ocstack and
+ *               used to refer to resource.
+ * @param resourceTypeName Name of resource type.  Example: "core.led".
+ * @param resourceInterfaceName Name of resource interface.  Example: "core.rw".
+ * @param uri URI of the resource.  Example:  "/a/led".
+ * @param entityHandler Entity handler function that is called by ocstack to handle requests, etc.
+ *                      NULL for default entity handler.
+ * @param resourceProperties Properties supported by resource.
+ *                           Example: ::OC_DISCOVERABLE|::OC_OBSERVABLE.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCCreateResource(OCResourceHandle *handle,
                                const char *resourceTypeName,
@@ -550,22 +215,20 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
                                uint8_t resourceProperties);
 
 /**
- * Create a resource. with host ip address for remote resource
+ * Create a resource. with host ip address for remote resource.
  *
- * @param handle - pointer to handle to newly created resource.  Set by ocstack.
- *                 Used to refer to resource
- * @param resourceTypeName - name of resource type.  Example: "core.led"
- * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
- * @param host - HOST address of the remote resource.  Example:  "coap://xxx.xxx.xxx.xxx:xxxxx"
- * @param uri - URI of the resource.  Example:  "/a/led"
- * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
- *                        NULL for default entity handler
- * @param resourceProperties - properties supported by resource.
- *                             Example: OC_DISCOVERABLE|OC_OBSERVABLE
+ * @param handle Pointer to handle to newly created resource.  Set by ocstack.
+ *               Used to refer to resource.
+ * @param resourceTypeName Name of resource type.  Example: "core.led".
+ * @param resourceInterfaceName Name of resource interface.  Example: "core.rw".
+ * @param host HOST address of the remote resource.  Example:  "coap://xxx.xxx.xxx.xxx:xxxxx".
+ * @param uri URI of the resource.  Example:  "/a/led".
+ * @param entityHandler Entity handler function that is called by ocstack to handle requests, etc.
+ *                      NULL for default entity handler.
+ * @param resourceProperties Properties supported by resource.
+ *                           Example: ::OC_DISCOVERABLE|::OC_OBSERVABLE
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
                                const char *resourceTypeName,
@@ -578,50 +241,40 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
 /**
  * Add a resource to a collection resource.
  *
- * @param collectionHandle - handle to the collection resource
- * @param resourceHandle - handle to resource to be added to the collection resource
+ * @param collectionHandle Handle to the collection resource.
+ * @param resourceHandle Handle to resource to be added to the collection resource.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- *     OC_STACK_INVALID_PARAM - invalid collectionhandle
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
 
 /**
  * Remove a resource from a collection resource.
  *
- * @param collectionHandle - handle to the collection resource
- * @param resourceHandle - handle to resource to be removed from the collection resource
+ * @param collectionHandle Handle to the collection resource.
+ * @param resourceHandle Handle to resource to be removed from the collection resource.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- *     OC_STACK_INVALID_PARAM - invalid collectionhandle
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
 
 /**
  * Bind a resourcetype to a resource.
  *
- * @param handle - handle to the resource
- * @param resourceTypeName - name of resource type.  Example: "core.led"
+ * @param handle Handle to the resource.
+ * @param resourceTypeName Name of resource type.  Example: "core.led".
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
                                            const char *resourceTypeName);
 /**
  * Bind a resource interface to a resource.
  *
- * @param handle - handle to the resource
- * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
+ * @param handle Handle to the resource.
+ * @param resourceInterfaceName Name of resource interface.  Example: "core.rw".
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
                                                 const char *resourceInterfaceName);
@@ -629,34 +282,27 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
 /**
  * Bind an entity handler to the resource.
  *
- * @param handle - handle to the resource that the contained resource is to be bound
- * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @param handle Handle to the resource that the contained resource is to be bound.
+ * @param entityHandler Entity handler function that is called by ocstack to handle requests, etc.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler entityHandler);
 
 /**
  * Get the number of resources that have been created in the stack.
  *
- * @param numResources - pointer to count variable
+ * @param numResources Pointer to count variable.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
-
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCGetNumberOfResources(uint8_t *numResources);
 
 /**
  * Get a resource handle by index.
  *
- * @param index - index of resource, 0 to Count - 1
+ * @param index Index of resource, 0 to Count - 1.
  *
- * @return
- *    Resource handle - if found
- *    NULL - if not found
+ * @return Found resource handle or NULL if not found.
  */
 OCResourceHandle OCGetResourceHandle(uint8_t index);
 
@@ -667,21 +313,17 @@ OCResourceHandle OCGetResourceHandle(uint8_t index);
  * Note: OCDeleteResource() performs operations similar to OCNotifyAllObservers() to notify all
  * client observers that "this" resource is being deleted.
  *
- * @param handle - handle of resource to be deleted
+ * @param handle Handle of resource to be deleted.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCDeleteResource(OCResourceHandle handle);
 
 /**
  * Get the URI of the resource specified by handle.
  *
- * @param handle - handle of resource
- * @return
- *    URI string - if resource found
- *    NULL - resource not found
+ * @param handle Handle of resource.
+ * @return URI string if resource found or NULL if not found.
  */
 const char *OCGetResourceUri(OCResourceHandle handle);
 
@@ -690,94 +332,79 @@ const char *OCGetResourceUri(OCResourceHandle handle);
  * NOTE: that after a resource is created, the OC_ACTIVE property is set
  * for the resource by the stack.
  *
- * @param handle - handle of resource
- * @return
- *    property bitmap - if resource found
- *    NULL - resource not found
+ * @param handle Handle of resource.
+ * @return OCResourceProperty Bitmask or -1 if resource is not found.
  */
-uint8_t OCGetResourceProperties(OCResourceHandle handle);
+OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
 
 /**
  * Get the number of resource types of the resource.
  *
- * @param handle - handle of resource
- * @param numResourceTypes - pointer to count variable
+ * @param handle Handle of resource.
+ * @param numResourceTypes Pointer to count variable.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
 
 /**
  * Get name of resource type of the resource.
  *
- * @param handle - handle of resource
- * @param index - index of resource, 0 to Count - 1
+ * @param handle Handle of resource.
+ * @param index Index of resource, 0 to Count - 1.
  *
- * @return
- *    resource type name - if resource found
- *    NULL - resource not found
+ * @return Resource type name if resource found or NULL if resource not found.
  */
 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 handle Handle of resource.
+ * @param numResourceInterfaces Pointer to count variable.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
-
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, uint8_t *numResourceInterfaces);
+OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+        uint8_t *numResourceInterfaces);
 
 /**
  * Get name of resource interface of the resource.
  *
- * @param handle - handle of resource
- * @param index - index of resource, 0 to Count - 1
+ * @param handle Handle of resource.
+ * @param index Index of resource, 0 to Count - 1.
  *
- * @return
- *    resource interface name - if resource found
- *    NULL - resource not found
+ * @return Resource interface name if resource found or NULL if resource not found.
  */
 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
 
 /**
  * Get methods of resource interface of the resource.
  *
- * @param handle - handle of resource
- * @param index - index of resource, 0 to Count - 1
+ * @param handle Handle of resource.
+ * @param index Index of resource, 0 to Count - 1.
  *
- * @return
- *    allowed methods - if resource found
- *    NULL - resource not found
+ * @return Allowed methods if resource found or NULL if resource not found.
  */
 uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
 
 /**
  * Get resource handle from the collection resource by index.
  *
- * @param collectionHandle - handle of collection resource
- * @param index - index of contained resource, 0 to Count - 1
+ * @param collectionHandle Handle of collection resource.
+ * @param index Index of contained resource, 0 to Count - 1.
  *
- * @return
- *    handle to contained resource - if resource found
- *    NULL - resource not found
+ * @return Handle to contained resource if resource found or NULL if resource not found.
  */
-OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle, uint8_t index);
+OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
+        uint8_t index);
 
 /**
  * Get the entity handler for a resource.
  *
- * @param handle - handle of resource
+ * @param handle Handle of resource.
  *
- * @return
- *    entity handler - if resource found
- *    NULL - resource not found
+ * @return Entity handler if resource found or NULL resource not found.
  */
 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
 
@@ -786,12 +413,10 @@ OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
  * changed. If observation includes a query the client is notified only
  * if the query is valid after the resource representation has changed.
  *
- * @param handle - handle of resource
+ * @param handle Handle of resource.
+ * @param qos    Desired quality of service for the observation notifications.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_NO_RESOURCE - invalid resource handle
- *     OC_STACK_NO_OBSERVERS - no more observers intrested in resource
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
 
@@ -800,54 +425,67 @@ OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService q
  * Before this API is invoked by entity handler it has finished processing
  * queries for the associated observers.
  *
- * @param handle - handle of resource
- * @param obsIdList - list of observation ids that need to be notified
- * @param numberOfIds - number of observation ids included in obsIdList
- * @param notificationJSONPayload - JSON encoded payload to send in notification
- * @param qos - desired quality of service of the observation notifications
+ * @param handle Handle of resource.
+ * @param obsIdList List of observation ids that need to be notified.
+ * @param numberOfIds Number of observation ids included in obsIdList.
+ * @param notificationJSONPayload JSON encoded payload to send in notification.
+ * @param qos Desired quality of service of the observation notifications.
  * NOTE: The memory for obsIdList and notificationJSONPayload is managed by the
  * entity invoking the API. The maximum size of the notification is 1015 bytes
  * for non-Arduino platforms. For Arduino the maximum size is 247 bytes.
  *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_NO_RESOURCE - invalid resource handle
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult
 OCNotifyListOfObservers (OCResourceHandle handle,
                             OCObservationId  *obsIdList,
                             uint8_t          numberOfIds,
-                            unsigned char    *notificationJSONPayload,
+                            const char    *notificationJSONPayload,
                             OCQualityOfService qos);
 
 
 /**
  * Send a response to a request.
  * The response can be a normal, slow, or block (i.e. a response that
- * is too large to be sent in a single PDU and must span multiple transmissions)
+ * is too large to be sent in a single PDU and must span multiple transmissions).
  *
- * @param response - pointer to structure that contains response parameters
+ * @param response Pointer to structure that contains response parameters.
  *
- * @return
- *     OC_STACK_OK    - no errors
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
 
+
+//Utility methods
+
 /**
- * Cancel a response.  Applies to a block response
- *
- * @param responseHandle - response handle set by stack in OCServerResponse after
- *                         OCDoResponse is called
+ * This method is used to retrieved the IPv4 address from OCDev address
+ * data structure.
  *
- * @return
- *     OC_STACK_OK               - No errors; Success
- *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
+ * @param ipAddr OCDevAddr address.
+ * @param a first byte of IPv4 address.
+ * @param b second byte of IPv4 address.
+ * @param c third byte of IPv4 address.
+ * @param d fourth byte of IPv4 address.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCCancelResponse(OCResponseHandle responseHandle);
+int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
+            uint8_t *c, uint8_t *d );
 
+/**
+ * This method is used to retrieve the port number from OCDev address
+ * data structure.
+ *
+ * @param ipAddr OCDevAddr address.
+ * @param port Port number.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port);
 
 #ifdef __cplusplus
 }
 #endif // __cplusplus
 
 #endif /* OCSTACK_H_ */
+
+
index 9e14bd3..0213def 100644 (file)
 // This file contains all the variables which can be configured/modified as
 // per platform or specific product usage scenarios.
 
+/** This would need to be updated in future as we move to support IPv6 and other
+ *  technologies.
+ */
+#define DEV_ADDR_SIZE_MAX (16)
 
 /**
  * Maximum length of the response supported by Server for any REST request.
+ * The actual repsonse length is 256 for Arduino and 1024 for other platforms.
+ * Note that the stack will add a prefix and suffix to the payload.
+ * Prefix : {"oc":[
+ * Suffix : ]}
+ * They have a combined size of 9 bytes.
  */
 #ifdef WITH_ARDUINO
-#define MAX_RESPONSE_LENGTH (256)
+#define MAX_RESPONSE_LENGTH (247)
 #else
-#define MAX_RESPONSE_LENGTH (1024)
+#define MAX_RESPONSE_LENGTH (1015)
 #endif
 
 /**
  */
 #define MAX_HEADER_OPTION_DATA_LENGTH (16)
 
+/*
+ * Sets the time to live (TTL) for response callbacks.
+ * The callbacks will be up for deletion after such time but are not guaranteed
+ * to be deleted immediately and you may get responses even after timeout.
+ * This timeout will NOT apply to OBSERVE requests. OBSERVE needs an explicit cancel using OCCancel().
+ * NOTE: Changing the setting to a very long duration may lead to unsupported and untested
+ * operation. Setting this to as small a value as reasonable will reclaim memory faster.
+ */
+#define MAX_CB_TIMEOUT_SECONDS   (2 * 60 * 60)  // 2 hours = 7200 seconds.
+
 #endif //OCSTACK_CONFIG_H_
diff --git a/resource/csdk/stack/include/octypes.h b/resource/csdk/stack/include/octypes.h
new file mode 100644 (file)
index 0000000..c597771
--- /dev/null
@@ -0,0 +1,501 @@
+//******************************************************************
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef OCTYPES_H_
+#define OCTYPES_H_
+
+#include "ocstackconfig.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+#define WITH_PRESENCE
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+
+//TODO: May want to refactor this in upcoming sprints.
+//Don't want to expose to application layer that lower level stack is using CoAP.
+
+/// Authority + URI string to prefix well known queries
+#define OC_WELL_KNOWN_QUERY                  "224.0.1.187:5683/oc/core"
+#define OC_MULTICAST_DISCOVERY_URI           "/oc/core"
+#define OC_EXPLICIT_DEVICE_DISCOVERY_URI     "224.0.1.187:5683/oc/core/d?rt=core.led"
+/// Multicast address and port string to prefix multicast queries
+#define OC_MULTICAST_PREFIX                  "224.0.1.187:5683"
+/// IP Multicast address to use for multicast requests
+#define OC_MULTICAST_IP                      "224.0.1.187"
+/// IP Multicast port to use for multicast requests
+#define OC_MULTICAST_PORT                    5683
+
+#ifdef WITH_PRESENCE
+#define OC_DEFAULT_PRESENCE_TTL_SECONDS (60)
+/// OC_MAX_PRESENCE_TTL_SECONDS sets the maximum time to live (TTL) for presence.
+/// NOTE: Changing the setting to a longer duration may lead to unsupported and untested
+/// operation.
+#define OC_MAX_PRESENCE_TTL_SECONDS     (60 * 60 * 24) // 60 sec/min * 60 min/hr * 24 hr/day
+#define OC_PRESENCE_URI                      "/oic/ad"
+#endif
+/**
+ * Attributes used to form a proper OIC conforming JSON message.
+ */
+#define OC_RSRVD_OC                     "oic"
+#define OC_RSRVD_PAYLOAD                "payload"
+#define OC_RSRVD_HREF                   "href"
+#define OC_RSRVD_PROPERTY               "prop"
+#define OC_RSRVD_REPRESENTATION         "rep"
+#define OC_RSRVD_CONTENT_TYPE           "ct"
+#define OC_RSRVD_RESOURCE_TYPE          "rt"
+#define OC_RSRVD_RESOURCE_TYPE_PRESENCE "oic.wk.ad"
+#define OC_RSRVD_INTERFACE              "if"
+#define OC_RSRVD_DEVICE_ID              "di"
+#define OC_RSRVD_DEVICE_NAME            "dn"
+#define OC_RSRVD_INTERFACE_DEFAULT      "oic.if.baseline"
+#define OC_RSRVD_INTERFACE_LL           "oic.if.ll"
+#define OC_RSRVD_INTERFACE_BATCH        "oic.if.b"
+#define OC_RSRVD_INTERFACE_GROUP        "oc.mi.grp"
+#define OC_RSRVD_FW_VERSION             "mnfv"
+#define OC_RSRVD_HOST_NAME              "hn"
+#define OC_RSRVD_VERSION                "icv"
+#define OC_RSRVD_OBSERVABLE             "obs"
+#define OC_RSRVD_SECURE                 "sec"
+#define OC_RSRVD_HOSTING_PORT           "port"
+#define OC_RSRVD_SERVER_INSTANCE_ID     "sid"
+
+  //**** Platform ****
+#define OC_RSRVD_PLATFORM_ID            "pi"
+#define OC_RSRVD_MFG_NAME               "mnmn"
+#define OC_RSRVD_MFG_URL                "mnml"
+#define OC_RSRVD_MODEL_NUM              "mnmo"
+#define OC_RSRVD_MFG_DATE               "mndt"
+#define OC_RSRVD_PLATFORM_VERSION       "mnpv"
+#define OC_RSRVD_OS_VERSION             "mnos"
+#define OC_RSRVD_HARDWARE_VERSION       "mnhw"
+#define OC_RSRVD_FIRMWARE_VERSION       "mnfv"
+#define OC_RSRVD_SUPPORT_URL            "mnsl"
+#define OC_RSRVD_SYSTEM_TIME             "st"
+//*******************
+
+//-----------------------------------------------------------------------------
+// Typedefs
+//-----------------------------------------------------------------------------
+
+/**
+ * Data structure to encapsulate IPv4/IPv6/Contiki/lwIP device addresses.
+ */
+typedef struct OCDevAddr
+{
+    uint32_t     size;                    ///< length of the address stored in addr field.
+    uint8_t      addr[DEV_ADDR_SIZE_MAX]; ///< device address.
+} OCDevAddr;
+
+/**
+ * OC Virtual resources supported by every OC device.
+ */
+typedef enum
+{
+    OC_WELL_KNOWN_URI= 0,       ///< "/oc/core"
+    OC_DEVICE_URI,              ///< "/oc/core/d"
+    OC_PLATFORM_URI,            ///< "/oic/p"
+    OC_RESOURCE_TYPES_URI,      ///< "/oc/core/d/type"
+    #ifdef WITH_PRESENCE
+    OC_PRESENCE,                ///< "/oic/ad"
+    #endif
+    OC_MAX_VIRTUAL_RESOURCES    ///<s Max items in the list
+} OCVirtualResources;
+
+/**
+ * Standard RESTful HTTP Methods.
+ */
+typedef enum
+{
+    OC_REST_NOMETHOD    = 0,
+    OC_REST_GET         = (1 << 0),     ///< Read
+    OC_REST_PUT         = (1 << 1),     ///< Write
+    OC_REST_POST        = (1 << 2),     ///< Update
+    OC_REST_DELETE      = (1 << 3),     ///< Delete
+    /// Register observe request for most up date notifications ONLY.
+    OC_REST_OBSERVE     = (1 << 4),
+    /// Register observe request for all notifications, including stale notifications.
+    OC_REST_OBSERVE_ALL = (1 << 5),
+    /// Deregister observation, intended for internal use
+    OC_REST_CANCEL_OBSERVE = (1 << 6),
+    #ifdef WITH_PRESENCE
+    /// Subscribe for all presence notifications of a particular resource.
+    OC_REST_PRESENCE    = (1 << 7)
+    #endif
+} OCMethod;
+
+/**
+ * Host Mode of Operation.
+ */
+typedef enum
+{
+    OC_CLIENT = 0,
+    OC_SERVER,
+    OC_CLIENT_SERVER
+} OCMode;
+
+/**
+ * Quality of Service.
+ *
+ * OCQualityOfService attempts to abstract the guarantees provided by the underlying transport
+ * protocol.  The precise definitions of each quality of service level depend on the
+ * implementation.  In descriptions below are for the current implementation and may changed
+ * over time.
+ */
+typedef enum
+{
+    /// Packet delivery is best effort
+    OC_LOW_QOS = 0,
+    /// Packet delivery is best effort
+    OC_MEDIUM_QOS,
+    /// Acknowledgements are used to confirm delivery
+    OC_HIGH_QOS,
+    /// No Quality is defined, let the stack decide
+    OC_NA_QOS
+} OCQualityOfService;
+
+/**
+ * Resource Properties.
+ *
+ * ::OC_ACTIVE       When this bit is set, the resource is initialized, otherwise the resource
+ *                   is 'inactive'. 'inactive' signifies that the resource has been marked for
+ *                   deletion or is already deleted.
+ * ::OC_DISCOVERABLE When this bit is set, the resource is allowed to be discovered by clients.
+ * ::OC_OBSERVABLE   When this bit is set, the resource is allowed to be observed by clients.
+ * ::OC_SLOW         When this bit is set, the resource has been marked as 'slow'. 'slow' signifies
+ *                   that responses from this resource can expect delays in processing its
+ *                   requests from clients.
+ * ::OC_SECURE       When this bit is set, the resource is a secure resource.
+ */
+typedef enum
+{
+    OC_ACTIVE       = (1 << 0),
+    OC_DISCOVERABLE = (1 << 1),
+    OC_OBSERVABLE   = (1 << 2),
+    OC_SLOW         = (1 << 3),
+    OC_SECURE       = (1 << 4)
+} OCResourceProperty;
+
+/**
+ * Transport Protocol IDs.
+ */
+typedef enum
+{
+    OC_INVALID_ID   = (1 << 0),
+    OC_COAP_ID      = (1 << 1)
+} OCTransportProtocolID;
+
+/**
+ * Adaptor types.
+ */
+typedef enum
+{
+    OC_IPV4 = 0,
+    OC_IPV6,
+    OC_EDR,
+    OC_LE,
+    OC_ALL // Multicast message: send over all the interfaces.
+} OCConnectivityType;
+
+/**
+ * Declares Stack Results & Errors.
+ */
+typedef enum
+{
+    /* Success status code - START HERE */
+    OC_STACK_OK = 0,
+    OC_STACK_RESOURCE_CREATED,
+    OC_STACK_RESOURCE_DELETED,
+    OC_STACK_CONTINUE,
+    /* Success status code - END HERE */
+    /* Error status code - START HERE */
+    OC_STACK_INVALID_URI = 20,
+    OC_STACK_INVALID_QUERY,
+    OC_STACK_INVALID_IP,
+    OC_STACK_INVALID_PORT,
+    OC_STACK_INVALID_CALLBACK,
+    OC_STACK_INVALID_METHOD,
+    OC_STACK_INVALID_PARAM,
+    OC_STACK_INVALID_OBSERVE_PARAM,
+    OC_STACK_NO_MEMORY,
+    OC_STACK_COMM_ERROR,
+    OC_STACK_TIMEOUT,
+    OC_STACK_ADAPTER_NOT_ENABLED,
+    OC_STACK_NOTIMPL,
+    OC_STACK_NO_RESOURCE,               /* resource not found */
+    OC_STACK_RESOURCE_ERROR,            /* ex: not supported method or interface */
+    OC_STACK_SLOW_RESOURCE,
+    OC_STACK_DUPLICATE_REQUEST,
+    OC_STACK_NO_OBSERVERS,              /* resource has no registered observers */
+    OC_STACK_OBSERVER_NOT_FOUND,
+    OC_STACK_VIRTUAL_DO_NOT_HANDLE,
+    OC_STACK_INVALID_OPTION,
+    OC_STACK_MALFORMED_RESPONSE,        /* the remote reply contained malformed data */
+    OC_STACK_PERSISTENT_BUFFER_REQUIRED,
+    OC_STACK_INVALID_REQUEST_HANDLE,
+    OC_STACK_INVALID_DEVICE_INFO,
+    OC_STACK_INVALID_JSON,
+    /* NOTE: Insert all new error codes here!*/
+    #ifdef WITH_PRESENCE
+    OC_STACK_PRESENCE_STOPPED = 128,
+    OC_STACK_PRESENCE_TIMEOUT,
+    OC_STACK_PRESENCE_DO_NOT_HANDLE,
+    #endif
+    OC_STACK_ERROR = 255
+    /* Error status code - END HERE */
+} OCStackResult;
+
+/**
+ * Handle to an @ref OCDoResource invocation.
+ */
+typedef void * OCDoHandle;
+
+/**
+ * Handle to an OCResource object owned by the OCStack.
+ */
+typedef void * OCResourceHandle;
+
+typedef void * OCRequestHandle;
+
+/**
+ * Unique identifier for each observation request. Used when observations are
+ * registered or deregistering. Used by entity handler to signal specific
+ * observers to be notified of resource changes.
+ * There can be maximum of 256 observations per server.
+ */
+typedef uint8_t OCObservationId;
+
+/**
+ * Action associated with observation.
+ */
+typedef enum
+{
+    OC_OBSERVE_REGISTER = 0,
+    OC_OBSERVE_DEREGISTER = 1,
+    OC_OBSERVE_NO_OPTION = 2
+} OCObserveAction;
+
+typedef struct
+{
+    // Action associated with observation request
+    OCObserveAction action;
+    // Identifier for observation being registered/deregistered
+    OCObservationId obsId;
+} OCObservationInfo;
+
+/**
+ * Possible returned values from entity handler.
+ */
+typedef enum
+{
+    OC_EH_OK = 0,
+    OC_EH_ERROR,
+    OC_EH_RESOURCE_CREATED,
+    OC_EH_RESOURCE_DELETED,
+    OC_EH_SLOW,
+    OC_EH_FORBIDDEN,
+    OC_EH_RESOURCE_NOT_FOUND
+} OCEntityHandlerResult;
+
+/**
+ * This structure will be used to define the vendor specific header options to be included
+ * in communication packets.
+ */
+typedef struct OCHeaderOption
+{
+    // The protocol ID this option applies to
+    OCTransportProtocolID protocolID;
+    // The header option ID which will be added to communication packets
+    uint16_t optionID;
+    // its length   191
+    uint16_t optionLength;
+    // pointer to its data
+    uint8_t optionData[MAX_HEADER_OPTION_DATA_LENGTH];
+} 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.
+ */
+typedef struct
+{
+    // Associated resource
+    OCResourceHandle resource;
+    OCRequestHandle requestHandle;
+    // the REST method retrieved from received request PDU
+    OCMethod method;
+    // resource query send by client
+    char * query;
+    // Information associated with observation - valid only when OCEntityHandler
+    // flag includes OC_OBSERVE_FLAG
+    OCObservationInfo obsInfo;
+    // An array of the received vendor specific header options
+    uint8_t numRcvdVendorSpecificHeaderOptions;
+    OCHeaderOption * rcvdVendorSpecificHeaderOptions;
+    // reqJSON is retrieved from the payload of the received request PDU
+    char * reqJSONPayload;
+} OCEntityHandlerRequest;
+
+/**
+ * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
+ */
+typedef struct
+{
+    /// Address of remote server
+    OCDevAddr * addr;
+    /// Indicates adaptor type on which the response was received
+    OCConnectivityType connType;
+    /// the is the result of our stack, OCStackResult should contain coap/other error codes;
+    OCStackResult result;
+    /// 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
+    const char * resJSONPayload;
+    /// An array of the received vendor specific header options
+    uint8_t numRcvdVendorSpecificHeaderOptions;
+    OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
+} OCClientResponse;
+
+/**
+ * This structure describes the platform properties. All non-Null properties will be included
+ * in a platform discovery request.
+ */
+typedef struct
+{
+    char *platformID;
+    char *manufacturerName;
+    char *manufacturerUrl;
+    char *modelNumber;
+    char *dateOfManufacture;
+    char *platformVersion;
+    char *operatingSystemVersion;
+    char *hardwareVersion;
+    char *firmwareVersion;
+    char *supportUrl;
+    char *systemTime;
+
+} OCPlatformInfo;
+
+/**
+ * TODO : Modify these. This is just so sample apps compile.
+ */
+typedef struct
+{
+    char *deviceName;
+    char *hostName;
+    char *deviceUUID;
+    char *contentType;
+    char *version;
+    char *manufacturerName;
+    char *manufacturerUrl;
+    char *modelNumber;
+    char *dateOfManufacture;
+    char *platformVersion;
+    char *firmwareVersion;
+    char *supportUrl;
+} OCDeviceInfo;
+
+typedef struct
+{
+    // Request handle is passed to server via the entity handler for each incoming request.
+    // Stack assigns when request is received, server sets to indicate what request response is for
+    OCRequestHandle requestHandle;
+    // Resource handle
+    OCResourceHandle resourceHandle;
+    // Allow the entity handler to pass a result with the response
+    OCEntityHandlerResult  ehResult;
+    // this is the pointer to server payload data to be transferred
+    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
+    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
+{
+    OC_REQUEST_FLAG = (1 << 1),
+    OC_OBSERVE_FLAG = (1 << 2)
+} OCEntityHandlerFlag; //entity_handler_flag_t ;
+
+/**
+ * Possible returned values from client application.
+ */
+typedef enum
+{
+    OC_STACK_DELETE_TRANSACTION = 0,//!< OC_STACK_DELETE_TRANSACTION
+    OC_STACK_KEEP_TRANSACTION       //!< OC_STACK_KEEP_TRANSACTION
+} OCStackApplicationResult;
+
+//-----------------------------------------------------------------------------
+// Callback function definitions
+//-----------------------------------------------------------------------------
+
+/**
+ * Client applications implement this callback to consume responses received from Servers.
+ */
+typedef OCStackApplicationResult (* OCClientResponseHandler)(void *context, OCDoHandle handle,
+    OCClientResponse * clientResponse);
+
+/**
+ * Client applications using a context pointer implement this callback to delete the
+ * context upon removal of the callback/context pointer from the internal callback-list.
+ */
+typedef void (* OCClientContextDeleter)(void *context);
+
+/**
+ * This info is passed from application to OC Stack when initiating a request to Server.
+ */
+typedef struct
+{
+    void *context;
+    /// The pointer to a function the stack will call to handle the requests
+    OCClientResponseHandler cb;
+    /// A pointer to a function to delete the context when this callback is removed
+    OCClientContextDeleter cd;
+} OCCallbackData;
+
+/**
+ * Application server implementations must implement this callback to consume requests OTA.
+ * Entity handler callback needs to fill the resPayload of the entityHandlerRequest.
+ */
+typedef OCEntityHandlerResult (*OCEntityHandler)
+(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest);
+
+/**
+ * Device Entity handler need to use this call back instead of OCEntityHandler.
+ */
+typedef OCEntityHandlerResult (*OCDeviceEntityHandler)
+(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, char* uri);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif /* OCTYPES_H_ */
diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/makefile b/resource/csdk/stack/samples/arduino/SimpleClientServer/makefile
deleted file mode 100644 (file)
index 09a61a4..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-BUILD := release
-ARDUINO_PORT := /dev/ttyACM0
-APP_INSTALL := ocserver
-PLATFORM := arduinomega
-ARDUINOWIFI := 0
-
-ocserver:
-       $(MAKE) -c ./$@ "BUILD=$(BUILD)" "install" "PLATFORM=$(PLATFORM)" "ARDUINO_PORT=$(ARDUINO_PORT)" "BUILD=$(BUILD)" "ARDUINOWIFI=$(ARDUINOWIFI)"
-
-occlient:
-       $(MAKE) -c ./$@ "BUILD=$(BUILD)"
-
-install:
-       $(MAKE) -C ./$(APP_INSTALL) "install" "PLATFORM=$(PLATFORM)" "ARDUINO_PORT=$(ARDUINO_PORT)" "BUILD=$(BUILD)" "ARDUINOWIFI=$(ARDUINOWIFI)"
-
-clean:
-       $(MAKE) -C ./occlient "clean"
-       $(MAKE) -C ./ocserver "clean"
index f5a4222..6f03453 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()
@@ -5,14 +25,15 @@ arduino_simplecs_env = env.Clone()
 # Build flags
 ######################################################################
 arduino_simplecs_env.PrependUnique(CPPPATH = [
-               '../../../../../ocsocket/include',
                '../../../../../logger/include',
                '../../../../../stack/include',
                '../../../../../../oc_logger/include'
                ])
 
 arduino_simplecs_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-arduino_simplecs_env.PrependUnique(LIBS = ['octbstack', 'coap'])
+arduino_simplecs_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+arduino_simplecs_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction','coap'])
 
 arduino_simplecs = arduino_simplecs_env.Program('SimpleClientServer', 'ocserver.cpp')
 env.CreateBin('SimpleClientServer')
@@ -20,4 +41,11 @@ env.CreateBin('SimpleClientServer')
 i_arduino_simplecs = arduino_simplecs_env.Install(env.get('BUILD_DIR'), arduino_simplecs)
 
 Alias('arduino_simplecs', i_arduino_simplecs)
-env.AppendTarget('arduino_simplecs')
\ No newline at end of file
+env.AppendTarget('arduino_simplecs')
+
+if(arduino_simplecs_env['UPLOAD'] == True):
+       from sys import platform as _platform
+       if _platform == "linux" or _platform == "linux2":
+               arduino_simplecs_env.Upload(env.get('BUILD_DIR') + '/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SimpleClientServer.hex')
+       else:
+               print 'Please use appropriate install method for your developing machine. Linux is the only supported platform right now.'
diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile
deleted file mode 100644 (file)
index 3b01109..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-BUILD := release
-PLATFORM := arduinomega
-ARDUINO_PORT := ttyACM0
-
-# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
-ARDUINOWIFI := 0
-
-APP_NAME := ocserver
-
-ROOT_DIR = ../../../../..
-LOGGER_DIR = $(ROOT_DIR)/logger
-OC_LOG_DIR = $(ROOT_DIR)/../oc_logger
-TBSTACK_DIR = $(ROOT_DIR)/stack
-TBSOCKET_DIR = $(ROOT_DIR)/ocsocket
-
-include $(ROOT_DIR)/local.properties
-include $(ROOT_DIR)/$(PLATFORM).properties
-
-VPATH := $(SDIR_ARD_PLATFORM)
-
-#include directories
-OCSOCK_DIR = $(ROOT_DIR)/ocsocket
-LOGGER_DIR = $(ROOT_DIR)/logger
-STACK_DIR  = $(ROOT_DIR)/stack
-INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include
-
-CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
-CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
-
-CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
-
-ifeq ($(ARDUINOWIFI),1)
-       CFLAGS += -DARDUINOWIFI
-       ARDUINO_SHIELD_TYPE := "/wifi_shield"
-       TRANSPORT_OBJS = $(WIFI_COBJ)
-else
-       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
-       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
-endif
-
-OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
-
-OBJ_DIR := $(OUT_DIR)/bin
-
-all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-
-core.a: $(PLATFORM_OBJS)
-       @cd $(OBJ_DIR) && $(AR) -x ../../../../$(ROOT_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a
-       $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o
-       @cd $(OBJ_DIR) && $(RANLIB) $@
-
-prep_dirs:
-       -mkdir $(PLATFORM)
-       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
-       -mkdir $(OUT_DIR)
-       -mkdir $(OBJ_DIR)
-
-%.o: %.c
-       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-
-%.o: %.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-
-$(APP_NAME).elf: $(APP_NAME).o core.a
-ifeq ($(PLATFORM),arduinomega)
-       $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-$(APP_NAME).hex: $(APP_NAME).elf
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep
-       $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-install: all
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i
-else ifeq ($(PLATFORM),arduinodue)
-       stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb
-       $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-.PHONY: clean
-
-clean: legacy_clean
-       rm -rf arduinomega
-       rm -rf arduinodue
-
-legacy_clean:
-       @rm -rf bin
-       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
index e5cd93f..fb1c61f 100644 (file)
@@ -57,17 +57,16 @@ typedef struct LIGHTRESOURCE{
 
 static LightResource Light;
 
-static char responsePayloadGet[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"on\",\"power\":10}}";
-static char responsePayloadPut[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"off\",\"power\":0}}";
-
-/// This is the port which Arduino Server will use for all unicast communication with it's peers
-static uint16_t OC_WELL_KNOWN_PORT = 5683;
+static char responsePayloadGet[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":true,\"power\":10}}";
+static char responsePayloadPut[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":false,\"power\":0}}";
 
 #ifdef ARDUINOWIFI
 // Arduino WiFi Shield
 // Note : Arduino WiFi Shield currently does NOT support multicast and therefore
 // this server will NOT be listening on 224.0.1.187 multicast address.
 
+static const char ARDUINO_WIFI_SHIELD_UDP_FW_VER[] = "1.1.0";
+
 /// WiFi Shield firmware with Intel patches
 static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
 
@@ -89,7 +88,7 @@ int ConnectToNetwork()
     // Verify that WiFi Shield is running the firmware with all UDP fixes
     fwVersion = WiFi.firmwareVersion();
     OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
-    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
+    if ( strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER)) !=0 )
     {
         OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
         return -1;
@@ -192,10 +191,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;
@@ -231,7 +231,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)
@@ -254,7 +255,6 @@ void setup()
     // Note : This will initialize Serial port on Arduino at 115200 bauds
     OC_LOG_INIT();
     OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
-    uint16_t port = OC_WELL_KNOWN_PORT;
 
     // Connect to Ethernet or WiFi network
     if (ConnectToNetwork() != 0)
@@ -264,7 +264,7 @@ void setup()
     }
 
     // Initialize the OC Stack in Server mode
-    if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, PCF("OCStack init error"));
         return;
@@ -278,7 +278,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
@@ -298,7 +298,7 @@ void createLightResource()
     Light.state = false;
     OCStackResult res = OCCreateResource(&Light.handle,
             "core.light",
-            "oc.mi.def",
+            OC_RSRVD_INTERFACE_DEFAULT,
             "/a/light",
             OCEntityHandlerCb,
             OC_DISCOVERABLE|OC_OBSERVABLE);
@@ -343,3 +343,4 @@ const char *getResult(OCStackResult result) {
         return "UNKNOWN";
     }
 }
+
diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript b/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript
new file mode 100644 (file)
index 0000000..b3250b7
--- /dev/null
@@ -0,0 +1,72 @@
+#******************************************************************
+#
+# 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')
+target_os = env.get('TARGET_OS')
+samples_env = env.Clone()
+######################################################################
+# Build flags
+######################################################################
+samples_env.PrependUnique(CPPPATH = [
+               '../../../../logger/include',
+               '../../../../stack/include',
+               '../../../../ocmalloc/include',
+               '../../../../../../extlibs/cjson',
+               '../../../../../oc_logger/include',
+               '../../../../../connectivity/lib/libcoap-4.1.1'
+               ])
+
+samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+samples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+samples_env.AppendUnique(LIBS = ['-lpthread' ])
+samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+if target_os in ['darwin', 'ios']:
+       samples_env.PrependUnique(LIBS = ['m','octbstack', 'connectivity_abstraction','coap' ])
+elif target_os not in ['arduino']:
+       samples_env.PrependUnique(LIBS = ['m', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
+       samples_env.AppendUnique(LIBS = ['rt'])
+
+if env.get('SECURED') == '1':
+    samples_env.AppendUnique(LIBS = ['tinydtls'])
+
+samples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+ocserver         = samples_env.Program('ocserver', ['ocserver.cpp', 'common.cpp'])
+occlient         = samples_env.Program('occlient', ['occlient.cpp', 'common.cpp'])
+ocserverslow     = samples_env.Program('ocserverslow', ['ocserverslow.cpp', 'common.cpp'])
+occlientslow     = samples_env.Program('occlientslow', ['occlientslow.cpp', 'common.cpp'])
+ocservercoll     = samples_env.Program('ocservercoll', ['ocservercoll.cpp', 'common.cpp'])
+occlientcoll     = samples_env.Program('occlientcoll', ['occlientcoll.cpp', 'common.cpp'])
+ocserverbasicops = samples_env.Program('ocserverbasicops', ['ocserverbasicops.cpp', 'common.cpp'])
+occlientbasicops = samples_env.Program('occlientbasicops', ['occlientbasicops.cpp', 'common.cpp'])
+
+Alias("samples", [ocserver, occlient,
+                               ocservercoll, occlientcoll,
+                               ocserverbasicops, occlientbasicops,
+                               ocserverslow, occlientslow
+                ])
+
+env.AppendTarget('samples')
+
+
index 3f2b586..0ea86ae 100644 (file)
 #include <stdlib.h>
 #include <ocstack.h>
 
-const char *getResult(OCStackResult result) {
-    switch (result) {
-    case OC_STACK_OK:
-        return "OC_STACK_OK";
-    case OC_STACK_RESOURCE_CREATED:
-        return "OC_STACK_RESOURCE_CREATED";
-    case OC_STACK_RESOURCE_DELETED:
-        return "OC_STACK_RESOURCE_DELETED";
-    case OC_STACK_INVALID_URI:
-        return "OC_STACK_INVALID_URI";
-    case OC_STACK_INVALID_QUERY:
-        return "OC_STACK_INVALID_QUERY";
-    case OC_STACK_INVALID_IP:
-        return "OC_STACK_INVALID_IP";
-    case OC_STACK_INVALID_PORT:
-        return "OC_STACK_INVALID_PORT";
-    case OC_STACK_INVALID_CALLBACK:
-        return "OC_STACK_INVALID_CALLBACK";
-    case OC_STACK_INVALID_METHOD:
-        return "OC_STACK_INVALID_METHOD";
-    case OC_STACK_NO_MEMORY:
-        return "OC_STACK_NO_MEMORY";
-    case OC_STACK_COMM_ERROR:
-        return "OC_STACK_COMM_ERROR";
-    case OC_STACK_INVALID_PARAM:
-        return "OC_STACK_INVALID_PARAM";
-    case OC_STACK_NOTIMPL:
-        return "OC_STACK_NOTIMPL";
-    case OC_STACK_NO_RESOURCE:
-        return "OC_STACK_NO_RESOURCE";
-    case OC_STACK_RESOURCE_ERROR:
-        return "OC_STACK_RESOURCE_ERROR";
-    case OC_STACK_SLOW_RESOURCE:
-        return "OC_STACK_SLOW_RESOURCE";
-    case OC_STACK_NO_OBSERVERS:
-        return "OC_STACK_NO_OBSERVERS";
-    #ifdef WITH_PRESENCE
-    case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
-        return "OC_STACK_VIRTUAL_DO_NOT_HANDLE";
-    case OC_STACK_PRESENCE_STOPPED:
-        return "OC_STACK_PRESENCE_STOPPED";
-    case OC_STACK_PRESENCE_TIMEOUT:
-        return "OC_STACK_PRESENCE_TIMEOUT";
-    #endif
-    case OC_STACK_ERROR:
-        return "OC_STACK_ERROR";
-    default:
-        return "UNKNOWN";
+const char *getResult(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_RESOURCE_CREATED:
+            return "OC_STACK_RESOURCE_CREATED";
+        case OC_STACK_RESOURCE_DELETED:
+            return "OC_STACK_RESOURCE_DELETED";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+#ifdef WITH_PRESENCE
+        case OC_STACK_PRESENCE_STOPPED:
+            return "OC_STACK_PRESENCE_STOPPED";
+        case OC_STACK_PRESENCE_TIMEOUT:
+            return "OC_STACK_PRESENCE_TIMEOUT";
+#endif
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
     }
 }
+
+void StripNewLineChar(char* str)
+{
+    int i = 0;
+    if (str)
+    {
+        while( str[i])
+        {
+            if (str[i] == '\n')
+            {
+                str[i] = '\0';
+            }
+            i++;
+        }
+    }
+}
+
diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/makefile b/resource/csdk/stack/samples/linux/SimpleClientServer/makefile
deleted file mode 100644 (file)
index 07164ad..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD   := release
-PLATFORM := linux
-CC      := g++
-OUT_DIR          := $(BUILD)
-OBJ_DIR          := $(OUT_DIR)/obj
-
-ifeq ($(ROOT_DIR), )
-ROOT_DIR       = ../../../..
-endif
-
-OUT_DIR        = .
-
-OCLOGGER_DIR   = $(ROOT_DIR)/logger
-OC_LOG_DIR = $(ROOT_DIR)/../oc_logger
-OCRANDOM_DIR   = $(ROOT_DIR)/ocrandom
-OCSOCKET_DIR   = $(ROOT_DIR)/ocsocket
-LCOAP_DIR      = $(ROOT_DIR)/libcoap-4.1.1
-OCCOAP_DIR     = $(ROOT_DIR)/occoap
-OCMALLOC_DIR   = $(ROOT_DIR)/ocmalloc
-OCTBSTACK_DIR  = $(ROOT_DIR)/stack
-EXTLIBS_DIR    = $(ROOT_DIR)/../../extlibs
-CJSON_DIR      = $(EXTLIBS_DIR)/cjson
-
-CJSON_SRC      = $(CJSON_DIR)
-
-OCLOGGER_INC   = $(OCLOGGER_DIR)/include
-OC_LOG_INC     = $(OC_LOG_DIR)/include
-OCRANDOM_INC   = $(OCRANDOM_DIR)/include
-OCSOCKET_INC   = $(OCSOCKET_DIR)/include
-LCOAP_INC      = $(LCOAP_DIR)
-OCCOAP_INC     = $(OCCOAP_DIR)/include
-OCMALLOC_INC   = $(OCMALLOC_DIR)/include
-OCTBSTACK_INC  = $(OCTBSTACK_DIR)/include
-CJSON_INC      = $(CJSON_DIR)
-
-INC_DIRS       := -I$(OCLOGGER_INC)
-INC_DIRS       += -I$(OC_LOG_INC)
-INC_DIRS       += -I$(OCRANDOM_INC)
-INC_DIRS       += -I$(OCSOCKET_INC)
-INC_DIRS       += -I$(LCOAP_INC)
-INC_DIRS       += -I$(OCCOAP_INC)
-INC_DIRS       += -I$(OCMALLOC_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)
-INC_DIRS       += -I$(CJSON_INC)
-
-CC_FLAGS.debug   := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \
-                        -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG
-CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \
-                        -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG
-
-LDLIBS         += -loctbstack -lpthread
-CPPFLAGS       += $(CC_FLAGS.$(BUILD)) $(LDLIBS)
-
-CJSON_SOURCES          := $(CJSON_SRC)/cJSON.c
-
-SOURCES        := $(CJSON_SOURCES)
-SOURCES        += occlient.cpp ocserver.cpp occlientcoll.cpp ocservercoll.cpp common.cpp ocserverbasicops.cpp occlientbasicops.cpp ocserverslow.cpp occlientslow.cpp
-
-OBJECTS:= $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(SOURCES))
-
-PROGRAMS       += ocserver
-PROGRAMS       += occlient
-PROGRAMS       += ocserverbasicops
-PROGRAMS       += ocserverslow
-PROGRAMS       += ocservercoll
-PROGRAMS       += occlientcoll
-PROGRAMS       += occlientbasicops
-PROGRAMS       += occlientslow
-
-all:   c_sdk prep_dirs $(OBJECTS) $(PROGRAMS)
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-       -mkdir -p $(OBJ_DIR)
-
-c_sdk:
-       cd $(ROOT_DIR) && $(MAKE) BUILD=$(BUILD) PLATFORM=$(PLATFORM)
-
-$(OBJ_DIR)/%.o: %.cpp
-       $(CC) -c $(CPPFLAGS) $< -o $@
-
-ocserver: $(OBJ_DIR)/ocserver.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-ocserverslow: $(OBJ_DIR)/ocserverslow.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-ocserverbasicops: $(OBJ_DIR)/ocserverbasicops.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-ocservercoll: $(OBJ_DIR)/ocservercoll.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-occlient: $(OBJ_DIR)/occlient.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-occlientbasicops: $(OBJ_DIR)/occlientbasicops.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-occlientslow: $(OBJ_DIR)/occlientslow.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-occlientcoll: $(OBJ_DIR)/occlientcoll.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-.PHONY: clean
-
-clean: legacy_clean
-       -rm -rf release
-       -rm -rf debug
-       cd $(ROOT_DIR) && $(MAKE) clean
-       cd $(ROOT_DIR) && $(MAKE) deepclean
-
-legacy_clean:
-       rm -f *.o $(PROGRAMS)
index 9965a22..fae9406 100644 (file)
 
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
-static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
-static const char * TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core/d";
-static const char * TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY = "coap://224.0.1.187:5683/oc/core/d";
-static std::string putPayload = "{\"state\":\"on\",\"power\":5}";
+static const char * UNICAST_DISCOVERY_QUERY = "coap://%s:6298/oc/core";
+static const char * UNICAST_DEVICE_DISCOVERY_QUERY = "coap://%s:6298/oc/core/d";
+static const char * UNICAST_PLATFORM_DISCOVERY_QUERY = "coap://%s:6298/oic/p";
+static const char * MULTICAST_DEVICE_DISCOVERY_QUERY = "/oc/core/d";
+static const char * MULTICAST_PLATFORM_DISCOVERY_QUERY = "/oic/p";
+static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
+//The following variable determines the interface protocol (IPv4, IPv6, etc)
+//to be used for sending unicast messages. Default set to IPv4.
+static OCConnectivityType OC_CONNTYPE = OC_IPV4;
+static std::string putPayload = "{\"oc\":[{\"rep\":{\"power\":15,\"state\":true}}]}";
 static std::string coapServerIP = "255.255.255.255";
 static std::string coapServerPort = "5683";
 static std::string coapServerResource = "/a/light";
+static const int IPV4_ADDR_SIZE = 16;
+//Use ipv4addr for both InitDiscovery and InitDeviceDiscovery
+char ipv4addr[IPV4_ADDR_SIZE];
+void StripNewLineChar(char* str);
 
 // The handle for the observe registration
 OCDoHandle gObserveDoHandle;
@@ -54,47 +64,57 @@ int gNumPresenceNotifies = 0;
 
 int gQuitFlag = 0;
 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
-void handleSigInt(int signum) {
-    if (signum == SIGINT) {
+void handleSigInt(int signum)
+{
+    if (signum == SIGINT)
+    {
         gQuitFlag = 1;
     }
 }
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7>");
+    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> : IPv4/IPv6 (IPv6 not currently supported)");
     OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
     OC_LOG(INFO, TAG, "-t 2  :  Discover Resources and Initiate Nonconfirmable Get Request");
-    OC_LOG(INFO, TAG, "-t 3  :  Discover Resources and Initiate Nonconfirmable Put Requests");
-    OC_LOG(INFO, TAG, "-t 4  :  Discover Resources and Initiate Nonconfirmable Post Requests");
-    OC_LOG(INFO, TAG, "-t 5  :  Discover Resources and Initiate Nonconfirmable Delete Requests");
-    OC_LOG(INFO, TAG, "-t 6  :  Discover Resources and Initiate Nonconfirmable Observe Requests");
-    OC_LOG(INFO, TAG, "-t 7  :  Discover Resources and Initiate Nonconfirmable Get Request for a resource which is unavailable");
-
-    OC_LOG(INFO, TAG, "-t 8  :  Discover Resources and Initiate Confirmable Get Request");
-    OC_LOG(INFO, TAG, "-t 9  :  Discover Resources and Initiate Confirmable Post Request");
-    OC_LOG(INFO, TAG, "-t 10 :  Discover Resources and Initiate Confirmable Delete Requests");
-    OC_LOG(INFO, TAG, "-t 11 :  Discover Resources and Initiate Confirmable Observe Requests");
-
-    #ifdef WITH_PRESENCE
-    OC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Nonconfirmable presence");
-    OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence with "\
-            "filter");
+    OC_LOG(INFO, TAG, "-t 3  :  Discover Resources and Initiate Nonconfirmable Get Request"
+            " with query filter.");
+    OC_LOG(INFO, TAG, "-t 4  :  Discover Resources and Initiate Nonconfirmable Put Requests");
+    OC_LOG(INFO, TAG, "-t 5  :  Discover Resources and Initiate Nonconfirmable Post Requests");
+    OC_LOG(INFO, TAG, "-t 6  :  Discover Resources and Initiate Nonconfirmable Delete Requests");
+    OC_LOG(INFO, TAG, "-t 7  :  Discover Resources and Initiate Nonconfirmable Observe Requests");
+    OC_LOG(INFO, TAG, "-t 8  :  Discover Resources and Initiate Nonconfirmable Get Request "\
+            "for a resource which is unavailable");
+    OC_LOG(INFO, TAG, "-t 9  :  Discover Resources and Initiate Confirmable Get Request");
+    OC_LOG(INFO, TAG, "-t 10  :  Discover Resources and Initiate Confirmable Post Request");
+    OC_LOG(INFO, TAG, "-t 11 :  Discover Resources and Initiate Confirmable Delete Requests");
+    OC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Confirmable Observe Requests"\
+            " and cancel with Low QoS");
+
+#ifdef WITH_PRESENCE
+    OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence");
     OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable presence with "\
+            "filter");
+    OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable presence with "\
             "2 filters");
-    #endif
+    OC_LOG(INFO, TAG, "-t 16 :  Discover Resources and Initiate Nonconfirmable multicast presence.");
+#endif
 
-    OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable Observe Requests "\
-            "then cancel immediately");
-    OC_LOG(INFO, TAG, "-t 16 :  Discover Resources and Initiate Nonconfirmable Get Request and "\
+    OC_LOG(INFO, TAG, "-t 17 :  Discover Resources and Initiate Nonconfirmable Observe Requests "\
+            "then cancel immediately with High QOS");
+    OC_LOG(INFO, TAG, "-t 18 :  Discover Resources and Initiate Nonconfirmable Get Request and "\
             "add  vendor specific header options");
-    OC_LOG(INFO, TAG, "-t 17 :  Discover Devices");
+    OC_LOG(INFO, TAG, "-t 19 :  Discover Platform");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
-                                 OCMethod method, OCQualityOfService qos,
-                                 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
+                                 OCMethod method,
+                                 OCQualityOfService qos,
+                                 OCClientResponseHandler cb,
+                                 OCHeaderOption * options,
+                                 uint8_t numOptions)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -106,7 +126,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
                        (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
-                       qos, &cbData, options, numOptions);
+                       (OC_CONNTYPE), qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -116,17 +136,18 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     {
         gObserveDoHandle = handle;
     }
-    #ifdef WITH_PRESENCE
+#ifdef WITH_PRESENCE
     else if (method == OC_REST_PRESENCE)
     {
         gPresenceHandle = handle;
     }
-    #endif
+#endif
 
     return ret;
 }
 
-OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
+OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+{
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
@@ -135,7 +156,12 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     if(clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
+        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;
 }
@@ -150,12 +176,18 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientRespons
     if(clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload);
+        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;
 }
 
-OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
+OCStackApplicationResult deleteReqCB(void *ctx,
+        OCDoHandle handle, OCClientResponse *clientResponse)
 {
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
@@ -165,7 +197,12 @@ OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientRespo
     if(clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload);
+        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;
 }
@@ -174,9 +211,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");
@@ -198,15 +236,17 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
             {
                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                         ((OCHeaderOption)rcvdOptions[i]).optionID );
+
                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
-                        ((OCHeaderOption)rcvdOptions[i]).optionLength);
+                    MAX_HEADER_OPTION_DATA_LENGTH);
             }
         }
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
+OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+{
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
@@ -216,63 +256,88 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
+        OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d",
+                gNumObserveNotifies);
+        OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response",
+                clientResponse->resJSONPayload);
         gNumObserveNotifies++;
-        if (gNumObserveNotifies == 3)  //large number to test observing in DELETE case.
+        if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
         {
-            if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
-                if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
+            if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON)
+            {
+                if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
+                {
                     OC_LOG(ERROR, TAG, "Observe cancel error");
                 }
                 return OC_STACK_DELETE_TRANSACTION;
-            }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
-                if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
+            }
+            else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM)
+            {
+                if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
+                {
                     OC_LOG(ERROR, TAG, "Observe cancel error");
                 }
             }
         }
-        if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
+        if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
+        {
             OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
-        }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
+        }
+        else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
+        {
             OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
             return OC_STACK_DELETE_TRANSACTION;
-        }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
+        }
+        else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
+        {
             OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "obsReqCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 #ifdef WITH_PRESENCE
-OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+{
+    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
+        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
         OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
-        OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
+        OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d",
+                gNumPresenceNotifies);
+        OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response",
+                clientResponse->resJSONPayload);
         gNumPresenceNotifies++;
         if (gNumPresenceNotifies == 20)
         {
-            if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
+            if (OCCancel(gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
+            {
                 OC_LOG(ERROR, TAG, "Presence cancel error");
             }
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 #endif
 
 // This is a function called back when a device is discovered
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
-        OCClientResponse * clientResponse) {
+        OCClientResponse * clientResponse)
+{
     uint8_t remoteIpAddr[4];
     uint16_t remotePortNu;
 
@@ -289,6 +354,8 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
 
+        std::string connectionType = getConnectivityType (clientResponse->connType);
+        OC_LOG_V(INFO, TAG, "Discovered on %s", connectionType.c_str());
         OC_LOG_V(INFO, TAG,
                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
@@ -299,10 +366,13 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         switch(TEST_CASE)
         {
             case TEST_GET_REQ_NON:
-                InitGetRequest(OC_LOW_QOS, 0);
+                InitGetRequest(OC_LOW_QOS, 0, 0);
+                break;
+            case TEST_GET_REQ_NON_WITH_FILTERS:
+                InitGetRequest(OC_LOW_QOS, 0, 1);
                 break;
             case TEST_PUT_REQ_NON:
-                InitPutRequest();
+                InitPutRequest(OC_LOW_QOS);
                 break;
             case TEST_POST_REQ_NON:
                 InitPostRequest(OC_LOW_QOS);
@@ -315,10 +385,10 @@ 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);
+                InitGetRequest(OC_HIGH_QOS, 0, 0);
                 break;
             case TEST_POST_REQ_CON:
                 InitPostRequest(OC_HIGH_QOS);
@@ -329,35 +399,38 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             case TEST_OBS_REQ_CON:
                 InitObserveRequest(OC_HIGH_QOS);
                 break;
-            #ifdef WITH_PRESENCE
+#ifdef WITH_PRESENCE
             case TEST_OBS_PRESENCE:
             case TEST_OBS_PRESENCE_WITH_FILTER:
             case TEST_OBS_PRESENCE_WITH_FILTERS:
+            case TEST_OBS_MULTICAST_PRESENCE:
                 InitPresence();
                 break;
-            #endif
+#endif
             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
-                InitGetRequest(OC_LOW_QOS, 1);
+                InitGetRequest(OC_LOW_QOS, 1, 0);
                 break;
             case TEST_DISCOVER_DEV_REQ:
-                InitDeviceDiscovery();
+                InitDeviceDiscovery(OC_LOW_QOS);
                 break;
             default:
                 PrintUsage();
                 break;
         }
     }
-
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
-
+    else
+    {
+        OC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
+    }
+    return OC_STACK_KEEP_TRANSACTION;
 }
 
-OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
+OCStackApplicationResult PlatformDiscoveryReqCB (void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
+        OC_LOG(INFO, TAG, "Callback Context for Platform DISCOVER query recvd successfully");
     }
 
     if(clientResponse)
@@ -366,6 +439,10 @@ OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
         fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
         fflush(stderr);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
+    }
 
     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
 }
@@ -386,7 +463,7 @@ int InitPresence()
     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER || TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
     {
         querySuffix.str("");
-        querySuffix << query.str() << "?rt=core.light";
+        querySuffix << query.str() << "?rt=core.led";
         result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
                 presenceCB, NULL, 0);
     }
@@ -400,15 +477,28 @@ int InitPresence()
                     presenceCB, NULL, 0);
         }
     }
+    if(TEST_CASE == TEST_OBS_MULTICAST_PRESENCE)
+    {
+        if(result == OC_STACK_OK)
+        {
+            std::ostringstream multicastPresenceQuery;
+            multicastPresenceQuery.str("");
+            multicastPresenceQuery << "coap://" << OC_MULTICAST_PREFIX << OC_PRESENCE_URI;
+            result = InvokeOCDoResource(multicastPresenceQuery, OC_REST_PRESENCE, OC_LOW_QOS,
+                    presenceCB, NULL, 0);
+        }
+    }
     return result;
 }
 #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)
@@ -416,15 +506,17 @@ int InitObserveRequest(OCQualityOfService qos)
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
+    return (InvokeOCDoResource(query,
+            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)
@@ -461,7 +553,7 @@ int InitPostRequest(OCQualityOfService qos)
 
 void* RequestDeleteDeathResourceTask(void* myqos)
 {
-    sleep (30);        //long enough to give the server time to finish deleting the resource.
+    sleep (30);//long enough to give the server time to finish deleting the resource.
     std::ostringstream query;
     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
 
@@ -470,9 +562,13 @@ void* RequestDeleteDeathResourceTask(void* myqos)
     // Second DELETE operation to delete the resource that might have been removed already.
     OCQualityOfService qos;
     if (myqos == NULL)
+    {
         qos = OC_LOW_QOS;
+    }
     else
+    {
         qos = OC_HIGH_QOS;
+    }
 
     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
                                qos,
@@ -514,18 +610,26 @@ int InitDeleteRequest(OCQualityOfService qos)
     return result;
 }
 
-int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
+int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions, bool getWithQuery)
 {
+
     OCHeaderOption options[MAX_HEADER_OPTIONS];
 
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
 
-    if(withVendorSpecificHeaderOptions)
+    // ocserver is written to only process "power<X" query.
+    if (getWithQuery)
+    {
+        OC_LOG(INFO, TAG, "Using query power<30");
+        query << "?power<30";
+    }
+
+    if (withVendorSpecificHeaderOptions)
     {
-        uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
-        uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
+        uint8_t option0[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+        uint8_t option1[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
         options[0].protocolID = OC_COAP_ID;
         options[0].optionID = 2048;
@@ -536,39 +640,49 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
         memcpy(options[1].optionData, option1, sizeof(option1));
         options[1].optionLength = 10;
     }
-    if(withVendorSpecificHeaderOptions)
+    if (withVendorSpecificHeaderOptions)
     {
-        return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
+        return (InvokeOCDoResource(query, OC_REST_GET,
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, options, 2));
     }
     else
     {
-        return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS: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 InitDeviceDiscovery()
+int InitDeviceDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
     char szQueryUri[64] = { 0 };
 
-    cbData.cb = DeviceDiscoveryReqCB;
+    cbData.cb = PlatformDiscoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
     if(UNICAST_DISCOVERY)
     {
-        strncpy(szQueryUri, TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY,
-                        (strlen(TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY) + 1));
+        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PLATFORM_DISCOVERY_QUERY, ipv4addr);
     }
     else
     {
-        strncpy(szQueryUri, TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY,
-                (strlen(TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY) + 1));
+        strncpy(szQueryUri, MULTICAST_PLATFORM_DISCOVERY_QUERY,
+                sizeof(szQueryUri) -1 );
+        szQueryUri[sizeof(szQueryUri) -1] = '\0';
     }
 
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
+    if(UNICAST_DISCOVERY)
+    {
+        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
+                (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),
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
+    }
 
     if (ret != OC_STACK_OK)
     {
@@ -578,25 +692,35 @@ int InitDeviceDiscovery()
     return ret;
 }
 
-int InitDiscovery()
+int InitDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
     /* Start a discovery query*/
     char szQueryUri[64] = { 0 };
+
     if (UNICAST_DISCOVERY)
     {
-        strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
+        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
     }
     else
     {
-        strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+        strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
     }
+
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
+    if(UNICAST_DISCOVERY)
+    {
+        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
+                (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),
+                (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");
@@ -604,14 +728,11 @@ int InitDiscovery()
     return ret;
 }
 
-int main(int argc, char* argv[]) {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+int main(int argc, char* argv[])
+{
     int opt;
 
-    while ((opt = getopt(argc, argv, "u:t:")) != -1)
+    while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
     {
         switch(opt)
         {
@@ -621,6 +742,12 @@ int main(int argc, char* argv[]) {
             case 't':
                 TEST_CASE = atoi(optarg);
                 break;
+            case 'c':
+                // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
+                // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
+                OC_CONNTYPE = OC_IPV4;
+                OC_LOG(INFO, TAG, "IPv6 not currently supported, using IPv4.");
+                break;
             default:
                 PrintUsage();
                 return -1;
@@ -634,30 +761,44 @@ int main(int argc, char* argv[]) {
         return -1;
     }
 
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
-        paddr = addr;
-    }
-
     /* Initialize OCStack*/
-    if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
+    if (UNICAST_DISCOVERY)
+    {
+        printf("Enter IPv4 address of the Server hosting resource (Ex: 192.168.0.15)\n");
+        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        {
+            //Strip newline char from ipv4addr
+            StripNewLineChar(ipv4addr);
+        }
+        else
+        {
+            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            return OC_STACK_INVALID_PARAM;
+        }
+     }
 
-    InitDiscovery();
+    if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_DEV_REQ)
+    {
+        InitDeviceDiscovery(OC_LOW_QOS);
+    }
+    else
+    {
+        InitDiscovery(OC_LOW_QOS);
+    }
 
     // Break from loop with Ctrl+C
     OC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
-    while (!gQuitFlag) {
+    while (!gQuitFlag)
+    {
 
-        if (OCProcess() != OC_STACK_OK) {
+        if (OCProcess() != OC_STACK_OK)
+        {
             OC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
@@ -666,41 +807,87 @@ int main(int argc, char* argv[]) {
     }
     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
-    if (OCStop() != OC_STACK_OK) {
+    if (OCStop() != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
 }
 
-std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
-    if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
+std::string getIPAddrTBServer(OCClientResponse * clientResponse)
+{
+    if (!clientResponse)
+    {
+        return "";
+    }
+    if (!clientResponse->addr)
+    {
+        return "";
+    }
     uint8_t a, b, c, d = 0;
-    if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
+    if (0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
+    {
+        return "";
+    }
 
     char ipaddr[16] = {'\0'};
-    snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
+    // ostringstream not working correctly here, hence snprintf
+    snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
     return std::string (ipaddr);
 }
 
-std::string getPortTBServer(OCClientResponse * clientResponse){
-    if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
+std::string getPortTBServer(OCClientResponse * clientResponse)
+{
+    if (!clientResponse)
+    {
+        return "";
+    }
+    if (!clientResponse->addr)
+    {
+        return "";
+    }
     uint16_t p = 0;
-    if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
+    if (0 != OCDevAddrToPort(clientResponse->addr, &p))
+    {
+        return "";
+    }
     std::ostringstream ss;
     ss << p;
     return ss.str();
 }
 
-std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
+std::string getConnectivityType (OCConnectivityType connType)
+{
+    switch (connType)
+    {
+        case OC_IPV4:
+            return "IPv4";
+
+        case OC_IPV6:
+            return "IPv6";
+
+        case OC_LE:
+            return "BLE";
+
+        case OC_EDR:
+            return "BT";
+
+        default:
+            return "Incorrect connectivity";
+    }
+}
+
+std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
+{
 
     return "/a/light";
 }
 
-void parseClientResponse(OCClientResponse * clientResponse){
+void parseClientResponse(OCClientResponse * clientResponse)
+{
     coapServerIP = getIPAddrTBServer(clientResponse);
     coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }
+
index 96444ca..1570a94 100644 (file)
@@ -43,6 +43,7 @@
 typedef enum {
     TEST_DISCOVER_REQ = 1,
     TEST_GET_REQ_NON,
+    TEST_GET_REQ_NON_WITH_FILTERS,
     TEST_PUT_REQ_NON,
     TEST_POST_REQ_NON,
     TEST_DELETE_REQ_NON,
@@ -56,6 +57,7 @@ typedef enum {
     TEST_OBS_PRESENCE,
     TEST_OBS_PRESENCE_WITH_FILTER,
     TEST_OBS_PRESENCE_WITH_FILTERS,
+    TEST_OBS_MULTICAST_PRESENCE,
 #endif
     TEST_OBS_REQ_NON_CANCEL_IMM,
     TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS,
@@ -70,6 +72,7 @@ int InitPresence();
 //----------------------------------------------------------------------------
 // Function prototype
 //----------------------------------------------------------------------------
+std::string getConnectivityType (OCConnectivityType connType);
 
 /* call getResult in common.cpp to get the result in string format. */
 const char *getResult(OCStackResult result);
@@ -86,15 +89,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 InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions);
+int InitPutRequest(OCQualityOfService qos);
+int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions, bool getWithQuery);
 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.
@@ -137,3 +140,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
 
 #endif
+
index a526935..30f79d9 100644 (file)
@@ -7,7 +7,6 @@
 // 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
 #include <string.h>
 #include <signal.h>
 #include <unistd.h>
-#include <iostream>
+#include <stdint.h>
 #include <sstream>
+
 #include "ocstack.h"
 #include "logger.h"
 #include "occlientbasicops.h"
+#include "cJSON.h"
+#include "ocmalloc.h"
 
+#define MAX_IP_ADDR_ST_SZ  16 //string size of "155.255.255.255" (15 + 1)
+#define MAX_PORT_ST_SZ  6     //string size of "65535" (5 + 1)
+
+static int IPV4_ADDR_SIZE = 16;
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
-static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
+
+static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oc/core";
 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
-static std::string coapServerIP = "255.255.255.255";
-static std::string coapServerPort = "5683";
-static std::string coapServerResource = "/a/led";
+
+//The following variable determines the interface protocol (IPv4, IPv6, etc)
+//to be used for sending unicast messages. Default set to IPv4.
+static OCConnectivityType OC_CONNTYPE = OC_IPV4;
+static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
 
 int gQuitFlag = 0;
 
-/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
+struct ResourceNode *resourceList;
+/*
+ * SIGINT handler: set gQuitFlag to 1 for graceful termination
+ * */
 void handleSigInt(int signum)
 {
     if (signum == SIGINT)
@@ -50,224 +62,323 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
+    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
             " Initiate Nonconfirmable Get/Put/Post Requests");
-    OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
+    OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
+            "Confirmable Get/Put/Post Requests");
+    OC_LOG(INFO, TAG, "-c <0|1> : IPv4/IPv6 (IPv6 not currently supported)");
+    OC_LOG(INFO, TAG, "Default connectivityType IPv4");
+}
+
+/*
+ * Returns the first resource in the list
+ */
+const ResourceNode * getResource()
+{
+    return resourceList;
 }
 
-OCStackResult InvokeOCDoResource(std::ostringstream &query,
-        OCMethod method, OCQualityOfService qos,
+OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
+                                 OCConnectivityType connType, OCQualityOfService qos,
         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
 
     cbData.cb = cb;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, method, query.str().c_str(), 0,
-            (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
-            qos, &cbData, options, numOptions);
+    ret = OCDoResource(NULL, method, query.str().c_str(), 0,
+        (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
+         connType, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
-        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
+        OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
+                 ret, method);
     }
 
     return ret;
 }
 
-OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle,
+                                OCClientResponse * clientResponse)
 {
+    uint8_t remoteIpAddr[4];
+    uint16_t remotePortNu;
+
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
+        OC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
     }
 
     if(clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
+        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
+                            remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
+        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
+
+        OC_LOG_V(INFO, TAG,"PUT Response: %s \nFrom %d.%d.%d.%d:%d\n",
+                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
+                remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
+OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle,
+                          OCClientResponse *clientResponse)
 {
+    uint8_t remoteIpAddr[4];
+    uint16_t remotePortNu;
+
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
+        OC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
     }
 
     if(clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
-                clientResponse->resJSONPayload);
+        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
+                            remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
+        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
+
+        OC_LOG_V(INFO, TAG,"POST Response: %s \nFrom %d.%d.%d.%d:%d\n",
+                    clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
+                    remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
     }
+    else
+    {
+        OC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
+    }
+
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle,
+                           OCClientResponse * clientResponse)
 {
-    if(clientResponse == NULL)
+    uint8_t remoteIpAddr[4];
+    uint16_t remotePortNu;
+
+    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "The clientResponse is NULL");
-        return   OC_STACK_DELETE_TRANSACTION;
+        OC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
     }
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    else
     {
-        OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
+        OC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
     }
 
-    OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-    OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-    OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
-            clientResponse->resJSONPayload);
-
-    if(clientResponse->rcvdVendorSpecificHeaderOptions &&
-            clientResponse->numRcvdVendorSpecificHeaderOptions)
+    if (clientResponse)
     {
-        OC_LOG (INFO, TAG, "Received vendor specific options");
-        uint8_t i = 0;
-        OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
-        for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
+        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, remoteIpAddr + 1,
+                remoteIpAddr + 2, remoteIpAddr + 3);
+        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
+
+        OC_LOG_V(INFO, TAG,"Get Response: %s \nFrom %d.%d.%d.%d:%d\n",
+                clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
+                remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+
+        if (clientResponse->rcvdVendorSpecificHeaderOptions
+                && clientResponse->numRcvdVendorSpecificHeaderOptions)
         {
-            if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
+            OC_LOG (INFO, TAG, "Received vendor specific options");
+            uint8_t i = 0;
+            OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
+            for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
             {
-                OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
-                        ((OCHeaderOption)rcvdOptions[i]).optionID );
-                OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
-                        ((OCHeaderOption)rcvdOptions[i]).optionLength);
+                if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
+                {
+                    OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
+                            ((OCHeaderOption)rcvdOptions[i]).optionID );
+
+                    OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
+                        MAX_HEADER_OPTION_DATA_LENGTH);
+                }
             }
         }
     }
+    else
+    {
+        OC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
+    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-// This is a function called back when a device is discovered
+/*
+ * This is a function called back when a device is discovered
+ */
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse)
 {
     uint8_t remoteIpAddr[4];
     uint16_t remotePortNu;
-
-    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
-        OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
+        OC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
+               "received successfully====>");
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
     }
 
     if (clientResponse)
     {
-        OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-
         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
 
         OC_LOG_V(INFO, TAG,
-                "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
+                "Device Discovered %s \n @ %d.%d.%d.%d:%d\n",
                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
 
-        parseClientResponse(clientResponse);
-
-        switch(TEST_CASE)
-        {
-            case TEST_NON_CON_OP:
-                InitGetRequest(OC_LOW_QOS);
-                InitPutRequest();
-                InitPostRequest(OC_LOW_QOS);
-                break;
-            case TEST_CON_OP:
-                InitGetRequest(OC_HIGH_QOS);
-                InitPutRequest();
-                InitPostRequest(OC_HIGH_QOS);
-                break;
-            default:
-                PrintUsage();
-                break;
-        }
+        collectUniqueResource(clientResponse);
     }
-
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
-
+    else
+    {
+        OC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
+    }
+    return (UNICAST_DISCOVERY) ?
+           OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
 }
 
-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));
+    //Get most recently inserted resource
+    const ResourceNode * resource  = getResource();
+
+    if(!resource)
+    {
+        OC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
+        return -1;
+    }
+    query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
+    OC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
+
+    return (InvokeOCDoResource(query, OC_REST_PUT, resource->connType,
+           ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
+            putReqCB, NULL, 0));
 }
 
 int InitPostRequest(OCQualityOfService qos)
 {
     OCStackResult result;
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    //Get most recently inserted resource
+    const ResourceNode * resource  = getResource();
+
+    if(!resource)
+    {
+        OC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
+        return -1;
+    }
+
+    query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
+    OC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
 
     // First POST operation (to create an LED instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
     {
         // Error can happen if for example, network connectivity is down
-        OC_LOG(INFO, TAG, "First POST call did not succeed");
+        OC_LOG(ERROR, TAG, "First POST call did not succeed");
     }
 
     // Second POST operation (to create an LED instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
     {
-        OC_LOG(INFO, TAG, "Second POST call did not succeed");
+        OC_LOG(ERROR, TAG, "Second POST call did not succeed");
     }
 
     // This POST operation will update the original resourced /a/led
-    return (InvokeOCDoResource(query, OC_REST_POST,
+    return (InvokeOCDoResource(query, OC_REST_POST,resource->connType,
                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                 postReqCB, NULL, 0));
 }
 
 int InitGetRequest(OCQualityOfService qos)
 {
-    OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    //Get most recently inserted resource
+    const ResourceNode * resource  = getResource();
+
+    if(!resource)
+    {
+        OC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
+        return -1;
+    }
+    query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
+    OC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
 
-    return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
-            OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_GET, resource->connType,
+            (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
 }
 
 int InitDiscovery()
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
     /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[64] = {};
     if (UNICAST_DISCOVERY)
     {
-        strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
+        char ipv4addr[IPV4_ADDR_SIZE];
+        printf("Enter IPv4 address of the Server hosting "
+               "resource (Ex: 192.168.0.15)\n");
+        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        {
+            //Strip newline char from ipv4addr
+            StripNewLineChar(ipv4addr);
+            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
+        }
+        else
+        {
+            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            return OC_STACK_INVALID_PARAM;
+        }
     }
     else
     {
-        strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+        strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
     }
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
+    if (UNICAST_DISCOVERY)
+    {
+        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
+                OC_LOW_QOS, &cbData, NULL, 0);
+    }
+    else
+    {
+        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
+                OC_LOW_QOS, &cbData, NULL, 0);
+    }
+
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -275,15 +386,311 @@ int InitDiscovery()
     return ret;
 }
 
+
+
+const char * getIPAddr(const OCClientResponse * clientResponse)
+{
+    uint8_t a, b, c, d;
+   if(!clientResponse || 0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
+    {
+        return "";
+    }
+
+    char * ipaddr = NULL;
+    if((ipaddr = (char *) OCCalloc(1, MAX_IP_ADDR_ST_SZ)))
+    {
+        snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%d.%d.%d.%d", a,b,c,d);
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, "Memory not allocated to ipaddr");
+    }
+    return ipaddr;
+}
+
+const char * getPort(const OCClientResponse * clientResponse)
+{
+    uint16_t p = 0;
+    if(!clientResponse || 0 != OCDevAddrToPort(clientResponse->addr, &p) )
+    {
+        return "";
+    }
+
+    char * port = NULL;
+    if((port = (char *) OCCalloc(1, MAX_PORT_ST_SZ)))
+    {
+        snprintf(port, MAX_PORT_ST_SZ, "%d", p);
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, "Memory not allocated to port");
+    }
+    return port;
+}
+
+int parseJSON(const char * resJSONPayload, char ** sid_c,
+              char *** uri_c, int * totalRes)
+{
+    cJSON * root = NULL;
+    cJSON * oc = NULL;
+
+    root = cJSON_Parse((char *)(resJSONPayload));
+
+    if (!root)
+    {
+        OC_LOG(ERROR, TAG, "JSON Parsing Error");
+        return OC_STACK_INVALID_JSON;
+    }
+
+    oc = cJSON_GetObjectItem(root,"oc");
+    if (!oc)
+    {
+        OC_LOG(ERROR, TAG, "Invalid JSON : Missing oc object");
+        return OC_STACK_INVALID_JSON;
+    }
+
+    * totalRes = cJSON_GetArraySize(oc);
+
+    if(oc->type == cJSON_Array)
+    {
+        cJSON * resource = cJSON_GetArrayItem(oc, 0);
+
+        if(!resource)
+        {
+            return OC_STACK_INVALID_JSON;
+        }
+
+        if (cJSON_GetObjectItem(resource, "sid"))
+        {
+            char * sid = cJSON_GetObjectItem(resource, "sid")->valuestring;
+            if((* sid_c = (char *)OCCalloc(1, strlen (sid) + 1)))
+            {
+                memcpy(* sid_c, sid, strlen(sid) + 1);
+            }
+            else
+            {
+                OC_LOG(ERROR, TAG, "Memory not allocated to sid");
+                return OC_STACK_NO_MEMORY;
+            }
+        }
+        else
+        {
+            OC_LOG(ERROR, TAG, "Invalid JSON : Missing sid object");
+            return OC_STACK_INVALID_JSON;
+        }
+
+        if(!(* uri_c =  (char ** )OCMalloc ((* totalRes) * sizeof(char **))))
+        {
+            OC_LOG(ERROR, TAG, "Memory not allocated to sid_c array");
+            return OC_STACK_NO_MEMORY;
+        }
+
+        int i = 0;
+
+        while(true)
+        {
+            if (cJSON_GetObjectItem(resource, "href"))
+            {
+                char *uri= cJSON_GetObjectItem(resource, "href")->valuestring;
+                if(((*uri_c)[i] = (char *)OCCalloc(1, strlen (uri) + 1)))
+                {
+                    memcpy((*uri_c)[i], uri, strlen(uri) + 1);
+                }
+                else
+                {
+                    OC_LOG(ERROR, TAG, "Memory not allocated to uri");
+                    return OC_STACK_NO_MEMORY;
+                }
+                i++;
+                if(i >= (* totalRes))
+                    break;
+                resource = cJSON_GetArrayItem(oc, i);
+            }
+            else
+            {
+               OC_LOG(ERROR, TAG, "Invalid JSON : Missing uri object");
+               return OC_STACK_INVALID_JSON;
+           }
+        }
+    }
+    else
+    {
+        return OC_STACK_INVALID_JSON;
+        OC_LOG(ERROR, TAG, "Invalid JSON : oc object type is not an array");
+    }
+    return OC_STACK_OK;
+}
+
+void queryResource()
+{
+    printf("\n");
+    switch(TEST_CASE)
+    {
+        case TEST_DISCOVER_REQ:
+            break;
+        case TEST_NON_CON_OP:
+            InitGetRequest(OC_LOW_QOS);
+            InitPutRequest(OC_LOW_QOS);
+            InitPostRequest(OC_LOW_QOS);
+            break;
+        case TEST_CON_OP:
+            InitGetRequest(OC_HIGH_QOS);
+            InitPutRequest(OC_HIGH_QOS);
+            InitPostRequest(OC_HIGH_QOS);
+            break;
+        default:
+            PrintUsage();
+            break;
+    }
+    printf("\n");
+}
+
+
+void collectUniqueResource(const OCClientResponse * clientResponse)
+{
+    char * sid = NULL;
+    char ** uri = NULL;
+    int totalRes = 0;
+
+    if(parseJSON(clientResponse->resJSONPayload, & sid, & uri, &totalRes)
+            != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, "Error while parsing JSON payload in OCClientResponse");
+        OCFree(sid);
+        OCFree(uri);
+        return;
+    }
+
+    int i;
+    for(i = 0; i < totalRes; i++)
+    {
+        if(insertResource(sid, uri[i], clientResponse) == 1)
+        {
+            printf("%s%s%s%s\n",sid, ":", uri[i], " is new");
+            printResourceList();
+            queryResource();
+        }
+        else
+        {
+            printf("%s%s%s%s\n\n",sid, ":", uri[i], " has been seen before");
+        }
+    }
+
+    OCFree(sid);
+    OCFree(uri);
+ }
+
+/* This function searches for the resource(sid:uri) in the ResourceList.
+ * If the Resource is found in the list then it returns 0 else insert
+ * the resource to front of the list and returns 1.
+ */
+int insertResource(const char * sid, char const * uri,
+            const OCClientResponse * clientResponse)
+{
+    ResourceNode * iter = resourceList;
+
+    //Checking if the resource(sid:uri) is new
+    while(iter)
+    {
+        if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
+        {
+            return 0;
+        }
+        else
+        {
+            iter = iter->next;
+        }
+    }
+
+    //Creating new ResourceNode
+    if((iter = (ResourceNode *) OCMalloc(sizeof(ResourceNode))))
+    {
+        iter->sid = sid;
+        iter->uri = uri;
+        iter->ip = getIPAddr(clientResponse);
+        iter->port = getPort(clientResponse);
+        iter->connType = clientResponse->connType;
+        iter->next = NULL;
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
+        return -1;
+    }
+
+    //Adding new ResourceNode to front of the ResourceList
+    if(!resourceList)
+    {
+        resourceList = iter;
+    }
+    else
+    {
+        iter->next = resourceList;
+        resourceList = iter;
+    }
+    return 1;
+}
+
+void printResourceList()
+{
+    ResourceNode * iter;
+    iter = resourceList;
+    printf("\nResource List\n");
+    while(iter)
+    {
+        printf("*****************************************************\n");
+        printf("sid = %s \n",iter->sid);
+        printf("uri = %s\n", iter->uri);
+        printf("ip = %s\n", iter->ip);
+        printf("port = %s\n", iter->port);
+        switch (iter->connType)
+        {
+            case OC_IPV4:
+                printf("connType = %s\n","IPv4");
+                break;
+            case OC_IPV6:
+                // TODO: Allow IPv6 when support is added
+                printf("IPv6 not currently supported, default to IPv4\n");
+                //printf("connType = %s\n","IPv6");
+                printf("connType = %s\n","IPv4");
+                break;
+            case OC_LE:
+                printf("connType = %s\n","BLE");
+                break;
+            case OC_EDR:
+                printf("connType = %s\n","BT");
+                break;
+            case OC_ALL:
+            default:
+                printf("connType = %s\n","Invalid connType");
+                break;
+        }
+        printf("*****************************************************\n");
+        iter = iter->next;
+    }
+}
+
+void freeResourceList()
+{
+    OC_LOG(INFO, TAG, "Freeing ResourceNode List");
+    ResourceNode * temp;
+    while(resourceList)
+    {
+        temp = resourceList;
+        resourceList = resourceList->next;
+        OCFree((void *)temp->sid);
+        OCFree((void *)temp->uri);
+        OCFree((void *)temp->ip);
+        OCFree((void *)temp->port);
+        OCFree(temp);
+    }
+}
+
 int main(int argc, char* argv[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
     int opt;
-
-    while ((opt = getopt(argc, argv, "u:t:")) != -1)
+    resourceList = NULL;
+    while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
     {
         switch(opt)
         {
@@ -293,6 +700,12 @@ int main(int argc, char* argv[])
             case 't':
                 TEST_CASE = atoi(optarg);
                 break;
+            case 'c':
+                // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
+                // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
+                OC_CONNTYPE = OC_IPV4;
+                OC_LOG(INFO, TAG, "Using default IPv4, IPv6 not currently supported.");
+                break;
             default:
                 PrintUsage();
                 return -1;
@@ -306,18 +719,8 @@ int main(int argc, char* argv[])
         return -1;
     }
 
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
-        paddr = addr;
-    }
-
     /* Initialize OCStack*/
-    if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
@@ -326,8 +729,8 @@ int main(int argc, char* argv[])
     InitDiscovery();
 
     // Break from loop with Ctrl+C
-    OC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
+
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
@@ -335,52 +738,16 @@ int main(int argc, char* argv[])
             OC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
-
         sleep(2);
     }
-    OC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
+    freeResourceList();
+    OC_LOG(INFO, TAG, "Exiting occlient main loop...");
     if (OCStop() != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack stop error");
     }
-
     return 0;
 }
 
-std::string getIPAddrTBServer(OCClientResponse * clientResponse)
-{
-    if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
-    uint8_t a, b, c, d = 0;
-    if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
-
-    char ipaddr[16] = {'\0'};
-    // ostringstream not working correctly here, hence snprintf
-    snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
-    return std::string (ipaddr);
-}
-
 
-std::string getPortTBServer(OCClientResponse * clientResponse)
-{
-    if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
-    uint16_t p = 0;
-    if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
-    std::ostringstream ss;
-    ss << p;
-    return ss.str();
-}
-
-std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
-{
-    return "/a/led";
-}
-
-void parseClientResponse(OCClientResponse * clientResponse)
-{
-    coapServerIP = getIPAddrTBServer(clientResponse);
-    coapServerPort = getPortTBServer(clientResponse);
-    coapServerResource = getQueryStrForGetPut(clientResponse);
-}
index 6752bed..c9d0dc9 100644 (file)
@@ -47,6 +47,19 @@ typedef enum {
 } CLIENT_TEST;
 
 //-----------------------------------------------------------------------------
+//ResourceNode
+//-----------------------------------------------------------------------------
+struct ResourceNode
+{
+    const char * sid;
+    const char * uri;
+    const char * ip;
+    const char * port;
+    OCConnectivityType connType;
+    ResourceNode * next;
+};
+
+//-----------------------------------------------------------------------------
 // Function prototype
 //-----------------------------------------------------------------------------
 
@@ -54,18 +67,48 @@ typedef enum {
 const char *getResult(OCStackResult result);
 
 /* Get the IP address of the server */
-std::string getIPAddrTBServer(OCClientResponse * clientResponse);
+const char * getIPAddr(const OCClientResponse * clientResponse);
 
 /* Get the port number the server is listening on */
-std::string getPortTBServer(OCClientResponse * clientResponse);
+const char * getPort(const OCClientResponse * clientResponse);
+
+/* Performs GET/PUT/POST query on most recently discovered resource*/
+void queryResource();
+
+/* Parses JSON payload received in the clientResponse to extract sid and resource uri information.
+ * Populates uri_c array with uris of the resources discovered and assigns sid_c with the server
+ * id received in the clientResponse.
+ */
+int parseJSON(unsigned  const char * resJSONPayload, char ** sid_c,
+              char *** uri_c, int * totalRes);
+
+/*
+ * Collect unique resource(sid:uri), regardless of the transport it arrives on.
+ */
+void collectUniqueResource(const OCClientResponse * clientResponse);
+
+/*
+ * Insert the newly discovered unique resource(sid:uri) in the front of the resourceList
+ *
+ */
+
+int insertResource(const char * sid, char const * uri,
+        const OCClientResponse * clientResponse);
 
-/* Returns the query string for GET and PUT operations */
-std::string getQueryStrForGetPut(OCClientResponse * clientResponse);
+/*
+ * Returns most recently discovered resource
+ */
+const ResourceNode * getResource();
+
+/*
+ * Frees the ResourceList
+ */
+void freeResourceList();
 
 /* 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();
@@ -82,6 +125,19 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
         OCMethod method, OCQualityOfService qos,
         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions);
 
+/*
+ * SIGINT handler: set gQuitFlag to 1 for graceful termination
+ */
+void handleSigInt(int signum);
+
+/*
+ * Printing helper functions
+ */
+static void PrintUsage();
+void printResourceList();
+
+
+
 //-----------------------------------------------------------------------------
 // Callback functions
 //-----------------------------------------------------------------------------
@@ -98,5 +154,6 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
 
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse);
-
+void StripNewLineChar(char* str);
 #endif
+
index e8db15a..f609aea 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
@@ -38,7 +38,8 @@ std::string getQueryStrForGetPut(unsigned  const char * responsePayload);
 #define MAX_LENGTH_IPv4_ADDR 16
 #endif
 
-typedef enum {
+typedef enum
+{
     TEST_INVALID = 0,
     TEST_GET_DEFAULT,
     TEST_GET_BATCH,
@@ -56,25 +57,30 @@ unsigned static int TEST = TEST_INVALID;
 
 typedef struct
 {
-    unsigned char text[30];
+    char text[30];
     CLIENT_TEST test;
 } testToTextMap;
 
 testToTextMap queryInterface[] = {
         {"invalid", TEST_INVALID},
-        {"?if=oc.mi.def", TEST_GET_DEFAULT},
-        {"?if=oc.mi.b", TEST_GET_BATCH},
-        {"?if=oc.mi.ll", TEST_GET_LINK_LIST},
-        {"?if=oc.mi.def", TEST_UNKNOWN_RESOURCE_GET_DEFAULT},
-        {"?if=oc.mi.b", TEST_UNKNOWN_RESOURCE_GET_BATCH},
-        {"?if=oc.mi.ll", TEST_UNKNOWN_RESOURCE_GET_LINK_LIST},
-        {"?if=oc.mi.def", TEST_PUT_DEFAULT},
-        {"?if=oc.mi.b", TEST_PUT_BATCH},
-        {"?if=oc.mi.ll", TEST_PUT_LINK_LIST},
+        {"?if=oic.if.baseline", TEST_GET_DEFAULT},
+        {"?if=oic.if.b", TEST_GET_BATCH},
+        {"?if=oic.if.ll", TEST_GET_LINK_LIST},
+        {"?if=oic.if.baseline", TEST_UNKNOWN_RESOURCE_GET_DEFAULT},
+        {"?if=oic.if.b", TEST_UNKNOWN_RESOURCE_GET_BATCH},
+        {"?if=oic.if.ll", TEST_UNKNOWN_RESOURCE_GET_LINK_LIST},
+        {"?if=oic.if.baseline", TEST_PUT_DEFAULT},
+        {"?if=oic.if.b", TEST_PUT_BATCH},
+        {"?if=oic.if.ll", TEST_PUT_LINK_LIST},
 };
 
 static std::string putPayload = "{\"state\":\"off\",\"power\":\"0\"}";
 
+//The following variable determines the interface protocol (IPv4, IPv6, etc)
+//to be used for sending unicast messages. Default set to IPv4.
+static OCConnectivityType OC_CONNTYPE = OC_IPV4;
+static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
+
 // The handle for the observe registration
 OCDoHandle gObserveDoHandle;
 // After this crosses a threshold client deregisters for further observations
@@ -82,8 +88,10 @@ int gNumObserveNotifies = 1;
 
 int gQuitFlag = 0;
 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
-void handleSigInt(int signum) {
-    if (signum == SIGINT) {
+void handleSigInt(int signum)
+{
+    if (signum == SIGINT)
+    {
         gQuitFlag = 1;
     }
 }
@@ -98,34 +106,37 @@ int InitDiscovery();
 
 void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlientcoll -t <Test Case>");
-    OC_LOG(INFO, TAG, "Test Case 1 : Discover Resources && Initiate GET Request on an"\
+    OC_LOG(INFO, TAG, "Usage : occlientcoll -t <Test Case> -c <CA connectivity Type>");
+    OC_LOG(INFO, TAG, "-c <0|1> : IPv4/IPv6 (IPv6 not currently supported)");
+    OC_LOG(INFO, TAG, "Test Case 1 : Discover Resources && Initiate GET Request on an "\
             "available resource using default interface.");
-    OC_LOG(INFO, TAG, "Test Case 2 : Discover Resources && Initiate GET Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 2 : Discover Resources && Initiate GET Request on an "\
                  "available resource using batch interface.");
-    OC_LOG(INFO, TAG, "Test Case 3 : Discover Resources && Initiate GET Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 3 : Discover Resources && Initiate GET Request on an "\
                  "available resource using link list interface.");
-    OC_LOG(INFO, TAG, "Test Case 4 : Discover Resources && Initiate GET & PUT Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 4 : Discover Resources && Initiate GET & PUT Request on an "\
                  "available resource using default interface.");
-    OC_LOG(INFO, TAG, "Test Case 5 : Discover Resources && Initiate GET & PUT Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 5 : Discover Resources && Initiate GET & PUT Request on an "\
                  "available resource using batch interface.");
-    OC_LOG(INFO, TAG, "Test Case 6 : Discover Resources && Initiate GET & PUT Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 6 : Discover Resources && Initiate GET & PUT Request on an "\
                  "available resource using link list interface.");
-    OC_LOG(INFO, TAG, "Test Case 7 : Discover Resources && Initiate GET Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 7 : Discover Resources && Initiate GET Request on an "\
                  "unavailable resource using default interface.");
-    OC_LOG(INFO, TAG, "Test Case 8 : Discover Resources && Initiate GET Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 8 : Discover Resources && Initiate GET Request on an "\
                  "unavailable resource using batch interface.");
-    OC_LOG(INFO, TAG, "Test Case 9 : Discover Resources && Initiate GET Request on an"\
+    OC_LOG(INFO, TAG, "Test Case 9 : Discover Resources && Initiate GET Request on an "\
                  "unavailable resource using link list interface.");
 }
 
-OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
+OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+{
     if(clientResponse == NULL)
     {
         OC_LOG(INFO, TAG, "The clientResponse is NULL");
         return   OC_STACK_DELETE_TRANSACTION;
     }
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE) {
+    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    {
         OC_LOG_V(INFO, TAG, "Callback Context for PUT query recvd successfully");
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Discovered", clientResponse->resJSONPayload);
     }
@@ -133,22 +144,28 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     return OC_STACK_KEEP_TRANSACTION;
 }
 
-OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
+OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+{
     OC_LOG_V(INFO, TAG, "StackResult: %s",
             getResult(clientResponse->result));
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE) {
+    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    {
         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        if(clientResponse->sequenceNumber == 0) {
+        if(clientResponse->sequenceNumber == 0)
+        {
             OC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully");
             OC_LOG_V(INFO, TAG, "Fnd' Rsrc': %s", clientResponse->resJSONPayload);
         }
-        else {
-            OC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d", gNumObserveNotifies);
+        else
+        {
+            OC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d",
+                    gNumObserveNotifies);
             OC_LOG_V(INFO, TAG, "Fnd' Rsrc': %s", clientResponse->resJSONPayload);
             gNumObserveNotifies++;
             if (gNumObserveNotifies == 3)
             {
-                if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
+                if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
+                {
                     OC_LOG(ERROR, TAG, "Observe cancel error");
                 }
             }
@@ -164,7 +181,8 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
 
 // This is a function called back when a device is discovered
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
-        OCClientResponse * clientResponse) {
+        OCClientResponse * clientResponse)
+{
     uint8_t remoteIpAddr[4];
     uint16_t remotePortNu;
 
@@ -173,7 +191,8 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
     OC_LOG_V(INFO, TAG, "StackResult: %s",
             getResult(clientResponse->result));
 
-    if (ctx == (void*) DEFAULT_CONTEXT_VALUE) {
+    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
+    {
         OC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
     }
 
@@ -203,14 +222,14 @@ int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
     std::ostringstream getQuery;
-    getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << "/SomeUnknownResource";
+    getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
+            getPortTBServer(clientResponse) << "/SomeUnknownResource";
     cbData.cb = getReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_LOW_QOS,
+    ret = OCDoResource(NULL, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_CONNTYPE, OC_LOW_QOS,
             &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
@@ -226,14 +245,16 @@ int InitObserveRequest(OCClientResponse * clientResponse)
     OCCallbackData cbData;
     OCDoHandle handle;
     std::ostringstream obsReg;
-    obsReg << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << getQueryStrForGetPut(clientResponse->resJSONPayload);
+    obsReg << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
+            getPortTBServer(clientResponse) <<
+            getQueryStrForGetPut(clientResponse->resJSONPayload);
     cbData.cb = getReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
     OC_LOG_V(INFO, TAG, "OBSERVE payload from client = %s ", putPayload.c_str());
 
-    ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(), 0, 0, OC_LOW_QOS,
-            &cbData, NULL, 0);
+    ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(), 0, 0, OC_CONNTYPE,
+            OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -250,18 +271,18 @@ int InitPutRequest(OCClientResponse * clientResponse)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
     //* Make a PUT query*/
     std::ostringstream getQuery;
-    getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) <<
-    "/a/room" << queryInterface[TEST].text;
+    getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
+            getPortTBServer(clientResponse) <<
+            "/a/room" << queryInterface[TEST].text;
     cbData.cb = putReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
     OC_LOG_V(INFO, TAG, "PUT payload from client = %s ", putPayload.c_str());
 
-    ret = OCDoResource(&handle, OC_REST_PUT, getQuery.str().c_str(), 0, putPayload.c_str(),
-            OC_LOW_QOS, &cbData, NULL, 0);
+    ret = OCDoResource(NULL, OC_REST_PUT, getQuery.str().c_str(), 0, putPayload.c_str(),
+                        OC_CONNTYPE, OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -274,7 +295,6 @@ int InitGetRequest(OCClientResponse * clientResponse)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
 
     uint8_t remoteIpAddr[4];
     uint16_t remotePortNu;
@@ -285,15 +305,17 @@ int InitGetRequest(OCClientResponse * clientResponse)
 
     //* Make a GET query*/
     std::ostringstream getQuery;
-    getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) <<
-    "/a/room" << queryInterface[TEST].text;
+    getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
+            getPortTBServer(clientResponse) <<
+            "/a/room" << queryInterface[TEST].text;
 
     std::cout << "Get Query: " << getQuery.str() << std::endl;
 
     cbData.cb = getReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    ret = OCDoResource(&handle, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_LOW_QOS,
+    ret = OCDoResource(NULL, OC_REST_GET,
+            getQuery.str().c_str(), 0, 0, OC_CONNTYPE, OC_LOW_QOS,
             &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
@@ -306,16 +328,16 @@ int InitDiscovery()
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
     /* Start a discovery query*/
     char szQueryUri[64] = { 0 };
 
-    strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+    strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
 
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS,
+    ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_ALL,
+                        OC_LOW_QOS,
             &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
@@ -324,41 +346,36 @@ int InitDiscovery()
     return ret;
 }
 
-int main(int argc, char* argv[]) {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+int main(int argc, char* argv[])
+{
     int opt;
 
-    while ((opt = getopt(argc, argv, "t:")) != -1)
+    while ((opt = getopt(argc, argv, "t:c:")) != -1)
     {
-        switch(opt)
+        switch (opt)
         {
-        case 't':
-            TEST = atoi(optarg);
-            break;
-        default:
-            PrintUsage();
-            return -1;
+            case 't':
+                TEST = atoi(optarg);
+                break;
+            case 'c':
+                // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
+                // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
+                OC_CONNTYPE = OC_IPV4;
+                break;
+            default:
+                PrintUsage();
+                return -1;
         }
     }
-    if(TEST <= TEST_INVALID || TEST >= MAX_TESTS){
+    if (TEST <= TEST_INVALID || TEST >= MAX_TESTS)
+    {
         PrintUsage();
         return -1;
     }
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                               sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
-        paddr = addr;
-    }
-
     /* Initialize OCStack*/
-    if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
@@ -368,50 +385,73 @@ int main(int argc, char* argv[]) {
     // Break from loop with Ctrl+C
     OC_LOG(INFO, TAG, "Entering occlient main loop...");
     signal(SIGINT, handleSigInt);
-    while (!gQuitFlag) {
+    while (!gQuitFlag)
+    {
 
-        if (OCProcess() != OC_STACK_OK) {
+        if (OCProcess() != OC_STACK_OK)
+        {
             OC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
 
         sleep(2);
-    }
-    OC_LOG(INFO, TAG, "Exiting occlient main loop...");
+    } OC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
-    if (OCStop() != OC_STACK_OK) {
+    if (OCStop() != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, "OCStack stop error");
     }
 
     return 0;
 }
 
-std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
-    if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
+std::string getIPAddrTBServer(OCClientResponse * clientResponse)
+{
+    if (!clientResponse)
+    {
+        return "";
+    }
+    if (!clientResponse->addr)
+    {
+        return "";
+    }
     uint8_t a, b, c, d = 0;
-    if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
+    if (0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
+    {
+        return "";
+    }
 
     char ipaddr[16] = {'\0'};
-    snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
-    //printf("IP address string of the TB server = %s\n", *out_ipaddr);
+    // ostringstream not working correctly here, hence snprintf
+    snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
     return std::string (ipaddr);
 }
 
-
-std::string getPortTBServer(OCClientResponse * clientResponse){
-    if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
+std::string getPortTBServer(OCClientResponse * clientResponse)
+{
+    if (!clientResponse)
+    {
+        return "";
+    }
+    if (!clientResponse->addr)
+    {
+        return "";
+    }
     uint16_t p = 0;
-    if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
+    if (0 != OCDevAddrToPort(clientResponse->addr, &p))
+    {
+        return "";
+    }
     std::ostringstream ss;
     ss << p;
     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 689b015..5fc29c6 100644 (file)
 
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
-static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
+static const char * UNICAST_DISCOVERY_QUERY = "coap://%s:6298/oc/core";
 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
 static std::string coapServerIP = "255.255.255.255";
 static std::string coapServerPort = "5683";
 static std::string coapServerResource = "/a/led";
 
+//The following variable determines the interface protocol (IPv4, IPv6, etc)
+//to be used for sending unicast messages. Default set to IPv4.
+static OCConnectivityType OC_CONNTYPE = OC_IPV4;
+static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
+static int IPV4_ADDR_SIZE = 16;
+void StripNewLineChar(char* str);
+
 int gQuitFlag = 0;
 
 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
@@ -50,7 +57,8 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
+    OC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
+    OC_LOG(INFO, TAG, "-c <0|1> : IPv4/IPv6 (IPv6 not currently supported)");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request");
@@ -63,15 +71,13 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
 
     cbData.cb = cb;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, method, query.str().c_str(), 0,
-            NULL,
-            qos, &cbData, options, numOptions);
+    ret = OCDoResource(NULL, method, query.str().c_str(), 0,
+            NULL, OC_CONNTYPE, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -110,8 +116,9 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
             {
                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                         ((OCHeaderOption)rcvdOptions[i]).optionID );
+
                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
-                        ((OCHeaderOption)rcvdOptions[i]).optionLength);
+                    MAX_HEADER_OPTION_DATA_LENGTH);
             }
         }
     }
@@ -177,21 +184,41 @@ int InitDiscovery()
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
     /* Start a discovery query*/
     char szQueryUri[64] = { 0 };
     if (UNICAST_DISCOVERY)
     {
-        strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
+        char ipv4addr[IPV4_ADDR_SIZE];
+        printf("Enter IPv4 address of the Server hosting resource (Ex: 192.168.0.15)\n");
+        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        {
+            //Strip newline char from ipv4addr
+            StripNewLineChar(ipv4addr);
+            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
+        }
+        else
+        {
+            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            return OC_STACK_INVALID_PARAM;
+        }
     }
     else
     {
-        strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+        strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
     }
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
+    if(UNICAST_DISCOVERY)
+    {
+        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
+                OC_LOW_QOS, &cbData, NULL, 0);
+    }
+    else
+    {
+        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_ALL,
+                OC_LOW_QOS, &cbData, NULL, 0);
+    }
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -201,13 +228,9 @@ int InitDiscovery()
 
 int main(int argc, char* argv[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
     int opt;
 
-    while ((opt = getopt(argc, argv, "u:t:")) != -1)
+    while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
     {
         switch(opt)
         {
@@ -217,6 +240,11 @@ int main(int argc, char* argv[])
             case 't':
                 TEST_CASE = atoi(optarg);
                 break;
+            case 'c':
+                // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
+                // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
+                OC_CONNTYPE = OC_IPV4;
+                break;
             default:
                 PrintUsage();
                 return -1;
@@ -230,18 +258,8 @@ int main(int argc, char* argv[])
         return -1;
     }
 
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
-        paddr = addr;
-    }
-
     /* Initialize OCStack*/
-    if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
@@ -285,7 +303,6 @@ std::string getIPAddrTBServer(OCClientResponse * clientResponse)
     return std::string (ipaddr);
 }
 
-
 std::string getPortTBServer(OCClientResponse * clientResponse)
 {
     if(!clientResponse) return "";
@@ -308,3 +325,4 @@ void parseClientResponse(OCClientResponse * clientResponse)
     coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }
+
index 60713d7..8b6bcc4 100644 (file)
@@ -39,7 +39,8 @@
 /**
  * List of methods that can be inititated from the client
  */
-typedef enum {
+typedef enum
+{
     TEST_DISCOVER_REQ = 1,
     TEST_NON_CON_OP,
     TEST_CON_OP,
@@ -93,3 +94,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse);
 
 #endif
+
index 6131cd0..d263b09 100644 (file)
@@ -56,9 +56,12 @@ static int stopPresenceCount = 10;
 #endif
 
 //TODO: Follow the pattern used in constructJsonResponse() when the payload is decided.
-const char responsePayloadDeleteOk[] = "{App determines payload: Delete Resource operation succeeded.}";
-const char responsePayloadDeleteNotOK[] = "{App determines payload: Delete Resource operation failed.}";
-const char responsePayloadResourceDoesNotExist[] = "{App determines payload: The resource does not exist.}";
+const char responsePayloadDeleteOk[] =
+        "{App determines payload: Delete Resource operation succeeded.}";
+const char responsePayloadDeleteNotOK[] =
+        "{App determines payload: Delete Resource operation failed.}";
+const char responsePayloadResourceDoesNotExist[] =
+        "{App determines payload: The resource does not exist.}";
 const char responsePayloadDeleteResourceNotSupported[] =
         "{App determines payload: The request is received for a non-support resource.}";
 
@@ -70,16 +73,23 @@ const char *deviceName = "myDeviceName";
 const char *deviceUUID = "myDeviceUUID";
 const char *firmwareVersion = "myFirmwareVersion";
 const char *hostName = "myHostName";
-const char *manufacturerName = "myManufacturerNa";
+const char *manufacturerName = "myName";
+const char *operatingSystemVersion = "myOS";
+const char *hardwareVersion = "myHardwareVersion";
+const char* platformID = "myPlatformID";
 const char *manufacturerUrl = "myManufacturerUrl";
 const char *modelNumber = "myModelNumber";
 const char *platformVersion = "myPlatformVersion";
 const char *supportUrl = "mySupportUrl";
 const char *version = "myVersion";
+const char *systemTime = "2015-05-15T11.04";
 
-OCDeviceInfo deviceInfo;
+// Entity handler should check for resourceTypeName and ResourceInterface in order to GET
+// the existence of a known resource
+const char *resourceTypeName = "core.light";
+const char *resourceInterface = OC_RSRVD_INTERFACE_DEFAULT;
 
-static uint16_t OC_WELL_KNOWN_PORT = 5683;
+OCPlatformInfo platformInfo;
 
 //This function takes the request as an input and returns the response
 //in JSON format.
@@ -103,16 +113,38 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
 
     if(OC_REST_PUT == ehRequest->method)
     {
-        cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
-        currLightResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring,
-                "on") ? true:false);
-        currLightResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
+        // Get cJSON pointer to query
+        cJSON *putJson = cJSON_Parse(ehRequest->reqJSONPayload);
+
+        if(!putJson)
+        {
+            OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
+            return NULL;
+        }
+
+        // Get root of JSON payload, then the 1st resource.
+        cJSON* carrier = cJSON_GetObjectItem(putJson, "oc");
+        carrier = cJSON_GetArrayItem(carrier, 0);
+        carrier = cJSON_GetObjectItem(carrier, "rep");
+
+        cJSON* prop = cJSON_GetObjectItem(carrier,"power");
+        if (prop)
+        {
+            currLightResource->power =prop->valueint;
+        }
+
+        prop = cJSON_GetObjectItem(carrier,"state");
+        if (prop)
+        {
+            currLightResource->state = prop->valueint;
+        }
+
         cJSON_Delete(putJson);
     }
 
     cJSON_AddStringToObject(json,"href",gResourceUri);
     cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
-    cJSON_AddStringToObject(format, "state", (char *) (currLightResource->state ? "on":"off"));
+    cJSON_AddBoolToObject(format, "state", currLightResource->state);
     cJSON_AddNumberToObject(format, "power", currLightResource->power);
 
     jsonResponse = cJSON_Print(json);
@@ -121,33 +153,96 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     return jsonResponse;
 }
 
-OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+/*
+ * Very simple example of query parsing.
+ * The query may have multiple filters separated by '&'.
+ * It is upto the entity handler to parse the query for the individual filters,
+ * VALIDATE them and respond as it sees fit.
+
+ * This function only returns false if the query is exactly "power<X" and
+ * current power is greater than X. If X cannot be parsed for an int,
+ * true is returned.
+ */
+bool checkIfQueryForPowerPassed(char * query)
+{
+    if (query && strncmp(query, "power<", strlen("power<")) == 0)
+    {
+        char * pointerToOperator = strstr(query, "<");
+
+        if (pointerToOperator)
+        {
+            int powerRequested = atoi(pointerToOperator + 1);
+            if (Light.power > powerRequested)
+            {
+                OC_LOG_V(INFO, TAG, "Current power: %d. Requested: <%d", Light.power
+                            , powerRequested);
+                return false;
+            }
+        }
+    }
+    return true;
+}
+
+/*
+ * Application should validate and process these as desired.
+ */
+OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest)
+{
+    OC_LOG_V(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query);
+    OC_LOG(INFO, TAG, PCF("Not processing query"));
+    return OC_EH_OK;
+}
+
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
+        char *payload, uint16_t maxPayloadSize)
 {
     OCEntityHandlerResult ehResult;
-    char *getResp = constructJsonResponse(ehRequest);
+    bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query);
 
-    if (maxPayloadSize > strlen ((char *)getResp))
+    // Empty payload if the query has no match.
+    if (queryPassed)
     {
-        strncpy(payload, getResp, strlen((char *)getResp));
-        ehResult = OC_EH_OK;
+        char *getResp = constructJsonResponse(ehRequest);
+        if(!getResp)
+        {
+            OC_LOG(ERROR, TAG, "constructJsonResponse failed");
+            return OC_EH_ERROR;
+        }
+
+        if (maxPayloadSize > strlen (getResp))
+        {
+            strncpy(payload, getResp, strlen(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;
+        ehResult = OC_EH_OK;
     }
 
-    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(!putResp)
+    {
+        OC_LOG(ERROR, TAG, "Failed to construct Json response");
+        return OC_EH_ERROR;
+    }
+
     if (maxPayloadSize > strlen ((char *)putResp))
     {
         strncpy(payload, putResp, strlen((char *)putResp));
@@ -165,7 +260,8 @@ OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char
     return ehResult;
 }
 
-OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
+        OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
 {
     OCEntityHandlerResult ehResult = OC_EH_OK;
     char *respPLPost_light = NULL;
@@ -253,7 +349,8 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, OCE
     return ehResult;
 }
 
-OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest,
+        char *payload, uint16_t maxPayloadSize)
 {
     if(ehRequest == NULL)
     {
@@ -333,7 +430,8 @@ OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, c
     return ehResult;
 }
 
-OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
+        char *payload, uint16_t maxPayloadSize)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__);
 
@@ -347,11 +445,11 @@ OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+        OC_LOG_V (ERROR, TAG, "Response buffer: %d bytes is too small",
                 maxPayloadSize);
     }
 
-    return OC_EH_RESOURCE_DELETED;
+    return OC_EH_RESOURCE_NOT_FOUND;
 }
 
 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest)
@@ -408,22 +506,22 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
         OC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
-
     // Initialize certain response fields
     response.numSendVendorSpecificHeaderOptions = 0;
-    memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+    memset(response.sendVendorSpecificHeaderOptions, 0,
+            sizeof response.sendVendorSpecificHeaderOptions);
     memset(response.resourceUri, 0, sizeof response.resourceUri);
 
-    if (flag & OC_INIT_FLAG)
-    {
-        OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
-    }
+
     if (flag & OC_REQUEST_FLAG)
     {
         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
-        if (entityHandlerRequest->resource == NULL) {
+
+        if (entityHandlerRequest->resource == NULL)
+        {
             OC_LOG (INFO, TAG, "Received request from client to a non-existing resource");
-            ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest, payload, sizeof(payload) - 1);
+            ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest,
+                           payload, sizeof(payload) - 1);
         }
         else if (OC_REST_GET == entityHandlerRequest->method)
         {
@@ -443,18 +541,17 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
         else
         {
             OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
-                    entityHandlerRequest->method);
+                      entityHandlerRequest->method);
             ehResult = OC_EH_ERROR;
         }
-
-        // If the result isn't an error or forbidden, send response
+               // If the result isn't an error or forbidden, send response
         if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
         {
             // Format the response.  Note this requires some info about the request
             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;
@@ -511,16 +608,14 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     // Initialize certain response fields
     response.numSendVendorSpecificHeaderOptions = 0;
-    memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+    memset(response.sendVendorSpecificHeaderOptions,
+            0, sizeof response.sendVendorSpecificHeaderOptions);
     memset(response.resourceUri, 0, sizeof response.resourceUri);
 
-    if (flag & OC_INIT_FLAG)
-    {
-        OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
-    }
     if (flag & OC_REQUEST_FLAG)
     {
         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+
         if (OC_REST_GET == entityHandlerRequest->method)
         {
             OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
@@ -544,9 +639,9 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
         else
         {
             OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
-                    entityHandlerRequest->method);
+                      entityHandlerRequest->method);
+            ehResult = OC_EH_ERROR;
         }
-
         // If the result isn't an error or forbidden, send response
         if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))
         {
@@ -554,7 +649,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;
@@ -565,15 +660,17 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
             {
                 OC_LOG (INFO, TAG, "Received vendor specific options");
                 uint8_t i = 0;
-                OCHeaderOption * rcvdOptions = entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
+                OCHeaderOption * rcvdOptions =
+                        entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
                 for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
                 {
                     if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
                     {
                         OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                                 ((OCHeaderOption)rcvdOptions[i]).optionID );
+
                         OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
-                                ((OCHeaderOption)rcvdOptions[i]).optionLength);
+                            MAX_HEADER_OPTION_DATA_LENGTH);
                     }
                 }
                 OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;
@@ -618,8 +715,10 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 }
 
 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
-void handleSigInt(int signum) {
-    if (signum == SIGINT) {
+void handleSigInt(int signum)
+{
+    if (signum == SIGINT)
+    {
         gQuitFlag = 1;
     }
 }
@@ -635,7 +734,7 @@ void *ChangeLightRepresentation (void *param)
 
     while (!gQuitFlag)
     {
-        sleep(10);
+        sleep(3);
         Light.power += 5;
         if (gLightUnderObservation)
         {
@@ -657,12 +756,12 @@ void *ChangeLightRepresentation (void *param)
                 cJSON *format;
                 cJSON_AddStringToObject(json,"href",gResourceUri);
                 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
-                cJSON_AddStringToObject(format, "state", (char *) (Light.state ? "on":"off"));
+                cJSON_AddBoolToObject(format, "state", Light.state);
                 cJSON_AddNumberToObject(format, "power", Light.power);
                 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)
@@ -684,7 +783,7 @@ void *ChangeLightRepresentation (void *param)
 #ifdef WITH_PRESENCE
         if(stopPresenceCount > 0)
         {
-            OC_LOG_V(INFO, TAG, "================ presence count %d", stopPresenceCount);
+            OC_LOG_V(INFO, TAG, "================  Counting down to stop presence %d", stopPresenceCount);
         }
         if(!stopPresenceCount--)
         {
@@ -696,6 +795,7 @@ void *ChangeLightRepresentation (void *param)
     return NULL;
 }
 
+#ifdef WITH_PRESENCE
 void *presenceNotificationGenerator(void *param)
 {
     sleep(5);
@@ -717,7 +817,7 @@ void *presenceNotificationGenerator(void *param)
             sleep(1);
             res = OCCreateResource(&presenceNotificationHandles[i],
                     presenceNotificationResources.at(i).c_str(),
-                    "oc.mi.def",
+                    OC_RSRVD_INTERFACE_DEFAULT,
                     presenceNotificationUris.at(i).c_str(),
                     OCNOPEntityHandlerCb,
                     OC_DISCOVERABLE|OC_OBSERVABLE);
@@ -729,6 +829,8 @@ void *presenceNotificationGenerator(void *param)
                     getResult(res));
             break;
         }
+        OC_LOG_V(INFO, TAG, PCF("Created %s for presence notification"),
+                                presenceNotificationUris[i].c_str());
     }
     sleep(5);
     for(int i=0; i<numPresenceResources; i++)
@@ -743,139 +845,13 @@ void *presenceNotificationGenerator(void *param)
                     "resource %s.", presenceNotificationResources.at(i).c_str());
             break;
         }
+        OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
+                                presenceNotificationUris[i].c_str());
     }
     return NULL;
 }
-
-static void PrintUsage()
-{
-    OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
-    OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
-    OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
-}
-
-int main(int argc, char* argv[])
-{
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = OC_WELL_KNOWN_PORT;
-    uint8_t ifname[] = "eth0";
-    pthread_t threadId;
-    pthread_t threadId_presence;
-    int opt;
-
-    while ((opt = getopt(argc, argv, "o:")) != -1)
-    {
-        switch(opt)
-        {
-            case 'o':
-                gObserveNotifyType = atoi(optarg);
-                break;
-            default:
-                PrintUsage();
-                return -1;
-        }
-    }
-
-    if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
-    {
-        PrintUsage();
-        return -1;
-    }
-
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-        paddr = addr;
-    }
-
-    if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack init error");
-        return 0;
-    }
-#ifdef WITH_PRESENCE
-    if (OCStartPresence(0) != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
-        return 0;
-    }
 #endif
 
-    OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
-
-    OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
-            deviceUUID, firmwareVersion, hostName, manufacturerName,
-            manufacturerUrl, modelNumber, platformVersion, supportUrl, version);
-
-    if (deviceResult != OC_STACK_OK)
-    {
-        OC_LOG(INFO, TAG, "Device Registration failed!");
-        exit (EXIT_FAILURE);
-    }
-
-    deviceResult = OCSetDeviceInfo(deviceInfo);
-
-    if (deviceResult != OC_STACK_OK)
-    {
-        OC_LOG(INFO, TAG, "Device Registration failed!");
-        exit (EXIT_FAILURE);
-    }
-
-    /*
-     * Declare and create the example resource: Light
-     */
-    createLightResource(gResourceUri, &Light);
-
-    // Initialize observations data structure for the resource
-    for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
-    {
-        interestedObservers[i].valid = false;
-    }
-
-    /*
-     * Create a thread for changing the representation of the Light
-     */
-    pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
-
-    /*
-     * Create a thread for generating changes that cause presence notifications
-     * to be sent to clients
-     */
-    pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
-
-    // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
-    DeleteDeviceInfo();
-    signal(SIGINT, handleSigInt);
-    while (!gQuitFlag) {
-        if (OCProcess() != OC_STACK_OK) {
-            OC_LOG(ERROR, TAG, "OCStack process error");
-            return 0;
-        }
-
-        sleep(2);
-    }
-
-    /*
-     * Cancel the Light thread and wait for it to terminate
-     */
-    pthread_cancel(threadId);
-    pthread_join(threadId, NULL);
-    pthread_cancel(threadId_presence);
-    pthread_join(threadId_presence, NULL);
-
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
-
-    if (OCStop() != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, "OCStack process error");
-    }
-
-    return 0;
-}
-
 int createLightResource (char *uri, LightResource *lightResource)
 {
     if (!uri)
@@ -897,20 +873,19 @@ int createLightResource (char *uri, LightResource *lightResource)
     return 0;
 }
 
-void DeleteDeviceInfo()
+void DeletePlatformInfo()
 {
-    free(deviceInfo.contentType);
-    free(deviceInfo.dateOfManufacture);
-    free(deviceInfo.deviceName);
-    free(deviceInfo.deviceUUID);
-    free(deviceInfo.firmwareVersion);
-    free(deviceInfo.hostName);
-    free(deviceInfo.manufacturerName);
-    free(deviceInfo.manufacturerUrl);
-    free(deviceInfo.modelNumber);
-    free(deviceInfo.platformVersion);
-    free(deviceInfo.supportUrl);
-    free(deviceInfo.version);
+    free (platformInfo.platformID);
+    free (platformInfo.manufacturerName);
+    free (platformInfo.manufacturerUrl);
+    free (platformInfo.modelNumber);
+    free (platformInfo.dateOfManufacture);
+    free (platformInfo.platformVersion);
+    free (platformInfo.operatingSystemVersion);
+    free (platformInfo.hardwareVersion);
+    free (platformInfo.firmwareVersion);
+    free (platformInfo.supportUrl);
+    free (platformInfo.systemTime);
 }
 
 bool DuplicateString(char** targetString, const char* sourceString)
@@ -923,7 +898,7 @@ bool DuplicateString(char** targetString, const char* sourceString)
     {
         *targetString = (char *) malloc(strlen(sourceString) + 1);
 
-        if(targetString)
+        if(*targetString)
         {
             strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
             return true;
@@ -932,11 +907,10 @@ bool DuplicateString(char** targetString, const char* sourceString)
     return false;
 }
 
-OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture,
-        const char *deviceName, const char *deviceUUID, const char *firmwareVersion,
-        const char *hostName, const char *manufacturerName, const char *manufacturerUrl,
-        const char *modelNumber, const char *platformVersion, const char *supportUrl,
-        const char *version)
+OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerName,
+    const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture,
+    const char *platformVersion, const char* operatingSystemVersion, const char* hardwareVersion,
+    const char *firmwareVersion, const char* supportUrl, const char* systemTime)
 {
 
     bool success = true;
@@ -951,62 +925,57 @@ OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufactu
         return OC_STACK_INVALID_PARAM;
     }
 
-    if(!DuplicateString(&deviceInfo.contentType, contentType))
+    if(!DuplicateString(&platformInfo.platformID, platformID))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture))
+    if(!DuplicateString(&platformInfo.manufacturerName, manufacturerName))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.deviceName, deviceName))
+    if(!DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID))
+    if(!DuplicateString(&platformInfo.modelNumber, modelNumber))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion))
+    if(!DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.hostName, hostName))
+    if(!DuplicateString(&platformInfo.platformVersion, platformVersion))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName))
+    if(!DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl))
+    if(!DuplicateString(&platformInfo.hardwareVersion, hardwareVersion))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.modelNumber, modelNumber))
+    if(!DuplicateString(&platformInfo.firmwareVersion, firmwareVersion))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.platformVersion, platformVersion))
+    if(!DuplicateString(&platformInfo.supportUrl, supportUrl))
     {
         success = false;
     }
 
-    if(!DuplicateString(&deviceInfo.supportUrl, supportUrl))
-    {
-        success = false;
-    }
-
-    if(!DuplicateString(&deviceInfo.version, version))
+    if(!DuplicateString(&platformInfo.systemTime, systemTime))
     {
         success = false;
     }
@@ -1016,6 +985,132 @@ OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufactu
         return OC_STACK_OK;
     }
 
-    DeleteDeviceInfo();
+    DeletePlatformInfo();
     return OC_STACK_ERROR;
 }
+
+static void PrintUsage()
+{
+    OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
+    OC_LOG(INFO, TAG, "-o 0 : Notify all observers");
+    OC_LOG(INFO, TAG, "-o 1 : Notify list of observers");
+}
+
+int main(int argc, char* argv[])
+{
+    pthread_t threadId;
+    pthread_t threadId_presence;
+    int opt;
+
+    while ((opt = getopt(argc, argv, "o:")) != -1)
+    {
+        switch(opt)
+        {
+            case 'o':
+                gObserveNotifyType = atoi(optarg);
+                break;
+            default:
+                PrintUsage();
+                return -1;
+        }
+    }
+
+    if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1))
+    {
+        PrintUsage();
+        return -1;
+    }
+
+    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, "OCStack init error");
+        return 0;
+    }
+#ifdef WITH_PRESENCE
+    if (OCStartPresence(0) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, "OCStack presence/discovery error");
+        return 0;
+    }
+#endif
+
+    OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
+
+    OCStackResult platformRegistrationResult =
+        SetPlatformInfo(platformID, manufacturerName, manufacturerUrl, modelNumber,
+            dateOfManufacture, platformVersion,  operatingSystemVersion,  hardwareVersion,
+            firmwareVersion,  supportUrl, systemTime);
+
+    if (platformRegistrationResult != OC_STACK_OK)
+    {
+        OC_LOG(INFO, TAG, "Platform info setting failed locally!");
+        exit (EXIT_FAILURE);
+    }
+
+    platformRegistrationResult = OCSetPlatformInfo(platformInfo);
+
+    if (platformRegistrationResult != OC_STACK_OK)
+    {
+        OC_LOG(INFO, TAG, "Platform Registration failed!");
+        exit (EXIT_FAILURE);
+    }
+
+    /*
+     * Declare and create the example resource: Light
+     */
+    createLightResource(gResourceUri, &Light);
+
+    // Initialize observations data structure for the resource
+    for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
+    {
+        interestedObservers[i].valid = false;
+    }
+
+    /*
+     * Create a thread for changing the representation of the Light
+     */
+    pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
+
+    /*
+     * Create a thread for generating changes that cause presence notifications
+     * to be sent to clients
+     */
+
+    #ifdef WITH_PRESENCE
+    pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
+    #endif
+
+    // Break from loop with Ctrl-C
+    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    DeletePlatformInfo();
+    signal(SIGINT, handleSigInt);
+    while (!gQuitFlag)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OC_LOG(ERROR, TAG, "OCStack process error");
+            return 0;
+        }
+
+        sleep(2);
+    }
+
+    /*
+     * Cancel the Light thread and wait for it to terminate
+     */
+    pthread_cancel(threadId);
+    pthread_join(threadId, NULL);
+    pthread_cancel(threadId_presence);
+    pthread_join(threadId_presence, NULL);
+
+    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, "OCStack process error");
+    }
+
+    return 0;
+}
\ No newline at end of file
index 81a9507..e6d123e 100644 (file)
 //-----------------------------------------------------------------------------
 
 /* Structure to represent a Light resource */
-typedef struct LIGHTRESOURCE{
+typedef struct LIGHTRESOURCE
+{
     OCResourceHandle handle;
     bool state;
     int power;
 } LightResource;
 
 /* Structure to represent the observers */
-typedef struct {
+typedef struct
+{
     OCObservationId observationId;
-    bool            valid;
+    bool valid;
     OCResourceHandle resourceHandle;
 } Observers;
 
@@ -68,6 +70,11 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest);
  */
 void *ChangeLightRepresentation (void *param);
 
+/* This method check the validity of resourceTypeName and resource interfaces
+ * Entity Handler has to parse the query string in order to process it
+ */
+OCEntityHandlerResult ValidateQueryParams (OCEntityHandlerRequest *entityHandlerRequest);
+
 /* Following methods process the PUT, GET, POST, Delete,
  * & Observe requests */
 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
@@ -115,3 +122,4 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
 
 #endif
+
index bcd741c..43b913f 100644 (file)
@@ -39,18 +39,23 @@ static LEDResource LED;
 // This variable determines instance number of the LED resource.
 // Used by POST method to create a new instance of LED resource.
 static int gCurrLedInstance = 0;
-#define SAMPLE_MAX_NUM_POST_INSTANCE  2
+#define SAMPLE_MAX_NUM_POST_INSTANCE 2
 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
 
 char *gResourceUri= (char *)"/a/led";
 
-static uint16_t OC_WELL_KNOWN_PORT = 5683;
-
 //This function takes the request as an input and returns the response
 //in JSON format.
 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;
@@ -69,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;
@@ -76,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);
 
@@ -85,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;
@@ -156,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))
@@ -223,11 +272,6 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
     OCEntityHandlerResponse response;
     char payload[MAX_RESPONSE_LENGTH] = {0};
 
-    if (flag & OC_INIT_FLAG)
-    {
-        OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
-        ehResult = OC_EH_OK;
-    }
     if (flag & OC_REQUEST_FLAG)
     {
         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
@@ -260,7 +304,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);
@@ -291,22 +335,8 @@ void handleSigInt(int signum)
 
 int main(int argc, char* argv[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = OC_WELL_KNOWN_PORT;
-    uint8_t ifname[] = "eth0";
-
     OC_LOG(DEBUG, TAG, "OCServer is starting...");
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-        paddr = addr;
-    }
-
-    if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
@@ -353,7 +383,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
     ledResource->power= resourcePower;
     OCStackResult res = OCCreateResource(&(ledResource->handle),
             "core.led",
-            "oc.mi.def",
+            OC_RSRVD_INTERFACE_DEFAULT,
             uri,
             OCEntityHandlerCb,
             OC_DISCOVERABLE|OC_OBSERVABLE);
@@ -361,3 +391,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 75124bb..aff73b6 100644 (file)
@@ -53,10 +53,12 @@ const char rspPutRoomCollection[] = "{\"href\":\"/a/room\"}";
 const char rspFailureRoom[] = "{\"href\":\"/a/room\",\"rep\":{\"error\":\"ROOM_OP_FAIL\"}}";
 
 // TODO : hard coded for now, change after Sprint4
-const char rspGetLightDefault[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"false\",\"color\":\"0\"}}";
+const char rspGetLightDefault[] =
+        "{\"href\":\"/a/light\",\"rep\":{\"state\":\"false\",\"color\":\"0\"}}";
 const char rspGetLightCollection[] = "{\"href\":\"/a/light\"}";
 // TODO : Needs to be changed to retrieve current status of light and return that in response
-const char rspPutLightDefault[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"true\",\"color\":\"0\"}}";
+const char rspPutLightDefault[] =
+        "{\"href\":\"/a/light\",\"rep\":{\"state\":\"true\",\"color\":\"0\"}}";
 const char rspPutLightCollection[] = "{\"href\":\"/a/light\"}";
 const char rspFailureLight[] = "{\"href\":\"/a/light\",\"rep\":{\"error\":\"LIGHT_OP_FAIL\"}}";
 
@@ -69,7 +71,8 @@ const char rspPutFanDefault[] = "{\"href\":\"/a/fan\",\"rep\":{\"state\":\"false
 const char rspPutFanCollection[] = "{\"href\":\"/a/fan\"}";
 const char rspFailureFan[] = "{\"href\":\"/a/fan\",\"rep\":{\"error\":\"FAN_OP_FAIL\"}}";
 
-typedef enum {
+typedef enum
+{
     TEST_INVALID = 0,
     TEST_DEFAULT_COLL_EH,
     TEST_APP_COLL_EH,
@@ -79,8 +82,10 @@ typedef enum {
 void PrintUsage()
 {
     OC_LOG(INFO, TAG, "Usage : ocservercoll -t <Test Case>");
-    OC_LOG(INFO, TAG, "Test Case 1 : Create room resource with default collection entity handler.");
-    OC_LOG(INFO, TAG, "Test Case 2 : Create room resource with application collection entity handler.");
+    OC_LOG(INFO, TAG,
+            "Test Case 1 : Create room resource with default collection entity handler.");
+    OC_LOG(INFO, TAG,
+            "Test Case 2 : Create room resource with application collection entity handler.");
 }
 
 unsigned static int TEST = TEST_INVALID;
@@ -118,10 +123,8 @@ PrintReceivedMsgInfo(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehReques
 {
     const char* typeOfMessage;
 
-    switch (flag) {
-        case OC_INIT_FLAG:
-            typeOfMessage = "OC_INIT_FLAG";
-            break;
+    switch (flag)
+    {
         case OC_REQUEST_FLAG:
             typeOfMessage = "OC_REQUEST_FLAG";
             break;
@@ -133,8 +136,8 @@ PrintReceivedMsgInfo(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehReques
     }
 
     OC_LOG_V(INFO, TAG, "Receiving message type: %s, method %s",
-             typeOfMessage,
-             (ehRequest->method == OC_REST_GET) ? "OC_REST_GET" : "OC_REST_PUT" );
+            typeOfMessage,
+            (ehRequest->method == OC_REST_GET) ? "OC_REST_GET" : "OC_REST_PUT" );
 }
 
 OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
@@ -153,46 +156,55 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
 
         if(OC_REST_GET == ehRequest->method)
         {
-            if(query.find("oc.mi.def") != std::string::npos)
+            if(query.find(OC_RSRVD_INTERFACE_DEFAULT) != std::string::npos)
             {
-                ret = HandleCallback(ehRequest, rspGetRoomDefault, rspFailureRoom, payload, sizeof(payload));
+                ret = HandleCallback(ehRequest,
+                        rspGetRoomDefault, rspFailureRoom, payload, sizeof(payload));
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspGetLightCollection, rspFailureLight, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspGetLightCollection, rspFailureLight, payload, sizeof(payload));
                 }
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
                 }
             }
-            else if(query.find("oc.mi.ll") != std::string::npos)
+            else if(query.find(OC_RSRVD_INTERFACE_LL) != std::string::npos)
             {
-                ret = HandleCallback(ehRequest, rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload));
+                ret = HandleCallback(ehRequest,
+                        rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload));
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspGetLightCollection, rspFailureLight, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspGetLightCollection, rspFailureLight, payload, sizeof(payload));
                 }
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspGetFanCollection, rspFailureFan, payload, sizeof(payload));
                 }
             }
-            else if(query.find("oc.mi.b") != std::string::npos)
+            else if(query.find(OC_RSRVD_INTERFACE_BATCH) != std::string::npos)
             {
-                ret = HandleCallback(ehRequest, rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload));
+                ret = HandleCallback(ehRequest,
+                        rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload));
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspGetLightDefault, rspFailureLight, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspGetLightDefault, rspFailureLight, payload, sizeof(payload));
                 }
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspGetFanDefault, rspFailureFan, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspGetFanDefault, rspFailureFan, payload, sizeof(payload));
                 }
             }
             if (ret == OC_EH_OK)
@@ -201,10 +213,11 @@ 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, 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;
@@ -218,45 +231,52 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
         }
         else if(OC_REST_PUT == ehRequest->method)
         {
-            if(query.find("oc.mi.def") != std::string::npos)
+            if(query.find(OC_RSRVD_INTERFACE_DEFAULT) != std::string::npos)
             {
                 if(ret != OC_EH_ERROR)
                 {
-                    ret = HandleCallback(ehRequest, rspPutRoomDefault, rspFailureRoom, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspPutRoomDefault, rspFailureRoom, payload, sizeof(payload));
                 }
             }
-            if(query.find("oc.mi.ll") != std::string::npos)
+            if(query.find(OC_RSRVD_INTERFACE_LL) != std::string::npos)
             {
                 if(ret != OC_EH_ERROR)
                 {
-                    ret = HandleCallback(ehRequest, rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
                 }
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspPutLightCollection, rspFailureLight, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspPutLightCollection, rspFailureLight, payload, sizeof(payload));
                 }
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspPutFanCollection, rspFailureFan, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspPutFanCollection, rspFailureFan, payload, sizeof(payload));
                 }
             }
-            if(query.find("oc.mi.b") != std::string::npos)
+            if(query.find(OC_RSRVD_INTERFACE_BATCH ) != std::string::npos)
             {
                 if(ret != OC_EH_ERROR)
                 {
-                    ret = HandleCallback(ehRequest, rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload));
                 }
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
                 }
                 if(ret != OC_EH_ERROR)
                 {
                     ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload));
-                    ret = HandleCallback(ehRequest, rspPutFanDefault, rspFailureFan, payload, sizeof(payload));
+                    ret = HandleCallback(ehRequest,
+                            rspPutFanDefault, rspFailureFan, payload, sizeof(payload));
                 }
             }
             if (ret == OC_EH_OK)
@@ -265,10 +285,11 @@ 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, 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;
@@ -294,7 +315,8 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
     return ret;
 }
 
-OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest)
+OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ret = OC_EH_OK;
     OCEntityHandlerResponse response;
@@ -307,11 +329,13 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag, OCEntityH
     {
         if(OC_REST_GET == ehRequest->method)
         {
-            ret = HandleCallback(ehRequest, rspGetLightDefault, rspFailureLight, payload, sizeof(payload));
+            ret = HandleCallback(ehRequest,
+                    rspGetLightDefault, rspFailureLight, payload, sizeof(payload));
         }
         else if(OC_REST_PUT == ehRequest->method)
         {
-            ret = HandleCallback(ehRequest, rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
+            ret = HandleCallback(ehRequest,
+                    rspPutLightDefault, rspFailureLight, payload, sizeof(payload));
         }
         else
         {
@@ -326,10 +350,11 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag, OCEntityH
             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, 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;
@@ -350,7 +375,8 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag, OCEntityH
     return ret;
 }
 
-OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest)
+OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ret = OC_EH_OK;
     OCEntityHandlerResponse response;
@@ -363,11 +389,13 @@ OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag, OCEntityHan
     {
         if(OC_REST_GET == ehRequest->method)
         {
-            ret = HandleCallback(ehRequest, rspGetFanDefault, rspFailureFan, payload, sizeof(payload));
+            ret = HandleCallback(ehRequest, rspGetFanDefault,
+                    rspFailureFan, payload, sizeof(payload));
         }
         else if(OC_REST_PUT == ehRequest->method)
         {
-            ret = HandleCallback(ehRequest, rspPutFanDefault, rspFailureFan, payload, sizeof(payload));
+            ret = HandleCallback(ehRequest, rspPutFanDefault,
+                    rspFailureFan, payload, sizeof(payload));
         }
         else
         {
@@ -382,10 +410,11 @@ OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag, OCEntityHan
             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, 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;
@@ -441,10 +470,6 @@ void *ChangeLightRepresentation (void *param)
 
 int main(int argc, char* argv[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = 0;
-    uint8_t ifname[] = "eth0";
     pthread_t threadId;
     int opt;
 
@@ -460,22 +485,16 @@ int main(int argc, char* argv[])
             return -1;
         }
     }
-    if(TEST <= TEST_INVALID || TEST >= MAX_TESTS){
+    if(TEST <= TEST_INVALID || TEST >= MAX_TESTS)
+    {
         PrintUsage();
         return -1;
     }
 
     OC_LOG(DEBUG, TAG, "OCServer is starting...");
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if (OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                               sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-        paddr = addr;
-    }
 
-    if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) {
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
@@ -525,7 +544,7 @@ void createResources()
     OCResourceHandle fan;
     OCStackResult res = OCCreateResource(&fan,
             "core.fan",
-            "oc.mi.def",
+            OC_RSRVD_INTERFACE_DEFAULT,
             "/a/fan",
             OCEntityHandlerFanCb,
             OC_DISCOVERABLE|OC_OBSERVABLE);
@@ -534,7 +553,7 @@ void createResources()
     OCResourceHandle light;
     res = OCCreateResource(&light,
             "core.light",
-            "oc.mi.def",
+            OC_RSRVD_INTERFACE_DEFAULT,
             "/a/light",
             OCEntityHandlerLightCb,
             OC_DISCOVERABLE|OC_OBSERVABLE);
@@ -546,7 +565,7 @@ void createResources()
     {
         res = OCCreateResource(&room,
                 "core.room",
-                "oc.mi.b",
+                OC_RSRVD_INTERFACE_BATCH,
                 "/a/room",
                 OCEntityHandlerRoomCb,
                 OC_DISCOVERABLE);
@@ -555,15 +574,15 @@ void createResources()
     {
         res = OCCreateResource(&room,
                 "core.room",
-                "oc.mi.b",
+                OC_RSRVD_INTERFACE_BATCH,
                 "/a/room",
                 NULL,
                 OC_DISCOVERABLE);
     }
 
     OC_LOG_V(INFO, TAG, "Created room resource with result: %s", getResult(res));
-    OCBindResourceInterfaceToResource(room, "oc.mi.ll");
-    OCBindResourceInterfaceToResource(room, "oc.mi.def");
+    OCBindResourceInterfaceToResource(room, OC_RSRVD_INTERFACE_LL);
+    OCBindResourceInterfaceToResource(room, OC_RSRVD_INTERFACE_DEFAULT);
 
     res = OCBindResource(room, light);
     OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
@@ -571,3 +590,4 @@ void createResources()
     res = OCBindResource(room, fan);
     OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
 }
+
index e1184e1..eb015e4 100644 (file)
@@ -38,22 +38,25 @@ static std::list<OCEntityHandlerRequest *> gRequestList;
 static constexpr unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
 
 static LEDResource LED;
-// This variable determines instance number of the LED resource.
-// Used by POST method to create a new instance of LED resource.
-static unsigned int gCurrLedInstance = 0;
+
 static constexpr unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
 
 //char *gResourceUri= const_cast<char *>("/a/led");
 char *gResourceUri= (char *)"/a/led";
 
-static constexpr uint16_t OC_WELL_KNOWN_PORT = 5683;
-
 //This function takes the request as an input and returns the response
 //in JSON format.
 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;
@@ -76,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;
@@ -83,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);
 
@@ -100,6 +120,12 @@ void ProcessGetRequest (OCEntityHandlerRequest *ehRequest)
 {
     OC_LOG(INFO, TAG, "Entering ProcessGetRequest");
     char *getResp = constructJsonResponse(ehRequest);
+
+    if(!getResp)
+    {
+        OC_LOG(ERROR, TAG, "Failed to constructJsonResponse");
+        return;
+    }
     OC_LOG(INFO, TAG, "After constructJsonResponse");
     OCEntityHandlerResponse response;
 
@@ -107,10 +133,11 @@ 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, 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;
@@ -127,22 +154,26 @@ void ProcessGetRequest (OCEntityHandlerRequest *ehRequest)
 OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
 {
     OC_LOG(INFO, TAG, "Copying received request for slow response");
-    OCEntityHandlerRequest *request = (OCEntityHandlerRequest *)OCMalloc(sizeof(OCEntityHandlerRequest));
+    OCEntityHandlerRequest *request =
+            (OCEntityHandlerRequest *)OCMalloc(sizeof(OCEntityHandlerRequest));
     if (request)
     {
         // Do shallow copy
         memcpy(request, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
         // Do deep copy of query
-        request->query = (unsigned char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
+        request->query =
+                (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(strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1);
+            request->reqJSONPayload = (char * )OCMalloc(
+                            strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1);
             if (request->reqJSONPayload)
             {
-                strcpy((char *)request->reqJSONPayload, (const char *)entityHandlerRequest->reqJSONPayload);
+                strcpy((char *)request->reqJSONPayload,
+                        (const char *)entityHandlerRequest->reqJSONPayload);
 
                 // Ignore vendor specific header options for example
                 request->numRcvdVendorSpecificHeaderOptions = 0;
@@ -181,11 +212,6 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
     OCEntityHandlerRequest *request = NULL;
 
     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
-    if (flag & OC_INIT_FLAG)
-    {
-        OC_LOG(INFO, TAG, "Flag includes OC_INIT_FLAG");
-        result = OC_EH_OK;
-    }
     if (flag & OC_REQUEST_FLAG)
     {
         OC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
@@ -273,23 +299,9 @@ void AlarmHandler(int sig)
 
 int main(int argc, char* argv[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = OC_WELL_KNOWN_PORT;
-    uint8_t ifname[] = "eth0";
-
-
     OC_LOG(DEBUG, TAG, "OCServer is starting...");
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-        paddr = addr;
-    }
 
-    if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
@@ -352,7 +364,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
     ledResource->power= resourcePower;
     OCStackResult res = OCCreateResource(&(ledResource->handle),
             "core.led",
-            "oc.mi.def",
+            OC_RSRVD_INTERFACE_DEFAULT,
             uri,
             OCEntityHandlerCb,
             OC_DISCOVERABLE|OC_OBSERVABLE);
@@ -360,3 +372,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index bf37c34..0c94421 100644 (file)
@@ -33,7 +33,8 @@
 //-----------------------------------------------------------------------------
 
 /* Structure to represent a LED resource */
-typedef struct LEDRESOURCE{
+typedef struct LEDRESOURCE
+{
     OCResourceHandle handle;
     bool state;
     int power;
@@ -69,3 +70,4 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest);
 
 #endif
+
diff --git a/resource/csdk/stack/samples/linux/secure/SConscript b/resource/csdk/stack/samples/linux/secure/SConscript
new file mode 100644 (file)
index 0000000..71e298f
--- /dev/null
@@ -0,0 +1,74 @@
+#******************************************************************
+#
+# 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')
+
+samples_env = env.Clone()
+######################################################################
+# Build flags
+######################################################################
+samples_env.PrependUnique(CPPPATH = [
+               '../../../../logger/include',
+               '../../../../stack/include',
+               '../../../../security/include',
+               '../../../../../../extlibs/cjson',
+               '../../../../../oc_logger/include'
+               ])
+
+target_os = env.get('TARGET_OS')
+if target_os not in ['windows', 'winrt']:
+       samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+
+       # Note: 'pthread' is in libc for android.
+       if target_os != 'android':
+               samples_env.AppendUnique(LIBS = ['-lpthread'])
+
+samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+samples_env.PrependUnique(LIBS = ['octbstack', 'm', 'oc_logger', 'connectivity_abstraction', 'coap'])
+if env.get('SECURED') == '1':
+    samples_env.AppendUnique(LIBS = ['tinydtls'])
+
+samples_env.Append(LINKFLAGS = ['-Wl,--no-as-needed'])
+
+if target_os == 'android':
+       samples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+       samples_env.AppendUnique(LIBS = ['gnustl_shared'])
+       samples_env.AppendUnique(CPPDEFINES = ['_GLIBCXX_USE_C99=1', '_GLIBCXX_HAVE_WCSTOF=1'])
+
+       if not env.get('RELEASE'):
+               samples_env.AppendUnique(LIBS = ['log'])
+
+if target_os in ['darwin', 'ios']:
+       samples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+
+samples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+ocserverbasicops = samples_env.Program('ocserverbasicops', ['common.cpp', 'ocserverbasicops.cpp'])
+occlientbasicops = samples_env.Program('occlientbasicops', ['common.cpp', 'occlientbasicops.cpp'])
+gen_sec_bin = samples_env.Program('gen_sec_bin', ['gen_sec_bin.cpp'])
+
+
+Alias("samples", [ocserverbasicops, occlientbasicops])
+
+env.AppendTarget('samples')
+
index 55fb32a..7c04494 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include "common.h"
 
-#include <ocstack.h>
-#include <ocsecurity.h>
-#include <logger.h>
+#include "ocsecurity.h"
+#include "logger.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
@@ -46,7 +46,7 @@ OCStackResult SetCredentials(const char* filename) {
                 if (fread(data, 1, st.st_size, fp) == (size_t)st.st_size)
                 {
                     // Provide credentials to OC Stack
-                    ret = OCSetDtlsPskCredentials((OCDtlsPskCredsBlob *)data,
+                    ret = OCSecSetConfigData((OCSecConfigData *)data,
                             st.st_size);
                 }
                 else
@@ -104,8 +104,6 @@ const char *getResult(OCStackResult result) {
     case OC_STACK_NO_OBSERVERS:
         return "OC_STACK_NO_OBSERVERS";
     #ifdef WITH_PRESENCE
-    case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
-        return "OC_STACK_VIRTUAL_DO_NOT_HANDLE";
     case OC_STACK_PRESENCE_STOPPED:
         return "OC_STACK_PRESENCE_STOPPED";
     #endif
@@ -115,3 +113,17 @@ const char *getResult(OCStackResult result) {
         return "UNKNOWN";
     }
 }
+
+void StripNewLineChar(char* str) {
+    int i = 0;
+    if (str)
+    {
+        while( str[i])
+        {
+            if (str[i] == '\n')
+                str[i] = '\0';
+            i++;
+        }
+    }
+}
+
index 408ba59..ac73c1d 100644 (file)
 #ifndef OCSAMPLE_COMMON_H_
 #define OCSAMPLE_COMMON_H_
 
+#include "ocstack.h"
+
 /* Get the result in string format. */
 const char *getResult(OCStackResult result);
 
 /* Read the credentials from persistent storage and provide to OC stack. */
 OCStackResult SetCredentials(const char* filename);
 
+/* Removes the new line character from a NULL terminated C string. */
+void StripNewLineChar(char* str);
+
 #endif //OCSAMPLE_COMMON_H_
 
+
index 2a259ac..c30aada 100644 (file)
 #include <time.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/stat.h>
 
 #define TAG "gen_sec_bin"
 
-void printStruct(const char * device, OCDtlsPskCredsBlob* s)
+//scratch buffer
+const int WORK_BUF_LEN = 512;
+
+const char SERVER_CRED_FILE[] = "server_cred.bin";
+const char CLIENT_CRED_FILE[] = "client_cred.bin";
+
+static void printStruct(const char * device, OCSecConfigData* s)
 {
-    OC_LOG(INFO, TAG, device);
-    OC_LOG_V(INFO, TAG, "Version - %d", s->blobVer);
-    OC_LOG(INFO, TAG, "My Identity :");
-    OC_LOG_BUFFER(INFO, TAG, s->identity, DTLS_PSK_ID_LEN);
-
-    OC_LOG_V(INFO, TAG, "Number of trusted Peers  - %d", s->num);
-    OC_LOG(INFO, TAG, "Peer Identity :");
-    OC_LOG_BUFFER(INFO, TAG, s->creds[0].id, DTLS_PSK_ID_LEN);
-    OC_LOG(INFO, TAG, "Peer Psk :");
-    OC_LOG_BUFFER(INFO, TAG, s->creds[0].psk, DTLS_PSK_PSK_LEN);
+    if (device && s)
+    {
+        OC_LOG(INFO, TAG, device);
+        OC_LOG_V(INFO, TAG, "Version - %d", s->version);
+        OC_LOG_V(INFO, TAG, "Number of blobs - %d", s->numBlob);
+
+        OCSecBlob* osb = (OCSecBlob*)(s->blob);
+        OC_LOG_V(INFO, TAG, "Blob Type - %d", osb->type);
+        OC_LOG_V(INFO, TAG, "Blob Data Length - %d", osb->len);
+
+        OCDtlsPskCredsBlob* odpcb = (OCDtlsPskCredsBlob*)(osb->val);
+        OC_LOG(INFO, TAG, "My Identity :");
+        OC_LOG_BUFFER(INFO, TAG, odpcb->identity, DTLS_PSK_ID_LEN);
+
+        OC_LOG_V(INFO, TAG, "Number of trusted Peers  - %d", odpcb->num);
+        OC_LOG(INFO, TAG, "Peer Identity :");
+        OC_LOG_BUFFER(INFO, TAG, odpcb->creds[0].id, DTLS_PSK_ID_LEN);
+        OC_LOG(INFO, TAG, "Peer Psk :");
+        OC_LOG_BUFFER(INFO, TAG, odpcb->creds[0].psk, DTLS_PSK_PSK_LEN);
+    }
 }
 
 
-int main()
+static int SizeOfOCConfigData (OCSecConfigData *oscd)
 {
-    OCDtlsPskCredsBlob * s = NULL;
-    OCDtlsPskCredsBlob * c = NULL;
-    FILE* fps, *fpc;
+    int len = 0;
+    if(oscd)
+    {
+        int i = 0;
+        OCSecBlob * osb;
+        len = len + sizeof(OCSecConfigData) - sizeof(uint8_t);
 
-    int i;
+        //go to first blob
+        osb = (OCSecBlob*)(oscd->blob);
+        for( i =0; i < oscd->numBlob; i++)
+        {
+            len += (sizeof(OCSecBlob) - sizeof(uint8_t) + osb->len);
+            osb = config_data_next_blob(osb);
+        }
+    }
+    return len;
+}
+
+int main()
+{
+    unsigned char buf_s[WORK_BUF_LEN];
+    unsigned char buf_c[WORK_BUF_LEN];
 
     srand(time(NULL));
 
-    s = (OCDtlsPskCredsBlob*) malloc(sizeof(OCDtlsPskCredsBlob));
-    c = (OCDtlsPskCredsBlob*) malloc(sizeof(OCDtlsPskCredsBlob));
+    OCSecConfigData * oscd_s = (OCSecConfigData*)buf_s;
+    OCSecConfigData * oscd_c = (OCSecConfigData*)buf_c;
+    oscd_s->version = oscd_c->version = OCSecConfigVer_CurrentVersion;
+
+    //Only storing 1 blob of type 'OC_BLOB_TYPE_PSK'
+    oscd_s->numBlob = oscd_c->numBlob = 1;
 
-    memset(s, 0, sizeof(OCDtlsPskCredsBlob));
-    memset(c, 0, sizeof(OCDtlsPskCredsBlob));
+    OCSecBlob * osb_s = (OCSecBlob*)oscd_s->blob;
+    OCSecBlob * osb_c = (OCSecBlob*)oscd_c->blob;
+    osb_s->type = osb_c->type = OC_BLOB_TYPE_PSK;
+    //length of this blob will be the length to contain PSK credentials
+    // for '1' peer device
+    osb_s->len = osb_c->len = sizeof(OCDtlsPskCredsBlob);
 
-    s->blobVer = DtlsPskCredsBlobVer_CurrentVersion;
-    c->blobVer = DtlsPskCredsBlobVer_CurrentVersion;
+    OCDtlsPskCredsBlob * odpcb_s = (OCDtlsPskCredsBlob*)(osb_s->val);
+    OCDtlsPskCredsBlob * odpcb_c = (OCDtlsPskCredsBlob*)(osb_c->val);
 
-    s->num = c->num = 1;
+    odpcb_s->num = odpcb_c->num = 1;
 
-    for(i = 0; i < DTLS_PSK_ID_LEN; i++)
+    for(int i = 0; i < DTLS_PSK_ID_LEN; i++)
     {
-        c->creds[0].id[i] = s->identity[i] = rand() % (2^8);
+        odpcb_c->creds[0].id[i] = odpcb_s->identity[i] = rand() % (2^8);
 
-        s->creds[0].id[i] = c->identity[i] = rand() % (2^8);
+        odpcb_s->creds[0].id[i] = odpcb_c->identity[i] = rand() % (2^8);
 
-        c->creds[0].psk[i] = s->creds[0].psk[i] = rand() % (2^8);
+        odpcb_c->creds[0].psk[i] = odpcb_s->creds[0].psk[i] = rand() % (2^8);
     }
 
     // Print Credentials
-    printStruct("Server", s);
-    printStruct("Client", c);
+    printStruct("Server", oscd_s);
+    printStruct("Client", oscd_c);
 
     // Write to files
+    FILE* fps, *fpc;
     if ((fps = (FILE*) fopen("server_cred.bin", "wb")) != NULL)
     {
-        fwrite(s, sizeof(OCDtlsPskCredsBlob), 1, fps);
+        fwrite(oscd_s, SizeOfOCConfigData(oscd_s), 1, fps);
         fclose(fps);
     }
 
 
     if ((fpc = (FILE*) fopen("client_cred.bin", "wb")) != NULL)
     {
-        fwrite(c, sizeof(OCDtlsPskCredsBlob), 1, fpc);
+        fwrite(oscd_c, SizeOfOCConfigData(oscd_c), 1, fpc);
         fclose(fpc);
     }
 
-    memset(s, 0, sizeof(OCDtlsPskCredsBlob));
-    memset(c, 0, sizeof(OCDtlsPskCredsBlob));
+    struct stat st;
+    memset(buf_s, 0, sizeof(buf_s));
+    memset(buf_c, 0, sizeof(buf_c));
     // Read from files; print and verify manually
-    if ((fps = (FILE*) fopen("server_cred.bin", "rb")) != NULL)
+    if ((fps = (FILE*) fopen(SERVER_CRED_FILE, "rb")) != NULL)
     {
-        if (sizeof(OCDtlsPskCredsBlob) != fread(s, 1, sizeof(OCDtlsPskCredsBlob), fps))
+        stat(SERVER_CRED_FILE, &st);
+        if ((sizeof(buf_s) < (unsigned int)st.st_size) ||
+            (fread(buf_s, 1, st.st_size, fps) != (unsigned int)st.st_size))
         {
             OC_LOG(INFO, TAG, PCF("Reading from the file failed."));
         }
@@ -103,9 +149,11 @@ int main()
     }
 
 
-    if ((fpc = (FILE*) fopen("client_cred.bin", "rb")) != NULL)
+    if ((fpc = (FILE*) fopen(CLIENT_CRED_FILE, "rb")) != NULL)
     {
-        if (sizeof(OCDtlsPskCredsBlob) != fread(c, 1, sizeof(OCDtlsPskCredsBlob), fpc))
+        stat(CLIENT_CRED_FILE, &st);
+        if ((sizeof(buf_c) < (unsigned int)st.st_size) ||
+            (fread(buf_c, 1, st.st_size, fpc) != (unsigned int)st.st_size))
         {
             OC_LOG(INFO, TAG, PCF("Reading from the file failed."));
         }
@@ -114,10 +162,10 @@ int main()
 
     printf("\n\n");
     OC_LOG(INFO, TAG, PCF("Reading from file and printing again to verify manually"));
-    printStruct("Server", s);
-    printStruct("Client", c);
+    printStruct("Server", (OCSecConfigData*)buf_s);
+    printStruct("Client", (OCSecConfigData*)buf_c);
 
-    free(s);
-    free(c);
+    return 1;
 }
 
+
diff --git a/resource/csdk/stack/samples/linux/secure/makefile b/resource/csdk/stack/samples/linux/secure/makefile
deleted file mode 100644 (file)
index c77d733..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD   := release
-PLATFORM := linux
-CC      := g++
-OUT_DIR          := $(BUILD)
-OBJ_DIR          := $(OUT_DIR)/obj
-
-ifeq ($(ROOT_DIR), )
-ROOT_DIR       = ../../../..
-endif
-
-OUT_DIR        = .
-
-OCLOGGER_DIR   = $(ROOT_DIR)/logger
-OC_LOG_DIR = $(ROOT_DIR)/../oc_logger
-OCRANDOM_DIR   = $(ROOT_DIR)/ocrandom
-OCSOCKET_DIR   = $(ROOT_DIR)/ocsocket
-LCOAP_DIR      = $(ROOT_DIR)/libcoap-4.1.1
-OCCOAP_DIR     = $(ROOT_DIR)/occoap
-OCTBSTACK_DIR  = $(ROOT_DIR)/stack
-EXTLIBS_DIR    = $(ROOT_DIR)/../../extlibs
-CJSON_DIR      = $(EXTLIBS_DIR)/cjson
-
-CJSON_SRC      = $(CJSON_DIR)
-
-OCLOGGER_INC   = $(OCLOGGER_DIR)/include
-OC_LOG_INC     = $(OC_LOG_DIR)/include
-OCRANDOM_INC   = $(OCRANDOM_DIR)/include
-OCSOCKET_INC   = $(OCSOCKET_DIR)/include
-LCOAP_INC      = $(LCOAP_DIR)
-OCCOAP_INC     = $(OCCOAP_DIR)/include
-OCTBSTACK_INC  = $(OCTBSTACK_DIR)/include
-CJSON_INC      = $(CJSON_DIR)
-
-INC_DIRS       := -I$(OCLOGGER_INC)
-INC_DIRS       += -I$(OC_LOG_INC)
-INC_DIRS       += -I$(OCRANDOM_INC)
-INC_DIRS       += -I$(OCSOCKET_INC)
-INC_DIRS       += -I$(LCOAP_INC)
-INC_DIRS       += -I$(OCCOAP_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)
-INC_DIRS       += -I$(CJSON_INC)
-
-CC_FLAGS.debug   := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \
-                        -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG
-CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \
-                        -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG
-
-LDLIBS         += -loctbstack -lpthread
-CPPFLAGS       += $(CC_FLAGS.$(BUILD)) $(LDLIBS)
-
-CJSON_SOURCES          := $(CJSON_SRC)/cJSON.c
-
-SOURCES                := $(CJSON_SOURCES)
-SOURCES     += common.cpp ocserverbasicops.cpp occlientbasicops.cpp gen_sec_bin.cpp
-
-OBJECTS:= $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(SOURCES))
-
-PROGRAMS       += ocserverbasicops
-PROGRAMS       += occlientbasicops
-PROGRAMS       += gen_sec_bin
-
-all:   c_sdk prep_dirs $(OBJECTS) $(PROGRAMS)
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-       -mkdir -p $(OBJ_DIR)
-
-c_sdk:
-       cd $(ROOT_DIR) && $(MAKE) BUILD=$(BUILD) PLATFORM=$(PLATFORM)
-
-$(OBJ_DIR)/%.o: %.cpp
-       $(CC) -c $(CPPFLAGS) $< -o $@
-
-ocserverbasicops: $(OBJ_DIR)/ocserverbasicops.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-occlientbasicops: $(OBJ_DIR)/occlientbasicops.o $(OBJ_DIR)/common.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-gen_sec_bin: $(OBJ_DIR)/gen_sec_bin.o
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-.PHONY: clean
-
-clean: legacy_clean
-       -rm -rf release
-       -rm -rf debug
-       cd $(ROOT_DIR) && $(MAKE) clean
-       cd $(ROOT_DIR) && $(MAKE) deepclean
-
-legacy_clean:
-       rm -f *.o $(PROGRAMS)
index e4125d2..5f8d7b6 100644 (file)
 #define TAG "occlientbasicops"
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
-static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
+
+static int IPV4_ADDR_SIZE = 16;
+static char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oc/core";
+static char MULTICAST_DISCOVERY_QUERY[] = "/oc/core";
+
 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
 static std::string coapServerIP;
 static std::string coapServerPort;
 static std::string coapServerResource;
 static int coapSecureResource;
+static OCConnectivityType ocConnType;
+
 
 //File containing Client's Identity and the PSK credentials
 //of other devices which the client trusts
@@ -74,15 +80,14 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
 
     cbData.cb = cb;
     cbData.context = NULL;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, method, query.str().c_str(), 0,
+    ret = OCDoResource(NULL, method, query.str().c_str(), 0,
             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
-            qos, &cbData, options, numOptions);
+            ocConnType, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -153,18 +158,20 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
 
+        ocConnType = clientResponse->connType;
+
         if (parseClientResponse(clientResponse) != -1)
         {
             switch(TEST_CASE)
             {
                 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;
             }
@@ -175,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));
+        << ":" << coapServerPort  << coapServerResource;
+    return (InvokeOCDoResource(query, OC_REST_PUT,
+            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
 }
 
 int InitPostRequest(OCQualityOfService qos)
@@ -232,21 +240,45 @@ int InitDiscovery()
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
-    /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[MAX_URI_LENGTH] = { 0 };
+    OCConnectivityType discoveryReqConnType;
+
     if (UNICAST_DISCOVERY)
     {
-        strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
+        char ipv4addr[IPV4_ADDR_SIZE];
+        printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
+        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        {
+            //Strip newline char from ipv4addr
+            StripNewLineChar(ipv4addr);
+            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
+        }
+        else
+        {
+            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            return OC_STACK_INVALID_PARAM;
+        }
+        discoveryReqConnType = OC_IPV4;
     }
     else
     {
-        strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+        //Send discovery request on Wifi and Ethernet interface
+        discoveryReqConnType = OC_ALL;
+        strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
     }
+
     cbData.cb = discoveryReqCB;
     cbData.context = NULL;
     cbData.cd = NULL;
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
+
+    /* Start a discovery query*/
+    OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
+        (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
+        szQueryUri);
+
+    ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
+            discoveryReqConnType, OC_LOW_QOS,
+            &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -256,10 +288,6 @@ int InitDiscovery()
 
 int main(int argc, char* argv[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
     int opt;
     struct timespec timeout;
 
@@ -286,18 +314,8 @@ int main(int argc, char* argv[])
         return -1;
     }
 
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
-        paddr = addr;
-    }
-
     /* Initialize OCStack*/
-    if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
@@ -440,3 +458,4 @@ int parseClientResponse(OCClientResponse * clientResponse)
     }
     return 0;
 }
+
index 689d7e6..8dee2f2 100644 (file)
@@ -53,7 +53,7 @@ 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();
index b6d579c..440b667 100644 (file)
@@ -41,8 +41,6 @@ static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
 
 char *gResourceUri= (char *)"/a/led";
 
-static uint16_t OC_WELL_KNOWN_PORT = 5683;
-
 //File containing Server's Identity and the PSK credentials
 //of other devices which the server trusts
 //This can be generated using 'gen_sec_bin' application
@@ -70,7 +68,13 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
 
     if(OC_REST_PUT == ehRequest->method)
     {
-        cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
+        cJSON *putJson = cJSON_Parse(ehRequest->reqJSONPayload);
+        if(!putJson)
+        {
+            OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
+            return NULL;
+        }
+
         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
                 "on") ? true:false);
         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
@@ -93,20 +97,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;
 }
 
@@ -116,20 +127,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;
 }
 
@@ -227,13 +246,8 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerResponse response;
-    char payload[MAX_RESPONSE_LENGTH];
+    char payload[MAX_RESPONSE_LENGTH] = {0};
 
-    if (flag & OC_INIT_FLAG)
-    {
-        OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
-        ehResult = OC_EH_OK;
-    }
     if (flag & OC_REQUEST_FLAG)
     {
         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
@@ -258,6 +272,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
             {
                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
+                ehResult = OC_EH_ERROR;
             }
 
             if (ehResult == OC_EH_OK)
@@ -266,7 +281,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);
@@ -297,23 +312,11 @@ void handleSigInt(int signum)
 
 int main(int argc, char* argv[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = OC_WELL_KNOWN_PORT;
-    uint8_t ifname[] = "eth0";
     struct timespec timeout;
 
     OC_LOG(DEBUG, TAG, "OCServer is starting...");
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-        paddr = addr;
-    }
 
-    if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
@@ -371,7 +374,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
     ledResource->power= resourcePower;
     OCStackResult res = OCCreateResource(&(ledResource->handle),
             "core.led",
-            "oc.mi.def",
+            OC_RSRVD_INTERFACE_DEFAULT,
             uri,
             OCEntityHandlerCb,
             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
@@ -379,3 +382,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 9e0b232..c2b324f 100644 (file)
 
 
 #include "occlientcb.h"
-#include "occoap.h"
 #include "utlist.h"
 #include "logger.h"
 #include "ocmalloc.h"
 #include <string.h>
 
+#ifdef WITH_ARDUINO
+#include "Time.h"
+#else
+#include <sys/time.h>
+#endif
+#include "coap_time.h"
+
+#include "cacommon.h"
+#include "cainterface.h"
+
 /// Module Name
 #define TAG PCF("occlientcb")
 
 struct ClientCB *cbList = NULL;
-OCMulticastNode * mcPresenceNodes = NULL;
+static OCMulticastNode * mcPresenceNodes = NULL;
 
-OCStackResult AddClientCB(ClientCB** clientCB, OCCallbackData* cbData,
-        OCCoAPToken * token, OCDoHandle *handle, OCMethod method,
-        unsigned char * requestUri, unsigned char * resourceTypeName) {
+OCStackResult
+AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
+             CAToken_t token, uint8_t tokenLength,
+             OCDoHandle *handle, OCMethod method,
+             char * requestUri, char * resourceTypeName, OCConnectivityType conType, uint32_t ttl)
+{
+    if(!clientCB || !cbData || !handle || !requestUri || tokenLength > CA_MAX_TOKEN_LEN)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     ClientCB *cbNode = NULL;
 
     #ifdef WITH_PRESENCE
     if(method == OC_REST_PRESENCE)
     {   // Retrieve the presence callback structure for this specific requestUri.
-        cbNode = GetClientCB(NULL, NULL, requestUri);
+        cbNode = GetClientCB(NULL, 0, NULL, requestUri);
     }
     #endif // WITH_PRESENCE
 
@@ -58,7 +74,10 @@ OCStackResult AddClientCB(ClientCB** clientCB, OCCallbackData* cbData,
             cbNode->callBack = cbData->cb;
             cbNode->context = cbData->context;
             cbNode->deleteCallback = cbData->cd;
-            memcpy(&(cbNode->token), token, sizeof(OCCoAPToken));
+            //Note: token memory is allocated in the caller OCDoResource
+            //but freed in DeleteClientCB
+            cbNode->token = token;
+            cbNode->tokenLength = tokenLength;
             cbNode->handle = *handle;
             cbNode->method = method;
             cbNode->sequenceNumber = 0;
@@ -66,7 +85,19 @@ OCStackResult AddClientCB(ClientCB** clientCB, OCCallbackData* cbData,
             cbNode->presence = NULL;
             cbNode->filterResourceType = NULL;
             #endif // WITH_PRESENCE
+
+            if (method == OC_REST_PRESENCE ||
+                method == OC_REST_OBSERVE  ||
+                method == OC_REST_OBSERVE_ALL)
+            {
+                cbNode->TTL = 0;
+            }
+            else
+            {
+                cbNode->TTL = ttl;
+            }
             cbNode->requestUri = requestUri;
+            cbNode->conType = conType;
             LL_APPEND(cbList, cbNode);
             *clientCB = cbNode;
         }
@@ -76,16 +107,30 @@ OCStackResult AddClientCB(ClientCB** clientCB, OCCallbackData* cbData,
         // Ensure that the handle the SDK hands back up to the application layer for the
         // OCDoResource call matches the found ClientCB Node.
         *clientCB = cbNode;
-        OCFree(requestUri);
+
+        if (cbData->cd)
+        {
+            cbData->cd(cbData->context);
+        }
+
+        OCFree(token);
         OCFree(*handle);
+        OCFree(requestUri);
         *handle = cbNode->handle;
     }
 
     #ifdef WITH_PRESENCE
     if(method == OC_REST_PRESENCE && resourceTypeName)
-    {   // Amend the found or created node by adding a new resourceType to it.
-        return InsertResourceTypeFilter(cbNode, (const char *)resourceTypeName);
+    {
+        // Amend the found or created node by adding a new resourceType to it.
+        return InsertResourceTypeFilter(cbNode,(char *)resourceTypeName);
+    }
+    else
+    {
+        OCFree(resourceTypeName);
     }
+    #else
+    OCFree(resourceTypeName);
     #endif
 
     return OC_STACK_OK;
@@ -94,11 +139,14 @@ OCStackResult AddClientCB(ClientCB** clientCB, OCCallbackData* cbData,
         return OC_STACK_NO_MEMORY;
 }
 
-void DeleteClientCB(ClientCB * cbNode) {
-    if(cbNode) {
+void DeleteClientCB(ClientCB * cbNode)
+{
+    if(cbNode)
+    {
         LL_DELETE(cbList, cbNode);
         OC_LOG(INFO, TAG, PCF("deleting tokens"));
-        OC_LOG_BUFFER(INFO, TAG, cbNode->token.token, cbNode->token.tokenLength);
+        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)cbNode->token, cbNode->tokenLength);
+        CADestroyToken (cbNode->token);
         OCFree(cbNode->handle);
         OCFree(cbNode->requestUri);
         if(cbNode->deleteCallback)
@@ -107,7 +155,8 @@ void DeleteClientCB(ClientCB * cbNode) {
         }
 
         #ifdef WITH_PRESENCE
-        if(cbNode->presence) {
+        if(cbNode->presence)
+        {
             OCFree(cbNode->presence->timeOut);
             OCFree(cbNode->presence);
         }
@@ -129,38 +178,82 @@ void DeleteClientCB(ClientCB * cbNode) {
     }
 }
 
-ClientCB* GetClientCB(OCCoAPToken * token, OCDoHandle handle, unsigned char * requestUri) {
+/*
+ * This function checks if the node is past its time to live and
+ * deletes it if timed-out. Calling this function with a  presence or observe
+ * callback with ttl set to 0 will not delete anything as presence nodes have
+ * their own mechanisms for timeouts. A null argument will cause the function to
+ * silently return.
+ */
+static void CheckAndDeleteTimedOutCB(ClientCB* cbNode)
+{
+    if (!cbNode)
+    {
+        return;
+    }
+    if (cbNode->TTL == 0)
+    {
+        return;
+    }
+    coap_tick_t now;
+    coap_ticks(&now);
+
+    if (cbNode->TTL < now)
+    {
+        OC_LOG(INFO, TAG, PCF("Deleting timed-out callback"));
+        DeleteClientCB(cbNode);
+    }
+}
+
+ClientCB* GetClientCB(const CAToken_t token, uint8_t tokenLength,
+        OCDoHandle handle, const char * requestUri)
+{
+
     ClientCB* out = NULL;
-    if(token) {
-        LL_FOREACH(cbList, out) {
+
+    if(token && *token && tokenLength <= CA_MAX_TOKEN_LEN && tokenLength > 0)
+    {
+        LL_FOREACH(cbList, out)
+        {
             OC_LOG(INFO, TAG, PCF("comparing tokens"));
-            OC_LOG_BUFFER(INFO, TAG, token->token, token->tokenLength);
-            OC_LOG_BUFFER(INFO, TAG, out->token.token, out->token.tokenLength);
-            if((out->token.tokenLength == token->tokenLength) &&
-                (memcmp(out->token.token, token->token, token->tokenLength) == 0) ) {
+            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
+            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
+
+            if(memcmp(out->token, token, tokenLength) == 0)
+            {
                 return out;
             }
+            CheckAndDeleteTimedOutCB(out);
         }
     }
-    else if(handle) {
-        LL_FOREACH(cbList, out) {
-            if(out->handle == handle) {
+    else if(handle)
+    {
+        LL_FOREACH(cbList, out)
+        {
+            if(out->handle == handle)
+            {
                 return out;
             }
+            CheckAndDeleteTimedOutCB(out);
         }
     }
-    else if(requestUri) {
-        LL_FOREACH(cbList, out) {
-            if(out->requestUri && strcmp((char *)out->requestUri, (char *)requestUri) == 0) {
+    else if(requestUri)
+    {
+        LL_FOREACH(cbList, out)
+        {
+            if(out->requestUri && strcmp(out->requestUri, requestUri ) == 0)
+            {
                 return out;
             }
+            CheckAndDeleteTimedOutCB(out);
         }
     }
     OC_LOG(INFO, TAG, PCF("Callback Not found !!"));
     return NULL;
 }
 
-OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceTypeName)
+#ifdef WITH_PRESENCE
+OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, char * resourceTypeName)
 {
     OCResourceType * newResourceType = NULL;
     if(cbNode && resourceTypeName)
@@ -173,24 +266,28 @@ OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceT
         }
 
         newResourceType->next = NULL;
-        newResourceType->resourcetypename = (char *) resourceTypeName;
+        newResourceType->resourcetypename = resourceTypeName;
 
         LL_APPEND(cbNode->filterResourceType, newResourceType);
         return OC_STACK_OK;
     }
     return OC_STACK_ERROR;
 }
+#endif // WITH_PRESENCE
 
-void DeleteClientCBList() {
+void DeleteClientCBList()
+{
     ClientCB* out;
     ClientCB* tmp;
-    LL_FOREACH_SAFE(cbList, out, tmp) {
+    LL_FOREACH_SAFE(cbList, out, tmp)
+    {
         DeleteClientCB(out);
     }
     cbList = NULL;
 }
 
-void FindAndDeleteClientCB(ClientCB * cbNode) {
+void FindAndDeleteClientCB(ClientCB * cbNode)
+{
     ClientCB* tmp;
     if(cbNode)
     {
@@ -205,13 +302,19 @@ 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));
 
-    if (node) {
+    if (node)
+    {
         node->nonce = nonce;
         node->uri = uri;
         LL_APPEND(mcPresenceNodes, node);
@@ -222,12 +325,16 @@ OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, u
     return OC_STACK_NO_MEMORY;
 }
 
-OCMulticastNode* GetMCPresenceNode(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(uri)
+    {
+        LL_FOREACH(mcPresenceNodes, out)
+        {
+            if(out->uri && strcmp(out->uri, uri) == 0)
+            {
                 return out;
             }
         }
@@ -235,3 +342,4 @@ OCMulticastNode* GetMCPresenceNode(unsigned char * uri) {
     OC_LOG(INFO, TAG, PCF("MulticastNode Not found !!"));
     return NULL;
 }
+
index 5d486bf..622288e 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+// Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2001 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2001 base specification,
+// Refer http://pubs.opengroup.org/onlinepubs/009695399/
 #define _POSIX_C_SOURCE 200112L
+#include "occollection.h"
 #include <string.h>
 #include "ocstack.h"
 #include "ocstackinternal.h"
 #include "ocresourcehandler.h"
 #include "logger.h"
-#include "debug.h"
+#include "ocmalloc.h"
 #include "cJSON.h"
+#include "ocmalloc.h"
+
 /// Module Name
 #include <stdio.h>
 
 
 #define TAG PCF("occollection")
 
-#define NUM_PARAM_IN_QUERY  2
+#define NUM_PARAM_IN_QUERY   2 // The expected number of parameters in a query
+#define NUM_FIELDS_IN_QUERY  2 // The expected number of fields in a query
 
 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;
     }
@@ -52,11 +69,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;
     }
@@ -64,10 +88,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
@@ -77,6 +102,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
@@ -103,29 +133,33 @@ 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);
             }
         }
-        if (numParam != 2)
+        if (numParam != NUM_PARAM_IN_QUERY)
         {
             // Query parameter should be of the form if=<string>. String should not have & or =
             return OC_STACK_INVALID_QUERY;
         }
         token = strtok_r (NULL, "&", &endStr);
     }
-    if (numFields > NUM_PARAM_IN_QUERY)
+    if (numFields > NUM_FIELDS_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;
     }
 
@@ -185,32 +219,47 @@ 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;
-    char *jsonStr;
+    cJSON *resObj = NULL;
+    char *jsonStr = NULL;
     uint16_t jsonLen;
 
     OC_LOG(INFO, TAG, PCF("Entering BuildRootResourceJSON"));
     resObj = cJSON_CreateObject();
 
-    if (resource)
+    if ( ! resObj)
+    {
+        ret = OC_STACK_NO_MEMORY;
+    }
+    else if (resource)
     {
         cJSON_AddItemToObject (resObj, OC_RSRVD_HREF, cJSON_CreateString(resource->uri));
+        jsonStr = cJSON_PrintUnformatted (resObj);
+
+        if(!jsonStr)
+        {
+            cJSON_Delete(resObj);
+            return OC_STACK_NO_MEMORY;
+        }
+
+        jsonLen = strlen(jsonStr);
+        if (jsonLen < *remaining)
+        {
+            strncpy(bufferPtr, jsonStr, jsonLen);
+            *remaining -= jsonLen;
+            bufferPtr += jsonLen;
+            ret = OC_STACK_OK;
+        }
     }
-    jsonStr = cJSON_PrintUnformatted (resObj);
-    jsonLen = strlen(jsonStr);
-    if (jsonLen < *remaining)
+    else
     {
-        strcpy((char*) bufferPtr, jsonStr);
-        *remaining -= jsonLen;
-        bufferPtr += jsonLen;
-        ret = OC_STACK_OK;
+        ret = OC_STACK_INVALID_PARAM;
     }
 
     cJSON_Delete (resObj);
-    free (jsonStr);
+    OCFree(jsonStr);
 
     return ret;
 }
@@ -220,21 +269,26 @@ 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;
     remaining = MAX_RESPONSE_LENGTH;
 
     ret = BuildRootResourceJSON(collResource, ptr, &remaining);
-    ptr += strlen((char*)ptr);
 
     if (ret == OC_STACK_OK && remaining >= (sizeof(OC_JSON_SEPARATOR) + 1))
     {
+        ptr += strlen((char*)ptr);
         *ptr = OC_JSON_SEPARATOR;
         ptr++;
         remaining--;
@@ -243,7 +297,6 @@ HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
     {
         ret = OC_STACK_ERROR;
     }
-    *(ptr + 1) = '\0';
 
     if (ret == OC_STACK_OK)
     {
@@ -252,19 +305,36 @@ HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
             OCResource* temp = collResource->rsrcResources[i];
             if (temp)
             {
-                ret = BuildVirtualResourceResponse(temp, filterOn, filterValue, (char*)ptr, &remaining);
+                //TODO : Update needed here to get correct connectivity type
+                //from ServerRequest data structure.
+
+                // Function will return error if not enough space in buffer.
+                ret = BuildVirtualResourceResponse(temp, filterOn, filterValue,
+                         (char*)ptr, &remaining, CA_IPV4 );
                 if (ret != OC_STACK_OK)
                 {
                     break;
                 }
                 ptr += strlen((char*)ptr);
+
+                // Check if we have added all resources.
+                if ((i + 1) == MAX_CONTAINED_RESOURCES)
+                {
+                    break;
+                }
+                // Add separator if more resources and enough space present.
                 if (collResource->rsrcResources[i+1] && remaining > sizeof(OC_JSON_SEPARATOR))
                 {
                     *ptr = OC_JSON_SEPARATOR;
                     ptr++;
                     remaining--;
                 }
-                *(ptr + 1) = '\0';
+                // No point continuing as no more space on buffer
+                // and/or no more resources.
+                else
+                {
+                    break;
+                }
             }
             else
             {
@@ -276,7 +346,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;
@@ -293,10 +363,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;
@@ -304,12 +374,11 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
 
     stackRet = BuildRootResourceJSON(collResource, ptr, &remaining);
     ptr += strlen((char*)ptr);
-    *(ptr + 1) = '\0';
 
     jsonbufferLength = strlen((const char *)jsonbuffer);
     if(jsonbufferLength)
     {
-        OCEntityHandlerResponse response = {0};
+        OCEntityHandlerResponse response = {};
         response.ehResult = OC_EH_OK;
         response.payload = jsonbuffer;
         response.payloadSize = jsonbufferLength + 1;
@@ -359,21 +428,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;
@@ -381,19 +462,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)
     {
@@ -412,7 +498,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);
@@ -422,7 +509,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:
@@ -434,7 +523,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);
@@ -466,6 +556,22 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                 return OC_STACK_ERROR;
         }
     }
+    else if (ehRequest->method == OC_REST_POST)
+    {
+
+        if(ifQueryParam == 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);
+        }
+        else
+        {
+            return OC_STACK_ERROR;
+        }
+    }
     return result;
 }
 
+
index c1e8a1b..654078d 100644 (file)
 #include "ocstackinternal.h"
 #include "ocobserve.h"
 #include "ocresourcehandler.h"
-#include "occoap.h"
-#include "utlist.h"
-#include "debug.h"
 #include "ocrandom.h"
 #include "ocmalloc.h"
 #include "ocserverrequest.h"
 
+#include "utlist.h"
+#include "pdu.h"
+
 // Module Name
 #define MOD_NAME PCF("ocobserve")
 
 
 static struct ResourceObserver * serverObsList = NULL;
 
-// send notifications based on the qos of the request
-// The qos passed as a parameter overrides what the client requested
-// If we want the client preference taking high priority make:
-// qos = resourceObserver->qos;
-OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * resourceObserver,
-        OCQualityOfService appQoS)
+/**
+ * Determine observe QOS based on the QOS of the request.
+ * The qos passed as a parameter overrides what the client requested.
+ * If we want the client preference taking high priority make:
+ *     qos = resourceObserver->qos;
+ *
+ * @param method RESTful method.
+ * @param resourceObserver Observer.
+ * @param appQoS Quality of service.
+ * @return The quality of service of the observer.
+ */
+static OCQualityOfService DetermineObserverQoS(OCMethod method,
+        ResourceObserver * resourceObserver, OCQualityOfService appQoS)
 {
+    if(!resourceObserver)
+    {
+        OC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
+        return OC_NA_QOS;
+    }
+
     OCQualityOfService decidedQoS = appQoS;
     if(appQoS == OC_NA_QOS)
     {
@@ -65,13 +78,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,12 +102,18 @@ 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;
+    bool observeErrorFlag = false;
 
     // Find clients that are observing this resource
     while (resourceObserver)
@@ -107,24 +126,32 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
             {
             #endif
                 qos = DetermineObserverQoS(method, resourceObserver, qos);
+
                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
                         0, resPtr->sequenceNum, qos, resourceObserver->query,
                         NULL, NULL,
-                        &resourceObserver->token, resourceObserver->addr,
-                        resourceObserver->resUri, 0);
-                request->observeResult = OC_STACK_OK;
-                if(request && result == OC_STACK_OK)
+                        resourceObserver->token, resourceObserver->tokenLength,
+                        resourceObserver->resUri, 0,
+                        &(resourceObserver->addressInfo), resourceObserver->connectivityType);
+
+                if(request)
                 {
-                    result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
-                                request->method, (OCResourceHandle) resPtr, request->query,
-                                request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
-                                request->rcvdVendorSpecificHeaderOptions, OC_OBSERVE_NO_OPTION, 0);
+                    request->observeResult = OC_STACK_OK;
                     if(result == OC_STACK_OK)
                     {
-                        ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest);
-                        if(ehResult == OC_EH_ERROR)
+                        result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
+                                    request->method, (OCResourceHandle) resPtr, request->query,
+                                    request->reqJSONPayload,
+                                    request->numRcvdVendorSpecificHeaderOptions,
+                                    request->rcvdVendorSpecificHeaderOptions,
+                                    OC_OBSERVE_NO_OPTION, 0);
+                        if(result == OC_STACK_OK)
                         {
-                            FindAndDeleteServerRequest(request);
+                            ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest);
+                            if(ehResult == OC_EH_ERROR)
+                            {
+                                FindAndDeleteServerRequest(request);
+                            }
                         }
                     }
                 }
@@ -132,14 +159,19 @@ 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,
-                        0, OC_OBSERVE_NO_OPTION, OC_LOW_QOS,
-                        NULL, NULL, NULL, &resourceObserver->token,
-                        resourceObserver->addr, resourceObserver->resUri, 0);
+                        0, resPtr->sequenceNum, qos, resourceObserver->query,
+                        NULL, NULL,
+                        resourceObserver->token, resourceObserver->tokenLength,
+                        resourceObserver->resUri, 0,
+                        &(resourceObserver->addressInfo), resourceObserver->connectivityType);
+
                 if(result == OC_STACK_OK)
                 {
                     // we create the payload here
@@ -164,81 +196,117 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                 }
             }
             #endif
+
+            // Since we are in a loop, set an error flag to indicate at least one error occurred.
+            if (result != OC_STACK_OK)
+            {
+                observeErrorFlag = true;
+            }
         }
         resourceObserver = resourceObserver->next;
     }
+
     if (numObs == 0)
     {
         OC_LOG(INFO, TAG, PCF("Resource has no observers"));
         result = OC_STACK_NO_OBSERVERS;
     }
+    else if (observeErrorFlag)
+    {
+        OC_LOG(ERROR, TAG, PCF("Observer notification error"));
+        result = OC_STACK_ERROR;
+    }
     return result;
 }
 
 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;
+    ResourceObserver *observer = NULL;
     uint8_t numSentNotification = 0;
     OCServerRequest * request = NULL;
     OCStackResult result = OC_STACK_ERROR;
-    OCEntityHandlerResponse ehResponse = {0};
+    bool observeErrorFlag = false;
 
     OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
     while(numIds)
     {
-        OC_LOG_V(INFO, TAG, "Need to notify observation id %d", *obsIdList);
-        observation = NULL;
-        observation = GetObserverUsingId (*obsIdList);
-        if(observation)
+        observer = GetObserverUsingId (*obsIdList);
+        if(observer)
         {
-            // Found observation - verify if it matches the resource handle
-            if (observation->resource == resource)
+            // Found observer - verify if it matches the resource handle
+            if (observer->resource == resource)
             {
-                qos = DetermineObserverQoS(OC_REST_GET, observation, qos);
+                qos = DetermineObserverQoS(OC_REST_GET, observer, qos);
+
 
                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
-                        0, resource->sequenceNum, qos, observation->query,
-                        NULL, NULL, &observation->token,
-                        observation->addr, observation->resUri, 0);
-                request->observeResult = OC_STACK_OK;
-                if(request && result == OC_STACK_OK)
+                        0, resource->sequenceNum, qos, observer->query,
+                        NULL, NULL, observer->token, observer->tokenLength,
+                        observer->resUri, 0,
+                        &(observer->addressInfo), observer->connectivityType);
+
+                if(request)
                 {
-                    memset(&ehResponse, 0, sizeof(OCEntityHandlerResponse));
-                    ehResponse.ehResult = OC_EH_OK;
-                    ehResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
-                    if(!ehResponse.payload)
+                    request->observeResult = OC_STACK_OK;
+                    if(result == OC_STACK_OK)
                     {
-                        FindAndDeleteServerRequest(request);
-                        continue;
+                        OCEntityHandlerResponse ehResponse = {};
+                        ehResponse.ehResult = OC_EH_OK;
+                        ehResponse.payload = (char *) OCMalloc(MAX_RESPONSE_LENGTH + 1);
+                        if(!ehResponse.payload)
+                        {
+                            FindAndDeleteServerRequest(request);
+                            continue;
+                        }
+                        strncpy(ehResponse.payload, notificationJSONPayload, MAX_RESPONSE_LENGTH-1);
+                        ehResponse.payload[MAX_RESPONSE_LENGTH] = '\0';
+                        ehResponse.payloadSize = strlen(ehResponse.payload) + 1;
+                        ehResponse.persistentBufferFlag = 0;
+                        ehResponse.requestHandle = (OCRequestHandle) request;
+                        ehResponse.resourceHandle = (OCResourceHandle) resource;
+                        result = OCDoResponse(&ehResponse);
+                        if(result == OC_STACK_OK)
+                        {
+                            OC_LOG_V(INFO, TAG, "Observer id %d notified.", *obsIdList);
+
+                            // Increment only if OCDoResponse is successful
+                            numSentNotification++;
+
+                            OCFree(ehResponse.payload);
+                            FindAndDeleteServerRequest(request);
+                        }
+                        else
+                        {
+                            OC_LOG_V(INFO, TAG, "Error notifying observer id %d.", *obsIdList);
+                        }
                     }
-                    strcpy((char *)ehResponse.payload, (const char *)notificationJSONPayload);
-                    ehResponse.payloadSize = strlen((const char *)ehResponse.payload) + 1;
-                    ehResponse.persistentBufferFlag = 0;
-                    ehResponse.requestHandle = (OCRequestHandle) request;
-                    ehResponse.resourceHandle = (OCResourceHandle) resource;
-                    result = OCDoResponse(&ehResponse);
-                    if(result == OC_STACK_OK)
+                    else
                     {
-                        OCFree(ehResponse.payload);
                         FindAndDeleteServerRequest(request);
                     }
                 }
-                else
+                // Since we are in a loop, set an error flag to indicate
+                // at least one error occurred.
+                if (result != OC_STACK_OK)
                 {
-                    FindAndDeleteServerRequest(request);
+                    observeErrorFlag = true;
                 }
-
-                numSentNotification++;
             }
         }
         obsIdList++;
         numIds--;
     }
-    if(numSentNotification == numberOfIds)
+
+    if(numSentNotification == numberOfIds && !observeErrorFlag)
     {
         return OC_STACK_OK;
     }
@@ -248,9 +316,8 @@ OCStackResult SendListObserverNotification (OCResource * resource,
     }
     else
     {
-        //TODO: we need to signal that not every one in the
-        // list got an update, should we also indicate who did not receive on?
-        return OC_STACK_OK;
+        OC_LOG(ERROR, TAG, PCF("Observer notification error"));
+        return OC_STACK_ERROR;
     }
 }
 
@@ -268,7 +335,7 @@ OCStackResult GenerateObserverId (OCObservationId *observationId)
         resObs = GetObserverUsingId (*observationId);
     } while (NULL != resObs);
 
-    OC_LOG_V(INFO, TAG, "Observation ID is %u", *observationId);
+    OC_LOG_V(INFO, TAG, "Generated bservation ID is %u", *observationId);
 
     return OC_STACK_OK;
 exit:
@@ -278,39 +345,57 @@ exit:
 OCStackResult AddObserver (const char         *resUri,
                            const char         *query,
                            OCObservationId    obsId,
-                           OCCoAPToken        *token,
-                           OCDevAddr          *addr,
+                           CAToken_t          token,
+                           uint8_t            tokenLength,
                            OCResource         *resHandle,
-                           OCQualityOfService qos)
+                           OCQualityOfService qos,
+                           const CAAddress_t  *addressInfo,
+                           CATransportType_t connectivityType)
 {
+    // Check if resource exists and is observable.
+    if (!resHandle)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (!(resHandle->resourceProperties & OC_OBSERVABLE))
+    {
+        return OC_STACK_RESOURCE_ERROR;
+    }
     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.tokenLength = token->tokenLength;
-        memcpy (obsNode->token.token, token->token, token->tokenLength);
-
-        obsNode->addr = (OCDevAddr *)OCMalloc(sizeof(OCDevAddr));
-        VERIFY_NON_NULL (obsNode->addr);
-        memcpy (obsNode->addr, addr, sizeof(OCDevAddr));
-
+        // If tokenLength is zero, the return value depends on the
+        // particular library implementation (it may or may not be a null pointer).
+        if(tokenLength)
+        {
+            obsNode->token = (CAToken_t)OCMalloc(tokenLength);
+            VERIFY_NON_NULL (obsNode->token);
+            memcpy(obsNode->token, token, tokenLength);
+        }
+        obsNode->tokenLength = tokenLength;
+        obsNode->addressInfo = *addressInfo;
+        obsNode->connectivityType = connectivityType;
         obsNode->resource = resHandle;
-
         LL_APPEND (serverObsList, obsNode);
         return OC_STACK_OK;
     }
@@ -320,7 +405,6 @@ exit:
     {
         OCFree(obsNode->resUri);
         OCFree(obsNode->query);
-        OCFree(obsNode->addr);
         OCFree(obsNode);
     }
     return OC_STACK_NO_MEMORY;
@@ -344,19 +428,18 @@ ResourceObserver* GetObserverUsingId (const OCObservationId observeId)
     return NULL;
 }
 
-ResourceObserver* GetObserverUsingToken (const OCCoAPToken * token)
+ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLength)
 {
     ResourceObserver *out = NULL;
 
-    if(token)
+    if(token && *token)
     {
         LL_FOREACH (serverObsList, out)
         {
             OC_LOG(INFO, TAG,PCF("comparing tokens"));
-            OC_LOG_BUFFER(INFO, TAG, token->token, token->tokenLength);
-            OC_LOG_BUFFER(INFO, TAG, out->token.token, out->token.tokenLength);
-            if((out->token.tokenLength == token->tokenLength) &&
-               (memcmp(out->token.token, token->token, token->tokenLength) == 0))
+            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
+            OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->token, tokenLength);
+            if((memcmp(out->token, token, tokenLength) == 0))
             {
                 return out;
             }
@@ -366,19 +449,24 @@ ResourceObserver* GetObserverUsingToken (const OCCoAPToken * token)
     return NULL;
 }
 
-OCStackResult DeleteObserverUsingToken (OCCoAPToken * token)
+OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
 {
+    if(!token || !*token)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     ResourceObserver *obsNode = NULL;
 
-    obsNode = GetObserverUsingToken (token);
+    obsNode = GetObserverUsingToken (token, tokenLength);
     if (obsNode)
     {
         OC_LOG_V(INFO, TAG, PCF("deleting tokens"));
-        OC_LOG_BUFFER(INFO, TAG, obsNode->token.token, obsNode->token.tokenLength);
+        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)obsNode->token, tokenLength);
         LL_DELETE (serverObsList, obsNode);
         OCFree(obsNode->resUri);
         OCFree(obsNode->query);
-        OCFree(obsNode->addr);
+        OCFree(obsNode->token);
         OCFree(obsNode);
     }
     // it is ok if we did not find the observer...
@@ -391,7 +479,94 @@ void DeleteObserverList()
     ResourceObserver *tmp = NULL;
     LL_FOREACH_SAFE (serverObsList, out, tmp)
     {
-        DeleteObserverUsingToken (&(out->token));
+        if(out)
+        {
+            DeleteObserverUsingToken ((out->token), out->tokenLength);
+        }
     }
     serverObsList = NULL;
 }
+
+/*
+ * CA layer expects observe registration/de-reg/notiifcations to be passed as a header
+ * option, which breaks the protocol abstraction requirement between RI & CA, and
+ * has to be fixed in the future. The function below adds the header option for observe.
+ * It should be noted that the observe header option is assumed to be the first option
+ * in the list of user defined header options and hence it is inserted at the front
+ * of the header options list and number of options adjusted accordingly.
+ */
+OCStackResult
+CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
+                           OCHeaderOption *ocHdrOpt,
+                           uint8_t numOptions,
+                           uint8_t observeFlag)
+{
+    if(!caHdrOpt)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    CAHeaderOption_t *tmpHdrOpt = NULL;
+
+    tmpHdrOpt = (CAHeaderOption_t *) OCCalloc ((numOptions+1), sizeof(CAHeaderOption_t));
+    if (NULL == tmpHdrOpt)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+    tmpHdrOpt[0].protocolID = CA_COAP_ID;
+    tmpHdrOpt[0].optionID = COAP_OPTION_OBSERVE;
+    tmpHdrOpt[0].optionLength = sizeof(uint32_t);
+    tmpHdrOpt[0].optionData[0] = observeFlag;
+    for (uint8_t i = 0; i < numOptions; i++)
+    {
+        memcpy (&(tmpHdrOpt[i+1]), &(ocHdrOpt[i]), sizeof(CAHeaderOption_t));
+    }
+
+    *caHdrOpt = tmpHdrOpt;
+    return OC_STACK_OK;
+}
+
+/*
+ * CA layer passes observe information to the RI layer as a header option, which
+ * breaks the protocol abstraction requirement between RI & CA, and has to be fixed
+ * in the future. The function below removes the observe header option and processes it.
+ * It should be noted that the observe header option is always assumed to be the first
+ * option in the list of user defined header options and hence it is deleted from the
+ * front of the header options list and the number of options is adjusted accordingly.
+ */
+OCStackResult
+GetObserveHeaderOption (uint32_t * observationOption,
+                        CAHeaderOption_t *options,
+                        uint8_t * numOptions)
+{
+    if(!observationOption)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    *observationOption = OC_OBSERVE_NO_OPTION;
+
+    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(uint8_t c = i; c < *numOptions-1; c++)
+            {
+                options[i].protocolID = options[i+1].protocolID;
+                options[i].optionID = options[i+1].optionID;
+                options[i].optionLength = options[i+1].optionLength;
+                memcpy(options[i].optionData, options[i+1].optionData, options[i+1].optionLength);
+            }
+            (*numOptions)--;
+            return OC_STACK_OK;
+        }
+    }
+    return OC_STACK_OK;
+}
+
index f2267d1..a5fa040 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+// Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2001 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2001 base specification,
+// Refer http://pubs.opengroup.org/onlinepubs/009695399/
 #define _POSIX_C_SOURCE 200112L
+#include "ocresource.h"
 #include <string.h>
-#include "ocstack.h"
-#include "ocstackconfig.h"
-#include "ocstackinternal.h"
 #include "ocresourcehandler.h"
 #include "ocobserve.h"
 #include "occollection.h"
-#include "occoap.h"
+#include "ocmalloc.h"
 #include "logger.h"
-#include "debug.h"
 #include "cJSON.h"
 
+#include "cacommon.h"
+#include "cainterface.h"
+
+
 /// Module Name
 #define TAG PCF("ocresource")
 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
              TAG, PCF(#arg " is NULL")); return (retVal); } }
 
 extern OCResource *headResource;
+static OCPlatformInfo savedPlatformInfo = {};
 static cJSON *savedDeviceInfo = NULL;
-
-static const char * VIRTUAL_RSRCS[] = {
+static const char * VIRTUAL_RSRCS[] =
+{
        "/oc/core",
        "/oc/core/d",
+       "/oic/p",
        "/oc/core/types/d",
        #ifdef WITH_PRESENCE
-       "/oc/presence"
+       "/oic/ad"
        #endif
 };
 
@@ -55,58 +64,191 @@ static const char * VIRTUAL_RSRCS[] = {
 // Default resource entity handler function
 //-----------------------------------------------------------------------------
 OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
-        OCEntityHandlerRequest * request) {
-    TODO ("Implement me!!!!");
+        OCEntityHandlerRequest * request)
+{
+    //TODO ("Implement me!!!!");
     // TODO:  remove silence unused param warnings
     (void) flag;
     (void) request;
     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
 }
 
-static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query,
+/* This method will retrieve the port at which the secure resource is hosted */
+static OCStackResult GetSecurePortInfo(CATransportType_t connType, uint16_t *port)
+{
+    CALocalConnectivity_t* info = NULL;
+    uint32_t size = 0;
+    OCStackResult ret = OC_STACK_ERROR;
+
+    CAResult_t caResult = CAGetNetworkInformation(&info, &size);
+    if ((caResult == CA_STATUS_OK) && info && size)
+    {
+        while (size--)
+        {
+            if (info[size].isSecured && info[size].type == connType)
+            {
+                if (info[size].type == CA_IPV4)
+                {
+                    *port = info[size].addressInfo.IP.port;
+                    ret = OC_STACK_OK;
+                    break;
+                }
+            }
+        }
+    }
+
+    OCFree(info);
+    return ret;
+}
+
+static char* GetJSONStringFromPlatformInfo(OCPlatformInfo info)
+{
+    cJSON *rootObj = cJSON_CreateObject();
+
+    if (!rootObj)
+    {
+        return NULL;
+    }
+
+    cJSON *repObj = NULL;
+    char *jsonEncodedInfo = NULL;
+
+    cJSON_AddItemToObject (rootObj, OC_RSRVD_HREF,
+            cJSON_CreateString(GetVirtualResourceUri(OC_PLATFORM_URI)));
+
+    cJSON_AddItemToObject (rootObj, OC_RSRVD_REPRESENTATION, repObj = cJSON_CreateObject());
+
+    cJSON_AddItemToObject (repObj, OC_RSRVD_PLATFORM_ID, cJSON_CreateString(info.platformID));
+    cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_NAME, cJSON_CreateString(info.manufacturerName));
+    if (info.manufacturerUrl)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_URL,
+                cJSON_CreateString(info.manufacturerUrl));
+    }
+
+    if (info.modelNumber)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MODEL_NUM,
+                cJSON_CreateString(info.modelNumber));
+    }
+
+    if (info.dateOfManufacture)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_DATE,
+                cJSON_CreateString(info.dateOfManufacture));
+    }
+
+    if (info.platformVersion)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_PLATFORM_VERSION,
+                cJSON_CreateString(info.platformVersion));
+    }
+
+    if (info.operatingSystemVersion)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_OS_VERSION,
+                cJSON_CreateString(info.operatingSystemVersion));
+    }
+
+    if (info.hardwareVersion)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_HARDWARE_VERSION,
+                cJSON_CreateString(info.hardwareVersion));
+    }
+
+    if (info.firmwareVersion)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_FIRMWARE_VERSION,
+                cJSON_CreateString(info.firmwareVersion));
+    }
+
+    if (info.supportUrl)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_SUPPORT_URL,
+                cJSON_CreateString(info.supportUrl));
+    }
+
+    if (info.systemTime)
+    {
+        cJSON_AddItemToObject (repObj, OC_RSRVD_SYSTEM_TIME,
+                cJSON_CreateString(info.systemTime));
+    }
+
+    jsonEncodedInfo = cJSON_PrintUnformatted (rootObj);
+
+    cJSON_Delete(rootObj);
+
+    return jsonEncodedInfo;
+}
+
+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 ||
+                strcmp((char *)url, GetVirtualResourceUri(OC_PLATFORM_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) || ! filterParam)
+            {
                 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;
     }
@@ -114,16 +256,26 @@ static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query,
     return OC_STACK_OK;
 }
 
-OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
-                                            char *filterValue, char * out, uint16_t *remaining)
+
+OCStackResult
+BuildVirtualResourceResponse(const OCResource *resourcePtr, uint8_t filterOn,
+                       const char *filterValue, char *out, uint16_t *remaining,
+                       CATransportType_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();
@@ -131,40 +283,58 @@ OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filt
     if (resourcePtr)
     {
         encodeRes = 0;
-        if (filterOn == STACK_RES_DISCOVERY_RT_FILTER) {
+        if ((filterOn == STACK_RES_DISCOVERY_RT_FILTER) && filterValue)
+        {
             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) && filterValue)
+        {
             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));
 
-            cJSON_AddItemToObject (resObj, "prop", propObj = cJSON_CreateObject());
+            // Add server instance id
+            cJSON_AddItemToObject (resObj,
+                                   OC_RSRVD_SERVER_INSTANCE_ID,
+                                   cJSON_CreateString(OCGetServerInstanceIDString()));
+
+            cJSON_AddItemToObject (resObj, OC_RSRVD_PROPERTY, 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;
@@ -172,22 +342,26 @@ OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filt
             // 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) {
-                uint16_t port;
+            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
-                if (OCGetResourceEndPointInfo (resourcePtr, &port) == OC_STACK_OK) {
+                uint16_t port = 0;
+                if (GetSecurePortInfo (connType, &port) == OC_STACK_OK)
+                {
                     cJSON_AddNumberToObject (propObj, OC_RSRVD_HOSTING_PORT, port);
                 }
             }
@@ -196,6 +370,12 @@ OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filt
     }
     jsonStr = cJSON_PrintUnformatted (resObj);
 
+    if(!jsonStr)
+    {
+        cJSON_Delete(resObj);
+        return OC_STACK_NO_MEMORY;
+    }
+
     jsonLen = strlen(jsonStr);
     if (jsonLen < *remaining)
     {
@@ -207,7 +387,7 @@ OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filt
         ret = OC_STACK_ERROR;
     }
     cJSON_Delete (resObj);
-    free (jsonStr);
+    OCFree (jsonStr);
 
     OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponse"));
     return ret;
@@ -216,28 +396,35 @@ OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filt
 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)
     {
         char *jsonStr = NULL;
         uint16_t jsonLen = 0;
-        cJSON *repObj = cJSON_GetObjectItem(savedDeviceInfo, "rep");
+        cJSON *repObj = cJSON_GetObjectItem(savedDeviceInfo, OC_RSRVD_REPRESENTATION);
 
         OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponseForDevice"));
 
-        if (filterOn == STACK_DEVICE_DISCOVERY_DI_FILTER)
+        if ((filterOn == STACK_DEVICE_DISCOVERY_DI_FILTER) && filterValue)
         {
-            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)
+        else if ((filterOn == STACK_DEVICE_DISCOVERY_DN_FILTER) && filterValue)
         {
-            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;
             }
@@ -270,7 +457,7 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
                     ret = OC_STACK_ERROR;
                 }
 
-                free(jsonStr);
+                OCFree(jsonStr);
             }
             else
             {
@@ -284,6 +471,7 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
     }
     else
     {
+        OC_LOG(ERROR, TAG, PCF("No device info found."));
         //error so that stack won't respond with empty payload
         ret = OC_STACK_INVALID_DEVICE_INFO;
     }
@@ -292,7 +480,39 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
     return ret;
 }
 
-TODO ("Does it make sense to make this method as inline")
+OCStackResult BuildVirtualResourceResponseForPlatform(char *out, uint16_t *remaining)
+{
+    OCStackResult ret = OC_STACK_OK;
+
+    char *jsonStr = GetJSONStringFromPlatformInfo(savedPlatformInfo);
+
+    if(jsonStr)
+    {
+        size_t jsonLen = strlen(jsonStr);
+
+        if (jsonLen < *remaining)
+        {
+            strncpy(out, jsonStr, (jsonLen + 1));
+            *remaining = *remaining - jsonLen;
+            ret = OC_STACK_OK;
+        }
+        else
+        {
+            OC_LOG_V(ERROR, TAG, PCF("Platform info string too big. len: %u"), jsonLen);
+            ret = OC_STACK_ERROR;
+        }
+        OCFree(jsonStr);
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, PCF("Error encoding save platform info."));
+        ret = OC_STACK_ERROR;
+    }
+
+
+    return ret;
+
+}
 const char * GetVirtualResourceUri( OCVirtualResources resource)
 {
     if (resource < OC_MAX_VIRTUAL_RESOURCES)
@@ -303,20 +523,30 @@ const char * GetVirtualResourceUri( OCVirtualResources resource)
     return NULL;
 }
 
-uint8_t IsVirtualResource(const char* resourceUri)
+bool IsVirtualResource(const char* resourceUri)
 {
+    if(!resourceUri)
+    {
+        return false;
+    }
+
     for (int i = 0; i < OC_MAX_VIRTUAL_RESOURCES; i++)
     {
         if (strcmp(resourceUri, GetVirtualResourceUri((OCVirtualResources)i)) == 0)
         {
-            return 1;
+            return true;
         }
     }
-    return 0;
+    return false;
 }
 
 uint8_t IsCollectionResource (OCResource *resource)
 {
+    if(!resource)
+    {
+        return 0;
+    }
+
     for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
     {
         if (resource->rsrcResources[i])
@@ -329,9 +559,16 @@ 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) {
+    while (pointer)
+    {
+        if (strcmp(resourceUri, pointer->uri) == 0)
+        {
             return pointer;
         }
         pointer = pointer->next;
@@ -341,10 +578,14 @@ OCResource *FindResourceByUri(const char* resourceUri)
 }
 
 
-OCStackResult DetermineResourceHandling (OCServerRequest *request,
+OCStackResult DetermineResourceHandling (const OCServerRequest *request,
                                          ResourceHandling *handling,
                                          OCResource **resource)
 {
+    if(!request || !handling || !resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OC_LOG(INFO, TAG, PCF("Entering DetermineResourceHandling"));
 
@@ -359,7 +600,7 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
     {
         // Resource URL not specified
         *handling = OC_RESOURCE_NOT_SPECIFIED;
-        return OC_STACK_OK;
+        return OC_STACK_NO_RESOURCE;
     }
     else
     {
@@ -383,7 +624,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;
         }
 
@@ -394,17 +635,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;
             }
@@ -436,6 +683,9 @@ OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
         case OC_EH_RESOURCE_DELETED:
             result = OC_STACK_RESOURCE_DELETED;
             break;
+        case OC_EH_RESOURCE_NOT_FOUND:
+            result = OC_STACK_NO_RESOURCE;
+            break;
         default:
             result = OC_STACK_ERROR;
     }
@@ -446,13 +696,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"));
 
@@ -467,7 +722,9 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
             ptr = discoveryResBuf;
             remaining = MAX_RESPONSE_LENGTH;
 
-            while(resource)
+            // Check if valid resource and enough space in buffer for atleast
+            // the null character.
+            while(resource && (remaining > 1))
             {
                 if((resource->resourceProperties & OC_ACTIVE)
                         && (resource->resourceProperties & OC_DISCOVERABLE))
@@ -483,7 +740,7 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
                     }
                     firstLoopDone = 1;
                     result = BuildVirtualResourceResponse(resource, filterOn, filterValue,
-                            (char*)ptr, &remaining);
+                            (char*)ptr, &remaining, request->connectivityType );
 
                     if (result != OC_STACK_OK)
                     {
@@ -497,14 +754,13 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
                         break;
                     }
                     ptr += strlen((char *)ptr);
-                    *(ptr + 1) = '\0';
                 }
                 resource = resource->next;
             }
 
             if(strlen((const char *)discoveryResBuf) > 0)
             {
-                OCEntityHandlerResponse response = {0};
+                OCEntityHandlerResponse response = {};
 
                 response.ehResult = OC_EH_OK;
                 response.payload = discoveryResBuf;
@@ -543,6 +799,32 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
                 result = OCDoResponse(&response);
             }
         }
+        else if (strcmp ((char *)request->resourceUrl, GetVirtualResourceUri(OC_PLATFORM_URI)) == 0)
+        {
+            remaining = MAX_RESPONSE_LENGTH;
+            ptr = discoveryResBuf;
+
+            result = BuildVirtualResourceResponseForPlatform((char*)ptr, &remaining);
+
+            if(result == OC_STACK_OK)
+            {
+                ptr += strlen((char*)ptr);
+            }
+
+            if(remaining < MAX_RESPONSE_LENGTH)
+            {
+                OCEntityHandlerResponse response = {0};
+
+                response.ehResult = OC_EH_OK;
+                response.payload = discoveryResBuf;
+                response.payloadSize = strlen((const char *)discoveryResBuf) + 1;
+                response.persistentBufferFlag = 0;
+                response.requestHandle = (OCRequestHandle) request;
+                response.resourceHandle = (OCResourceHandle) resource;
+
+                result = OCDoResponse(&response);
+            }
+        }
         #ifdef WITH_PRESENCE
         else
         {
@@ -552,22 +834,28 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
         }
         #endif
     }
-    result = OC_STACK_VIRTUAL_DO_NOT_HANDLE;
+    result = OC_STACK_OK;
     return result;
 }
 
 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
@@ -592,12 +880,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,
@@ -621,19 +914,24 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
 
         result = AddObserver ((const char*)(request->resourceUrl),
                 (const char *)(request->query),
-                ehRequest.obsInfo.obsId, &request->requestToken,
-                &request->requesterAddr, resource, request->qos);
+                ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
+                resource, request->qos,
+                &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);
         }
         else
         {
             result = OC_STACK_OK;
+            // The error in observeResult for the request will be
+            // used when responding to this request by omitting
+            // the observation option/sequence number.
             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;
         }
 
@@ -642,7 +940,9 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
             !collectionResource)
     {
         OC_LOG(INFO, TAG, PCF("Deregistering observation requested"));
-        resObs = GetObserverUsingToken (&request->requestToken);
+
+        resObs = GetObserverUsingToken (request->requestToken, request->tokenLength);
+
         if (NULL == resObs)
         {
             // Stack does not contain this observation request
@@ -653,17 +953,18 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
         ehRequest.obsInfo.obsId = resObs->observeId;
         ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG);
 
-        result = DeleteObserverUsingToken (&request->requestToken);
+        result = DeleteObserverUsingToken (request->requestToken, request->tokenLength);
+
         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
@@ -691,8 +992,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,
@@ -766,101 +1072,119 @@ void DeleteDeviceInfo()
     }
 }
 
-OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
+void DeletePlatformInfo()
 {
-    DeleteDeviceInfo();
+    OC_LOG(INFO, TAG, PCF("Deleting platform info."));
 
-    savedDeviceInfo = cJSON_CreateObject();
-    cJSON *repObj = NULL;
+    OCFree(savedPlatformInfo.platformID);
+    savedPlatformInfo.platformID = NULL;
 
-    cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_HREF,
-            cJSON_CreateString(GetVirtualResourceUri(OC_DEVICE_URI)));
+    OCFree(savedPlatformInfo.manufacturerName);
+    savedPlatformInfo.manufacturerName = NULL;
 
-    cJSON_AddItemToObject (savedDeviceInfo, "rep", repObj = cJSON_CreateObject());
+    OCFree(savedPlatformInfo.manufacturerUrl);
+    savedPlatformInfo.manufacturerUrl = NULL;
 
-    if (deviceInfo.contentType)
-    {
-        cJSON_AddItemToObject (repObj, "ct",
-                cJSON_CreateString(deviceInfo.contentType));
-    }
+    OCFree(savedPlatformInfo.modelNumber);
+    savedPlatformInfo.modelNumber = NULL;
 
-    if (deviceInfo.dateOfManufacture)
-    {
-        cJSON_AddItemToObject (repObj, "mndt",
-                cJSON_CreateString(deviceInfo.dateOfManufacture));
-    }
+    OCFree(savedPlatformInfo.dateOfManufacture);
+    savedPlatformInfo.dateOfManufacture = NULL;
 
-    if (deviceInfo.deviceName)
-    {
-        cJSON_AddItemToObject (repObj, "dn",
-                cJSON_CreateString(deviceInfo.deviceName));
-    }
+    OCFree(savedPlatformInfo.platformVersion);
+    savedPlatformInfo.platformVersion = NULL;
 
-    if (deviceInfo.deviceUUID)
-    {
-        cJSON_AddItemToObject (repObj, "di",
-                cJSON_CreateString(deviceInfo.deviceUUID));
-    }
+    OCFree(savedPlatformInfo.operatingSystemVersion);
+    savedPlatformInfo.operatingSystemVersion = NULL;
 
-    if (deviceInfo.firmwareVersion)
-    {
-        cJSON_AddItemToObject (repObj, "mnfv",
-                cJSON_CreateString(deviceInfo.firmwareVersion));
-    }
+    OCFree(savedPlatformInfo.hardwareVersion);
+    savedPlatformInfo.hardwareVersion = NULL;
 
-    if (deviceInfo.hostName)
-    {
-        cJSON_AddItemToObject (repObj, "hn", cJSON_CreateString(deviceInfo.hostName));
-    }
+    OCFree(savedPlatformInfo.firmwareVersion);
+    savedPlatformInfo.firmwareVersion = NULL;
 
-    if (deviceInfo.manufacturerName)
-    {
-        if(strlen(deviceInfo.manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH)
-        {
-            DeleteDeviceInfo();
-            return OC_STACK_INVALID_PARAM;
-        }
+    OCFree(savedPlatformInfo.supportUrl);
+    savedPlatformInfo.supportUrl = NULL;
 
-        cJSON_AddItemToObject (repObj, "mnmn",
-                cJSON_CreateString(deviceInfo.manufacturerName));
-    }
+    OCFree(savedPlatformInfo.systemTime);
+    savedPlatformInfo.systemTime = NULL;
+}
 
-    if (deviceInfo.manufacturerUrl)
+static OCStackResult CloneStringIfNonNull(char **dest, char *src)
+{
+    if (src)
     {
-        if(strlen(deviceInfo.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
+        *dest = (char*) OCMalloc(strlen(src) + 1);
+        if (!*dest)
         {
-            DeleteDeviceInfo();
-            return OC_STACK_INVALID_PARAM;
+            return OC_STACK_NO_MEMORY;
         }
-
-        cJSON_AddItemToObject (repObj, "mnml",
-                cJSON_CreateString(deviceInfo.manufacturerUrl));
+        strcpy(*dest, src);
     }
-
-    if (deviceInfo.modelNumber)
+    else
     {
-        cJSON_AddItemToObject (repObj, "mnmo",
-                cJSON_CreateString(deviceInfo.modelNumber));
+        *dest = NULL;
     }
+    return OC_STACK_OK;
+}
+static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
+{
+    DeletePlatformInfo();
 
-    if (deviceInfo.platformVersion)
-    {
-        cJSON_AddItemToObject (repObj, "mnpv",
-                cJSON_CreateString(deviceInfo.platformVersion));
-    }
+    OCStackResult ret = OC_STACK_OK;
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.platformID), info.platformID);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.manufacturerName), info.manufacturerName);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.manufacturerUrl), info.manufacturerUrl);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.modelNumber), info.modelNumber);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.dateOfManufacture), info.dateOfManufacture);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.platformVersion), info.platformVersion);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.operatingSystemVersion), info.operatingSystemVersion);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
 
-    if (deviceInfo.supportUrl)
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.hardwareVersion), info.hardwareVersion);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.firmwareVersion), info.firmwareVersion);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.supportUrl), info.supportUrl);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    ret = CloneStringIfNonNull(&(savedPlatformInfo.systemTime), info.systemTime);
+    VERIFY_SUCCESS(ret, OC_STACK_OK);
+
+    return OC_STACK_OK;
+
+    exit:
+        DeletePlatformInfo();
+        return ret;
+
+}
+
+OCStackResult SavePlatformInfo(OCPlatformInfo info)
+{
+    OCStackResult res = DeepCopyPlatFormInfo(info);
+
+    if (res != OC_STACK_OK)
     {
-        cJSON_AddItemToObject (repObj, "mnsl",
-                cJSON_CreateString(deviceInfo.supportUrl));
+        OC_LOG_V(ERROR, TAG, PCF("Failed to save platform info. errno(%d)"), res);
     }
-
-    if (deviceInfo.version)
+    else
     {
-        cJSON_AddItemToObject (repObj, "icv",
-                cJSON_CreateString(deviceInfo.version));
+        OC_LOG(ERROR, TAG, PCF("Platform info saved."));
     }
 
-    return OC_STACK_OK;
+    return res;
 }
-
diff --git a/resource/csdk/stack/src/ocsecurity.c b/resource/csdk/stack/src/ocsecurity.c
deleted file mode 100644 (file)
index 0dd7aae..0000000
+++ /dev/null
@@ -1,86 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocstack.h"
-#include "ocmalloc.h"
-#include "ocsecurity.h"
-#include "ocsecurityconfig.h"
-#include <string.h>
-
-static OCDtlsPskCredsBlob* pskCredsBlob;
-static int pskCredsBlobLen;
-
-// Internal API. Invoked by OC stack to cleanup memory
-void DeinitOCSecurityInfo()
-{
-    if (pskCredsBlob)
-    {
-        // Initialize sensitive data to zeroes before freeing.
-        memset(pskCredsBlob, 0, pskCredsBlobLen);
-
-        OCFree(pskCredsBlob);
-        pskCredsBlob = NULL;
-    }
-}
-
-// Internal API. Invoked by OC stack to retrieve credentials from this module
-void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
-{
-    *credInfo = pskCredsBlob;
-}
-
-/**
- * Provides the DTLS PSK credetials blob to OC stack.
- *
- * @param credInfo
- *     binary blob containing credentials
- * @param len
- *     length of binary blob
- *
- * @retval OC_STACK_OK for Success, otherwise some error value
- */
-OCStackResult OCSetDtlsPskCredentials(const OCDtlsPskCredsBlob *credInfo,
-                size_t len)
-{
-    if(credInfo && len > 0)
-    {
-        if (credInfo->blobVer != DtlsPskCredsBlobVer_CurrentVersion)
-        {
-            return OC_STACK_INVALID_PARAM;
-        }
-
-        // Remove existing blob
-        DeinitOCSecurityInfo();
-        // Allocate storage for new blob
-        pskCredsBlob = (OCDtlsPskCredsBlob*)OCMalloc(len);
-        if (pskCredsBlob)
-        {
-            memcpy(pskCredsBlob, credInfo, len);
-            pskCredsBlobLen = len;
-            return OC_STACK_OK;
-        }
-
-        return OC_STACK_NO_MEMORY;
-    }
-
-    return OC_STACK_INVALID_PARAM;
-}
-
-
index 3398857..8448b87 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <string.h>
 
 #include "ocstack.h"
 #include "ocserverrequest.h"
 #include "ocresourcehandler.h"
+#include "ocmalloc.h"
+
+#include "cacommon.h"
+#include "cainterface.h"
+
+#include "utlist.h"
+#include "pdu.h"
 
 // Module Name
 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
 static struct OCServerRequest * serverRequestList = NULL;
 static struct OCServerResponse * serverResponseList = NULL;
 
-OCServerRequest * GetServerRequestUsingToken (const OCCoAPToken token)
+//-------------------------------------------------------------------------------------------------
+// Local functions
+//-------------------------------------------------------------------------------------------------
+
+/**
+ * Add a server response to the server response list
+ *
+ * @param response initialized server response that is created by this function
+ * @param requestHandle - handle of the response
+ *
+ * @return
+ *     OCStackResult
+ */
+static OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
 {
+    OCServerResponse * serverResponse = NULL;
+
+    serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
+    VERIFY_NON_NULL(serverResponse);
+
+    serverResponse->payload = (char *) OCCalloc(1, MAX_RESPONSE_LENGTH);
+    VERIFY_NON_NULL(serverResponse->payload);
+
+    serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
+    serverResponse->requestHandle = requestHandle;
+
+    *response = serverResponse;
+    OC_LOG(INFO, TAG, PCF("Server Response Added!!"));
+    LL_APPEND (serverResponseList, serverResponse);
+    return OC_STACK_OK;
+
+exit:
+    if (serverResponse)
+    {
+        OCFree(serverResponse);
+        serverResponse = NULL;
+    }
+    *response = NULL;
+    return OC_STACK_NO_MEMORY;
+}
+
+/**
+ * Delete a server request from the server request list
+ *
+ * @param serverRequest - server request to delete
+ */
+static void DeleteServerRequest(OCServerRequest * serverRequest)
+{
+    if(serverRequest)
+    {
+        LL_DELETE(serverRequestList, serverRequest);
+        OCFree(serverRequest->requestToken);
+        OCFree(serverRequest);
+        serverRequest = NULL;
+        OC_LOG(INFO, TAG, PCF("Server Request Removed!!"));
+    }
+}
+
+/**
+ * Delete a server response from the server response list
+ *
+ * @param serverResponse - server response to delete
+ */
+static void DeleteServerResponse(OCServerResponse * serverResponse)
+{
+    if(serverResponse)
+    {
+        LL_DELETE(serverResponseList, serverResponse);
+        OCFree(serverResponse->payload);
+        OCFree(serverResponse);
+        OC_LOG(INFO, TAG, PCF("Server Response Removed!!"));
+    }
+}
+
+/**
+ * Find a server response and delete it from the server response list
+ *
+ * @param serverResponse - server response to find and delete
+ */
+static void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
+{
+    OCServerResponse* tmp;
+    if(serverResponse)
+    {
+        LL_FOREACH(serverResponseList, tmp)
+        {
+            if (serverResponse == tmp)
+            {
+                DeleteServerResponse(tmp);
+                return;
+            }
+        }
+    }
+}
+
+//-------------------------------------------------------------------------------------------------
+// Internal APIs
+//-------------------------------------------------------------------------------------------------
+
+/**
+ * Get a server request from the server request list using the specified token.
+ *
+ * @param token - token of server request
+ * @param tokenLength - length of token
+ *
+ * @return
+ *     OCServerRequest*
+ */
+OCServerRequest * GetServerRequestUsingToken (const CAToken_t token, uint8_t tokenLength)
+{
+    if(!token)
+    {
+        OC_LOG(ERROR, TAG, PCF("Invalid Parameter Token"));
+        return NULL;
+    }
+
     OCServerRequest * out = NULL;
     LL_FOREACH (serverRequestList, out)
     {
         OC_LOG(INFO, TAG,PCF("comparing tokens"));
-        OC_LOG_BUFFER(INFO, TAG, token.token, token.tokenLength);
-        OC_LOG_BUFFER(INFO, TAG, out->requestToken.token, out->requestToken.tokenLength);
-        if((out->requestToken.tokenLength == token.tokenLength) &&
-                (memcmp(out->requestToken.token, token.token, token.tokenLength) == 0))
+        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
+        OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, tokenLength);
+        if(memcmp(out->requestToken, token, tokenLength) == 0)
         {
             return out;
         }
     }
-    OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
+    OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
     return NULL;
 }
 
+/**
+ * Get a server request from the server request list using the specified handle
+ *
+ * @param handle - handle of server request
+ * @return
+ *     OCServerRequest*
+ */
 OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
 {
     OCServerRequest * out = NULL;
@@ -58,10 +186,18 @@ 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;
 }
 
+/**
+ * Get a server response from the server response list using the specified handle
+ *
+ * @param handle - handle of server response
+ *
+ * @return
+ *     OCServerResponse*
+ */
 OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
 {
     OCServerResponse * out = NULL;
@@ -72,21 +208,52 @@ 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;
 }
 
+/**
+ * Add a server request to the server request list
+ *
+ * @param request - initialized server request that is created by this function
+ * @param coapID - ID of CoAP pdu
+ * @param delayedResNeeded - delayed response required 0=no 1=yes
+ * @param secured - secure endpoint 0=no 1=yes
+ * @param notificationFlag - //TODO: remove - does not appear to be used any longer
+ * @param method - RESTful method
+ * @param numRcvdVendorSpecificHeaderOptions - number of received vendor specific header options
+ * @param observationOption - value of observation option
+ * @param qos - request QOS
+ * @param query - request query
+ * @param rcvdVendorSpecificHeaderOptions - received vendor specific header options
+ * @param reqJSONPayload - request JSON payload
+ * @param requestToken - request token
+ * @param tokenLength - request token length
+ * @param resourceUrl - URL of resource
+ * @param reqTotalSize - total size of the request
+ * @param addressInfo - CA Address
+ * @param connectivityType - connection type
+ *
+ * @return
+ *     OCStackResult
+ */
 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, OCCoAPToken * requestToken,
-        OCDevAddr * requesterAddr, unsigned char * resourceUrl, uint32_t reqTotalSize)
+        char * reqJSONPayload, CAToken_t requestToken,
+        uint8_t tokenLength,
+        char * resourceUrl, size_t reqTotalSize,
+        CAAddress_t *addressInfo, CATransportType_t connectivityType)
 {
     OCServerRequest * serverRequest = NULL;
 
-    serverRequest = (OCServerRequest *) OCCalloc(1, sizeof(OCServerRequest) + reqTotalSize - 1);
+    //Note: OCServerRequest includes 1 byte for the JSON Payload.  payloadSize is calculated
+    //as the required length of the string, so this will result in enough room for the
+    //null terminator as well.
+    serverRequest = (OCServerRequest *) OCCalloc(1, sizeof(OCServerRequest) +
+        (reqTotalSize ? reqTotalSize : 1) - 1);
     VERIFY_NON_NULL(serverRequest);
 
     serverRequest->coapID = coapID;
@@ -101,33 +268,52 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
     serverRequest->qos = qos;
     serverRequest->ehResponseHandler = HandleSingleResponse;
     serverRequest->numResponses = 1;
+
     if(query)
     {
-        memcpy(serverRequest->query, query, strlen((const char *)query) + 1);
+        strncpy((char*)serverRequest->query,
+                (const char*)query, sizeof(serverRequest->query) - 1);
     }
+
     if(rcvdVendorSpecificHeaderOptions)
     {
         memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
             MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
     }
-    if(reqJSONPayload)
+    if(reqJSONPayload && reqTotalSize)
     {
-        memcpy((void *)serverRequest->reqJSONPayload, (void *)reqJSONPayload,
-            strlen((const char *)reqJSONPayload) + 1);
+        // destination is at least 1 greater than the source, so a NULL always exists in the
+        // last character
+        strncpy((char*)serverRequest->reqJSONPayload,
+                (const char*)reqJSONPayload, reqTotalSize - 1);
     }
     serverRequest->requestComplete = 0;
     if(requestToken)
     {
-        memcpy(&serverRequest->requestToken, requestToken, sizeof(OCCoAPToken));
+        // If tokenLength is zero, the return value depends on the
+        // particular library implementation (it may or may not be a null pointer).
+        if (tokenLength)
+        {
+            serverRequest->requestToken = (CAToken_t) OCMalloc(tokenLength);
+            VERIFY_NON_NULL(serverRequest->requestToken);
+            memcpy(serverRequest->requestToken, requestToken, tokenLength);
+        }
+
     }
-    if(requesterAddr)
+    serverRequest->tokenLength = tokenLength;
+
+    if(resourceUrl)
     {
-        memcpy(&serverRequest->requesterAddr, requesterAddr, sizeof(OCDevAddr));
+        strncpy((char*)serverRequest->resourceUrl,
+                (const char*)resourceUrl, sizeof(serverRequest->resourceUrl) - 1);
     }
-    if(resourceUrl)
+
+    if (addressInfo)
     {
-        memcpy(serverRequest->resourceUrl, resourceUrl, strlen((const char *)resourceUrl) + 1);
+        serverRequest->addressInfo = *addressInfo;
     }
+    serverRequest->connectivityType = connectivityType;
+
     *request = serverRequest;
     OC_LOG(INFO, TAG, PCF("Server Request Added!!"));
     LL_APPEND (serverRequestList, serverRequest);
@@ -143,39 +329,33 @@ exit:
     return OC_STACK_NO_MEMORY;
 }
 
-OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
-{
-    OCServerResponse * serverResponse = NULL;
-
-    serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
-    VERIFY_NON_NULL(serverResponse);
-
-    serverResponse->payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
-    VERIFY_NON_NULL(serverResponse->payload);
-    memset(serverResponse->payload, 0, sizeof(MAX_RESPONSE_LENGTH));
-
-    serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
-    serverResponse->requestHandle = requestHandle;
-
-    *response = serverResponse;
-    OC_LOG(INFO, TAG, PCF("Server Response Added!!"));
-    LL_APPEND (serverResponseList, serverResponse);
-    return OC_STACK_OK;
-
-exit:
-    if (serverResponse)
-    {
-        OCFree(serverResponse);
-        serverResponse = NULL;
-    }
-    *response = NULL;
-    return OC_STACK_NO_MEMORY;
-}
-
-// Form the OCEntityHandlerRequest struct
-OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest, OCRequestHandle request,
-        OCMethod method, OCResourceHandle resource, unsigned char * queryBuf, unsigned char * bufReqPayload,
-        uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction,
+/**
+ * Form the OCEntityHandlerRequest struct that is passed to a resource's entity handler
+ *
+ * @param entityHandlerRequest - pointer to the OCEntityHandlerRequest struct that is created
+ * @param request          - request handle
+ * @param method           - RESTful method
+ * @param resource         - resource handle
+ * @param queryBuf         - resource query of request
+ * @param bufReqPayload    - JSON payload of request
+ * @param numVendorOptions - number of vendor options
+ * @param vendorOptions    - vendor options
+ * @param observeAction    - observe action flag
+ * @param observeID        - observe ID
+ *
+ * @return
+ *     OCStackResult
+ */
+OCStackResult FormOCEntityHandlerRequest(
+        OCEntityHandlerRequest * entityHandlerRequest,
+        OCRequestHandle request,
+        OCMethod method,
+        OCResourceHandle resource,
+        char * queryBuf,
+        char * bufReqPayload,
+        uint8_t numVendorOptions,
+        OCHeaderOption * vendorOptions,
+        OCObserveAction observeAction,
         OCObservationId observeID)
 {
     if (entityHandlerRequest)
@@ -197,32 +377,11 @@ OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerR
     return OC_STACK_INVALID_PARAM;
 }
 
-void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
-{
-    OCServerResponse* tmp;
-    if(serverResponse)
-    {
-        LL_FOREACH(serverResponseList, tmp)
-        {
-            if (serverResponse == tmp)
-            {
-                DeleteServerResponse(tmp);
-                return;
-            }
-        }
-    }
-}
-
-void DeleteServerResponse(OCServerResponse * serverResponse)
-{
-    if(serverResponse) {
-        LL_DELETE(serverResponseList, serverResponse);
-        OCFree(serverResponse->payload);
-        OCFree(serverResponse);
-        OC_LOG(INFO, TAG, PCF("Server Response Removed!!"));
-    }
-}
-
+/**
+ * Find a server request in the server request list and delete
+ *
+ * @param serverRequest - server request to find and delete
+ */
 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
 {
     OCServerRequest* tmp;
@@ -239,80 +398,246 @@ void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
     }
 }
 
-void DeleteServerRequest(OCServerRequest * serverRequest)
+CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result)
 {
-    if(serverRequest) {
-        LL_DELETE(serverRequestList, serverRequest);
-        OCFree(serverRequest);
-        serverRequest = NULL;
-        OC_LOG(INFO, TAG, PCF("Server Request Removed!!"));
+    CAResponseResult_t caResult = CA_BAD_REQ;
+
+    switch (result)
+    {
+        case OC_EH_OK:
+            caResult = CA_SUCCESS;
+            break;
+        case OC_EH_ERROR:
+            caResult = CA_BAD_REQ;
+            break;
+        case OC_EH_RESOURCE_CREATED:
+            caResult = CA_CREATED;
+            break;
+        case OC_EH_RESOURCE_DELETED:
+            caResult = CA_DELETED;
+            break;
+        case OC_EH_SLOW:
+            caResult = CA_SUCCESS;
+            break;
+        case OC_EH_FORBIDDEN:
+            caResult = CA_BAD_REQ;
+            break;
+        case OC_EH_RESOURCE_NOT_FOUND:
+            caResult = CA_NOT_FOUND;
+            break;
+        default:
+            caResult = CA_BAD_REQ;
+            break;
     }
+    return caResult;
 }
 
+
+/**
+ * Handler function for sending a response from a single resource
+ *
+ * @param ehResponse - pointer to the response from the resource
+ *
+ * @return
+ *     OCStackResult
+ */
+
 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
 {
     OCStackResult result = OC_STACK_ERROR;
-    OCServerProtocolResponse protocolResponse = {0};
+    CARemoteEndpoint_t responseEndpoint = {};
+    CAResponseInfo_t responseInfo = {};
+    CAHeaderOption_t* optionsPointer = NULL;
 
     OC_LOG_V(INFO, TAG, "Inside HandleSingleResponse: %s", ehResponse->payload);
 
+    if(!ehResponse || !ehResponse->requestHandle)
+    {
+        return OC_STACK_ERROR;
+    }
+
+    if(ehResponse->payloadSize >= (MAX_RESPONSE_LENGTH))// - OC_JSON_PREFIX_LEN - OC_JSON_SUFFIX_LEN))
+    {
+        OC_LOG_V(ERROR, TAG, "Response payload size was too large.  Max is %hu, payload size was %hu",
+                (MAX_RESPONSE_LENGTH - OC_JSON_PREFIX_LEN - OC_JSON_SUFFIX_LEN), ehResponse->payloadSize);
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
-    // Format protocol response structure with data needed for
-    // sending the response
-    protocolResponse.qos = serverRequest->qos;
-
-    if((OCResource *)ehResponse->resourceHandle &&
-            ((OCResource *)ehResponse->resourceHandle)->resourceProperties == (OCResourceProperty) 0)
-    {
-        ehResponse->ehResult = OC_EH_RESOURCE_DELETED;
-    }
-    protocolResponse.result = EntityHandlerCodeToOCStackCode(ehResponse->ehResult);
-    protocolResponse.requesterAddr = &serverRequest->requesterAddr;
-    protocolResponse.requestToken = &serverRequest->requestToken;
-    protocolResponse.numSendVendorSpecificHeaderOptions = ehResponse->numSendVendorSpecificHeaderOptions;
-    protocolResponse.sendVendorSpecificHeaderOptions = ehResponse->sendVendorSpecificHeaderOptions;
-    protocolResponse.resourceUri = ehResponse->resourceUri;
-    protocolResponse.delayedResNeeded = serverRequest->delayedResNeeded;
-    protocolResponse.secured = serverRequest->secured;
-    protocolResponse.slowFlag = serverRequest->slowFlag;
-    protocolResponse.notificationFlag = serverRequest->notificationFlag;
-
-    //should we put the prefix and suffix here?
-    protocolResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
-    if(!protocolResponse.payload)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-    strcpy((char *)protocolResponse.payload, (const char *)OC_JSON_PREFIX);
-    strcat((char *)protocolResponse.payload, (const char *)ehResponse->payload);
-    strcat((char *)protocolResponse.payload, (const char *)OC_JSON_SUFFIX);
-    protocolResponse.payloadSize = strlen((const char *)protocolResponse.payload) + 1;
-    protocolResponse.resourceUri = ehResponse->resourceUri;
-
-    //revise the following
-    protocolResponse.coapID = serverRequest->coapID;
+
+    // Copy the address
+    responseEndpoint.resourceUri      = (CAURI_t) serverRequest->resourceUrl;
+    responseEndpoint.addressInfo      = serverRequest->addressInfo;
+    responseEndpoint.transportType    = serverRequest->connectivityType;
+    responseEndpoint.isSecured        = serverRequest->secured;
+
+    responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult);
+
+    if(serverRequest->notificationFlag && serverRequest->qos == OC_HIGH_QOS)
+    {
+        responseInfo.info.type = CA_MSG_CONFIRM;
+    }
+    else if(serverRequest->notificationFlag && serverRequest->qos != OC_HIGH_QOS)
+    {
+        responseInfo.info.type = CA_MSG_NONCONFIRM;
+    }
+    else if(!serverRequest->notificationFlag && !serverRequest->slowFlag &&
+            serverRequest->qos == OC_HIGH_QOS)
+    {
+        responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
+    }
+    else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
+            serverRequest->qos == OC_HIGH_QOS)
+    {
+        responseInfo.info.type = CA_MSG_CONFIRM;
+    }
+    else if(!serverRequest->notificationFlag)
+    {
+        responseInfo.info.type = CA_MSG_NONCONFIRM;
+    }
+
+    responseInfo.info.messageId = serverRequest->coapID;
+    responseInfo.info.token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
+    if (!responseInfo.info.token)
+    {
+        OC_LOG(FATAL, TAG, "Response Info Token is NULL");
+        return result;
+    }
+
+    memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
+    responseInfo.info.tokenLength = serverRequest->tokenLength;
+
     if(serverRequest->observeResult == OC_STACK_OK)
     {
-        protocolResponse.observationOption = serverRequest->observationOption;
+        responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
+    }
+    else
+    {
+        responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
+    }
+
+    if(responseInfo.info.numOptions > 0)
+    {
+        responseInfo.info.options = (CAHeaderOption_t *)
+                                      OCCalloc(responseInfo.info.numOptions,
+                                              sizeof(CAHeaderOption_t));
+
+        if(!responseInfo.info.options)
+        {
+            OC_LOG(FATAL, TAG, PCF("options is NULL"));
+            OCFree(responseInfo.info.token);
+            return OC_STACK_NO_MEMORY;
+        }
+
+        optionsPointer = responseInfo.info.options;
+
+        // 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)
+        {
+            responseInfo.info.options[0].protocolID = CA_COAP_ID;
+            responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
+            responseInfo.info.options[0].optionLength = sizeof(uint32_t);
+            memcpy(responseInfo.info.options[0].optionData,
+                    &(serverRequest->observationOption), sizeof(uint32_t));
+
+            // Point to the next header option before copying vender specific header options
+            optionsPointer += 1;
+        }
+
+        if (ehResponse->numSendVendorSpecificHeaderOptions)
+        {
+            memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
+                            sizeof(OCHeaderOption) *
+                            ehResponse->numSendVendorSpecificHeaderOptions);
+        }
+    }
+    else
+    {
+        responseInfo.info.options = NULL;
+    }
+
+    char payload[MAX_RESPONSE_LENGTH + OC_JSON_PREFIX_LEN + OC_JSON_SUFFIX_LEN] = {};
+
+    // Put the JSON prefix and suffix around the payload
+    strcpy(payload, (const char *)OC_JSON_PREFIX);
+    strncat(payload, (const char *)ehResponse->payload, ehResponse->payloadSize);
+    strcat(payload, (const char *)OC_JSON_SUFFIX);
+    responseInfo.info.payload = (CAPayload_t)payload;
+
+    #ifdef WITH_PRESENCE
+    //TODO: Add other connectivity types to CAConnTypes[] when enabled
+    CATransportType_t CAConnTypes[] = {CA_IPV4};
+    const char * connTypes[] = {"ip transport"};
+    int size = sizeof(CAConnTypes)/ sizeof(CATransportType_t);
+    CATransportType_t connType = responseEndpoint.transportType;
+    CAResult_t caResult = CA_STATUS_FAILED;
+    result = OC_STACK_OK;
+
+    //Sending response on all n/w interfaces
+    for(int i = 0; i < size; i++ )
+    {
+        responseEndpoint.transportType = (CATransportType_t)(connType & CAConnTypes[i]);
+        if(responseEndpoint.transportType)
+        {
+            //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
+            //response on all the n/w interfaces else it is set to OC_STACK_ERROR
+            caResult = CASendResponse(&responseEndpoint, &responseInfo);
+            if(caResult != CA_STATUS_OK)
+            {
+                OC_LOG_V(ERROR, TAG, "CASendResponse failed on %s", connTypes[i]);
+                result = CAResultToOCResult(caResult);
+            }
+            else
+            {
+                OC_LOG_V(INFO, TAG, "CASendResponse succeeded on %s", connTypes[i]);
+            }
+        }
+    }
+    #else
+    CAResult_t caResult = CASendResponse(&responseEndpoint, &responseInfo);
+    if(caResult != CA_STATUS_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("CASendResponse failed"));
+        result = CAResultToOCResult(caResult);
     }
     else
     {
-        protocolResponse.observationOption = OC_OBSERVE_NO_OPTION;
+        result = OC_STACK_OK;
     }
-    // Make call to OCCoAP layer
-    result = OCDoCoAPResponse(&protocolResponse);
+    #endif
 
-    OCFree(protocolResponse.payload);
+    OCFree(responseInfo.info.token);
+    OCFree(responseInfo.info.options);
     //Delete the request
     FindAndDeleteServerRequest(serverRequest);
     return result;
 }
 
+/**
+ * Handler function for sending a response from multiple resources, such as a collection.
+ * Aggregates responses from multiple resource until all responses are received then sends the
+ * concatenated response
+ *
+ * TODO: Need to add a timeout in case a (remote?) resource does not respond
+ *
+ * @param ehResponse - pointer to the response from the resource
+ *
+ * @return
+ *     OCStackResult
+ */
 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 {
     OCStackResult stackRet = OC_STACK_ERROR;
     OCServerRequest * serverRequest = NULL;
     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);
 
@@ -334,16 +659,22 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
             VERIFY_NON_NULL(serverResponse->payload);
         }
 
-        if((serverResponse->remainingPayloadSize >= ehResponse->payloadSize + 1 &&
-                serverRequest->numResponses == 1) ||
-                (serverResponse->remainingPayloadSize >= ehResponse->payloadSize + 2 &&
-                        serverRequest->numResponses > 1))
+        // If there is more than 1 response, then we need to allow for a null-termination
+        // in the server response payload buffer AND the JSON response separator
+        bufferNeeded = ehResponse->payloadSize + 1;
+        if (serverRequest->numResponses > 1)
         {
-            OC_LOG(INFO, TAG, PCF("There is room in response buffer"));
+            bufferNeeded += strlen(OC_JSON_SEPARATOR_STR);
+        }
+        if(serverResponse->remainingPayloadSize >= bufferNeeded)
+        {
+            OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
             // append
-            snprintf((char *)serverResponse->payload, serverResponse->remainingPayloadSize, "%s%s", (char *)serverResponse->payload, (char *)ehResponse->payload);
+            strncat((char *)serverResponse->payload,
+                    (char *)ehResponse->payload,
+                    serverResponse->remainingPayloadSize);
             OC_LOG_V(INFO, TAG, "Current aggregated response  ...%s", serverResponse->payload);
-            serverResponse->remainingPayloadSize -= ehResponse->payloadSize;
+            serverResponse->remainingPayloadSize -= strlen((char *)ehResponse->payload);
             (serverRequest->numResponses)--;
             if(serverRequest->numResponses == 0)
             {
@@ -357,17 +688,18 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
             }
             else
             {
-                OC_LOG(INFO, TAG, PCF("More response fragment to come"));
-                // TODO: we should consider using strcat rather than setting a char by char here!
-                snprintf((char *)serverResponse->payload, serverResponse->remainingPayloadSize, "%s%c", (char *)serverResponse->payload,OC_JSON_SEPARATOR);
+                OC_LOG(INFO, TAG, PCF("More response fragments to come"));
+                strncat((char *)serverResponse->payload,
+                        OC_JSON_SEPARATOR_STR,
+                        serverResponse->remainingPayloadSize);
                 OC_LOG_V(INFO, TAG, "Current aggregated response  ...%s", serverResponse->payload);
-                (serverResponse->remainingPayloadSize)--;
+                serverResponse->remainingPayloadSize -= strlen(OC_JSON_SEPARATOR_STR);
                 stackRet = OC_STACK_OK;
             }
         }
         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);
@@ -377,3 +709,4 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 exit:
     return stackRet;
 }
+
index b2aec91..2ccd77a 100644 (file)
 //-----------------------------------------------------------------------------
 // Includes
 //-----------------------------------------------------------------------------
+
+// Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2001 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2001 base specification,
+// Refer http://pubs.opengroup.org/onlinepubs/009695399/
 #define _POSIX_C_SOURCE 200112L
 #include <string.h>
+#include <ctype.h>
 
 #include "ocstack.h"
 #include "ocstackinternal.h"
 #include "occlientcb.h"
 #include "ocobserve.h"
 #include "ocrandom.h"
-#include "debug.h"
-#include "occoap.h"
 #include "ocmalloc.h"
 #include "ocserverrequest.h"
+#include "ocsecurityinternal.h"
+
+#include "cacommon.h"
+#include "cainterface.h"
+
+#ifdef WITH_ARDUINO
+#include "Time.h"
+#else
+#include <sys/time.h>
+#endif
+#include "coap_time.h"
+#include "utlist.h"
+#include "pdu.h"
+
+#ifndef ARDUINO
+#include <arpa/inet.h>
+#endif
+
+#ifndef UINT32_MAX
+#define UINT32_MAX   (0xFFFFFFFFUL)
+#endif
 
 //-----------------------------------------------------------------------------
 // Typedefs
 //-----------------------------------------------------------------------------
-typedef enum {
-    OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS
+typedef enum
+{
+    OC_STACK_UNINITIALIZED = 0,
+    OC_STACK_INITIALIZED,
+    OC_STACK_UNINIT_IN_PROGRESS
 } OCStackState;
 
 #ifdef WITH_PRESENCE
-typedef enum {
-    OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED
+typedef enum
+{
+    OC_PRESENCE_UNINITIALIZED = 0,
+    OC_PRESENCE_INITIALIZED
 } OCPresenceState;
 #endif
 
@@ -55,29 +87,393 @@ typedef enum {
 static OCStackState stackState = OC_STACK_UNINITIALIZED;
 
 OCResource *headResource = NULL;
+static OCResource *tailResource = NULL;
 #ifdef WITH_PRESENCE
 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
 static PresenceResource presenceResource;
-uint8_t PresenceTimeOutSize = 0;
-uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
+static uint8_t PresenceTimeOutSize = 0;
+static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
 #endif
 
-OCMode myStackMode;
+static OCMode myStackMode;
 OCDeviceEntityHandler defaultDeviceHandler;
 
+
 //-----------------------------------------------------------------------------
 // Macros
 //-----------------------------------------------------------------------------
 #define TAG  PCF("OCStack")
+#define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
+            {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
              TAG, PCF(#arg " is NULL")); return (retVal); } }
+#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
+    goto exit;} }
 
 //TODO: we should allow the server to define this
 #define MAX_OBSERVE_AGE (0x2FFFFUL)
+
+#define MILLISECONDS_PER_SECOND   (1000)
+/**
+ * Parse the presence payload and extract various parameters.
+ * Note: Caller should invoke OCFree after done with resType pointer.
+ *
+ * @param payload Presence payload.
+ * @param seqNum Sequence number.
+ * @param maxAge Time To Live (in seconds).
+ * @param resType Resource type.
+ */
+// TODO: Not sure if I agree with this.  I think it should be static but it is called in
+// stack/test/stacktests.cpp, not included via a header file.  If we intend to allow it
+// to be called externally, we should change the name to OCParsePresencePayload and make
+// it part of the official public API.  But can't change now due to current API freeze.
+// Another option might be to make non-API utility functions for doing stuff like this.
+void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType);
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+
+/**
+ * Generate handle of OCDoResource invocation for callback management.
+ *
+ * @return Generated OCDoResource handle.
+ */
+static OCDoHandle GenerateInvocationHandle();
+
+/**
+ * Initialize resource data structures, variables, etc.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult initResources();
+
+/**
+ * Add a resource to the end of the linked list of resources.
+ *
+ * @param resource Resource to be added
+ */
+static void insertResource(OCResource *resource);
+
+/**
+ * Find a resource in the linked list of resources.
+ *
+ * @param resource Resource to be found.
+ * @return Pointer to resource that was found in the linked list or NULL if the resource was not
+ *         found.
+ */
+static OCResource *findResource(OCResource *resource);
+
+/**
+ * Insert a resource type into a resource's resource type linked list.
+ * If resource type already exists, it will not be inserted and the
+ * resourceType will be free'd.
+ * resourceType->next should be null to avoid memory leaks.
+ * Function returns silently for null args.
+ *
+ * @param resource Resource where resource type is to be inserted.
+ * @param resourceType Resource type to be inserted.
+ */
+static void insertResourceType(OCResource *resource,
+        OCResourceType *resourceType);
+
+/**
+ * Get a resource type at the specified index within a resource.
+ *
+ * @param handle Handle of resource.
+ * @param index Index of resource type.
+ *
+ * @return Pointer to resource type if found, NULL otherwise.
+ */
+static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
+        uint8_t index);
+
+/**
+ * Insert a resource interface into a resource's resource interface linked list.
+ * If resource interface already exists, it will not be inserted and the
+ * resourceInterface will be free'd.
+ * resourceInterface->next should be null to avoid memory leaks.
+ *
+ * @param resource Resource where resource interface is to be inserted.
+ * @param resourceInterface Resource interface to be inserted.
+ */
+static void insertResourceInterface(OCResource *resource,
+        OCResourceInterface *resourceInterface);
+
+/**
+ * Get a resource interface at the specified index within a resource.
+ *
+ * @param handle Handle of resource.
+ * @param index Index of resource interface.
+ *
+ * @return Pointer to resource interface if found, NULL otherwise.
+ */
+static OCResourceInterface *findResourceInterfaceAtIndex(
+        OCResourceHandle handle, uint8_t index);
+
+/**
+ * Delete all of the dynamically allocated elements that were created for the resource type.
+ *
+ * @param resourceType Specified resource type.
+ */
+static void deleteResourceType(OCResourceType *resourceType);
+
+/**
+ * Delete all of the dynamically allocated elements that were created for the resource interface.
+ *
+ * @param resourceInterface Specified resource interface.
+ */
+static void deleteResourceInterface(OCResourceInterface *resourceInterface);
+
+/**
+ * Delete all of the dynamically allocated elements that were created for the resource.
+ *
+ * @param resource Specified resource.
+ */
+static void deleteResourceElements(OCResource *resource);
+
+/**
+ * Delete resource specified by handle.  Deletes resource and all resourcetype and resourceinterface
+ * linked lists.
+ *
+ * @param handle Handle of resource to be deleted.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult deleteResource(OCResource *resource);
+
+/**
+ * Delete all of the resources in the resource list.
+ */
+static void deleteAllResources();
+
+/**
+ * Increment resource sequence number.  Handles rollover.
+ *
+ * @param resPtr Pointer to resource.
+ */
+static void incrementSequenceNumber(OCResource * resPtr);
+
+/**
+ * Verify the lengths of the URI and the query separately.
+ *
+ * @param inputUri Input URI and query.
+ * @param uriLen The length of the initial URI with query.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult verifyUriQueryLength(const char * inputUri,
+        uint16_t uriLen);
+
+/**
+ * Determine if a request/response must be sent in a block transfer because it is too large to be
+ * sent in a single PDU.  This function can be used for either a request or a response.
+ * Note:  Either the request or response parameter should be non-NULL (i.e. only one, not both).
+ *
+ * @param request  NULL or pointer to request.
+ * @param response NULL or pointer to response.
+ * @param size     0 or size of the request/response.  If 0, strlen is used for determining
+ *                 the length of the request/response.
+ *
+ * @return
+ *    false - packet transfer NOT required (i.e. normal request/response).
+ *    true  - packet transfer required (i.e. block transfer needed).
+ */
+static bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size);
+
+/**
+ * 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 query part of the URI.
+ * @param resourceType The resource type to be populated; pass by reference.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult getResourceType(const char * query, char** resourceType);
+
+/*
+ * Attempts to initialize every network interface that the CA Layer might have compiled in.
+ *
+ * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
+ * return something other than @ref CA_STATUS_OK, then this function fails.
+ *
+ * @return ::CA_STATUS_OK on success, some other value upon failure.
+ */
+static CAResult_t OCSelectNetwork();
+
+/**
+ * Get the CoAP ticks after the specified number of milli-seconds.
+ *
+ * @param afterMilliSeconds Milli-seconds.
+ * @return
+ *     CoAP ticks
+ */
+static uint32_t GetTicks(uint32_t afterMilliSeconds);
+
+/**
+ * This method is used to create the IPv4 dev_addr structure.
+ * Builds a socket interface address using IP address and port number.
+ * TODO: Remove in future. Temporary helper function.
+ *
+ * @param a IPv4 octet 0.
+ * @param b IPv4 octet 1.
+ * @param c IPv4 octet 2.
+ * @param d IPv4 octet 3.
+ * @param port Port number.
+ * @param ipAddr - IPv4 address.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
+        uint16_t port, OCDevAddr *ipAddr);
+
+/**
+ * Convert CAResponseResult_t to OCStackResult.
+ *
+ * @param caCode CAResponseResult_t code.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
+
+/**
+ * Convert OCStackResult to CAResponseResult_t.
+ *
+ * @param caCode OCStackResult code.
+ * @return ::CA_SUCCESS on success, some other value upon failure.
+ */
+static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode);
+
+/**
+ * Convert OCConnectivityType to CATransportType_t.
+ *
+ * @param ocConType OCConnectivityType input.
+ * @param caConType CATransportType_t output.
+ * @return  ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult OCToCATransportType(OCConnectivityType ocConType,
+        CATransportType_t* caConType);
+
+/**
+ * Convert CATransportType_t to OCConnectivityType.
+ *
+ * @param caConType CATransportType_t input.
+ * @param ocConType OCConnectivityType output.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult CAToOCConnectivityType(CATransportType_t caConType,
+        OCConnectivityType *ocConType);
+
+/**
+ * Update response.addr appropriately from endPoint.addressInfo.
+ *
+ * @param address OCDevAddr output.
+ * @param endPoint CARemoteEndpoint_t input.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint);
+
+/**
+ * Handle response from presence request.
+ *
+ * @param endPoint CA remote endpoint.
+ * @param responseInfo CA response info.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
+        const CAResponseInfo_t* responseInfo);
+
+/**
+ * This function will be called back by CA layer when a response is received.
+ *
+ * @param endPoint CA remote endpoint.
+ * @param responseInfo CA response info.
+ */
+static void HandleCAResponses(const CARemoteEndpoint_t* endPoint,
+        const CAResponseInfo_t* responseInfo);
+
+/**
+ * This function will be called back by CA layer when a request is received.
+ *
+ * @param endPoint CA remote endpoint.
+ * @param requestInfo CA request info.
+ */
+static void HandleCARequests(const CARemoteEndpoint_t* endPoint,
+        const CARequestInfo_t* requestInfo);
+
+/**
+ * Extract query from a URI.
+ *
+ * @param uri Full URI with query.
+ * @param query Pointer to string that will contain query.
+ * @param newURI Pointer to string that will contain URI.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
+
+/**
+ * Finds a resource type in an OCResourceType link-list.
+ *
+ * @param resourceTypeList The link-list to be searched through.
+ * @param resourceTypeName The key to search for.
+ *
+ * @return Resource type that matches the key (ie. resourceTypeName) or
+ *      NULL if there is either an invalid parameter or this function was unable to find the key.
+ */
+static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
+        const char * resourceTypeName);
+
+/**
+ * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
+ * TTL will be set to maxAge.
+ *
+ * @param cbNode Callback Node for which presence ttl is to be reset.
+ * @param maxAge New value of ttl in seconds.
+
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
+
 //-----------------------------------------------------------------------------
-// Externs
+// Internal functions
 //-----------------------------------------------------------------------------
-extern void DeinitOCSecurityInfo();
+
+uint32_t GetTicks(uint32_t afterMilliSeconds)
+{
+    coap_tick_t now;
+    coap_ticks(&now);
+
+    // Guard against overflow of uint32_t
+    if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
+                             COAP_TICKS_PER_SECOND)
+    {
+        return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
+    }
+    else
+    {
+        return UINT32_MAX;
+    }
+}
+
+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, PCF("Invalid argument"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    ipAddr->addr[0] = a;
+    ipAddr->addr[1] = b;
+    ipAddr->addr[2] = c;
+    ipAddr->addr[3] = d;
+    ipAddr->addr[4] = (uint8_t)port;
+    ipAddr->addr[5] = (uint8_t)(port >> 8);
+
+    return OC_STACK_OK;
+}
 
 //-----------------------------------------------------------------------------
 // Internal API function
@@ -85,17 +481,17 @@ extern void DeinitOCSecurityInfo();
 
 // This internal function is called to update the stack with the status of
 // observers and communication failures
-OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
+OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
 {
     OCStackResult result = OC_STACK_ERROR;
     ResourceObserver * observer = NULL;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     switch(status)
     {
     case OC_OBSERVER_NOT_INTERESTED:
         OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore"));
-        observer = GetObserverUsingToken (token);
+        observer = GetObserverUsingToken (token, tokenLength);
         if(observer)
         {
             result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL,
@@ -108,7 +504,7 @@ OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
             observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
         }
         //observer is not observing anymore
-        result = DeleteObserverUsingToken (token);
+        result = DeleteObserverUsingToken (token, tokenLength);
         if(result == OC_STACK_OK)
         {
             OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
@@ -123,7 +519,7 @@ OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
         //observer is still interested
         OC_LOG(DEBUG, TAG, PCF("observer is interested in our \
                 notifications, reset the failedCount"));
-        observer = GetObserverUsingToken(token);
+        observer = GetObserverUsingToken (token, tokenLength);
         if(observer)
         {
             observer->forceHighQos = 0;
@@ -138,7 +534,7 @@ OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
     case OC_OBSERVER_FAILED_COMM:
         //observer is not reachable
         OC_LOG(DEBUG, TAG, PCF("observer is unreachable"));
-        observer = GetObserverUsingToken(token);
+        observer = GetObserverUsingToken (token, tokenLength);
         if(observer)
         {
             if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
@@ -152,7 +548,7 @@ OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
                 }
                 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest);
                 //observer is unreachable
-                result = DeleteObserverUsingToken (token);
+                result = DeleteObserverUsingToken (token, tokenLength);
                 if(result == OC_STACK_OK)
                 {
                     OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
@@ -179,99 +575,1046 @@ OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status)
         }
     return result;
 }
-
-//This function will be called back by occoap layer when a request is received
-OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
+OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
 {
-    OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
+    OCStackResult ret = OC_STACK_ERROR;
 
-    OCStackResult result = OC_STACK_ERROR;
-    ResourceHandling resHandling;
-    OCResource *resource;
-
-    OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken);
-    if(!request)
+    switch(caCode)
     {
-        OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
-        result = AddServerRequest(&request, protocolRequest->coapID,
-                protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
-                protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
-                protocolRequest->observationOption, protocolRequest->qos,
-                protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
-                protocolRequest->reqJSONPayload, &protocolRequest->requestToken,
-                &protocolRequest->requesterAddr, protocolRequest->resourceUrl,
-                protocolRequest->reqTotalSize);
-        if (OC_STACK_OK != result)
-        {
-            OC_LOG(ERROR, TAG, PCF("Error adding server request"));
-            return result;
-        }
-        VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
-
-        if(!protocolRequest->reqMorePacket)
-        {
-            request->requestComplete = 1;
-        }
+        case CA_SUCCESS:
+            ret = OC_STACK_OK;
+            break;
+        case CA_CREATED:
+            ret = OC_STACK_RESOURCE_CREATED;
+            break;
+        case CA_DELETED:
+            ret = OC_STACK_RESOURCE_DELETED;
+            break;
+        case CA_BAD_REQ:
+            ret = OC_STACK_INVALID_QUERY;
+            break;
+        case CA_BAD_OPT:
+            ret = OC_STACK_INVALID_OPTION;
+            break;
+        case CA_NOT_FOUND:
+            ret = OC_STACK_NO_RESOURCE;
+            break;
+        case CA_RETRANSMIT_TIMEOUT:
+            ret = OC_STACK_COMM_ERROR;
+            break;
+        default:
+            break;
     }
-    else
+    return ret;
+}
+
+CAResponseResult_t OCToCAStackResult(OCStackResult ocCode)
+{
+    CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
+
+    switch(ocCode)
     {
-        OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
+        case OC_STACK_OK:
+            ret = CA_SUCCESS;
+            break;
+        case OC_STACK_RESOURCE_CREATED:
+            ret = CA_CREATED;
+            break;
+        case OC_STACK_RESOURCE_DELETED:
+            ret = CA_DELETED;
+            break;
+        case OC_STACK_INVALID_QUERY:
+            ret = CA_BAD_REQ;
+            break;
+        case OC_STACK_INVALID_OPTION:
+            ret = CA_BAD_OPT;
+            break;
+        case OC_STACK_NO_RESOURCE:
+            ret = CA_NOT_FOUND;
+            break;
+        case OC_STACK_COMM_ERROR:
+            ret = CA_RETRANSMIT_TIMEOUT;
+            break;
+        default:
+            break;
     }
+    return ret;
+}
 
-    if(request->requestComplete)
+OCStackResult OCToCATransportType(OCConnectivityType ocConType, CATransportType_t* caConType)
+{
+    OCStackResult ret = OC_STACK_OK;
+
+    switch(ocConType)
+    {
+        case OC_IPV4:
+            *caConType = CA_IPV4;
+            break;
+        case OC_IPV6:
+            *caConType = CA_IPV6;
+            break;
+        case OC_EDR:
+            *caConType = CA_EDR;
+            break;
+        case OC_LE:
+            *caConType = CA_LE;
+            break;
+        case OC_ALL:
+            // Currently OC_ALL represents IPv4
+            // Add other connectivity types as they are enabled in future
+            *caConType = (CATransportType_t) (CA_IPV4);
+            break;
+        default:
+            ret = OC_STACK_INVALID_PARAM;
+            break;
+    }
+    return ret;
+}
+
+OCStackResult CAToOCConnectivityType(CATransportType_t caConType, OCConnectivityType *ocConType)
+{
+    OCStackResult ret = OC_STACK_OK;
+
+    switch(caConType)
+    {
+        case CA_IPV4:
+            *ocConType = OC_IPV4;
+            break;
+        case CA_IPV6:
+            *ocConType = OC_IPV6;
+            break;
+        case CA_EDR:
+            *ocConType = OC_EDR;
+            break;
+        case CA_LE:
+            *ocConType = OC_LE;
+            break;
+        default:
+            ret = OC_STACK_INVALID_PARAM;
+            break;
+    }
+    return ret;
+}
+
+OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    char * tok = NULL;
+    char * savePtr = NULL;
+    char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
+    if(!cpAddress)
+    {
+        ret = OC_STACK_NO_MEMORY;
+        goto exit;
+    }
+    memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
+            strlen(endPoint->addressInfo.IP.ipAddress) + 1);
+
+    // Grabs the first three numbers from the IPv4 address and replaces dots
+    for(int i=0; i<4; i++)
+    {
+        tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
+
+        if(!tok)
+        {
+            ret = OC_STACK_ERROR;
+            goto exit;
+        }
+        address->addr[i] = atoi(tok);
+    }
+
+    memcpy(&address->addr[4], &endPoint->addressInfo.IP.port, sizeof(uint16_t));
+    ret = OC_STACK_OK;
+
+exit:
+    OCFree(cpAddress);
+    return ret;
+}
+
+static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
+{
+    uint32_t lowerBound  = 0;
+    uint32_t higherBound = 0;
+
+    if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
+
+    cbNode->presence->TTL = maxAgeSeconds;
+
+    for(int index = 0; index < PresenceTimeOutSize; index++)
+    {
+        // Guard against overflow
+        if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
+                                     * 100)
+        {
+            lowerBound = GetTicks((PresenceTimeOut[index] *
+                                  cbNode->presence->TTL *
+                                  MILLISECONDS_PER_SECOND)/100);
+        }
+        else
+        {
+            lowerBound = GetTicks(UINT32_MAX);
+        }
+
+        if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
+                                     * 100)
+        {
+            higherBound = GetTicks((PresenceTimeOut[index + 1] *
+                                   cbNode->presence->TTL *
+                                   MILLISECONDS_PER_SECOND)/100);
+        }
+        else
+        {
+            higherBound = GetTicks(UINT32_MAX);
+        }
+
+        cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
+
+        OC_LOG_V(DEBUG, TAG, "lowerBound timeout  %d", lowerBound);
+        OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
+        OC_LOG_V(DEBUG, TAG, "timeOut entry  %d", cbNode->presence->timeOut[index]);
+    }
+
+    cbNode->presence->TTLlevel = 0;
+
+    OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
+    return OC_STACK_OK;
+}
+
+void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
+{
+    char * tok = NULL;
+    char * savePtr = NULL;
+    // The format of the payload is {"oc":[%u:%u:%s]}
+    // %u : sequence number,
+    // %u : max age
+    // %s : Resource Type (Optional)
+
+    if (!payload || !seqNum || !maxAge || !resType)
+    {
+        return;
+    }
+    tok = strtok_r(payload, "[:]}", &savePtr);
+    payload[strlen(payload)] = ':';
+
+    //Retrieve sequence number
+    tok = strtok_r(NULL, "[:]}", &savePtr);
+    if(tok == NULL)
+    {
+        return;
+    }
+    payload[strlen((char *)payload)] = ':';
+    *seqNum = (uint32_t) atoi(tok);
+
+    //Retrieve MaxAge
+    tok = strtok_r(NULL, "[:]}", &savePtr);
+    if(tok == NULL)
+    {
+        return;
+    }
+    *maxAge = (uint32_t) atoi(tok);
+
+    //Retrieve ResourceType
+    tok = strtok_r(NULL, "[:]}",&savePtr);
+    if(tok == NULL)
+    {
+        return;
+    }
+
+    *resType = (char *)OCMalloc(strlen(tok) + 1);
+    if(!*resType)
+    {
+        return;
+    }
+    payload[strlen((char *)payload)] = ':';
+    strcpy(*resType, tok);
+    OC_LOG_V(DEBUG, TAG, "resourceTypeName %s", *resType);
+
+    payload[strlen((char *)payload)] = ']';
+}
+
+static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
+                            const CAResponseInfo_t* responseInfo)
+{
+    OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
+    ClientCB * cbNode = NULL;
+    char *resourceTypeName = NULL;
+    OCClientResponse response = {};
+    OCDevAddr address = {};
+    OCStackResult result = OC_STACK_ERROR;
+    uint32_t maxAge = 0;
+
+    char *fullUri = NULL;
+    char *ipAddress = NULL;
+    int presenceSubscribe = 0;
+    int multicastPresenceSubscribe = 0;
+    size_t addressLen = 0;
+
+    if (responseInfo->result != CA_SUCCESS)
+    {
+        OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
+        return OC_STACK_ERROR;
+    }
+
+    fullUri = (char *) OCMalloc(MAX_URI_LENGTH);
+
+    if(!fullUri)
+    {
+        OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
+        result = OC_STACK_NO_MEMORY;
+        goto exit;
+    }
+
+    addressLen = strlen(endPoint->addressInfo.IP.ipAddress);
+    ipAddress = (char *) OCMalloc(addressLen + 1);
+
+    if(!ipAddress)
+    {
+        OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
+        result = OC_STACK_NO_MEMORY;
+        goto exit;
+    }
+
+    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, 0, NULL, fullUri);
+
+    if(cbNode)
+    {
+        presenceSubscribe = 1;
+    }
+    else
+    {
+        snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", OC_MULTICAST_IP, OC_MULTICAST_PORT,
+                                                endPoint->resourceUri);
+        cbNode = GetClientCB(NULL, 0, NULL, fullUri);
+        if(cbNode)
+        {
+            multicastPresenceSubscribe = 1;
+        }
+    }
+
+    if(!presenceSubscribe && !multicastPresenceSubscribe)
+    {
+        OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
+        goto exit;
+    }
+
+    // No payload to the application in case of presence
+    response.resJSONPayload = NULL;
+    response.result = OC_STACK_OK;
+
+    result = UpdateResponseAddr(&address, endPoint);
+    if(result != OC_STACK_OK)
+    {
+        goto exit;
+    }
+
+    response.addr = &address;
+
+    result = CAToOCConnectivityType(endPoint->transportType, &(response.connType));
+    if(result != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
+        goto exit;
+    }
+
+    if(responseInfo->info.payload)
+    {
+        parsePresencePayload(responseInfo->info.payload,
+                                &(response.sequenceNumber),
+                                &maxAge,
+                                &resourceTypeName);
+    }
+
+    if(presenceSubscribe)
+    {
+        if(cbNode->sequenceNumber == response.sequenceNumber)
+        {
+            if (cbNode->presence)
+            {
+                OC_LOG(INFO, TAG, PCF("No presence change. Updating TTL."));
+
+                result = ResetPresenceTTL(cbNode, maxAge);
+
+                if (result != OC_STACK_OK)
+                {
+                    OC_LOG_V(ERROR, TAG, "ResetPresenceTTL failed with error: %u", result);
+                }
+            }
+            else
+            {
+                OC_LOG(INFO, TAG, PCF("Not subscribed to presence."));
+            }
+
+            goto exit;
+        }
+        if(maxAge == 0)
+        {
+            OC_LOG(INFO, TAG, PCF("Stopping presence"));
+            response.result = OC_STACK_PRESENCE_STOPPED;
+            if(cbNode->presence)
+            {
+                OCFree(cbNode->presence->timeOut);
+                OCFree(cbNode->presence);
+                cbNode->presence = NULL;
+            }
+        }
+        else
+        {
+            if(!cbNode->presence)
+            {
+                cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
+                if(!(cbNode->presence))
+                {
+                    OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
+                    result = OC_STACK_NO_MEMORY;
+                    goto exit;
+                }
+
+                VERIFY_NON_NULL_V(cbNode->presence);
+                cbNode->presence->timeOut = NULL;
+                cbNode->presence->timeOut = (uint32_t *)
+                        OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
+                if(!(cbNode->presence->timeOut)){
+                    OC_LOG(ERROR, TAG,
+                                  PCF("Could not allocate memory for cbNode->presence->timeOut"));
+                    OCFree(cbNode->presence);
+                    result = OC_STACK_NO_MEMORY;
+                    goto exit;
+                }
+            }
+
+            ResetPresenceTTL(cbNode, maxAge);
+
+            OC_LOG(INFO, TAG, PCF("Presence changed, calling up the stack"));
+            cbNode->sequenceNumber = response.sequenceNumber;
+
+            // Ensure that a filter is actually applied.
+            if(resourceTypeName && cbNode->filterResourceType)
+            {
+                if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
+                {
+                    goto exit;
+                }
+            }
+        }
+    }
+    else
+    {
+        // This is the multicast case
+
+        OCMulticastNode* mcNode = NULL;
+        mcNode = GetMCPresenceNode(fullUri);
+
+        if(mcNode != NULL)
+        {
+            if(mcNode->nonce == response.sequenceNumber)
+            {
+                OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
+                goto exit;
+            }
+            mcNode->nonce = response.sequenceNumber;
+
+            if(maxAge == 0)
+            {
+                OC_LOG(INFO, TAG, PCF("Stopping presence"));
+                response.result = OC_STACK_PRESENCE_STOPPED;
+            }
+        }
+        else
+        {
+            uint32_t uriLen = strlen(fullUri);
+            char* uri = (char *) OCMalloc(uriLen + 1);
+            if(uri)
+            {
+                memcpy(uri, fullUri, (uriLen + 1));
+            }
+            else
+            {
+                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, uri, response.sequenceNumber);
+            if(result != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, TAG,
+                    PCF("Unable to add Multicast Presence Node"));
+                OCFree(uri);
+                goto exit;
+            }
+        }
+
+        // Ensure that a filter is actually applied.
+        if(resourceTypeName && cbNode->filterResourceType)
+        {
+            if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
+            {
+                goto exit;
+            }
+        }
+    }
+
+    cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
+
+    if (cbResult == OC_STACK_DELETE_TRANSACTION)
+    {
+        FindAndDeleteClientCB(cbNode);
+    }
+
+exit:
+OCFree(fullUri);
+OCFree(ipAddress);
+OCFree(resourceTypeName);
+return result;
+}
+
+void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+{
+    OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
+
+    if(NULL == endPoint)
+    {
+        OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
+        return;
+    }
+
+    if(NULL == responseInfo)
+    {
+        OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
+        return;
+    }
+
+    if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
+    {
+        HandlePresenceResponse(endPoint, responseInfo);
+        return;
+    }
+
+    ClientCB *cbNode = GetClientCB(responseInfo->info.token,
+            responseInfo->info.tokenLength, NULL, NULL);
+    OC_LOG_V(DEBUG, TAG, "Response has the token %s", responseInfo->info.token);
+    ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
+            responseInfo->info.tokenLength);
+
+    if(cbNode)
+    {
+        OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token"));
+        if(responseInfo->result == CA_EMPTY)
+        {
+            OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
+            // We do not have a case for the client to receive a RESET
+            if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
+            {
+                //This is the case of receiving an ACK on a request to a slow resource!
+                OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
+                //TODO: should we inform the client
+                //      app that at least the request was received at the server?
+            }
+        }
+        else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
+        {
+            OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
+            OC_LOG(INFO, TAG, PCF("Calling into application address space"));
+            OCClientResponse response = {};
+            OCDevAddr address = {};
+            OCStackResult result = UpdateResponseAddr(&address, endPoint);
+            if(result != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr"));
+                return;
+            }
+
+            result = UpdateResponseAddr(&address, endPoint);
+            if(result != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
+                return;
+            }
+            response.addr = &address;
+
+            response.result = CAToOCStackResult(responseInfo->result);
+            cbNode->callBack(cbNode->context,
+                    cbNode->handle, &response);
+            FindAndDeleteClientCB(cbNode);
+        }
+        else
+        {
+            OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
+            OC_LOG(INFO, TAG, PCF("Calling into application address space"));
+            OCClientResponse response = {};
+            OCDevAddr address = {};
+
+            OCStackResult result = UpdateResponseAddr(&address, endPoint);
+            if(result != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr"));
+                return;
+            }
+            response.addr = &address;
+            // Populate the connectivity type. If this is a discovery response,
+            // the resource that will be constructed from this response will make
+            // further API calls from this interface.
+            result = CAToOCConnectivityType(endPoint->transportType,
+                                    &(response.connType));
+            if(result != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
+                return;
+            }
+
+            response.result = CAToOCStackResult(responseInfo->result);
+            response.resJSONPayload = (const char*)responseInfo->info.payload;
+            response.numRcvdVendorSpecificHeaderOptions = 0;
+            if(responseInfo->info.numOptions > 0)
+            {
+                int start = 0;
+                //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
+                if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
+                {
+                    memcpy (&(response.sequenceNumber),
+                            &(responseInfo->info.options[0].optionData), sizeof(uint32_t));
+                    response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
+                    start = 1;
+                }
+                else
+                {
+                    response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
+                }
+
+                if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
+                {
+                    OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS"));
+                    return;
+                }
+
+                for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
+                {
+                    memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
+                            &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
+                }
+            }
+
+            if (cbNode->method == OC_REST_OBSERVE &&
+                response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
+                response.sequenceNumber <= cbNode->sequenceNumber)
+            {
+                OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"),
+                                                 response.sequenceNumber);
+            }
+            else
+            {
+                OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
+                                                                        cbNode->handle,
+                                                                        &response);
+                cbNode->sequenceNumber = response.sequenceNumber;
+
+                if (appFeedback == OC_STACK_DELETE_TRANSACTION)
+                {
+                    FindAndDeleteClientCB(cbNode);
+                }
+                else
+                {
+                    // To keep discovery callbacks active.
+                    cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
+                                            MILLISECONDS_PER_SECOND);
+                }
+            }
+
+            //Need to send ACK when the response is CON
+            if(responseInfo->info.type == CA_MSG_CONFIRM)
+            {
+                SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
+                        CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0);
+            }
+        }
+        return;
+    }
+
+    if(observer)
     {
-        OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
-        result = DetermineResourceHandling (request, &resHandling, &resource);
-        if (result == OC_STACK_OK)
+        OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token"));
+        if(responseInfo->result == CA_EMPTY)
         {
-            result = ProcessRequest(resHandling, resource, request);
+            OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token"));
+            if(responseInfo->info.type == CA_MSG_RESET)
+            {
+                OC_LOG(INFO, TAG, PCF("This is a RESET"));
+                OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
+                        OC_OBSERVER_NOT_INTERESTED);
+            }
+            else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
+            {
+                OC_LOG(INFO, TAG, PCF("This is a pure ACK"));
+                OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
+                        OC_OBSERVER_STILL_INTERESTED);
+            }
+        }
+        else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
+        {
+            OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer"));
+            OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
+                    OC_OBSERVER_FAILED_COMM);
+        }
+        return;
+    }
+
+    if(!cbNode && !observer)
+    {
+        if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER)
+        {
+            OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token"));
+            if(responseInfo->result == CA_EMPTY)
+            {
+                OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack"));
+            }
+            else
+            {
+                OC_LOG(INFO, TAG, PCF("Received a response or notification,\
+                        but I do not have callback. Sending RESET"));
+                SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
+                        CA_MSG_RESET, 0, NULL, NULL, 0);
+            }
+        }
+
+        if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
+        {
+            OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token"));
+            if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
+            {
+                OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"),
+                                            responseInfo->info.messageId);
+            }
+            if (responseInfo->info.type == CA_MSG_RESET)
+            {
+                OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"),
+                                            responseInfo->info.messageId);
+            }
+        }
+        return;
+    }
+
+    OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload);
+    OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses"));
+}
+
+/*
+ * This function sends out Direct Stack Responses. These are responses that are not coming
+ * from the application entity handler. These responses have no payload and are usually ACKs,
+ * RESETs or some error conditions that were caught by the stack.
+ */
+OCStackResult SendDirectStackResponse(const CARemoteEndpoint_t* endPoint, const uint16_t coapID,
+        const CAResponseResult_t responseResult, const CAMessageType_t type,
+        const uint8_t numOptions, const CAHeaderOption_t *options,
+        CAToken_t token, uint8_t tokenLength)
+{
+    CAResponseInfo_t respInfo = {};
+    respInfo.result = responseResult;
+    respInfo.info.messageId = coapID;
+    respInfo.info.numOptions = numOptions;
+    respInfo.info.options = (CAHeaderOption_t*)options;
+    respInfo.info.payload = NULL;
+    respInfo.info.token = token;
+    respInfo.info.tokenLength = tokenLength;
+    respInfo.info.type = type;
+
+    CAResult_t caResult = CASendResponse(endPoint, &respInfo);
+    if(caResult != CA_STATUS_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("CASendResponse error"));
+        return OC_STACK_ERROR;
+    }
+    return OC_STACK_OK;
+}
+
+//This function will be called back by CA layer when a request is received
+void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+{
+    OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
+    if(!endPoint)
+    {
+        OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
+        return;
+    }
+
+    if(!requestInfo)
+    {
+        OC_LOG(ERROR, TAG, PCF("requestInfo is NULL"));
+        return;
+    }
+
+    OCStackResult requestResult = OC_STACK_ERROR;
+
+    if(myStackMode == OC_CLIENT)
+    {
+        //TODO: should the client be responding to requests?
+        return;
+    }
+
+    OCServerProtocolRequest serverRequest = {};
+
+    OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s\n"), (char*)endPoint->resourceUri);
+
+    char * newUri = NULL;
+    char * query  = NULL;
+
+    requestResult = getQueryFromUri(endPoint->resourceUri, &query, &newUri);
+
+    if (requestResult != OC_STACK_OK)
+    {
+        OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
+        return;
+    }
+    OC_LOG_V(INFO, TAG, PCF("URI without query: %s\n"), newUri);
+    OC_LOG_V(INFO, TAG, PCF("Query : %s\n"), query);
+
+    if(strlen(newUri) < MAX_URI_LENGTH)
+    {
+        //copy URI
+        memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
+        OCFree(newUri);
+    }
+    else
+    {
+        OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH."));
+        OCFree(newUri);
+        OCFree(query);
+        return;
+    }
+    //copy query
+    if(query)
+    {
+        if(strlen(query) < MAX_QUERY_LENGTH)
+        {
+            memcpy (&(serverRequest.query), query, strlen(query));
+            OCFree(query);
         }
         else
         {
-            result = OC_STACK_ERROR;
+            OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH."));
+            OCFree(query);
+            return;
         }
     }
+    //copy request payload
+    if (requestInfo->info.payload)
+    {
+        size_t payloadLen = strlen(requestInfo->info.payload);
+        serverRequest.reqTotalSize = payloadLen + 1;
+        memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
+                payloadLen);
+    }
     else
     {
-        OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
-        result = OC_STACK_CONTINUE;
+        serverRequest.reqTotalSize = 1;
+        serverRequest.reqJSONPayload[0] = '\0';
     }
-    return result;
+
+    switch (requestInfo->method)
+    {
+        case CA_GET:
+            {
+                serverRequest.method = OC_REST_GET;
+                break;
+            }
+        case CA_PUT:
+            {
+                serverRequest.method = OC_REST_PUT;
+                break;
+            }
+        case CA_POST:
+            {
+                serverRequest.method = OC_REST_POST;
+                break;
+            }
+        case CA_DELETE:
+            {
+                serverRequest.method = OC_REST_DELETE;
+                break;
+            }
+        default:
+            {
+                OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
+                SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
+                        requestInfo->info.type, requestInfo->info.numOptions,
+                        requestInfo->info.options, requestInfo->info.token,
+                        requestInfo->info.tokenLength);
+                return;
+            }
+    }
+
+    OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d",
+            requestInfo->info.tokenLength);
+    OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
+            requestInfo->info.tokenLength);
+    serverRequest.requestToken = (CAToken_t)OCMalloc(requestInfo->info.tokenLength);
+    serverRequest.tokenLength = requestInfo->info.tokenLength;
+    // Module Name
+    if (!serverRequest.requestToken)
+    {
+        OC_LOG(FATAL, TAG, "Server Request Token is NULL");
+        SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
+                requestInfo->info.type, requestInfo->info.numOptions,
+                requestInfo->info.options, requestInfo->info.token,
+                requestInfo->info.tokenLength);
+        return;
+    }
+    memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
+
+    if (requestInfo->info.type == CA_MSG_CONFIRM)
+    {
+        serverRequest.qos = OC_HIGH_QOS;
+    }
+    else
+    {
+        serverRequest.qos = OC_LOW_QOS;
+    }
+    // CA does not need the following 2 fields
+    // Are we sure CA does not need them? how is it responding to multicast
+    serverRequest.delayedResNeeded = 0;
+    serverRequest.secured = endPoint->isSecured;
+
+    serverRequest.coapID = requestInfo->info.messageId;
+
+    // copy the address
+    serverRequest.addressInfo      = endPoint->addressInfo;
+    serverRequest.connectivityType = endPoint->transportType;
+
+    // copy vendor specific header options
+    uint8_t tempNum = (requestInfo->info.numOptions);
+    GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
+    if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
+    {
+        OC_LOG(ERROR, TAG,
+                PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS"));
+        SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
+                requestInfo->info.type, requestInfo->info.numOptions,
+                requestInfo->info.options, requestInfo->info.token,
+                requestInfo->info.tokenLength);
+        OCFree(serverRequest.requestToken);
+        return;
+    }
+    serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
+    if (serverRequest.numRcvdVendorSpecificHeaderOptions)
+    {
+        memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
+            sizeof(CAHeaderOption_t)*tempNum);
+    }
+
+    requestResult = HandleStackRequests (&serverRequest);
+
+    // Send ACK to client as precursor to slow response
+    if(requestResult == OC_STACK_SLOW_RESOURCE)
+    {
+        SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
+                    CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0);
+    }
+    else if(requestResult != OC_STACK_OK)
+    {
+        OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult);
+
+        CAResponseResult_t stackResponse = OCToCAStackResult(requestResult);
+
+        SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
+                requestInfo->info.type, requestInfo->info.numOptions,
+                requestInfo->info.options, requestInfo->info.token,
+                requestInfo->info.tokenLength);
+    }
+    // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
+    // The token is copied in there, and is thus still owned by this function.
+    OCFree(serverRequest.requestToken);
+    OC_LOG(INFO, TAG, PCF("Exit HandleCARequests"));
 }
 
-//This function will be called back by occoap layer when a response is received
-void HandleStackResponses(OCResponse * response)
+OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
 {
-    OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION;
-    OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)"));
+    OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)"));
+    OCStackResult result = OC_STACK_ERROR;
+    ResourceHandling resHandling;
+    OCResource *resource;
+    if(!protocolRequest)
+    {
+        OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
+            protocolRequest->tokenLength);
+    if(!request)
+    {
+        OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
+        result = AddServerRequest(&request, protocolRequest->coapID,
+                protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
+                protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
+                protocolRequest->observationOption, protocolRequest->qos,
+                protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
+                protocolRequest->reqJSONPayload, protocolRequest->requestToken,
+                protocolRequest->tokenLength,
+                protocolRequest->resourceUrl,protocolRequest->reqTotalSize,
+                &protocolRequest->addressInfo, protocolRequest->connectivityType);
+        if (OC_STACK_OK != result)
+        {
+            OC_LOG(ERROR, TAG, PCF("Error adding server request"));
+            return result;
+        }
+
+        if(!request)
+        {
+            OC_LOG(ERROR, TAG, PCF("Out of Memory"));
+            return OC_STACK_NO_MEMORY;
+        }
+
+        if(!protocolRequest->reqMorePacket)
+        {
+            request->requestComplete = 1;
+        }
+    }
+    else
+    {
+        OC_LOG(INFO, TAG,
+                PCF("This is either a repeated or blocked Server Request"));
+    }
 
-    if (response->cbNode)
+    if(request->requestComplete)
     {
-        OC_LOG(INFO, TAG, PCF("Calling into application address space"));
-        result = response->cbNode->callBack(response->cbNode->context,
-                response->cbNode->handle, response->clientResponse);
-        if (result == OC_STACK_DELETE_TRANSACTION ||
-                response->clientResponse->result == OC_STACK_COMM_ERROR ||
-                response->clientResponse->result == OC_STACK_RESOURCE_DELETED)
+        OC_LOG(INFO, TAG, PCF("This Server Request is complete"));
+        result = DetermineResourceHandling (request, &resHandling, &resource);
+        if (result == OC_STACK_OK)
         {
-            FindAndDeleteClientCB(response->cbNode);
+            result = ProcessRequest(resHandling, resource, request);
         }
     }
+    else
+    {
+        OC_LOG(INFO, TAG, PCF("This Server Request is incomplete"));
+        result = OC_STACK_CONTINUE;
+    }
+    return result;
 }
 
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
+bool ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
 {
     size_t index = 0;
-    unsigned char *itr, *coap;
-    uint8_t dotCount = 0;
+     char *itr, *coap;
+     uint8_t dotCount = 0;
 
-    ipAddr[index] = 0;
-    *port = 0;
-    /* search for scheme */
-    itr = ipAddrStr;
-    if (!isdigit((unsigned char) *ipAddrStr))
+     ipAddr[index] = 0;
+     *port = 0;
+     /* search for scheme */
+     itr = ipAddrStr;
+    if (!isdigit((char) *ipAddrStr))
     {
-        coap = (unsigned char *) OC_COAP_SCHEME;
+        coap = OC_COAP_SCHEME;
         while (*coap && tolower(*itr) == *coap)
         {
             coap++;
@@ -280,13 +1623,14 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
     }
     ipAddrStr = itr;
 
-    while (*ipAddrStr) {
-        if (isdigit((unsigned char) *ipAddrStr))
+    while (*ipAddrStr)
+    {
+        if (isdigit(*ipAddrStr))
         {
             ipAddr[index] *= 10;
             ipAddr[index] += *ipAddrStr - '0';
         }
-        else if ((unsigned char) *ipAddrStr == '.')
+        else if (*ipAddrStr == '.')
         {
             index++;
             dotCount++;
@@ -302,7 +1646,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';
@@ -315,125 +1659,132 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
         }
     }
 
+    return (3 == dotCount);
+}
+
+bool validatePlatformInfo(OCPlatformInfo info)
+{
+
+    if (!info.platformID)
+    {
+        OC_LOG(ERROR, TAG, PCF("No platform ID found."));
+        return false;
+    }
 
-    if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
-            && dotCount == 3)
+    if (info.manufacturerName)
     {
-        return 1;
+        size_t lenManufacturerName = strlen(info.manufacturerName);
+
+        if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
+        {
+            OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements."));
+            return false;
+        }
     }
     else
     {
-        return 0;
+        OC_LOG(ERROR, TAG, PCF("No manufacturer name present"));
+        return false;
     }
-}
-
-//-----------------------------------------------------------------------------
-// Private internal function prototypes
-//-----------------------------------------------------------------------------
-
-static OCDoHandle GenerateInvocationHandle();
-static OCStackResult initResources();
-static void insertResource(OCResource *resource);
-static OCResource *findResource(OCResource *resource);
-static void insertResourceType(OCResource *resource,
-        OCResourceType *resourceType);
-static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
-        uint8_t index);
-static void insertResourceInterface(OCResource *resource,
-        OCResourceInterface *resourceInterface);
-static OCResourceInterface *findResourceInterfaceAtIndex(
-        OCResourceHandle handle, uint8_t index);
-static void deleteResourceType(OCResourceType *resourceType);
-static void deleteResourceInterface(OCResourceInterface *resourceInterface);
-static void deleteResourceElements(OCResource *resource);
-static int 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 * uri, unsigned char** resourceType, char ** newURI);
 
+    if (info.manufacturerUrl)
+    {
+        if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
+        {
+            OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements."));
+            return false;
+        }
+    }
+    return true;
+}
 //-----------------------------------------------------------------------------
 // Public APIs
 //-----------------------------------------------------------------------------
 
-/**
- * Initialize the OC Stack.  Must be called prior to starting the stack.
- *
- * @param ipAddr
- *     IP Address of host device
- * @param port
- *     Port of host device
- * @param mode
- *     Host device is client, server, or client-server
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack init error
- */
 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
 {
-    OCStackResult result = OC_STACK_ERROR;
-    OC_LOG(INFO, TAG, PCF("Entering OCInit"));
-
-    if (ipAddr)
+    if(stackState == OC_STACK_INITIALIZED)
     {
-        OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr);
+        OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
+                OCStop() between them are ignored."));
+        return OC_STACK_OK;
     }
 
-    switch (mode)
+    (void) ipAddr;
+    (void) port;
+    OCStackResult result = OC_STACK_ERROR;
+    OC_LOG(INFO, TAG, PCF("Entering OCInit"));
+
+    // Validate mode
+    if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)))
     {
-    case OC_CLIENT:
-        OC_LOG(INFO, TAG, PCF("Client mode"));
-        break;
-    case OC_SERVER:
-        OC_LOG(INFO, TAG, PCF("Server mode"));
-        break;
-    case OC_CLIENT_SERVER:
-        OC_LOG(INFO, TAG, PCF("Client-server mode"));
-        break;
-    default:
         OC_LOG(ERROR, TAG, PCF("Invalid mode"));
         return OC_STACK_ERROR;
-        break;
     }
     myStackMode = mode;
 
     defaultDeviceHandler = NULL;
+    OCSeedRandom();
+
+    result = CAResultToOCResult(CAInitialize());
+    VERIFY_SUCCESS(result, OC_STACK_OK);
+
+    result = CAResultToOCResult(OCSelectNetwork());
+    VERIFY_SUCCESS(result, OC_STACK_OK);
+
+    CARegisterHandler(HandleCARequests, HandleCAResponses);
+    switch (myStackMode)
+    {
+        case OC_CLIENT:
+            result = CAResultToOCResult(CAStartDiscoveryServer());
+            OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer"));
+            break;
+        case OC_SERVER:
+            result = CAResultToOCResult(CAStartListeningServer());
+            OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer"));
+            break;
+        case OC_CLIENT_SERVER:
+            result = CAResultToOCResult(CAStartListeningServer());
+            if(result == OC_STACK_OK)
+            {
+                result = CAResultToOCResult(CAStartDiscoveryServer());
+            }
+            break;
+    }
+    VERIFY_SUCCESS(result, OC_STACK_OK);
+
+#if defined(__WITH_DTLS__)
+    result = (CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials) == CA_STATUS_OK) ?
+        OC_STACK_OK : OC_STACK_ERROR;
+    VERIFY_SUCCESS(result, OC_STACK_OK);
+#endif // (__WITH_DTLS__)
 
 #ifdef WITH_PRESENCE
     PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1;
 #endif // WITH_PRESENCE
 
-    // Make call to OCCoAP layer
-    result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode);
-    if (result == OC_STACK_OK)
-    {
-        stackState = OC_STACK_INITIALIZED;
-    }
+    //Update Stack state to initialized
+    stackState = OC_STACK_INITIALIZED;
+
     // Initialize resource
-    if(result == OC_STACK_OK && myStackMode != OC_CLIENT)
+    if(myStackMode != OC_CLIENT)
     {
         result = initResources();
     }
+
+exit:
     if(result != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, PCF("Stack initialization error"));
+        deleteAllResources();
+        CATerminate();
+        stackState = OC_STACK_UNINITIALIZED;
     }
     return result;
 }
 
-/**
- * Stop the OC stack.  Use for a controlled shutdown.
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack not initialized
- */
 OCStackResult OCStop()
 {
-    OCStackResult result = OC_STACK_ERROR;
-
     OC_LOG(INFO, TAG, PCF("Entering OCStop"));
 
     if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
@@ -458,40 +1809,32 @@ OCStackResult OCStop()
     // Free memory dynamically allocated for resources
     deleteAllResources();
     DeleteDeviceInfo();
-
-    // Make call to OCCoAP layer
-    if (OCStopCoAP() == OC_STACK_OK)
-    {
-        // Remove all observers
-        DeleteObserverList();
-        // Remove all the client callbacks
-        DeleteClientCBList();
-        stackState = OC_STACK_UNINITIALIZED;
-        result = OC_STACK_OK;
-    } else {
-        stackState = OC_STACK_INITIALIZED;
-        result = OC_STACK_ERROR;
-    }
-
+    DeletePlatformInfo();
+    CATerminate();
+    // Remove all observers
+    DeleteObserverList();
+    // Remove all the client callbacks
+    DeleteClientCBList();
     // Deinit security blob
     DeinitOCSecurityInfo();
+    stackState = OC_STACK_UNINITIALIZED;
+    return OC_STACK_OK;
+}
 
-    if (result != OC_STACK_OK) {
-        OC_LOG(ERROR, TAG, PCF("Stack stop error"));
+CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
+{
+    switch (qos)
+    {
+        case OC_HIGH_QOS:
+            return CA_MSG_CONFIRM;
+        case OC_LOW_QOS:
+        case OC_MEDIUM_QOS:
+        case OC_NA_QOS:
+        default:
+            return CA_MSG_NONCONFIRM;
     }
-
-    return result;
 }
 
-/**
- * Verify the lengths of the URI and the query separately
- *
- * @param inputUri       - Input URI and query.
- * @param uriLen         - The length of the initial URI with query.
- *
- * Note: The '?' that appears after the URI is not considered as
- * a part of the query.
- */
 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
 {
     char *query;
@@ -517,40 +1860,26 @@ OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
     return OC_STACK_OK;
 }
 
-/**
- * Discover or Perform requests on a specified resource (specified by that Resource's respective URI).
- *
- * @param handle             - @ref OCDoHandle to refer to the request sent out on behalf of calling this API.
- * @param method             - @ref OCMethod to perform on the resource
- * @param requiredUri        - URI of the resource to interact with
- * @param referenceUri       - URI of the reference resource
- * @param request            - JSON encoded request
- * @param qos                - quality of service
- * @param cbData             - struct that contains 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
- *                             header options to be sent with the request
- * @param numOptions         - Number of vendor specific header options to be included
- *
- * @return
- *     OC_STACK_OK               - no errors
- *     OC_STACK_INVALID_CALLBACK - invalid callback function pointer
- *     OC_STACK_INVALID_METHOD   - invalid resource method
- *     OC_STACK_INVALID_URI      - invalid required or reference URI
- */
-
 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
-                           const char *referenceUri, const char *request,
-                           OCQualityOfService qos, OCCallbackData *cbData,
-                           OCHeaderOption * options, uint8_t numOptions)
+            const char *referenceUri, const char *request, OCConnectivityType conType,
+            OCQualityOfService qos, OCCallbackData *cbData,
+            OCHeaderOption * options, uint8_t numOptions)
 {
     OCStackResult result = OC_STACK_ERROR;
-    OCCoAPToken token;
     ClientCB *clientCB = NULL;
-    unsigned char * requestUri = NULL;
-    unsigned char * resourceType = 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;
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+    OCDoHandle resHandle = NULL;
+    CAInfo_t requestData ={};
+    CARequestInfo_t requestInfo ={};
+    CAGroupEndpoint_t grpEnd = {};
 
     OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
 
@@ -558,26 +1887,42 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
 
-    TODO ("Need to form the final query by concatenating require and reference URI's");
+    //TODO ("Need to form the final query by concatenating require and reference URI's");
     VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
 
     uint16_t uriLen = strlen(requiredUri);
 
-    // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS
+    // ToDo: We should also check if the requiredUri has a mutlicast address,
+    // then qos has to be OC_Low_QOS
     switch (method)
     {
         case OC_REST_GET:
-        case OC_REST_PUT:
-        case OC_REST_POST:
-        case OC_REST_DELETE:
         case OC_REST_OBSERVE:
         case OC_REST_OBSERVE_ALL:
         case OC_REST_CANCEL_OBSERVE:
+            requestInfo.method = CA_GET;
+            break;
+
+        case OC_REST_PUT:
+            requestInfo.method = CA_PUT;
+            break;
+
+        case OC_REST_POST:
+            requestInfo.method = CA_POST;
             break;
+
+        case OC_REST_DELETE:
+            requestInfo.method = CA_DELETE;
+            break;
+
         #ifdef WITH_PRESENCE
         case OC_REST_PRESENCE:
+            // Replacing method type with GET because "presence"
+            // is a stack layer only implementation.
+            requestInfo.method = CA_GET;
             break;
         #endif
+
         default:
             result = OC_STACK_INVALID_METHOD;
             goto exit;
@@ -597,13 +1942,31 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
 #ifdef WITH_PRESENCE
     if(method == OC_REST_PRESENCE)
     {
-        result = getResourceType(requiredUri, &resourceType, &newUri);
-        if(resourceType) {
-            OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
+        result = getQueryFromUri(requiredUri, &query, &newUri);
+
+        if(result != OC_STACK_OK)
+        {
+            OC_LOG_V(ERROR, TAG, "Invalid Param from getQueryFromUri: %d, URI is %s",
+                    result, requiredUri);
+            goto exit;
+        }
+
+        if(query)
+        {
+            result = getResourceType((char *) query, &resourceType);
+            OCFree(query);
+            if(resourceType)
+            {
+                OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
+            }
+            else
+            {
+                OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
+            }
         }
         else
         {
-            OC_LOG(DEBUG, TAG, "Got Resource Type is NULL.");
+            OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
         }
         if(result != OC_STACK_OK)
         {
@@ -612,7 +1975,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));
@@ -623,26 +1986,110 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
         goto exit;
     }
 
-    *handle = GenerateInvocationHandle();
-    if(!*handle)
+    resHandle = GenerateInvocationHandle();
+    if(!resHandle)
     {
         result = OC_STACK_NO_MEMORY;
         goto exit;
     }
 
-    // Generate token which will be used by OCStack to match responses received
-    // with the request
-    OCGenerateCoAPToken(&token);
+    // create token
+    caResult = CAGenerateToken(&token, tokenLength);
+    if (caResult != CA_STATUS_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
+        CADestroyToken(token);
+        result = CAResultToOCResult (caResult);
+        goto exit;
+    }
+
+    requestData.type = qualityOfServiceToMessageType(qos);
+
+    requestData.token = token;
+    requestData.tokenLength = tokenLength;
+
+    if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
+    {
+        result = CreateObserveHeaderOption (&(requestData.options), options,
+                                    numOptions, OC_OBSERVE_REGISTER);
+        if (result != OC_STACK_OK)
+        {
+            CADestroyToken(token);
+            goto exit;
+        }
+        requestData.numOptions = numOptions + 1;
+    }
+    else
+    {
+        requestData.options = (CAHeaderOption_t*)options;
+        requestData.numOptions = numOptions;
+    }
+
+    requestData.payload = (char *)request;
+
+    requestInfo.info = requestData;
+
+    CATransportType_t caConType;
+
+    result = OCToCATransportType((OCConnectivityType) conType, &caConType);
+    if (result != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
+        goto exit;
+    }
+
+    // send request
+    if(conType == OC_ALL)
+    {
+        grpEnd.transportType = caConType;
+
+        grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1);
+        if(!grpEnd.resourceUri)
+        {
+            result = OC_STACK_NO_MEMORY;
+            CADestroyToken(token);
+            goto exit;
+        }
+        strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
+
+        caResult = CASendRequestToAll(&grpEnd, &requestInfo);
+    }
+    else
+    {
+        caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
+
+        if (caResult != CA_STATUS_OK)
+        {
+            OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
+            result = CAResultToOCResult (caResult);
+            CADestroyToken(token);
+            goto exit;
+        }
+
+        caResult = CASendRequest(endpoint, &requestInfo);
+    }
+
+    if (caResult != CA_STATUS_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("CASendRequest"));
+        result = CAResultToOCResult (caResult);
+        CADestroyToken(token);
+        goto exit;
+    }
 
-    if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType))
-            != OC_STACK_OK)
+    result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle, method,
+                             requestUri, resourceType, conType,
+                             GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND));
+    if(result != OC_STACK_OK)
     {
         result = OC_STACK_NO_MEMORY;
         goto exit;
     }
 
-    // Make call to OCCoAP layer
-    result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions);
+    if(handle)
+    {
+        *handle = resHandle;
+    }
 
 exit:
     if(newUri != requiredUri)
@@ -651,27 +2098,28 @@ exit:
     }
     if (result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
+        OC_LOG_V(ERROR, TAG, PCF("OCDoResource error no %d"), result);
         FindAndDeleteClientCB(clientCB);
+        OCFree(resHandle);
+        OCFree(requestUri);
+        OCFree(resourceType);
+    }
+    CADestroyRemoteEndpoint(endpoint);
+    OCFree(grpEnd.resourceUri);
+
+    if (requestData.options  && requestData.numOptions > 0)
+    {
+        if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
+        {
+            OCFree(requestData.options);
+        }
     }
     return result;
 }
 
-/**
- * Cancel a request associated with a specific @ref OCDoResource invocation.
- *
- * @param handle - Used to identify a specific OCDoResource invocation.
- * @param qos    - used to specify Quality of Service (read below for more info)
- * @param options- used to specify vendor specific header options when sending
- *                 explicit observe cancellation
- * @param numOptions- Number of header options to be included
- *
- * @return
- *     OC_STACK_OK               - No errors; Success
- *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
- */
 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
-        uint8_t numOptions) {
+        uint8_t numOptions)
+{
     /*
      * This ftn is implemented one of two ways in the case of observation:
      *
@@ -680,7 +2128,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
      *      When the next notification comes in from server,
      *      reply with RESET message to server.
      *      Keep in mind that the server will react to RESET only
-     *      if the last notification was sent ans CON
+     *      if the last notification was sent as CON
      *
      * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
      *      and it is associated with an observe request
@@ -690,42 +2138,97 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
      *      Remove the callback associated on client side.
      */
     OCStackResult ret = OC_STACK_OK;
+    CARemoteEndpoint_t* endpoint = NULL;
+    CAResult_t caResult;
+    CAInfo_t requestData = {};
+    CARequestInfo_t requestInfo = {};
 
-    if(!handle) {
+    if(!handle)
+    {
         return OC_STACK_INVALID_PARAM;
     }
 
     OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
 
-    ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
+    ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
 
-    if(clientCB) {
+    if(clientCB)
+    {
         switch (clientCB->method)
         {
             case OC_REST_OBSERVE:
             case OC_REST_OBSERVE_ALL:
                 if(qos == OC_HIGH_QOS)
                 {
-                    ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos,
-                            &(clientCB->token), (const char *) clientCB->requestUri, NULL, options,
-                            numOptions);
+                    requestData.type =  qualityOfServiceToMessageType(qos);
+                    requestData.token = clientCB->token;
+                    requestData.tokenLength = clientCB->tokenLength;
+
+                    if (CreateObserveHeaderOption (&(requestData.options),
+                            options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
+                    {
+                        return OC_STACK_ERROR;
+                    }
+                    requestData.numOptions = numOptions + 1;
+                    requestInfo.method = CA_GET;
+                    requestInfo.info = requestData;
+
+                    CATransportType_t caConType;
+                    ret = OCToCATransportType(clientCB->conType, &caConType);
+                    if(ret != OC_STACK_OK)
+                    {
+                        goto Error;
+                    }
+
+                    caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri,
+                            caConType, &endpoint);
+                    if (caResult != CA_STATUS_OK)
+                    {
+                        OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
+                        ret = OC_STACK_ERROR;
+                        goto Error;
+                    }
+
+                    // send request
+                    caResult = CASendRequest(endpoint, &requestInfo);
+                    if (caResult != CA_STATUS_OK)
+                    {
+                        OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
+                        ret = OC_STACK_ERROR;
+                    }
+                    ret = CAResultToOCResult (caResult);
                 }
                 else
                 {
                     FindAndDeleteClientCB(clientCB);
                 }
                 break;
+
             #ifdef WITH_PRESENCE
             case OC_REST_PRESENCE:
                 FindAndDeleteClientCB(clientCB);
                 break;
             #endif
             default:
-                return OC_STACK_INVALID_METHOD;
+                ret = OC_STACK_INVALID_METHOD;
+                break;
         }
     }
+    else
+    {
+        OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
+    }
+
+    Error:
+    CADestroyRemoteEndpoint(endpoint);
+    if (requestData.numOptions > 0)
+    {
+        OCFree(requestData.options);
+    }
+
     return ret;
 }
+
 #ifdef WITH_PRESENCE
 OCStackResult OCProcessPresence()
 {
@@ -735,18 +2238,20 @@ OCStackResult OCProcessPresence()
 
     OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
     ClientCB* cbNode = NULL;
-    OCDevAddr dst;
-    OCClientResponse clientResponse;
-    OCResponse * response = NULL;
+    OCDevAddr dst = {};
+    OCClientResponse clientResponse ={};
+    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", cbNode->presence->TTLlevel);
-                OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
+                uint32_t now = GetTicks(0);
+                OC_LOG_V(DEBUG, TAG, "this TTL level %d",
+                                                        cbNode->presence->TTLlevel);
+                OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
 
 
                 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
@@ -754,34 +2259,29 @@ 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"));
-                    if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
+                    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,
                                 &dst);
-                        result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT,
-                                (OCDevAddr *) &dst, 0, NULL);
-                        if(result != OC_STACK_OK)
-                        {
-                            goto exit;
-                        }
-                        result = FormOCResponse(&response, cbNode, 0, &clientResponse);
-                        if(result != OC_STACK_OK)
-                        {
-                            goto exit;
-                        }
+
+                        clientResponse.sequenceNumber = 0;
+                        clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
+                        clientResponse.addr = (OCDevAddr *) &dst;
+                        clientResponse.resJSONPayload = NULL;
 
                         // 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
@@ -789,21 +2289,52 @@ OCStackResult OCProcessPresence()
                         result = OC_STACK_INVALID_IP;
                         goto exit;
                     }
-                    HandleStackResponses(response);
+
+                    cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
+                    if (cbResult == OC_STACK_DELETE_TRANSACTION)
+                    {
+                        FindAndDeleteClientCB(cbNode);
+                    }
                 }
+
                 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
                 {
-                    OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
-                    OCCoAPToken token;
-                    OCGenerateCoAPToken(&token);
-                    result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS,
-                            &token, (const char *)cbNode->requestUri, NULL, NULL, 0);
-                    if(result != OC_STACK_OK)
+                    CAResult_t caResult = CA_STATUS_OK;
+                    CARemoteEndpoint_t* endpoint = NULL;
+                    CAInfo_t requestData ={};
+                    CARequestInfo_t requestInfo = {};
+
+                    OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
+
+
+                    CATransportType_t caConType;
+                    result = OCToCATransportType(cbNode->conType, &caConType);
+                    caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, caConType,
+                                                        &endpoint);
+                    if (caResult != CA_STATUS_OK || result != OC_STACK_OK)
+                    {
+                        OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
+                        goto exit;
+                    }
+
+                    requestData.type = CA_MSG_NONCONFIRM;
+                    requestData.token = cbNode->token;
+                    requestData.tokenLength = cbNode->tokenLength;
+                    requestInfo.method = CA_GET;
+                    requestInfo.info = requestData;
+
+                    caResult = CASendRequest(endpoint, &requestInfo);
+                    CADestroyRemoteEndpoint(endpoint);
+
+                    if (caResult != CA_STATUS_OK)
                     {
+                        OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
                         goto exit;
                     }
+
                     cbNode->presence->TTLlevel++;
-                    OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel);
+                    OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
+                                                            cbNode->presence->TTLlevel);
                 }
             }
         }
@@ -811,68 +2342,69 @@ OCStackResult OCProcessPresence()
 exit:
     if (result != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
+        OC_LOG_V(ERROR, TAG, PCF("OCProcessPresence error no %d"), result);
     }
     return result;
 }
-#endif
-
-/**
- * Called in main loop of OC client or server.  Allows low-level processing of
- * stack services.
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- */
-OCStackResult OCProcess() {
+#endif // WITH_PRESENCE
 
-    OC_LOG(INFO, TAG, PCF("Entering OCProcess"));
+OCStackResult OCProcess()
+{
     #ifdef WITH_PRESENCE
     OCProcessPresence();
     #endif
-    OCProcessCoAP();
+    CAHandleRequestResponse();
 
     return OC_STACK_OK;
 }
 
 #ifdef WITH_PRESENCE
-/**
- * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out
- * presence notifications to clients via multicast. Once this API has been called with a success,
- * clients may query for this server's presence and this server's stack will respond via multicast.
- *
- * 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.
- *
- * @param ttl - Time To Live in seconds
- * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
- *
- * @return
- *     OC_STACK_OK      - No errors; Success
- */
 OCStackResult OCStartPresence(const uint32_t ttl)
 {
+    uint8_t tokenLength = CA_MAX_TOKEN_LEN;
     OCChangeResourceProperty(
             &(((OCResource *)presenceResource.handle)->resourceProperties),
             OC_ACTIVE, 1);
 
-    if(ttl > 0)
+    if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
+    {
+        presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
+        OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value"));
+    }
+    else if (0 == ttl)
+    {
+        presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
+        OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value"));
+    }
+    else
     {
         presenceResource.presenceTTL = ttl;
     }
+    OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
 
-    if(OC_PRESENCE_UNINITIALIZED == presenceState)
+    if (OC_PRESENCE_UNINITIALIZED == presenceState)
     {
-        OCDevAddr multiCastAddr;
-        OCCoAPToken token;
-
         presenceState = OC_PRESENCE_INITIALIZED;
-        OCGenerateCoAPToken(&token);
-        OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr);
-        //add the presence observer
-        AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr,
-            (OCResource *)presenceResource.handle, OC_LOW_QOS);
+
+        CAAddress_t addressInfo;
+        strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE);
+        addressInfo.IP.port = OC_MULTICAST_PORT;
+
+        CAToken_t caToken = NULL;
+        CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
+        if (caResult != CA_STATUS_OK)
+        {
+            OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
+            CADestroyToken(caToken);
+            return OC_STACK_ERROR;
+        }
+
+        CATransportType_t connType;
+        OCToCATransportType(OC_ALL, &connType );
+        AddObserver(OC_PRESENCE_URI, NULL, 0, caToken, tokenLength,
+                (OCResource *)presenceResource.handle, OC_LOW_QOS,
+                &addressInfo, connType);
+        CADestroyToken(caToken);
     }
 
     // Each time OCStartPresence is called
@@ -882,31 +2414,31 @@ OCStackResult OCStartPresence(const uint32_t ttl)
     return SendPresenceNotification(NULL);
 }
 
-/**
- * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out
- * presence notifications to clients via multicast. Once this API has been called with a success,
- * this server's stack will not respond to clients querying for this server's presence.
- *
- * Server can call this function when it is terminating, going offline, or when going
- * away from network.
- *
- * @return
- *     OC_STACK_OK      - No errors; Success
- */
 OCStackResult OCStopPresence()
 {
     OCStackResult result = OC_STACK_ERROR;
-    //make resource inactive
+
+    if(presenceResource.handle)
+    {
+        ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+    }
+
+    // make resource inactive
     result = OCChangeResourceProperty(
             &(((OCResource *) presenceResource.handle)->resourceProperties),
             OC_ACTIVE, 0);
-    result = SendPresenceNotification(NULL);
 
-    return result;
+    if(result != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG,
+                      PCF("Changing the presence resource properties to ACTIVE not successful"));
+        return result;
+    }
+
+    return SendStopNotification();
 }
 #endif
 
-
 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler)
 {
     defaultDeviceHandler = entityHandler;
@@ -914,80 +2446,90 @@ OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandle
     return OC_STACK_OK;
 }
 
-OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
+OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
 {
-    OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
+    OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo"));
 
-    if(myStackMode == OC_CLIENT)
+    if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER)
+    {
+        if (validatePlatformInfo(platformInfo))
+        {
+            return SavePlatformInfo(platformInfo);
+        }
+        else
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+    }
+    else
     {
         return OC_STACK_ERROR;
     }
+}
+
+OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
+{
+    // TODO: Implement this.
+    OC_LOG(ERROR, TAG, "Implement OCSetDeviceInfo !!");
 
-    return SaveDeviceInfo(deviceInfo);
+    // Returning ok to make samples work.
+    return OC_STACK_OK;
 }
 
-/**
- * Create a resource
- *
- * @param handle - pointer to handle to newly created resource.  Set by ocstack.  Used to refer to resource
- * @param resourceTypeName - name of resource type.  Example: "core.led"
- * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
- * @param uri - URI of the resource.  Example:  "/a/led"
- * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
- *                        NULL for default entity handler
- * @param resourceProperties - properties supported by resource.  Example: OC_DISCOVERABLE|OC_OBSERVABLE
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- */
 OCStackResult OCCreateResource(OCResourceHandle *handle,
         const char *resourceTypeName,
         const char *resourceInterfaceName,
         const char *uri, OCEntityHandler entityHandler,
-        uint8_t resourceProperties) {
+        uint8_t resourceProperties)
+{
 
     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;
     }
     // Is it presented during resource discovery?
-    if (!handle || !resourceTypeName) {
+    if (!handle || !resourceTypeName)
+    {
         OC_LOG(ERROR, TAG, PCF("Input parameter is NULL"));
         return OC_STACK_INVALID_PARAM;
     }
 
-    if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
+    if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
+    {
         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
     }
 
     // Make sure resourceProperties bitmask has allowed properties specified
     if (resourceProperties
-            > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) {
+            > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE))
+    {
         OC_LOG(ERROR, TAG, PCF("Invalid property"));
         return OC_STACK_INVALID_PARAM;
     }
 
     // If the headResource is NULL, then no resources have been created...
     pointer = headResource;
-    if (pointer) {
+    if (pointer)
+    {
         // At least one resources is in the resource list, so we need to search for
         // repeated URLs, which are not allowed.  If a repeat is found, exit with an error
-        while (pointer) {
-            if (strcmp(uri, pointer->uri) == 0) {
+        while (pointer)
+        {
+            if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
+            {
                 OC_LOG(ERROR, TAG, PCF("URI already in use"));
                 return OC_STACK_INVALID_PARAM;
             }
@@ -996,7 +2538,9 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
     }
     // Create the pointer and insert it into the resource list
     pointer = (OCResource *) OCCalloc(1, sizeof(OCResource));
-    if (!pointer) {
+    if (!pointer)
+    {
+        result = OC_STACK_NO_MEMORY;
         goto exit;
     }
     pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
@@ -1006,7 +2550,9 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
     // Set the uri
     size = strlen(uri) + 1;
     str = (char *) OCMalloc(size);
-    if (!str) {
+    if (!str)
+    {
+        result = OC_STACK_NO_MEMORY;
         goto exit;
     }
     strncpy(str, uri, size);
@@ -1018,14 +2564,16 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
 
     // Add the resourcetype to the resource
     result = BindResourceTypeToResource(pointer, resourceTypeName);
-    if (result != OC_STACK_OK) {
+    if (result != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, PCF("Error adding resourcetype"));
         goto exit;
     }
 
     // Add the resourceinterface to the resource
     result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
-    if (result != OC_STACK_OK) {
+    if (result != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface"));
         goto exit;
     }
@@ -1061,27 +2609,6 @@ exit:
     return result;
 }
 
-
-
-/**
- * Create a resource. with host ip address for remote resource
- *
- * @param handle - pointer to handle to newly created resource.  Set by ocstack.
- *                 Used to refer to resource
- * @param resourceTypeName - name of resource type.  Example: "core.led"
- * @param resourceInterfaceName - name of resource interface.  Example: "core.rw"
- * @param host - HOST address of the remote resource.  Example:  "coap://xxx.xxx.xxx.xxx:xxxxx"
- * @param uri - URI of the resource.  Example:  "/a/led"
- * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
- *                        NULL for default entity handler
- * @param resourceProperties - properties supported by resource.
- *                             Example: OC_DISCOVERABLE|OC_OBSERVABLE
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- */
-
 OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
         const char *resourceTypeName,
         const char *resourceInterfaceName,
@@ -1090,44 +2617,44 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
         OCEntityHandler entityHandler,
         uint8_t resourceProperties)
 {
+    OC_LOG(INFO, TAG, PCF("Entering OCCreateResourceWithHost"));
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
+
+    if(!host)
+    {
+        OC_LOG(ERROR, TAG, PCF("Added resource host is NULL."));
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
 
     result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
                                 uri, entityHandler, resourceProperties);
 
-    if (result != OC_STACK_ERROR)
+    if (result == OC_STACK_OK)
     {
         // Set the uri
         size = strlen(host) + 1;
         str = (char *) OCMalloc(size);
         if (!str)
         {
-            return OC_STACK_ERROR;
+            OC_LOG(ERROR, TAG, PCF("Memory could not be allocated."));
+            return OC_STACK_NO_MEMORY;
         }
         strncpy(str, host, size);
+
         ((OCResource *) *handle)->host = str;
     }
 
     return result;
 }
 
-/**
- * Add a resource to a collection resource.
- *
- * @param collectionHandle - handle to the collection resource
- * @param resourceHandle - handle to resource to be added to the collection resource
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- *     OC_STACK_INVALID_PARAM - invalid collectionhandle
- */
 OCStackResult OCBindResource(
-        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 OCBindResource"));
 
@@ -1135,55 +2662,50 @@ OCStackResult OCBindResource(
     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("Added 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 (!resource->rsrcResources[i]) {
+    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    {
+        if (!resource->rsrcResources[i])
+        {
             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;
 }
 
-/**
- * Remove a resource from a collection resource.
- *
- * @param collectionHandle - handle to the collection resource
- * @param resourceHandle - handle to resource to be added to the collection resource
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- *     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"));
 
@@ -1191,38 +2713,43 @@ 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"));
+
+            // Send notification when resource is unbounded successfully.
+            #ifdef WITH_PRESENCE
+            if(presenceResource.handle)
+            {
+                ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+                SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
+            }
+            #endif
             return OC_STACK_OK;
         }
     }
 
     OC_LOG(INFO, TAG, PCF("resource not found in collection"));
 
-    #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;
 }
@@ -1232,28 +2759,30 @@ 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"));
 
     // Validate parameters
     VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
-    // TODO:  Does resource attribute resentation really have to be maintained in stack?
+    // TODO:  Does resource attribute representation really have to be maintained in stack?
     // Is it presented during resource discovery?
 
-    TODO ("Make sure that the resourcetypename doesn't already exist in the resource");
-
     // Create the resourcetype and insert it into the resource list
     pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType));
-    if (!pointer) {
+    if (!pointer)
+    {
+        result = OC_STACK_NO_MEMORY;
         goto exit;
     }
 
     // Set the resourceTypeName
     size = strlen(resourceTypeName) + 1;
     str = (char *) OCMalloc(size);
-    if (!str) {
+    if (!str)
+    {
+        result = OC_STACK_NO_MEMORY;
         goto exit;
     }
     strncpy(str, resourceTypeName, size);
@@ -1262,7 +2791,9 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
     insertResourceType(resource, pointer);
     result = OC_STACK_OK;
 
-    exit: if (result != OC_STACK_OK) {
+    exit:
+    if (result != OC_STACK_OK)
+    {
         OCFree(pointer);
         OCFree(str);
     }
@@ -1275,7 +2806,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"));
@@ -1283,18 +2814,22 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
     // Validate parameters
     VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
 
-    TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
+    //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource");
 
     // Create the resourceinterface and insert it into the resource list
     pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface));
-    if (!pointer) {
+    if (!pointer)
+    {
+        result = OC_STACK_NO_MEMORY;
         goto exit;
     }
 
     // Set the resourceinterface name
     size = strlen(resourceInterfaceName) + 1;
     str = (char *) OCMalloc(size);
-    if (!str) {
+    if (!str)
+    {
+        result = OC_STACK_NO_MEMORY;
         goto exit;
     }
     strncpy(str, resourceInterfaceName, size);
@@ -1305,7 +2840,9 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
 
     result = OC_STACK_OK;
 
-    exit: if (result != OC_STACK_OK) {
+    exit:
+    if (result != OC_STACK_OK)
+    {
         OCFree(pointer);
         OCFree(str);
     }
@@ -1313,25 +2850,17 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
     return result;
 }
 
-/**
- * Bind a resourcetype to a resource.
- *
- * @param handle - handle to the resource
- * @param resourceTypeName - name of resource type.  Example: "core.led"
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     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;
     }
@@ -1350,26 +2879,17 @@ OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
     return result;
 }
 
-/**
- * Bind a resourceinterface to a resource.
- *
- * @param handle - handle to the resource
- * @param resourceInterfaceName - name of resource interface.  Example: "oc.mi.b"
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- */
-
 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;
     }
@@ -1388,79 +2908,54 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
     return result;
 }
 
-/**
- * Get the number of resources that have been created in the stack.
- *
- * @param numResources - pointer to count variable
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     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;
     }
     return OC_STACK_OK;
 }
 
-/**
- * Get a resource handle by index.
- *
- * @param index - index of resource, 0 to Count - 1
- *
- * @return
- *    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;
 }
 
-/**
- * Delete resource specified by handle.  Deletes resource and all resourcetype and resourceinterface
- * linked lists.
- *
- * @param handle - handle of resource to be deleted
- *
- * @return
- *     OC_STACK_OK              - no errors
- *     OC_STACK_ERROR           - stack process error
- *     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;
     }
@@ -1468,60 +2963,37 @@ OCStackResult OCDeleteResource(OCResourceHandle handle) {
     return OC_STACK_OK;
 }
 
-/**
- * Get the URI of the resource specified by handle.
- *
- * @param handle - handle of resource
- * @return
- *    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;
 }
 
-/**
- * Get the properties of the resource specified by handle.
- * NOTE: that after a resource is created, the OC_ACTIVE property is set
- * for the resource by the stack.
- *
- * @param handle - handle of resource
- * @return
- *    property bitmap - if resource found
- *    NULL - resource 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;
 }
 
-/**
- * Get the number of resource types of the resource.
- *
- * @param handle - handle of resource
- * @param numResourceTypes - pointer to count variable
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     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);
@@ -1530,9 +3002,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;
         }
@@ -1540,44 +3014,25 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
     return OC_STACK_OK;
 }
 
-/**
- * Get name of resource type of the resource.
- *
- * @param handle - handle of resource
- * @param index - index of resource, 0 to Count - 1
- *
- * @return
- *    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;
 }
 
-
-
-/**
- * Get the number of resource interfaces of the resource.
- *
- * @param handle - handle of resource
- * @param numResources - pointer to count variable
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     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"));
 
@@ -1586,9 +3041,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;
         }
@@ -1596,78 +3053,55 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
     return OC_STACK_OK;
 }
 
-/**
- * Get name of resource interface of the resource.
- *
- * @param handle - handle of resource
- * @param index - index of resource, 0 to Count - 1
- *
- * @return
- *    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;
 }
 
-/**
- * Get resource handle from the collection resource by index.
- *
- * @param collectionHandle - handle of collection resource
- * @param index - index of contained resource, 0 to Count - 1
- *
- * @return
- *    handle to resource - if resource found
- *    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;
     }
 
     return resource->rsrcResources[index];
 }
 
-/**
- * Bind an entity handler to the resource.
- *
- * @param handle - handle to the resource that the contained resource is to be bound
- * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc
- * @return
- *     OC_STACK_OK    - no errors
- *     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;
     }
@@ -1686,23 +3120,16 @@ OCStackResult OCBindResourceHandler(OCResourceHandle handle,
     return OC_STACK_OK;
 }
 
-/**
- * Get the entity handler for a resource.
- *
- * @param handle - handle of resource
- *
- * @return
- *    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;
     }
@@ -1723,18 +3150,10 @@ void incrementSequenceNumber(OCResource * resPtr)
 }
 
 #ifdef WITH_PRESENCE
-/**
- * Notify Presence subscribers that a resource has been modified
- *
- * @param resourceType - Handle to the resourceType linked list of resource
- *                       that was modified.
- * @param qos          - Quality Of Service
- *
- */
 OCStackResult SendPresenceNotification(OCResourceType *resourceType)
 {
     OCResource *resPtr = NULL;
-    OCStackResult result;
+    OCStackResult result = OC_STACK_ERROR;
     OCMethod method = OC_REST_PRESENCE;
     uint32_t maxAge = 0;
     resPtr = findResource((OCResource *) presenceResource.handle);
@@ -1742,36 +3161,42 @@ OCStackResult SendPresenceNotification(OCResourceType *resourceType)
     {
         return OC_STACK_NO_RESOURCE;
     }
+
     if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
     {
         maxAge = presenceResource.presenceTTL;
+
+        result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
     }
-    else
+
+    return result;
+}
+
+OCStackResult SendStopNotification()
+{
+    OCResource *resPtr = NULL;
+    OCStackResult result = OC_STACK_ERROR;
+    OCMethod method = OC_REST_PRESENCE;
+    resPtr = findResource((OCResource *) presenceResource.handle);
+    if(NULL == resPtr)
     {
-        maxAge = 0;
+        return OC_STACK_NO_RESOURCE;
     }
 
-    result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS);
+    // maxAge is 0. ResourceType is NULL.
+    result = SendAllObserverNotification(method, resPtr, 0, NULL, OC_LOW_QOS);
+
     return result;
 }
-#endif
 
-/**
- * Notify observers that an observed value has changed.
- *
- * @param handle - handle of resource
- *
- * @return
- *     OC_STACK_OK    - no errors
- *     OC_STACK_NO_RESOURCE - invalid resource handle
- *     OC_STACK_NO_OBSERVERS - no more observers intrested in resource
- */
-OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
+#endif // WITH_PRESENCE
+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;
 
@@ -1809,7 +3234,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"));
@@ -1836,20 +3261,6 @@ OCNotifyListOfObservers (OCResourceHandle handle,
             notificationJSONPayload, maxAge, qos));
 }
 
-/**
- * Send a response to a request.
- * The response can be a regular, slow, or block (i.e. a response that
- * is too large to be sent in a single PDU and must span multiple transmissions)
- *
- * @param response - pointer to structure that contains response parameters
- *
- * @return
- *     OC_STACK_OK                         - No errors; Success
- *     OC_STACK_INVALID_PARAM              - Invalid pointer to OCServerResponse
- *     OC_STACK_INVALID_REQUEST_HANDLE     - Request handle not found
- *     OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a
- *                                           persistent response buffer is necessary
- */
 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
 {
     OCStackResult result = OC_STACK_ERROR;
@@ -1883,7 +3294,6 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
     else
     {
         // Normal response
-
         // Get pointer to request info
         serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
         if(serverRequest)
@@ -1894,51 +3304,33 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
     return result;
 }
 
-/**
- * Cancel a response.  Applies to a block response
- *
- * @param responseHandle - response handle set by stack in OCServerResponse after
- *                         OCDoResponse is called
- *
- * @return
- *     OC_STACK_OK               - No errors; Success
- *     OC_STACK_INVALID_PARAM    - The handle provided is invalid.
- */
-OCStackResult OCCancelResponse(OCResponseHandle responseHandle)
-{
-    OCStackResult result = OC_STACK_NOTIMPL;
-
-    OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse"));
-
-    // TODO: validate response handle
-
-    return result;
-}
-
 //-----------------------------------------------------------------------------
 // Private internal function definitions
 //-----------------------------------------------------------------------------
-/**
- * Generate handle of OCDoResource invocation for callback management.
- */
 static OCDoHandle GenerateInvocationHandle()
 {
     OCDoHandle handle = NULL;
     // Generate token here, it will be deleted when the transaction is deleted
-    handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH]));
+    handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
     if (handle)
     {
-        OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH]));
+        OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
     }
 
     return handle;
 }
+
 #ifdef WITH_PRESENCE
 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
         OCResourceProperty resourceProperties, uint8_t enable)
 {
+    if (!inputProperty)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
     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;
     }
@@ -1954,16 +3346,15 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
 }
 #endif
 
-/**
- * Initialize resource data structures, variables, etc.
- */
-OCStackResult initResources() {
+OCStackResult initResources()
+{
     OCStackResult result = OC_STACK_OK;
     // Init application resource vars
     headResource = NULL;
+    tailResource = NULL;
     // Init Virtual Resources
     #ifdef WITH_PRESENCE
-    presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL;
+    presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
     //presenceResource.token = OCGenerateCoAPToken();
     result = OCCreateResource(&presenceResource.handle,
             OC_RSRVD_RESOURCE_TYPE_PRESENCE,
@@ -1975,44 +3366,33 @@ OCStackResult initResources() {
     result = OCChangeResourceProperty(
             &(((OCResource *) presenceResource.handle)->resourceProperties),
             OC_ACTIVE, 0);
-    #endif
-    return result;
-}
-
-/**
- * Add a resource to the end of the linked list of resources.
- *
- * @param resource - resource to be added
- */
-void insertResource(OCResource *resource) {
-    OCResource *pointer;
+    #endif
+    return result;
+}
 
-    if (!headResource) {
+void insertResource(OCResource *resource)
+{
+    if (!headResource)
+    {
         headResource = resource;
-    } else {
-        pointer = headResource;
-
-        while (pointer->next) {
-            pointer = pointer->next;
-        }
-        pointer->next = resource;
+        tailResource = resource;
+    }
+    else
+    {
+        tailResource->next = resource;
+        tailResource = resource;
     }
     resource->next = NULL;
 }
 
-/**
- * Find a resource in the linked list of resources.
- *
- * @param resource - resource to be found
- * @return
- *     NULL                - resource not found
- *     pointer to resource - pointer to resource that was found in the linked list
- */
-OCResource *findResource(OCResource *resource) {
+OCResource *findResource(OCResource *resource)
+{
     OCResource *pointer = headResource;
 
-    while (pointer) {
-        if (pointer == resource) {
+    while (pointer)
+    {
+        if (pointer == resource)
+        {
             return resource;
         }
         pointer = pointer->next;
@@ -2023,7 +3403,7 @@ OCResource *findResource(OCResource *resource) {
 void deleteAllResources()
 {
     OCResource *pointer = headResource;
-    OCResource *temp;
+    OCResource *temp = NULL;
 
     while (pointer)
     {
@@ -2031,9 +3411,9 @@ void deleteAllResources()
         #ifdef WITH_PRESENCE
         if(pointer != (OCResource *) presenceResource.handle)
         {
-            #endif // WITH_PRESENCE
+        #endif // WITH_PRESENCE
             deleteResource(pointer);
-            #ifdef WITH_PRESENCE
+        #ifdef WITH_PRESENCE
         }
         #endif // WITH_PRESENCE
         pointer = temp;
@@ -2046,21 +3426,16 @@ void deleteAllResources()
     #endif // WITH_PRESENCE
 }
 
-/**
- * Delete the resource from the linked list.
- *
- * @param resource - resource to be deleted
- * @return
- *    0 - error
- *    1 - success
- */
-int deleteResource(OCResource *resource) {
+OCStackResult deleteResource(OCResource *resource)
+{
     OCResource *prev = NULL;
-    OCResource *temp;
+    OCResource *temp = NULL;
 
     temp = headResource;
-    while (temp) {
-        if (temp == resource) {
+    while (temp)
+    {
+        if (temp == resource)
+        {
             // Invalidate all Resource Properties.
             resource->resourceProperties = (OCResourceProperty) 0;
             #ifdef WITH_PRESENCE
@@ -2083,33 +3458,47 @@ int deleteResource(OCResource *resource) {
                     SendPresenceNotification(NULL);
                 }
             }
-        #endif
-
-            if (temp == headResource) {
+            #endif
+            // Only resource in list.
+            if (temp == headResource && temp == tailResource)
+            {
+                headResource = NULL;
+                tailResource = NULL;
+            }
+            // Deleting head.
+            else if (temp == headResource)
+            {
                 headResource = temp->next;
-            } else {
+            }
+            // Deleting tail.
+            else if (temp == tailResource)
+            {
+                tailResource = prev;
+                tailResource->next = NULL;
+            }
+            else
+            {
                 prev->next = temp->next;
             }
 
             deleteResourceElements(temp);
             OCFree(temp);
-            return 1;
-        } else {
+            return OC_STACK_OK;
+        }
+        else
+        {
             prev = temp;
             temp = temp->next;
         }
     }
 
-    return 0;
+    return OC_STACK_ERROR;
 }
 
-/**
- * Delete all of the dynamically allocated elements that were created for the resource.
- *
- * @param resource - specified resource
- */
-void deleteResourceElements(OCResource *resource) {
-    if (!resource) {
+void deleteResourceElements(OCResource *resource)
+{
+    if (!resource)
+    {
         return;
     }
 
@@ -2123,16 +3512,13 @@ void deleteResourceElements(OCResource *resource) {
     deleteResourceInterface(resource->rsrcInterface);
 }
 
-/**
- * Delete all of the dynamically allocated elements that were created for the resource type.
- *
- * @param resourceType - specified resource type
- */
-void deleteResourceType(OCResourceType *resourceType) {
+void deleteResourceType(OCResourceType *resourceType)
+{
     OCResourceType *pointer = resourceType;
-    OCResourceType *next;
+    OCResourceType *next = NULL;
 
-    while (pointer) {
+    while (pointer)
+    {
         next = pointer->next;
         OCFree(pointer->resourcetypename);
         OCFree(pointer);
@@ -2140,16 +3526,13 @@ void deleteResourceType(OCResourceType *resourceType) {
     }
 }
 
-/**
- * Delete all of the dynamically allocated elements that were created for the resource interface.
- *
- * @param resourceInterface - specified resource interface
- */
-void deleteResourceInterface(OCResourceInterface *resourceInterface) {
+void deleteResourceInterface(OCResourceInterface *resourceInterface)
+{
     OCResourceInterface *pointer = resourceInterface;
-    OCResourceInterface *next;
+    OCResourceInterface *next = NULL;
 
-    while (pointer) {
+    while (pointer)
+    {
         next = pointer->next;
         OCFree(pointer->name);
         OCFree(pointer);
@@ -2157,80 +3540,67 @@ void deleteResourceInterface(OCResourceInterface *resourceInterface) {
     }
 }
 
-/**
- * Insert a resource type into a resource's resource type linked list.
- *
- * @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;
-
-    if (resource && !resource->rsrcType) {
+void insertResourceType(OCResource *resource, OCResourceType *resourceType)
+{
+    OCResourceType *pointer = NULL;
+    OCResourceType *previous = NULL;
+    if (!resource || !resourceType)
+    {
+        return;
+    }
+    // resource type list is empty.
+    else if (!resource->rsrcType)
+    {
         resource->rsrcType = resourceType;
-    } else {
-        if(resource)
-        {
-            pointer = resource->rsrcType;
-        }
-        else
+    }
+    else
+    {
+        pointer = resource->rsrcType;
+
+        while (pointer)
         {
-            pointer = resourceType;
-        }
-        while (pointer->next) {
+            // resource type already exists. Free 2nd arg and return.
+            if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
+            {
+                OCFree(resourceType->resourcetypename);
+                OCFree(resourceType);
+                return;
+            }
+            previous = pointer;
             pointer = pointer->next;
         }
-        pointer->next = resourceType;
+        previous->next = resourceType;
     }
     resourceType->next = NULL;
 }
 
-/**
- * Get a resource type at the specified index within a resource.
- *
- * @param handle - handle of resource
- * @param index - index of resource type
- *
- * @return
- *    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);
-    if (!resource) {
+    if (!resource)
+    {
         return NULL;
     }
 
     // Make sure a resource has a resourcetype
-    if (!resource->rsrcType) {
+    if (!resource->rsrcType)
+    {
         return NULL;
     }
 
     // Iterate through the list
     pointer = resource->rsrcType;
-    i = 0;
-    while ((i < index) && pointer) {
-        i++;
+    for(uint8_t i = 0; i< index && pointer; ++i)
+    {
         pointer = pointer->next;
     }
     return pointer;
 }
 
-/**
- * Finds a resource type in an OCResourceType link-list.
- *
- * @param resourceTypeList - the link-list to be searched through
- * @param resourceTypeName - the key to search for
- *
- * @return
- *      resourceType that matches the key (ie. resourceTypeName)
- *      NULL - either an invalid parameter or this function was unable to find the key.
- */
 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
 {
     if(resourceTypeList && resourceTypeName)
@@ -2250,81 +3620,89 @@ OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char *
     }
     return NULL;
 }
-/**
- * Insert a resource interface into a resource's resource interface linked list.
- *
- * @param resource - resource where resource interface is to be inserted
- * @param resourceInterface - resource interface to be inserted
+
+/*
+ * Insert a new interface into interface linked list only if not already present.
+ * If alredy present, 2nd arg is free'd.
+ * Default interface will always be first if present.
  */
-void insertResourceInterface(OCResource *resource,
-        OCResourceInterface *resourceInterface) {
-    OCResourceInterface *pointer;
+void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
+{
+    OCResourceInterface *pointer = NULL;
+    OCResourceInterface *previous = NULL;
 
-    if (!resource->rsrcInterface) {
-        resource->rsrcInterface = resourceInterface;
-    } else {
-        pointer = resource->rsrcInterface;
-        while (pointer->next) {
+    newInterface->next = NULL;
+
+    OCResourceInterface **firstInterface = &(resource->rsrcInterface);
+
+    if (!*firstInterface)
+    {
+        *firstInterface = newInterface;
+    }
+    else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
+    {
+        if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
+        {
+            OCFree(newInterface->name);
+            OCFree(newInterface);
+            return;
+        }
+        else
+        {
+            newInterface->next = *firstInterface;
+            *firstInterface = newInterface;
+        }
+    }
+    else
+    {
+        pointer = *firstInterface;
+        while (pointer)
+        {
+            if (strcmp(newInterface->name, pointer->name) == 0)
+            {
+                OCFree(newInterface->name);
+                OCFree(newInterface);
+                return;
+            }
+            previous = pointer;
             pointer = pointer->next;
         }
-        pointer->next = resourceInterface;
+        previous->next = newInterface;
     }
-    resourceInterface->next = NULL;
 }
 
-/**
- * Get a resource interface at the specified index within a resource.
- *
- * @param handle - handle of resource
- * @param index - index of resource interface
- *
- * @return
- *    resourceinterface - if found
- *    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;
 }
 
-/**
- * Determine if a request/response must be sent in a block transfer because it is too large to be
- * sent in a single PDU.  This function can be used for either a request or a response
- *
- * @param request  - NULL or pointer to request
- * @param response - NULL or pointer to response
- * @param size     - 0 or size of the request/response.  If 0, strlen is used for determining
- *                   the length of the request/response
- *
- * @return
- *    0 - packet transfer NOT required (i.e. normal request/response)
- *    1 - packet transfer required (i.e. block transfer needed)
- */
-uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size)
+bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size)
 {
-    uint8_t result = 0;
+    bool result = false;
 
     // Determine if we are checking a request or a response
     if (request)
@@ -2333,7 +3711,7 @@ uint8_t OCIsPacketTransferRequired(const char *request, const char *response, ui
         // assume request is null terminated and use strlen for size value
         if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH))
         {
-            result = 1;
+            result = true;
         }
     }
     else if (response)
@@ -2342,68 +3720,241 @@ uint8_t OCIsPacketTransferRequired(const char *request, const char *response, ui
         // assume response is null terminated and use strlen for size value
         if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH))
         {
-            result = 1;
+            result = true;
         }
     }
     return result;
 }
 
-/**
- * Retrieves a resource type based upon a uri string if the uri string contains only just one
- * resource attribute (and that has to be of type "rt").
- *
- * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType
- * or newURI before passing in.
- *
- * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API.
- * @param resourceType - The resource type to be populated; pass by reference.
- * @param newURI - Return URI without resourceType appended to the end of it. This is used to
- *                 ensure that the uri parameter is not modified; pass by reference.
- *
- * @return
- *  OC_STACK_INVALID_URI   - Returns this if the URI is invalid/NULL.
- *  OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
- *  OC_STACK_OK            - Success
+OCStackResult getResourceType(const char * query, char** resourceType)
+{
+    if(!query)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult result = OC_STACK_ERROR;
+
+    if(strncmp(query, "rt=", 3) == 0)
+    {
+        *resourceType = (char *) OCMalloc(strlen(query)-3 + 1);
+        if(!*resourceType)
+        {
+            result = OC_STACK_NO_MEMORY;
+        }
+        else
+        {
+            strcpy((char *)*resourceType, ((const char *)&query[3]));
+            result = OC_STACK_OK;
+        }
+    }
+
+    return result;
+}
+
+/*
+ * This function splits the uri using the '?' delimiter.
+ * "uriWithoutQuery" is the block of characters between the beginning
+ * till the delimiter or '\0' which ever comes first.
+ * "query" is whatever is to the right of the delimiter if present.
+ * No delimiter sets the query to NULL.
+ * If either are present, they will be malloc'ed into the params 2, 3.
+ * The first param, *uri is left untouched.
+
+ * NOTE: This function does not account for whitespace at the end of the uri NOR
+ *       malformed uri's with '??'. Whitespace at the end will be assumed to be
+ *       part of the query.
  */
-OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI)
+OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
 {
     if(!uri)
     {
         return OC_STACK_INVALID_URI;
     }
-    if(!resourceType || !newURI)
+    if(!query || !uriWithoutQuery)
     {
         return OC_STACK_INVALID_PARAM;
     }
-    char * leftToken = NULL;
-    char * tempURI = (char *) OCMalloc(strlen(uri) + 1);
-    if(!tempURI)
+
+    *query           = NULL;
+    *uriWithoutQuery = NULL;
+
+    size_t uriWithoutQueryLen = 0;
+    size_t queryLen = 0;
+    size_t uriLen = strlen(uri);
+
+    char *pointerToDelimiter = strstr(uri, "?");
+
+    uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri;
+    queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
+
+    if (uriWithoutQueryLen)
+    {
+        *uriWithoutQuery =  (char *) OCCalloc(uriWithoutQueryLen + 1, 1);
+        if (!*uriWithoutQuery)
+        {
+            goto exit;
+        }
+        strncpy(*uriWithoutQuery, uri, uriWithoutQueryLen);
+    }
+    else
     {
-        goto exit;
+        return OC_STACK_INVALID_PARAM;
     }
-    strcpy(tempURI, uri);
-    char* strTokPtr;
-    leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
 
-    while(leftToken != NULL)
+    if (queryLen)
     {
-        if(strncmp(leftToken, "rt=", 3) == 0)
+        *query = (char *) OCCalloc(queryLen + 1, 1);
+        if (!*query)
         {
-            *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3);
-            if(!*resourceType)
-            {
-                goto exit;
-            }
-            strcpy((char *)*resourceType, ((const char *)&leftToken[3]));
-            break;
+            OCFree(*uriWithoutQuery);
+            *uriWithoutQuery = NULL;
+            goto exit;
         }
-        leftToken = strtok_r(NULL, "?", &strTokPtr);
+        strncpy(*query, pointerToDelimiter + 1, queryLen);
     }
 
-    *newURI = tempURI;
-
     return OC_STACK_OK;
 
     exit:
         return OC_STACK_NO_MEMORY;
 }
+
+const uint8_t* OCGetServerInstanceID(void)
+{
+    static bool generated = false;
+    static ServerID sid;
+    if(generated)
+    {
+        return sid;
+    }
+
+    if (OCGenerateUuid(sid) != RAND_UUID_OK)
+    {
+        OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!"));
+        return NULL;
+    }
+    generated = true;
+    return sid;
+}
+
+const char* OCGetServerInstanceIDString(void)
+{
+    static bool generated = false;
+    static char sidStr[UUID_STRING_SIZE];
+
+    if(generated)
+    {
+        return sidStr;
+    }
+
+    const uint8_t* sid = OCGetServerInstanceID();
+
+    if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK)
+    {
+        OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!"));
+        return NULL;
+    }
+
+    generated = true;
+    return sidStr;
+}
+
+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, PCF("Invalid argument"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    *a = ipAddr->addr[0];
+    *b = ipAddr->addr[1];
+    *c = ipAddr->addr[2];
+    *d = ipAddr->addr[3];
+
+    return OC_STACK_OK;
+}
+
+int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
+{
+    if ( !ipAddr || !port )
+    {
+        OC_LOG(FATAL, TAG, PCF("Invalid argument"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    *port = (ipAddr->addr[5]<< 8) | ipAddr->addr[4];
+
+    return OC_STACK_OK;
+}
+
+CAResult_t OCSelectNetwork()
+{
+    CAResult_t retResult = CA_STATUS_FAILED;
+    CAResult_t caResult = CA_STATUS_OK;
+
+    CATransportType_t connTypes[] = {
+            CA_IPV4,
+            CA_EDR,
+            CA_LE};
+    int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
+
+    for(int i = 0; i<numConnTypes; i++)
+    {
+        // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
+        if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
+        {
+           caResult = CASelectNetwork(connTypes[i]);
+           if(caResult == CA_STATUS_OK)
+           {
+               retResult = CA_STATUS_OK;
+           }
+        }
+    }
+
+    if(retResult != CA_STATUS_OK)
+    {
+        return caResult; // Returns error of appropriate transport that failed fatally.
+    }
+
+    return retResult;
+}
+
+OCStackResult CAResultToOCResult(CAResult_t caResult)
+{
+    switch (caResult)
+    {
+        case CA_STATUS_OK:
+            return OC_STACK_OK;
+        case CA_STATUS_INVALID_PARAM:
+            return OC_STACK_INVALID_PARAM;
+        case CA_ADAPTER_NOT_ENABLED:
+            return OC_STACK_ADAPTER_NOT_ENABLED;
+        case CA_SERVER_STARTED_ALREADY:
+            return OC_STACK_OK;
+        case CA_SERVER_NOT_STARTED:
+            return OC_STACK_ERROR;
+        case CA_DESTINATION_NOT_REACHABLE:
+            return OC_STACK_COMM_ERROR;
+        case CA_SOCKET_OPERATION_FAILED:
+            return OC_STACK_COMM_ERROR;
+        case CA_SEND_FAILED:
+            return OC_STACK_COMM_ERROR;
+        case CA_RECEIVE_FAILED:
+            return OC_STACK_COMM_ERROR;
+        case CA_MEMORY_ALLOC_FAILED:
+            return OC_STACK_NO_MEMORY;
+        case CA_REQUEST_TIMEOUT:
+            return OC_STACK_TIMEOUT;
+        case CA_DESTINATION_DISCONNECTED:
+            return OC_STACK_COMM_ERROR;
+        case CA_STATUS_FAILED:
+            return OC_STACK_ERROR;
+        case CA_NOT_SUPPORTED:
+            return OC_STACK_NOTIMPL;
+        default:
+            return OC_STACK_ERROR;
+    }
+}
index b9f70ac..47d34be 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #define _POSIX_C_SOURCE 200112L
+
 #include <string.h>
 
+#include "oicgroup.h"
 #include "cJSON.h"
 #include "ocmalloc.h"
-#include "oicgroup.h"
-#include "ocresource.h"
 #include "occollection.h"
+#include "logger.h"
+#include "timer.h"
+
+#ifndef WITH_ARDUINO
+#include <pthread.h>
+#endif
 
 #define TAG PCF("OICGROUP")
 
-#define DESC_DELIMITER "\""
-#define ACTION_DELIMITER "*"
-#define ATTR_DELIMITER "|"
+#define DESC_DELIMITER          "\""
+#define ACTION_DELIMITER        "*"
+#define ATTR_DELIMITER          "|"
+#define ATTR_ASSIGN             "="
+
+// Definitions for operations related to actions
+#define DO_ACTION               "DoAction"
+#define GET_ACTIONSET           "GetActionSet"
+#define ACTIONSET               "ActionSet"
+#define DELETE_ACTIONSET        "DelActionSet"
+
+#define OIC_ACTION_PREFIX               "{\"oc\":[{\"rep\":{"
+#define VARIFY_POINTER_NULL(pointer, result, toExit) \
+    if(pointer == NULL) \
+    {\
+        result = OC_STACK_NO_MEMORY;\
+        goto toExit;\
+    }
+#define VARIFY_PARAM_NULL(pointer, result, toExit) \
+    if(pointer == NULL)\
+    {\
+        result = OC_STACK_INVALID_PARAM;\
+        goto exit;\
+    }
+
+#define OCFREE(pointer) \
+    { \
+        OCFree(pointer); \
+        pointer = NULL; \
+    }
+
+#ifndef WITH_ARDUINO
+pthread_mutex_t lock;
+#endif
+
+enum ACTION_TYPE
+{
+    NONE = 0, SCHEDULED, RECURSIVE
+};
+
+typedef struct scheduledresourceinfo
+{
+    OCResource *resource;
+    OCActionSet *actionset;
+
+    int timer_id;
+
+    OCServerRequest *ehRequest;
+
+    time_t time;
+    struct scheduledresourceinfo* next;
+} ScheduledResourceInfo;
+
+ScheduledResourceInfo *scheduleResourceList = NULL;
+
+void AddScheduledResource(ScheduledResourceInfo **head,
+        ScheduledResourceInfo* add)
+{
+    OC_LOG(INFO, TAG, PCF("AddScheduledResource Entering..."));
+
+#ifndef WITH_ARDUINO
+    pthread_mutex_lock(&lock);
+#endif
+    ScheduledResourceInfo *tmp = NULL;
+
+    if (*head != NULL)
+    {
+        tmp = *head;
+
+        while (tmp->next)
+        {
+            tmp = tmp->next;
+        }
+        tmp->next = add;
+    }
+    else
+    {
+        *head = add;
+    }
+#ifndef WITH_ARDUINO
+    pthread_mutex_unlock(&lock);
+#endif
+}
+
+ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
+{
+    OC_LOG(INFO, TAG, PCF("GetScheduledResource Entering..."));
+
+#ifndef WITH_ARDUINO
+    pthread_mutex_lock(&lock);
+#endif
+
+    time_t t_now;
+
+    ScheduledResourceInfo *tmp = NULL;
+    tmp = head;
+
+#ifndef WITH_ARDUINO
+    time(&t_now);
+#else
+    t_now = now();
+#endif
+
+    if (tmp)
+    {
+        while (tmp)
+        {
+            time_t diffTm = 0;
+#ifndef WITH_ARDUINO
+            diffTm = timespec_diff(tmp->time, t_now);
+#else
+            diffTm = timespec_diff(tmp->time, t_now);
+#endif
+
+            if (diffTm <= (time_t) 0)
+            {
+                OC_LOG(INFO, TAG, PCF("return Call INFO."));
+                goto exit;
+            }
+
+            tmp = tmp->next;
+        }
+    }
+
+    exit:
+#ifndef WITH_ARDUINO
+    pthread_mutex_unlock(&lock);
+#endif
+    if (tmp == NULL)
+    {
+        OC_LOG(INFO, TAG, PCF("Cannot Find Call Info."));
+    }
+    return tmp;
+}
+
+ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo *head, char *setName)
+{
+    OC_LOG(INFO, TAG, PCF("GetScheduledResourceByActionSetName Entering..."));
+
+#ifndef WITH_ARDUINO
+    pthread_mutex_lock(&lock);
+#endif
+    ScheduledResourceInfo *tmp = NULL;
+    tmp = head;
+
+    if (tmp)
+    {
+        while (tmp)
+        {
+            if (strcmp(tmp->actionset->actionsetName, setName) == 0)
+            {
+                OC_LOG(INFO, TAG, PCF("return Call INFO."));
+                goto exit;
+            }
+            tmp = tmp->next;
+        }
+    }
+
+exit:
+#ifndef WITH_ARDUINO
+    pthread_mutex_unlock(&lock);
+#endif
+    if (tmp == NULL)
+    {
+        OC_LOG(INFO, TAG, PCF("Cannot Find Call Info."));
+    }
+    return tmp;
+}
+
+void RemoveScheduledResource(ScheduledResourceInfo **head,
+        ScheduledResourceInfo* del)
+{
+#ifndef WITH_ARDUINO
+    pthread_mutex_lock(&lock);
+#endif
+    OC_LOG(INFO, TAG, PCF("RemoveScheduledResource Entering..."));
+    ScheduledResourceInfo *tmp = NULL;
+
+    if (del == NULL)
+    {
+        return;
+    }
+
+    if (*head == del)
+    {
+        *head = (*head)->next;
+    }
+    else
+    {
+        tmp = *head;
+        while (tmp->next && (tmp->next != del))
+        {
+            tmp = tmp->next;
+        }
+        if (tmp->next)
+        {
+            tmp->next = del->next;
+        }
+    }
+
+    OCFREE(del)
+#ifndef WITH_ARDUINO
+    pthread_mutex_unlock(&lock);
+#endif
+}
 
 typedef struct aggregatehandleinfo
 {
@@ -40,16 +248,13 @@ typedef struct aggregatehandleinfo
     OCResource *collResource;
 
     struct aggregatehandleinfo *next;
-} ClientRequstInfo;
-
-// unsigned int nHandleIdx = 0;
-// ClientRequstInfo g_AggregateResponseHandle[10];
+} ClientRequestInfo;
 
-ClientRequstInfo *clientRequstList = NULL;
+ClientRequestInfo *clientRequstList = NULL;
 
-void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add)
+void AddClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* add)
 {
-    ClientRequstInfo *tmp = NULL;
+    ClientRequestInfo *tmp = NULL;
 
     if (*head != NULL)
     {
@@ -67,9 +272,10 @@ 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;
 
@@ -77,7 +283,6 @@ ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle
     {
         while (tmp)
         {
-//            printf("%p :: %p\n", tmp->required, handle);
             if (tmp->required == handle)
             {
                 break;
@@ -91,9 +296,12 @@ 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 (del == NULL)
+        return;
 
     if (*head == del)
     {
@@ -113,8 +321,6 @@ void RemoveClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* del)
     }
 }
 
-
-
 void AddCapability(OCCapability** head, OCCapability* node)
 {
     OCCapability *pointer = *head;
@@ -152,31 +358,46 @@ void AddAction(OCAction** head, OCAction* node)
     }
 }
 
-void AddActionSet(OCActionSet **head, OCActionSet* node)
+OCStackResult AddActionSet(OCActionSet **head, OCActionSet* node)
 {
     OCActionSet *pointer = *head;
+    OCActionSet *prev = NULL;
+    if(node == NULL)
+    {
+        return OC_STACK_ERROR;
+    }
     if (NULL == pointer)
     {
         *head = node;
     }
     else
     {
-
-        while (pointer->next != NULL)
+        prev = pointer;
+        while (pointer != NULL)
         {
+            // check the uniqeness of actionsetname.
+            if (strcmp(pointer->actionsetName, node->actionsetName) == 0)
+            {
+                return OC_STACK_ERROR;
+            }
+
+            prev = pointer;
             pointer = pointer->next;
         }
 
-        pointer->next = node;
+        prev->next = node;
     }
+
+    return OC_STACK_OK;
 }
 
 void DeleteCapability(OCCapability *del)
 {
-    free(del->capability);
+    OCFREE(del->capability)
     del->capability = NULL;
-    free(del->status);
+    OCFREE(del->status)
     del->status = NULL;
+    OCFREE(del)
 }
 
 void DeleteAction(OCAction** action)
@@ -190,15 +411,17 @@ void DeleteAction(OCAction** action)
         pointer = pointer->next;
 
         DeleteCapability(pDel);
-        pDel->next = NULL;
     }
-    OCFree((*action)->resourceUri);
-    (*action)->resourceUri = NULL;
+    OCFREE((*action)->resourceUri)
     (*action)->next = NULL;
+    OCFREE(*action)
 }
 
 void DeleteActionSet(OCActionSet** actionset)
 {
+    if(*actionset == NULL)
+        return;
+
     OCAction* pointer = (*actionset)->head;
     OCAction* pDel = NULL;
 
@@ -208,19 +431,17 @@ void DeleteActionSet(OCActionSet** actionset)
         pointer = pointer->next;
 
         DeleteAction(&pDel);
-        pDel->next = NULL;
     }
-
-    OCFree((*actionset)->actionsetName);
-    (*actionset)->head = NULL;
+    //    (*actionset)->head = NULL;
+    OCFREE((*actionset)->actionsetName)
+    OCFREE(*actionset)
 }
 
-OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actionsetName)
+OCStackResult FindAndDeleteActionSet(OCResource **resource,
+        const char * actionsetName)
 {
-
     if (*resource != NULL)
     {
-
         OCActionSet *pointer = NULL;
         OCActionSet *pDel = NULL;
 
@@ -240,7 +461,6 @@ OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actions
                     (*resource)->actionsetHead = NULL;
 
                 DeleteActionSet(&pointer);
-
             }
             else if (pointer->next != NULL)
             {
@@ -248,7 +468,8 @@ OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actions
                 {
                     if (pointer->next != NULL)
                     {
-                        if (strcmp(pointer->next->actionsetName, actionsetName) == 0)
+                        if (strcmp(pointer->next->actionsetName, actionsetName)
+                                == 0)
                         {
                             pDel = pointer->next;
                             pointer->next = pointer->next->next;
@@ -256,6 +477,7 @@ OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actions
                             DeleteActionSet(&pDel);
                         }
                     }
+                    pointer = pointer->next;
                 }
             }
 
@@ -263,7 +485,6 @@ OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actions
         }
 
     }
-
     return OC_STACK_ERROR;
 }
 
@@ -285,7 +506,8 @@ OCStackResult DeleteActionSets(OCResource** resource)
     return OC_STACK_OK;
 }
 
-OCStackResult GetActionSet(const char *actionName, OCActionSet *head, OCActionSet** actionset)
+OCStackResult GetActionSet(const char *actionName, OCActionSet *head,
+        OCActionSet** actionset)
 {
     OCActionSet *pointer = head;
 
@@ -304,227 +526,226 @@ OCStackResult GetActionSet(const char *actionName, OCActionSet *head, OCActionSe
 
 }
 
-OCStackResult GetActionSetFromString(OCResource **resource, unsigned char *request, char** method,
-        char **actionsetName)
+OCStackResult ExtractKeyValueFromRequest(char *request, char **key,
+        char **value)
 {
-    char *acitonRequest;
-    char *iterTokenPtr = NULL;
-    char *iterToken = NULL;
-    char *description = NULL;
-    char *iterDescPtr = NULL;
+    OCStackResult result = OC_STACK_OK;
+    size_t length = 0;
+
+    char* pRequest = (char *) request + strlen(OIC_ACTION_PREFIX);
+    char* iterToken, *iterTokenPtr;
+
+    iterToken = (char *) strtok_r(pRequest, ":", &iterTokenPtr);
+    VARIFY_POINTER_NULL(iterToken, result, exit);
+    length = strlen(iterToken) + 1;
 
-    char *attributes = NULL;
-    char *iterAttrbutesPtr = NULL;
+    *key = (char *) OCMalloc(length);
+    VARIFY_POINTER_NULL(*key, result, exit)
 
-    char *attr = NULL;
-    char *iterAttrPtr = NULL;
+    strncpy(*key, iterToken + 1, length);
+    ((*key)[((length - 1) - 2)]) = '\0';
 
-    OCActionSet* actionset = NULL;
-    OCAction* action = NULL;
+    iterToken = (char *) strtok_r(NULL, "}", &iterTokenPtr);
+    VARIFY_POINTER_NULL(iterToken, result, exit);
+    length = strlen(iterToken) + 1;
 
-    acitonRequest = (char *) OCMalloc(strlen((char *) request) + 1);
-    strncpy(acitonRequest, (char *) request, strlen((char *) request) + 1);
+    *value = (char *) OCMalloc(length);
+    VARIFY_POINTER_NULL(*value, result, exit)
 
-    //printf("\t%s\n", acitonRequest);
-    if (acitonRequest != NULL)
+    strncpy(*value, iterToken + 1, length);
+    ((*value)[((length - 1) - 2)]) = '\0';
+
+exit:
+    if (result != OC_STACK_OK)
     {
-        iterToken = (char *) strtok_r(acitonRequest, DESC_DELIMITER, &iterTokenPtr);
+        OCFREE(*key)
+        OCFREE(*value)
+    }
 
-        while (iterToken != NULL)
-        {
-            if (strcmp(iterToken, "ActionSet") == 0)
-            { // if iterToken is ActionSet, will be created and added a new action set.
-
-                *method = (char *) OCMalloc(strlen(iterToken) + 1);
-                strncpy(*method, iterToken, strlen(iterToken) + 1);
-
-                //GetActionName(iterToken, &actionsetName);
-                // printf("%s\n", iterToken, &iterTokenPtr);
-                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is mean ':'.
-                // printf("%s\n", iterToken);
-                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is body of action description.
-                // printf("%s\n", iterToken);
-
-                // printf("DESC :: %s\n", iterToken);
-                description = (char *) OCMalloc(strlen(iterToken) + 1);
-                strncpy(description, iterToken, strlen(iterToken) + 1);
-                // printf("DESC Copied :: %s\n", description);
-
-                // Find the action name from description.
-                iterDescPtr = NULL;
-                iterToken = (char *) strtok_r(description, ACTION_DELIMITER, &iterDescPtr);
-                //while(iterToken != NULL)
-                if (iterToken != NULL)
-                {
-                    if (*actionsetName != NULL)
-                    {
-                        // printf("ERROR :: ACTIONSET NAME as ActionSet(%s)\n", iterToken);
-                        return OC_STACK_ERROR; // ERROR OCCURED.
-                    }
-                    else
-                    {
-                        //  Actionset name.
-                        // printf("ACTION SET NAME :: %s\n", iterToken);
-                        *actionsetName = (char *) OCMalloc(strlen(iterToken) + 1);
+    return result;
+}
 
-                        strncpy(*actionsetName, iterToken, strlen(iterToken) + 1);
-                        // printf("ACTION SET NAME :: %s\n", *actionsetName);
-                        // break;
-                    }
+OCStackResult ExtractActionSetNameAndDelaytime(char *pChar, char **setName,
+        long int *pa)
+{
+    char *token, *tokenPtr;
+    OCStackResult result = OC_STACK_OK;
 
-                    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr);
-                }
-                else
-                {
-                    return OC_STACK_ERROR;
+    token = (char*) strtok_r(pChar, ACTION_DELIMITER, &tokenPtr);
+    *setName = (char *) OCMalloc(strlen(token) + 1);
+    VARIFY_POINTER_NULL(*setName, result, exit)
+    VARIFY_PARAM_NULL(token, result, exit)
+    strncpy(*setName, token, strlen(token) + 1);
 
-                } // end Action Set Name.
+    token = strtok_r(NULL, ACTION_DELIMITER, &tokenPtr);
+    VARIFY_POINTER_NULL(pa, result, exit)
+    VARIFY_PARAM_NULL(token, result, exit)
+    *pa = atoi(token);
 
-                // New ActionSet Add to OCResource's ActionSet list.
-                // 1. Allocate a new pointer for actionset.
-                actionset = (OCActionSet*) OCMalloc(sizeof(OCActionSet));
-                // 2. Initiate actionset.
-                memset(actionset, 0, sizeof(OCActionSet));
-                actionset->actionsetName = (char *) OCMalloc(strlen(*actionsetName) + 1);
-                strncpy(actionset->actionsetName, *actionsetName, strlen(*actionsetName) + 1);
-                // printf("ACTION SET NAME :: %s\n", actionset->actionsetName);
+    return OC_STACK_OK;
 
-                while (iterToken != NULL)
-                {
-                    action = (OCAction *) OCMalloc(sizeof(OCAction));
-                    memset(action, 0, sizeof(OCAction));
+exit:
+    OCFREE(*setName);
+    return result;
+}
 
-                    // printf("ATTR Copied :: %s\n", iterToken);
-                    attributes = (char *) OCMalloc(strlen(iterToken) + 1);
-                    strncpy(attributes, iterToken, strlen(iterToken) + 1);
-                    // printf("ATTR Copied :: %s\n", attributes);
+OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
+{
+    OCStackResult result = OC_STACK_OK;
 
-                    iterToken = (char *) strtok_r(attributes, ATTR_DELIMITER, &iterAttrbutesPtr);
-                    while (iterToken != NULL)
-                    {
-                        attr = (char *) OCMalloc(strlen(iterToken) + 1);
-                        strncpy(attr, iterToken, strlen(iterToken) + 1);
+    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;
 
-                        iterToken = (char *) strtok_r(attr, "=", &iterAttrPtr);
-                        while (iterToken != NULL)
-                        {
-                            // Find the URI from description.
-                            if (strcmp(iterToken, "uri") == 0)
-                            {
-                                iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr);
-                                //printf("uri :: %s\n", iterToken);
-                                action->resourceUri = (char *) OCMalloc(strlen(iterToken) + 1);
-                                strncpy(action->resourceUri, iterToken, strlen(iterToken) + 1);
-                            }
-                            else
-                            {
-                                OCCapability* capa = (OCCapability*) OCMalloc(sizeof(OCCapability));
-                                memset(capa, 0, sizeof(OCCapability));
-                                //printf("%s :: ", iterToken);
-                                capa->capability = (char *) OCMalloc(strlen(iterToken) + 1);
-                                strncpy(capa->capability, iterToken, strlen(iterToken) + 1);
-                                iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr);
-                                //printf("%s\n", iterToken);
-                                capa->status = (char *) OCMalloc(strlen(iterToken) + 1);
-                                strncpy(capa->status, iterToken, strlen(iterToken) + 1);
-
-                                AddCapability(&action->head, capa);
-                            }
+    OCAction *action = NULL;
+    OCCapability *capa = NULL;
 
-                            iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr);
-                        }
+    OC_LOG(INFO, TAG, PCF("Build ActionSet Instance."));
 
-                        iterToken = (char *) strtok_r(NULL, ATTR_DELIMITER, &iterAttrbutesPtr);
-                    } // End of Action
+    *set = (OCActionSet*) OCMalloc(sizeof(OCActionSet));
+    VARIFY_POINTER_NULL(*set, result, exit)
 
-                    AddAction(&actionset->head, action);
+    iterToken = (char *) strtok_r(actiondesc, ACTION_DELIMITER, &iterTokenPtr);
 
-                    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr);
-                }
+    // ActionSet Name
+    memset(*set, 0, sizeof(OCActionSet));
+    (*set)->actionsetName = (char *) OCMalloc(strlen(iterToken) + 1);
+    VARIFY_POINTER_NULL((*set)->actionsetName, result, exit)
+    VARIFY_PARAM_NULL(iterToken, result, exit)
+    strncpy((*set)->actionsetName, iterToken, strlen(iterToken) + 1);
+
+    // Time info. for Scheduled/Recursive Group action.
+    // d is meant Day of the week.
+    // T is meant ActionType.
+    // yyyy-mm-dd hh:mm:ss d
+    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
+    VARIFY_PARAM_NULL(iterToken, result, exit)
+#ifndef WITH_ARDUINO
+    sscanf(iterToken, "%ld %d", &(*set)->timesteps, &(*set)->type);
+#endif
 
-                // 3. Add the pointer OCResource's ActionSet list.
-                AddActionSet(&(*resource)->actionsetHead, actionset);
-                return OC_STACK_OK;
+    OC_LOG_V(INFO, TAG, "ActionSet Name : %s", (*set)->actionsetName);
+
+    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
+    while (iterToken)
+    {
+        desc = (char *) OCMalloc(strlen(iterToken) + 1);
+        VARIFY_POINTER_NULL(desc, result, exit)
+        VARIFY_PARAM_NULL(desc, result, exit)
+        strncpy(desc, iterToken, strlen(iterToken) + 1);
+        descIterToken = (char *) strtok_r(desc, ATTR_DELIMITER,
+                &descIterTokenPtr);
+        while (descIterToken)
+        {
+            attr = (char *) OCMalloc(strlen(descIterToken) + 1);
+            VARIFY_POINTER_NULL(attr, result, exit)
+            VARIFY_PARAM_NULL(descIterToken, result, exit)
+            strncpy(attr, descIterToken, strlen(descIterToken) + 1);
+
+            attrIterToken = (char *) strtok_r(attr, ATTR_ASSIGN,
+                    &attrIterTokenPtr);
+            key = (char *) OCMalloc(strlen(attrIterToken) + 1);
+            VARIFY_POINTER_NULL(key, result, exit)
+            VARIFY_PARAM_NULL(attrIterToken, result, exit)
+            strncpy(key, attrIterToken, strlen(attrIterToken) + 1);
+
+            attrIterToken = (char *) strtok_r(NULL, ATTR_ASSIGN,
+                    &attrIterTokenPtr);
+            value = (char *) OCMalloc(strlen(attrIterToken) + 1);
+            VARIFY_POINTER_NULL(value, result, exit)
+            VARIFY_PARAM_NULL(attrIterToken, result, exit)
+            strncpy(value, attrIterToken, strlen(attrIterToken) + 1);
+
+            if (strcmp(key, "uri") == 0)
+            {
+                OC_LOG(INFO, TAG, PCF("Build OCAction Instance."));
+
+                action = (OCAction*) OCMalloc(sizeof(OCAction));
+                VARIFY_POINTER_NULL(action, result, exit)
+                memset(action, 0, sizeof(OCAction));
+                action->resourceUri = (char *) OCMalloc(strlen(value) + 1);
+                VARIFY_POINTER_NULL(action->resourceUri, result, exit)
+                VARIFY_PARAM_NULL(value, result, exit)
+                strncpy(action->resourceUri, value, strlen(value) + 1);
             }
-            else if (strcmp(iterToken, "DoAction") == 0 || strcmp(iterToken, "DelActionSet") == 0
-                    || strcmp(iterToken, "GetActionSet") == 0)
+            else
             {
-                *method = (char *) OCMalloc(strlen(iterToken) + 1);
-                strncpy(*method, iterToken, strlen(iterToken) + 1);
+                if ((key != NULL) && (value != NULL))
+                {
+                    OC_LOG(INFO, TAG, PCF("Build OCCapability Instance."));
 
-                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is mean ':'.
-                // printf("%s\n", iterToken);
-                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is body of action description.
-                // printf("%s\n", iterToken);
+                    capa = (OCCapability*) OCMalloc(sizeof(OCCapability));
+                    VARIFY_POINTER_NULL(capa, result, exit)
+                    memset(capa, 0, sizeof(OCCapability));
 
-                description = (char *) OCMalloc(strlen(iterToken) + 1);
-                strncpy(description, iterToken, strlen(iterToken) + 1);
+                    capa->capability = (char *) OCMalloc(strlen(key) + 1);
+                    VARIFY_POINTER_NULL(capa->capability, result, exit)
+                    VARIFY_PARAM_NULL(key, result, exit)
+                    strncpy(capa->capability, key, strlen(key) + 1);
 
-                // Find the action name from description.
-                iterDescPtr = NULL;
-                iterToken = (char *) strtok_r(description, ACTION_DELIMITER, &iterDescPtr);
-                if (iterToken != NULL)
-                {
-                    if (*actionsetName != NULL)
-                    {
-                        // printf("ERROR :: ACTIONSET NAME as ActionSet(%s)\n", iterToken);
-                        return OC_STACK_ERROR; // ERROR OCCURED.
-                    }
-                    else
-                    {
-                        //  Actionset name.
-                        // printf("ACTION SET NAME :: %s\n", iterToken);
-                        *actionsetName = (char *) OCMalloc(strlen(iterToken) + 1);
+                    capa->status = (char *) OCMalloc(strlen(value) + 1);
+                    VARIFY_POINTER_NULL(capa->status, result, exit)
+                    VARIFY_PARAM_NULL(value, result, exit)
+                    strncpy(capa->status, value, strlen(value) + 1);
 
-                        strncpy(*actionsetName, iterToken, strlen(iterToken) + 1);
-                        // printf("ACTION SET NAME :: %s\n", *actionsetName);
-                    }
+                    VARIFY_POINTER_NULL(action, result, exit)
 
-                    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr);
-                    return OC_STACK_OK;
+                    AddCapability(&action->head, capa);
                 }
-                else
-                {
-                    return OC_STACK_ERROR;
-
-                } // end Action Set Name.
-                break;
             }
 
-            iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr);
+            OCFREE(key)
+            OCFREE(value)
+            OCFREE(attr)
+
+            descIterToken = (char *) strtok_r(NULL, ATTR_DELIMITER,
+                    &descIterTokenPtr);
         }
+
+        AddAction(&(*set)->head, action);
+        iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
+        OCFREE(desc);
     }
 
-    return OC_STACK_ERROR;
+    return OC_STACK_OK;
+exit:
+    OCFREE(attr)
+    OCFREE(desc)
+    OCFREE(capa)
+    OCFREE(action)
+    OCFREE(*set)
+    OCFREE(key)
+    OCFREE(value)
+    OCFREE(attr)
+
+    return result;
 }
 
-OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc)
+OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
 {
-    char temp[1024] =
-    { 0 };
+    char temp[1024] = { 0 };
     int remaining = 1023;
+    OCStackResult res = OC_STACK_ERROR;
 
-    // OCActionSet *as = resource->actionsetHead;
-    // while(as != NULL)
-    // {
-    printf("\n\n\nAction Set Name :: %s\n", actionset->actionsetName);
     OCAction *action = actionset->head;
 
     if (remaining >= strlen(actionset->actionsetName) + 1)
     {
         strcat(temp, actionset->actionsetName);
         remaining -= strlen(actionset->actionsetName);
-        strcat(temp, "*");
+        strcat(temp, ACTION_DELIMITER);
         remaining--;
     }
     else
     {
-        return OC_STACK_ERROR;
+        res = OC_STACK_ERROR;
+        goto exit;
     }
 
     while (action != NULL)
     {
-        printf("\tURI :: %s\n", action->resourceUri);
         strcat(temp, "uri=");
         remaining -= strlen("uri=");
         strcat(temp, action->resourceUri);
@@ -535,7 +756,6 @@ OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc)
         OCCapability *capas = action->head;
         while (capas != NULL)
         {
-            printf("\t\t%s = %s\n", capas->capability, capas->status);
             strcat(temp, capas->capability);
             remaining -= strlen(capas->capability);
             strcat(temp, "=");
@@ -553,26 +773,29 @@ OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc)
         action = action->next;
         if (action != NULL)
         {
-            strcat(temp, "*");
+            strcat(temp, ACTION_DELIMITER);
             remaining--;
         }
     }
-    //     as = as->next;
-    // }
 
     *desc = (char *) OCMalloc(1024 - remaining);
+    VARIFY_POINTER_NULL(*desc, res, exit);
     strcpy(*desc, temp);
-    // printf("\t\tPlain Text = %s(%i)\n", *desc, 1024 - remaining);
 
     return OC_STACK_OK;
+
+exit:
+    OCFREE(*desc);
+    return res;
+
 }
 
 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
         OCClientResponse* clientResponse)
 {
-    printf("\n\n\tcallback is called\n\n");
+    OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
 
-    ClientRequstInfo *info = GetClientRequestInfo(clientRequstList, handle);
+    ClientRequestInfo *info = GetClientRequestInfo(clientRequstList, handle);
 
     if (info)
     {
@@ -580,19 +803,23 @@ OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
 
         unsigned char *responseJson;
         responseJson = (unsigned char *) OCMalloc(
-                (unsigned int) (strlen((char *) clientResponse->resJSONPayload) + 1));
+                (unsigned int) (strlen((char *) clientResponse->resJSONPayload)
+                        + 1));
+
+        if( responseJson == NULL )
+            return OC_STACK_DELETE_TRANSACTION;
 
         // We need the body of response.
         // Copy the body from the response
-        strcpy((char *) responseJson, ((char *) clientResponse->resJSONPayload
-                + OC_JSON_PREFIX_LEN));
+        strcpy((char *) responseJson,
+                ((char *) clientResponse->resJSONPayload + OC_JSON_PREFIX_LEN));
         idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
         // And insert NULL at the end of body.
         (responseJson[idx]) = 0;
 
         OCEntityHandlerResponse response = { 0 };
         response.ehResult = OC_EH_OK;
-        response.payload = responseJson;
+        response.payload = (char*)responseJson;
         response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
         response.persistentBufferFlag = 0;
         response.requestHandle = (OCRequestHandle) info->ehRequest;
@@ -601,22 +828,19 @@ OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
         OCDoResponse(&response);
 
         RemoveClientRequestInfo(&clientRequstList, info);
-        OCFree(responseJson);
+        OCFREE(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, unsigned char* bufferPtr,
+        uint16_t *remaining)
 {
     OCStackResult ret = OC_STACK_ERROR;
     cJSON *json;
@@ -633,7 +857,8 @@ OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16
     OCCapability* pointerCapa = action->head;
     while (pointerCapa)
     {
-        cJSON_AddStringToObject(body, pointerCapa->capability, pointerCapa->status);
+        cJSON_AddStringToObject(body, pointerCapa->capability,
+                pointerCapa->status);
         pointerCapa = pointerCapa->next;
     }
 
@@ -656,47 +881,169 @@ OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16
 
 unsigned int GetNumOfTargetResource(OCAction *actionset)
 {
-    int numOfREsource = 0;
+    int 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)
+
+#define DEFAULT_CONTEXT_VALUE 0x99
+
+OCStackResult SendAction(OCDoHandle *handle, const char *targetUri,
+        const unsigned char *action)
 {
-    OCCallbackData cbdata =
-    { 0 };
+    OCCallbackData cbdata = { 0 };
     cbdata.cb = &ActionSetCB;
-    cbdata.cd = &ActionSetCD;
-    cbdata.context = (void *) 0x99;
+    cbdata.cd = NULL;
+    cbdata.context = (void*)DEFAULT_CONTEXT_VALUE;
+
+// TODO: Selecting OC_IPV4.
+// It is temporary change as OC_ALL is not working currently. Remove this code and use OC_ALL
+// once it is functioning.
 
     return OCDoResource(handle, OC_REST_PUT, targetUri,
-    //temp->rsrcType->resourcetypename,
-            NULL, (char *) action, OC_NA_QOS, &cbdata, NULL, 0);
+    NULL, (char *) action, OC_IPV4, OC_NA_QOS, &cbdata, NULL, 0);
+}
+
+OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
+        OCServerRequest* requestHandle)
+{
+    OCStackResult result = OC_STACK_ERROR;
+    OCAction *pointerAction = actionset->head;
+
+    while (pointerAction != NULL)
+    {
+        unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
+        unsigned char* actionDescPtr = actionDesc;
+        uint16_t remaining = MAX_RESPONSE_LENGTH;
+
+        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));
+
+        ClientRequestInfo *info = (ClientRequestInfo *) OCMalloc(
+                sizeof(ClientRequestInfo));
+
+        if( info == NULL )
+            return OC_STACK_NO_MEMORY;
+
+        memset(info, 0, sizeof(ClientRequestInfo));
+
+        info->collResource = resource;
+        info->ehRequest = requestHandle;
+
+        result = SendAction(&info->required, pointerAction->resourceUri,
+                actionDescPtr);
+        if (result != OC_STACK_OK)
+        {
+            return result;
+        }
+
+        AddClientRequestInfo(&clientRequstList, info);
+
+        pointerAction = pointerAction->next;
+    }
+
+    return result;
 }
 
-OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHandlerFlag flag*/,
-        OCResource *resource, OCEntityHandlerRequest *ehRequest)
+void DoScheduledGroupAction()
+{
+    OC_LOG(INFO, TAG, PCF("DoScheduledGroupAction Entering..."));
+    ScheduledResourceInfo* info = GetScheduledResource(scheduleResourceList);
+
+    if (info == NULL)
+    {
+        OC_LOG(INFO, TAG, PCF("Target resource is NULL"));
+        goto exit;
+    }
+    else if (info->resource == NULL)
+    {
+        OC_LOG(INFO, TAG, PCF("Target resource is NULL"));
+        goto exit;
+    }
+    else if (info->actionset == NULL)
+    {
+        OC_LOG(INFO, TAG, PCF("Target ActionSet is NULL"));
+        goto exit;
+    }
+    else if (info->ehRequest == NULL)
+    {
+        OC_LOG(INFO, TAG, PCF("Target ActionSet is NULL"));
+        goto exit;
+    }
+#ifndef WITH_ARDUINO
+    pthread_mutex_lock(&lock);
+#endif
+    DoAction(info->resource, info->actionset, info->ehRequest);
+#ifndef WITH_ARDUINO
+    pthread_mutex_unlock(&lock);
+#endif
+
+    if (info->actionset->type == RECURSIVE)
+    {
+        ScheduledResourceInfo *schedule;
+        schedule = (ScheduledResourceInfo *) OCMalloc(
+                sizeof(ScheduledResourceInfo));
+
+        if (schedule)
+        {
+            OC_LOG(INFO, TAG, PCF("Building New Call Info."));
+            memset(schedule, 0, sizeof(ScheduledResourceInfo));
+
+            if (info->actionset->timesteps > 0)
+            {
+#ifndef WITH_ARDUINO
+                pthread_mutex_lock(&lock);
+#endif
+                schedule->resource = info->resource;
+                schedule->actionset = info->actionset;
+                schedule->ehRequest = info->ehRequest;
+
+                schedule->time = registerTimer(info->actionset->timesteps,
+                        &schedule->timer_id,
+                        &DoScheduledGroupAction);
+
+                OC_LOG(INFO, TAG, PCF("Reregisteration."));
+#ifndef WITH_ARDUINO
+                pthread_mutex_unlock(&lock);
+#endif
+                AddScheduledResource(&scheduleResourceList, schedule);
+            }
+        }
+    }
+
+    RemoveScheduledResource(&scheduleResourceList, info);
+
+    exit:
+
+    return;
+}
+
+OCStackResult BuildCollectionGroupActionJSONResponse(
+        OCMethod method/*OCEntityHandlerFlag flag*/, OCResource *resource,
+        OCEntityHandlerRequest *ehRequest)
 {
     OCStackResult stackRet = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Group Action is requested."));
     // if (stackRet == OC_STACK_OK)
     {
-
         char *doWhat = NULL;
-        char *actionName = NULL;
+        char *details = NULL;
 
         size_t bufferLength = 0;
-        unsigned char buffer[MAX_RESPONSE_LENGTH] =
-        { 0 };
+        unsigned char buffer[MAX_RESPONSE_LENGTH] = { 0 };
         unsigned char *bufferPtr = NULL;
 
         bufferPtr = buffer;
@@ -705,6 +1052,17 @@ OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHa
 
         char *jsonResponse;
 
+        stackRet = ExtractKeyValueFromRequest((char *) ehRequest->reqJSONPayload,
+                &doWhat, &details);
+
+        if(stackRet != OC_STACK_OK)
+        {
+            OC_LOG_V(ERROR, TAG, "ExtractKeyValueFromRequest failed: %d", stackRet);
+            return stackRet;
+        }
+
+        stackRet = OC_STACK_ERROR;
+
         cJSON *json;
         cJSON *format;
 
@@ -716,12 +1074,36 @@ OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHa
 
             OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
 
-            unsigned char *actionPtr = (unsigned char *) ehRequest->reqJSONPayload;
-            GetActionSetFromString(&resource, actionPtr, &doWhat, &actionName);
+            if (strcmp(doWhat, ACTIONSET) == 0)
+            {
+                OCActionSet *actionSet = NULL;
+                stackRet = BuildActionSetFromString(&actionSet, details);
+
+                if(stackRet == OC_STACK_OK)
+                {
+                    if (actionSet != NULL)
+                    {
+                        stackRet = AddActionSet(&resource->actionsetHead,
+                                actionSet);
+                        if (stackRet == OC_STACK_ERROR)
+                        {
+                            if(actionSet != NULL)
+                            {
+                                DeleteActionSet( &actionSet );
+                            }
+                            OC_LOG(INFO, TAG, PCF("Duplicated ActionSet "));
+                        }
+                    }
+                }
+                else
+                {
+                    stackRet = OC_STACK_ERROR;
+                }
 
-            if (strcmp(doWhat, "DelActionSet") == 0)
+            }
+            else if (strcmp(doWhat, DELETE_ACTIONSET) == 0)
             {
-                if (FindAndDeleteActionSet(&resource, actionName) == OC_STACK_OK)
+                if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
                 {
                     stackRet = OC_STACK_OK;
                 }
@@ -739,106 +1121,165 @@ OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHa
             bufferLength = strlen((const char *) buffer);
             if (bufferLength > 0)
             {
-                OCEntityHandlerResponse response =
-                { 0 };
-                response.ehResult = OC_EH_OK;
-                response.payload = buffer;
+                OCEntityHandlerResponse response = { 0 };
+                if(stackRet == OC_STACK_OK)
+                    response.ehResult = OC_EH_OK;
+                else
+                    response.ehResult = OC_EH_ERROR;
+                response.payload = (char*)buffer;
                 response.payloadSize = bufferLength + 1;
                 response.persistentBufferFlag = 0;
-                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+                response.requestHandle =
+                        (OCRequestHandle) ehRequest->requestHandle;
                 response.resourceHandle = (OCResourceHandle) collResource;
                 stackRet = OCDoResponse(&response);
             }
-
-            stackRet = OC_STACK_OK;
         }
 
         if (method == OC_REST_POST)
         {
-            OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
-
             OCActionSet *actionset = NULL;
-            unsigned char *actionPtr = (unsigned char *) ehRequest->reqJSONPayload;
-
-            GetActionSetFromString(&resource, actionPtr, &doWhat, &actionName);
 
             json = cJSON_CreateObject();
             cJSON_AddStringToObject(json, "href", resource->uri);
 
-            if (strcmp(doWhat, "DoAction") == 0)
+            if ((strcmp(doWhat, DO_ACTION) == 0)
+                    || (strcmp(doWhat, "DoScheduledAction") == 0))
             {
-                if (GetActionSet(actionName, resource->actionsetHead, &actionset) != OC_STACK_OK)
-                {
-                    OC_LOG(INFO, TAG, PCF("ERROR"));
-                    stackRet = OC_STACK_ERROR;
-                }
+                char *pActionsetName = NULL;
+                long int delay = -1;
 
-                if (actionset == NULL)
+                if (strcmp(doWhat, "DoScheduledAction") == 0)
                 {
-                    OC_LOG(INFO, TAG, PCF("ERROR"));
-                    stackRet = OC_STACK_ERROR;
+                    stackRet = ExtractActionSetNameAndDelaytime(details,
+                            &pActionsetName, &delay);
+
+                    OCFREE(details)
+                    details = pActionsetName;
                 }
                 else
                 {
+                    stackRet = OC_STACK_OK;
+                }
 
-                    OCAction *pointerAction = actionset->head;
-
-                    unsigned int num = GetNumOfTargetResource(pointerAction);
-
-                    ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
-                            HandleAggregateResponse;
-                    ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
-
-//                    printf("ActionSet Name :: %s\n", actionset->actionsetName);
-                    while (pointerAction != NULL)
+                if (stackRet == OC_STACK_OK)
+                {
+                    if (GetActionSet(details, resource->actionsetHead,
+                            &actionset) != OC_STACK_OK)
                     {
-                        unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
-                        unsigned char* actionDescPtr = actionDesc;
-                        uint16_t remaining = MAX_RESPONSE_LENGTH;
-
-                        strcpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX);
-                        BuildActionJSON(pointerAction, actionDescPtr, &remaining);
-                        strcat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX);
-
-                        ClientRequstInfo *info = (ClientRequstInfo *) OCMalloc(
-                                sizeof(ClientRequstInfo));
-                        memset(info, 0, sizeof(ClientRequstInfo));
-
-                        info->collResource = resource;
-                        info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
+                        OC_LOG(INFO, TAG, PCF("ERROR"));
+                        stackRet = OC_STACK_ERROR;
+                    }
 
-                        SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
+                    if (actionset == NULL)
+                    {
+                        OC_LOG(INFO, TAG, PCF("Cannot Find ActionSet"));
+                        stackRet = OC_STACK_ERROR;
+                    }
+                    else
+                    {
+                        OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
+                        if (actionset->type == NONE)
+                        {
+                            OC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
+                                    actionset->actionsetName);
+                            unsigned int num = GetNumOfTargetResource(
+                                    actionset->head);
+
+                            ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
+                                    HandleAggregateResponse;
+                            ((OCServerRequest *) ehRequest->requestHandle)->numResponses =
+                                    num + 1;
+
+                            DoAction(resource, actionset,
+                                    (OCServerRequest*) ehRequest->requestHandle);
+                            stackRet = OC_STACK_OK;
+                        }
+                        else
+                        {
+                            OC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
+                                    actionset->actionsetName);
 
-                        AddClientRequestInfo(&clientRequstList, info);
+                            delay =
+                                    (delay == -1 ? actionset->timesteps : delay);
 
+                            ScheduledResourceInfo *schedule;
+                            schedule = (ScheduledResourceInfo *) OCMalloc(
+                                    sizeof(ScheduledResourceInfo));
 
-                        pointerAction = pointerAction->next;
+                            if (schedule)
+                            {
+                                OC_LOG(INFO, TAG, PCF("Building New Call Info."));
+                                memset(schedule, 0,
+                                        sizeof(ScheduledResourceInfo));
+
+                                schedule->resource = resource;
+                                schedule->actionset = actionset;
+                                schedule->ehRequest =
+                                        (OCServerRequest*) ehRequest->requestHandle;
+
+                                if (delay > 0)
+                                {
+                                    OC_LOG_V(INFO, TAG, "delay_time is %lf seconds.",
+                                            actionset->timesteps);
+
+                                    schedule->time = registerTimer(delay,
+                                            &schedule->timer_id,
+                                            &DoScheduledGroupAction);
+
+                                    AddScheduledResource(&scheduleResourceList,
+                                            schedule);
+                                    stackRet = OC_STACK_OK;
+                                }
+                                else
+                                {
+                                    stackRet = OC_STACK_ERROR;
+                                }
+                            }
+                        }
                     }
+                }
+            }
+            else if (strcmp(doWhat, "CancelAction") == 0)
+            {
+                ScheduledResourceInfo *info =
+                        GetScheduledResourceByActionSetName(scheduleResourceList, details);
 
+                if(info != NULL)
+                {
+                    unregisterTimer(info->timer_id);
 
+                    RemoveScheduledResource(&scheduleResourceList, info);
                     stackRet = OC_STACK_OK;
                 }
+                else
+                {
+                    stackRet = OC_STACK_ERROR;
+                }
             }
-            else if (strcmp(doWhat, "GetActionSet") == 0)
+
+            else if (strcmp(doWhat, GET_ACTIONSET) == 0)
             {
                 char *plainText = NULL;
                 OCActionSet *actionset = NULL;
 
-                cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
-                GetActionSet(actionName, resource->actionsetHead, &actionset);
+                cJSON_AddItemToObject(json, "rep", format =
+                        cJSON_CreateObject());
+                GetActionSet(details, resource->actionsetHead, &actionset);
                 if (actionset != NULL)
                 {
-                    GetStringFromActionSet(actionset, &plainText);
+                    BuildStringFromActionSet(actionset, &plainText);
 
                     if (plainText != NULL)
                     {
-                        cJSON_AddStringToObject(format, "ActionSet", plainText);
+                        cJSON_AddStringToObject(format, ACTIONSET, plainText);
                     }
-
+                    OCFree(plainText);
                     stackRet = OC_STACK_OK;
                 }
             }
 
+
             jsonResponse = cJSON_Print(json);
             cJSON_Delete(json);
 
@@ -847,17 +1288,23 @@ OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHa
             bufferLength = strlen((const char *) buffer);
             if (bufferLength > 0)
             {
-                OCEntityHandlerResponse response =
-                { 0 };
-                response.ehResult = OC_EH_OK;
-                response.payload = buffer;
+                OCEntityHandlerResponse response = { 0 };
+                if(stackRet == OC_STACK_OK)
+                    response.ehResult = OC_EH_OK;
+                else
+                    response.ehResult = OC_EH_ERROR;
+                response.payload = (char *)buffer;
                 response.payloadSize = bufferLength + 1;
                 response.persistentBufferFlag = 0;
-                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+                response.requestHandle =
+                        (OCRequestHandle) ehRequest->requestHandle;
                 response.resourceHandle = (OCResourceHandle) collResource;
                 stackRet = OCDoResponse(&response);
             }
         }
+
+        OCFREE(doWhat)
+        OCFREE(details)
     }
 
     return stackRet;
index 0e3dfa4..7da8c21 100644 (file)
@@ -2,16 +2,19 @@
 //  NOTICE - Transition to SCONS
 //---------------------------------------------------------------------
 
-The IoTivity build system is transitioning to SCONS. Although the 
-makefiles are still available (until v1.0) and some developers are 
-still using them, they are currently no longer supported. To learn more 
-about building using SCONS see Readme.scons.txt in the repository root 
+The IoTivity build system is transitioning to SCONS. Although the
+makefiles are still available (until v1.0) and some developers are
+still using them, they are currently no longer supported. To learn more
+about building using SCONS see Readme.scons.txt in the repository root
 directory. The build steps used in continuous integration can be found
 in auto_build.sh which is also in the the repository root directory.
 
+To dynamically link with the Google Unit test library,
+add <src_dir>/extlibs/gtest/gtest-1.7.0/lib/.libs/ to LD_LIBRARY_PATH
+
 //---------------------------------------------------------------------
 
-stacktests.cpp is a unit test of the APIs in ocstack.c.  
+stacktests.cpp is a unit test of the APIs in ocstack.c.
 It uses Google Test for the unit tests.  Note that
 the unit tests are only to test the functionality of
 ocstack.c.  It is not a system or end-to-end test.
@@ -19,24 +22,25 @@ 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 
+   by the makefile and specifies the path to the
    Google Test directory on the build machine.
    Since local.properties is specific to each build
    system, do not add local.properties to the code repo.
 
    local.properties should contain GTEST_DIR.
    For example:
-   
+
 
    GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
 
-3. The unit test assumes that the "eth0" interface is
-   available.  If not, the unit tests will FAIL.
+3. The unit test assumes that a network interface is available
+   (e.g. "eth0", "wlan0", etc.)
+   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
@@ -50,3 +54,4 @@ Unit Test Requirements:
    root/csdk/stack/test/release/stacktests
    root/csdk/stack/test/debug/stacktests
 
+
diff --git a/resource/csdk/stack/test/SConscript b/resource/csdk/stack/test/SConscript
new file mode 100644 (file)
index 0000000..a331fa3
--- /dev/null
@@ -0,0 +1,82 @@
+#******************************************************************
+#
+# 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
+stacktest_env = env.Clone()
+
+src_dir = stacktest_env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+stacktest_env.PrependUnique(CPPPATH = [
+               '../../ocsocket/include',
+               '../../logger/include',
+               '../../stack/include',
+               '../../ocmalloc/include',
+               '../../extlibs/cjson',
+               '../../../oc_logger/include',
+               '../../../../extlibs/gtest/gtest-1.7.0/include'
+               ])
+
+stacktest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+stacktest_env.AppendUnique(LIBS = ['-lpthread'])
+stacktest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+stacktest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
+stacktest_env.PrependUnique(LIBS = ['m',
+                                    'octbstack',
+                                    'connectivity_abstraction',
+                                    'coap',
+                                    'gtest',
+                                    'gtest_main'])
+
+target_os = env.get('TARGET_OS')
+if target_os != 'darwin':
+    stacktest_env.PrependUnique(LIBS = ['oc_logger'])
+
+
+if env.get('SECURED') == '1':
+    stacktest_env.AppendUnique(LIBS = ['tinydtls'])
+
+if env.get('LOGGING'):
+       stacktest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+stacktests = stacktest_env.Program('stacktests', ['stacktests.cpp'])
+
+Alias("test", [stacktests])
+
+env.AppendTarget('test')
+if env.get('TEST') == '1':
+       target_os = env.get('TARGET_OS')
+       if target_os == 'linux':
+               out_dir = env.get('BUILD_DIR')
+               result_dir = env.get('BUILD_DIR') + '/test_out/'
+               if not os.path.isdir(result_dir):
+                       os.makedirs(result_dir)
+               stacktest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
+               stacktest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+               stacktest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
+               ut = stacktest_env.Command ('ut', None, 'valgrind -q --leak-check=full --xml=yes --xml-file=resource_csdk_stack_test.memcheck ' + out_dir + 'resource/csdk/stack/test/stacktests')
+               AlwaysBuild ('ut')
index 0c51097..66aa0c0 100644 (file)
@@ -20,7 +20,7 @@ Note: add the following to the ./jni/Android.mk file
 LOCAL_SRC_FILES += logger.c
 LOCAL_SRC_FILES += loggertests.cpp
 LOCAL_SRC_FILES += ocstack.c
-LOCAL_SRC_FILES += occoap.c
 LOCAL_SRC_FILES += stacktests.cpp
 
 
+
index b2e46d0..3f51a4f 100644 (file)
@@ -24,11 +24,12 @@ Properties|C/C++ Build|Settings|Tool Settings|AVR Compiler|Symbols
 and
 Properties|C/C++ Build|Settings|Tool Settings|AVR C++ Compiler|Symbols
 
-Copy logger.c/h, occoap.c/h, and ocstack.c/h, and ocstackinternal.h to the Arduino project
-Note: when building for Arduino, force the compiler to use avr-g++ to build logger.c, stack.c, and occoap.c
+Copy logger.c/h and ocstack.c/h, and ocstackinternal.h to the Arduino project
+Note: when building for Arduino, force the compiler to use avr-g++ to build logger.c, and stack.c.
 
 Note: when building for Arduino, several warnings are generated when trying to place strings in
 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
 
+
diff --git a/resource/csdk/stack/test/arduino/makefile b/resource/csdk/stack/test/arduino/makefile
deleted file mode 100644 (file)
index f753da8..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-BUILD   := release
-PLATFORM := arduinomega
-
-ROOT_DIR = ../../..
-include $(ROOT_DIR)/local.properties
-LIBCOAP_DIR = $(ROOT_DIR)/libcoap-4.1.1
-OCSOCK_DIR = $(ROOT_DIR)/ocsocket
-OCCOAP_DIR = $(ROOT_DIR)/occoap
-LOGGER_DIR = $(ROOT_DIR)/logger
-RANDOM_DIR = $(ROOT_DIR)/ocrandom
-JSON_DIR = $(ROOT_DIR)/../../extlibs/cjson
-OCSTACK_DIR = $(ROOT_DIR)/stack
-BIN_DIR = $(OCSTACK_DIR)/bin/arduino/
-OBJ_DIR = $(OCSTACK_DIR)/obj/arduino/
-
-#Source directories
-SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-SDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI
-SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet
-SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility
-SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time
-
-VPATH = $(SDIR_ARD_CORE):$(SDIR_ARD_SPI):$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL):$(SDIR_ARD_TIME):$(RANDOM_DIR)/src:$(OCSTACK_DIR)/src:$(OCCOAP_DIR)/src:$(JSON_DIR)
-
-#include directories
-IDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-IDIR_ARD_VARIANT = $(ARDUINO_DIR)/hardware/arduino/variants/mega
-IDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI
-IDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet
-IDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility
-IDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time
-
-INC_DIRS = -I$(IDIR_ARD_CORE) -I$(IDIR_ARD_VARIANT) -I$(IDIR_ARD_SPI) \
-       -I$(IDIR_ARD_ETH) -I$(IDIR_ARD_ETH_UTIL) -I$(IDIR_ARD_TIME) \
-       -I$(OCSOCK_DIR)/include -I$(LOGGER_DIR)/include -I$(RANDOM_DIR)/include \
-       -I$(OCSTACK_DIR)/include -I$(OCSTACK_DIR)/include/internal \
-        -I$(LIBCOAP_DIR)/ -I$(OCCOAP_DIR)/include -I$(JSON_DIR)
-
-#Compiler/Linker flags
-COPTIONS_ARDUINO = -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -MMD -DNDEBUG
-CFLAGS += -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 -DTB_LOG -DWITH_ARDUINO
-
-#Compilers
-CXX=avr-g++
-CC=avr-gcc
-AR=avr-ar
-RANLIB=avr-ranlib
-
-TESTAPP = ocserver
-
-CORE_COBJ = WInterrupts.o wiring.o wiring_digital.o
-CORE_CPPOBJ = main.o Stream.o WMath.o WString.o HardwareSerial.o Print.o SPI.o IPAddress.o wiring_analog.o
-ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o
-ETH_UTIL_CPPOBJ = socket.o w5100.o
-OCSTACK_CPPOBJ = ocrandom.o ocresource.o occollection.o ocobserve.o ocserverrequest.o ocstack.o occoaphelper.o occoap.o occlientcb.o
-OCDEPENDENT_CPPOBJ = wiring_analog.o
-CJSON_COBJ = cJSON.o
-
-all: core.a $(TESTAPP).o $(TESTAPP).elf $(TESTAPP).hex
-       mkdir -p $(BIN_DIR)
-       cp $(TESTAPP).hex $(BIN_DIR)
-       mkdir -p $(OBJ_DIR)
-       cp *.o $(OBJ_DIR)
-       cp *.elf $(OBJ_DIR)
-
-# Note for Arduino: The C files are compiled using C++ compiler since Arduino
-# build includes Time.h header file which has C++ style definitions.
-%.o: %.c
-       $(CXX) $(CFLAGS) $(COPTIONS_ARDUINO) $(INC_DIRS) $< -o $@
-
-%.o: %.cpp
-       $(CXX) $(CFLAGS) $(COPTIONS_ARDUINO) $(INC_DIRS) $< -o $@
-
-core.a: $(CORE_COBJ) $(CORE_CPPOBJ) $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) $(LIBCOAP_DIR)/$(BUILD)/libcoap.a
-       $(AR) rcs $@ $^
-       $(RANLIB) $@
-
-$(TESTAPP).elf: $(TESTAPP).o core.a $(OCSTACK_CPPOBJ) $(OCDEPENDENT_CPPOBJ) $(LIBCOAP_DIR)/$(BUILD)/libcoap.a $(CJSON_COBJ)
-       $(CC) -Os -Wl,--gc-sections,--relax $(COPTIONS_ARDUINO) $^ -lm -o $@
-
-$(TESTAPP).hex: $(TESTAPP).elf
-       avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(TESTAPP).eep
-       avr-objcopy -O ihex -R .eeprom $< $@
-
-install: all
-       avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/ttyACM0 -b115200 -D -Uflash:w:$(TESTAPP).hex:i
-
-.PHONY: clean
-
-clean:
-       rm -f *.o *.d *.elf *.eep *.a *.hex *-
-       rm -fr $(BIN_DIR)
-       rm -fr $(OBJ_DIR)
-
index 3c47701..dc8be91 100644 (file)
@@ -9,17 +9,15 @@ static uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0F, 0x2B, 0x72 };
 #define TAG PCF("ocserver")
 
 void ocInitialize () {
-    char ipAddr[16] = "";
-    OCGetInterfaceAddress (NULL, 0, AF_INET, (uint8_t *)ipAddr, 16);
     OC_LOG(DEBUG, TAG, PCF("IP addr is:"));
     OC_LOG_BUFFER(INFO, TAG, (uint8_t*)ipAddr, sizeof(ipAddr));
     delay(2000);
-    OCInit (ipAddr, 8001, OC_SERVER);
+    OCInit (NULL, 0, OC_SERVER);
 }
 
 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");
@@ -28,7 +26,8 @@ void setup() {
 }
 
 void loop() {
-       Serial.println ("Processing CoAP messages!\n");
+    Serial.println ("Processing CoAP messages!\n");
     OCProcess ();
-       delay(1000);
+    delay(1000);
 }
+
diff --git a/resource/csdk/stack/test/gtest_helper.h b/resource/csdk/stack/test/gtest_helper.h
new file mode 100644 (file)
index 0000000..97ce5f9
--- /dev/null
@@ -0,0 +1,151 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef IOTY_GTEST_HELPER_H
+#define IOTY_GTEST_HELPER_H
+
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <future>
+#include <mutex>
+#include <thread>
+
+namespace iotivity
+{
+    namespace test
+    {
+        /**
+         * Simple implementation of a deadman's timer that can be used to
+         * terminate a test that hangs.
+         *
+         * Since there is no standard way to terminate an individual thread,
+         * the entire process will be killed once time has been exceeded.
+         *
+         * @note provisions for watchdog thread cleanup are not currently added.
+         * Testing has not yet shown any need for such complexity.
+         */
+        class DeadmanTimer
+        {
+        public:
+
+            /**
+             * Creates an instance of a timer set to kill the running process
+             * after the specified timeout.
+             *
+             * If the destructor is invoked before time is up (aka this instance
+             * goes out of scope) the timeout will not cause the program to be
+             * terminated.
+             *
+             * @param time to wait before assuming the process is hung and must be
+             * killed.
+             * Examples of values that can be passed include
+             * std::chrono::milliseconds(250), std::chrono::seconds(5),
+             * std::chrono::minutes(3).
+             */
+            DeadmanTimer(std::chrono::milliseconds timeout) :
+                m_ctx(new DeadmanCtx(timeout)),
+                m_thread()
+                {
+                    m_thread = std::thread([this](){run(m_ctx);});
+                    {
+                        std::unique_lock<std::mutex> lock(m_ctx->m_mutex);
+                        while (!m_ctx->m_isArmed)
+                        {
+                            m_ctx->m_cond.wait(lock);
+                        }
+                    }
+                    // Now that the thread is live, we can stop tracking it.
+                    m_thread.detach();
+                }
+
+            /**
+             * Destructor that also will cancel the termination of the
+             * running process.
+             */
+            ~DeadmanTimer()
+            {
+                std::unique_lock<std::mutex> lock(m_ctx->m_mutex);
+                m_ctx->m_isArmed = false;
+            }
+
+        private:
+
+            /**
+             * Shared data that main and child thread might both need to
+             * access.
+             *
+             * Avoids referencing data in class instances that have been
+             * deleted.
+             */
+            class DeadmanCtx
+            {
+            public:
+
+                DeadmanCtx(std::chrono::milliseconds timeout) :
+                    m_mutex(),
+                    m_cond(),
+                    m_isArmed(false),
+                    m_timeout(timeout)
+                    {
+                    }
+
+                std::mutex m_mutex;
+                std::condition_variable m_cond;
+                bool m_isArmed;
+                std::chrono::milliseconds m_timeout;
+            };
+
+            // Explicitly block assignment and copy ctor
+            DeadmanTimer &operator=(const DeadmanTimer &rhs);
+            DeadmanTimer(const iotivity::test::DeadmanTimer &rhs);
+
+            std::shared_ptr<DeadmanCtx> m_ctx;
+            std::thread m_thread;
+
+
+            static void run(std::shared_ptr<DeadmanCtx> ctx)
+            {
+                // Let the calling thread know it can stop waiting:
+                {
+                    std::unique_lock<std::mutex> lock(ctx->m_mutex);
+                    ctx->m_isArmed = true;
+                    ctx->m_cond.notify_all();
+                }
+
+                std::this_thread::sleep_for(ctx->m_timeout);
+
+                std::unique_lock<std::mutex> lock(ctx->m_mutex);
+                if (ctx->m_isArmed)
+                {
+                    try {
+                        throw std::runtime_error("deadman timer expired");
+                    }
+                    catch (std::exception&)
+                    {
+                        std::terminate();
+                    }
+                }
+            }
+        };
+    } // namespace test
+} // namespace iotivity
+
+#endif // IOTY_GTEST_HELPER_H
diff --git a/resource/csdk/stack/test/linux/makefile b/resource/csdk/stack/test/linux/makefile
deleted file mode 100644 (file)
index 43ebff7..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-VERSION:=4.1.1
-
-# override with `make BUILD=release`
-# default to release build
-BUILD   := release
-
-#other options are android, arduino
-PLATFORM=linux
-
-ROOT_DIR = ../../..
-OCSOCK_DIR = $(ROOT_DIR)/ocsocket
-OCSTACK_DIR = $(ROOT_DIR)/stack
-LOGGER_DIR = $(ROOT_DIR)/logger
-OC_LOG_DIR = $(ROOT_DIR)/../oc_logger
-RANDOM_DIR = $(ROOT_DIR)/ocrandom
-
-OBJ_DIR = ./
-
-INC_DIRS := -I$(OCSTACK_DIR)/include
-INC_DIRS += -I$(OCSOCK_DIR)/include
-INC_DIRS += -I$(LOGGER_DIR)/include
-INC_DIRS += -I$(OC_LOG_DIR)/include
-INC_DIRS += -I$(RANDOM_DIR)/include
-
-ifeq ($(PLATFORM),android)
-       CXX=arm-linux-androideabi-g++
-       CC=arm-linux-androideabi-gcc
-       AR=arm-linux-androideabi-ar
-       RANLIB=arm-linux-androideabi-ranlib
-       CFLAGS_ANDROID =  -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16
-       LDFLAGS_ANDROID = -march=armv7-a -Wl,--fix-cortex-a8 -llog
-else ifeq ($(PLATFORM),linux)
-       CXX=g++
-       CC=gcc
-       AR=ar
-       RANLIB=ranlib
-else
-   $(error Wrong value for PLATFORM !!)
-endif
-
-DEP_LIBS = $(ROOT_DIR)/linux/$(BUILD)/liboctbstack.a
-
-CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions \
-       -Wextra -Wno-variadic-macros -pedantic -std=gnu99 -DWITH_POSIX -DTB_LOG
-
-PROGRAMS = ocserver occlient
-
-SOURCES:= occlient.c ocserver.c
-
-OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
-
-all: objdirs $(PROGRAMS)
-
-%.o: %.c
-       $(CC) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) $< -o $(BUILD)/$@
-
-objdirs: $(ROOT_DIR)
-       mkdir -p $(BUILD)
-       
-##Added -lm as needed by json calling floor()
-occlient: occlient.o $(DEP_LIBS)
-       $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $(BUILD)/$^ -o $(BUILD)/$@ -lm
-
-ocserver: ocserver.o $(DEP_LIBS)
-       $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $(BUILD)/$^ -o $(BUILD)/$@ -lm
-
-install: all
-       @echo "Installing for PLATFORM $(PLATFORM)"
-ifeq ($(PLATFORM),android)
-       adb push coap-client /data/local/tmp/
-       adb push coap-server /data/local/tmp/
-endif
-
-.PHONY: clean
-
-clean:
-       rm -rf debug
-       rm -rf release
index ec48462..322b487 100644 (file)
@@ -53,18 +53,10 @@ OCStackApplicationResult applicationDiscoverCB(
 }
 
 int main() {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-    OCDoHandle handle;
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
     OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
 
     /* Initialize OCStack*/
-    if (OCInit((char *) addr, port, OC_CLIENT) != OC_STACK_OK) {
+    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK) {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
@@ -72,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;
@@ -97,3 +89,4 @@ int main() {
 
     return 0;
 }
+
index 580ea0c..3813637 100644 (file)
@@ -48,16 +48,8 @@ void handleSigInt(int signum) {
 }
 
 int main() {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
     OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    if (OCInit((char *) addr, port, OC_SERVER) != OC_STACK_OK) {
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
@@ -102,3 +94,4 @@ OCStackResult createLightResource() {
                     OC_DISCOVERABLE|OC_OBSERVABLE);
     return res;
 }
+
diff --git a/resource/csdk/stack/test/makefile b/resource/csdk/stack/test/makefile
deleted file mode 100644 (file)
index ac76a47..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD   := release
-PLATFORM := linux
-CC      := g++
-
-ifeq ($(ROOT_DIR), )
-ROOT_DIR       = $(PWD)/../..
-endif
-
-# You must create the file "local.properties" on your local machine which contains any local paths, etc
-# local.properties should NOT be committed to repo
-include $(ROOT_DIR)/local.properties
-# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties
-#  Example:
-#  GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
-
-# NOTE:  to run app, make sure that LD_LIBRARY_PATH env variable
-#        contains $(GTEST_DIR)/lib/.libs
-
-OUT_DIR          := $(PWD)/$(BUILD)
-OBJ_DIR          := $(OUT_DIR)/obj
-
-
-OUT_DIR          := $(PWD)
-
-LOGGER_DIR     = $(ROOT_DIR)/logger
-OC_LOG_DIR      = $(ROOT_DIR)/../oc_logger
-OCRANDOM_DIR   = $(ROOT_DIR)/ocrandom
-OCSOCKET_DIR   = $(ROOT_DIR)/ocsocket
-LCOAP_DIR      = $(ROOT_DIR)/libcoap-4.1.1
-OCCOAP_DIR     = $(ROOT_DIR)/occoap
-OCTBSTACK_DIR  = $(ROOT_DIR)/stack
-
-LOGGER_INC     = $(LOGGER_DIR)/include
-OC_LOG_INC     = $(OC_LOG_DIR)/include
-OCRANDOM_INC   = $(OCRANDOM_DIR)/include
-OCSOCKET_INC   = $(OCSOCKET_DIR)/include
-LCOAP_INC      = $(LCOAP_DIR)
-OCCOAP_INC     = $(OCCOAP_DIR)/include
-OCTBSTACK_INC  = $(OCTBSTACK_DIR)/include
-
-INC_DIRS       := -I$(LOGGER_INC)
-INC_DIRS       += -I$(OC_LOG_INC)
-INC_DIRS       += -I$(OCRANDOM_INC)
-INC_DIRS       += -I$(OCSOCKET_INC)
-INC_DIRS       += -I$(LCOAP_INC)
-INC_DIRS       += -I$(OCCOAP_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)
-INC_DIRS       += -I$(OCTBSTACK_INC)/internal
-INC_DIRS       += -I$(GTEST_DIR)/include
-
-CC_FLAGS.debug      := -g -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \
-                        -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG
-CC_FLAGS.release    := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \
-                        -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) 
-                                       
-LDLIBS         += -loctbstack -lpthread -lgtest -lgtest_main
-CPPFLAGS       += $(CC_FLAGS.$(BUILD)) $(LDLIBS) -L$(GTEST_DIR)/lib/.libs
-
-SOURCES := stacktests.cpp
-
-OBJECTS:= $(patsubst %.c, $(OBJ_DIR)/%.o, $(SOURCES))
-
-PROGRAMS := stacktests
-
-all:   prep_dirs $(OBJECTS) $(PROGRAMS) 
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-       -mkdir -p $(OBJ_DIR)
-
-$(OBJ_DIR)/%.o: %.cpp
-       $(CC) -c $(CPPFLAGS) $< -o $@
-
-stacktests: $(OBJ_DIR)/stacktests.o 
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-.PHONY: clean
-
-clean: legacy_clean
-       -rm -rf release
-       -rm -rf debug
-
-legacy_clean:
-       rm -f *.o $(PROGRAMS)
index 31c8dff..19631d7 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 
-extern "C" {
+extern "C"
+{
     #include "ocstack.h"
-    #include "ocstackinternal.h"
     #include "logger.h"
+    #include "ocmalloc.h"
 }
 
 #include "gtest/gtest.h"
@@ -41,18 +42,27 @@ extern "C" {
 
 #include <iostream>
 #include <stdint.h>
+
+#include "gtest_helper.h"
+
 using namespace std;
 
+namespace itst = iotivity::test;
+
 #define DEFAULT_CONTEXT_VALUE 0x99
+
 //-----------------------------------------------------------------------------
 // Private variables
 //-----------------------------------------------------------------------------
 static const char TAG[] = "TestHarness";
 
+std::chrono::seconds const SHORT_TEST_TIMEOUT = std::chrono::seconds(5);
+
 //-----------------------------------------------------------------------------
 // Callback functions
 //-----------------------------------------------------------------------------
-extern "C"  OCStackApplicationResult asyncDoResourcesCallback(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
+extern "C"  OCStackApplicationResult asyncDoResourcesCallback(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+{
     OC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback");
 
     EXPECT_EQ(OC_STACK_OK, clientResponse->result);
@@ -65,118 +75,245 @@ extern "C"  OCStackApplicationResult asyncDoResourcesCallback(void* ctx, OCDoHan
     return OC_STACK_KEEP_TRANSACTION;
 }
 
+//-----------------------------------------------------------------------------
+// Entity handler
+//-----------------------------------------------------------------------------
+OCEntityHandlerResult entityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest)
+{
+    OC_LOG(INFO, TAG, "Entering entityHandler");
+
+    return OC_EH_OK;
+}
+
+//-----------------------------------------------------------------------------
+//  Local functions
+//-----------------------------------------------------------------------------
+void InitStack(OCMode mode)
+{
+    OC_LOG(INFO, TAG, "Entering InitStack");
+
+    EXPECT_EQ(OC_STACK_OK, OCInit(NULL, 0, mode));
+    OC_LOG(INFO, TAG, "Leaving InitStack");
+}
+
+uint8_t InitNumExpectedResources()
+{
+#ifdef WITH_PRESENCE
+    // When presence is enabled, it is a resource and so is (currently) included
+    // in the returned resource count returned by the OCGetNumberOfResources API.
+    return 1;
+#else
+    return 0;
+#endif
+}
 
+uint8_t InitResourceIndex()
+{
+#ifdef WITH_PRESENCE
+    // When presence is enabled, it is a resource and so is (currently) included
+    // in the returned resource count returned by the OCGetNumberOfResources API.
+    // The index of the presence resource is 0, so the first user app resource index
+    // is 1.
+    return 1;
+#else
+    return 0;
+#endif
+}
 //-----------------------------------------------------------------------------
 //  Tests
 //-----------------------------------------------------------------------------
-#if 1
-TEST(StackTest, StackInitNullAddr) {
+
+TEST(StackInit, StackInitNullAddr)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit(0, 5683, OC_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, StackInitNullPort) {
+TEST(StackInit, StackInitNullPort)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 0, OC_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, StackInitNullAddrAndPort) {
+TEST(StackInit, StackInitNullAddrAndPort)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, StackInitInvalidMode) {
+TEST(StackInit, StackInitInvalidMode)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_ERROR, OCInit(0, 0, (OCMode)10));
     EXPECT_EQ(OC_STACK_ERROR, OCStop());
 }
 
-TEST(StackTest, StackStartSuccessClient) {
+TEST(StackStart, StackStartSuccessClient)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, StackStartSuccessServer) {
+TEST(StackStart, StackStartSuccessServer)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, StackStartSuccessClientServer) {
+TEST(StackStart, StackStartSuccessClientServer)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, StackStartSuccessiveInits) {
+TEST(StackStart, StackStartSuccessiveInits)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.2", 5683, OC_SERVER));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, DoResourceDeviceDiscovery) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackStart, SetPlatformInfoValid)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+
+    OCPlatformInfo info = {};
+    info.platformID = (char *) "platform_id";
+    info.manufacturerName = (char *) "manufac_name";
+
+    EXPECT_EQ(OC_STACK_OK, OCSetPlatformInfo(info));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackStart, SetPlatformInfoWithNoPlatformID)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+
+    OCPlatformInfo info = {};
+    info.manufacturerName = (char *) "manufac_name";
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSetPlatformInfo(info));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackStart, SetPlatformInfoWithNoManufacturerName)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+
+    OCPlatformInfo info = {};
+    info.platformID = (char *) "platform_id";
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSetPlatformInfo(info));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackStart, SetPlatformInfoWithTooLongManufacName)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+
+    OCPlatformInfo info = {};
+    info.platformID = (char *) "platform_id";
+    info.manufacturerName = (char *) "extremelylongmanufacturername";
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSetPlatformInfo(info));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackStart, SetPlatformInfoWithTooLongManufacURL)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+
+    OCPlatformInfo info = {};
+    info.platformID = (char *) "platform_id";
+    info.manufacturerName = (char *) "extremelylongmanufacturername";
+    info.manufacturerUrl = (char *)"www.foooooooooooooooo.baaaaaaaaaaaaar";
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSetPlatformInfo(info));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+
+TEST(StackDiscovery, DISABLED_DoResourceDeviceDiscovery)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     OCCallbackData cbData;
     OCDoHandle handle;
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-    OC_LOG_V(INFO, TAG, "Starting DoResourceDeviceDiscovery test on address %s",addr);
+    OC_LOG(INFO, TAG, "Starting DoResourceDeviceDiscovery test ");
+    InitStack(OC_CLIENT);
 
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_CLIENT));
     /* Start a discovery query*/
     char szQueryUri[64] = { 0 };
     strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
     cbData.cb = asyncDoResourcesCallback;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-
-    EXPECT_EQ(OC_STACK_OK, OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0));
-    //EXPECT_EQ(OC_STACK_OK, OCUpdateResources(SERVICE_URI));
+    EXPECT_EQ(OC_STACK_OK, OCDoResource(&handle,
+                                        OC_REST_GET,
+                                        szQueryUri,
+                                        0,
+                                        0,
+                                        OC_IPV4,
+                                        OC_LOW_QOS,
+                                        &cbData,
+                                        NULL,
+                                        0));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, StackStopWithoutInit) {
+TEST(StackStop, StackStopWithoutInit)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
     EXPECT_EQ(OC_STACK_OK, OCStop());
     EXPECT_EQ(OC_STACK_ERROR, OCStop());
 }
 
-TEST(StackTest, UpdateResourceNullURI) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackResource, DISABLED_UpdateResourceNullURI)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
     OCCallbackData cbData;
     OCDoHandle handle;
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-    OC_LOG_V(INFO, TAG, "Starting UpdateResourceNullURI test on address %s",addr);
+    OC_LOG(INFO, TAG, "Starting UpdateResourceNullURI test");
+    InitStack(OC_CLIENT);
 
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_CLIENT));
     /* Start a discovery query*/
     char szQueryUri[64] = { 0 };
     strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
     cbData.cb = asyncDoResourcesCallback;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    EXPECT_EQ(OC_STACK_OK, OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0));
-    //EXPECT_EQ(OC_STACK_INVALID_URI, OCUpdateResources(0));
+    EXPECT_EQ(OC_STACK_OK, OCDoResource(&handle,
+                                        OC_REST_GET,
+                                        szQueryUri,
+                                        0,
+                                        0,
+                                        OC_IPV4,
+                                        OC_LOW_QOS,
+                                        &cbData,
+                                        NULL,
+                                        0));
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, CreateResourceBadParams) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, CreateResourceBadParams)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting CreateResourceBadParams test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
 
@@ -200,23 +337,17 @@ TEST(StackTest, CreateResourceBadParams) {
                                             "core.rw",
                                             "/a/led",
                                             0,
-                                            16));//OC_DISCOVERABLE|OC_OBSERVABLE));
+                                            128));// invalid bitmask for OCResourceProperty
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
-#endif
 
-TEST(StackTest, CreateResourceSuccess) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, CreateResourceSuccess)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting CreateResourceSuccess test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -231,17 +362,11 @@ TEST(StackTest, CreateResourceSuccess) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, CreateResourceFailDuplicateUri) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, CreateResourceFailDuplicateUri)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting CreateResourceFailDuplicateUri test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -263,17 +388,11 @@ TEST(StackTest, CreateResourceFailDuplicateUri) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, CreateResourceMultipleResources) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, CreateResourceMultipleResources)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting CreateResourceMultipleResources test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle1;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
@@ -310,17 +429,11 @@ TEST(StackTest, CreateResourceMultipleResources) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, CreateResourceBadResoureType) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, CreateResourceBadResoureType)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting CreateResourceBadResoureType test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(&handle,
@@ -333,17 +446,11 @@ TEST(StackTest, CreateResourceBadResoureType) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, CreateResourceGoodResourceType) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, CreateResourceGoodResourceType)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting CreateResourceGoodResourceType test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -356,17 +463,11 @@ TEST(StackTest, CreateResourceGoodResourceType) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, ResourceTypeName) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, ResourceTypeName)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting ResourceTypeName test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -392,116 +493,11 @@ TEST(StackTest, ResourceTypeName) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindResourceTypeNameBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle handle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-
-    uint8_t numResourceTypes;
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
-    EXPECT_EQ(1, numResourceTypes);
-    const char *resourceTypeName = OCGetResourceTypeName(handle, 0);
-    EXPECT_STREQ("core.led", resourceTypeName);
-
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceTypeToResource(handle, NULL));
-
-    EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(StackTest, BindResourceTypeNameGood) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle handle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-
-    uint8_t numResourceTypes;
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
-    EXPECT_EQ(1, numResourceTypes);
-    const char *resourceTypeName = OCGetResourceTypeName(handle, 0);
-    EXPECT_STREQ("core.led", resourceTypeName);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.brightled"));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
-    EXPECT_EQ(2, numResourceTypes);
-    resourceTypeName = OCGetResourceTypeName(handle, 1);
-    EXPECT_STREQ("core.brightled", resourceTypeName);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.reallybrightled"));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
-    EXPECT_EQ(3, numResourceTypes);
-    resourceTypeName = OCGetResourceTypeName(handle, 2);
-    EXPECT_STREQ("core.reallybrightled", resourceTypeName);
-
-    EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(StackTest, ResourceTypeAttrRepresentation) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle handle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-
-    uint8_t numResourceTypes;
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
-    EXPECT_EQ(1, numResourceTypes);
-
-    EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(StackTest, BindResourceTypeAttribRepGood) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, ResourceTypeAttrRepresentation)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting ResourceTypeAttrRepresentation test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -515,28 +511,14 @@ TEST(StackTest, BindResourceTypeAttribRepGood) {
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
     EXPECT_EQ(1, numResourceTypes);
 
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.brightled"));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
-    EXPECT_EQ(2, numResourceTypes);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.reallybrightled"));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
-    EXPECT_EQ(3, numResourceTypes);
-
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, ResourceTypeInterface) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, ResourceTypeInterface)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting ResourceTypeInterface test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -562,17 +544,13 @@ TEST(StackTest, ResourceTypeInterface) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindResourceInterfaceNameBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackResource, ResourceDefaultInterfaceAlwaysFirst)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
+    OC_LOG(INFO, TAG, "Starting ResourceDefaultInterfaceAlwaysFirst test");
 
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -581,29 +559,28 @@ TEST(StackTest, BindResourceInterfaceNameBad) {
                                             "/a/led",
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
-
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle,
+                                        OC_RSRVD_INTERFACE_DEFAULT));
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
-    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0);
-    EXPECT_STREQ("core.rw", resourceInterfaceName);
+    EXPECT_EQ(2, numResourceInterfaces);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, NULL));
+    const char *interfaceName_1 = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_STREQ(OC_RSRVD_INTERFACE_DEFAULT, interfaceName_1);
+
+    const char*interfaceName_2 = OCGetResourceInterfaceName(handle, 1);
+    EXPECT_STREQ("core.rw", interfaceName_2);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindResourceInterfaceNameGood) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackResource, ResourceDuplicateDefaultInterfaces)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
+    OC_LOG(INFO, TAG, "Starting ResourceDuplicateDefaultInterfaces test");
 
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -613,33 +590,28 @@ TEST(StackTest, BindResourceInterfaceNameGood) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
 
-    uint8_t numResourceInterfaces;
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
-    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0);
-    EXPECT_STREQ("core.rw", resourceInterfaceName);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r"));
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle,
+                                        OC_RSRVD_INTERFACE_DEFAULT));
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle,
+                                        OC_RSRVD_INTERFACE_DEFAULT));
 
+    uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
     EXPECT_EQ(2, numResourceInterfaces);
-    resourceInterfaceName = OCGetResourceInterfaceName(handle, 1);
-    EXPECT_STREQ("core.r", resourceInterfaceName);
+
+    const char *interfaceName_1 = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_STREQ(OC_RSRVD_INTERFACE_DEFAULT, interfaceName_1);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, ResourceTypeInterfaceMethods) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackResource, ResourceDuplicateNonDefaultInterfaces)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
+    OC_LOG(INFO, TAG, "Starting ResourceDuplicateInterfaces test");
 
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -649,6 +621,11 @@ TEST(StackTest, ResourceTypeInterfaceMethods) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
 
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle,
+                                        "core.rw"));
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle,
+                                        "core.rw"));
+
     uint8_t numResourceInterfaces;
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
     EXPECT_EQ(1, numResourceInterfaces);
@@ -656,17 +633,11 @@ TEST(StackTest, ResourceTypeInterfaceMethods) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindResourceInterfaceMethodsBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, ResourceTypeInterfaceMethods)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting ResourceTypeInterfaceMethods test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -680,22 +651,14 @@ TEST(StackTest, BindResourceInterfaceMethodsBad) {
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
     EXPECT_EQ(1, numResourceInterfaces);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, 0));
-
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindResourceInterfaceMethodsGood) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResource, GetResourceProperties)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting GetResourceProperties test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -705,88 +668,66 @@ TEST(StackTest, BindResourceInterfaceMethodsGood) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
 
-    uint8_t numResourceInterfaces;
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(1, numResourceInterfaces);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r"));
-
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
-    EXPECT_EQ(2, numResourceInterfaces);
+    EXPECT_EQ(OC_ACTIVE|OC_DISCOVERABLE|OC_OBSERVABLE, OCGetResourceProperties(handle));
+    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle));
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindContainedResourceBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle containerHandle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/kitchen",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+TEST(StackResource, StackTestResourceDiscoverOneResourceBad)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverOneResourceBad test");
+    InitStack(OC_SERVER);
 
-    OCResourceHandle handle0;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
                                             "core.led",
                                             "core.rw",
-                                            "/a/led",
+                                            "/a1/led",
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
+    const char *url = OCGetResourceUri(handle);
+    EXPECT_STREQ("/a1/led", url);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResource(containerHandle, containerHandle));
+    //EXPECT_EQ(OC_STACK_INVALID_URI, OCHandleServerRequest(&res, uri, query, req, rsp));
+    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle));
+    uint8_t numResources = 0;
+    uint8_t numExpectedResources = InitNumExpectedResources();
 
-    EXPECT_EQ(OC_STACK_ERROR, OCBindResource((OCResourceHandle) 0, handle0));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(numExpectedResources, numResources);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindContainedResourceGood) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    uint8_t numResources = 0;
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
+TEST(StackResource, StackTestResourceDiscoverOneResource)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverOneResource test");
+    InitStack(OC_SERVER);
 
-    OCResourceHandle containerHandle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle,
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
                                             "core.led",
                                             "core.rw",
-                                            "/a/kitchen",
+                                            "/a/led",
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    const char *url = OCGetResourceUri(handle);
+    EXPECT_STREQ("/a/led", url);
 
-    OCResourceHandle handle0;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led0",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(2, numResources);
+    //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
+    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle));
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackResource, StackTestResourceDiscoverManyResources)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting StackTestResourceDiscoverManyResources test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle1;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
@@ -794,9 +735,9 @@ TEST(StackTest, BindContainedResourceGood) {
                                             "core.rw",
                                             "/a/led1",
                                             0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(3, numResources);
+                                            OC_DISCOVERABLE));
+    const char *url = OCGetResourceUri(handle1);
+    EXPECT_STREQ("/a/led1", url);
 
     OCResourceHandle handle2;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2,
@@ -805,8 +746,11 @@ TEST(StackTest, BindContainedResourceGood) {
                                             "/a/led2",
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(4, numResources);
+    url = OCGetResourceUri(handle2);
+    EXPECT_STREQ("/a/led2", url);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle2, "core.brightled"));
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle2, "core.colorled"));
 
     OCResourceHandle handle3;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3,
@@ -815,8 +759,11 @@ TEST(StackTest, BindContainedResourceGood) {
                                             "/a/led3",
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(5, numResources);
+    url = OCGetResourceUri(handle3);
+    EXPECT_STREQ("/a/led3", url);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle3, OC_RSRVD_INTERFACE_LL));
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle3, OC_RSRVD_INTERFACE_BATCH));
 
     OCResourceHandle handle4;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle4,
@@ -824,54 +771,253 @@ TEST(StackTest, BindContainedResourceGood) {
                                             "core.rw",
                                             "/a/led4",
                                             0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(6, numResources);
+                                            OC_DISCOVERABLE));
+    url = OCGetResourceUri(handle4);
+    EXPECT_STREQ("/a/led4", url);
 
-    OCResourceHandle handle5;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle5,
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle4, "core.brightled"));
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle4, OC_RSRVD_INTERFACE_LL));
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle4, OC_RSRVD_INTERFACE_BATCH));
+
+    //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackBind, BindResourceTypeNameBad)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindResourceTypeNameBad test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
                                             "core.led",
                                             "core.rw",
-                                            "/a/led5",
+                                            "/a/led",
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(7, numResources);
 
+    uint8_t numResourceTypes;
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
+    EXPECT_EQ(1, numResourceTypes);
+    const char *resourceTypeName = OCGetResourceTypeName(handle, 0);
+    EXPECT_STREQ("core.led", resourceTypeName);
 
-    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle0));
-    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle1));
-    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle2));
-    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle3));
-    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle4));
-    EXPECT_EQ(OC_STACK_ERROR, OCBindResource(containerHandle, handle5));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceTypeToResource(handle, NULL));
 
-    EXPECT_EQ(handle0, OCGetResourceHandleFromCollection(containerHandle, 0));
-    EXPECT_EQ(handle1, OCGetResourceHandleFromCollection(containerHandle, 1));
-    EXPECT_EQ(handle2, OCGetResourceHandleFromCollection(containerHandle, 2));
-    EXPECT_EQ(handle3, OCGetResourceHandleFromCollection(containerHandle, 3));
-    EXPECT_EQ(handle4, OCGetResourceHandleFromCollection(containerHandle, 4));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
 
-    EXPECT_EQ(NULL, OCGetResourceHandleFromCollection(containerHandle, 5));
+TEST(StackBind, BindResourceTypeNameGood)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindResourceTypeNameGood test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    uint8_t numResourceTypes;
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
+    EXPECT_EQ(1, numResourceTypes);
+    const char *resourceTypeName = OCGetResourceTypeName(handle, 0);
+    EXPECT_STREQ("core.led", resourceTypeName);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.brightled"));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
+    EXPECT_EQ(2, numResourceTypes);
+    resourceTypeName = OCGetResourceTypeName(handle, 1);
+    EXPECT_STREQ("core.brightled", resourceTypeName);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.reallybrightled"));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
+    EXPECT_EQ(3, numResourceTypes);
+    resourceTypeName = OCGetResourceTypeName(handle, 2);
+    EXPECT_STREQ("core.reallybrightled", resourceTypeName);
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackBind, BindResourceTypeAttribRepGood)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindResourceTypeAttribRepGood test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    uint8_t numResourceTypes;
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
+    EXPECT_EQ(1, numResourceTypes);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.brightled"));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
+    EXPECT_EQ(2, numResourceTypes);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.reallybrightled"));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes));
+    EXPECT_EQ(3, numResourceTypes);
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+
+TEST(StackBind, BindResourceInterfaceNameBad)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceNameBad test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    uint8_t numResourceInterfaces;
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
+    EXPECT_EQ(1, numResourceInterfaces);
+    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_STREQ("core.rw", resourceInterfaceName);
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, NULL));
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackBind, BindResourceInterfaceNameGood)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceNameGood test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    uint8_t numResourceInterfaces;
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
+    EXPECT_EQ(1, numResourceInterfaces);
+    const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0);
+    EXPECT_STREQ("core.rw", resourceInterfaceName);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r"));
+
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
+    EXPECT_EQ(2, numResourceInterfaces);
+    resourceInterfaceName = OCGetResourceInterfaceName(handle, 1);
+    EXPECT_STREQ("core.r", resourceInterfaceName);
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackBind, BindResourceInterfaceMethodsBad)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceMethodsBad test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    uint8_t numResourceInterfaces;
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
+    EXPECT_EQ(1, numResourceInterfaces);
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, 0));
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackBind, BindResourceInterfaceMethodsGood)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindResourceInterfaceMethodsGood test");
+    InitStack(OC_SERVER);
+
+    OCResourceHandle handle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    uint8_t numResourceInterfaces;
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
+    EXPECT_EQ(1, numResourceInterfaces);
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r"));
+
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces));
+    EXPECT_EQ(2, numResourceInterfaces);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, GetResourceByIndex) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackBind, BindContainedResourceBad)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindContainedResourceBad test");
+    InitStack(OC_SERVER);
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
+    OCResourceHandle containerHandle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/kitchen",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
 
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+    OCResourceHandle handle0;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResource(containerHandle, containerHandle));
+
+    EXPECT_EQ(OC_STACK_ERROR, OCBindResource((OCResourceHandle) 0, handle0));
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackBind, BindContainedResourceGood)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindContainedResourceGood test");
+    InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
+    uint8_t numExpectedResources = InitNumExpectedResources();
+
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
+    EXPECT_EQ(numExpectedResources, numResources);
 
     OCResourceHandle containerHandle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle,
@@ -881,7 +1027,7 @@ TEST(StackTest, GetResourceByIndex) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle0;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
@@ -891,7 +1037,7 @@ TEST(StackTest, GetResourceByIndex) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(2, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle1;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
@@ -901,7 +1047,7 @@ TEST(StackTest, GetResourceByIndex) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(3, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle2;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2,
@@ -911,7 +1057,7 @@ TEST(StackTest, GetResourceByIndex) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(4, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle3;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3,
@@ -921,7 +1067,7 @@ TEST(StackTest, GetResourceByIndex) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(5, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle4;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle4,
@@ -931,7 +1077,7 @@ TEST(StackTest, GetResourceByIndex) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(6, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle5;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle5,
@@ -941,30 +1087,33 @@ TEST(StackTest, GetResourceByIndex) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(7, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
+
+
+    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle0));
+    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle1));
+    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle2));
+    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle3));
+    EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle4));
+    EXPECT_EQ(OC_STACK_ERROR, OCBindResource(containerHandle, handle5));
 
-    EXPECT_EQ(containerHandle, OCGetResourceHandle(0));
-    EXPECT_EQ(handle0, OCGetResourceHandle(1));
-    EXPECT_EQ(handle1, OCGetResourceHandle(2));
-    EXPECT_EQ(handle2, OCGetResourceHandle(3));
-    EXPECT_EQ(handle3, OCGetResourceHandle(4));
-    EXPECT_EQ(handle4, OCGetResourceHandle(5));
-    EXPECT_EQ(handle5, OCGetResourceHandle(6));
+    EXPECT_EQ(handle0, OCGetResourceHandleFromCollection(containerHandle, 0));
+    EXPECT_EQ(handle1, OCGetResourceHandleFromCollection(containerHandle, 1));
+    EXPECT_EQ(handle2, OCGetResourceHandleFromCollection(containerHandle, 2));
+    EXPECT_EQ(handle3, OCGetResourceHandleFromCollection(containerHandle, 3));
+    EXPECT_EQ(handle4, OCGetResourceHandleFromCollection(containerHandle, 4));
+
+    EXPECT_EQ(NULL, OCGetResourceHandleFromCollection(containerHandle, 5));
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, BindEntityHandlerBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackBind, BindEntityHandlerBad)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindEntityHandlerBad test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -974,30 +1123,16 @@ TEST(StackTest, BindEntityHandlerBad) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceHandler(handle, NULL));
     EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceHandler(NULL, NULL));
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-
-OCEntityHandlerResult entityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest) {
-    OC_LOG(INFO, TAG, "Entering entityHandler");
-
-    return OC_EH_OK;
-}
-
-TEST(StackTest, BindEntityHandlerGood) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackBind, BindEntityHandlerGood)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting BindEntityHandlerGood test");
+    InitStack(OC_SERVER);
 
     OCResourceHandle handle;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
@@ -1016,21 +1151,28 @@ TEST(StackTest, BindEntityHandlerGood) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, DeleteHeadResource) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackResourceAccess, GetResourceByIndex)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting GetResourceByIndex test");
+    InitStack(OC_SERVER);
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
+    uint8_t numResources = 0;
+    uint8_t numExpectedResources = InitNumExpectedResources();
+    uint8_t resourceIndex = InitResourceIndex();
 
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(numExpectedResources, numResources);
 
-    uint8_t numResources = 0;
+    OCResourceHandle containerHandle;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/kitchen",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle0;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
@@ -1040,30 +1182,110 @@ TEST(StackTest, DeleteHeadResource) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
-    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle0));
+    OCResourceHandle handle1;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led1",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(++numExpectedResources, numResources);
+
+    OCResourceHandle handle2;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led2",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(++numExpectedResources, numResources);
+
+    OCResourceHandle handle3;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led3",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(++numExpectedResources, numResources);
+
+    OCResourceHandle handle4;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle4,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led4",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(++numExpectedResources, numResources);
+
+    OCResourceHandle handle5;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle5,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led5",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
+
+    EXPECT_EQ(containerHandle, OCGetResourceHandle(resourceIndex));
+    EXPECT_EQ(handle0, OCGetResourceHandle(++resourceIndex));
+    EXPECT_EQ(handle1, OCGetResourceHandle(++resourceIndex));
+    EXPECT_EQ(handle2, OCGetResourceHandle(++resourceIndex));
+    EXPECT_EQ(handle3, OCGetResourceHandle(++resourceIndex));
+    EXPECT_EQ(handle4, OCGetResourceHandle(++resourceIndex));
+    EXPECT_EQ(handle5, OCGetResourceHandle(++resourceIndex));
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, DeleteHeadResource2) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
+TEST(StackResourceAccess, DeleteHeadResource)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting DeleteHeadResource test");
+    InitStack(OC_SERVER);
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
+    uint8_t numResources = 0;
+    uint8_t numExpectedResources = InitNumExpectedResources();
 
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(numExpectedResources, numResources);
+
+    OCResourceHandle handle0;
+    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
+                                            "core.led",
+                                            "core.rw",
+                                            "/a/led0",
+                                            0,
+                                            OC_DISCOVERABLE|OC_OBSERVABLE));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(++numExpectedResources, numResources);
+
+    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle0));
+    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
+    EXPECT_EQ(--numExpectedResources, numResources);
+
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackResourceAccess, DeleteHeadResource2)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting DeleteHeadResource2 test");
+    InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
+    uint8_t numExpectedResources = InitNumExpectedResources();
+    uint8_t resourceIndex = InitResourceIndex();
+
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
+    EXPECT_EQ(numExpectedResources, numResources);
 
     OCResourceHandle handle0;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
@@ -1073,7 +1295,7 @@ TEST(StackTest, DeleteHeadResource2) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle1;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
@@ -1083,33 +1305,30 @@ TEST(StackTest, DeleteHeadResource2) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(2, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle0));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    EXPECT_EQ(--numExpectedResources, numResources);
 
-    EXPECT_EQ(handle1, OCGetResourceHandle(0));
+    EXPECT_EQ(handle1, OCGetResourceHandle(resourceIndex));
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
 
-TEST(StackTest, DeleteLastResource) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResourceAccess, DeleteLastResource)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting DeleteLastResource test");
+    InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
+    uint8_t numExpectedResources = InitNumExpectedResources();
+    uint8_t resourceIndex = InitResourceIndex();
+
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
+    EXPECT_EQ(numExpectedResources, numResources);
 
     OCResourceHandle handle0;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
@@ -1119,7 +1338,7 @@ TEST(StackTest, DeleteLastResource) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle1;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
@@ -1129,13 +1348,13 @@ TEST(StackTest, DeleteLastResource) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(2, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle1));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    EXPECT_EQ(--numExpectedResources, numResources);
 
-    EXPECT_EQ(handle0, OCGetResourceHandle(0));
+    EXPECT_EQ(handle0, OCGetResourceHandle(resourceIndex));
 
     OCResourceHandle handle2;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2,
@@ -1145,26 +1364,23 @@ TEST(StackTest, DeleteLastResource) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(2, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, DeleteMiddleResource) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
+TEST(StackResourceAccess, DeleteMiddleResource)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting DeleteMiddleResource test");
+    InitStack(OC_SERVER);
 
     uint8_t numResources = 0;
+    uint8_t numExpectedResources = InitNumExpectedResources();
+    uint8_t resourceIndex = InitResourceIndex();
+
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
+    EXPECT_EQ(numExpectedResources, numResources);
 
     OCResourceHandle handle0;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0,
@@ -1174,7 +1390,7 @@ TEST(StackTest, DeleteMiddleResource) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(1, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle1;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
@@ -1184,7 +1400,7 @@ TEST(StackTest, DeleteMiddleResource) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(2, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     OCResourceHandle handle2;
     EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2,
@@ -1194,14 +1410,14 @@ TEST(StackTest, DeleteMiddleResource) {
                                             0,
                                             OC_DISCOVERABLE|OC_OBSERVABLE));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(3, numResources);
+    EXPECT_EQ(++numExpectedResources, numResources);
 
     EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle1));
     EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(2, numResources);
+    EXPECT_EQ(--numExpectedResources, numResources);
 
-    EXPECT_EQ(handle0, OCGetResourceHandle(0));
-    EXPECT_EQ(handle2, OCGetResourceHandle(1));
+    EXPECT_EQ(handle0, OCGetResourceHandle(resourceIndex));
+    EXPECT_EQ(handle2, OCGetResourceHandle(++resourceIndex));
 
     // Make sure the resource elements are still correct
     uint8_t numResourceInterfaces;
@@ -1213,208 +1429,75 @@ TEST(StackTest, DeleteMiddleResource) {
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-TEST(StackTest, GetResourceProperties) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle handle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-
-    EXPECT_EQ(OC_ACTIVE|OC_DISCOVERABLE|OC_OBSERVABLE, OCGetResourceProperties(handle));
-    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle));
-
-    EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(StackTest, StackTestResourceDiscoverOneResourceBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
 
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle handle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a1/led",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-    const char *url = OCGetResourceUri(handle);
-    EXPECT_STREQ("/a1/led", url);
-
-    //EXPECT_EQ(OC_STACK_INVALID_URI, OCHandleServerRequest(&res, uri, query, req, rsp));
-    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle));
-    uint8_t numResources = 0;
-    EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources));
-    EXPECT_EQ(0, numResources);
-
-    EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(StackTest, StackTestResourceDiscoverOneResource) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle handle;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-    const char *url = OCGetResourceUri(handle);
-    EXPECT_STREQ("/a/led", url);
-
-    //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
-    EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle));
-
-    EXPECT_EQ(OC_STACK_OK, OCStop());
-}
-
-TEST(StackTest, StackTestResourceDiscoverManyResources) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr));
-
-    OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
-    EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER));
-
-    OCResourceHandle handle1;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led1",
-                                            0,
-                                            OC_DISCOVERABLE));
-    const char *url = OCGetResourceUri(handle1);
-    EXPECT_STREQ("/a/led1", url);
-
-    OCResourceHandle handle2;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led2",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-    url = OCGetResourceUri(handle2);
-    EXPECT_STREQ("/a/led2", url);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle2, "core.brightled"));
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle2, "core.colorled"));
-
-    OCResourceHandle handle3;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led3",
-                                            0,
-                                            OC_DISCOVERABLE|OC_OBSERVABLE));
-    url = OCGetResourceUri(handle3);
-    EXPECT_STREQ("/a/led3", url);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle3, "oc.mi.ll"));
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle3, "oc.mi.b"));
-
-    OCResourceHandle handle4;
-    EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle4,
-                                            "core.led",
-                                            "core.rw",
-                                            "/a/led4",
-                                            0,
-                                            OC_DISCOVERABLE));
-    url = OCGetResourceUri(handle4);
-    EXPECT_STREQ("/a/led4", url);
-
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle4, "core.brightled"));
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle4, "oc.mi.ll"));
-    EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle4, "oc.mi.b"));
-
-    //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
-
-    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));
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+    void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType);
+#ifdef __cplusplus
 }
-
-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 // __cplusplus
+
+TEST(StackPresence, ParsePresencePayload)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    OC_LOG(INFO, TAG, "Starting ParsePresencePayload test");
+
+    char payload[100];
+    uint32_t seqNum = 0, maxAge = 0;
+    char * resType = NULL;
+
+    //Good Scenario
+    strncpy(payload, "{\"oc\":[100:99:presence]}", sizeof(payload));
+    parsePresencePayload(payload, &seqNum, &maxAge, &resType);
+    EXPECT_TRUE(100 == seqNum);
+    EXPECT_TRUE(99 == maxAge);
+    EXPECT_STREQ("presence", resType);
+    OCFree(resType);
+
+    //Bad Scenario -- should not result in Seg Fault
+    parsePresencePayload(payload, NULL, &maxAge, &resType);
+
+    //Bad Scenario
+    seqNum = 0; maxAge = 0; resType = NULL;
+    strncpy(payload, "{abracadabra}", sizeof(payload));
+    parsePresencePayload(payload, &seqNum, &maxAge, &resType);
+    EXPECT_TRUE(0 == seqNum);
+    EXPECT_TRUE(0 == maxAge);
+    EXPECT_EQ(NULL, resType);
+    OCFree(resType);
+
+    //Bad Scenario
+    seqNum = 0; maxAge = 0; resType = NULL;
+    strncpy(payload, "{\"oc\":[100]}", sizeof(payload));
+    parsePresencePayload(payload, &seqNum, &maxAge, &resType);
+    EXPECT_TRUE(100 == seqNum);
+    EXPECT_TRUE(0 == maxAge);
+    EXPECT_EQ(NULL, resType);
+    OCFree(resType);
+
+    //Bad Scenario
+    seqNum = 0; maxAge = 0; resType = NULL;
+    strncpy(payload, "{\"oc\":[]}", sizeof(payload));
+    parsePresencePayload(payload, &seqNum, &maxAge, &resType);
+    EXPECT_TRUE(0 == seqNum);
+    EXPECT_TRUE(0 == maxAge);
+    EXPECT_EQ(NULL, resType);
+    OCFree(resType);
+
+    //Bad Scenario
+    strncpy(payload, "{:]}", sizeof(payload));
+    parsePresencePayload(payload, &seqNum, &maxAge, &resType);
+    EXPECT_TRUE(0 == seqNum);
+    EXPECT_TRUE(0 == maxAge);
+    EXPECT_EQ(NULL, resType);
+    OCFree(resType);
+
+    //Bad Scenario
+    strncpy(payload, "{:[presence}", sizeof(payload));
+    parsePresencePayload(payload, &seqNum, &maxAge, &resType);
+    EXPECT_TRUE(0 == seqNum);
+    EXPECT_TRUE(0 == maxAge);
+    EXPECT_EQ(NULL, resType);
+    OCFree(resType);
 }
-#endif
index 27e9c0f..8b5740a 100644 (file)
@@ -26,13 +26,13 @@ DOXYFILE_ENCODING      = UTF-8
 # identify the project. Note that if you do not use Doxywizard you need
 # to put quotes around the project name if it contains spaces.
 
-PROJECT_NAME           = "C++ SDK"
+PROJECT_NAME           = "IoTivity C++ SDK"
 
 # The PROJECT_NUMBER tag can be used to enter a project or revision number.
 # This could be handy for archiving the generated documentation or
 # if some version control system is used.
 
-PROJECT_NUMBER         = "M1 Release"
+PROJECT_NUMBER         = 
 
 # Using the PROJECT_BRIEF tag one can provide an optional one line description
 # for a project that appears at the top of each page and should give viewer
@@ -163,7 +163,7 @@ SHORT_NAMES            = NO
 # comments will behave just like regular Qt-style comments
 # (thus requiring an explicit @brief command for a brief description.)
 
-JAVADOC_AUTOBRIEF      = NO
+JAVADOC_AUTOBRIEF      = YES
 
 # If the QT_AUTOBRIEF tag is set to YES then Doxygen will
 # interpret the first line (until the first dot) of a Qt-style
@@ -196,7 +196,7 @@ SEPARATE_MEMBER_PAGES  = NO
 # The TAB_SIZE tag can be used to set the number of spaces in a tab.
 # Doxygen uses this value to replace tabs by spaces in code fragments.
 
-TAB_SIZE               = 16
+TAB_SIZE               = 8
 
 # This tag can be used to specify a number of aliases that acts
 # as commands in the documentation. An alias has the form "name=value".
@@ -339,22 +339,6 @@ INLINE_SIMPLE_STRUCTS  = NO
 
 TYPEDEF_HIDES_STRUCT   = NO
 
-# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
-# determine which symbols to keep in memory and which to flush to disk.
-# When the cache is full, less often used symbols will be written to disk.
-# For small to medium size projects (<1000 input files) the default value is
-# probably good enough. For larger projects a too small cache size can cause
-# doxygen to be busy swapping symbols to and from disk most of the time
-# causing a significant performance penalty.
-# If the system has enough physical memory increasing the cache will improve the
-# performance by keeping more symbols in memory. Note that the value works on
-# a logarithmic scale so increasing the size by one will roughly double the
-# memory usage. The cache size is given by this formula:
-# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
-# corresponding to a cache size of 2^16 = 65536 symbols.
-
-SYMBOL_CACHE_SIZE      = 0
-
 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be
 # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given
 # their name and scope. Since this can be an expensive process and often the
@@ -678,13 +662,17 @@ WARN_LOGFILE           =
 INPUT                  = . \
                          ../include/OCApi.h \
                          ../include/OCPlatform.h \
-                         ../include/OCPlatformHandler.h \
+                         ../include/OCRepresentation.h \
                          ../include/OCResourceRequest.h \
                          ../include/OCResourceResponse.h \
                          ../include/OCResource.h \
-                         ../include/OCResourceHandler.h \
+                         ../resource/csdk/stack/include/octypes.h \
+                         ../resource/csdk/stack/include/ocstackconfig.h \
                          guides \
-                         ../RELEASE.txt
+                         ../../service/things-manager/sdk/inc \
+                         ../../service/soft-sensor-manager/SDK/cpp/include \
+                         ../../service/protocol-plugin/plugin-manager/src/PluginManager.h \
+                         ../../service/noification-manager/NotificationManager/include/hosting.h 
 
 # This tag can be used to specify the character encoding of the source files
 # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
@@ -1462,18 +1450,6 @@ GENERATE_XML           = NO
 
 XML_OUTPUT             = xml
 
-# The XML_SCHEMA tag can be used to specify an XML schema,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_SCHEMA             =
-
-# The XML_DTD tag can be used to specify an XML DTD,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_DTD                =
-
 # If the XML_PROGRAMLISTING tag is set to YES Doxygen will
 # dump the program listings (including syntax highlighting
 # and cross-referencing information) to the XML output. Note that
diff --git a/resource/docs/devdocs.doxyfile b/resource/docs/devdocs.doxyfile
new file mode 100644 (file)
index 0000000..4ab5086
--- /dev/null
@@ -0,0 +1,330 @@
+# Doxyfile 1.8.8
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+DOXYFILE_ENCODING      = UTF-8
+PROJECT_NAME           = "IoTivity Internals Documentation"
+PROJECT_NUMBER         =
+PROJECT_BRIEF          =
+PROJECT_LOGO           =
+OUTPUT_DIRECTORY       = devdocs
+CREATE_SUBDIRS         = NO
+ALLOW_UNICODE_NAMES    = NO
+OUTPUT_LANGUAGE        = English
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       =
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        =
+STRIP_FROM_INC_PATH    =
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = YES
+QT_AUTOBRIEF           = NO
+MULTILINE_CPP_IS_BRIEF = NO
+INHERIT_DOCS           = YES
+SEPARATE_MEMBER_PAGES  = NO
+TAB_SIZE               = 4
+ALIASES                =
+TCL_SUBST              =
+OPTIMIZE_OUTPUT_FOR_C  = NO
+OPTIMIZE_OUTPUT_JAVA   = NO
+OPTIMIZE_FOR_FORTRAN   = NO
+OPTIMIZE_OUTPUT_VHDL   = NO
+EXTENSION_MAPPING      =
+MARKDOWN_SUPPORT       = YES
+AUTOLINK_SUPPORT       = YES
+BUILTIN_STL_SUPPORT    = NO
+CPP_CLI_SUPPORT        = NO
+SIP_SUPPORT            = NO
+IDL_PROPERTY_SUPPORT   = YES
+DISTRIBUTE_GROUP_DOC   = NO
+SUBGROUPING            = YES
+INLINE_GROUPED_CLASSES = NO
+INLINE_SIMPLE_STRUCTS  = NO
+TYPEDEF_HIDES_STRUCT   = NO
+LOOKUP_CACHE_SIZE      = 0
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = YES
+EXTRACT_PACKAGE        = YES
+EXTRACT_STATIC         = YES
+EXTRACT_LOCAL_CLASSES  = YES
+EXTRACT_LOCAL_METHODS  = NO
+EXTRACT_ANON_NSPACES   = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = YES
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+SHOW_GROUPED_MEMB_INC  = NO
+FORCE_LOCAL_INCLUDES   = NO
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_MEMBERS_CTORS_1ST = NO
+SORT_GROUP_NAMES       = NO
+SORT_BY_SCOPE_NAME     = NO
+STRICT_PROTO_MATCHING  = NO
+GENERATE_TODOLIST      = YES
+GENERATE_TESTLIST      = YES
+GENERATE_BUGLIST       = YES
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       =
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_FILES             = YES
+SHOW_NAMESPACES        = YES
+FILE_VERSION_FILTER    =
+LAYOUT_FILE            =
+CITE_BIB_FILES         =
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           =
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = devdox \
+                         ../include \
+                         ../src \
+                         ../csdk/connectivity/api \
+                         ../csdk/connectivity/common/inc \
+                         ../csdk/connectivity/common/src \
+                         ../csdk/connectivity/inc \
+                         ../csdk/connectivity/src \
+                         ../csdk/logger/include \
+                         ../csdk/logger/src \
+                         ../csdk/ocmalloc/include \
+                         ../csdk/ocmalloc/src \
+                         ../csdk/ocrandom/include \
+                         ../csdk/ocrandom/src \
+                         ../csdk/security/include \
+                         ../csdk/security/src \
+                         ../csdk/stack/include \
+                         ../csdk/stack/src
+
+INPUT_ENCODING         = UTF-8
+FILE_PATTERNS          =
+RECURSIVE              = YES
+EXCLUDE                =
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       =
+EXCLUDE_SYMBOLS        =
+EXAMPLE_PATH           =
+EXAMPLE_PATTERNS       =
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             =
+INPUT_FILTER           =
+FILTER_PATTERNS        =
+FILTER_SOURCE_FILES    = NO
+FILTER_SOURCE_PATTERNS =
+USE_MDFILE_AS_MAINPAGE =
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = NO
+REFERENCES_RELATION    = NO
+REFERENCES_LINK_SOURCE = YES
+SOURCE_TOOLTIPS        = YES
+USE_HTAGS              = NO
+VERBATIM_HEADERS       = YES
+CLANG_ASSISTED_PARSING = NO
+CLANG_OPTIONS          =
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = YES
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          =
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = YES
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            =
+HTML_FOOTER            =
+HTML_STYLESHEET        =
+HTML_EXTRA_STYLESHEET  =
+HTML_EXTRA_FILES       =
+HTML_COLORSTYLE_HUE    = 220
+HTML_COLORSTYLE_SAT    = 100
+HTML_COLORSTYLE_GAMMA  = 80
+HTML_TIMESTAMP         = YES
+HTML_DYNAMIC_SECTIONS  = NO
+HTML_INDEX_NUM_ENTRIES = 100
+GENERATE_DOCSET        = NO
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+DOCSET_PUBLISHER_NAME  = Publisher
+GENERATE_HTMLHELP      = NO
+CHM_FILE               =
+HHC_LOCATION           =
+GENERATE_CHI           = NO
+CHM_INDEX_ENCODING     =
+BINARY_TOC             = NO
+TOC_EXPAND             = NO
+GENERATE_QHP           = NO
+QCH_FILE               =
+QHP_NAMESPACE          = org.doxygen.Project
+QHP_VIRTUAL_FOLDER     = doc
+QHP_CUST_FILTER_NAME   =
+QHP_CUST_FILTER_ATTRS  =
+QHP_SECT_FILTER_ATTRS  =
+QHG_LOCATION           =
+GENERATE_ECLIPSEHELP   = NO
+ECLIPSE_DOC_ID         = org.doxygen.Project
+DISABLE_INDEX          = NO
+GENERATE_TREEVIEW      = NO
+ENUM_VALUES_PER_LINE   = 4
+TREEVIEW_WIDTH         = 250
+EXT_LINKS_IN_WINDOW    = NO
+FORMULA_FONTSIZE       = 10
+FORMULA_TRANSPARENT    = YES
+USE_MATHJAX            = NO
+MATHJAX_FORMAT         = HTML-CSS
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+MATHJAX_EXTENSIONS     =
+MATHJAX_CODEFILE       =
+SEARCHENGINE           = YES
+SERVER_BASED_SEARCH    = NO
+EXTERNAL_SEARCH        = NO
+SEARCHENGINE_URL       =
+SEARCHDATA_FILE        = searchdata.xml
+EXTERNAL_SEARCH_ID     =
+EXTRA_SEARCH_MAPPINGS  =
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = YES
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4
+EXTRA_PACKAGES         =
+LATEX_HEADER           =
+LATEX_FOOTER           =
+LATEX_EXTRA_FILES      =
+PDF_HYPERLINKS         = YES
+USE_PDFLATEX           = YES
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+LATEX_SOURCE_CODE      = NO
+LATEX_BIB_STYLE        = plain
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = NO
+RTF_OUTPUT             = rtf
+COMPACT_RTF            = NO
+RTF_HYPERLINKS         = NO
+RTF_STYLESHEET_FILE    =
+RTF_EXTENSIONS_FILE    =
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_SUBDIR             =
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+GENERATE_DOCBOOK       = NO
+DOCBOOK_OUTPUT         = docbook
+DOCBOOK_PROGRAMLISTING = NO
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX =
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = NO
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           =
+INCLUDE_FILE_PATTERNS  =
+PREDEFINED             =
+EXPAND_AS_DEFINED      =
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+TAGFILES               =
+GENERATE_TAGFILE       =
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+EXTERNAL_PAGES         = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = YES
+MSCGEN_PATH            =
+DIA_PATH               =
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = YES
+DOT_NUM_THREADS        = 0
+DOT_FONTNAME           = Helvetica
+DOT_FONTSIZE           = 10
+DOT_FONTPATH           =
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+UML_LIMIT_NUM_FIELDS   = 10
+TEMPLATE_RELATIONS     = NO
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+CALLER_GRAPH           = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+INTERACTIVE_SVG        = NO
+DOT_PATH               =
+DOTFILE_DIRS           = devdox/dot
+MSCFILE_DIRS           =
+DIAFILE_DIRS           =
+PLANTUML_JAR_PATH      =
+DOT_GRAPH_MAX_NODES    = 50
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
diff --git a/resource/docs/devdox/ca_functional.dox b/resource/docs/devdox/ca_functional.dox
new file mode 100644 (file)
index 0000000..c469fe0
--- /dev/null
@@ -0,0 +1,89 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+@page ca_functional CA Functional design/implementation
+
+- @ref caf_overview
+  - @ref caf_ovr_communication
+    - @ref caf_ovr_comm_netinterface
+      - @ref caf_ovr_comm_netinterface_msg
+      - @ref caf_ovr_comm_netinterface_control
+      - @ref caf_ovr_comm_netinterface_eth
+      - @ref caf_ovr_comm_netinterface_wifi
+      - @ref caf_ovr_comm_netinterface_edr
+      - @ref caf_ovr_comm_netinterface_le
+      - @ref caf_ovr_comm_netinterface_detail
+
+<hr>
+
+@section caf_overview Overview
+
+The following are assorted implementation notes/references in regards to
+@ref ca_overview
+
+@subsection caf_ovr_communication Communication Adapters
+
+@subsubsection caf_ovr_comm_netinterface Network Interface Creation
+
+Interface connections are created at program startup. A Message Handler is
+started by invoking the CAInitialize() command. This in turn establishes
+the needed data structures and callbacks.
+
+@dotfile ca_arch_sketch.gv
+
+@paragraph caf_ovr_comm_netinterface_msg Message Handler
+
+The message handler owns athread pool and send and reive queue.
+
+@paragraph caf_ovr_comm_netinterface_control Interface controller
+
+This directly controls the individual adapters. Calling CAInitializeAdapters(ca_thread_pool_t handle)
+will invoke whatever config had been established by compile-time flags.
+
+@paragraph caf_ovr_comm_netinterface_eth Ethernet Adapter
+
+An interface adapter implemented to support Ethernet connections. It is
+created by calling CAInitializeEthernet()
+
+@paragraph caf_ovr_comm_netinterface_wifi WiFi Adapter
+
+An interface adapter implemented to support WiFi connections. It is created
+by calling CAInitializeWifi()
+
+@paragraph caf_ovr_comm_netinterface_edr EDR Adapter
+
+An interface adapter implemented to support EDR connections. It is created
+by calling CAInitializeEDR()
+
+@paragraph caf_ovr_comm_netinterface_le LE Adapter
+
+An interface adapter implemented to support LE connections. It is created
+by calling CAInitializeLE()
+
+@paragraph caf_ovr_comm_netinterface_detail Detailed Structure
+
+The following is a more detailed breakdown on the main types involved.
+Several structs and function details are present. However the diagram
+is more of a sketch and is not 100% complete.
+
+@dotfile ca_arch.gv
+
+*/
diff --git a/resource/docs/devdox/ca_overview.dox b/resource/docs/devdox/ca_overview.dox
new file mode 100644 (file)
index 0000000..626a973
--- /dev/null
@@ -0,0 +1,501 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+@page ca_overview CA Overview
+
+- @ref cao_overview
+- @ref cao_ddoc
+    - @ref cao_ddoc_freqs
+        - @ref cao_ddoc_freqs_discovery
+            - @ref cao_ddoc_fr1101
+            - @ref cao_ddoc_fr1102
+            - @ref cao_ddoc_fr1103
+            - @ref cao_ddoc_fr1104
+            - @ref cao_ddoc_fr1105
+            - @ref cao_ddoc_fr1106
+            - @ref cao_ddoc_fr1107
+            - @ref cao_ddoc_fr1108
+            - @ref cao_ddoc_fr1109
+        - @ref cao_ddoc_freqs_msg
+            - @ref cao_ddoc_fr1201
+            - @ref cao_ddoc_fr1202
+            - @ref cao_ddoc_fr1203
+            - @ref cao_ddoc_fr1204
+        - @ref cao_ddoc_freqs_obs
+            - @ref cao_ddoc_fr1301
+            - @ref cao_ddoc_fr1302
+            - @ref cao_ddoc_fr1303
+            - @ref cao_ddoc_fr1304
+        - @ref cao_ddoc_freqs_netconfig
+            - @ref cao_ddoc_fr1401
+            - @ref cao_ddoc_fr1402
+            - @ref cao_ddoc_fr1403
+        - @ref cao_ddoc_freqs_control_ip
+            - @ref cao_ddoc_fr2101
+            - @ref cao_ddoc_fr2102
+            - @ref cao_ddoc_fr2103
+            - @ref cao_ddoc_fr2104
+            - @ref cao_ddoc_fr2105
+            - @ref cao_ddoc_fr2106
+        - @ref cao_ddoc_freqs_control_bt
+            - @ref cao_ddoc_fr2201
+            - @ref cao_ddoc_fr2202
+            - @ref cao_ddoc_fr2203
+            - @ref cao_ddoc_fr2204
+            - @ref cao_ddoc_fr2205
+            - @ref cao_ddoc_fr2206
+        - @ref cao_ddoc_freqs_control_ble
+            - @ref cao_ddoc_fr2301
+            - @ref cao_ddoc_fr2302
+            - @ref cao_ddoc_fr2303
+            - @ref cao_ddoc_fr2304
+            - @ref cao_ddoc_fr2305
+            - @ref cao_ddoc_fr2306
+            - @ref cao_ddoc_fr2307
+        - @ref cao_ddoc_freqs_control_zigbee
+            - @ref cao_ddoc_fr2401
+            - @ref cao_ddoc_fr2402
+            - @ref cao_ddoc_fr2403
+            - @ref cao_ddoc_fr2404
+            - @ref cao_ddoc_fr2405
+            - @ref cao_ddoc_fr2406
+        - @ref cao_ddoc_freqs_control_zwave
+            - @ref cao_ddoc_fr2501
+            - @ref cao_ddoc_fr2502
+            - @ref cao_ddoc_fr2503
+            - @ref cao_ddoc_fr2504
+            - @ref cao_ddoc_fr2505
+            - @ref cao_ddoc_fr2506
+    - @ref cao_ddoc_qattr
+        - @ref cao_ddoc_qattr_reliability
+            - @ref cao_ddoc_nfr201
+            - @ref cao_ddoc_nfr202
+        - @ref cao_ddoc_qattr_security
+            - @ref cao_ddoc_nfr301
+            - @ref cao_ddoc_nfr302
+        - @ref cao_ddoc_qattr_maintenance
+            - @ref cao_ddoc_nfr501
+        - @ref cao_ddoc_qattr_portability
+            - @ref cao_ddoc_nfr601
+            - @ref cao_ddoc_nfr602
+            - @ref cao_ddoc_nfr603
+            - @ref cao_ddoc_nfr604
+            - @ref cao_ddoc_nfr605
+        - @ref cao_ddoc_qattr_extensibility
+            - @ref cao_ddoc_nfr701
+    - @ref cao_ddoc_constraints
+        - @ref cao_ddoc_constraints_licence
+            - @ref cao_ddoc_con101
+<hr>
+
+@section cao_overview Overview
+
+The original Connectivity Abstraction design overview diagram was from a presentation format. A similar version has been recreated in dot.
+
+@dotfile ca_overview.gv
+
+
+@section cao_ddoc Design doc info
+
+
+@subsection cao_ddoc_freqs Functional Requirements
+
+
+@subsubsection cao_ddoc_freqs_discovery Discovery
+
+
+@paragraph cao_ddoc_fr1101 FR.1101
+Client can find all resources on the reachable networks.
+- CA should provide the way to discover all resources on the WiFi/Ethernet/BLE/BT network.
+- Resources should be represented by dedicated URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1102 FR.1102
+Client can find all resources on the specific network.
+- CA should provide the way to discover all resources on the specified network.
+- The specified network can be the one of or those of WiFi/Ethernet/BLE/BT network.
+- Resources should be represented by dedicated URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1103 FR.1103
+Client can find specific resource on the reachable networks.
+- CA should provide discovery method to find specific resource on the WiFi/Ethernet/BLE/BT network.
+- Resource should be represented by URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1104 FR.1104
+Client can find specific resource on the specific network.
+- CA should provide discovery method to find specific resource on the specific network.
+- The specified network can be the one of or those of WiFi/Ethernet/BLE/BT network.
+- Resources should be represented by dedicated URI.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1105 FR.1105
+Server can advertise single resource on the reachable network.
+- CA should provide advertising method to notify the resource on the WiFi/Ethernet/BLE/BT network.
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1106 FR.1106
+Server can advertise single resource on the specific network.
+- CA should provide advertising method to notify the resource on the specified network.
+- The spefied network can be the on of or those of WiFi/Ethernet/BLE/BT network
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1107 FR.1107
+Server can advertise all resources at a time on the reachable network.
+- CA should provide advertising method to notify the all resources on the WiFi/Ethernet/BLE/BT network.
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1108 FR.1108
+Server can advertise all resource  at a time on the specific network.
+- CA should provide advertising method to notify the all resources on the specified network.
+- The spefied network can be the on of or those of WiFi/Ethernet/BLE/BT network
+- Resource should be represented by URI
+- Advertising can include 'alive' or 'disappear'.
+- Add ZigBee and ZWave to supported network. ( 2015.01 ) : TBD
+
+@paragraph cao_ddoc_fr1109 FR.1109
+Client can send periodic hearbeat request on the specific resource.
+- CA should check the status of discovered resource periodically.
+- Heartbeat policy can be followed by IoTivity specification.
+
+
+@subsubsection cao_ddoc_freqs_msg Messaging
+
+
+@paragraph cao_ddoc_fr1201 FR.1201
+Client can send request message to server
+- CA should provide the way to send request message to server on the supported network.
+- CA should notify the event to server when the request message arrives from client.
+
+@paragraph cao_ddoc_fr1202 FR.1202
+Server can send response message to client
+- CA should provide the way to send response messate to client on the supported network.
+- CA should notify the event to client when the response message arrives from server.
+
+@paragraph cao_ddoc_fr1203 FR.1203
+Client and Server can select QoS level for each message
+- CA should provide the way to select message QoS level to the server and client.
+- QoS level policy can follow CoAP guideline ( CON / NON / ACK / RESET )
+
+@paragraph cao_ddoc_fr1204 FR.1204
+Message can be re-sent if acknowledgement didn't received.
+- CA should send high QoS level message repeatly until the acknowledgement arrive.
+- Retransmission policy can follows CoAP guideline.
+
+
+@subsubsection cao_ddoc_freqs_obs Observation
+
+
+@paragraph cao_ddoc_fr1301 FR.1301
+Client can send observation request message to server 
+- CA should provide the way to send observation request message to server on the supported network.
+
+@paragraph cao_ddoc_fr1302 FR.1302
+Server can send observation message 
+- CA should provider the way to send observation event to the clients which request observation on the supported network.
+
+@paragraph cao_ddoc_fr1303 FR.1303
+Client can send observation cancel request message to server
+- CA should provide the way to send observation cancel request message to server on the supported network.
+
+@paragraph cao_ddoc_fr1304 FR.1304
+Server can cancel observation
+- CA should provide the way to send observation cancel event to the clients which request observation on the supported network.
+
+
+@subsubsection cao_ddoc_freqs_netconfig Network Configuration
+
+
+@paragraph cao_ddoc_fr1401 FR.1401
+Server / Client can select the network interfaces to use.
+- CA should provide the way to select network interfaces to use for communication.
+
+@paragraph cao_ddoc_fr1402 FR.1402
+Server / Client can unselect the network interfaces
+- CA should provide the way to unselect network interfaces to use for communication.
+
+@paragraph cao_ddoc_fr1403 FR.1403
+Server / Client can receive the status changes of network interface
+- CA should notify whenever the network interface status changes.
+
+
+@subsubsection cao_ddoc_freqs_control_ip Connectivity Control - Wifi/Ethernet
+
+
+@paragraph cao_ddoc_fr2101 FR.2101
+Server / client can listen multicast message
+- CA should bind multicast port
+- Multicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2102 FR.2102
+Server / client can send multicast message
+- CA should bind multicast port
+- Multicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2103 FR.2103
+Serve / client can listen unicast message
+- CA should bind unicast port
+- Unicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2104 FR.2104
+Server / client can send unicast message
+- CA should bind unicast port
+- Unicast IP address and port policy can be followed by IoTivity specification.
+
+@paragraph cao_ddoc_fr2105 FR.2105
+Server / client can monitor the interface status.
+- CA should notify the status of interface whenever change the status
+
+@paragraph cao_ddoc_fr2106 FR.2106
+Server / client can communicate in secured way
+- CA should provde the way to send / receive data in secure way
+- DTLS should be supported as a secure transfer
+
+
+@subsubsection cao_ddoc_freqs_control_bt Connectivity Control - Bluetooth
+
+
+@paragraph cao_ddoc_fr2201 FR.2201
+Client can discover the device has IoTivity server when inquiry time.
+- CA should scan the device using the specific UUID.
+- The specific UUID should represent IoTivity service and be unique
+
+@paragraph cao_ddoc_fr2202 FR.2202
+Server can register IoTivity service which can be found when inquiry scan time
+- CA should register the specific UUID to BT service.
+- The specific UUID should represent IoTivity service and be unique
+
+@paragraph cao_ddoc_fr2203 FR.2203
+Client can request bonding to the device has IoTivity server.
+- CA should request bonding to the device.
+- CA should delegate the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2204 FR.2204
+Server can accept / deny the bonding request from client device
+- CA should deletage the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2205 FR.2205
+Server / client can get the bonded device list from BT service
+
+@paragraph cao_ddoc_fr2206 FR.2206
+Server / client can communicate throuth the RFCOMM
+- Serial Port Profile( SPP ) should be provided by platform.
+- Platform should provide the fundamental operation functions to CA.
+  : connect(), accept(), disconnect(), send(), recv()
+
+@subsubsection cao_ddoc_freqs_control_ble Connectivity Control - BLE
+
+
+@paragraph cao_ddoc_fr2301 FR.2301
+Client can discover the device has IoTivity server when scan time.
+- CA should scan the device using the specific UUID
+- The specific UUID should represent IoTivity service ahd be unique
+
+@paragraph cao_ddoc_fr2302 FR.2302
+Server can register IoTivity service which can be found when
+advertising time
+- CA should register the specific UUID to BT service.
+- The specific UUID should represent IoTivity service and be unique
+
+@paragraph cao_ddoc_fr2303 FR.2303
+Client can request bonding to the device has IoTivity server.
+- CA should request bonding to the device.
+- CA should delegate the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2304 FR.2304
+Server can accept / deny the bonding request from client device
+- CA should deletage the bonding procedure to the platform
+
+@paragraph cao_ddoc_fr2305 FR.2305
+Server / client can get the bonded device list from BT service
+
+@paragraph cao_ddoc_fr2306 FR.2306
+Server / client can communicate throuth the RFCOMM
+- General Attribute Profile( GATT ) should be provided by platform.
+- Platform should provide the fundamental operation functions to CA.
+  : connect(), accept(), disconnect(), send(), recv()
+
+@paragraph cao_ddoc_fr2307 FR.2307
+Server / client can send more lager data than 23 bytes
+- (Optional) Platform may provide 'read long' and 'write long' feature of BLE
+- CA should fragment and reassemble the lager data
+
+
+@subsubsection cao_ddoc_freqs_control_zigbee Connectivity Control - ZigBee
+
+
+@paragraph cao_ddoc_fr2401 FR.2401
+Client can start forming the ZigBee network
+- Client means ZigBee coordinator device
+- ZigBee service should provide the way to start ZigBee network forming
+
+@paragraph cao_ddoc_fr2402 FR.2402
+Client can finish the formed ZigBee network
+- Client means ZigBee coordinator device
+- ZigBee service should provide the way to finish ZigBee network forming
+
+@paragraph cao_ddoc_fr2403 FR.2403
+Client can receive the event whenever the ZigBee end-device joins and leaves
+- CA should know the identifier of ZigBee end-device when joins and leaves.
+- CA should know the identifier of ZigBee end-device joined through ZigBee router when joins and leaves.
+- CA could select the ZigBee end-device to join
+
+@paragraph cao_ddoc_fr2404 FR.2404
+Client can convert common ZigBee cluster to IoTivity URI.
+- CA should convert the common ZigBee cluster to URI.
+- The common ZigBee cluster can be one of the clusters announced by ZigBee alliance.
+  : eg. Home Automation Profile, Smart Energy Profile, and so on.
+
+@paragraph cao_ddoc_fr2405 FR.2405
+Client can convert common ZigBee cluster attributes to IoTivity attributes
+- CA should convert the common ZigBee cluster to attribute of the URI.
+- The common ZigBee profile can be one of the clusters announced by ZigBee alliance.
+
+@paragraph cao_ddoc_fr2406 FR.2406
+Client can convert CoAP message to ZCL command
+- CA should convert CoAP message to ZCL command to send ZigBee end-device
+
+
+@subsubsection cao_ddoc_freqs_control_zwave Connectivity Control - ZWave
+
+
+@paragraph cao_ddoc_fr2501 FR.2501
+Client can start creating PAN ( ZWave network )
+- Client means ZWave controller device
+- ZWave service should provide the way to start ZWave network creation
+
+@paragraph cao_ddoc_fr2502 FR.2502
+Client can finish the created PAN ( ZWave network )
+- Client means ZWave controller device
+- ZWave service should provide the way to finish created ZWave network
+
+@paragraph cao_ddoc_fr2503 FR.2503
+Client can receive the event whenever the ZWave slave joins and leaves
+- CA should know the identifier of ZWave slave when joins and leaves.
+- CA should know the identifier of ZWave slave joined through ZWave router when joins and leaves.
+- CA could select the ZWave slave to join
+
+@paragraph cao_ddoc_fr2504 FR.2504
+Client can convert common ZWave device class to IoTivity URI
+- CA should convert the common ZWave device class to URI.
+- The common ZWave device class can be one of the device classes announced by ZWave alliance.
+
+@paragraph cao_ddoc_fr2505 FR.2505
+Client can convert common ZWave command class to IoTivity attribute
+- CA should convert the common ZWave command class to attribute of the URI.
+- The common ZWave command class can be one of the command classes announced by ZWave alliance.
+
+@paragraph cao_ddoc_fr2506 FR.2506
+Client can convert CoAP message to ZWave command
+- CA should convert CoAP message to command class to send ZWave slave
+
+
+@subsection cao_ddoc_qattr Quality Attributes
+
+
+@subsubsection cao_ddoc_qattr_reliability Reliability
+
+
+@paragraph cao_ddoc_nfr201 NFR.201
+Network availability detection
+- Maxinum number of messaging failure is 3 during 10 minutes in available network .
+- Terminate the connection when the number is over the maximum value.
+
+@paragraph cao_ddoc_nfr202 NFR.202
+Messaging
+- The transmitted message from source has to be deliverd to the destination completely.
+
+@subsubsection cao_ddoc_qattr_security Security
+
+
+@paragraph cao_ddoc_nfr301 NFR.301
+Transfer Channel Protection
+- should protect the transfer channel using DTLS in CoaP , authentication in BT and other mechanisms in connectivities
+
+@paragraph cao_ddoc_nfr302 NFR.302
+Message Protection ( TBD )
+- should be able to encrypt the message to protect using RSA??
+
+
+@subsubsection cao_ddoc_qattr_maintenance Maintenance
+
+
+@paragraph cao_ddoc_nfr501 NFR.501
+Modularization for connectivities
+- One connectivity module change shouldn't have an effect on the other connectivity module.
+
+@subsubsection cao_ddoc_qattr_portability Portability
+
+
+@paragraph cao_ddoc_nfr601 NFR.601
+Support on Ubuntu 12.04
+- The software should be ported on Ubuntu (12.04) without change.
+- The platform specific portion should be controlled by build configurations.
+
+@paragraph cao_ddoc_nfr602 NFR.602
+Support on Android 4.4 / 5.0 and higher
+- The software should be ported on Android v5.0 and higher without change.
+- The platform specific portion should be controlled by build configurations.
+- JNI block can be added
+
+@paragraph cao_ddoc_nfr603 NFR.603
+Support on Tizen v2.3 and higher
+- The software should be ported on Tizen v2.3 and higher without change.
+- The platform specific portion should be controlled by build configurations.
+
+@paragraph cao_ddoc_nfr604 NFR.604
+Support on Arduino Mega
+- The software should be ported on Arduino Mega without change.
+- Connectivity function can be supported through the various shields.
+- The platform specific portion should be controlled by build configurations.
+
+@paragraph cao_ddoc_nfr605 NFR.605
+Support on Arduino Due
+- The software should be ported on Arduino Due without change.
+- Connectivity function can be supported through the various shields.
+- The platform specific portion should be controlled by build configurations.
+
+
+@subsubsection cao_ddoc_qattr_extensibility Extensibility
+
+@paragraph cao_ddoc_nfr701 NFR.701
+Connectivity Extension
+- The Architecture change has to be minimized when expanding Connectivities.
+
+
+@subsection cao_ddoc_constraints Constraints
+
+
+@subsubsection cao_ddoc_constraints_licence License
+
+
+@paragraph cao_ddoc_con101 CON.101
+Open source license
+- All source codes should be released under Apache License v2 or compatible.
+
+*/
diff --git a/resource/docs/devdox/dot/ca_arch.gv b/resource/docs/devdox/dot/ca_arch.gv
new file mode 100644 (file)
index 0000000..eee3d5b
--- /dev/null
@@ -0,0 +1,283 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+digraph G {
+    label = "Network Interface Creation";
+    fontsize = 10;
+
+    edge [
+        fontsize = 10
+    ]
+
+    node [
+        fontsize = 10,
+    ]
+
+ // ----
+
+    msg_handler [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td port="a" tooltip="Message Handler" bgcolor="gray">Message Handler</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref g_threadPoolHandle" tooltip="-g_threadPoolHandle: ca_thread_pool_t">-g_threadPoolHandle: ca_thread_pool_t</td></tr>
+                    <tr><td align="left" href="\ref g_sendThread" tooltip="-g_sendThread: CAQueueingThread_t">-g_sendThread: CAQueueingThread_t</td></tr>
+                    <tr><td align="left" href="\ref g_receiveThread" tooltip="-g_receiveThread: CAQueueingThread_t">-g_receiveThread: CAQueueingThread_t</td></tr>
+                    <tr><td align="left" href="\ref g_retransmissionContext" tooltip="-g_retransmissionContext: CARetransmission_t">-g_retransmissionContext: CARetransmission_t</td></tr>
+                    <tr><td align="left" href="\ref g_requestHandler" tooltip="-g_requestHandler: CARequestCallback">-g_requestHandler: CARequestCallback</td></tr>
+                    <tr><td align="left" href="\ref g_responseHandler" tooltip="-g_responseHandler: CAResponseCallback">-g_responseHandler: CAResponseCallback</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeMessageHandler()" tooltip="+CAInitializeMessageHandler">+CAInitializeMessageHandler</td></tr>
+                    <tr><td align="left" href="\ref CATerminateMessageHandler()" tooltip="+CATerminateMessageHandler">+CATerminateMessageHandler</td></tr>
+                </table>>
+    ]
+
+    threadpool [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref ca_thread_pool_t" tooltip="ca_threadpool_t" bgcolor="gray">ca_threadpool_t</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref ca_thread_pool_init()" tooltip="+ca_thread_pool_init">+ca_thread_pool_init</td></tr>
+                    <tr><td align="left" href="\ref ca_thread_pool_free()" tooltip="+ca_thread_pool_free">+ca_thread_pool_free</td></tr>
+                    <tr><td align="left" href="\ref ca_thread_pool_add_task()" tooltip="+ca_thread_pool_add_task">+ca_thread_pool_add_task</td></tr>
+                </table>>
+    ]
+
+
+    thread_out [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CASendThreadProcess()" tooltip="Send Thread" bgcolor="gray">Send Thread</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CASendThreadProcess()" tooltip="+CASendThreadProcess">+CASendThreadProcess</td></tr>
+                </table>>
+    ]
+
+    thread_in [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAReceiveThreadProcess()" tooltip="Receive Thread" bgcolor="gray">Receive Thread</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAReceiveThreadProcess()" tooltip="+CAReceiveThreadProcess">+CAReceiveThreadProcess</td></tr>
+                </table>>
+    ]
+
+    thread_retrans [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CASendUnicastData()" tooltip="Retransmit Thread" bgcolor="gray">Retransmit Thread</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CASendUnicastData()" tooltip="+CASendUnicastData">+CASendUnicastData</td></tr>
+                </table>>
+    ]
+
+    control [
+        tooltip = "Interface Controller",
+        label = "{Interface Controller| +CAInitializeAdapters()\l\n \n }",
+        URL = "\ref CAInitializeAdapters()"
+
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeAdapters()" tooltip="Interface Controller" bgcolor="gray">Interface Controller</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref g_adapterHandler" tooltip="-g_adapterHandler: CAConnectivityHandler_t[]">-g_adapterHandler: CAConnectivityHandler_t[]</td></tr>
+                    <tr><td align="left" href="\ref g_networkPacketReceivedCallback" tooltip="-g_networkPacketReceivedCallback: CANetworkPacketReceivedCallback">-g_networkPacketReceivedCallback: CANetworkPacketReceivedCallback</td></tr>
+
+                    <tr><td align="left" href="\ref g_networkChangeCallback" tooltip="-g_networkChangeCallback: CANetworkChangeCallback">-g_networkChangeCallback: CANetworkChangeCallback</td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeAdapters()" tooltip="+CAInitializeAdapters">+CAInitializeAdapters</td></tr>
+                    <tr><td align="left" href="\ref CATerminateAdapters()" tooltip="+CATerminateAdapters">+CATerminateAdapters</td></tr>
+                    <tr><td align="left" href="\ref CAStartAdapter()" tooltip="+CAStartAdapter">+CAStartAdapter</td></tr>
+                    <tr><td align="left" href="\ref CAStopAdapter()" tooltip="+CAStopAdapter">+CAStopAdapter</td></tr>
+                    <tr><td align="left" href="\ref CAGetNetworkInfo()" tooltip="+CAGetNetworkInfo">+CAGetNetworkInfo</td></tr>
+                    <tr><td align="left" href="\ref CAStartListeningServerAdapters()" tooltip="+CAStartListeningServerAdapters">+CAStartListeningServerAdapters</td></tr>
+                    <tr><td align="left" href="\ref CAStartDiscoveryServerAdapters()" tooltip="+CAStartDiscoveryServerAdapters">+CAStartDiscoveryServerAdapters</td></tr>
+                </table>>
+    ]
+
+
+    conn_handler [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAConnectivityHandler_t" tooltip="CAConnectivityHandler_t" bgcolor="gray">CAConnectivityHandler_t</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::startAdapter" tooltip="+startAdapter: CAAdapterStart">+startAdapter: CAAdapterStart</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::startListenServer" tooltip="+startListenServer: CAAdapterStartListeningServer">+startListenServer: CAAdapterStartListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::startDiscoveryServer" tooltip="+startDiscoveryServer: CAAdapterStartDiscoveryServer">+startDiscoveryServer: CAAdapterStartDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::sendData" tooltip="+sendData: CAAdapterSendUnitcastData">+sendData: CAAdapterSendUnitcastData</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::sendDataToAll" tooltip="+sendDataToAll: CAAdapterSendMulticastData">+sendDataToAll: CAAdapterSendMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::GetnetInfo" tooltip="+GetnetInfo: CAAdapterGetNetworkInfo">+GetnetInfo: CAAdapterGetNetworkInfo</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::readData" tooltip="+readData: CAAdapterReadData">+readData: CAAdapterReadData</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::stopAdapter" tooltip="+stopAdapter: CAAdapterStop">+stopAdapter: CAAdapterStop</td></tr>
+                    <tr><td align="left" href="\ref CAConnectivityHandler_t::terminate" tooltip="+terminate: CAAdapterTerminate">+terminate: CAAdapterTerminate</td></tr>
+                </table>>
+
+
+    ]
+
+    adapt01 [
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeEthernet" tooltip="Ethernet Adapter" bgcolor="gray">Ethernet Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeEthernet" tooltip="+CAInitializeEthernet">+CAInitializeEthernet</td></tr>
+                    <tr><td align="left" href="\ref CATerminateEthernet()" tooltip="+CATerminateEthernet">+CATerminateEthernet</td></tr>
+                    <tr><td align="left" href="\ref CAStartEthernet()" tooltip="+CAStartEthernet">+CAStartEthernet</td></tr>
+                    <tr><td align="left" href="\ref CAStopEthernet()" tooltip="+CAStopEthernet">+CAStopEthernet</td></tr>
+                    <tr><td align="left" href="\ref CAStartEthernetListeningServer()" tooltip="+CAStartEthernetListeningServer">+CAStartEthernetListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartEthernetDiscoveryServer()" tooltip="+CAStartEthernetDiscoveryServer">+CAStartEthernetDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetEthernetInterfaceInformation" tooltip="+CAGetEthernetInterfaceInformation">+CAGetEthernetInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendEthernetUnicastData()" tooltip="+CASendEthernetUnicastData">+CASendEthernetUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendEthernetMulticastData()" tooltip="+CASendEthernetMulticastData">+CASendEthernetMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadEthernetData()" tooltip="+CAReadEthernetData">+CAReadEthernetData</td></tr>
+                </table>>
+    ]
+
+    adapt02 [
+        tooltip = "WiFi Adapter",
+        label = "{WiFi Adapter| +CAInitializeWifi()\l\n \n }",
+        URL = "\ref CAInitializeWifi()"
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeWifi" tooltip="WiFi Adapter" bgcolor="gray">WiFi Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeWifi()" tooltip="+CAInitializeWifi">+CAInitializeWifi</td></tr>
+                    <tr><td align="left" href="\ref CATerminateWIFI()" tooltip="+CATerminateWIFI">+CATerminateWIFI</td></tr>
+                    <tr><td align="left" href="\ref CAStartWIFI()" tooltip="+CAStartWIFI">+CAStartWIFI</td></tr>
+                    <tr><td align="left" href="\ref CAStopWIFI()" tooltip="+CAStopWIFI">+CAStopWIFI</td></tr>
+                    <tr><td align="left" href="\ref CAStartWIFIListeningServer()" tooltip="+CAStartWIFIListeningServer">+CAStartWIFIListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartWIFIDiscoveryServer()" tooltip="+CAStartWIFIDiscoveryServer">+CAStartWIFIDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetWIFIInterfaceInformation()" tooltip="+CAGetWIFIInterfaceInformation">+CAGetWIFIInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendWIFIUnicastData()" tooltip="+CASendWIFIUnicastData">+CASendWIFIUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendWIFIMulticastData()" tooltip="+CASendWIFIMulticastData">+CASendWIFIMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadWIFIData()" tooltip="+CAReadWIFIData">+CAReadWIFIData</td></tr>
+                </table>>
+    ]
+
+    adapt03 [
+        tooltip = "EDR Adapter",
+        label = "{EDR Adapter| +CAInitializeEDR()\l\n \n }",
+        URL = "\ref CAInitializeEDR()"
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeEDR" tooltip="EDR Adapter" bgcolor="gray">EDR Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeEDR" tooltip="+CAInitializeEDR">+CAInitializeEDR</td></tr>
+                    <tr><td align="left" href="\ref CATerminateEDR()" tooltip="+CATerminateEDR">+CATerminateEDR</td></tr>
+                    <tr><td align="left" href="\ref CAStartEDR()" tooltip="+CAStartEDR">+CAStartEDR</td></tr>
+                    <tr><td align="left" href="\ref CAStopEDR()" tooltip="+CAStopEDR">+CAStopEDR</td></tr>
+                    <tr><td align="left" href="\ref CAStartEDRListeningServer()" tooltip="+CAStartEDRListeningServer">+CAStartEDRListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartEDRDiscoveryServer()" tooltip="+CAStartEDRDiscoveryServer">+CAStartEDRDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetEDRInterfaceInformation" tooltip="+CAGetEDRInterfaceInformation">+CAGetEDRInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendEDRUnicastData()" tooltip="+CASendEDRUnicastData">+CASendEDRUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendEDRMulticastData()" tooltip="+CASendEDRMulticastData">+CASendEDRMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadEDRData()" tooltip="+CAReadEDRData">+CAReadEDRData</td></tr>
+                </table>>
+    ]
+
+    adapt04 [
+        tooltip = "LE Adapter",
+        label = "{LE Adapter| +CAInitializeLE()\l\n \n }",
+        URL = "\ref CAInitializeLE()"
+
+        shape = none
+        margin = 0
+        label = <<table border="1" cellspacing="0" cellborder="0">
+                    <tr><td href="\ref CAInitializeLE" tooltip="LE Adapter" bgcolor="gray">LE Adapter</td></tr>
+                    <hr/>
+                    <tr><td> </td></tr>
+                    <hr/>
+                    <tr><td align="left" href="\ref CAInitializeLE()" tooltip="+CAInitializeLE">+CAInitializeLE</td></tr>
+                    <tr><td align="left" href="\ref CATerminateLE()" tooltip="+CATerminateLE">+CATerminateLE</td></tr>
+                    <tr><td align="left" href="\ref CAStartLE()" tooltip="+CAStartLE">+CAStartLE</td></tr>
+                    <tr><td align="left" href="\ref CAStopLE" tooltip="+CAStopLE">+CAStopLE</td></tr>
+                    <tr><td align="left" href="\ref CAStartLEListeningServer()" tooltip="+CAStartLEListeningServer">+CAStartLEListeningServer</td></tr>
+                    <tr><td align="left" href="\ref CAStartLEDiscoveryServer()" tooltip="+CAStartLEDiscoveryServer">+CAStartLEDiscoveryServer</td></tr>
+                    <tr><td align="left" href="\ref CAGetLEInterfaceInformation()" tooltip="+CAGetLEInterfaceInformation">+CAGetLEInterfaceInformation</td></tr>
+                    <tr><td align="left" href="\ref CASendLEUnicastData()" tooltip="+CASendLEUnicastData">+CASendLEUnicastData</td></tr>
+                    <tr><td align="left" href="\ref CASendLEMulticastData()" tooltip="+CASendLEMulticastData">+CASendLEMulticastData</td></tr>
+                    <tr><td align="left" href="\ref CAReadLEData()" tooltip="+CAReadLEData">+CAReadLEData</td></tr>
+                </table>>
+    ]
+
+
+    // UML Inheritance relationships
+    edge [
+        arrowtail = open,
+        dir = back
+    ]
+
+    {
+        conn_handler -> adapt01
+        conn_handler -> adapt02
+        conn_handler -> adapt03
+        conn_handler -> adapt04
+    }
+
+    // UML Aggregation relationships
+    edge [
+        arrowtail = odiamond,
+        dir = back
+    ]
+
+    msg_handler -> control
+    msg_handler -> threadpool
+    msg_handler -> thread_out
+    msg_handler -> thread_in
+    msg_handler -> thread_retrans
+    control -> conn_handler
+
+
+    // Additional 'layout' tweaks
+    {rank = same control threadpool thread_out thread_in thread_retrans}
+    edge [
+        style = invis
+    ]
+    threadpool -> thread_out -> control -> thread_in -> thread_retrans
+}
diff --git a/resource/docs/devdox/dot/ca_arch_sketch.gv b/resource/docs/devdox/dot/ca_arch_sketch.gv
new file mode 100644 (file)
index 0000000..fd6f322
--- /dev/null
@@ -0,0 +1,90 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+digraph G {
+    label = "Network Interface Creation";
+    fontsize = 10;
+
+    edge [
+        fontsize = 10
+    ]
+
+    node [
+        fontsize = 10,
+        shape = "record"
+    ]
+
+ // ----
+
+    msg_handler [
+        label = "{Message Handler| | }",
+        tooltip = "Message Handler",
+        URL = "\ref caf_ovr_comm_netinterface_msg"
+    ]
+
+    control [
+        label = "{Interface controller| | }",
+        tooltip = "Interface controller",
+        URL = "\ref caf_ovr_comm_netinterface_control"
+    ]
+
+    adapt01 [
+        label = "{Ethernet Adapter| | }",
+        tooltip = "Ethernet Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_eth"
+    ]
+
+    adapt02 [
+        label = "{WiFi Adapter| | }",
+        tooltip = "WiFi Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_wifi"
+    ]
+
+    adapt03 [
+        label = "{EDR Adapter| | }",
+        tooltip = "EDR Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_edr"
+    ]
+
+    adapt04 [
+        label = "{LE Adapter| | }"
+        tooltip = "LE Adapter",
+        URL = "\ref caf_ovr_comm_netinterface_le"
+    ]
+
+    // UML Aggregation relationships
+    edge [
+        arrowtail = odiamond,
+        dir = back
+    ]
+
+    msg_handler -> control
+
+    // UML Composition relationships
+    edge [
+        arrowtail = diamond,
+        dir = back
+    ]
+
+    control -> adapt01
+    control -> adapt02
+    control -> adapt03
+    control -> adapt04
+}
diff --git a/resource/docs/devdox/dot/ca_overview.gv b/resource/docs/devdox/dot/ca_overview.gv
new file mode 100644 (file)
index 0000000..2ac92d7
--- /dev/null
@@ -0,0 +1,197 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Note that this diagram is not the best example of efficient
+// graphviz/doxygen use. It was recreating the look of an existing
+// graphic and thus is focused too much on appearance over
+// functionality.
+//
+
+digraph G {
+    label = "Abstracted Architecture";
+
+    z [
+        label = "Resource Introspection",
+        shape = box,
+        style = filled,
+        fillcolor="#efefef:#bdbdbd",
+        gradientangle=270,
+        width=8
+    ];
+
+    subgraph cluster_0 {
+        label = "Connectivity Framework";
+        labeljust="l";
+
+        yy [
+            label = "Connectivity API",
+            shape = box,
+            style = filled,
+            color = "#4a7bbd",
+            fillcolor="#e6efff:#a5c5ff",
+            gradientangle=270,
+            width=8
+        ];
+
+        subgraph cluster_1 {
+            label = "Control layer";
+            style=filled;
+            color = "#4a7bbd";
+            fillcolor="#e6efff:#a5c5ff";
+            gradientangle=270;
+
+            node [
+                style=filled,
+                color="#9cbd52",
+                fillcolor="#f7ffe6:#deffad",
+                gradientangle=270,
+                shape=box
+            ];
+
+            a0 [label="Network\nConfiguration"];
+            a1 [label="CoAP\nProtocol"];
+            a2 [label="Interface\nController"];
+
+            {rank = same a0 a1 a2}
+        }
+
+        subgraph cluster_2 {
+            label = "Transport Adapter";
+            style=filled;
+            color = "#4a7bbd"
+            fillcolor="#e6efff:#a5c5ff";
+            gradientangle=270;
+            node [
+                style=filled,
+                color="#9cbd52",
+                fillcolor="#f7ffe6:#deffad",
+                gradientangle=270,
+                shape=box
+            ];
+
+            bb [label = "Common Adapter Interface", width=5];
+
+            b0 [label="IP\nAdapter"];
+            b1 [label="LE GATT\nAdapter"];
+            b2 [label="BT SPP\nAdapter"];
+            b3 [label="XXX\nAdapter"];
+
+            {rank = same b0 b1 b2 b3}
+        }
+
+        subgraph cluster_3 {
+            label = "Platform Adapter";
+            style=filled;
+            color = "#4a7bbd"
+            fillcolor="#e6efff:#a5c5ff";
+            gradientangle=270;
+            node [
+                style=filled
+                color="#7b5aa5"
+                fillcolor="#f7e6f7:#c5b5ef";
+                gradientangle=270;
+                shape=box
+            ];
+
+            c0 [label="Ubuntu\nAdapter\n(ETH/WIFI/BT)"];
+            c1 [label="Android\nAdapter\n(WIFI/BLE/BT)"];
+            c2 [label="Tizen\nAdapter\n(WIFI/BLE/BT)"];
+            c3 [label="Arduino\nAdapter\n(ETH/WIFI/BLE)"];
+            c4 [label="Platform\n(6loWPAN)\n ", color="#f7e6f7"];
+
+            {rank = same c0 c1 c2 c3 c4}
+        }
+    }
+
+    {
+        node [
+            style = filled,
+            fillcolor="#efefef:#bdbdbd",
+            gradientangle=270,
+            shape=box
+        ];
+
+        d0 [label="Ubuntu"];
+        d1 [label="Android"];
+        d2 [label="Tizen"];
+        d3 [label="Arduino"];
+        d4 [label="????"];
+
+        {rank = same d0 d1 d2 d3 d4}
+    }
+
+    subgraph cluster_lgd {
+        label = "Legend";
+
+        node [
+            style = filled,
+            width=0.25,
+            height=0.25,
+            fixedsize=true,
+            shape=box,
+            gradientangle=270
+        ];
+
+        e0 [label=" ", color="#4a7bbd", fillcolor="#e6efff:#a5c5ff"];
+        e1 [label=" ", color="#9cbd52", fillcolor="#f7ffe6:#deffad"];
+        e2 [label=" ", color="#7b5aa5", fillcolor="#f7e6f7:#c5b5ef"];
+        e3 [label=" ", fillcolor="#efefef:#bdbdbd"];
+        e_dummy[shape=point, style=invis];
+
+        edge [penwidth=0,
+              arrowhead=none,
+              fontsize=10];
+        e0 -> e1 [label="CA Component    "];
+        e1 -> e2 [label="CA Module-platform independent    "];
+        e2 -> e3 [label="CA Module-platform specific    "];
+        e3 -> e_dummy [label="External"];
+
+        {rank = same e0 e1 e2 e3 e_dummy}
+    }
+
+    // In order to control placement of the sets of items in a
+    // top-to-bottom placement, invisible edges/arrows are used.
+    // This gives a logcial control for the physical appearance we want.
+    {
+        edge[style = invis];
+
+        // order groups to get top-to-bottom
+        z -> yy
+        yy -> {a0 a2}
+        a1 -> bb
+        {a0 a2} -> {b1 b2}
+        bb -> {b1 b2}
+        {b0 b1 b2 b3} -> c2
+        c0 -> d0
+        c1 -> d1
+        c2 -> d2
+        c3 -> d3
+        d0 -> e0
+        {d2} -> {e1 e2}
+        d4 -> e3
+
+        // order nodes left-to-right
+        a0 -> a1 -> a2
+        b0 -> b1 -> b2 -> b3
+        c0 -> c1 -> c2 -> c3 -> c4
+        d0 -> d1 -> d2 -> d3 -> d4
+        e0 -> e1 -> e2 -> e3
+    }
+}
diff --git a/resource/docs/devdox/mainpage.dox b/resource/docs/devdox/mainpage.dox
new file mode 100644 (file)
index 0000000..b2dc361
--- /dev/null
@@ -0,0 +1,43 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+@mainpage
+
+This is documentation intended for internal use of developers actually
+working on the implementation code itself. At the moment this specific page
+is just a simplified placeholder.
+
+<hr>
+
+Quick starting points:
+
+- @ref ca_overview which replicates an existing requirements doc.
+  - An overview diagram in that document: @ref cao_overview
+- @ref ca_functional Minimal sample showing how diagrams and code doc can be
+  integrated.
+  - @ref caf_ovr_comm_netinterface a section with a minimal UML sketch
+  - @ref caf_ovr_comm_netinterface_detail a more detailed UML diagram
+- The 'Related Pages' tab
+
+Then see CAEthernetInitializeServer() for...
+- CAInitializeEthernet()
+- other
+*/
\ No newline at end of file
index 6cc3fa7..330cb9a 100644 (file)
@@ -1,13 +1,14 @@
 <doxygenlayout version="1.0">
     <navindex>
         <tab type="mainpage" visible="yes" title="Home"/>
-        <tab type="user" url="@ref AboutOIC"   title="About OIC" />
-        <tab type="user" url="@ref OCGuides"   title="Programmer's Guide" />
-        <tab type="user" url="@ref OCHowTo"    title="How To..." />
         <tab type="classes" visible="yes" title="API Reference">
             <tab type="classlist" visible="yes" title=""/>
             <tab type="hierarchy" visible="yes" title="" intro=""/>
             <tab type="classmembers" visible="yes" title="" intro=""/>
         </tab>
+        <tab type="files" visible="yes" title="">
+          <tab type="filelist" visible="yes" title="" intro=""/>
+          <tab type="globals" visible="yes" title="" intro=""/>
+        </tab>
     </navindex>
 </doxygenlayout>
diff --git a/resource/docs/guides/AboutOIC.txt b/resource/docs/guides/AboutOIC.txt
deleted file mode 100644 (file)
index 04ee0bc..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*!
-
-@page AboutOIC About Open Interconnect Consortium
-
-@section WhoAreWe Who are we?
-
-\li We want to connect the next 25 billion devices for the Internet of Things.
-
-\li We want to provide secure and reliable device discovery and connectivity across multiple OSs and platforms.
-
-\li There are multiple proposals and forums driving different approaches... but no single solution addresses the majority of key requirements.
-
-\li We need industry consolidation around a common, interoperable approach.
-
-\li We need a broad industry consortium of companies to create a scalable solution.
-
-
-@section WhyAreWeDoingThis Why are we doing this?
-
-\li We are defining the specification, certification & branding to deliver reliable interoperability - a connectivity framework that abstracts complexity
-
-\li This standard will be an open specification that anyone can implement and is easy for developers to use
-
-\li It will include IP protection & branding for certified devices (via compliance testing) and service-level interoperability
-
-\li There will also be an Open Source implementation of the standard
-
-\li This Open Source implementation will be designed to enable application developers and device manufacturers to deliver interoperable products across Android, iOS, Windows, Linux, Tizen, and more.
-
-@section WhoNeedsThis Who needs this?
-
-\li Consumers, Enterprise, Industrial, Automotive, Health, etc. who want smart devices to easily interconnect and communicate with appliances, embedded devices, etc.
-
-\li Developers of operating systems, platforms, and applications who want their products to interoperate seamlessly across many brands and ecosystems.
-
-\li End users who want consistent levels of security and identity across smart devices down to the smallest connected appliance
-
-@section HowWillWeDeliverIt How will we deliver it?
-
-\li Our goal is to define a comprehensive communications framework to enable emerging applications in all key vertical markets.
-
-\li The framework must enable multiple new modes of communication, such as Peer-to-Peer, Mesh & Bridging, Reporting & Control, etc.
-
-\li The framework should include a consistent implementation of identity, authentication and security across the modes of User ID, Enterprise / Industrial ID & Credentials.
-
-\li It should include a sense of proximity for the Internet of Things and Wearable devices and include support for Onboarding and Provisioning.
-
-\li And the framework must support a "building block" architecture and provide an Open Source implementation
-
-
-*/
\ No newline at end of file
index 5202e8a..4131aff 100644 (file)
@@ -2,14 +2,12 @@
 
 @mainpage Welcome
 
-IoTivity runs as an open source project. This infrastructure can be used by OIC partners to contribute and co-work for the project. This document is for any developer trying to utilize the IoTivity project in building applications. This document includes:
+IoTivity is an open source software framework enabling seamless device-to-device connectivity to address the emerging needs of the Internet of Things. These API references are for any developer trying to utilize the IoTivity project for building applications.
 
-\li \ref OCGuides - High level overview of the API and how to use them
-
-\li \ref OCHowTo - contains guides and tutorials to help developers get started
-
-\li <a href="annotated.html"> API Reference </a> - provides a reference to all public APIs available to utilize the power of IoTivity.
+\li <a href="annotated.html"><strong>API References</strong></a><br />Provides a reference to all public APIs available to utilize the power of IoTivity.
 
+\li <a href="https://www.iotivity.org/documentation"><strong>Getting Started Guides and Tutorials</strong></a><br />Detailed getting started guides and tutorials can be found on the iotivity.org website.
 
+\li <a href="https://wiki.iotivity.org"><strong>Wiki</strong></a><br />Additional documentation can be found on the IoTivity Wiki.
 
 */
diff --git a/resource/docs/guides/HowToGuidesIndex.txt b/resource/docs/guides/HowToGuidesIndex.txt
deleted file mode 100644 (file)
index 0d8c717..0000000
+++ /dev/null
@@ -1,1556 +0,0 @@
-/*!\r
-\r
-@page OCHowTo How To... Guides\r
-\r
-@ref Guide_Representative_Devices "Sample representative devices used in these tutorials"\r
-\r
-@ref Guide_Stack_Init "How to initialize the stack"\r
-\r
-@ref Guide_Register_Resource "How to register a resource"\r
-\r
-@ref Guide_Find_Resource "How to find a resource"\r
-\r
-@ref Guide_PUT  "How to set resource state [PUT]"\r
-\r
-@ref Guide_GET "How to query resource state [GET]"\r
-\r
-@ref Guide_Observe "How to observe resource state [Observe]"\r
-\r
-\r
-\r
-********************************************************************\r
-\r
-\r
-@page Guide_Representative_Devices Representative Devices\r
-\r
-The best way to understand the concepts for IoTivity is through following an example and understanding the use case. The following devices are referred to throughout this document for use cases and basic operations. The details are listed here for reference so that implementers can compare the responses from these devices with their configuration to develop an understanding of what the responses mean.\r
-\r
-@section Rep_Light_Device Light devices (192.168.1.11-13)\r
-\r
-A lighting device that can handle up to two light bulbs with dimmers. Each light bulb resource has two attributes:\r
-\li Power: controls power and can have a value of 0 (off) or 1 (on)\r
-\li Level: current dimmer level with a value from 1 (low) to 10 (full)\r
-\r
-The separation of the attributes allows the light to return to the previous light level when the power is toggled.\r
-\r
-@subsection Rep_Light_Device_Description Description of resources on this device type\r
-\r
-<table cellspacing="0" cellpadding="0" border=1 >\r
-\r
-<tr>\r
-<td valign="top" ><b>Resource</b></td>\r
-<td valign="top" ><b>Description</b></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core</p></td>\r
-<td valign="top" ><p>Standard resource listing in JSON format.</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core/d</p></td>\r
-<td valign="top" ><p>Virtual (hidden) resource that describes the device. It is searchable and supports the JSON attributes listed in the appendix.</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/lights</p></td>\r
-<td valign="top" ><p>The resource collection that contains light resources</p>\r
-\r
-<p>rt=alpha.light</p>\r
-\r
-<p>if=oc.mi.ll (linked-list)</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/light/1</p></td>\r
-<td valign="top" ><p>The resource associated with the first light bulb attached to this device </p>\r
-\r
-<p>rt=alpha.light</p>\r
-\r
-<p>if=oc.mi.def (default)</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/light/2</p></td>\r
-<td valign="top" ><p>The resource associated with the second light bulb attached to this device</p>\r
-\r
-<p>rt=alpha.light</p>\r
-\r
-<p>if=oc.mi.def (default)</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-@subsection Rep_Light_Device_Resource_11 Resource(s) at 192.168.1.11\r
-\r
-This device contains a single light resource. The following lists the valid resources and their typical state:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<td valign="top" ><b>Resource</b></td>\r
-<td valign="top" ><b>Representation</b></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core</p></td>\r
-<td valign="top" ><p>[</p>\r
-\r
-<p>{ "href" : "/lights", "rt" : ["alpha.light"], "if" : ["oc.mi.ll"]},</p>\r
-\r
-<p>{ "href" : "/light/1", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs" : 1}</p>\r
-\r
-<p>]</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core/d</p></td>\r
-<td valign="top" ><p>{</p>\r
-\r
-<p>"di" : "12345678-1234-1234-0000000000000011",</p>\r
-\r
-<p>"dn" : "Alpha Light Controller",</p>\r
-\r
-<p>"dd" : "A Light Controller"</p>\r
-\r
-<p>}</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/light/1</p></td>\r
-<td valign="top" ><p>{ "power" : 0, "level" : 4 }</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-\r
-@subsection Rep_Light_Device_Resource_12 Resource(s) at 192.168.1.12\r
-\r
-This device contains a single light resource. The following lists the valid resources and their typical state:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<td valign="top" ><b>Resource</b></td>\r
-<td valign="top" ><b>Representation</b></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core</p></td>\r
-<td valign="top" ><p>[</p>\r
-\r
-<p>{ "href" : "/lights", "rt" : ["alpha.light"], "if" : ["oc.mi.ll"]},</p>\r
-\r
-<p>{ "href" : "/light/2", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs":1}</p>\r
-\r
-<p>]</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core/d</p></td>\r
-<td valign="top" ><p>{</p>\r
-\r
-<p>"di" : "12345678-1234-1234-0000000000000012",</p>\r
-\r
-<p>"dn" : "Alpha Light Controller",</p>\r
-\r
-<p>"dd" : "A Light Controller"</p>\r
-\r
-<p>}</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/light/2</p></td>\r
-<td valign="top" ><p>{ "power" : 1, "level" : 6 }</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-@subsection Rep_Light_Device_Resource_13 Resource(s) at 192.168.1.13\r
-\r
-This device contains two light resources. The following lists the valid resources and their typical state:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-\r
-<tr>\r
-<td valign="top" ><p>Resource</p></td>\r
-<td valign="top" ><p>Representation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core</p></td>\r
-<td valign="top" ><p>[</p>\r
-\r
-<p>{ "href" : "/lights", "rt" : ["alpha.light"], "if" : ["oc.mi.ll"]},</p>\r
-\r
-<p>{ "href" : "/light/1", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs":1},</p>\r
-\r
-<p>{ "href" : "/light/2", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs":1}</p>\r
-\r
-<p>]</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/oc/core/d</p></td>\r
-<td valign="top" ><p>{</p>\r
-\r
-<p>"di" : "12345678-1234-1234-0000000000000013",</p>\r
-\r
-<p>"dn" : "Alpha Light Controller",</p>\r
-\r
-<p>"dd" : "A Light Controller"</p>\r
-\r
-<p>}</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/light/1</p></td>\r
-<td valign="top" ><p>{ "power" : 0, "level" : 8 }</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>/light/2</p></td>\r
-<td valign="top" ><p>{ "power" : 1, "level" : 10 }</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-@page Guide_Stack_Init Stack Initialization\r
-\r
-@section Stack_Init_SD Sequence Diagram\r
-\r
-@image html seq_stack_init.png\r
-\r
-@note API calls take only important parameters. We omitted some of the parameters for clarity.\r
-\r
-The asynchronous processing block handles incoming network traffic including packet processing, scheduled tasks including communication timeouts and callbacks to the application resulting from these activities.\r
\r
-@section Stack_Init_CPP Stack Initialization in C++\r
-\r
-@code {.cpp}\r
-    // Create PlatformConfig object\r
-    PlatformConfig cfg;\r
-    cfg.ipAddress = "134.134.161.33";\r
-    cfg.port = 5683;\r
-    cfg.mode = ModeType::Client;\r
-    cfg.serviceType = ServiceType::InProc;\r
-\r
-    // Create a OCPlatform instance.\r
-    // Note: Platform creation is synchronous call.\r
-    try\r
-    {\r
-        OCPlatform platform(cfg);\r
-    }catch(OCException& e)\r
-    {\r
-        //Handle error\r
-    }\r
- @endcode\r
-\r
-Stack initialization in C++ consists of:\r
-@li Creating a OCPlatform object with Platform configuration which allows definition of role operation (server or client), stack operation (in-process or out-of-process), etc.\r
-@note\r
-@li This is a synchronous call. The application will receive an exception if platform object creation fails.\r
-@li The C++ SDK handles all of the memory allocation and collection. Therefore, the application need not worry about memory management related to the stack.\r
-@li Platform creation happens on the main thread while the message pump happens on a worker thread.\r
-\r
-\r
-\r
-\r
-\r
-********************************************************************\r
-\r
-@page Guide_Register_Resource Registering A Resource\r
-\r
-Registering a resource requires two basic items:\r
-\li A handler to process requests from the stack, and\r
-\li A URI path to register the resource. \r
-The URI path should be rooted (in other words, start with a slash). The stack will construct the fully qualified URI by adding the URI authority to the provided URI path. For example, given a service running on port 5683 in a device at IP address 192.168.1.1, if the application registers a resource with a URI path "/light/1", the resulting fully qualified URI is "oc://192.168.1.1:5683/light/1", which uniquely identifies the resource's location (IP address port and path).\r
-@note Only one resource can be registered at a given URI.\r
\r
-@image HTML seq_register_resource_2.png\r
-\r
-@section Register_Resource_SD Sequence Diagram\r
-The following call sequence diagram outlines the operations performed in the stack when a resource is registered:\r
-\r
-@image HTML seq_register_resource.png\r
-\r
-<b>Step 1</b>:\r
-Assuming the application has created a valid OCPlatform object, the application registers a new resource with the stack by calling OCPlatform::registerResource(...).\r
-\r
-In this example, the call would take the form:\r
-\r
-       platform.registerResource(&handle, "/light/1", "light", "oc.mi.def", handler, OC_DISCOVERABLE)\r
-\r
-The handle is a reference to the resource that is used on other APIs. The URI path ("/light/1") is where on this server that the resource can be located. The URI path is unique; this call will fail if the application attempts to register another resource using an existing URI. The resource type ("light") and interface ("oc.mi.def") are properties of the resource used in the discovery process. The handler is a function called from the stack to process requests. The flags control how the stack should handle the resource. The OC_DISCOVERABLE flag indicates that the resource should be reported if a client performs a resource discovery on this server.\r
-\r
-<b>Step 2</b>:\r
-\r
-The OCPlatform::registerResource(...) method delegates the call to the appropriate instance of the stack (in-process or out-of-process via IPC).\r
-\r
-<b>Step 3</b>:\r
-The internal registerResource(...) method constructs a C++ entity handler and registers it with the C SDK using OCCreateResource(...).\r
-\r
-In this example, the call would take the form:\r
-\r
-       OCCreateResource(&handle, "light", "oc.mi.def", "/light/1", handler, OC_ DISCOVERABLE)\r
-\r
-Many of these parameters are passed through to the C SDK directly. However, the entity handler is a proxy function for the handler passed from OCPlatform::registerResource(...).\r
\r
-@section Register_Resource_CPP Register Resource in C++ [Server]\r
-\r
-@code{.cpp}\r
-    OCResourceHandle resourceHandle;\r
-    std::string resourceURI = "/light/1"; \r
-    std::string resourceTypeName = "alpha.light\r
-    std::string resourceInterface = DEFAULT_INTERFACE; \r
-    uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;\r
-\r
-    OCStackResult result = platform.registerResource(resourceHandle, \r
-                                                        resourceURI,\r
-                                                        resourceTypeName,\r
-                                                        resourceInterface,\r
-                                                        &entityHandler,\r
-                                                        resourceProperty);\r
-\r
-    if (OC_STACK_OK == result)\r
-    {\r
-        //Successfull\r
-    }\r
-\r
-\r
-@endcode\r
-\r
-\r
-\r
-********************************************************************\r
-\r
-@page Guide_Find_Resource Finding A Resource\r
-\r
-This operation returns all resources of given type on the network service. This operation is sent via multicast to all services. However, the filter limits the responders to just those that support the resource type in the query. Currently only exact matches are supported.\r
-\r
-@image HTML seq_find_resource_2.png\r
-\r
-@section Find_Resource_SD Sequence Diagram\r
-\r
-The following sequence diagram illustrates the resource discovery process over the network when using CoAP. The mechanism is different for Bluetooth, SSDP/HTTP, etc. In the case of CoAP, a 'get' request is sent via multicast to all IoTivity devices. Each device processes the query and responds if the request filter is satisfied. \r
-\r
-In the following example, the client requests all of the light resources with a resource type (rt). Both lights respond to the request, but the fan does not.\r
-\r
-@image HTML seq_find_resource_3.png\r
-\r
-\r
-The following sequence diagram describes the call sequence for discovery from the client side.\r
-@image HTML seq_find_resource.png\r
-\r
-Notes:\r
-\li Assuming that the client has a properly initialized OCPlatform object, a C++ SDK client can discover resources by calling OCPlatform::findResources(...).\r
-\r
-In this example, the call would take the form:\r
-\r
-       platform.findResources("", "/oc/core?rt=alpha.light", findHandler)\r
-\r
-The first parameter is the URI authority (target host), which, when empty, indicates that this is for all nodes. The second parameter ("/oc/core?rt=alpha.light") is the URI path and URI query. The URI path ("/oc/core") indicates the resource and the URI query ("rt=alpha.light") is the filter.\r
-\r
-\li The SDK call findResources(...) internally delegates the call directly to the in-process or to the out-of process stack via IPC based on the stack configuration.\r
-\li Within the stack, findResource(...) calls the C API function OCDoResource(...). In this example, the call is OCDoResource(&handle, OC_REST_GET, "/oc/core?rt=alpha.light", 0, 0, OC_NON_CONFIRMABLE,  ...)\r
-\li OCDoResource determines which transport is needed to dispatch the request and delegates the call. In the case of CoAP, the following calls are made:\r
-       - Calls OCDoCoapResource(OC_REST_GET, OC_NON_CONFIRMABLE, token, "/oc/core?rt=alpha.light", 0). The token in this example is a nonce that ties a CoAP response back to the CoAP request. Internally, this method creates the CoAP PDU for dispatching.\r
-       - Calls coap_send(context, host, pdu), which is a wrapper for the implementation below.\r
-       - Calls coap_send_impl(context, host, packet), which dispatches the packet to the socket and does the appropriate CoAP bookkeeping.\r
-       - Calls OCSend(socket, buffer, size...), which is a wrapper for the socket implementation as the functions for dispatching a UDP packet can vary in the embedded systems.\r
-\li Servers that offer the resource on the network will reply to the query. The message pump that is evoked from the OCProcess(...) function in the C SDK receives these response packets and dispatches them to the callback associated with the original request based on the CoAP message ID. These responses will come back at the timing defined by their servers. The client stack has timeouts for these responses that are listed in the appendices.\r
-\li As previously mentioned, the stack matches the response to the original request using the message ID and send the results to the callback associated with the request. At this level, the raw payload is presented in JSON format. It is the responsibility of the callback passed to OCDoResource(...) to parse this result.\r
-\li The C++ SDK provides a callback to OCDoResource(...) that will parse the results, construct collections of OCResource objects from the response, and pass them to a C++ client using the handler passed to the platform.findResource(...) method. The handler will be called once for each resource server that responds to the query.\r
-\r
-Notes:\r
-\li Some of the API call parameters have been omitted for brevity.\r
-\li The findResource() method can be used in the following ways:\r
-       - Find all resources on the network that match the provided criteria\r
-       - Query a specific (single) server for the resources that it provides matching the provided criteria\r
-\li The findResource() method may be used multiple times to find a resource\r
-\li The findResource() callback is called from the message pump thread in multithreaded environments\r
-\li Blocking in the findResource() callback will block other stack processing including servicing the network I/O which can cause delays and missed packets.\r
-\r
-<b>Detailed server call sequence diagram</b>\r
-The following sequence diagram illustrates the call sequence for discovery from the server side. \r
-\r
-@note When the request is sent to all nodes, all nodes will run through this sequence.\r
-\r
-@image HTML seq_find_resource_4.png\r
-\r
-Notes:\r
-\li The discovery request under CoAP is handled like any other resource GET request. The request can be received via unicast or multicast, but the response, if any, is always sent via unicast.\r
-\li The stack dispatches the request to an entity handler that is defined by the stack.\r
-\li The handler for "/oc/core", processes the URI query, if any, and builds a list of resources that match the criteria and returns the result in JSON to the network transport.\r
-\li In the case of CoAP, if the request is made to all nodes (multicast) and the resource list is empty, no response is sent to the clients. If the request is directed (unicast) or the resource list has results, the response is sent unicast back the client.\r
-\r
-\r
-@section Find_Resource_CPP Register Resource in C++ [Client]\r
-\r
-@code{.cpp}\r
-// Callback to found resources\r
-    void foundResource(std::shared_ptr<OCResource> resource)\r
-    {\r
-            \r
-    std::string resourceURI;\r
-    std::string hostAddress;\r
-    try\r
-    {\r
-        // Do some operations with resource object.\r
-        if(resource)\r
-        {\r
-            std::cout<<"DISCOVERED Resource:"<<std::endl;\r
-            // Get the resource URI\r
-            resourceURI = resource->uri();\r
-            std::cout << "\tURI of the resource: " << resourceURI << std::endl;\r
-\r
-            // Get the resource host address\r
-            hostAddress = resource->host();\r
-            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;\r
-\r
-            // Get the resource types\r
-            std::cout << "\tList of resource types: " << std::endl;\r
-            for(auto &resourceTypes : resource->getResourceTypes())\r
-            {\r
-                std::cout << "\t\t" << resourceTypes << std::endl;\r
-            }\r
-\r
-            // Get the resource interfaces\r
-            std::cout << "\tList of resource interfaces: " << std::endl;\r
-            for(auto &resourceInterfaces : resource->getResourceInterfaces())\r
-            {\r
-                std::cout << "\t\t" << resourceInterfaces << std::endl;\r
-            }\r
-\r
-            if(resourceURI == "/a/light1")\r
-            {\r
-                // Found interested resource\r
-            }\r
-        }\r
-        else\r
-        {\r
-            // Resource is invalid\r
-            std::cout << "Resource is invalid" << std::endl;\r
-        }\r
-\r
-    }\r
-    catch(std::exception& e)\r
-    {\r
-        //log\r
-    }\r
-\r
-    }\r
-\r
-\r
-    try\r
-    {\r
-        OCPlatform platform(cfg);\r
-\r
-        // Find all resources\r
-        platform.findResource("", "coap://224.0.1.187/oc/core?rt=alpha.light", &foundResource);\r
-\r
-    }catch(OCException& e)\r
-    {\r
-        //Handle Error\r
-    }\r
-\r
-\r
-@endcode\r
-\r
-@section Find_Resource_OTA_Request Over the air Request\r
-\r
-The request is sent to all nodes on the network:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Note(s)</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>224.0.1.187:5683</p></td>\r
-<td valign="top" ><p>Multicast packet</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>NON, GET, MID=0x7d40</p></td>\r
-<td valign="top" ><p>Multicast discovery request should be non-confirmable</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>oc</p></td>\r
-<td rowspan="3" valign="top" ><p>"/oc/core?rt=alpha.light"</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>core</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Query</p></td>\r
-<td valign="top" ><p>rt=alpha.light</p></td>\r
-<td valign="middle" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Accept</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-\r
-</table>\r
-\r
-\r
-\r
-@section Find_Resource_OTA_Response Over the air Response(s)\r
-\r
-Assuming that all of the representative devices (see @ref Guide_Representative_Devices "Representative Devices") are online, three responses are expected. Only the three devices with light resources respond; the list of resources has been filtered to contain just the resources that match the criteria.\r
-\r
-<b>From 192.168.1.11</b>:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.1:5683</p></td>\r
-<td valign="top" ><p>Client Address</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>ACK, CONTENT, MID=0x7d40</p></td>\r
-<td valign="top" ><p>Success w/content</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Content</p>\r
-\r
-<p>Format</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Payload</p></td>\r
-<td valign="top" ><p>[</p>\r
-\r
-<p>{ "href" : "/light/1", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1}</p>\r
-\r
-<p>]</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-<b>From 192.168.1.12</b>:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.1:5683</p></td>\r
-<td valign="top" ><p>Client Address</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>ACK, CONTENT, MID=0x7d40</p></td>\r
-<td valign="top" ><p>Success w/content</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Content</p>\r
-\r
-<p>Format</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Payload</p></td>\r
-<td valign="top" ><p>[</p>\r
-\r
-<p>{ "href" : "/light/2", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1}</p>\r
-\r
-<p>]</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-<b>From 192.168.1.13</b>:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.1:5683</p></td>\r
-<td valign="top" ><p>Client Address</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>ACK, CONTENT, MID=0x7d40</p></td>\r
-<td valign="top" ><p>Success w/content</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Content</p>\r
-\r
-<p>Format</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Payload</p></td>\r
-<td valign="top" ><p>[</p>\r
-\r
-<p>{ "href" : "/light/1", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1},</p>\r
-\r
-<p>{ "href" : "/light/2", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1}</p>\r
-\r
-<p>]</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-********************************************************************\r
-\r
-@page Guide_PUT Setting a resource state [PUT]\r
-\r
-This operation sets the value of a simple resource. In this example, we turn on a light resource and set the brightness to 50%.\r
-\r
-@section PUT_SD Sequence Diagram\r
-\r
-@image HTML seq_put.png\r
-\r
-Steps:\r
-1.     The client application calls resource.put(...) to set representation of resource. \r
-Example call: \r
-resource.put(attributeMap, queryParamsMap, &onPut);   \r
-2.     Client SDK internally calls the setResourceAttributes function of the client wrapper.\r
-Example call:\r
-OCDoResource(OC_REST_PUT, "//192.168.1.11/light/1, 0, 0, OC_CONFIRMABLE, callback);\r
-3.     Send PUT request to remote device\r
-4.     The OCProcess() service function (server-side message pump) reads the packet from the socket and dispatches the request to the entity handler for the provided URI.\r
-5.     The entity handler, which was provided by an upper layer when the resource was registered, parses the representation and in the case of the C++ API passes the results to the upper layer handler. In a C only environment, the results would also be processed in the entity handler.\r
-6.     The upper layer entity handler written by the app developer/vendor is invoked, and response is formed accordingly.\r
-7.     The upper layer entity handler returns success or failure with a response.\r
-8.     Returns   success or failure to lower layer for transmission to client.\r
-9.     Returns success or failure to lower layer for transmission to client.\r
-10.    Returns success or failure to lower layer for transmission to client.\r
-11.    Result is formatted and sent over network to client\r
-12.    The OCProcess() service function (client-side message pump) reads results and passes the results back to the client application via the callback passed to OCDoResource\r
-\r
-\r
-@section PUT__Client_CPP Set Resource's State [PUT] in C++ [Client]\r
-\r
-@code{.cpp}\r
-void putLightRepresentation(std::shared_ptr<OCResource> resource)\r
-{\r
-    if(resource)\r
-    {\r
-        OCRepresentation rep;\r
-\r
-        std::cout << "Putting light representation..."<<std::endl;\r
-        // Create AttributeMap\r
-        AttributeMap attributeMap;\r
-        // Add the attribute name and values in the attribute map\r
-        AttributeValues stateVal;\r
-        stateVal.push_back("true");\r
-\r
-        AttributeValues powerVal;\r
-        powerVal.push_back("10");\r
-\r
-        attributeMap["state"] = stateVal;\r
-        attributeMap["power"] = powerVal;\r
-\r
-        // Create QueryParameters Map and add query params (if any)\r
-        QueryParamsMap queryParamsMap;\r
-\r
-        rep.setAttributeMap(attributeMap);\r
-\r
-        // Invoke resource's put API with attribute map, query map and the callback parameter\r
-        resource->put(rep, queryParamsMap, &onPut);\r
-    }\r
-}\r
-\r
-// callback handler on PUT request\r
-void onPut(const OCRepresentation& rep, const int eCode)\r
-{\r
-    if(eCode == SUCCESS_RESPONSE)\r
-    {\r
-        std::cout << "PUT request was successful" << std::endl;\r
-\r
-        AttributeMap attributeMap = rep.getAttributeMap();\r
-\r
-        for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it)\r
-        {\r
-            std::cout << "\tAttribute name: "<< it->first << " value: ";\r
-            for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr)\r
-            {\r
-                std::cout <<"\t"<< *valueItr << " ";\r
-            }\r
-\r
-            std::cout << std::endl;\r
-        }\r
-\r
-        std::vector<OCRepresentation> children = rep.getChildren();\r
-\r
-        for(auto oit = children.begin(); oit != children.end(); ++oit)\r
-        {\r
-            attributeMap = oit->getAttributeMap();\r
-\r
-            for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it)\r
-            {\r
-                std::cout << "\tAttribute name: "<< it->first << " value: ";\r
-                for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr)\r
-                {\r
-                    std::cout <<"\t"<< *valueItr << " ";\r
-                }\r
-\r
-                std::cout << std::endl;\r
-            }\r
-        }\r
-\r
-    }\r
-    else\r
-    {\r
-        std::cout << "onPut Response error: " << eCode << std::endl;\r
-        std::exit(-1);\r
-    }\r
-}\r
-\r
-@endcode\r
-\r
-@section PUT_Server_CPP Set Resource's State [PUT] in C++ [Server]\r
-\r
-@code{.cpp}\r
-//Entity handle sample for PUT\r
-            if(requestType == "PUT")\r
-            {\r
-                cout << "\t\t\trequestType : PUT\n";\r
-\r
-                // Check for query params (if any)\r
-                QueryParamsMap queryParamsMap = request->getQueryParameters();\r
-\r
-                cout << "\t\t\tquery params: \n";\r
-                for(auto it = queryParamsMap.begin(); it != queryParamsMap.end(); it++)\r
-                {\r
-                    cout << "\t\t\t\t" << it->first << ":" << it->second << endl;\r
-                }\r
-\r
-                // Get the representation from the request\r
-                OCRepresentation rep = request->getResourceRepresentation();\r
-\r
-                myLightResource.setRepresentation(rep); // See code snippet below\r
-\r
-                // Do related operations related to PUT request // See code snippet below\r
-                rep = myLightResource.getRepresentation();\r
-\r
-                if(response)\r
-                {\r
-                    \r
-                    response->setErrorCode(200);\r
-\r
-                    auto findRes = queryParamsMap.find("if");\r
-\r
-                    if(findRes != queryParamsMap.end())\r
-                    {\r
-                        response->setResourceRepresentation(rep, findRes->second);\r
-                    }\r
-                    else\r
-                    {\r
-                        response->setResourceRepresentation(rep, DEFAULT_INTERFACE);\r
-                    }\r
-                }\r
-}\r
-\r
-    void setRepresentation(OCRepresentation& light)\r
-    {\r
-        AttributeMap attributeMap = light.getAttributeMap();\r
-\r
-        if(attributeMap.find("state") != attributeMap.end() && attributeMap.find("power") != attributeMap.end())\r
-        {\r
-            cout << "\t\t\t" << "Received representation: " << endl;\r
-            cout << "\t\t\t\t" << "power: " << attributeMap["power"][0] << endl;\r
-            cout << "\t\t\t\t" << "state: " << attributeMap["state"][0] << endl;\r
-\r
-            m_state = attributeMap["state"][0].compare("true") == 0;\r
-            m_power= std::stoi(attributeMap["power"][0]);\r
-        }\r
-    }\r
-\r
-    OCRepresentation getRepresentation()\r
-    {\r
-        OCRepresentation light;\r
-\r
-        light.setUri(m_lightUri);\r
-\r
-        std::vector<std::string> interfaces;\r
-        //interfaces.push_back(m_lightInterface);\r
-\r
-        light.setResourceInterfaces(interfaces);\r
-\r
-        std::vector<std::string> types;\r
-        //types.push_back(m_lightType);\r
-\r
-        light.setResourceTypes(types);\r
-\r
-        AttributeMap attributeMap;\r
-        AttributeValues stateVal;\r
-        if(m_state)\r
-        {\r
-            stateVal.push_back("true");\r
-        }\r
-        else\r
-        {\r
-            stateVal.push_back("false");\r
-        }\r
-\r
-        AttributeValues powerVal;\r
-        powerVal.push_back(to_string(m_power));\r
-\r
-        attributeMap["state"] = stateVal;\r
-        attributeMap["power"] = powerVal;\r
-\r
-        light.setAttributeMap(attributeMap);\r
-\r
-        return light;\r
-    }\r
-\r
-@endcode\r
-\r
-\r
-@section PUT_OTA_Response Over the air request\r
-\r
-In this example, we are pushing state to one of the lights. At this point, the resource was discovered by its type, and we understand its interface and the attributes exposed by the resource.\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-\r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Note(s)</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.13:5683</p></td>\r
-<td valign="top" ><p>Unicast packet</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>CON, PUT, MID=0x7d41</p></td>\r
-<td valign="top" ><p>Confirmation is requested</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>light</p></td>\r
-<td rowspan="2" valign="top" ><p>"/light/1"</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>1</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Content-Type</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Payload</p></td>\r
-<td valign="top" ><p>{</p>\r
-\r
-<p>"power" : 1,</p>\r
-\r
-<p>"level" : 5</p>\r
-\r
-<p>}</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-@section PUT_OTA_Response Over the air response(s)\r
-\r
-Assuming that the request is valid and the resource is able to complete the transition, the following represents a successful change in state.\r
-\r
-<b>From 192.168.1.13</b>:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-\r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.1:5683</p></td>\r
-<td valign="top" ><p>Client Address</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>ACK, CHANGED, MID=0x7d41</p></td>\r
-<td valign="top" ><p>Success (changed)</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-**********************************************************************\r
-\r
-@page Guide_GET Querying resource State [GET]\r
-\r
-This operation fetches the value of a simple resource. In this example, we fetch the state from the light resource.\r
-\r
-@section GET_SD Sequence Diagram\r
-@image HTML seq_get.png\r
-\r
-Steps:\r
-1.     The client application calls resource.get(...) to retrieve a representation from the resources.\r
-2.     The call is marshalled to the stack which is either running in-process or out-of-process (daemon).\r
-3.     The C API is called to dispatch the request. The call may look like the following:\r
-OCDoResource(OC_REST_GET, "//192.168.1.11/light/1, 0, 0, OC_CONFIRMABLE, callback); \r
-4.     Where CoAP is used as a transport, the lower stack will send a GET request to the target server.\r
-5.     On the server side, the OCProcess() function (message pump) receives and parses the request from the socket, then dispatches it to the correct entity handler based on the URI of the request.\r
-6.     Where the C++ API is used, the C++ entity handler parses the payload and marshals it to the client application depending on if the server stack is running in-process or out-of-process (daemon).\r
-7.     The C++ SDK passes it up the C++ handler associated with the OCResource.\r
-8.     The handler returns the result code and representation to the SDK.\r
-9.     The SDK marshals the result code and representation to the C++ entity handler.\r
-10.    The entity handler returns the result code and representation to the CoAP protocol.\r
-11.    The CoAP protocol transports the results to the client device.\r
-12.    The results are returned the OCDoResource callback.\r
-13.    The results are returned to the C++ client application's asyncResultCallback.\r
-\r
-@section GET_Client_CPP Querying resource State [GET] in C++ [Client]\r
-@code{.cpp}\r
-// Local function to get representation of light resource\r
-void getLightRepresentation(std::shared_ptr<OCResource> resource)\r
-{\r
-    if(resource)\r
-    {\r
-        std::cout << "Getting Light Representation..."<<std::endl;\r
-        // Invoke resource's get API with the callback parameter\r
-\r
-        QueryParamsMap test;\r
-        resource->get(test, &onGet);\r
-    }\r
-}\r
-\r
-// callback handler on GET request\r
-void onGet(const OCRepresentation& rep, const int eCode)\r
-{\r
-    if(eCode == SUCCESS_RESPONSE)\r
-    {\r
-        std::cout << "GET request was successful" << std::endl;\r
-\r
-        AttributeMap attributeMap = rep.getAttributeMap();\r
-\r
-        std::cout << "Resource URI: " << rep.getUri() << std::endl;\r
-\r
-        for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it)\r
-        {\r
-            std::cout << "\tAttribute name: "<< it->first << " value: ";\r
-            for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr)\r
-            {\r
-                std::cout <<"\t"<< *valueItr << " ";\r
-            }\r
-\r
-            std::cout << std::endl;\r
-        }\r
-\r
-        std::vector<OCRepresentation> children = rep.getChildren();\r
-\r
-        for(auto oit = children.begin(); oit != children.end(); ++oit)\r
-        {\r
-            std::cout << "Child Resource URI: " << oit->getUri() << std::endl;\r
-\r
-            attributeMap = oit->getAttributeMap();\r
-\r
-            for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it)\r
-            {\r
-                std::cout << "\tAttribute name: "<< it->first << " value: ";\r
-                for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr)\r
-                {\r
-                    std::cout <<"\t"<< *valueItr << " ";\r
-                }\r
-\r
-                std::cout << std::endl;\r
-            }\r
-        }\r
-\r
-        putLightRepresentation(curResource);\r
-    }\r
-    else\r
-    {\r
-        std::cout << "onGET Response error: " << eCode << std::endl;\r
-        std::exit(-1);\r
-    }\r
-}\r
-\r
-\r
-@endcode\r
-\r
-@section GET_Server_CPP Querying resource State [GET] in C++ [Server]\r
-@code{.cpp}\r
-\r
-// Handling GET request in Entity handler            \r
-if(requestType == "GET")\r
-            {\r
-                cout << "\t\t\trequestType : GET\n";\r
-\r
-                // Check for query params (if any)\r
-                QueryParamsMap queryParamsMap = request->getQueryParameters();\r
-\r
-                cout << "\t\t\tquery params: \n";\r
-                for(QueryParamsMap::iterator it = queryParamsMap.begin(); it != queryParamsMap.end(); it++)\r
-                {\r
-                    cout << "\t\t\t\t" << it->first << ":" << it->second << endl;\r
-                }\r
-\r
-                // Process query params and do required operations ..\r
-\r
-                // Get the representation of this resource at this point and send it as response\r
-                // AttributeMap attributeMap;\r
-                OCRepresentation rep;\r
-                rep = myLightResource.getRepresentation();\r
-\r
-                if(response)\r
-                {\r
-                    // TODO Error Code\r
-                    response->setErrorCode(200);\r
-\r
-                    auto findRes = queryParamsMap.find("if");\r
-\r
-                    if(findRes != queryParamsMap.end())\r
-                    {\r
-                        response->setResourceRepresentation(rep, findRes->second);\r
-                    }\r
-                    else\r
-                    {\r
-                        response->setResourceRepresentation(rep, DEFAULT_INTERFACE);\r
-                    }\r
-                }\r
-            }\r
-\r
-\r
-@endcode\r
-\r
-\r
-@section GET_OTA_Response Over the air request\r
-\r
-In this example, we are querying state from one of the lights. At this point, the resource was discovered by its type, and we understand its interface and the attributes that the resource exposes.\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Note(s)</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.11:5683</p></td>\r
-<td valign="top" ><p>Unicast packet</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>CON, GET, MID=0x7d42</p></td>\r
-<td valign="top" ><p>Confirmation is requested</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>light</p></td>\r
-<td rowspan="2" valign="top" ><p>"/light/1"</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>1</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Accept</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-@section GET_OTA_Response Over the air response(s)\r
-\r
-Assuming that the request is valid, we expect the following reply from the resource.\r
-\r
-<b>From 192.168.1.11</b>:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.1:5683</p></td>\r
-<td valign="top" ><p>Client Address</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>ACK, CONTENT, MID=0x7d42</p></td>\r
-<td valign="top" ><p>Success w/Content</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Content</p>\r
-\r
-<p>Type</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Payload</p></td>\r
-<td valign="top" ><p>{</p>\r
-\r
-<p>"power" : 0,</p>\r
-\r
-<p>"level" : 10</p>\r
-\r
-<p>}</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-\r
-**********************************************************************\r
-\r
-@page Guide_Observe Observing resource state [Observe]\r
-\r
-This operation fetches and registers as an observer for the value of a simple resource. In this example, we fetch the state of the light resource. For more implementation details, see "Observing Resources in CoAP" listed in the referenced documents. (https://datatracker.ietf.org/doc/draft-ietf-core-observe/?include_text=1)\r
-\r
-The handling of observation registration is application specific. It should not be assumed that a resource is observable, or a resource can handle any specific number of observers. If the server responds with a success (2.xx) code, the registration is considered successful.\r
-\r
-Notifications from the server to the client may be confirmable or non-confirmable. If the client returns a RST message, the observation registration should be dropped immediately. If the client fails to acknowledge a number of confirmable requests, the server should assume that the client has abandoned the observation and drop the registration.\r
-\r
-If the observed resource is removed, the server sends a NOTFOUND status to all observers.\r
-\r
-If an observed resource fails to notify a client before the max-age of a resource value update, the client should attempt to re-register the observation.\r
-\r
-\r
-@section Observe_SD Sequence Diagram\r
-@image HTML seq_observe.png\r
-\r
-Steps:\r
-1.     The client application calls resource.observe(...) to retrieve a representation from the resources.\r
-2.     The call is marshalled to the stack which is either running in-process or out-of-process (daemon).\r
-3.     The C API is called to dispatch the request. The call may look like this:\r
-OCDoResource(OC_REST_GET | OC_REST_OBSERVE, "//192.168.1.11/light/1, 0, 0, OC_CONFIRMABLE, callback);\r
-4.     Where CoAP is used as a transport, the lower stack will send a GET request to the target server. The primary difference between a GET request and an observe request is that the observe request contains an observe option indicating that, in addition to querying this resource, the client wishes to get notifications if/when the resource state changes.\r
-5.     On the server side, the OCProcess() function (message pump) receives and parses the request from the socket, then dispatches it to the correct entity handler based on the URI of the request. The request to the entity handler will indicate that the request is both a query and subscription request. The entity handler MAY take note of this, but it is not responsible to tracking the observers. The stack tracks the observers of record.\r
-6.     Where the C++ API is used the C++ entity handler parses the payload and marshals it to the client application depending on if the server stack is running in-process or out-of-process (daemon).\r
-7.     The C++ SDK passes it up the C++ handler associated with the OCResource.\r
-8.     The handler returns the result code and representation to the SDK.\r
-9.     The SDK marshals the result code and representation to the C++ entity handler.\r
-10.    The entity handler returns the result code and representation to the CoAP protocol.\r
-11.    The CoAP protocol transport the results to the client device.\r
-12.    The results are returned to the OCDoResource callback.\r
-13.    The results are returned to the C++ client application's asyncResultCallback.\r
-14.    If the entity handler has registered   observers, it will periodically be called with the observe flag set so that it may sample or poll underlying hardware to determine if the state has changes.\r
-15.    When the application has deemed that the resource state has changed either via polling (entity handler observe) or via external signal, the application should call OCNotifyObservers(). This tells the stack the observers need updating.\r
-16.    For each observer of a changed resource, the entity handler is called to generate a representation that is transmitted to the observing clients. \r
-17.    Where CoAP is used as a transport, a packet with content is sent to the devices that have observing clients. The packets may be confirmable or non-confirmable based on application needs.\r
-18.    The client-side OCProcess function (message pump) receives the message and matches it to the original request based on the CoAP token ID and dispatches the appropriate \r
-C API callback.\r
-19.    The C API callback passes the final results to the C++ client application's asyncResultCallback.\r
-20.    When the C++ client no longer desires to receive notifications from the server, it calls observation cancellation method cancelObserve(). \r
-21.    The C++ cancellation method calls the OCCancel() function from the C API.\r
-22.    OCCancel() finds the observation that is associated with the operation and sends an observe deregistration request to the server.\r
-\r
-\r
-@section Observe_Client_CPP Observing resource state [Observe] in C++ [Client]\r
-@code{.cpp}\r
-      if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)\r
-            std::cout << endl << "Observe is used." << endl << endl;\r
-        else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)\r
-            std::cout << endl << "ObserveAll is used." << endl << endl;\r
-\r
-        QueryParamsMap test;\r
-\r
-        curResource->observe(OBSERVE_TYPE_TO_USE, test, &onObserve);\r
-\r
-// callback\r
-void onObserve(const OCRepresentation& rep, const int& eCode, const int& sequenceNumber)\r
-{\r
-    if(eCode == SUCCESS_RESPONSE)\r
-    {\r
-        AttributeMap attributeMap = rep.getAttributeMap();\r
-\r
-        std::cout << "OBSERVE RESULT:"<<std::endl;\r
-        std::cout << "\tSequenceNumber: "<< sequenceNumber << endl;\r
-        for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it)\r
-        {\r
-            std::cout << "\tAttribute name: "<< it->first << " value: ";\r
-            for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr)\r
-            {\r
-                std::cout <<"\t"<< *valueItr << " ";\r
-            }\r
-\r
-            std::cout << std::endl;\r
-        }\r
-\r
-        if(observe_count() > 30)\r
-        {\r
-            std::cout<<"Cancelling Observe..."<<std::endl;\r
-            OCStackResult result = curResource->cancelObserve();\r
-\r
-            std::cout << "Cancel result: "<< result <<std::endl;\r
-            sleep(10);\r
-            std::cout << "DONE"<<std::endl;\r
-            std::exit(0);\r
-        }\r
-    }\r
-    else\r
-    {\r
-        std::cout << "onObserve Response error: " << eCode << std::endl;\r
-        std::exit(-1);\r
-    }\r
-}\r
-\r
-\r
-@endcode\r
-\r
-\r
-\r
-@section Observe_Server_CPP Observing resource state [Observe] in C++ [Server]\r
-@code{.cpp}\r
-// Handling observe in server's entity handler        \r
-if(requestFlag == RequestHandlerFlag::ObserverFlag)\r
-        {\r
-            pthread_t threadId;\r
-\r
-            cout << "\t\trequestFlag : Observer\n";\r
-            gObservation = 1;\r
-\r
-            static int startedThread = 0;\r
-\r
-            // Observation happens on a different thread in ChangeLightRepresentation function.\r
-            // If we have not created the thread already, we will create one here.\r
-            if(!startedThread)\r
-            {\r
-                pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);\r
-                startedThread = 1;\r
-            }\r
-\r
-// ChangeLightRepresentaion is an observation function,\r
-// which notifies any changes to the resource to stack\r
-// via notifyObservers\r
-void * ChangeLightRepresentation (void *param)\r
-{\r
-    // This function continuously monitors for the changes\r
-    while (1)\r
-    {\r
-        sleep (5);\r
-\r
-        if (gObservation)\r
-        {\r
-            // If under observation if there are any changes to the light resource\r
-            // we call notifyObservors\r
-            //\r
-            // For demostration we are changing the power value and notifying.\r
-            myLightResource.m_power += 10;\r
-\r
-            cout << "\nPower updated to : " << myLightResource.m_power << endl;\r
-            cout << "Notifying observers with resource handle: " << myLightResource.getHandle() << endl;\r
-\r
-            OCStackResult result = OCPlatform::notifyObservers(myLightResource.getHandle());\r
-\r
-            if(OC_STACK_NO_OBSERVERS == result)\r
-            {\r
-                cout << "No More observers, stopping notifications" << endl;\r
-                gObservation = 0;\r
-            }\r
-        }\r
-    }\r
-\r
-    return NULL;\r
-}\r
-\r
-\r
-@endcode\r
-\r
-\r
-\r
-\r
-@section Oberve_OTA_Response Over the air request\r
-\r
-The following observation request is basically a GET request with the observation option set.\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-<tr>\r
-<td valign="top" ><p>Fields</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Notes</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.11:5683</p></td>\r
-<td valign="top" ><p>Unicast packet</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>CON, GET, MID=0x7d44, TOK=0x3f</p></td>\r
-<td valign="top" ><p>Confirmation requested</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Observe</p></td>\r
-<td valign="top" ><p>Register (0)</p></td>\r
-<td valign="top" ><p>This indicates registration</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>Light</p></td>\r
-<td valign="top" ><p>"/light/1 "</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>URI-Path</p></td>\r
-<td valign="top" ><p>1</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Accept</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p>Requesting result in JSON</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-@section Observe_OTA_Response Over the air response(s)\r
-\r
-A successful observe request would be similar to the following:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.1:5683</p></td>\r
-<td valign="top" ><p>Client Address</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>ACK, CONTENT, MID=0x7d44, TOK=0x3f</p></td>\r
-<td valign="top" ><p>Success w/content</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Observe</p></td>\r
-<td valign="top" ><p>12</p></td>\r
-<td valign="top" ><p>Sequence number for ordering</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Max-Age</p></td>\r
-<td valign="top" ><p>30</p></td>\r
-<td valign="top" ><p>Indicates that the value is fresh for 30 seconds.</p>\r
-\r
-<p>It also indicates that the server should send an</p>\r
-\r
-<p>update within this time period.</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Content</p>\r
-\r
-<p>Type</p></td>\r
-<td valign="top" ><p>application/json</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Payload</p></td>\r
-<td valign="top" ><p>{</p>\r
-\r
-<p>"power" : 0,</p>\r
-\r
-<p>"level" : 10</p>\r
-\r
-<p>}</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-<b>Subsequent Notifications from 192.168.1.1 </b>\r
-\r
-If the light resource is being observed and the light transitions from an off state to an on state, a notification is sent to the client from the server. The following is an example of such a notification:\r
-\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.1:5683</p></td>\r
-<td valign="top" ><p>Client Address</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>CON, CONTENT, MID=0x7D45, TOK=0x3f</p></td>\r
-<td valign="top" ><p>Content, Can be confirmable or non-confirmable</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Observe</p></td>\r
-<td valign="top" ><p>15</p></td>\r
-<td valign="top" ><p>Monotonically increasing until overflow</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Max-Age</p></td>\r
-<td valign="top" ><p>30</p></td>\r
-<td valign="top" ><p>Indicates that the value is fresh for 30 seconds.</p>\r
-\r
-<p>It also indicates that the server should send an</p>\r
-\r
-<p>update within this time period.</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Payload</p></td>\r
-<td valign="top" ><p>{</p>\r
-\r
-<p>"power" : 1,</p>\r
-\r
-<p>"level" : 10</p>\r
-\r
-<p>}</p></td>\r
-<td valign="top" ><p><br />\r
-</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-Since the above notification was marked confirmable, the client should acknowledge the notification with a packet such as the following:\r
-\r
-<table cellspacing="0" cellpadding="0" border=1> \r
-\r
-<tr>\r
-<td valign="top" ><p>Field</p></td>\r
-<td valign="top" ><p>Value</p></td>\r
-<td valign="top" ><p>Explanation</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Address</p></td>\r
-<td valign="top" ><p>192.168.1.11:5683</p></td>\r
-<td valign="top" ><p>Unicast packet</p></td>\r
-</tr>\r
-\r
-<tr>\r
-<td valign="top" ><p>Header</p></td>\r
-<td valign="top" ><p>ACK, MID=0x7D45, TOK=0x3f</p></td>\r
-<td valign="top" ><p>Success</p></td>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-\r
-\r
-**********************************************************************\r
-\r
-\r
-*/\r
diff --git a/resource/docs/guides/ProgrammersGuide.txt b/resource/docs/guides/ProgrammersGuide.txt
deleted file mode 100644 (file)
index 78f7d46..0000000
+++ /dev/null
@@ -1,308 +0,0 @@
-/*!\r
-\r
-\r
-@page OCGuides Programmer's Guide\r
-\r
-\r
-This document covers the architecture and basic operations of the Iotivity Resource API stack, including sample coverage of protocol, flows, APIs and some use cases. It is intended to provide context for the developers using IoTivity APIs and provide a high level architectural overview.\r
-\r
-@section Stack_Blocks Stack Blocks\r
-\r
-The Resource API stack consists of several thin layers of software. In unconstrained environments such as Android*, iOS*, or Microsoft* Windows*, the stack provides APIs in C and C++ which allow developers to talk to both constrained and unconstrained devices via IP networks, with potential support for additional network protocols and wireless technologies. In the first release, the key technologies for connectivity include UDP/IP and the Constrained Application Protocol (CoAP).
-\r
-@image html stack_diagram.png\r
-\r
-@section Terminology Terminology\r
-\r
-<b>Device</b>\r
-A constrained device that has the Thin Block stack installed which enabled one or more services for other Thin Block or Unified Block devices to consume.\r
-\r
-<b>Resource</b>\r
-A resource is a component in a server that can be viewed and controlled by another Thin Block or Unified Block device. There are different resource types, for example a temperature sensor, a light controller etc.\r
-\r
-Resources can be arranged in a hierarchal manner to form a tree of resources. This generic method of structure enables one to model many different topologies of resources.\r
-\r
-@li Example: A light controller could be a resource.\r
-@li Example: A light array could be a set of resources organized in a flat (non-hierarchical) manner.\r
-@li Example: A garage door opener could be a resource; it could host two resources - light and lock.\r
-\r
-A more detailed description of resources and management of resources along with code snippets is provided later in this document.\r
-\r
-<b>Operations</b>\r
-Operations are actions that a Thin Block or Unified Block can perform on attributes associated with a particular resource. Resource attributes can have different operations on it based on the nature of the resource type. Fundamentally, these are GET and PUT operations. Additionally, attributes can also be declared to be observable to enable remote devices to subscribe to changes.\r
-\r
-@li Example: One of the child resources on the garage door opener is the light control; it has a GET operation that allows a device to get the current light state (on / off).\r
-\r
-@section Functionally Functionally\r
-\r
-The initial release of IoTivity includes functionally for:\r
- @li @ref Guide_Register_Resource "Resource registration"\r
- @li @ref Guide_Find_Resource "Resource discovery"\r
- @li Device discovery with filtering\r
- @li Property attributes (@ref Guide_GET "get"/ @ref Guide_PUT "set"/ @ref Guide_Observe "observe")\r
- @li Resource tree (resources having sub-resources)\r
- @li Presence notification service defined as a virtual resource (not detailed in this document)\r
-\r
-@section External_References External References \r
-\r
-The following references may provide guidance to this document.\r
- @note In some places, the IoTivity design may differ from the CoRE specifications. In these cases, please consider the CoRE specifications as informative but not definitive on the Iotivity design and architecture.\r
-\r
- @li The Constrained Application Protocol (CoAP) - https://datatracker.ietf.org/doc/rfc7252\r
- @li Constrained RESTful Environments (CoRE) Link Format - https://datatracker.ietf.org/doc/rfc6690\r
- @li Observing Resources in CoAP - https://datatracker.ietf.org/doc/draft-ietf-core-observe\r
- @li CoRE Interfaces (expired draft) - https://datatracker.ietf.org/doc/draft-ietf-core-interfaces\r
-\r
-@section Protocol Protocol Message Format(s)\r
-\r
-The OIC protocol (abbreviated to OC in code) is a REST-like interface similar to HTTP and CoAP. However, it is   a one level up abstraction of the those protocols to allow the addition of additional transports including Bluetooth Classic, Bluetooth Smart (BLE), Zigbee or others in the future. To that end, every attempt has been made to keep CoAP and HTTP specific aspects from being expressed directly in the OIC protocol. The following sections  describe how specific transports are used to support the OIC protocol and abstractions.\r
-\r
-@subsection Protocol_CoAP Constrained Application Protocol (CoAP)\r
-\r
-Constrained Application Protocol is one of the IoTivity supported transports. It is designed to be used in very simple devices and is particularly targeted for small, low power devices like sensors, switches, etc. The protocol is modeled after HTTP and provides easy translation between HTTP and CoAP. It is UDP-based (instead of TCP), providing support for multicast.\r
-\r
-CoAP is now a standard (RFC7252) as defined by the Internet Engineering Task Force (IETF) Constrained RESTful environments (CoRE) Working Group. Additional RFCs and drafts cover higher order behaviors.\r
-\r
-<b>Message format</b>\r
-The following table contains a brief overview of the contents of a CoAP packet. Use it as a cheat sheet for the following discussion. For details on the Constrain Resource Protocol, see http://datatracker.ietf.org/doc/rfc7252/?include_text=1.\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<th valign="top" ><p>Field</p></th>\r
-<th valign="top" ><p>Value</p></th>\r
-<th valign="top" ><p>Short</p>\r
-\r
-<p>Hand</p></th>\r
-<th valign="top" ><p>Notes</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Address</p></th>\r
-<th valign="top" ><p>&lt;Device IPD&gt;:&lt;port&gt;</p>\r
-\r
-<p>224.0.1.187:5683</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p>Device IP address and port multicast group IP address and port</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Version</p></th>\r
-<th valign="top" ><p>Version 1 (01b)</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p>Constant</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Type</p></th>\r
-<th valign="top" ><p>Confirmable (00b)</p>\r
-\r
-<p>Non-confirmable (01b)</p>\r
-\r
-<p>Acknowledgement (10b)</p>\r
-\r
-<p>Reset (11b)</p></th>\r
-<th valign="top" ><p>CON</p>\r
-\r
-<p>NON</p>\r
-\r
-<p>ACK</p>\r
-\r
-<p>RST</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Token</p>\r
-\r
-<p>Length</p></th>\r
-<th valign="top" ><p>Xxxxb</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p>Length of the token. Valid values are between 0 and 8.</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Code</p></th>\r
-<th valign="top" ><p>Request (0.xx)</p>\r
-\r
-<p>Success (2.xx)</p>\r
-\r
-<p>Client error (4.xx)</p>\r
-\r
-<p>Server error (5.xx)</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p>Common requests and responses:</p>\r
-\r
-<p>GET (0.01)</p>\r
-\r
-<p>CREATED (2.01)</p>\r
-\r
-<p>CHANGED (2.04)</p>\r
-\r
-<p>CONTENT (2.05)</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Message</p>\r
-\r
-<p>ID</p></th>\r
-<th valign="top" ><p>0xXXXX</p></th>\r
-<th valign="top" ><p>MID</p></th>\r
-<th valign="top" ><p>Generated by sender</p>\r
-\r
-<p>Allows receiver to de-duplicate requests</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Token</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p>TOK</p></th>\r
-<th valign="top" ><p>Generated by client to match REQ to RESP</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Options</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p>*</p></th>\r
-<th valign="top" ><p>Contains the URI path and query, request and response headers</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Payload</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-<th valign="top" ><p><br />\r
-</p></th>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-<b>Short-hand notation</b>\r
-\r
-The following two tables provide examples of request and response packets with explanations on the meaning of the short-hand notation used through the description of the queries and replies.\r
-\r
-@note Acknowledgements can come back separate from content. For the purposes of understanding the semantics of the query and responses, we will assume that all responses come back immediately. In production, requests can be acknowledged and the contents sent back at a later time. In addition, retry logic, de-duplication, congestion control and other features of the CoAP protocol libraries are neglected here.\r
-\r
-<b>Request example</b>\r
-\r
-In this example, the request is to the CoRE "core" resource in the well-known namespace. It provides a simple example of a multicast request to a compound URI with a query section.\r
-\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<th valign="top" ><p>Fields</p></th>\r
-<th valign="top" ><p>Sample Values</p></th>\r
-<th valign="top" ><p>Explanation</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Address</p></th>\r
-<th valign="top" ><p>224.0.1.187:5683</p></th>\r
-<th valign="top" ><p>Multicast packet address</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Header</p></th>\r
-<th valign="top" ><p>NON, GET, MID=0x7D40</p></th>\r
-<th valign="top" ><p>Non-confirmable</p>\r
-\r
-<p>GET (code=0.01)</p>\r
-\r
-<p>Message ID = 0x7D40</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Token</p></th>\r
-<th valign="top" ><p>0x75, 0x55</p></th>\r
-<th valign="top" ><p>Token Length = s</p>\r
-\r
-<p>Token = 0x75, 0x55</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>URI-Path</p></th>\r
-<th valign="top" ><p>oc</p></th>\r
-<th rowspan="4" valign="top" ><p>"/oc/core?rt=sensor&if=core.ll"</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>URI-Path</p></th>\r
-<th valign="top" ><p>core</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>URI-Query</p></th>\r
-<th valign="top" ><p>rt=sensor</p></th>\r
-<th valign="middle" ><p><br />\r
-</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>URI-Query</p></th>\r
-<th valign="top" ><p>if=core.ll</p></th>\r
-<th valign="middle" ><p><br />\r
-</p></th>\r
-</tr>\r
-\r
-</table>\r
-\r
-<b>Acknowledged response example</b>\r
-\r
-In this example, the response is returned.\r
-@note The payload in this example is for demonstration of the packet format and not a valid discovery response.\r
-\r
-<table cellspacing="0" cellpadding="0" border=1>\r
-\r
-<tr>\r
-<th valign="top" ><p>Fields</p></th>\r
-<th valign="top" ><p>Sample Values</p></th>\r
-<th valign="top" ><p>Explanation</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Address</p></th>\r
-<th valign="top" ><p>192.168.0.0:5683</p></th>\r
-<th valign="top" ><p>Unicast packet</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Header</p></th>\r
-<th valign="top" ><p>ACK, CONTENT, MID=0x7D40</p></th>\r
-<th valign="top" ><p>Non-confirmable</p>\r
-\r
-<p>Content (code=2.05)</p>\r
-\r
-<p>Message ID = 0x7D40</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Token</p></th>\r
-<th valign="top" ><p>0x75, 0x55</p></th>\r
-<th valign="top" ><p>Token Length = 2</p>\r
-\r
-<p>Token = 0x75, 0x55</p></th>\r
-</tr>\r
-\r
-<tr>\r
-<th valign="top" ><p>Payload</p></th>\r
-<th valign="top" ><p>"Sample Payload"</p></th>\r
-<th valign="top" ><p>Raw content</p></th>\r
-</tr>\r
-\r
-</table>\r
-\r
-\r
-\r
-\r
-*/\r
index f3a1e20..914a5ee 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
 ##
@@ -14,10 +34,8 @@ examples_env = lib_env.Clone()
 examples_env.AppendUnique(CPPPATH = [
                '../include/',
                '../csdk/stack/include',
-               '../csdk/ocsocket/include',
                '../csdk/ocrandom/include',
                '../csdk/logger/include',
-               '../csdk/libcoap',
                '../oc_logger/include'
                ])
 
@@ -31,11 +49,14 @@ if target_os not in ['windows', 'winrt']:
                examples_env.AppendUnique(LIBS = ['-lpthread'])
 
 examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'coap', 'oc_logger'])
+examples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
+if env.get('SECURED') == '1':
+    examples_env.AppendUnique(LIBS = ['tinydtls'])
 
 if target_os == 'android':
        examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       examples_env.AppendUnique(LIBS = ['gnustl_static'])
+       examples_env.AppendUnique(LIBS = ['gnustl_shared'])
 
        if not env.get('RELEASE'):
                examples_env.AppendUnique(LIBS = ['log'])
@@ -47,8 +68,8 @@ if target_os in ['darwin', 'ios']:
 # Source files and Targets
 ######################################################################
 simpleserver = examples_env.Program('simpleserver', 'simpleserver.cpp')
-simpleserverHQ = examples_env.Program('simpleserverHQ', 'simpleserverHQ.cpp')
 simpleclient = examples_env.Program('simpleclient', 'simpleclient.cpp')
+simpleserverHQ = examples_env.Program('simpleserverHQ', 'simpleserverHQ.cpp')
 simpleclientHQ = examples_env.Program('simpleclientHQ', 'simpleclientHQ.cpp')
 fridgeserver = examples_env.Program('fridgeserver', 'fridgeserver.cpp')
 fridgeclient = examples_env.Program('fridgeclient', 'fridgeclient.cpp')
@@ -59,15 +80,24 @@ roomserver = examples_env.Program('roomserver', 'roomserver.cpp')
 roomclient = examples_env.Program('roomclient', 'roomclient.cpp')
 garageserver = examples_env.Program('garageserver', 'garageserver.cpp')
 garageclient = examples_env.Program('garageclient', 'garageclient.cpp')
+groupserver = examples_env.Program('groupserver', 'groupserver.cpp')
+groupclient = examples_env.Program('groupclient', 'groupclient.cpp')
+lightserver = examples_env.Program('lightserver', 'lightserver.cpp')
 devicediscoveryserver = examples_env.Program('devicediscoveryserver', 'devicediscoveryserver.cpp')
 devicediscoveryclient = examples_env.Program('devicediscoveryclient', 'devicediscoveryclient.cpp')
+threadingsample = examples_env.Program('threadingsample', 'threadingsample.cpp')
 
-Alias("examples", [simpleserver, simpleserverHQ, simpleclient, simpleclientHQ,
-               fridgeserver, fridgeclient, presenceserver, presenceclient,
+Alias("examples", [simpleserver, simpleclient,
+               simpleserverHQ, simpleclientHQ,
+               fridgeserver, fridgeclient,
+               presenceserver, presenceclient,
                simpleclientserver, roomserver, roomclient, garageserver,
-               garageclient, devicediscoveryserver, devicediscoveryclient])
+               garageclient,
+               groupserver, groupclient,
+               lightserver,
+               devicediscoveryserver, devicediscoveryclient,
+               threadingsample
+     ])
 env.AppendTarget('examples')
 
-#ios doesn't allow run application from terminal, so won't build these examples
-if target_os != 'ios':
-       SConscript('ocicuc/SConscript')
+
index f08a8c7..90d22d8 100644 (file)
 using namespace OC;
 
 //Callback after device information is received
-void receivedDeviceInfo(const OCRepresentation& rep)
+void receivedPlatformInfo(const OCRepresentation& rep)
 {
-    std::cout << "\nDevice Information received ---->\n";
-
-    std::string contentType;
-    std::string dateOfManufacture;
-    std::string deviceName;
-    std::string deviceUUID;
-    std::string firmwareVersion;
-    std::string hostName;
-    std::string manufacturerName;
-    std::string manufacturerUrl;
-    std::string modelNumber;
-    std::string platformVersion;
-    std::string supportUrl;
-    std::string version;
-
-    if(rep.getValue("ct", contentType))
-    {
-        std::cout << "Content Type: " << contentType << std::endl;
-    }
-
-    if(rep.getValue("mndt", dateOfManufacture))
-    {
-        std::cout << "Date of manufacture: " << dateOfManufacture << std::endl;
-    }
-
-    if(rep.getValue("dn", deviceName))
-    {
-        std::cout << "Device Name: " << deviceName << std::endl;
-    }
-
-    if(rep.getValue("di", deviceUUID))
+    std::cout << "\nPlatform Information received ---->\n";
+    std::string value;
+    std::string values[22] =
     {
-        std::cout << "Device UUID: " << deviceUUID << std::endl;
-    }
+        "pi",   "Platform ID                    ",
+        "mnmn", "Manufacturer name              ",
+        "mnml", "Manufacturer url               ",
+        "mnmo", "Manufacturer Model No          ",
+        "mndt", "Manufactured Date              ",
+        "mnpv", "Manufacturer Platform Version  ",
+        "mnos", "Manufacturer OS version        ",
+        "mnhw", "Manufacturer hardware version  ",
+        "mnfv", "Manufacturer firmware version  ",
+        "mnsl", "Manufacturer support url       ",
+        "st",   "Manufacturer system time       "
+    };
 
-    if(rep.getValue("mnfv", firmwareVersion))
+    for (int i = 0; i < 22; i += 2)
     {
-        std::cout << "Firmware Version: " << firmwareVersion << std::endl;
+        if(rep.getValue(values[i], value))
+        {
+            std::cout << values[i + 1] << " : "<< value << std::endl;
+        }
     }
+}
 
-    if(rep.getValue("hn", hostName))
-    {
-        std::cout << "Host Name: " << hostName << std::endl;
-    }
+void receivedDeviceInfo(const OCRepresentation& rep)
+{
+    std::cout << "Implement me !" << std::endl;
+}
 
-    if(rep.getValue("mnmn", manufacturerName))
-    {
-        std::cout << "Manufacturer Name: " << manufacturerName << std::endl;
-    }
+int main(int argc, char* argv[]) {
 
-    if(rep.getValue("mnml", manufacturerUrl))
-    {
-        std::cout << "Manufacturer Url: " << manufacturerUrl << std::endl;
-    }
+    std::ostringstream platformDiscoveryRequest;
+    std::ostringstream deviceDiscoveryRequest;
 
-    if(rep.getValue("mnmo", modelNumber))
-    {
-        std::cout << "Model No. : " << modelNumber << std::endl;
-    }
+    std::string platformDiscoveryURI = "/oic/p";
+    std::string deviceDiscoveryURI   = "/oic/d";
 
-    if(rep.getValue("mnpv", platformVersion))
-    {
-        std::cout << "Platform Version: " << platformVersion << std::endl;
-    }
+    OCConnectivityType connectivityType = OC_IPV4;
 
-    if(rep.getValue("mnsl", supportUrl))
+    if(argc == 2)
     {
-        std::cout << "Support URL: " << supportUrl << std::endl;
+        try
+        {
+            std::size_t inputValLen;
+            int optionSelected = std::stoi(argv[1], &inputValLen);
+
+            if(inputValLen == strlen(argv[1]))
+            {
+                if(optionSelected == 0)
+                {
+                    connectivityType = OC_IPV4;
+                }
+                else if(optionSelected == 1)
+                {
+                    // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
+                    //connectivityType = OC_IPV6;
+                    connectivityType = OC_IPV4;
+                    std::cout << "IPv6 not currently supported. Using default IPv4" << std::endl;
+                }
+                else
+                {
+                    std::cout << "Invalid connectivity type selected. Using default IPv4"
+                    << std::endl;
+                }
+            }
+            else
+            {
+                std::cout << "Invalid connectivity type selected. Using default IPv4" << std::endl;
+            }
+        }
+        catch(std::exception&)
+        {
+            std::cout << "Invalid input argument. Using IPv4 as connectivity type" << std::endl;
+        }
     }
-
-    if(rep.getValue("icv", version))
+    else
     {
-        std::cout << "Version: " << version << std::endl;
+        std::cout << "Usage devicediscoveryclient <connectivityType(0|1)>" << std::endl;
+        std::cout << "connectivityType: Default IPv4" << std::endl;
+        std::cout << "connectivityType 0: IPv4" << std::endl;
+        std::cout << "connectivityType 1: IPv6 (not currently supported)" << std::endl;
     }
-}
-
-int main() {
-
     // Create PlatformConfig object
     PlatformConfig cfg {
         OC::ServiceType::InProc,
@@ -125,9 +131,42 @@ int main() {
     OCPlatform::Configure(cfg);
     try
     {
-        OCPlatform::getDeviceInfo("", "coap://224.0.1.187/oc/core/d", &receivedDeviceInfo);
-        std::cout<< "Querying for device information... " <<std::endl;
-
+        platformDiscoveryRequest << OC_MULTICAST_PREFIX << platformDiscoveryURI;
+        deviceDiscoveryRequest << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
+
+        OCStackResult ret;
+
+        std::cout<< "Querying for platform information... ";
+
+        ret = OCPlatform::getPlatformInfo("", platformDiscoveryRequest.str(), connectivityType,
+                &receivedPlatformInfo);
+
+        if (ret == OC_STACK_OK)
+        {
+            std::cout << "done." << std::endl;
+        }
+        else
+        {
+            std::cout << "failed." << std::endl;
+        }
+
+        bool is_oic_d_implemented = false;
+        if (is_oic_d_implemented)
+        {
+            std::cout<< "Querying for device information... ";
+
+            ret = OCPlatform::getDeviceInfo("", deviceDiscoveryRequest.str(), connectivityType,
+                    &receivedDeviceInfo);
+
+            if (ret == OC_STACK_OK)
+            {
+                std::cout << "done." << std::endl;
+            }
+            else
+            {
+                std::cout << "failed." << std::endl;
+            }
+        }
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
         // don't ever call cv.notify, this should be a non-processor intensive version
@@ -135,13 +174,14 @@ int main() {
         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)
     {
-        //log(e.what());
+        std::cerr << "Failure in main thread: "<<e.reason()<<std::endl;
     }
 
     return 0;
 }
 
+
index 9db7736..3c09140 100644 (file)
 using namespace OC;
 
 //Set of strings for each of deviceInfo fields
-std::string contentType = "myContentType";
 std::string dateOfManufacture = "myDateOfManufacture";
-std::string deviceName = "myDeviceName";
-std::string deviceUUID = "myDeviceUUID";
-std::string firmwareVersion = "myFirmwareVersion";
-std::string hostName = "myHostName";
-std::string manufacturerName = "myManufacturerNa";
-std::string manufacturerUrl = "myManufacturerUrl";
+std::string firmwareVersion = "my.Firmware.Version";
+std::string manufacturerName = "myName";
+std::string operatingSystemVersion = "myOS";
+std::string hardwareVersion = "myHardwareVersion";
+std::string platformID = "myPlatformID";
+std::string manufacturerUrl = "www.myurl.com";
 std::string modelNumber = "myModelNumber";
-std::string platformVersion = "myPlatformVersion";
-std::string supportUrl = "mySupportUrl";
-std::string version = "myVersion";
+std::string platformVersion = "platformVersion";
+std::string supportUrl = "www.mysupporturl.com";
+std::string systemTime = "mySystemTime";
 
-//OCDeviceInfo Contains all the device info to be stored
-OCDeviceInfo deviceInfo;
+//OCPlatformInfo Contains all the platform info to be stored
+OCPlatformInfo platformInfo;
 
-void DeleteDeviceInfo()
+void DeletePlatformInfo()
 {
-    delete[] deviceInfo.contentType;
-    delete[] deviceInfo.dateOfManufacture;
-    delete[] deviceInfo.deviceName;
-    delete[] deviceInfo.deviceUUID;
-    delete[] deviceInfo.firmwareVersion;
-    delete[] deviceInfo.hostName;
-    delete[] deviceInfo.manufacturerName;
-    delete[] deviceInfo.manufacturerUrl;
-    delete[] deviceInfo.modelNumber;
-    delete[] deviceInfo.platformVersion;
-    delete[] deviceInfo.supportUrl;
-    delete[] deviceInfo.version;
+    delete[] platformInfo.platformID;
+    delete[] platformInfo.manufacturerName;
+    delete[] platformInfo.manufacturerUrl;
+    delete[] platformInfo.modelNumber;
+    delete[] platformInfo.dateOfManufacture;
+    delete[] platformInfo.platformVersion;
+    delete[] platformInfo.operatingSystemVersion;
+    delete[] platformInfo.hardwareVersion;
+    delete[] platformInfo.firmwareVersion;
+    delete[] platformInfo.supportUrl;
+    delete[] platformInfo.systemTime;
 }
 
 void DuplicateString(char ** targetString, std::string sourceString)
@@ -71,44 +69,22 @@ void DuplicateString(char ** targetString, std::string sourceString)
     strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
 }
 
-OCStackResult SetDeviceInfo(std::string contentType, std::string dateOfManufacture,
-                std::string deviceName, std::string deviceUUID, std::string firmwareVersion,
-                std::string hostName, std::string manufacturerName, std::string manufacturerUrl,
-                std::string modelNumber, std::string platformVersion, std::string supportUrl,
-                std::string version)
+OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
+    std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
+    std::string platformVersion, std::string operatingSystemVersion, std::string hardwareVersion,
+    std::string firmwareVersion, std::string supportUrl, std::string systemTime)
 {
-    if(manufacturerName.length() > MAX_MANUFACTURER_NAME_LENGTH)
-    {
-        return OC_STACK_INVALID_PARAM;
-
-    }
-
-    if(manufacturerUrl.length() > MAX_MANUFACTURER_URL_LENGTH)
-    {
-        return OC_STACK_INVALID_PARAM;
-
-    }
-
-    try
-    {
-        DuplicateString(&deviceInfo.contentType, contentType);
-        DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture);
-        DuplicateString(&deviceInfo.deviceName, deviceName);
-        DuplicateString(&deviceInfo.deviceUUID, deviceUUID);
-        DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion);
-        DuplicateString(&deviceInfo.hostName, hostName);
-        DuplicateString(&deviceInfo.manufacturerName, manufacturerName);
-        DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl);
-        DuplicateString(&deviceInfo.modelNumber, modelNumber);
-        DuplicateString(&deviceInfo.platformVersion, platformVersion);
-        DuplicateString(&deviceInfo.supportUrl, supportUrl);
-        DuplicateString(&deviceInfo.version, version);
-    }catch(exception &e)
-    {
-        std::cout<<"String Copy failed!!\n";
-        return OC_STACK_ERROR;
-    }
-
+    DuplicateString(&platformInfo.platformID, platformID);
+    DuplicateString(&platformInfo.manufacturerName, manufacturerName);
+    DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
+    DuplicateString(&platformInfo.modelNumber, modelNumber);
+    DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
+    DuplicateString(&platformInfo.platformVersion, platformVersion);
+    DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
+    DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
+    DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
+    DuplicateString(&platformInfo.supportUrl, supportUrl);
+    DuplicateString(&platformInfo.systemTime, systemTime);
     return OC_STACK_OK;
 }
 
@@ -128,27 +104,27 @@ int main()
 
     OCPlatform::Configure(cfg);
 
-    std::cout<<"Starting server & setting device info\n";
+    std::cout<<"Starting server & setting platform info\n";
 
-    OCStackResult result = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
-            deviceUUID, firmwareVersion, hostName, manufacturerName, manufacturerUrl,
-            modelNumber, platformVersion, supportUrl, version);
+    OCStackResult result = SetPlatformInfo(platformID, manufacturerName, manufacturerUrl,
+            modelNumber, dateOfManufacture, platformVersion,  operatingSystemVersion,
+            hardwareVersion, firmwareVersion,  supportUrl, systemTime);
 
     if(result != OC_STACK_OK)
     {
-        std::cout << "Device Registration failed\n";
+        std::cout << "Platform Registration failed\n";
         return -1;
     }
 
-    result = OCPlatform::registerDeviceInfo(deviceInfo);
+    result = OCPlatform::registerPlatformInfo(platformInfo);
 
     if(result != OC_STACK_OK)
     {
-        std::cout << "Device Registration failed\n";
+        std::cout << "Platform Registration failed\n";
         return -1;
     }
 
-    DeleteDeviceInfo();
+    DeletePlatformInfo();
 
     // A condition variable will free the mutex it is given, then do a non-
     // intensive block until 'notify' is called on it.  In this case, since we
@@ -157,7 +133,7 @@ int main()
     std::mutex blocker;
     std::condition_variable cv;
     std::unique_lock<std::mutex> lock(blocker);
-    cv.wait(lock);
+    cv.wait(lock, []{return false;});
 
     // No explicit call to stop the platform.
     // When OCPlatform::destructor is invoked, internally we do platform cleanup
@@ -168,3 +144,4 @@ int main()
 
 
 
+
index a37c581..501ad75 100644 (file)
@@ -27,6 +27,7 @@
 #include <stdexcept>
 #include <condition_variable>
 #include <mutex>
+#include <atomic>
 #include "OCPlatform.h"
 #include "OCApi.h"
 
@@ -40,13 +41,15 @@ const uint16_t TOKEN = 3000;
 class ClientFridge
 {
     public:
-    ClientFridge()
+    ClientFridge(OCConnectivityType ct): m_callbackCount(0),
+        m_callsMade(0),m_connectivityType(ct)
     {
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=intel.fridge";
         std::cout << "Fridge Client has started " <<std::endl;
         FindCallback f (std::bind(&ClientFridge::foundDevice, this, PH::_1));
-
         OCStackResult result = OCPlatform::findResource(
-                "", "coap://224.0.1.187/oc/core?rt=intel.fridge", f);
+                "", requestURI.str(), OC_ALL, f);
 
         if(OC_STACK_OK != result)
         {
@@ -59,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;});
         }
     }
 
@@ -80,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", false, lightTypes, ifaces);
+                                "/light", m_connectivityType, false, lightTypes, ifaces);
 
         if(!light)
         {
@@ -89,9 +92,9 @@ class ClientFridge
         }
 
         std::vector<std::string> doorTypes = {"intel.fridge.door"};
-
         OCResource::Ptr leftdoor = constructResourceObject(resource->host(),
-                                "/door/left", false, doorTypes, ifaces);
+                                "/door/left", m_connectivityType, false, doorTypes, ifaces);
+
         if(!leftdoor)
         {
             std::cout << "Error: Left Door Resource Object construction returned null\n";
@@ -99,7 +102,8 @@ class ClientFridge
         }
 
         OCResource::Ptr rightdoor = constructResourceObject(resource->host(),
-                                "/door/right", false, doorTypes, ifaces);
+                                "/door/right", m_connectivityType, false, doorTypes, ifaces);
+
         if(!rightdoor)
         {
             std::cout << "Error: Right Door Resource Object construction returned null\n";
@@ -107,7 +111,7 @@ class ClientFridge
         }
 
         OCResource::Ptr randomdoor = constructResourceObject(resource->host(),
-                                "/door/random", false, doorTypes, ifaces);
+                                "/door/random", m_connectivityType, false, doorTypes, ifaces);
         if(!randomdoor)
         {
             std::cout << "Error: Random Door Resource Object construction returned null\n";
@@ -135,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)
@@ -211,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.
@@ -220,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
@@ -237,10 +260,58 @@ 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 main(int argc, char* argv[])
 {
+    OCConnectivityType connectivityType = OC_IPV4;
+    if(argc == 2)
+    {
+        try
+        {
+            std::size_t inputValLen;
+            int optionSelected = std::stoi(argv[1], &inputValLen);
+
+            if(inputValLen == strlen(argv[1]))
+            {
+                if(optionSelected == 0)
+                {
+                    connectivityType = OC_IPV4;
+                }
+                else if(optionSelected == 1)
+                {
+                    // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
+                    //connectivityType = OC_IPV6;
+                    connectivityType = OC_IPV4;
+                    std::cout << "IPv6 not currently supported. Using default IPv4" << std::endl;
+                }
+                else
+                {
+                    std::cout << "Invalid connectivity type selected. Using default IPv4"
+                        << std::endl;
+                }
+            }
+            else
+            {
+                std::cout << "Invalid connectivity type selected. Using default IPv4" << std::endl;
+            }
+        }
+        catch(std::exception&)
+        {
+            std::cout << "Invalid input argument. Using IPv4 as connectivity type" << std::endl;
+        }
+    }
+    else
+    {
+        std::cout << "Usage: fridgeclient <ConnectivityType(0|1)>\n";
+        std::cout << "connectivityType: Default IPv4" << std::endl;
+        std::cout << "connectivityType 0: IPv4" << std::endl;
+        std::cout << "connectivityType 1: IPv6 (not currently supported)" << std::endl;
+    }
+
     PlatformConfig cfg
     {
         ServiceType::InProc,
@@ -251,6 +322,7 @@ int main()
     };
 
     OCPlatform::Configure(cfg);
-    ClientFridge cf;
+    ClientFridge cf(connectivityType);
     return 0;
 }
+
index ae6eb32..45f626b 100644 (file)
@@ -57,7 +57,7 @@ class DeviceResource : public Resource
 {
     public:
 
-    DeviceResource()
+    DeviceResource():m_modelName{}
     {
         std::string resourceURI = "/device";
         std::string resourceTypeName = "intel.fridge";
@@ -254,7 +254,7 @@ class DeviceResource : public Resource
 class LightResource : public Resource
 {
     public:
-    LightResource()
+    LightResource() : m_isOn(false)
     {
         std::string resourceURI = "/light";
         std::string resourceTypeName = "intel.fridge.light";
@@ -345,7 +345,7 @@ class LightResource : public Resource
 class DoorResource : public Resource
 {
     public:
-    DoorResource(const std::string& side):m_side(side)
+    DoorResource(const std::string& side):m_isOpen{false}, m_side(side)
     {
 
         std::string resourceURI = "/door/"+ side;
@@ -479,3 +479,4 @@ int main ()
     std::this_thread::sleep_for(std::chrono::minutes(30));
     return 0;
 }
+
index ba8a09a..c64528d 100644 (file)
@@ -32,6 +32,7 @@ using namespace OC;
 
 const int SUCCESS_RESPONSE = 0;
 std::shared_ptr<OCResource> curResource;
+std::mutex curResourceLock;
 
 class Garage
 {
@@ -43,6 +44,7 @@ public:
     std::vector<int> m_lightPowers;
     OCRepresentation m_lightRep;
     std::vector<OCRepresentation> m_reps;
+    std::vector<std::vector<int>> m_hingeStates;
 
     Garage() : m_state(false), m_name("")
     {
@@ -57,7 +59,7 @@ void printRepresentation(const OCRepresentation& rep)
         // Check if attribute "name" exists, and then getValue
         if(rep.hasAttribute("name"))
         {
-            myGarage.m_name = rep.getValue<std::string>("name");
+            myGarage.m_name = rep["name"];
         }
         std::cout << "\tname: " << myGarage.m_name << std::endl;
 
@@ -92,10 +94,10 @@ void printRepresentation(const OCRepresentation& rep)
             std::cout << "\tnullAttribute is not null." << std::endl;
         }
 
-        rep.getValue("light", myGarage.m_lightRep);
+        myGarage.m_lightRep = rep["light"];
 
-        myGarage.m_lightRep.getValue("states", myGarage.m_lightStates);
-        myGarage.m_lightRep.getValue("powers", myGarage.m_lightPowers);
+        myGarage.m_lightStates = myGarage.m_lightRep["states"];
+        myGarage.m_lightPowers = myGarage.m_lightRep["powers"];
 
         std::cout << "\tlightRep: states: ";
 
@@ -131,13 +133,26 @@ void printRepresentation(const OCRepresentation& rep)
         std::cout << std::endl;
 
         // Get vector of representations
-        rep.getValue("reps", myGarage.m_reps);
-        // Client know that server is sending two representations
-        // and has key1 and key2 repsectively
-        std::cout << "\treps[0].key1: " << myGarage.m_reps[0].getValue<int>("key1") << std::endl;
-        std::cout << "\treps[0].key2: " << myGarage.m_reps[1].getValue<int>("key2") << std::endl;
+        myGarage.m_reps = rep["reps"];
+
+        int ct = 0;
+        for(auto& rep : myGarage.m_reps)
+        {
+            for(auto& attribute : rep)
+            {
+                std::cout<< "\treps["<<ct<<"]."<<attribute.attrname()<<":"
+                    << attribute.type()<<" with value " <<attribute.getValueToString() <<std::endl;
+            }
+            ++ct;
+        }
+
+        std::cout << "\tjson: " << rep["json"] << std::endl;
+        myGarage.m_hingeStates = rep["hinges"];
+
+        std::cout<< "\tHinge parameter is type: " << rep["hinges"].type() << " with depth "<<
+            rep["hinges"].depth() << " and a base type of "<< rep["hinges"].base_type()<<std::endl;
+
 
-        std::cout << "\tjson: " << rep.getValue<std::string>("json") << std::endl;
 }
 // callback handler on PUT request
 void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
@@ -166,7 +181,7 @@ void putLightRepresentation(std::shared_ptr<OCResource> resource)
 
         myGarage.m_state = true;
 
-        rep.setValue("state", myGarage.m_state);
+        rep["state"] = myGarage.m_state;
 
         // Create QueryParameters Map and add query params (if any)
         QueryParamsMap queryParamsMap;
@@ -211,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(curResourceLock);
     if(curResource)
     {
         std::cout << "Found another resource, ignoring"<<std::endl;
+        return;
     }
 
     std::string resourceURI;
@@ -263,12 +280,14 @@ void foundResource(std::shared_ptr<OCResource> resource)
     }
     catch(std::exception& e)
     {
-        //log(e.what());
+        std::cerr << "Exception in foundResource: "<< e.what()<<std::endl;
     }
 }
 
 int main(int argc, char* argv[]) {
 
+    std::ostringstream requestURI;
+
     // Create PlatformConfig object
     PlatformConfig cfg {
         OC::ServiceType::InProc,
@@ -282,8 +301,11 @@ int main(int argc, char* argv[]) {
     try
     {
         // Find all resources
-        OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.garage",
-                    &foundResource);
+        requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.garage";
+
+        OCPlatform::findResource("", requestURI.str(),
+                OC_ALL, &foundResource);
+
         std::cout<< "Finding Resource... " <<std::endl;
 
         // A condition variable will free the mutex it is given, then do a non-
@@ -303,3 +325,4 @@ int main(int argc, char* argv[]) {
     return 0;
 }
 
+
index e2a57d8..fd839fc 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:
@@ -53,25 +52,22 @@ public:
     // array of lights representation with in GarageResource
     OCRepresentation m_lightRep;
     std::vector<OCRepresentation> m_reps;
+    std::vector<std::vector<int>> m_hingeStates;
 
 public:
     /// Constructor
-    GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage") {
+    GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage"),
+        m_hingeStates{{1,2,3},{4,5,6}}
+    {
         // Initialize representation
         m_garageRep.setUri(m_garageUri);
 
-        m_garageRep.setValue("state", m_state);
-        m_garageRep.setValue("name", m_name);
+        m_garageRep["state"] = m_state;
+        m_garageRep["name"] = m_name;
 
         // For demonstration purpose we are setting x to nullptr here.
         // In reality it may happen else where.
-        int* x = nullptr;
-
-        // Check for nullptr and set null for that attribute
-        if(x == nullptr)
-        {
-            m_garageRep.setNULL("nullAttribute");
-        }
+        m_garageRep["nullAttribute"] = nullptr;
 
         std::vector<bool> lightStates;
         std::vector<int>  lightPowers;
@@ -82,30 +78,32 @@ public:
             lightPowers.push_back(i);
         }
 
-        m_lightRep.setValue("states", lightStates);
-        m_lightRep.setValue("powers", lightPowers);
+        m_lightRep["states"] = lightStates;
+        m_lightRep["powers"] = lightPowers;
 
         // Storing another representation within a representation
-        m_garageRep.setValue("light", m_lightRep);
+        m_garageRep["light"] = m_lightRep;
 
         OCRepresentation rep1;
         int value1 = 5;
-        rep1.setValue("key1", value1);
+        rep1["key1"] = value1;
         OCRepresentation rep2;
         int value2 = 10;
-        rep2.setValue("key2", value2);
+        rep2["key2"] = value2;
 
         m_reps.push_back(rep1);
         m_reps.push_back(rep2);
 
         // storing array of representations
-        m_garageRep.setValue("reps", m_reps);
+        m_garageRep["reps"] =  m_reps;
 
 
         // setting json string
         std::string json = "{\"num\":10,\"rno\":23.5,\"aoa\":[[1,2],[3]],\"str\":\"john\",\
 \"object\":{\"bl1\":false,\"ar\":[2,3]}, \"objects\":[{\"bl2\":true,\"nl\":null},{\"ar1\":[1,2]}]}";
-        m_garageRep.setValue("json", json);
+        m_garageRep["json"] = json;
+
+        m_garageRep["hinges"] = m_hingeStates;
     }
 
     /* Note that this does not need to be a member function: for classes you do not have
@@ -164,7 +162,7 @@ public:
     // sending out.
     OCRepresentation get()
     {
-        m_garageRep.setValue("state", m_state);
+        m_garageRep["state"] = m_state;
 
         return m_garageRep;
     }
@@ -197,12 +195,6 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
         if(requestFlag & RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
@@ -277,7 +269,7 @@ int main(int argc, char* argv[1])
     }
     catch(OCException e)
     {
-        //log(e.what());
+        oclog() << e.what();
     }
 
     // No explicit call to stop the OCPlatform
@@ -285,3 +277,4 @@ int main(int argc, char* argv[1])
 
     return 0;
 }
+
old mode 100755 (executable)
new mode 100644 (file)
index 11afb80..89c5a61
 
 #include "OCPlatform.h"
 #include "OCApi.h"
+#include "logger.h"
 
 #include <functional>
 #include <pthread.h>
+#include <mutex>
+#include <condition_variable>
 #include <iostream>
+#include <mutex>
+
+#define DO_ACTION               "DoAction"
+#define GET_ACTIONSET           "GetActionSet"
+#define ACTIONSET               "ActionSet"
+#define DELETE_ACTIONSET        "DelActionSet"
 
 using namespace std;
 using namespace OC;
 namespace PH = std::placeholders;
+std::mutex resourceLock;
 
 OCResourceHandle resourceHandle;
-
 shared_ptr< OCResource > g_resource;
 vector< string > lights;
+std::mutex blocker;
+std::condition_variable cv;
 
 bool isReady = false;
 
@@ -44,6 +55,13 @@ void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, con
 
 void foundResource(std::shared_ptr< OCResource > resource)
 {
+    std::lock_guard<std::mutex> lock(resourceLock);
+    if(g_resource)
+    {
+        std::cout << "Found another resource, ignoring"<<std::endl;
+        return;
+    }
+
     std::string resourceURI;
     std::string hostAddress;
 
@@ -55,18 +73,18 @@ void foundResource(std::shared_ptr< OCResource > resource)
         {
             string resourceURI = resource->uri();
             cout << resourceURI << endl;
+            cout << "HOST :: " << resource->host() << endl;
             if (resourceURI == "/core/a/collection")
             {
                 g_resource = resource;
+                resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), onGet);
             }
-
-            g_resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), onGet);
             printf("HOST :: %s\n", resource->host().c_str());
         }
     }
     catch (std::exception& e)
     {
-        std::cout << "" << std::endl;
+        std::cerr << "Exception in foundResource: "<< e.what() << std::endl;
     }
 }
 
@@ -84,6 +102,7 @@ void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCod
     }
 
     isReady = true;
+    cv.notify_one();
 }
 
 void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
@@ -121,8 +140,39 @@ void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, con
     }
 }
 
-int main()
+string buildActionSetDesc(unsigned int delay = 0, unsigned int type = 0)
+{
+    string actionsetDesc = "";
+    actionsetDesc = "allbulboff";
+    actionsetDesc.append("*");
+    actionsetDesc.append(std::to_string(delay));        // Set delay time.
+    actionsetDesc.append(" ");
+    actionsetDesc.append(std::to_string(type));         // Set action type.
+    actionsetDesc.append("*");
+    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+    {
+        actionsetDesc.append("uri=").append((*iter));
+        actionsetDesc.append("|");
+        actionsetDesc.append("power=");
+        actionsetDesc.append("off");
+        if ((iter + 1) != lights.end())
+        {
+            actionsetDesc.append("*");
+        }
+    }
+    return actionsetDesc;
+}
+
+bool isResourceReady()
+{
+    return isReady;
+}
+
+int main(int argc, char* argv[])
 {
+    ostringstream requestURI;
+    requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=a.collection";
+
     PlatformConfig config
     { OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos };
 
@@ -133,102 +183,82 @@ int main()
         OCPlatform::Configure(config);
 
         string resourceTypeName = "a.collection";
-        OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=a.collection", &foundResource);
 
-        isReady = false;
+        OCPlatform::findResource("", requestURI.str(),
+                                 OC_ALL, &foundResource);
+
+        //Non-intensive block until foundResource callback is called by OCPlatform
+        //and onGet gets resource.
+        //isResourceReady takes care of spurious wake-up
+
+        std::unique_lock<std::mutex> lock(blocker);
+        cv.wait(lock, isResourceReady);
 
+        isReady = false;
         while (isRun)
         {
-            usleep(100);
-            while (isReady)
-            {
-                int n;
+            int selectedMenu;
 
-                cout << endl
-                        << "1 :: CREATE ACTIONSET 2 :: EXECUTE ACTION SET 3 :: GET ACTIONSET\n";
-                cout << "4 :: DELETE ACTIONSET 5 :: Quit\n";
+            cout << endl <<  "0 :: Quit 1 :: CREATE ACTIONSET 2 :: EXECUTE ACTION SET \n";
+            cout << "3 :: GET ACTIONSET 4 :: DELETE ACTIONSET \n" << endl;
 
-                cin >> n;
-                if (n == 1)
-                {
-                    string actionsetDesc;
-                    //"movieTime*uri=coap://10.251.44.228:49858/a/light|power=10*uri=coap://10.251.44.228:49858/a/light|power=10|";
+            cin >> selectedMenu;
+            OCRepresentation rep;
+            string actionsetDesc;
 
-                    actionsetDesc = "allbulboff";
-                    actionsetDesc.append("*");
-                    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+            switch(selectedMenu)
+            {
+                case 0:
+                    isRun = false;
+                    break;
+                case 1:
+                    actionsetDesc = buildActionSetDesc();
+                    if(!actionsetDesc.empty())
                     {
-                        actionsetDesc.append("uri=").append((*iter));
-                        actionsetDesc.append("|");
-                        actionsetDesc.append("power=");
-                        actionsetDesc.append("off");
-                        if ((iter + 1) != lights.end())
-                        {
-                            actionsetDesc.append("*");
-                        }
+                        cout << "ActionSet :: " << actionsetDesc << endl;
+                        rep.setValue("ActionSet", actionsetDesc);
                     }
-
-                    cout << "ActionSet :: " << actionsetDesc << endl;
-
-                    OCRepresentation rep;
-                    rep.setValue("ActionSet", actionsetDesc);
-
                     if (g_resource)
                     {
                         g_resource->put("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
-                                &onPut);
+                        &onPut);
                     }
-                }
-                else if (n == 2)
-                {
-                    OCRepresentation rep;
-
-                    rep.setValue("DoAction", std::string("allbulboff"));
-
+                    break;
+                case 2:
+                    rep.setValue(DO_ACTION, std::string("allbulboff"));
                     if (g_resource)
                     {
                         g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
-                                &onPost);
-                    }
-                }
-                else if (n == 3)
-                {
-                    OCRepresentation rep;
-
-                    rep.setValue("GetActionSet", std::string("allbulboff"));
-
+                                         &onPost);
+                     }
+                     break;
+                case 3:
+                    rep.setValue(GET_ACTIONSET, std::string("allbulboff"));
                     if (g_resource)
                     {
                         g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
                                 &onPost);
                     }
-                }
-                else if (n == 4)
-                {
-                    OCRepresentation rep;
-
+                    break;
+                case 4:
                     rep.setValue("DelActionSet", std::string("allbulboff"));
-
                     if (g_resource)
                     {
                         g_resource->put("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
                                 &onPut);
                     }
-                }
-                else if (n == 5)
-                {
-                    isRun = false;
                     break;
-                }
-
-                fflush(stdin);
+                default:
+                    cout << "Invalid option" << endl;
+                    break;
             }
+            fflush(stdin);
         }
     }
     catch (OCException& e)
     {
         cout << e.what() << endl;
     }
-
     return 0;
 }
+
old mode 100755 (executable)
new mode 100644 (file)
index 4cebd44..c4b069d
@@ -67,20 +67,19 @@ void foundResource(std::shared_ptr< OCResource > resource)
                     cout << "\tresource Error!" << endl;
                 }
             }
-
-            // p_platform.bindResource(resourceHandle, foundResourceHandle);
-
         }
     }
     catch (std::exception& e)
     {
-        std::cout << "" << std::endl;
+        std::cout << "Exception in foundResource:"<< e.what() << std::endl;
     }
 
 }
 
-int main()
+int main(int argc, char* argv[])
 {
+    ostringstream requestURI;
+
     PlatformConfig config
     { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
 
@@ -101,29 +100,44 @@ int main()
 
         cout << "registerResource is called." << endl;
 
-        OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResource);
+        requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
+
+        OCPlatform::findResource("", requestURI.str(),
+                                 OC_ALL, &foundResource);
+
         OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE);
         OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE);
 
         int selectedMenu;
-        while (true)
+        bool isRun = true;
+        while (isRun)
         {
+            cout << endl << "0 :: Quit 1 :: UNREGISTER RESOURCES\n" << endl;
             std::cin >> selectedMenu;
 
-            if (selectedMenu == 1)
+            switch(selectedMenu)
             {
+            case 0:
+                isRun = false;
+                break;
+            case 1:
+                std::cout << "Unregistering resources" << std::endl;
                 for (unsigned int i = 0; i < resourceHandleVector.size(); ++i)
                 {
                     OCPlatform::unregisterResource(resourceHandleVector.at(i));
                 }
+                break;
+            default:
+                cout << "Invalid option" << endl;
             }
 
         }
     }
     catch (OCException& e)
     {
-
+        oclog() << "Exception in main: "<< e.what();
     }
 
     return 0;
 }
+
old mode 100755 (executable)
new mode 100644 (file)
index f95722d..6bddfbd
@@ -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
 {
@@ -176,12 +176,6 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
         if(requestFlag & RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
@@ -311,7 +305,7 @@ int main(int argc, char* argv[])
         myLight.createResource();
 
         myLight.addType(std::string("core.brightlight"));
-        myLight.addInterface(std::string("oc.mi.ll"));
+        myLight.addInterface(std::string(LINK_INTERFACE));
 
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
@@ -322,9 +316,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 +326,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
diff --git a/resource/examples/makefile b/resource/examples/makefile
deleted file mode 100755 (executable)
index ec87ec7..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=release`
-# default to release build+
-BUILD    := release
-PLATFORM  := linux
-CXX          := g++
-#CXX     := clang
-OUT_DIR          := $(BUILD)
-
-CXX_FLAGS.debug     := -O0 -g3 -std=c++0x -Wall -pthread
-
-CXX_FLAGS.release   := -O3 -std=c++0x -Wall -pthread
-
-CXX_INC          := -I../include/
-CXX_INC   += -I../oc_logger/include
-CXX_INC          += -I../csdk/stack/include
-CXX_INC          += -I../csdk/ocsocket/include
-CXX_INC          += -I../csdk/ocrandom/include
-CXX_INC          += -I../csdk/logger/include
-CXX_INC          += -I../csdk/libcoap
-
-LIB_OC_LOGGER := ../oc_logger/lib/oc_logger.a
-
-CXX_LIBS  := ../$(BUILD)/obj/liboc.a ../csdk/$(PLATFORM)/$(BUILD)/liboctbstack.a $(LIB_OC_LOGGER)
-
-# Force metatargets to build:
-all.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient ocicuc_target threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver
-
-apps.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver
-
-buildScript_all.PHONY: prep_dirs simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver
-
-all: all.PHONY
-
-apps: apps.PHONY
-
-buildScript_all: buildScript_all.PHONY
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-
-oc_cpp_sdk:
-       cd ../ && $(MAKE) cpp_sdk "BUILD=$(BUILD)"
-
-simpleserver: simpleserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-simpleserverHQ: simpleserverHQ.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleserverHQ.cpp $(CXX_INC) $(CXX_LIBS)
-
-simpleclientHQ: simpleclientHQ.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleclientHQ.cpp $(CXX_INC) $(CXX_LIBS)
-
-simpleclient: simpleclient.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleclient.cpp $(CXX_INC) $(CXX_LIBS)
-
-fridgeserver: fridgeserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ fridgeserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-fridgeclient: fridgeclient.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ fridgeclient.cpp $(CXX_INC) $(CXX_LIBS)
-
-presenceserver: presenceserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ presenceserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-presenceclient: presenceclient.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ presenceclient.cpp $(CXX_INC) $(CXX_LIBS)
-
-simpleclientserver: simpleclientserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleclientserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-roomserver: roomserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ roomserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-roomclient: roomclient.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ roomclient.cpp $(CXX_INC) $(CXX_LIBS)
-
-garageserver: garageserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ garageserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-garageclient: garageclient.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ garageclient.cpp $(CXX_INC) $(CXX_LIBS)
-
-threadingsample: threadingsample.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ threadingsample.cpp $(CXX_INC) $(CXX_LIBS)
-
-groupserver: groupserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ groupserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-groupclient: groupclient.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ groupclient.cpp $(CXX_INC) $(CXX_LIBS)
-
-lightserver: lightserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ lightserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-devicediscoveryserver: devicediscoveryserver.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ devicediscoveryserver.cpp $(CXX_INC) $(CXX_LIBS)
-
-devicediscoveryclient: devicediscoveryclient.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ devicediscoveryclient.cpp $(CXX_INC) $(CXX_LIBS)
-       
-       
-
-ocicuc_target:
-       cd ocicuc && $(MAKE) apps
-
-clean:
-       rm -rf debug
-       rm -rf release
-       cd ../ && $(MAKE) clean_cpp_sdk
-       cd ocicuc && $(MAKE) clean
-       cd ocicuc && $(MAKE) clean_apps
-
-clean_apps:
-       rm -rf debug
-       rm -rf release
-       cd ocicuc && $(MAKE) clean
-       cd ocicuc && $(MAKE) clean_apps
diff --git a/resource/examples/ocicuc/.gitignore b/resource/examples/ocicuc/.gitignore
deleted file mode 100644 (file)
index 3f5d712..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-# Ignore our example executables
-client
-monoprocess
-server
diff --git a/resource/examples/ocicuc/Makefile b/resource/examples/ocicuc/Makefile
deleted file mode 100644 (file)
index 17556f8..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-BUILD:=release
-PLATFORM:=linux
-
-OCLIB=../..
-OCLIB_LIB=../../$(BUILD)/obj/liboc.a
-
-BOOST_BASE=/usr/local/boost
-BOOST_INC=$(BOOST_BASE)/include
-BOOST_LIB=$(BOOST_BASE)/lib
-
-CXX_FLAGS.debug     := -g3 -O0
-CXX_FLAGS.release   := -O3
-
-CXX_FLAGS:=-Werror -Wall -std=c++0x -ggdb $(CXX_FLAGS.$(BUILD)) -pthread
-
-# There's probably nicer Makefile magic for this, but hopefully it will suffice:
-CXX_INC=-I$(OCLIB)/include \
-       -I$(BOOST_INC) \
-       -I../../include/ \
-       -I../../oc_logger/include/ \
-       -I../../csdk/stack/include \
-       -I../../csdk/ocsocket/include \
-       -I../../csdk/ocrandom/include \
-       -I../../csdk/logger/include \
-
-BOOST_LIBS=-lboost_program_options
-#BOOST_LIBS=-L/usr/local/boost/lib/ -lboost_program_options    # for boost libraries at the specified path
-
-LIB_OC_LOGGER:=../../oc_logger/lib/oc_logger.a
-
-CXX_LIBS=$(OCLIB_LIB) ../../csdk/$(PLATFORM)/$(BUILD)/liboctbstack.a $(LIB_OC_LOGGER) $(BOOST_LIBS)
-
-APPS += client
-APPS += server
-APPS += monoprocess
-APPS += small_example
-
-.PHONY: client server
-
-all: apps
-       @echo Remember to \"export LD_LIBRARY_PATH=$(BOOST_LIB)\:\$$LD_LIBRARY_PATH\"
-
-apps: $(APPS)
-
-%.o: %.cpp
-       $(CXX) $(CXXFLAGS) $(CXX_FLAGS) $(CXX_INC) -c -o $@ $<
-
-client: client.o driver.o utility.o
-       $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS)
-
-server: server.o driver.o utility.o light_resource.o
-       $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS)
-
-monoprocess: monoprocess.o driver.o utility.o light_resource.o
-       $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS)
-
-small_example: small_example.o driver.o utility.o
-       $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS)
-
-clean:
-       rm -f *.o $(APPS)
-
-clean_apps:
-       rm -f *.o $(APPS)
diff --git a/resource/examples/ocicuc/README b/resource/examples/ocicuc/README
deleted file mode 100644 (file)
index d0d99b7..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-
-OCICUC is a light framework for rapidly building OIC test/demo/example applications. It provides pre-built
-entry points and handling for things like command line parameters and modularlizes resources, so that
-adding new features or building a new test application is a lightweight undertaking.
-
-.
-├── client.cpp                           - a multi-resource client, similar to simpleclient
-├── demo_client.hpp                      - client code, shared between client and multiprocess programs
-├── driver.cpp                           - ocicuc base driver program
-├── exec.hpp                             - header for binding with the driver
-├── light_resource.cpp           - example resource
-├── light_resource.hpp           - example resource
-├── monoprocess.cpp                      - client and server in a single process
-├── server.cpp                           - a multi-resource server, similar to simpleserver
-├── small_example.cpp            - a near-minimal example program
-├── utility.cpp                          - utility functions for the demo programs
-└── utility.hpp                          - utility functions
-
-You can extend the existing programs to add new resource types, etc.. Refer to the help screen for each program
-for further details. For instance, to start a server with 5 resources and then test it with a separate client,
-you could run:
-
-       ./server --nres=5
-
-...and, in another shell:
-
-       ./client --nres=5
-
-To build a new program that hooks into the ocicuc driver program, you just need to define the functions in "exec.hpp",
-for example:
-
-namespace Intel { namespace OCDemo {
-
-int exec(const boost::program_options::variables_map& vm);
-
-auto make_description()
-    -> boost::program_options::options_description;
-
-}} // namespace Intel::OCDemo
-
-You can see an example of a skeleton program in small_example.cpp.
-
-To run a program with default parameters, use "--", for example:
-
-./monoprocess --
-
-Have fun!
-
-
diff --git a/resource/examples/ocicuc/SConscript b/resource/examples/ocicuc/SConscript
deleted file mode 100644 (file)
index 434efd7..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-##
-# Examples build script
-##
-Import('env')
-# Add third party libraries
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
-
-ocicuc_env = lib_env.Clone()
-######################################################################
-# Build flags
-######################################################################
-ocicuc_env.AppendUnique(CPPPATH = [
-               '../../include/',
-               '../../csdk/stack/include',
-               '../../csdk/ocsocket/include',
-               '../../csdk/ocrandom/include',
-               '../../csdk/logger/include',
-               '../../oc_logger/include'
-               ])
-
-ocicuc_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-ocicuc_env.PrependUnique(LIBS = ['oc', 'octbstack', 'coap', 'oc_logger'])
-
-target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
-       ocicuc_env.AppendUnique(CXXFLAGS = ['-std=c++0x'])
-
-if target_os == 'android':
-       ocicuc_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       ocicuc_env.AppendUnique(LIBS = ['boost_program_options', 'boost_thread', 'gnustl_static'])
-
-       if not env.get('RELEASE'):
-               ocicuc_env.AppendUnique(LIBS = ['log'])
-
-if target_os == 'darwin':
-       ocicuc_env.AppendUnique(LIBS = ['boost_program_options'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-client = ocicuc_env.Program('client', ['client.cpp', 'driver.cpp', 'utility.cpp'])
-server = ocicuc_env.Program('server', ['server.cpp', 'driver.cpp', 'utility.cpp', 'light_resource.cpp'])
-monoprocess = ocicuc_env.Program('monoprocess', ['monoprocess.cpp', 'driver.cpp', 'utility.cpp', 'light_resource.cpp'])
-small_example = ocicuc_env.Program('small_example', ['small_example.cpp', 'driver.cpp', 'utility.cpp'])
-
-Alias("examples_ocicuc", [client, server, monoprocess, small_example])
-env.AppendTarget('examples_ocicuc')
diff --git a/resource/examples/ocicuc/client.cpp b/resource/examples/ocicuc/client.cpp
deleted file mode 100644 (file)
index c3771bb..0000000
+++ /dev/null
@@ -1,126 +0,0 @@
-//******************************************************************
-//
-// 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 contains the Boost MPL defines required for the boost_variant
-// serialization, so it must go before the boost/program_options
-#include "OCApi.h"
-
-#include <map>
-#include <string>
-#include <memory>
-#include <utility>
-#include <ostream>
-#include <sstream>
-#include <iostream>
-
-#include <boost/program_options.hpp>
-
-#include "OCResource.h"
-#include "OCPlatform.h"
-
-#include "exec.hpp"
-#include "utility.hpp"
-
-#include "demo_client.hpp"
-
-namespace Intel { namespace OCDemo {
-
-auto make_description()
-    -> boost::program_options::options_description
-{
- using std::string;
- using std::vector;
-
- namespace po = boost::program_options;
-
- po::options_description desc("Client options");
-
- desc.add_options()
-    ("nres",        po::value<unsigned long>()->default_value(1),           "number of resources to use for testing")
-    ("host_ip",     po::value<string>()->default_value("0.0.0.0"),   "IP of host")
-    ("host_port",   po::value<uint16_t>()->default_value(0),             "port of host")
-    ("interface",   po::value<string>()->default_value("eth0"),             "network interface name")
-    ("uri",         po::value<vector<string>>(),                            "remote resource URI")
-    ;
-
- return desc;
-}
-
-int exec(const boost::program_options::variables_map& vm)
-{
- using namespace std;
-
- OC::OCPlatform::Configure({
-                          OC::ServiceType::InProc,              // in-process server
-                          OC::ModeType::Client,                 // client mode
-                          vm["host_ip"].as<string>(),           // host
-                          vm["host_port"].as<uint16_t>(),       // port
-                          OC::QualityOfService::LowQos
-                        });
-
- vector<string> resource_URIs;
-
- if(0 == vm.count("uri"))
-  {
-    std::cout << "No URI specified, looking for everything in \"core\".\n";
-
-    // Find all resources:
-    resource_URIs.push_back("coap://224.0.1.187/oc/core");
-
-    /* Example of finding specific resources:
-    const auto& nprops = vm["nres"].as<unsigned long>();
-
-    for(unsigned long instance_number = 1;
-        instance_number <= nprops;
-        instance_number++)
-     {
-        ostringstream uri;
-
-
-        uri << "coap://" << vm["host_ip"].as<string>() << "/oc/core?rt=core.light" << '_' << instance_number;
-        resource_URIs.push_back(uri.str()); // ie. "coap://224.0.1.187/oc/core?rt=core.light_1");
-     }
-    */
-  }
- else
-  {
-    const vector<string>& input_URIs = vm["uri"].as< vector<string> >();
-    copy(begin(input_URIs), end(input_URIs), back_inserter(resource_URIs));
-  }
-
- std::cout << "Requesting " << resource_URIs.size() << " URIs:\n";
-
- for(const auto& resource_URI : resource_URIs)
-  cout << resource_URI << '\n';
-
- Intel::OCDemo::client::resource_handler resources(resource_URIs);
-
- // Register callbacks and wait for resources:
- resources.find_resources();
-
- // Allow the client to receive events from the server:
- for(;;)
-  ;
-
- return 0;
-}
-
-}} // namespace Intel::OCDemo
-
diff --git a/resource/examples/ocicuc/demo_client.hpp b/resource/examples/ocicuc/demo_client.hpp
deleted file mode 100644 (file)
index d5ce578..0000000
+++ /dev/null
@@ -1,234 +0,0 @@
-
-/* Example client program (this is not a library header, don't include it in random programs): */
-
-namespace Intel { namespace OCDemo { namespace client {
-
-// Although not "done" here, this could be expanded into an interface to handle any sort of
-// resource:
-class resource_handle
-{
- friend class resource_handler;
-
- private:
- const std::string                     URI;
- std::shared_ptr<OC::OCResource>       resource;
-
- public:
- resource_handle(const std::string& URI_, std::shared_ptr<OC::OCResource> resource_)
-  : URI(URI_),
-    resource(resource_)
- {}
-
- resource_handle(const std::string& URI_)
-  : URI(URI_)
- {}
-
- // Callbacks (note that the signature after binding will match exactly:
- private:
- void onFoundResource(std::shared_ptr<OC::OCResource> in_resource);
- void onResourceGet(const OC::HeaderOptions& headerOptions,
-                OC::OCRepresentation rep, const int error_code);
- void onResourcePut(const OC::HeaderOptions& headerOptions, const OC::OCRepresentation rep,
-                const int error_code);
- void onObserve(const OC::HeaderOptions& headerOptions, const OC::OCRepresentation rep,
-                const int error_code, const int& sequence_number);
-};
-
-class resource_handler
-{
-
- static std::vector<std::shared_ptr<resource_handle>> resources;    // URI -> Maybe resource
-
- public:
- resource_handler(const std::vector<std::string>& resource_URIs_);
- resource_handler();
-
- public:
- bool has(const std::string& URI)
- {
-    for(const auto& r : resources)
-     {
-      if(URI == r->URI)
-       return true;
-     }
-
-    return false;
- }
-
- void add(const std::string& URI)
- {
-    if(!has(URI))
-     resources.emplace_back(std::make_shared<resource_handle>(URI));
- }
-
- void find_resources()
- {
-        for(const auto& resource : resources)
-         {
-                std::cout << "* Finding resources \"" << resource->URI << "\".\n";
-
-                call_timer.mark("find_resources");
-
-                OC::OCPlatform::findResource("", resource->URI,
-                                      std::bind(&resource_handle::onFoundResource, resource, std::placeholders::_1));
-         }
- }
-};
-
-std::vector<std::shared_ptr<resource_handle>> resource_handler::resources;
-
-resource_handler::resource_handler(const std::vector<std::string>& resource_URIs)
-{
- for(const auto& URI : resource_URIs)
-  add(URI);
-}
-
-void resource_handle::onFoundResource(std::shared_ptr<OC::OCResource> in_resource)
-{
- using std::cout;
-
- cout << "* onFoundResource():\n";
-
- try
-  {
-       if(nullptr == in_resource)
-        throw OC::OCException("invalid resource passed to client callback");
-
-       call_timer.report_and_reset("find_resources");
-
-       // Now, fixup our own representation ptr:
-       resource = in_resource;
-
-       /* Note: You can combine the host and URI to get a unique identifier, for
-       example to filter out events you aren't interested in. Here, we just report the
-       data: */
-       cout << "resource URI: " << resource->uri() << "; "
-            << "host address: " << resource->host() << '\n';
-
-       call_timer.mark("get_resource");
-
-       OC::QueryParamsMap qpm;
-
-       resource->get(qpm, std::bind(&resource_handle::onResourceGet, this,
-            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
-  }
- catch(OC::OCException& e)
-  {
-        std::cerr << "onFoundResource(): exception " << e.reason() << ": " << e.what() << '\n';
-  }
- catch(std::exception& e)
-  {
-        std::cerr << "onFoundResource(): exception: " << e.what() << '\n';
-  }
-}
-
-void resource_handle::onResourceGet(const OC::HeaderOptions& headerOptions,
-                const OC::OCRepresentation rep, const int error_code)
-{
- using std::cout;
-
- cout << "onResourceGet():\n";
-
- call_timer.report_and_reset("get_resource");
-
- if(error_code)
-  {
-        std::cerr << "onResourceGet(): error: " << error_code << '\n';
-        return;
-  }
-
- if(nullptr == resource)
-  {
-        std::cerr << "onResourceGet(): empty resource pointer.\n";
-        return;
-  }
-
- std::cout << "input attributes:\n";
- std::cout << "Attribute \"" << "state" << "\": "<< rep.getValue<bool>("state")<<"; ";
- std::cout << "Attribute \"" << "power" << "\": "<< rep.getValue<int>("power")<<"; \n";
-
- // Now, make a change to the light representation (replacing, rather than parsing):
- bool state = true;
- int power = 10;
-
- std::cout << "output attributes:\n";
- std::cout << "Attribute \"" << "state" << "\": "<< state<<"; ";
- std::cout << "Attribute \"" << "power" << "\": "<< power<<"; \n";
-
- call_timer.mark("put_resource");
-
- OC::OCRepresentation out_rep;
- out_rep.setValue("state", state);
- out_rep.setValue("power", power);
-
- resource->put(out_rep, OC::QueryParamsMap(),
-               std::bind(&resource_handle::onResourcePut, this, std::placeholders::_1,
-               std::placeholders::_2, std::placeholders::_3));
-}
-
-void resource_handle::onResourcePut(const OC::HeaderOptions& headerOptions,
-            const OC::OCRepresentation rep, const int error_code)
-{
- std::cout << "onResourcePut():\n";
-
- call_timer.report_and_reset("put_resource");
-
- if(0 != error_code)
-  {
-        std::ostringstream os;
-
-        os << "onResourcePut(): error code " << error_code << " from server response.";
-
-        throw OC::OCException(os.str());
-  }
-
- std::cout << "input attributes:\n";
- std::cout << "Attribute \"" << "state" << "\": "<< rep.getValue<bool>("state")<<"; ";
- std::cout << "Attribute \"" << "power" << "\": "<< rep.getValue<int>("power")<<"; \n";
-
- call_timer.mark("observe_resource");
-
- // Start an observer:
- resource->observe(OC::ObserveType::Observe, OC::QueryParamsMap(),
-                std::bind(&resource_handle::onObserve, this,
-                std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
-                std::placeholders::_4));
-}
-
-void resource_handle::onObserve(const OC::HeaderOptions& headerOptions,
-            const OC::OCRepresentation rep, const int error_code, const int& sequence_number)
-{
- if(0 != error_code)
-  {
-    std::ostringstream os;
-    os << "onObserve(): error " << error_code << " from callback.\n";
-    throw OC::OCException(os.str());
-  }
-
- std::cout << "onObserve(): sequence number: " << sequence_number << ":\n";
-
- call_timer.report_and_reset("observe_resource");
-
- std::cout << "Attribute \"" << "state" << "\": "<< rep.getValue<bool>("state")<<"; ";
- std::cout << "Attribute \"" << "power" << "\": "<< rep.getValue<int>("power")<<"; \n";
-
- const auto oc = observe_count();
-
- std::cout << "onObserve(): observation count is: " << oc << '\n';
-
- // We don't want to be observed forever for purposes of this demo:
- if(10 <= oc)
-  {
-    std::cout << "onObserve(): cancelling observation.\n";
-
-    const auto result = resource->cancelObserve();
-
-    std::cout << "onObserve(): result of cancellation: " << result << ".\n";
-
-    this_thread::sleep_for(chrono::seconds(10));
-  }
-}
-
-}}} // namespace Intel::OCDemo::client
-
-
diff --git a/resource/examples/ocicuc/driver.cpp b/resource/examples/ocicuc/driver.cpp
deleted file mode 100644 (file)
index 9d7edb5..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-
-#include <iostream>
-
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <boost/program_options.hpp>
-
-#include "exec.hpp"
-
-namespace Intel { namespace OCDemo {
-
-auto parse_options(boost::program_options::options_description& desc, int argc, char *argv[]) 
-    -> boost::program_options::variables_map 
-{
- namespace po = boost::program_options;
-
- po::positional_options_description popts;
- popts.add("uri", -1);
-
- po::variables_map vm;
-
- po::store(po::command_line_parser(argc,argv).options(desc).positional(popts).run(), 
-           vm);
-
- po::notify(vm);
-
- return vm;
-}
-
-}} // namespace Intel::OCDemo
-
-int main(int argc, char *argv[])
-try
-{
- using namespace std;
- auto desc = Intel::OCDemo::make_description();
- auto vm   = Intel::OCDemo::parse_options(desc, argc, argv);
-
- if(1 == argc || vm.count("help"))
-  {
-    std::cerr << desc << '\n';
-    return 1;
-  }
-
- return Intel::OCDemo::exec(vm);
-}
-catch(std::exception& e)
-{
- std::cerr << "Unhandled exception: " << e.what() << '\n';
- return 1;
-}
-catch(...)
-{
- std::cerr << "Unhandled exception.\n";
- return 1;
-}
diff --git a/resource/examples/ocicuc/exec.hpp b/resource/examples/ocicuc/exec.hpp
deleted file mode 100644 (file)
index f1ff62a..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef __EXEC_HPP
- #define __EXEC_HPP 1
-
-#include <boost/program_options.hpp>
-
-/* Interface point for the driver code. Your program needs to implement these
-functions: */
-namespace Intel { namespace OCDemo {
-
-int exec(const boost::program_options::variables_map& vm);
-
-auto make_description()
-    -> boost::program_options::options_description;
-
-}} // namespace Intel::OCDemo
-
-#endif
diff --git a/resource/examples/ocicuc/light_resource.cpp b/resource/examples/ocicuc/light_resource.cpp
deleted file mode 100644 (file)
index 6586ac6..0000000
+++ /dev/null
@@ -1,211 +0,0 @@
-#include "light_resource.hpp"
-
-namespace Intel { namespace OCDemo {
-
-std::atomic<bool> LightResource::shutdown_flag(false);
-std::thread LightResource::observe_thread;
-
-void LightResource::setRepresentation(const OCRepresentation& rep)
-{
- cout << "\t\t\t" << "Received representation: " << endl;
-
- rep.getValue("state", m_state);
- rep.getValue("power", m_power);
-
- cout << "\t\t\t\t" << "power: " << m_power << endl;
- cout << "\t\t\t\t" << "state: " << m_state << endl;
-}
-
-OCRepresentation LightResource::getRepresentation(void)
-{
- m_rep.setValue("state", m_state);
- m_rep.setValue("power", m_power);
- return m_rep;
-}
-
-void LightResource::addType(const std::string& type) const
-{
- OCStackResult result = OC::OCPlatform::bindTypeToResource(m_resourceHandle, type);
-
- if(OC_STACK_OK != result)
-  cout << "Binding TypeName to Resource was unsuccessful, result was " << result << '\n';
-}
-
-void LightResource::addInterface(const std::string& interface) const
-{
- OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
-
- if(OC_STACK_OK != result)
-  cout << "Binding TypeName to Resource was unsuccessful, result was " << result << '\n';
-}
-
-void LightResource::createResource(const unsigned int resource_number)
-{
- string resourceURI      { make_URI(resource_number) };
- string resourceTypeName { "core.light" };
-
- cout << "registering resource: " << resourceURI << '\n';
- cout << "registering type name \"" << resourceTypeName << "\".\n";
- // This will internally create and register the resource, binding the current instance's method as a callback:
- OCStackResult result = OC::OCPlatform::registerResource(
-                                            m_resourceHandle, resourceURI, resourceTypeName,
-                                            DEFAULT_INTERFACE,
-                                            std::bind(&LightResource::entityHandler, this, std::placeholders::_1),
-                                            OC_DISCOVERABLE | OC_OBSERVABLE);
-  if (OC_STACK_OK != result)
-   std::cout << "Resource creation failed.\n";
-}
-
-void LightResource::observe_function()
-{
- cerr << "Observation thread is spinning up.\n";
-
- while(!shutdown_flag)
-  {
-    std::this_thread::sleep_for(std::chrono::seconds(2));
-
-    if(!m_observation)
-     continue;
-
-    m_power += 10;
-
-    const auto result = OC::OCPlatform::notifyAllObservers(getHandle());
-
-    // Stop notifications when there are no more observers:
-    if(OC_STACK_NO_OBSERVERS == result)
-     {
-        m_observation = 0;
-     }
-  }
-
- cerr << "Observation thread is shutting down.\n";
-}
-
-void LightResource::unregisterResource()
-{
-    std::cout << "Unregistering light resource"<<std::endl;
-
-    OCStackResult result = OC::OCPlatform::unregisterResource(m_resourceHandle);
-
-    if(result == OC_STACK_OK)
-    {
-        std::cout << "Resource unregistered."<<std::endl;
-    }
-    else
-    {
-        cerr << "Unregister resource failed: "<<std::endl;
-    }
-}
-
-// This is just a sample implementation of entity handler.
-// Entity handler can be implemented in several ways by the manufacturer
-OCEntityHandlerResult LightResource::entityHandler(std::shared_ptr<OCResourceRequest> request)
-{
-    if(!request)
-     {
-        cerr << "entityHandler(): Received invalid request object.\n";
-        return OC_EH_ERROR;
-     }
-
-    switch(request->getRequestHandlerFlag())
-    {
-        default:
-                cerr << "entityHandler(): invalid request flag\n";
-                break;
-
-        case RequestHandlerFlag::InitFlag:
-                cerr << "entityHandler(): Initialization requested.\n";
-                break;
-
-        case RequestHandlerFlag::RequestFlag:
-                dispatch_request(request->getRequestType(), request);
-                break;
-
-        case RequestHandlerFlag::ObserverFlag:
-                handle_observe_event(request);
-                break;
-    }
-
-    return OC_EH_OK;
-}
-
-void LightResource::dispatch_request(const std::string& request_type, std::shared_ptr<OCResourceRequest> request)
-{
- std::cout << "dispatch_request(): " << request_type << '\n';
-
- if("GET" == request_type)
-  return handle_get_request(request);
-
- if("PUT" == request_type)
-  return handle_put_request(request);
-
- if("POST" == request_type)
-  return handle_post_request(request);
-
- if("DELETE" == request_type)
-  return handle_delete_request(request);
-
- cerr << "entityHandler(): Invalid request type \"" << request_type << "\".\n";
-}
-
-void LightResource::handle_get_request(std::shared_ptr<OCResourceRequest> request)
-{
- cout << "handle_get_request():\n";
-
- const auto query_params_map = request->getQueryParameters();
-
- // ...do any processing of the query here...
-
- // Get a representation of the resource and send it back as a response:
- auto pResponse = std::make_shared<OC::OCResourceResponse>();
- pResponse->setRequestHandle(request->getRequestHandle());
- pResponse->setResourceHandle(request->getResourceHandle());
- pResponse->setErrorCode(200);
- pResponse->setResponseResult(OC_EH_OK);
- pResponse->setResourceRepresentation(getRepresentation());
- OCPlatform::sendResponse(pResponse);
-}
-
-void LightResource::handle_put_request(std::shared_ptr<OCResourceRequest> request)
-{
- // Here's how you would get any query parameters:
- const auto query_params_map = request->getQueryParameters();
- // ...do something with the query parameters (if there were any)...
-
- auto rep = request->getResourceRepresentation();
-
- setRepresentation(rep);
-
- auto pResponse = std::make_shared<OC::OCResourceResponse>();
- pResponse->setRequestHandle(request->getRequestHandle());
- pResponse->setResourceHandle(request->getResourceHandle());
- pResponse->setErrorCode(200);
- pResponse->setResponseResult(OC_EH_OK);
- pResponse->setResourceRepresentation(getRepresentation());
- OCPlatform::sendResponse(pResponse);
-}
-
-void LightResource::handle_post_request(std::shared_ptr<OCResourceRequest> request)
-{
- // ...demo-code...
-}
-
-void LightResource::handle_delete_request(std::shared_ptr<OCResourceRequest> request)
-{
- // ...demo-code...
-}
-
-// Set up observation in a separate thread:
-void LightResource::handle_observe_event(std::shared_ptr<OCResourceRequest> request)
-{
- if(observe_thread.joinable())
-  return;
-
- observe_thread = thread(bind(&LightResource::observe_function, this));
- observe_thread.detach();
-}
-
-
-
-}} // namespace Intel::OCDemo
-
diff --git a/resource/examples/ocicuc/light_resource.hpp b/resource/examples/ocicuc/light_resource.hpp
deleted file mode 100644 (file)
index 494b366..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-#ifndef __LIGHT_RESOURCE_HPP
- #define __LIGHT_RESOURCE_HPP
-
-#include <map>
-#include <atomic>
-#include <thread>
-#include <string>
-#include <ostream>
-#include <sstream>
-#include <iostream>
-#include <functional>
-
-#include "OCApi.h"
-#include "OCResource.h"
-#include "OCPlatform.h"
-
-/* An example of a server-side resource: */
-namespace Intel { namespace OCDemo {
-
-using namespace OC;
-using namespace std;
-
-/// This class represents a single resource named 'lightResource'. This resource has
-/// two simple properties named 'state' and 'power'
-class LightResource
-{
- public:
-    bool m_state;       // off or on?
-    int m_power;        // power level
-    OCRepresentation m_rep;
-
-    private:
-    atomic<bool> m_observation; // are we under observation?
-
-    private:
-    static atomic<bool> shutdown_flag;
-    static thread observe_thread;
-
-    private:
-    OCResourceHandle m_resourceHandle;
-
-    public:
-    LightResource()
-     : m_state(false),
-       m_power(0),
-       m_observation(false)
-    {}
-
-    ~LightResource()
-    {
-        shutdown_flag = true;
-
-        if(observe_thread.joinable())
-         observe_thread.join();
-    }
-
-    private:
-    inline std::string make_URI(const unsigned int resource_number)
-    {
-        std::string uri = std::string("/a/light") + "_" + std::to_string(resource_number);
-        m_rep.setUri(uri);
-        return uri;
-    }
-
-    public:
-    // This function internally calls registerResource API.
-    void createResource(const unsigned int resource_number);
-    void unregisterResource();
-    OCResourceHandle getHandle() const { return m_resourceHandle; }
-
-    void setRepresentation(const OCRepresentation& rep);
-    OCRepresentation getRepresentation(void);
-
-    void addType(const std::string& type) const;
-    void addInterface(const std::string& interface) const;
-
-    private:
-    OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
-
-    private:
-    void observe_function();
-
-    // Request handlers:
-    private:
-    void dispatch_request(const std::string& request_type, std::shared_ptr<OCResourceRequest> request);
-    void handle_get_request(std::shared_ptr<OCResourceRequest> request);
-    void handle_put_request(std::shared_ptr<OCResourceRequest> request);
-    void handle_post_request(std::shared_ptr<OCResourceRequest> request);
-    void handle_delete_request(std::shared_ptr<OCResourceRequest> request);
-    void handle_observe_event(std::shared_ptr<OCResourceRequest> request);
-};
-
-}} // namespace Intel::OCDemo
-
-#endif
diff --git a/resource/examples/ocicuc/monoprocess.cpp b/resource/examples/ocicuc/monoprocess.cpp
deleted file mode 100644 (file)
index 14566ea..0000000
+++ /dev/null
@@ -1,222 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <map>
-#include <thread>
-#include <atomic>
-#include <string>
-#include <memory>
-#include <utility>
-#include <ostream>
-#include <sstream>
-#include <iostream>
-
-#include "OCApi.h"
-#include "OCResource.h"
-#include "OCPlatform.h"
-
-#include "exec.hpp"
-#include "utility.hpp"
-
-#include "demo_client.hpp"
-#include "light_resource.hpp"
-
-namespace Intel { namespace OCDemo {
-
-auto make_description()
-    -> boost::program_options::options_description
-{
- using std::string;
-
- namespace po = boost::program_options;
-
- po::options_description desc("Monoprocess Client/Server options");
-
- desc.add_options()
-    ("nres",        po::value<unsigned long>()->default_value(1),  "number of resources to use for testing")
-    ("host_ip",     po::value<string>()->default_value("0.0.0.0"), "IP of host")
-    ("host_port",   po::value<uint16_t>()->default_value(0),       "port of host")
-    ("interface",   po::value<string>()->default_value("eth0"),    "network interface name")
-    ("uri",         po::value<vector<string>>(),                   "resource URI")
-    ;
-
- return desc;
-}
-
-/* Unfortunately, our target compiler may not support std::async correctly, so this
-leverages RAII to save us from having to use the double-join-check pattern: */
-struct simple_join_guard
-{
- thread t;
-
- template <class FnT>
- simple_join_guard(FnT&& fn)
-  : t(fn)
- {}
-
- ~simple_join_guard()
- {
-    if(t.joinable())
-     t.join();
- }
-};
-
-struct client_t
-{
- const boost::program_options::variables_map        m_vm;
-
- atomic<bool>&                                      quit_flag;
-
- vector<string>                                     resource_URIs;
-
- public:
- client_t(const boost::program_options::variables_map vm,
-          atomic<bool>& quit_flag_)
-  : m_vm(vm),
-    quit_flag(quit_flag_)
- {}
-
- public:
- void init()
- {
-    if(0 != m_vm.count("uri"))
-     {
-        const vector<string>& input_URIs = m_vm["uri"].as< vector<string> >();
-        copy(begin(input_URIs), end(input_URIs), back_inserter(resource_URIs));
-     }
-    else
-     resource_URIs.push_back("coap://224.0.1.187/oc/core");
-  }
-
- void operator()()
- {
-    std::cout << "Requesting " << resource_URIs.size() << " URIs:\n";
-
-    for(const auto& resource_URI : resource_URIs)
-     cout << resource_URI << '\n';
-
-    Intel::OCDemo::client::resource_handler resources(resource_URIs);
-
-    // Register callbacks and wait for resources:
-    resources.find_resources();
-
-    // Allow the client to receive events from the server:
-    while(!quit_flag)
-     {
-        std::this_thread::sleep_for(std::chrono::seconds(1));
-     }
- }
-};
-
-struct server_t
-{
- const boost::program_options::variables_map        m_vm;
-
- atomic<bool>&                                      quit_flag;
-
- unsigned long                                      m_nresources;
-
- vector<string>                                     resource_URIs;
-
- vector<shared_ptr<Intel::OCDemo::LightResource>>   lights;
-
- public:
- server_t(const boost::program_options::variables_map& vm,
-          atomic<bool>& quit_flag_)
-  : m_vm(vm),
-    quit_flag(quit_flag_)
- {
-    m_nresources = vm["nres"].as<unsigned long>();
- }
-
- public:
- void init();
-
- void operator()()
- {
-    while(!quit_flag)
-     {
-        std::this_thread::sleep_for(std::chrono::seconds(5));
-     }
- }
-};
-
-void server_t::init()
-{
- lights.resize(m_nresources);
-
- for(unsigned int resource_number = 1; m_nresources >= resource_number; resource_number++)
-  {
-    cout << "Registering resource " << resource_number << ": " << std::flush;
-
-    auto lr = make_shared<Intel::OCDemo::LightResource>();
-
-    lr->createResource(resource_number);
-    lr->addType("core.brightlight");
-    lr->addInterface("oc.mi.ll");
-
-    lights.push_back(lr);
-
-    cout << "Ok." << std::endl;
-  }
-}
-
-int exec(const boost::program_options::variables_map& vm)
-{
- using namespace std;
-
- std::cout << "Starting platform: " << std::flush;
-
- OC::OCPlatform::Configure(OC::PlatformConfig {
-                          OC::ServiceType::InProc,
-                          OC::ModeType::Both,                   // run in client/server mode
-                          vm["host_ip"].as<string>(),           // host
-                          vm["host_port"].as<uint16_t>(),       // port
-                          OC::QualityOfService::LowQos
-                        });
- std::cout << "Ok." << std::endl;
-
- std::atomic<bool> quit_flag;
-
- server_t server(vm, quit_flag);
- client_t client(vm, quit_flag);
-
-std::cout << "JFW: TODO: don't need to separate these any more\n";
- server.init();
- client.init();
-
- // Run the server and client:
- {
-    simple_join_guard server_guard(server);
-    simple_join_guard client_guard(client);
-
-    // Note that at present nothing makes this true:
-    while(!quit_flag)
-     {
-        // Perform app tasks
-        std::this_thread::sleep_for(std::chrono::seconds(2));
-     }
-  }
-
- return 1;
-}
-
-}} // namespace Intel::OCDemo
-
diff --git a/resource/examples/ocicuc/server.cpp b/resource/examples/ocicuc/server.cpp
deleted file mode 100644 (file)
index 65fca0e..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "utility.hpp"
-
-#include "exec.hpp"
-#include "light_resource.hpp"
-
-namespace Intel { namespace OCDemo {
-
-auto make_description()
-    -> boost::program_options::options_description
-{
- using std::string;
-
- namespace po = boost::program_options;
-
- po::options_description desc("Server options");
-
- desc.add_options()
-    ("nres",        po::value<unsigned long>()->default_value(1),         "number of resources to use for testing")
-    ("host_ip",     po::value<string>()->default_value("0.0.0.0"), "IP of host")
-    ("host_port",   po::value<uint16_t>()->default_value(0),          "port of host")
-    ("interface",   po::value<string>()->default_value("eth0"),           "network interface name")
-    ("uri",     po::value<vector<string>>(),                              "resource URI")
-    ("runtime", po::value<unsigned int>()->default_value(3600),             "time in seconds to keep the server alive")
-    ;
-
- return desc;
-}
-
-int exec(const boost::program_options::variables_map& vm)
-{
- using namespace std;
-
- std::cout << "Starting platform: " << std::flush;
-
- OC::OCPlatform::Configure({
-                          OC::ServiceType::InProc,              // in-process server
-                          OC::ModeType::Server,                 // run in server mode
-                          vm["host_ip"].as<string>(),           // host
-                          vm["host_port"].as<uint16_t>(),       // port
-                          OC::QualityOfService::LowQos
-                        });
-
- std::cout << "Ok." << std::endl;
-
- vector<string> resource_URIs;
-
- vector<shared_ptr<Intel::OCDemo::LightResource>> lights;
-
- const unsigned long& nresources = vm["nres"].as<unsigned long>();
-
- for(unsigned int resource_number = 1; nresources >= resource_number; resource_number++)
-  {
-        cout << "Registering resource " << resource_number << ": " << std::flush;
-
-        auto lr = make_shared<Intel::OCDemo::LightResource>();
-
-        lr->createResource(resource_number);
-        lr->addType(std::string("core.brightlight"));
-        lr->addInterface(std::string("oc.mi.ll"));
-
-        lights.push_back(lr);
-
-        cout << "Ok." << std::endl;
-  }
-
- // Perform app tasks
- cout << "Sleeping for "<< vm["runtime"].as<unsigned int>()<<" seconds."<<endl;
- std::this_thread::sleep_for(std::chrono::seconds( vm["runtime"].as<unsigned int>()));
-
- for(auto light: lights)
- {
-    light->unregisterResource();
- }
-
- return 1;
-}
-
-}} // namespace Intel::OCDemo
-
diff --git a/resource/examples/ocicuc/small_example.cpp b/resource/examples/ocicuc/small_example.cpp
deleted file mode 100644 (file)
index e641cff..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Example program illustrating how to work with the ocicuc driver program: */
-
-#include "exec.hpp"
-
-#include <iostream>
-
-namespace Intel { namespace OCDemo {
-
-/* exec() is essentially main(), and is where the driver will start your
-program after command-line options have been parsed: */
-int exec(const boost::program_options::variables_map& vm)
-{
- using std::cout;
-
- cout << "This is the start of my wonderful program!\n";
-
- cout << "My command-line options are:\n";
-
- for(const auto& o : vm)
-  cout << o.first << " => " << o.second.as<std::string>() << '\n';
-
- return 0;
-}
-
-/* make_description() is your opportunity to describe your program's help screen and command
-line parameter types. Refer to the boost::program_options library for details on how to
-add different kinds of command-line options: */
-auto make_description()
-    -> boost::program_options::options_description
-{
- namespace po = boost::program_options;     // because boost::program_options is a lot to type!
-
- po::options_description desc("My wonderful program's options! Run with \"--\" to simply use the defaults.");
-
- desc.add_options()
-    ("param",   po::value<std::string>()->default_value("Hello, World!"),   "description of param")
-    ;
-
- return desc;
-}
-
-}} // namespace Intel::OCDemo
-
-
diff --git a/resource/examples/ocicuc/utility.cpp b/resource/examples/ocicuc/utility.cpp
deleted file mode 100644 (file)
index 823e57f..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-#include <chrono>
-#include <string>
-#include <iostream>
-#include <algorithm>
-
-#include "utility.hpp"
-
-namespace Intel { namespace OCDemo {
-
-int observe_count()
-{
- static unsigned long long oc = 0;
- return ++oc;
-}
-
-}} // namespace Intel::OCDemo
-
-// Helper for measuring call times:
-namespace Intel { namespace OCDemo {
-
-using std::cout;
-using namespace std::chrono;
-
-call_times call_timer;
-
-void call_times::reset(const std::string& entry) 
-{ 
- timings[entry] = make_pair(high_resolution_clock::now(), std::chrono::high_resolution_clock::time_point()); 
-}
-
-void call_times::mark(const std::string& name)
-{
- auto e = timings.find(name);
-
-    if(timings.end() == e)
-     {
-        reset(name);
-        return;
-     }
-
-    auto& tp = (*e).second;
-
-    if(tp.first > tp.second)
-     timings[name].second = high_resolution_clock::now();
-  }
-
-void call_times::report()
-{
- cout << "Time marks:\n";
-
- for_each(begin(timings), end(timings), 
- [](const std::pair<std::string, clock_interval>& tm) -> void 
- {
-    const std::string& name     { tm.first };
-
-    const time_point<high_resolution_clock>& request_time    { tm.second.first };
-    const time_point<high_resolution_clock>& response_time   { tm.second.second };
-
-    cout << '\t' << name << ": ";
-
-    if(request_time > response_time)
-     {
-        cout << "<waiting>\n";
-        return;
-     }
-
-    auto elapsed_ms = duration_cast<std::chrono::milliseconds>(response_time - request_time).count();
-    cout << elapsed_ms << "ms (";
-
-    auto elapsed_us = duration_cast<std::chrono::microseconds>(response_time - request_time).count();
-    cout << elapsed_us << "us)\n";
- });
-}
-
-void call_times::report_and_reset(const std::string& name)
-{
- mark(name), report(), reset(name);
-}
-
-
-}} // namespace Intel::OCDemo
diff --git a/resource/examples/ocicuc/utility.hpp b/resource/examples/ocicuc/utility.hpp
deleted file mode 100644 (file)
index bc734d7..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef __OC_OCDEMO_UTILITY_H
- #define __OC_OCDEMO_UTILITY_H
-
-#include <map>
-#include <tuple>
-#include <chrono>
-#include <ostream>
-
-#include "OCApi.h"
-
-namespace Intel { namespace OCDemo {
-
-/* A static observation counter: */
-int observe_count();
-
-/* Helpers for measuring request times: */
-typedef std::pair<
-                    std::chrono::time_point<std::chrono::high_resolution_clock>,
-                    std::chrono::time_point<std::chrono::high_resolution_clock>
-                 > clock_interval;
-
-struct call_times
-{
- public:
- bool display_reports;
-
- public:
- std::map<std::string, clock_interval> timings;
-
- public:
- call_times()
-  : display_reports(true)
- {}
-
- call_times(const bool& display_reports_)
-  : display_reports(display_reports_)
- {}
-
- public:
- void reset(const std::string& entry);
- void mark(const std::string& name);
-
- void report();
- void report_and_reset(const std::string& name);
-};
-
-extern call_times call_timer;
-
-}} // namespace Intel::OCDemo
-
-#endif
diff --git a/resource/examples/old_tests/MyMultiResourceHandler.cpp b/resource/examples/old_tests/MyMultiResourceHandler.cpp
deleted file mode 100644 (file)
index 76b5f4e..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <iostream>
-
-#include "ocapi.h"
-#include "OCReflect.h"
-#include "OCObserver.h"
-#include "OCException.h"
-#include "MyMultiResourceHandler.h"
-
-namespace {
-
-void log(const std::string& msg)
-{
- std::cerr << msg << '\n';
-}
-
-} // namespace
-
-void OC::MyMultiResourceHandler::onFoundResource(OCResourceResult *update, void *params){
-
-       //Step1: Find a specific resource that also contains OCReflect byte stream of methods and properties
-       for( auto &resource : update->resources ) 
-       {
-               if(resource.getURI() == "/garage/dimmer/a")
-               {
-                       performDimmerOperations(resource, update);
-               }
-               else if(resource.getURI() == "/garage/door/a")
-               {
-                       performDoorOperations(resource, update);
-               }
-       }
-}
-
-void OC::MyMultiResourceHandler::performDimmerOperations(OC::OCResource myResource, OC::OCResourceResult *update)
-{
-        using OC::OCReflect::entity;
-        using OC::OCReflect::method;
-        using OC::OCReflect::remote_resource;
-
-        using OC::bind_observer;
-        using OC::unbind_observer;
-
-       try
-       {
-               // Perform resource operation
-               // Note that this resource dimmer has 
-               // 'manufacturer' as a property
-               // 'powerState' as a observable property
-               // 'setPowered' as a method 
-               // 'getPowered' as a method 
-
-               //Step1: Find a specific method and invoke it. or Find a specific property and use it.
-
-               // Canonical one-step approach to get a callable function object:
-               // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource
-               auto setPowered = OCReflect::method(myResource, "setPowered");
-
-               // invoke the remote method, 
-               // invalid arguments return as an OC::OCReflect::reflect_exception
-               setPowered(true); 
-
-               // Canonical one-step approach to get a callable function object:
-               // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource
-               auto getPowered = OCReflect::method(myResource, "getPowered");
-
-               // invoke the remote method, 
-               // invalid arguments return as an OC::OCReflect::reflect_exception
-               // bool power = getPowered(); // Use power variable to do other operations
-
-               // Canonical one-step approach to access a property:
-               std::string manufacturer = update->property<std::string>("manufacturer");
-
-               //Example to observe a property
-               bind_observer(&myObserverHandler, myResource, "powerState");
-
-               //Example to unobserve a property
-               unbind_observer(&myObserverHandler, myResource, "powerState");
-       }
-       catch(OC::reflection_exception& e)
-       {
-               log(e.what());
-       }
-       catch(std::exception& e)
-       {
-               log(e.what());
-       }
-}
-
-void OC::MyMultiResourceHandler::performDoorOperations(OC::OCResource myResource, OC::OCResourceResult *update)
-{
-       // Perform resource operation
-       // Note that this resource door has 
-       // 'manufacturer' as a property
-       // 'setLockState' as a method 
-       // 'getLockState' as a method
-
-       try
-       {
-               // Step1: Find a specific method and invoke it or find a specific property and use it.
-
-               // Canonical one-step approach to get a callable function object:
-               // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource
-               auto setLockState = OCReflect::method(myResource, "setLockState");
-
-               // invoke the remote method, 
-               // invalid arguments return as an OC::OCReflect::reflect_exception
-               setLockState(true); 
-
-               // Canonical one-step approach to get a callable function object:
-               // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource
-               auto getLockState = OCReflect::method(myResource, "getLockState");
-
-               // invoke the remote method, 
-               // invalid arguments return as an OC::OCReflect::reflect_exception
-               // bool lockState = getLockState(); // use lockState variable for any other operations
-
-               // Canonical one-step approach to access a property
-               std::string manufacturer = update->property<std::string>("manufacturer");
-       }
-       catch(OC::reflection_exception& e)
-       {
-               log(e.what());
-       }
-       catch(std::exception& e)
-       {
-               log(e.what());
-       }
-}
-
-void OC::MyMultiResourceHandler::MyMultiResourceHandler::onCompleted()
-{
-
-}
-
-void OC::MyMultiResourceHandler::MyMultiResourceHandler::onFailed()
-{
-
-}
diff --git a/resource/examples/old_tests/MyMultiResourceHandler.h b/resource/examples/old_tests/MyMultiResourceHandler.h
deleted file mode 100644 (file)
index c0695b7..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocapi.h"
-#include "OCResourceHandler.h"
-#include "MyObserverHandler.h"
-
-namespace OC {
-
-class MyMultiResourceHandler :
-       public OCResourceHandler
-{
-public:
-       void onFoundResource(OCResourceResult *update, void *params);
-       void onCompleted();
-       void onFailed();
-
-private:
-       MyObserverHandler myObserverHandler;
-
-       /// This is a private function to perform operations related to dimmer resource 
-       void performDimmerOperations(OCResource myResource, OCResourceResult *update);
-
-       /// This is a private function to perform operations related to door resource
-       void performDoorOperations(OCResource myResource, OCResourceResult *update);
-};
-
-} // namespace OC
diff --git a/resource/examples/old_tests/MyObserverHandler.cpp b/resource/examples/old_tests/MyObserverHandler.cpp
deleted file mode 100644 (file)
index ee090ce..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "MyObserverHandler.h"
-
-void OC::MyObserverHandler::onObserverUpdate(std::string propertyName, void *value)
-{
-
-}
diff --git a/resource/examples/old_tests/MyObserverHandler.h b/resource/examples/old_tests/MyObserverHandler.h
deleted file mode 100644 (file)
index 25d6991..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "OCApi.h"
-#include "OCObserverHandler.h"
-
-namespace OC {
-
-class MyObserverHandler :
-       public OC::OCObserverHandler
-{
-public:
-       void onObserverUpdate(std::string propertyName, void *value);
-};
-
-} // namespace OC
diff --git a/resource/examples/old_tests/MyResourceHandler.cpp b/resource/examples/old_tests/MyResourceHandler.cpp
deleted file mode 100644 (file)
index cd6a511..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#include <iostream>
-
-#include "ocapi.h"
-#include "OCReflect.h"
-#include "OCObserver.h"
-#include "OCException.h"
-#include "MyResourceHandler.h"
-
-void log(const std::string& msg)
-{
- std::cerr << msg << '\n';
-}
-
-MyResourceHandler::MyResourceHandler(void)
-{
-}
-
-
-MyResourceHandler::~MyResourceHandler(void)
-{
-}
-
-void MyResourceHandler::onFoundResource(OCResourceResult *update, void *params){
-       using OC::OCReflect::entity;
-       using OC::OCReflect::method;
-       using OC::OCReflect::remote_resource;
-
-       using OC::bind_observer;
-       using OC::unbind_observer;
-
-       try
-       {
-               //Step1: Find a specific resource that also contains OCReflect byte stream of methods and properties
-               OCResource myResource;
-               for ( auto &resource : update->resources ) {
-                       if(resource.getURI() == "/light/a"){
-                               myResource = resource;
-                               break;
-                       }
-               }
-
-               //Step2: Find a specific method and invoke it. or Find a specific property and use it.
-
-               // Canonical one-step approach to get a callable function object:
-               // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource
-               auto setLevel = OC::OCReflect::method(myResource, "setLevel");
-
-               setLevel(75, 255); 
-
-               // Individual steps-- each may throw on failure:
-               remote_resource myLight(myResource, "lights/a");        // JFW: this may be subsumed by type OCResource
-
-               entity e_setPowered = myLight("setPowered");
-
-               method setPowered = OC::OCReflect::narrow<OCReflect::method>(e_setPowered);
-
-               setPowered(true);
-
-               // Canonical one-step approach to access a property:
-               std::string manufacturer = update->property<std::string>("manufacturer");
-
-               // Individual steps:
-               entity e_manufacturer = myResource.property("manufacturer");
-               std::string manufacturer_2 = OC::OCReflect::narrow<std::string>(e_manufacturer);
-
-               //Example to observe a property
-               bind_observer(&myObserverHandler, myResource, "PowerState");
-
-               //Example to unobserve a property
-               unbind_observer(&myObserverHandler, myResource, "PowerState");
-       }
-       catch(OC::reflection_exception& e)
-       {
-               log(e.what());
-       }
-       catch(std::exception& e)
-       {
-               log(e.what());
-       }
-}
-
-void MyResourceHandler::onCompleted(){
-}
-
-void MyResourceHandler::onFailed(){
-}
diff --git a/resource/examples/old_tests/MyResourceHandler.h b/resource/examples/old_tests/MyResourceHandler.h
deleted file mode 100644 (file)
index 28b9e88..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ocapi.h"
-#include "OCResourceHandler.h"
-#include "MyObserverHandler.h"
-
-using namespace OC;
-
-class MyResourceHandler :
-       public OCResourceHandler
-{
-public:
-       MyResourceHandler(void);
-       virtual ~MyResourceHandler(void);
-       void onFoundResource(OCResourceResult *update, void *params);
-       void onCompleted();
-       void onFailed();
-
-private:
-       MyObserverHandler myObserverHandler;
-
-};
-
diff --git a/resource/examples/old_tests/OCWrapper/makefile b/resource/examples/old_tests/OCWrapper/makefile
deleted file mode 100644 (file)
index e0b44e4..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread
-
-final: server client serverApp
-
-serverApp: InProcServerWrapper.o testServerApp.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o OCPlatform.o
-       $(CXX) $(CXX_FLAGS) -o serverApp InProcServerWrapper.o testServerApp.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o OCPlatform.o
-
-server: InProcServerWrapper.o testServer.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o
-       $(CXX) $(CXX_FLAGS) -o server InProcServerWrapper.o testServer.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o
-
-client: InProcServerWrapper.o testClient.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o
-       $(CXX) $(CXX_FLAGS) -o client InProcServerWrapper.o testClient.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o
-
-OCReflect.o: ../../../OCLib/OCReflect.cpp
-       $(CXX) $(CXX_FLAGS) -c ../../../OCLib/OCReflect.cpp -I../../../csdk/ -I../../../include -I../
-
-OCPlatform.o: ../../../OCLib/OCPlatform.cpp
-       $(CXX) $(CXX_FLAGS) -c ../../../OCLib/OCPlatform.cpp -I../../../csdk/ -I../../../include/ -I../ -I../client/ -I../server/
-
-OCResource.o: ../../../OCLib/OCResource.cpp
-       $(CXX) $(CXX_FLAGS) -c ../../../OCLib/OCResource.cpp -I../../../csdk/ -I../../../include/ -I../ -I../client/ -I../server/
-
-ocstack_stub.o : ../../../csdk/ocstack_stub.c
-       gcc -c ../../../csdk/ocstack_stub.c -I../../../csdk/
-
-InProcServerWrapper.o: ../server/InProcServerWrapper.cpp
-       $(CXX) $(CXX_FLAGS) -c ../server/InProcServerWrapper.cpp -I../../../csdk/ -I../../../include -I../
-
-InProcClientWrapper.o: ../client/InProcClientWrapper.cpp
-       $(CXX) $(CXX_FLAGS) -c ../client/InProcClientWrapper.cpp -I../../../csdk/ -I../../../include -I../
-
-testServer.o : testServer.cpp
-       $(CXX) $(CXX_FLAGS) -c testServer.cpp -I../../../csdk/ -I../../../include -I../ -I../client/ -I../server/
-
-testServerApp.o : testServerApp.cpp
-       $(CXX) $(CXX_FLAGS) -c testServerApp.cpp -I../../../csdk/ -I../../../include -I../ -I../client/ -I../server/
-
-testClient.o : testClient.cpp
-       $(CXX) $(CXX_FLAGS) -c testClient.cpp -I../../../csdk/ -I../../../include -I../ -I../client/ -I../server/
-
-clean:
-       rm *.o server client serverApp
-
diff --git a/resource/examples/old_tests/OCWrapper/parsetest.cpp b/resource/examples/old_tests/OCWrapper/parsetest.cpp
deleted file mode 100644 (file)
index 9eb71da..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <iostream>
-#include <boost/property_tree/ptree.hpp>
-#include <boost/property_tree/json_parser.hpp>
-
-using namespace std;
-using namespace boost::property_tree;
-
-void parseResource(ptree resource)
-{
-       cout<<"\t\tParsing Resource with "<< resource.size() <<" facts:"<<endl;
-       cout << "\t\tAddress is "<< resource.get<std::string>("href", "") <<endl;
-       cout << "\t\tIs Observable? : "<< (resource.get<int>("obs",0)==1)<<endl;
-       
-       // types:
-       cout << "\t\tResource Type Count : "<<resource.get_child("rt", ptree()).size()<<endl;
-       for(auto resourceItr : resource.get_child("rt", ptree()))
-       {
-               cout << "\t\t\tResource Type: "<< resourceItr.second.data()<<endl;
-       }
-       
-       // interfaces:
-       cout << "\t\tInterface Count : "<<resource.get_child("if", ptree()).size()<<endl;
-       for(auto resourceItr : resource.get_child("if", ptree()))
-       {
-               cout << "\t\t\tInterface: "<< resourceItr.second.data()<<endl;
-       }
-       
-       cout<<endl;
-}
-
-void parseTest(const char* data)
-{
-       
-       std::stringstream requestStream;
-       requestStream << data;
-               
-       ptree root;
-       boost::property_tree::read_json(requestStream, root);
-       
-       ptree payload = root.get_child("oc.payload", ptree());
-       cout << "\tResource Count:" << payload.size()<<endl;
-       
-       for(auto itr : payload)
-       {
-               parseResource(itr.second);
-       }
-       
-//     cout << "PTree Size: " << requestTree.size() << " DATA: "<<requestTree.get_value<string>() <<endl;
-       //cout << "\t Child:"<<requestTree.front().first.data()<<"  " << requestTree.front().second.data()<<endl;
-}
-
-
-int main()
-{
-       const char* data1 = "{\"oc\": {\
-    \"payload\": [{\
-            \"href\":\"/a/tube\",\
-            \"rt\":[\"alpha.act.tb\"],\
-            \"if\":[\"oc.mi.a\"]\
-                },\
-                {\
-            \"href\":\"/b/tube\",\
-            \"rt\":[\"alpha.act.tb\"],\
-            \"if\":[\"oc.mi.a\"],\
-            \"obs\" : 1\
-                }\
-               ]\
-        }\
-}";
-
-       const char* data2 = "{\"oc\": {\
-    \"payload\": [{\
-            \"href\":\"/temp-sensor\",\
-            \"rt\":[\"beta.sensor.temp\"],\
-            \"if\":[\"oc.mi.s\"],\
-            \"obs\" : 1\
-                }\
-               ]\
-        }\
-} ";
-
-       const char* data3 = "{\"oc\": {\
-    \"payload\": [{\
-            \"href\":\"/room-lights\",\
-            \"rt\":[\"gamma.lights\"],\
-            \"if\":[\"oc.mi.ll\", \"oc.mi.b\"]\
-                }\
-               ]\
-        }\
-} ";
-
-       cout<<"Data1:\n";
-       parseTest(data1);
-       cout<<"Data2:\n";
-       parseTest(data2);
-       cout<<"Data3:\n";
-       parseTest(data3);
-
-       return 0;
-}
\ No newline at end of file
diff --git a/resource/examples/old_tests/OCWrapper/testClient.cpp b/resource/examples/old_tests/OCWrapper/testClient.cpp
deleted file mode 100644 (file)
index 0b11384..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#include <WrapperFactory.h>
-#include <OCApi.h>
-#include <IServerWrapper.h>
-#include <IClientWrapper.h>
-
-using namespace OC;
-
-void testClient()
-{
-       PlatformConfig cfg;
-    cfg.ipAddress = "192.168.1.5";
-    cfg.port = 8080;
-    cfg.mode = ModeType::Client;
-    cfg.serviceType = ServiceType::InProc;
-       
-       IWrapperFactory::Ptr pFactory = std::make_shared<WrapperFactory>();
-       IClientWrapper::Ptr pWrapper = pFactory->CreateClientWrapper(cfg);
-}
-
-int main()
-{
-       testClient();
-}
diff --git a/resource/examples/old_tests/OCWrapper/testServer.cpp b/resource/examples/old_tests/OCWrapper/testServer.cpp
deleted file mode 100644 (file)
index 986c3a4..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#include <WrapperFactory.h>
-#include <OCApi.h>
-#include <IServerWrapper.h>
-#include <IClientWrapper.h>
-#include <OCReflect.h>
-
-#include <algorithm>
-#include <cstring>
-#include <cstdlib>
-
-using namespace OC;
-using namespace OC::OCReflect;
-
-// Demo of how to generate OCStack stuff:
-void rep_test()
-{
-       using OC::OCReflect::property_type;
-       using OC::OCReflect::named_property_binding;
-
-       named_property_binding_vector sigs {
-              named_property_binding("state", property_type::boolean),
-              named_property_binding("power", property_type::integer),
-       };
-
-       using namespace OC::OCReflect::OCStack;
-
-       std::vector<std::string> reps { convert(sigs) };
-
-       for(const auto& r : reps)
-           std::cout << r << '\n';
-
-       char **LEDrep = convert(reps);
-
-       std::for_each(LEDrep, LEDrep + length(LEDrep), [](const char *s) { std::cout << s << '\n'; });
-
-
-
-
-    OCEntityHandler entityHandler;
-    OCResourceHandle resourceHandle;
-
-    OCCreateResource(   &resourceHandle, // OCResourceHandle *handl
-                        "core.led", // const char * resourceTypeName
-                        "state:oc.bt.b;power:oc.bt.i", //const char * resourceTypeRepresentation
-                        "core.rw", //const char * resourceInterfaceName
-                        OC_REST_GET | OC_REST_PUT, // uint8_t allowedMethods
-                        "/a/led", // const char * uri
-                        entityHandler, // OCEntityHandler entityHandler
-                        OC_DISCOVERABLE | OC_OBSERVABLE // uint8_t resourceProperties
-                    );
-                                        
-
-
- release(LEDrep);
-}
-
-void testServer()
-{
-    PlatformConfig cfg;
-    cfg.ipAddress = "192.168.1.5";
-    cfg.port = 8080;
-    cfg.mode = ModeType::Server;
-    cfg.serviceType = ServiceType::InProc;
-
-    IWrapperFactory::Ptr pFactory= std::make_shared<WrapperFactory>();
-
-    IServerWrapper::Ptr pServer = pFactory->CreateServerWrapper(cfg);
-
-    //pServer->bindTo
-}
-
-int main()
-{
-    rep_test();
-       testServer();
-}
diff --git a/resource/examples/old_tests/OCWrapper/testServerApp.cpp b/resource/examples/old_tests/OCWrapper/testServerApp.cpp
deleted file mode 100644 (file)
index 3db9871..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-///
-/// This sample provides steps to define an interface for a resource
-/// (properties and methods) and host this resource on the server. 
-///
-
-#include <functional>
-
-#include <OCServer.h>
-#include <OCReflect.h>
-#include <OCPlatform.h>
-#include <OCApi.h>
-#include <iostream>
-
-using namespace std;
-
-using namespace OC;
-using namespace OC::OCReflect;
-
-/// This class represents a single resource named 'light'. This resource has 
-/// two simple properties named 'state' and 'power' and they have respective setter
-/// and getter methods.
-
-class light
-{
-private:
-       /// Access this property from a TB client 
-       bool m_state;
-       int m_power;
-
-public:
-       light()
-               : m_power(0),
-               m_state(false)
-       {}
-
-public:
-       /// Setter method for the setting the power of this light resource
-       void setPower(int powerValue)             
-       { 
-               m_power = powerValue; 
-       }
-
-       /// Getter method for the getting the power of this light resource
-       int getPower() const                           
-       { 
-               return m_power; 
-       }
-
-       /// Setter method for the setting the state of this light resource
-       void setState(bool state)             
-       { 
-               m_state = state; 
-       }
-
-       /// Getter method for the getting the state of this light resource
-       bool getState() const                           
-       { 
-               return m_state; 
-       }
-       
-public:
-       /* Note that this does not need to be a member function: for classes you do not have
-       access to, you can accomplish this with a free function: */
-       
-       /// This function binds the properties and methods to the server. 
-       void bindTo(OC::OCPlatform& platform)
-       {
-               using OC::OCReflect::property_type;
-               using OC::OCReflect::property_binding;
-
-               property_binding_vector properties {
-                       property_binding("state", property_type::boolean),
-                       property_binding("power", property_type::integer)
-               };
-
-               std::string resourceURI = "/a/light";
-               std::string resourceTypeName = "light";
-               platform.registerResource(resourceURI, resourceTypeName, properties);
-       }
-};
-
-int main()
-{
-       // Step1: Create a OCPlatform instance. 
-       // Step1.1: The constructor of OCPlatform class takes PlatformConfig object.
-       // Note: Platform creation is synchronous call. 
-
-       PlatformConfig cfg;
-       cfg.ipAddress = "192.168.1.5";
-       cfg.port = 8080;
-       cfg.mode = ModeType::Server;
-       cfg.serviceType = ServiceType::InProc;
-
-    cout << "Creating OCPlatform .. \n";
-       
-       OCPlatform platform(cfg);
-       
-       // Step2: Create the instance of the resource class (in this case instance of class 'light'). 
-       // Step2.1: Invoke bindTo function of class light. 
-       
-       light myLight;
-       myLight.bindTo(platform);
-
-       while(true)
-       {
-               //some tasks
-       }
-
-       // No explicit call to stop the platform. 
-       // When OCPlatform destructor is invoked, internally we do platform cleanup
-}
diff --git a/resource/examples/old_tests/multiple_resources.cpp b/resource/examples/old_tests/multiple_resources.cpp
deleted file mode 100644 (file)
index f0fc986..0000000
+++ /dev/null
@@ -1,264 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-///
-/// This sample provides steps to define an interface for multiple resources
-/// (properties and methods) and host these resources on the server. 
-///
-#include <functional>
-
-#include "OCServer.h"
-#include "OCReflect.h"
-
-using namespace OC::OCReflect;
-
-class dimmer
-{
-private:
-       int m_level;
-       int m_color;
-
-public:
-       bool m_powered;                         // This is an observable property
-       std::string manufacturer;       // This is a non-observable property
-
-public:
-       dimmer()
-               : m_level(0),
-               m_color(0),
-               m_powered(false),
-               manufacturer("Integrated Electronics")
-       {}
-
-public:
-       /// Setter method for the setting the power state of this dimmer resource
-       void setPowered(const bool newState)             
-       { 
-               m_powered = newState; 
-       }
-
-       /// Getter method for the setting the power state of this dimmer resource
-       bool getPowered() const                           
-       { 
-               return m_powered; 
-       }
-
-       /// Setter method for the setting the intensity level of this dimmer resource
-       /// Along with above basic method, this method takes two arguments
-       /// with first argument as intensity level and second level as color.
-       void setLevel(const int newLevel, int color)     
-       { 
-               m_level = newLevel; 
-               m_color = color; 
-       }
-
-       /// Getter method for getting the intensity level of the dimmer resoruce
-       int getLevel() const                              
-       { 
-               return m_level; 
-       }
-
-       /// Note that this does not need to be a member function: for classes you do not have
-       /// access to, you can accomplish this with a free function:
-public:
-       void bindTo(OC::OCServer& server, const std::string& base_URI)
-       {
-               /*using OC::OCReflect::method_signature;
-               using OC::OCReflect::method_binding;
-               using OC::OCReflect::property_signature;
-               using OC::OCReflect::property_binding;
-               using OC::OCReflect::bind_service;
-               using OC::OCReflect::bind_property;
-
-               using OC::OCReflect::property_type;*/
-
-               // Register the URI with the server
-               server.registerResource(this, base_URI);
-
-               // Steps to map the property
-
-               // The canonical way to bind a property to a server in one step:
-               bind_property(
-                       server,                                      // server to bind to
-                       this->manufacturer,                          // pointer to property
-                       "manufacturer",                              // property binding name
-                       OC::OCReflect::property_type::string,        // property
-                       OC::OCReflect::property_attribute::r         // type decoration
-                       );
-
-               // The canonical way to bind a property to a server in one step:
-               bind_property(
-                       server,                                      // server to bind to
-                       this->m_powered,                             // pointer to property
-                       "powerState",                                // property binding name
-                       OC::OCReflect::property_type::boolean,       // property
-                       OC::OCReflect::property_attribute::r         // type decoration
-                       );
-
-               // Steps to map the methods
-
-               // Example to map getPowered method using the canonical way in one step:
-               bind_service(server,                    // server to bind to
-                       this,                                           // instance (ourself) to bind 
-                       &dimmer::getPowered,                    // address of the method to bind
-                       "getPowered",                           // name to bind with service URL
-                       property_type::boolean);        // return type of the method
-
-               // Example to map setPowered method using the canonical way in one step:
-               bind_service(server,                    // server to bind to
-                       this,                                           // instance (ourself) to bind 
-                       &dimmer::setPowered,                    // address of the method to bind
-                       "setPowered",                           // name to bind with service URL
-                       property_type::nil,                     // return type of the method
-                       property_type::boolean);        // parameter type for setPowered method
-
-               // Example to map setLevel method using the canonical way in one step:
-               bind_service(
-                       server,                         // server to bind with
-                       this,                           // instance to bind
-                       &dimmer::setLevel,              // method to bind
-                       "setLevel",                     // service name
-                       property_type::nil,             // input type
-                       property_type::integer,         // parameter list starts (parameter type for level)
-                       property_type::integer);        // parameter list (parameter type for color) 
-
-               // Example to map getLevel method using the canonical way in one step:
-               bind_service(server, this, &dimmer::getLevel, "getLevel", property_type::integer);
-       }
-};
-
-class door
-{
- bool m_locked;
-
-public:
-       std::string manufacturer;
-
-public:
-       door()
-               : m_locked(true),
-               manufacturer("Integrated Electronics")
-       {}
-
-public:
-       /// Setter method for the setting the lock state of this door resource
-       void setLockState(const bool lockState)             
-       { 
-               m_locked = lockState; 
-       }
-
-       /// Getter method for the setting the lock state of this door resource
-       bool getLockState() const                           
-       { 
-               return m_locked; 
-       }
-
-       /* Note that this does not need to be a member function: for classes you do not have
-       access to, you can accomplish this with a free function: */
-public:
-       void bindTo(OC::OCServer& server, const std::string& base_URI)
-       {
-               /*using OC::OCReflect::method_signature;
-               using OC::OCReflect::method_binding;
-               using OC::OCReflect::property_signature;
-               using OC::OCReflect::property_binding;
-               using OC::OCReflect::bind_service;
-               using OC::OCReflect::bind_property;
-
-               using OC::OCReflect::property_type;*/
-
-               // Register the URI with the server
-               server.registerResource(this, base_URI);
-
-               // Steps to map the property
-
-               // The canonical way to bind a property to a server in one step:
-               bind_property(
-                       server,                                      // server to bind to
-                       this->manufacturer,                          // pointer to property
-                       "manufacturer",                              // property binding name
-                       OC::OCReflect::property_type::string,        // property
-                       OC::OCReflect::property_attribute::r         // type decoration
-                       );
-
-               // Steps to map the methods
-
-               // Example to map getPowered method using the canonical way in one step:
-               bind_service(server,                    // server to bind to
-                       this,                                           // instance (ourself) to bind 
-                       &door::getLockState,            // address of the method to bind
-                       "getLockState",                         // name to bind with service URL
-                       property_type::boolean);        // return type of the method
-
-               // Example to map setPowered method using the canonical way in one step:
-               bind_service(server,                    // server to bind to
-                       this,                                           // instance (ourself) to bind 
-                       &door::setLockState,            // address of the method to bind
-                       "setLockState",                         // name to bind with service URL
-                       property_type::nil,                     // return type of the method
-                       property_type::boolean);        // parameter type for setPowered method
-       }
-};
-
-class garage 
-{
-private:
-       dimmer myDimmer;
-       door myDoor;
-
-public:
-       void bindTo(OC::OCServer& server, const std::string& base_URI)
-       {
-               // Register the URI with the server
-               server.registerResource(this, base_URI);
-
-               // Bind child resource 'dimmer' to the server 
-               myDimmer.bindTo(server, base_URI + "/dimmer/a");
-
-               // Bind child resource 'door' to the server
-               myDoor.bindTo(server, base_URI + "/door/a");
-       }
-};
-
-int main()
-{
-       //Step1: create a server
-       OC::OCSecurityModel securityModel;
-       OC::OCServer server;
-       server.setSecurityModel(securityModel);
-
-       //Step2: Create a Garage resource
-       garage myGarage;
-
-       //Step3: Bind garage resource to the server
-       //Note: Garage resource has child resources -- dimmer and door.
-       myGarage.bindTo(server, "/garage/");
-
-       //Step4: Start the server
-       server.start();
-
-       while(true)
-       {
-               //do something here
-       }
-
-       //Step4: Stop the server
-       server.stop();
-}
index 857d0f4..305bfe5 100644 (file)
 using namespace OC;
 
 std::shared_ptr<OCResource> curResource;
-
+std::mutex resourceLock;
 static int TEST_CASE = 0;
 
+static OCConnectivityType connectivityType = OC_IPV4;
+
 /**
  * List of methods that can be inititated from the client
  */
@@ -50,17 +52,20 @@ typedef enum {
 
 void printUsage()
 {
-    std::cout << "Usage : presenceclient -t <1|2>" << 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;
     std::cout << "-t 3 : Discover Resources and Initiate Unicast Presence with Two Filters"
-            << std::endl;
+              << std::endl;
     std::cout << "-t 4 : Discover Resources and Initiate Multicast Presence" << std::endl;
     std::cout << "-t 5 : Discover Resources and Initiate Multicast Presence with Filter"
               << std::endl;
     std::cout << "-t 6 : Discover Resources and Initiate Multicast Presence with two Filters"
-                  << std::endl;
+            << std::endl;
+    std::cout<<"ConnectivityType: Default IPv4" << std::endl;
+    std::cout << "-c 0 : Send message with IPv4" << std::endl;
+    std::cout << "-c 1 : Send message with IPv6" << std::endl;
 }
 
 // Callback to presence
@@ -80,9 +85,6 @@ void presenceHandler(OCStackResult result, const unsigned int nonce, const std::
         case OC_STACK_PRESENCE_TIMEOUT:
             std::cout << "Presence Timeout\n";
             break;
-        case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
-            std::cout << "Virtual do not handle\n";
-            break;
         default:
             std::cout << "Error\n";
             break;
@@ -92,9 +94,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;
@@ -136,7 +140,7 @@ void foundResource(std::shared_ptr<OCResource> resource)
                 if(TEST_CASE == TEST_UNICAST_PRESENCE_NORMAL)
                 {
                     result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
-                            &presenceHandler);
+                            connectivityType, &presenceHandler);
                     if(result == OC_STACK_OK)
                     {
                         std::cout<< "Subscribed to unicast address: " << hostAddress << std::endl;
@@ -151,7 +155,7 @@ void foundResource(std::shared_ptr<OCResource> resource)
                         TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTERS)
                 {
                     result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
-                            "core.light", &presenceHandler);
+                            "core.light", connectivityType, &presenceHandler);
                     if(result == OC_STACK_OK)
                     {
                         std::cout<< "Subscribed to unicast address: " << hostAddress;
@@ -165,7 +169,7 @@ void foundResource(std::shared_ptr<OCResource> resource)
                 if(TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTERS)
                 {
                     result = OCPlatform::subscribePresence(presenceHandle, hostAddress, "core.fan",
-                            &presenceHandler);
+                            connectivityType, &presenceHandler);
                     if(result == OC_STACK_OK)
                     {
                         std::cout<< "Subscribed to unicast address: " << hostAddress;
@@ -187,25 +191,71 @@ void foundResource(std::shared_ptr<OCResource> resource)
     }
     catch(std::exception& e)
     {
+        std::cerr << "Exception in foundResource: "<< e.what() << std::endl;
         //log(e.what());
     }
 }
 
 int main(int argc, char* argv[]) {
+
+    std::ostringstream requestURI;
+
     int opt;
 
-    while ((opt = getopt(argc, argv, "t:")) != -1)
+    int optionSelected;
+
+    try
     {
-        switch(opt)
+        while ((opt = getopt(argc, argv, "t:c:")) != -1)
         {
-            case 't':
-                TEST_CASE = atoi(optarg);
-                break;
-            default:
-                printUsage();
-                return -1;
+            switch(opt)
+            {
+                case 't':
+                    TEST_CASE = std::stoi(optarg);
+                    break;
+                case 'c':
+                    std::size_t inputValLen;
+                    optionSelected = std::stoi(optarg, &inputValLen);
+
+                    if(inputValLen == strlen(optarg))
+                    {
+                        if(optionSelected == 0)
+                        {
+                            connectivityType = OC_IPV4;
+                        }
+                        else if(optionSelected == 1)
+                        {
+                            // TODO: re-enable IPv4/IPv6 command line selection when IPv6
+                            // is supported
+                            //connectivityType = OC_IPV6;
+                            connectivityType = OC_IPV4;
+                            std::cout << "IPv6 not currently supported. Using default IPv4"
+                                    << std::endl;
+                        }
+                        else
+                        {
+                            std::cout << "Invalid connectivity type selected. Using default IPv4"
+                                << std::endl;
+                        }
+                    }
+                    else
+                    {
+                        std::cout << "Invalid connectivity type selected. Using default IPv4"
+                            << std::endl;
+                    }
+                    break;
+                default:
+                    printUsage();
+                    return -1;
+            }
         }
     }
+    catch(std::exception& )
+    {
+        std::cout << "Invalid input argument. Using IPv4 as connectivity type"
+            << std::endl;
+    }
+
     if(TEST_CASE >= MAX_TESTS || TEST_CASE <= 0)
     {
         printUsage();
@@ -230,10 +280,14 @@ int main(int argc, char* argv[]) {
         OCPlatform::OCPresenceHandle presenceHandle = nullptr;
         OCStackResult result = OC_STACK_OK;
 
+        std::ostringstream multicastPresenceURI;
+        multicastPresenceURI << "coap://" << OC_MULTICAST_PREFIX;
+
         if(TEST_CASE == TEST_MULTICAST_PRESENCE_NORMAL)
         {
             result = OCPlatform::subscribePresence(presenceHandle,
-                    OC_MULTICAST_IP, presenceHandler);
+                    multicastPresenceURI.str(), connectivityType, presenceHandler);
+
             if(result == OC_STACK_OK)
             {
                 std::cout << "Subscribed to multicast presence." << std::endl;
@@ -245,8 +299,8 @@ int main(int argc, char* argv[]) {
         }
         else if(TEST_CASE == TEST_MULTICAST_PRESENCE_WITH_FILTER)
         {
-            result = OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, "core.light",
-                    &presenceHandler);
+            result = OCPlatform::subscribePresence(presenceHandle, multicastPresenceURI.str(), "core.light",
+                    connectivityType, &presenceHandler);
             if(result == OC_STACK_OK)
             {
                 std::cout << "Subscribed to multicast presence with resource type";
@@ -259,8 +313,8 @@ int main(int argc, char* argv[]) {
         }
         else if(TEST_CASE == TEST_MULTICAST_PRESENCE_WITH_FILTERS)
         {
-            result = OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, "core.light",
-                    &presenceHandler);
+            result = OCPlatform::subscribePresence(presenceHandle, multicastPresenceURI.str(), "core.light",
+                    connectivityType, &presenceHandler);
             if(result == OC_STACK_OK)
             {
                 std::cout << "Subscribed to multicast presence with resource type";
@@ -271,8 +325,8 @@ int main(int argc, char* argv[]) {
             }
             std::cout << "\"core.light\"." << std::endl;
 
-            result = OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, "core.fan",
-                    &presenceHandler);
+            result = OCPlatform::subscribePresence(presenceHandle, multicastPresenceURI.str(), "core.fan",
+                    connectivityType, &presenceHandler);
             if(result == OC_STACK_OK)
             {
                 std::cout<< "Subscribed to multicast presence with resource type";
@@ -286,7 +340,10 @@ int main(int argc, char* argv[]) {
         else
         {
             // Find all resources
-            result = OCPlatform::findResource("", "coap://224.0.1.187/oc/core", &foundResource);
+            requestURI << OC_MULTICAST_DISCOVERY_URI;
+
+            result = OCPlatform::findResource("", requestURI.str(),
+                    OC_ALL, &foundResource);
             if(result == OC_STACK_OK)
             {
                 std::cout << "Finding Resource... " << std::endl;
@@ -306,11 +363,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..4931dfc 100644 (file)
@@ -210,29 +210,33 @@ int main()
 
         // Invoke createResource function of class light.
         myLightResource.createResource();
-        printf("Created first resource of type \"core.light\"");
+        std :: cout << "Creating first resource of type \"core.light\"" << std :: endl;
 
-        printf("\nEnter a key to create the second resource of type \"core.light\"\n");
-        getchar();
+        std :: cout << "Will start creating/deleting resources for presence in 10 seconds.\n";
+
+        sleep(10);
+
+        std :: cout << "\nCreating the second resource of type \"core.light\"" <<  std :: endl;
+        sleep(1);
 
         myLightResource.createResource2();
 
-        printf("\nEnter a key to stop the presence\n");
-        getchar();
+        std :: cout << "Stopping presence\n" << std :: endl;
+        sleep(1);
         stopPresence();
 
-        printf("\nEnter a key to restart the presence\n");
-        getchar();
+        std :: cout << "Restarting presence\n" << std :: endl;
+        sleep(1);
 
         startPresence(30);
 
-        printf("\nEnter a key to create the third resource of type \"core.light\"\n");
-        getchar();
+        std :: cout << "Creating a third resource of type \"core.light\"\n" << std :: endl;
+        sleep(1);
 
         myLightResource.createResource3();
 
-        printf("\nEnter a key to create two non-operational resources.\"\n");
-        getchar();
+        std :: cout << "Creating two non-operational resources.\"\n" << std :: endl;
+        sleep(1);
 
         createPresenceResources();
 
@@ -245,9 +249,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 +259,4 @@ int main()
 
     return 0;
 }
+
index 7e73597..fdba60d 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;
@@ -213,12 +215,16 @@ void foundResource(std::shared_ptr<OCResource> resource)
     }
     catch(std::exception& e)
     {
+        std::cerr << "Exception in foundResource: "<< e.what() <<std::endl;
         //log(e.what());
     }
 }
 
 int main(int argc, char* argv[]) {
 
+    std::ostringstream requestURI;
+
+
     // Create PlatformConfig object
     PlatformConfig cfg {
         OC::ServiceType::InProc,
@@ -233,7 +239,9 @@ int main(int argc, char* argv[]) {
     try
     {
         // Find all resources
-        OCPlatform::findResource("", "coap://224.0.1.187/oc/core", &foundResource);
+        requestURI << OC_MULTICAST_DISCOVERY_URI;
+
+        OCPlatform::findResource("", requestURI.str(), OC_ALL, &foundResource);
         std::cout<< "Finding Resource... " <<std::endl;
 
         // A condition variable will free the mutex it is given, then do a non-
@@ -247,9 +255,10 @@ int main(int argc, char* argv[]) {
 
     }catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<< e.what();
     }
 
     return 0;
 }
 
+
index 25c7ee9..7768b3f 100644 (file)
@@ -74,8 +74,9 @@ public:
 
 public:
     /// Constructor
-    RoomResource(): m_roomName("John's Room"), m_lightState(false),
-                    m_lightColor(0), m_fanState(false), m_fanSpeed(0)
+    RoomResource(): m_roomName("John's Room"), m_roomHandle(nullptr), m_lightState(false),
+                    m_lightColor(0),m_lightHandle(nullptr),  m_fanState(false), m_fanSpeed(0),
+                    m_fanHandle(nullptr)
     {
         m_lightUri = "/a/light"; // URI of the resource
         m_lightTypes.push_back("core.light"); // resource type name. In this case, it is light
@@ -289,13 +290,7 @@ bool prepareLightResponse(std::shared_ptr<OCResourceRequest> request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag == RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-        else if(requestFlag == RequestHandlerFlag::RequestFlag)
+        if(requestFlag == RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
 
@@ -350,13 +345,7 @@ bool prepareFanResponse(std::shared_ptr<OCResourceRequest> request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag == RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-        else if(requestFlag == RequestHandlerFlag::RequestFlag)
+        if(requestFlag == RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
 
@@ -411,13 +400,7 @@ OCEntityHandlerResult entityHandlerRoom(std::shared_ptr<OCResourceRequest> reque
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag == RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-        else if(requestFlag == RequestHandlerFlag::RequestFlag)
+        if(requestFlag == RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
 
@@ -592,7 +575,7 @@ int main(int argc, char* argv[])
         cv.wait(lock);
 
     }
-    catch(OCException e)
+    catch(OCException &e)
     {
         std::cout << "Exception in main: " << e.what();
     }
@@ -602,3 +585,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index 85c0dc1..e06d731 100644 (file)
 // OCClient.cpp : Defines the entry point for the console application.
 //
 #include <string>
+#include <map>
 #include <cstdlib>
 #include <pthread.h>
 #include <mutex>
 #include <condition_variable>
-
 #include "OCPlatform.h"
 #include "OCApi.h"
 
 using namespace OC;
 
+typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap;
+
+DiscoveredResourceMap discoveredResources;
 std::shared_ptr<OCResource> curResource;
 static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+std::mutex curResourceLock;
 
 class Light
 {
@@ -58,112 +62,134 @@ int observe_count()
 void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
                     const int& eCode, const int& sequenceNumber)
 {
-    if(eCode == OC_STACK_OK)
+    try
     {
-        std::cout << "OBSERVE RESULT:"<<std::endl;
-        std::cout << "\tSequenceNumber: "<< sequenceNumber << endl;
+        if(eCode == OC_STACK_OK)
+        {
+            std::cout << "OBSERVE RESULT:"<<std::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);
 
-        rep.getValue("state", mylight.m_state);
-        rep.getValue("power", mylight.m_power);
-        rep.getValue("name", mylight.m_name);
+            std::cout << "\tstate: " << mylight.m_state << std::endl;
+            std::cout << "\tpower: " << mylight.m_power << std::endl;
+            std::cout << "\tname: " << mylight.m_name << std::endl;
 
-        std::cout << "\tstate: " << mylight.m_state << std::endl;
-        std::cout << "\tpower: " << mylight.m_power << std::endl;
-        std::cout << "\tname: " << mylight.m_name << std::endl;
+            if(observe_count() > 10)
+            {
+                std::cout<<"Cancelling Observe..."<<std::endl;
+                OCStackResult result = curResource->cancelObserve();
 
-        if(observe_count() > 30)
+                std::cout << "Cancel result: "<< result <<std::endl;
+                sleep(10);
+                std::cout << "DONE"<<std::endl;
+                std::exit(0);
+            }
+        }
+        else
         {
-            std::cout<<"Cancelling Observe..."<<std::endl;
-            OCStackResult result = curResource->cancelObserve();
-
-            std::cout << "Cancel result: "<< result <<std::endl;
-            sleep(10);
-            std::cout << "DONE"<<std::endl;
-            std::exit(0);
+            std::cout << "onObserve Response error: " << eCode << std::endl;
+            std::exit(-1);
         }
     }
-    else
+    catch(std::exception& e)
     {
-        std::cout << "onObserve Response error: " << eCode << std::endl;
-        std::exit(-1);
+        std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;
     }
+
 }
 
 void onPost2(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
+    try
     {
-        std::cout << "POST request was successful" << std::endl;
-
-        if(rep.hasAttribute("createduri"))
-        {
-            std::cout << "\tUri of the created resource: "
-                      << rep.getValue<std::string>("createduri") << std::endl;
-        }
-        else
+        if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
         {
-            rep.getValue("state", mylight.m_state);
-            rep.getValue("power", mylight.m_power);
-            rep.getValue("name", mylight.m_name);
+            std::cout << "POST request was successful" << std::endl;
 
-            std::cout << "\tstate: " << mylight.m_state << std::endl;
-            std::cout << "\tpower: " << mylight.m_power << std::endl;
-            std::cout << "\tname: " << mylight.m_name << std::endl;
-        }
+            if(rep.hasAttribute("createduri"))
+            {
+                std::cout << "\tUri of the created resource: "
+                    << rep.getValue<std::string>("createduri") << std::endl;
+            }
+            else
+            {
+                rep.getValue("state", mylight.m_state);
+                rep.getValue("power", mylight.m_power);
+                rep.getValue("name", mylight.m_name);
 
-        if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
-            std::cout << endl << "Observe is used." << endl << endl;
-        else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
-            std::cout << endl << "ObserveAll is used." << endl << endl;
+                std::cout << "\tstate: " << mylight.m_state << std::endl;
+                std::cout << "\tpower: " << mylight.m_power << std::endl;
+                std::cout << "\tname: " << mylight.m_name << std::endl;
+            }
+
+            if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
+                std::cout << std::endl << "Observe is used." << std::endl << std::endl;
+            else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
+                std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
 
-        curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
+            curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
 
+        }
+        else
+        {
+            std::cout << "onPost2 Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
     }
-    else
+    catch(std::exception& e)
     {
-        std::cout << "onPost2 Response error: " << eCode << std::endl;
-        std::exit(-1);
+        std::cout << "Exception: " << e.what() << " in onPost2" << std::endl;
     }
+
 }
 
 void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
+    try
     {
-        std::cout << "POST request was successful" << std::endl;
-
-        if(rep.hasAttribute("createduri"))
-        {
-            std::cout << "\tUri of the created resource: "
-                      << rep.getValue<std::string>("createduri") << std::endl;
-        }
-        else
+        if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
         {
-            rep.getValue("state", mylight.m_state);
-            rep.getValue("power", mylight.m_power);
-            rep.getValue("name", mylight.m_name);
+            std::cout << "POST request was successful" << std::endl;
 
-            std::cout << "\tstate: " << mylight.m_state << std::endl;
-            std::cout << "\tpower: " << mylight.m_power << std::endl;
-            std::cout << "\tname: " << mylight.m_name << std::endl;
-        }
+            if(rep.hasAttribute("createduri"))
+            {
+                std::cout << "\tUri of the created resource: "
+                    << rep.getValue<std::string>("createduri") << std::endl;
+            }
+            else
+            {
+                rep.getValue("state", mylight.m_state);
+                rep.getValue("power", mylight.m_power);
+                rep.getValue("name", mylight.m_name);
+
+                std::cout << "\tstate: " << mylight.m_state << std::endl;
+                std::cout << "\tpower: " << mylight.m_power << std::endl;
+                std::cout << "\tname: " << mylight.m_name << std::endl;
+            }
 
-        OCRepresentation rep2;
+            OCRepresentation rep2;
 
-        std::cout << "Posting light representation..."<<std::endl;
+            std::cout << "Posting light representation..."<<std::endl;
 
-        mylight.m_state = true;
-        mylight.m_power = 55;
+            mylight.m_state = true;
+            mylight.m_power = 55;
 
-        rep2.setValue("state", mylight.m_state);
-        rep2.setValue("power", mylight.m_power);
+            rep2.setValue("state", mylight.m_state);
+            rep2.setValue("power", mylight.m_power);
 
-        curResource->post(rep2, QueryParamsMap(), &onPost2);
+            curResource->post(rep2, QueryParamsMap(), &onPost2);
+        }
+        else
+        {
+            std::cout << "onPost Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
     }
-    else
+    catch(std::exception& e)
     {
-        std::cout << "onPost Response error: " << eCode << std::endl;
-        std::exit(-1);
+        std::cout << "Exception: " << e.what() << " in onPost" << std::endl;
     }
 }
 
@@ -190,24 +216,31 @@ void postLightRepresentation(std::shared_ptr<OCResource> resource)
 // callback handler on PUT request
 void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    if(eCode == OC_STACK_OK)
+    try
     {
-        std::cout << "PUT request was successful" << std::endl;
+        if(eCode == OC_STACK_OK)
+        {
+            std::cout << "PUT request was successful" << std::endl;
 
-        rep.getValue("state", mylight.m_state);
-        rep.getValue("power", mylight.m_power);
-        rep.getValue("name", mylight.m_name);
+            rep.getValue("state", mylight.m_state);
+            rep.getValue("power", mylight.m_power);
+            rep.getValue("name", mylight.m_name);
 
-        std::cout << "\tstate: " << mylight.m_state << std::endl;
-        std::cout << "\tpower: " << mylight.m_power << std::endl;
-        std::cout << "\tname: " << mylight.m_name << std::endl;
+            std::cout << "\tstate: " << mylight.m_state << std::endl;
+            std::cout << "\tpower: " << mylight.m_power << std::endl;
+            std::cout << "\tname: " << mylight.m_name << std::endl;
 
-        postLightRepresentation(curResource);
+            postLightRepresentation(curResource);
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
     }
-    else
+    catch(std::exception& e)
     {
-        std::cout << "onPut Response error: " << eCode << std::endl;
-        std::exit(-1);
+        std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
     }
 }
 
@@ -234,25 +267,32 @@ void putLightRepresentation(std::shared_ptr<OCResource> resource)
 // Callback handler on GET request
 void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    if(eCode == OC_STACK_OK)
+    try
     {
-        std::cout << "GET request was successful" << std::endl;
-        std::cout << "Resource URI: " << rep.getUri() << std::endl;
+        if(eCode == OC_STACK_OK)
+        {
+            std::cout << "GET request was successful" << std::endl;
+            std::cout << "Resource URI: " << rep.getUri() << std::endl;
 
-        rep.getValue("state", mylight.m_state);
-        rep.getValue("power", mylight.m_power);
-        rep.getValue("name", mylight.m_name);
+            rep.getValue("state", mylight.m_state);
+            rep.getValue("power", mylight.m_power);
+            rep.getValue("name", mylight.m_name);
 
-        std::cout << "\tstate: " << mylight.m_state << std::endl;
-        std::cout << "\tpower: " << mylight.m_power << std::endl;
-        std::cout << "\tname: " << mylight.m_name << std::endl;
+            std::cout << "\tstate: " << mylight.m_state << std::endl;
+            std::cout << "\tpower: " << mylight.m_power << std::endl;
+            std::cout << "\tname: " << mylight.m_name << std::endl;
 
-        putLightRepresentation(curResource);
+            putLightRepresentation(curResource);
+        }
+        else
+        {
+            std::cout << "onGET Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
     }
-    else
+    catch(std::exception& e)
     {
-        std::cout << "onGET Response error: " << eCode << std::endl;
-        std::exit(-1);
+        std::cout << "Exception: " << e.what() << " in onGet" << std::endl;
     }
 }
 
@@ -272,15 +312,31 @@ void getLightRepresentation(std::shared_ptr<OCResource> resource)
 // Callback to found resources
 void foundResource(std::shared_ptr<OCResource> resource)
 {
-    if(curResource)
-    {
-        std::cout << "Found another resource, ignoring"<<std::endl;
-    }
-
+    std::cout << "In foundResource\n";
     std::string resourceURI;
     std::string hostAddress;
     try
     {
+        {
+            std::lock_guard<std::mutex> lock(curResourceLock);
+            if(discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())
+            {
+                std::cout << "Found resource " << resource->uniqueIdentifier() <<
+                    " for the first time on server with ID: "<< resource->sid()<<std::endl;
+                discoveredResources[resource->uniqueIdentifier()] = 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)
         {
@@ -323,36 +379,63 @@ void foundResource(std::shared_ptr<OCResource> resource)
     }
     catch(std::exception& e)
     {
-        //log(e.what());
+        std::cerr << "Exception in foundResource: "<< e.what() << std::endl;
     }
 }
 
-void PrintUsage()
+void printUsage()
 {
     std::cout << std::endl;
+    std::cout << "---------------------------------------------------------------------\n";
     std::cout << "Usage : simpleclient <ObserveType>" << std::endl;
     std::cout << "   ObserveType : 1 - Observe" << std::endl;
     std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
+    std::cout << "---------------------------------------------------------------------\n\n";
 }
 
-int main(int argc, char* argv[]) {
-    if (argc == 1)
+void checkObserverValue(int value)
+{
+    if (value == 1)
     {
         OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+        std::cout << "<===Setting ObserveType to Observe===>\n\n";
     }
-    else if (argc == 2)
+    else if (value == 2)
     {
-        int value = atoi(argv[1]);
-        if (value == 1)
-            OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-        else if (value == 2)
-            OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
-        else
-            OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+        OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
+        std::cout << "<===Setting ObserveType to ObserveAll===>\n\n";
     }
     else
     {
-        PrintUsage();
+        std::cout << "<===Invalid ObserveType selected."
+                  <<" Setting ObserveType to Observe===>\n\n";
+    }
+}
+
+int main(int argc, char* argv[]) {
+
+    std::ostringstream requestURI;
+
+    try
+    {
+        printUsage();
+        if (argc == 1)
+        {
+            std::cout << "<===Setting ObserveType to Observe and ConnectivityType to IPv4===>\n\n";
+        }
+        else if (argc == 2)
+        {
+            checkObserverValue(std::stoi(argv[1]));
+        }
+        else
+        {
+            std::cout << "<===Invalid number of command line arguments===>\n\n";
+            return -1;
+        }
+    }
+    catch(std::exception& )
+    {
+        std::cout << "<===Invalid input arguments===>\n\n";
         return -1;
     }
 
@@ -371,9 +454,19 @@ int main(int argc, char* argv[]) {
         // makes it so that all boolean values are printed as 'true/false' in this stream
         std::cout.setf(std::ios::boolalpha);
         // Find all resources
-        OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResource);
+        requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
+
+        OCPlatform::findResource("", requestURI.str(),
+                OC_ALL, &foundResource);
         std::cout<< "Finding Resource... " <<std::endl;
 
+        // Find resource is done twice so that we discover the original resources a second time.
+        // These resources will have the same uniqueidentifier (yet be different objects), so that
+        // we can verify/show the duplicate-checking code in foundResource(above);
+        OCPlatform::findResource("", requestURI.str(),
+                OC_ALL, &foundResource);
+        std::cout<< "Finding Resource for second time..." << std::endl;
+
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
         // don't ever call cv.notify, this should be a non-processor intensive version
@@ -385,9 +478,10 @@ int main(int argc, char* argv[]) {
 
     }catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<<e.what();
     }
 
     return 0;
 }
 
+
index e3a6f2c..af0bea4 100644 (file)
 
 // OCClient.cpp : Defines the entry point for the console application.
 //
+#include <set>
 #include <string>
 #include <cstdlib>
 #include <pthread.h>
 #include <mutex>
 #include <condition_variable>
-
 #include "OCPlatform.h"
 #include "OCApi.h"
 
 using namespace OC;
 
+struct dereference_compare
+{
+    bool operator()(std::shared_ptr<OCResource> lhs, std::shared_ptr<OCResource> rhs )const
+    {
+        return *lhs < *rhs;
+    }
+};
+typedef std::set<std::shared_ptr<OCResource>, dereference_compare> DiscoveredResourceSet;
+
+DiscoveredResourceSet discoveredResources;
 const int SUCCESS_RESPONSE = 0;
 std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
 static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
 
 class Light
@@ -62,20 +73,20 @@ void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
     if(eCode == SUCCESS_RESPONSE)
     {
         std::cout << "OBSERVE RESULT:"<<std::endl;
-        if(sequenceNumber == 0)
+        if(sequenceNumber == (int) ObserveAction::ObserveRegister)
         {
-            std::cout << "\tObserve Registration Confirmed: "<< endl;
+            std::cout << "\tObserve Registration Confirmed: "<< std::endl;
         }
-        else if (sequenceNumber == 1)
+        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);
@@ -86,7 +97,7 @@ void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
         std::cout << "\tpower: " << mylight.m_power << std::endl;
         std::cout << "\tname: " << mylight.m_name << std::endl;
 
-        if(observe_count() > 30)
+        if(observe_count() > 10)
         {
             std::cout<<"Cancelling Observe..."<<std::endl;
             OCStackResult result = curResource->cancelObserve(OC::QualityOfService::HighQos);
@@ -124,9 +135,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::HighQos);
@@ -285,11 +296,6 @@ void getLightRepresentation(std::shared_ptr<OCResource> resource)
 // Callback to found resources
 void foundResource(std::shared_ptr<OCResource> resource)
 {
-    if(curResource)
-    {
-        std::cout << "Found another resource, ignoring"<<std::endl;
-    }
-
     std::string resourceURI;
     std::string hostAddress;
     try
@@ -297,6 +303,25 @@ void foundResource(std::shared_ptr<OCResource> resource)
         // 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();
@@ -324,7 +349,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);
             }
         }
@@ -337,37 +363,53 @@ void foundResource(std::shared_ptr<OCResource> resource)
     }
     catch(std::exception& e)
     {
-        //log(e.what());
+        std::cerr << "Exception in foundResource: "<< e.what() <<std::endl;
     }
 }
 
 void PrintUsage()
 {
     std::cout << std::endl;
-    std::cout << "Usage : simpleclient <ObserveType>" << std::endl;
+    std::cout << "Usage : simpleclientHQ <ObserveType>" << std::endl;
     std::cout << "   ObserveType : 1 - Observe" << std::endl;
     std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
 }
 
 int main(int argc, char* argv[]) {
-    if (argc == 1)
-    {
-        OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-    }
-    else if (argc == 2)
+
+    std::ostringstream requestURI;
+
+    try
     {
-        int value = atoi(argv[1]);
-        if (value == 1)
+        if (argc == 1)
+        {
             OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-        else if (value == 2)
-            OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
+        }
+        else if (argc == 2)
+        {
+            int value = std::stoi(argv[1]);
+            if (value == 1)
+            {
+                OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+            }
+            else if (value == 2)
+            {
+                OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
+            }
+            else
+            {
+                OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+            }
+        }
         else
-            OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+        {
+            PrintUsage();
+            return -1;
+        }
     }
-    else
+    catch(std::exception&)
     {
-        PrintUsage();
-        return -1;
+        std::cout << "Invalid input argument. Using Observe as observe type" << std::endl;
     }
 
     // Create PlatformConfig object
@@ -376,7 +418,7 @@ int main(int argc, char* argv[]) {
         OC::ModeType::Client,
         "0.0.0.0",
         0,
-        OC::QualityOfService::LowQos
+        OC::QualityOfService::HighQos
     };
 
     OCPlatform::Configure(cfg);
@@ -384,10 +426,19 @@ int main(int argc, char* argv[]) {
     try
     {
         // Find all resources
-        OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResource,
-                OC::QualityOfService::LowQos);
+        requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
+
+        OCPlatform::findResource("", requestURI.str(),
+                OC_ALL, &foundResource, OC::QualityOfService::LowQos);
         std::cout<< "Finding Resource... " <<std::endl;
 
+        // Find resource is done twice so that we discover the original resources a second time.
+        // These resources will have the same uniqueidentifier (yet be different objects), so that
+        // we can verify/show the duplicate-checking code in foundResource(above);
+        OCPlatform::findResource("", requestURI.str(),
+                OC_ALL, &foundResource, OC::QualityOfService::LowQos);
+        std::cout<< "Finding Resource for second time... " <<std::endl;
+
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
         // don't ever call cv.notify, this should be a non-processor intensive version
@@ -397,11 +448,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 d3ee18b..f4282a3 100644 (file)
 #include "OCApi.h"
 using namespace OC;
 
+
 class ClientWorker
 {
 private:
-    bool m_isFoo;
-    int m_barCount;
     void putResourceInfo(const HeaderOptions& headerOptions,
             const OCRepresentation rep, const OCRepresentation rep2, const int eCode)
     {
@@ -142,13 +141,20 @@ private:
     }
 
 public:
+    ClientWorker(OCConnectivityType ct):m_connectivityType{ct}
+    {}
+
     void start()
     {
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_DISCOVERY_URI << "?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("", "coap://224.0.1.187/oc/core?rt=core.foo", f)
-            << std::endl;
+        OCPlatform::findResource("", requestURI.str(), OC_ALL, f)
+        << std::endl;
+
         std::cout<<"Finding Resource..."<<std::endl;
 
         {
@@ -161,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
@@ -269,11 +278,7 @@ struct FooResource
             {
                 std::cout <<"\t\trequestFlag : UNSUPPORTED: ";
 
-                if(request->getRequestHandlerFlag()==RequestHandlerFlag::InitFlag)
-                {
-                    std::cout<<"InitFlag"<<std::endl;
-                }
-                else if(request->getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag)
+                if(request->getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag)
                 {
                     std::cout<<"ObserverFlag"<<std::endl;
                 }
@@ -289,8 +294,54 @@ struct FooResource
 
 };
 
-int main()
+int main(int argc, char* argv[])
 {
+    OCConnectivityType connectivityType = OC_IPV4;
+
+    if(argc == 2)
+    {
+        try
+        {
+            std::size_t inputValLen;
+            int optionSelected = std::stoi(argv[1], &inputValLen);
+
+            if(inputValLen == strlen(argv[1]))
+            {
+                if(optionSelected == 0)
+                {
+                    connectivityType = OC_IPV4;
+                }
+                else if(optionSelected == 1)
+                {
+                    // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
+                    // connectivityType = OC_IPV6;
+                    connectivityType = OC_IPV4;
+                    std::cout << "IPv6 not currently supported. Using default IPv4" << std::endl;
+                }
+                else
+                {
+                    std::cout << "Invalid connectivity type selected. Using default IPv4"
+                    << std::endl;
+                }
+            }
+            else
+            {
+                std::cout << "Invalid connectivity type selected. Using default IPv4" << std::endl;
+            }
+        }
+        catch(std::exception& )
+        {
+            std::cout << "Invalid input argument. Using IPv4 as connectivity type" << std::endl;
+        }
+    }
+    else
+    {
+        std::cout<< "Usage simpleclientserver <ConnectivityType(0|1)>" << std::endl;
+        std::cout<< "    ConnectivityType: Default IPv4" << std::endl;
+        std::cout << "   ConnectivityType : 0 - IPv4" << std::endl;
+        std::cout << "   ConnectivityType : 1 - IPv6 (not currently supported)" << std::endl;
+    }
+
     PlatformConfig cfg {
         OC::ServiceType::InProc,
         OC::ModeType::Both,
@@ -310,7 +361,7 @@ int main()
             return -1;
         }
 
-        ClientWorker cw;
+        ClientWorker cw(connectivityType);
         cw.start();
     }
     catch(OCException& e)
@@ -320,3 +371,4 @@ int main()
 
     return 0;
 }
+
index 86b1546..f52588b 100644 (file)
@@ -74,7 +74,8 @@ public:
 public:
     /// Constructor
     LightResource()
-        :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light") {
+        :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light"),
+                m_resourceHandle(nullptr) {
         // Initialize representation
         m_lightRep.setUri(m_lightUri);
 
@@ -89,9 +90,12 @@ public:
     /// This function internally calls registerResource API.
     void createResource()
     {
-        std::string resourceURI = m_lightUri; //URI of the resource
-        std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
-        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+        //URI of the resource
+        std::string resourceURI = m_lightUri;
+        //resource type name. In this case, it is light
+        std::string resourceTypeName = "core.light";
+        // resource interface.
+        std::string resourceInterface = DEFAULT_INTERFACE;
 
         // OCResourceProperty is defined ocstack.h
         uint8_t resourceProperty;
@@ -118,9 +122,12 @@ public:
 
     OCStackResult createResource1()
     {
-        std::string resourceURI = "/a/light1"; // URI of the resource
-        std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
-        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+        // URI of the resource
+        std::string resourceURI = "/a/light1";
+        // resource type name. In this case, it is light
+        std::string resourceTypeName = "core.light";
+        // resource interface.
+        std::string resourceInterface = DEFAULT_INTERFACE;
 
         // OCResourceProperty is defined ocstack.h
         uint8_t resourceProperty;
@@ -255,12 +262,6 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
         if(requestFlag & RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
@@ -268,6 +269,19 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
             pResponse->setRequestHandle(request->getRequestHandle());
             pResponse->setResourceHandle(request->getResourceHandle());
 
+            // Check for query params (if any)
+            QueryParamsMap queries = request->getQueryParameters();
+
+            if (!queries.empty())
+            {
+                std::cout << "\nQuery processing upto entityHandler" << std::endl;
+            }
+            for (auto it : queries)
+            {
+                std::cout << "Query key: " << it.first << " value : " << it.second
+                        << std:: endl;
+            }
+
             // If the request type is GET
             if(requestType == "GET")
             {
@@ -325,6 +339,10 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
                     pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
                     pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
                 }
+                else
+                {
+                    pResponse->setResponseResult(OC_EH_OK);
+                }
 
                 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                 {
@@ -333,7 +351,7 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
             }
             else if(requestType == "DELETE")
             {
-                // DELETE request operations
+                cout << "Delete request received" << endl;
             }
         }
 
@@ -389,7 +407,7 @@ void * ChangeLightRepresentation (void *param)
     // This function continuously monitors for the changes
     while (1)
     {
-        sleep (5);
+        sleep (3);
 
         if (gObservation)
         {
@@ -406,7 +424,8 @@ void * ChangeLightRepresentation (void *param)
 
             if(isListOfObservers)
             {
-                std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+                std::shared_ptr<OCResourceResponse> resourceResponse =
+                            {std::make_shared<OCResourceResponse>()};
 
                 resourceResponse->setErrorCode(200);
                 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
@@ -492,6 +511,7 @@ int main(int argc, char* argv[])
                 break;
             case 4:
                 isSlowResponse = true;
+                break;
             default:
                 break;
        }
@@ -519,9 +539,12 @@ int main(int argc, char* argv[])
 
         // Invoke createResource function of class light.
         myLight.createResource();
+        std::cout << "Created resource." << std::endl;
 
         myLight.addType(std::string("core.brightlight"));
-        myLight.addInterface(std::string("oc.mi.ll"));
+        myLight.addInterface(std::string(LINK_INTERFACE));
+        std::cout << "Added Interface and Type" << std::endl;
+
 
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
@@ -530,11 +553,12 @@ int main(int argc, char* argv[])
         std::mutex blocker;
         std::condition_variable cv;
         std::unique_lock<std::mutex> lock(blocker);
-        cv.wait(lock);
+        std::cout <<"Waiting" << std::endl;
+        cv.wait(lock, []{return false;});
     }
-    catch(OCException e)
+    catch(OCException &e)
     {
-        //log(e.what());
+        std::cout << "OCException in main : " << e.what() << endl;
     }
 
     // No explicit call to stop the platform.
index cf0d09a..492968c 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
@@ -265,11 +266,6 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-            // entity handler to perform resource initialization operations
-        }
         if(requestFlag & RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
@@ -362,7 +358,7 @@ void * ChangeLightRepresentation (void *param)
     // This function continuously monitors for the changes
     while (1)
     {
-        sleep (5);
+        sleep (3);
 
         if (gObservation)
         {
@@ -379,7 +375,8 @@ void * ChangeLightRepresentation (void *param)
 
             if(isListOfObservers)
             {
-                std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+                std::shared_ptr<OCResourceResponse> resourceResponse =
+                            std::make_shared<OCResourceResponse>();
 
                 resourceResponse->setErrorCode(200);
                 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
@@ -410,7 +407,7 @@ void * ChangeLightRepresentation (void *param)
 void PrintUsage()
 {
     std::cout << std::endl;
-    std::cout << "Usage : simplserver <isListOfObservers>\n";
+    std::cout << "Usage : simpleserverHQ <ObserveType>\n";
     std::cout << "   ObserveType : 0 - Observe All\n";
     std::cout << "   ObserveType : 1 - Observe List of observers\n\n";
 }
@@ -450,14 +447,15 @@ 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.
         myLight.createResource();
 
         myLight.addType(std::string("core.brightlight"));
-        myLight.addInterface(std::string("oc.mi.ll"));
+        myLight.addInterface(std::string(LINK_INTERFACE));
 
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
@@ -466,11 +464,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 +476,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index ff556e2..e1332c8 100644 (file)
 #include <condition_variable>
 #include <map>
 #include <vector>
+
 #include "OCPlatform.h"
 #include "OCApi.h"
 using namespace OC;
 
+static std::ostringstream requestURI;
 
 struct FooResource
 {
@@ -139,11 +141,7 @@ struct FooResource
             {
                 std::cout <<"\t\trequestFlag : UNSUPPORTED: ";
 
-                if(request->getRequestHandlerFlag()==RequestHandlerFlag::InitFlag)
-                {
-                    std::cout<<"InitFlag"<<std::endl;
-                }
-                else if(request->getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag)
+                if(request->getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag)
                 {
                     std::cout<<"ObserverFlag"<<std::endl;
                 }
@@ -280,9 +278,8 @@ void foundResource1(std::shared_ptr<OCResource> resource)
 void client1()
 {
     std::cout << "in client1\n";
-
-    std::cout<<"result1:" << OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.foo",
-            foundResource1)<< std::endl;
+    std::cout<<"result1:" << OCPlatform::findResource("", requestURI.str(),
+            OC_ALL, foundResource1)<< std::endl;
 
     // A condition variable will free the mutex it is given, then do a non-
     // intensive block until 'notify' is called on it.  In this case, since we
@@ -297,10 +294,9 @@ void client1()
 void client2()
 {
     std::cout << "in client2\n";
-
     std::cout<<"result2:" << OCPlatform::findResource("",
-                "coap://224.0.1.187/oc/core?rt=core.foo",
-                foundResource2)<< std::endl;
+                requestURI.str(),
+                OC_ALL, foundResource2)<< std::endl;
 
     // A condition variable will free the mutex it is given, then do a non-
     // intensive block until 'notify' is called on it.  In this case, since we
@@ -331,8 +327,11 @@ void server()
     cv.wait(lock);
 }
 
-int main()
+int main(int argc, char* argv[])
 {
+
+    requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.foo";
+
     PlatformConfig cfg {
         OC::ServiceType::InProc,
         OC::ModeType::Both,
@@ -382,3 +381,4 @@ int main()
 
     return 0;
 }
+
index 5d0d524..327bf13 100644 (file)
@@ -1,4 +1,3 @@
-
 //******************************************************************
 //
 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file AttributeValue.h
-
-/// @brief  This file contains the definition of the internally used
-// type AttributeValue
+/**
+ * @file
+ *
+ * This file contains the definition of the internally used type
+ * AttributeValue.
+ */
 
 #ifndef __ATTRIBUTEVALUE_H
 #define __ATTRIBUTEVALUE_H
 #define BOOST_MPL_LIMIT_LIST_SIZE 30
 #define BOOST_MPL_LIMIT_VECTOR_SIZE 30
 #include <boost/variant.hpp>
-
+#include <iosfwd>
+#include <OCUtilities.h>
 namespace OC
 {
     class OCRepresentation;
 
     struct NullType{};
+
     // Since null needs to be encoded in a special fashion in JSON, the encoder
     // needs to know the index of the NullType Sentinel  Any time the code does a special
     // case for the NullType, we use the AttributeValueNullIndex.  This MUST be kept up to date
     // with the variant's which() for NullType.
     static const int AttributeValueNullIndex = 0;
     typedef boost::variant<
-
-        // Base values:
         NullType, // Note: this handles the null-type and must match the above static const
         int,
         double,
@@ -78,5 +79,56 @@ namespace OC
         std::vector<std::vector<std::vector<OC::OCRepresentation>>>
     > AttributeValue;
 
+    enum class AttributeType
+    {
+        Null,
+        Integer,
+        Double,
+        Boolean,
+        String,
+        OCRepresentation,
+        Vector
+    };
+
+    template<typename T>
+    struct AttributeTypeConvert{};
+
+    template<>
+    struct AttributeTypeConvert<NullType>
+    {
+        constexpr static AttributeType type = AttributeType::Null;
+    };
+
+    template<>
+    struct AttributeTypeConvert<int>
+    {
+        constexpr static AttributeType type = AttributeType::Integer;
+    };
+
+    template<>
+    struct AttributeTypeConvert<double>
+    {
+        constexpr static AttributeType type = AttributeType::Double;
+    };
+
+    template<>
+    struct AttributeTypeConvert<bool>
+    {
+        constexpr static AttributeType type = AttributeType::Boolean;
+    };
+
+    template<>
+    struct AttributeTypeConvert<std::string>
+    {
+        constexpr static AttributeType type = AttributeType::String;
+    };
+
+    template<>
+    struct AttributeTypeConvert<OCRepresentation>
+    {
+        constexpr static AttributeType type = AttributeType::OCRepresentation;
+    };
+
+    std::ostream& operator << (std::ostream& os, const AttributeType at);
 }
 #endif // __ATTRIBUTEVALUE_H
index 1e40e23..7c31bde 100644 (file)
@@ -41,42 +41,49 @@ namespace OC
         {}
 
         virtual OCStackResult ListenForResource(const std::string& serviceUrl,
-                        const std::string& resourceType, FindCallback& callback,
+                        const std::string& resourceType, OCConnectivityType connectivityType,
+                        FindCallback& callback,
                         QualityOfService QoS) = 0;
 
         virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
-                        const std::string& deviceURI, FindDeviceCallback& callback,
+                        const std::string& deviceURI, OCConnectivityType connectivityType,
+                        FindDeviceCallback& callback,
                         QualityOfService QoS) = 0;
 
         virtual OCStackResult GetResourceRepresentation(const std::string& host,
-                        const std::string& uri, const QueryParamsMap& queryParams,
+                        const std::string& uri, OCConnectivityType connectivityType,
+                        const QueryParamsMap& queryParams,
                         const HeaderOptions& headerOptions,
                         GetCallback& callback, QualityOfService QoS)=0;
 
         virtual OCStackResult PutResourceRepresentation(const std::string& host,
-                        const std::string& uri, const OCRepresentation& rep,
-                        const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
+                        const std::string& uri, OCConnectivityType connectivityType,
+                        const OCRepresentation& rep, const QueryParamsMap& queryParams,
+                        const HeaderOptions& headerOptions,
                         PutCallback& callback, QualityOfService QoS) = 0;
 
         virtual OCStackResult PostResourceRepresentation(const std::string& host,
-                        const std::string& uri, const OCRepresentation& rep,
-                        const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
+                        const std::string& uri, OCConnectivityType connectivityType,
+                        const OCRepresentation& rep, const QueryParamsMap& queryParams,
+                        const HeaderOptions& headerOptions,
                         PostCallback& callback, QualityOfService QoS) = 0;
 
         virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri,
-                        const HeaderOptions& headerOptions, DeleteCallback& callback,
-                        QualityOfService QoS) = 0;
+                        OCConnectivityType connectivityType, const HeaderOptions& headerOptions,
+                        DeleteCallback& callback, QualityOfService QoS) = 0;
 
         virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle,
                         const std::string& host, const std::string& uri,
-                        const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
-                        ObserveCallback& callback, QualityOfService QoS)=0;
+                        OCConnectivityType connectivityType, const QueryParamsMap& queryParams,
+                        const HeaderOptions& headerOptions, ObserveCallback& callback,
+                        QualityOfService QoS)=0;
 
         virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host,
             const std::string& uri, const HeaderOptions& headerOptions, QualityOfService QoS)=0;
 
         virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host,
-                        const std::string& resourceType, SubscribeCallback& presenceHandler)=0;
+                        const std::string& resourceType, OCConnectivityType connectivityType,
+                        SubscribeCallback& presenceHandler)=0;
 
         virtual OCStackResult UnsubscribePresence(OCDoHandle handle) =0;
 
@@ -87,3 +94,4 @@ namespace OC
 }
 
 #endif
+
index c6c0b2d..ef45485 100644 (file)
@@ -54,6 +54,9 @@ namespace OC
         virtual OCStackResult registerDeviceInfo(
                     const OCDeviceInfo deviceInfo) = 0;
 
+        virtual OCStackResult registerPlatformInfo(
+                    const OCPlatformInfo PlatformInfo) = 0;
+
         virtual OCStackResult registerResourceWithHost(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceHOST,
index ced111d..9b7b95c 100644 (file)
@@ -84,40 +84,43 @@ namespace OC
         virtual ~InProcClientWrapper();
 
         virtual OCStackResult ListenForResource(const std::string& serviceUrl,
-            const std::string& resourceType, FindCallback& callback,
-            QualityOfService QoS);
+            const std::string& resourceType, OCConnectivityType connectivityType,
+            FindCallback& callback, QualityOfService QoS);
 
         virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
-            const std::string& deviceURI, FindDeviceCallback& callback,
-            QualityOfService QoS);
+            const std::string& deviceURI, OCConnectivityType connectivityType,
+            FindDeviceCallback& callback, QualityOfService QoS);
 
         virtual OCStackResult GetResourceRepresentation(const std::string& host,
-            const std::string& uri, const QueryParamsMap& queryParams,
-            const HeaderOptions& headerOptions,
+            const std::string& uri, OCConnectivityType connectivityType,
+            const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
             GetCallback& callback, QualityOfService QoS);
 
         virtual OCStackResult PutResourceRepresentation(const std::string& host,
-            const std::string& uri, const OCRepresentation& attributes,
-            const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
-            PutCallback& callback, QualityOfService QoS);
+            const std::string& uri, OCConnectivityType connectivityType,
+            const OCRepresentation& attributes, const QueryParamsMap& queryParams,
+            const HeaderOptions& headerOptions, PutCallback& callback, QualityOfService QoS);
 
         virtual OCStackResult PostResourceRepresentation(const std::string& host,
-            const std::string& uri, const OCRepresentation& attributes,
-            const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
-            PostCallback& callback, QualityOfService QoS);
+            const std::string& uri, OCConnectivityType connectivityType,
+            const OCRepresentation& attributes, const QueryParamsMap& queryParams,
+            const HeaderOptions& headerOptions, PostCallback& callback, QualityOfService QoS);
 
         virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri,
-             const HeaderOptions& headerOptions, DeleteCallback& callback, QualityOfService QoS);
+            OCConnectivityType connectivityType, const HeaderOptions& headerOptions,
+            DeleteCallback& callback, QualityOfService QoS);
 
         virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle,
-            const std::string& host, const std::string& uri, const QueryParamsMap& queryParams,
-            const HeaderOptions& headerOptions, ObserveCallback& callback, QualityOfService QoS);
+            const std::string& host, const std::string& uri, OCConnectivityType connectivityType,
+            const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
+            ObserveCallback& callback, QualityOfService QoS);
 
         virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host,
             const std::string& uri, const HeaderOptions& headerOptions, QualityOfService QoS);
 
         virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host,
-            const std::string& resourceType, SubscribeCallback& presenceHandler);
+            const std::string& resourceType, OCConnectivityType connectivityType,
+            SubscribeCallback& presenceHandler);
 
         virtual OCStackResult UnsubscribePresence(OCDoHandle handle);
         OCStackResult GetDefaultQos(QualityOfService& QoS);
@@ -125,8 +128,8 @@ namespace OC
         void listeningFunc();
         std::string assembleSetResourceUri(std::string uri, const QueryParamsMap& queryParams);
         std::string assembleSetResourcePayload(const OCRepresentation& attributes);
-        void assembleHeaderOptions(OCHeaderOption options[],
-            const HeaderOptions& headerOptions);
+        OCHeaderOption* assembleHeaderOptions(OCHeaderOption options[],
+           const HeaderOptions& headerOptions);
         std::thread m_listeningThread;
         bool m_threadRun;
         std::weak_ptr<std::recursive_mutex> m_csdkLock;
@@ -137,3 +140,4 @@ namespace OC
 }
 
 #endif
+
index b68f599..1a9192a 100644 (file)
@@ -48,6 +48,9 @@ namespace OC
         virtual OCStackResult registerDeviceInfo(
                     const OCDeviceInfo deviceInfo);
 
+        virtual OCStackResult registerPlatformInfo(
+                    const OCPlatformInfo PlatformInfo);
+
         virtual OCStackResult registerResourceWithHost(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceHOST,
index c6eed56..f87972f 100644 (file)
 
 namespace OC
 {
-    class InitializeException : public std::exception
+    class InitializeException : public OC::OCException
     {
     public:
-        InitializeException(const std::string& msg, OCStackResult reasonCode): m_errorMessage(msg), m_reason(reasonCode)
+        InitializeException(const std::string& msg, OCStackResult reasonCode):
+            OC::OCException(msg, reasonCode)
         {
         }
-
-        OCStackResult ReasonCode()
-        {
-            return m_reason;
-        }
-
-        std::string Message()
-        {
-            return m_errorMessage;
-        }
-
-        std::string Reason()
-        {
-            switch(m_reason)
-            {
-            case OC_STACK_OK:
-                return OC::InitException::NO_ERROR;
-            case OC_STACK_INVALID_URI:
-                return OC::InitException::INVALID_URI;
-            case OC_STACK_INVALID_IP:
-                return OC::InitException::INVALID_IP;
-            case OC_STACK_INVALID_PORT:
-                return OC::InitException::INVALID_PORT;
-            case OC_STACK_INVALID_CALLBACK:
-                return OC::InitException::INVALID_CB;
-            case OC_STACK_INVALID_METHOD:
-                return OC::InitException::INVALID_METHOD;
-            case OC_STACK_ERROR:
-                return OC::InitException::GENERAL_FAULT;
-            default:
-                return OC::InitException::UNKNOWN_ERROR;
-            }
-        }
-
-    private:
-        const std::string& m_errorMessage;
-        OCStackResult m_reason;
     };
 }
 
index ec015ee..2e7f7f7 100644 (file)
@@ -33,9 +33,15 @@ namespace std {
        unsigned long long stoull(const std::string& s);
        long double stold(const string& s);
 
-       std::string to_string(int i);
-       std::string to_string(uint32_t i);
-       std::string to_string(double d);
+       std::string to_string(int val);
+       std::string to_string(long val);
+       std::string to_string(long long val);
+       std::string to_string(unsigned val);
+       std::string to_string(unsigned long val);
+       std::string to_string(unsigned long long val);
+       std::string to_string(float val);
+       std::string to_string(double val);
+       std::string to_string(long double val);
 }
 
 #endif
index b523da5..8087a4e 100644 (file)
@@ -28,7 +28,7 @@
 #include <memory>
 #include <iterator>
 
-#include "ocstack.h"
+#include "octypes.h"
 #include "OCHeaderOption.h"
 #include <OCException.h>
 #include "StringConstants.h"
@@ -110,9 +110,9 @@ namespace OC
     *  ServiceType: indicate InProc or OutOfProc
     *  ModeType   : indicate whether we want to do server, client or both
     *  ipAddress  : ip address of server.
-    *               if you speecifiy 0.0.0.0 : it listens on any interface.
+    *               if you specify 0.0.0.0 : it listens on any interface.
     *  port       : port of server.
-    *             : if you specifiy 0 : next available random port is used.
+    *             : if you specify 0 : next available random port is used.
     *             : if you specify 5683 : client discovery can work even if they don't specify port.
     *  QoS        : Quality of Service : CONFIRMABLE or NON CONFIRMABLE.
     */
@@ -148,7 +148,6 @@ namespace OC
 
     enum RequestHandlerFlag
     {
-        InitFlag = 1 << 0,
         RequestFlag = 1 << 1,
         ObserverFlag = 1 << 2
     };
@@ -186,22 +185,24 @@ namespace OC
     // const strings for different interfaces
 
     // Default interface
-    const std::string DEFAULT_INTERFACE = "oc.mi.def";
+    const std::string DEFAULT_INTERFACE = "oic.if.baseline";
 
     // Used in discovering (GET) links to other resources of a collection.
-    const std::string LINK_INTERFACE = "oc.mi.ll";
+    const std::string LINK_INTERFACE = "oic.if.ll";
 
     // Used in GET, PUT, POST, DELETE methods on links to other resources of a collection.
-    const std::string BATCH_INTERFACE = "oc.mi.b";
+    const std::string BATCH_INTERFACE = "oic.if.b";
 
     // Used in GET, PUT, POST methods on links to other remote resources of a group.
-    const std::string GROUP_INTERFACE = "oc.mi.c";
+    const std::string GROUP_INTERFACE = "oc.mi.grp";
 
 
     typedef std::function<void(std::shared_ptr<OCResource>)> FindCallback;
 
     typedef std::function<void(const OCRepresentation&)> FindDeviceCallback;
 
+    typedef std::function<void(const OCRepresentation&)> FindPlatformCallback;
+
     typedef std::function<OCEntityHandlerResult(
                             const std::shared_ptr<OCResourceRequest>)> EntityHandler;
 
index b297a0c..2852202 100644 (file)
@@ -42,9 +42,9 @@ class OCException : public std::runtime_error
             return reason(m_reason);
         }
 
-        std::string reason(const OC::OCException& e) const
+        OCStackResult code() const
         {
-            return e.reason();
+            return m_reason;
         }
 
     private:
index 31517c5..c70ecc0 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCHeaderOption.h
-
-/// @brief  This file contains the declaration of classes and its members related to
-///         OCHeaderOption.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * OCHeaderOption.
+ */
 
 #ifndef __OCHEADEROPTION_H
 #define __OCHEADEROPTION_H
@@ -64,6 +66,16 @@ namespace OC
                 }
             }
 
+            virtual ~OCHeaderOption(){}
+
+            OCHeaderOption(const OCHeaderOption&) = default;
+
+            OCHeaderOption(OCHeaderOption&&) = default;
+
+            OCHeaderOption& operator=(const OCHeaderOption&) = default;
+
+            OCHeaderOption& operator=(OCHeaderOption&&) = default;
+
             /**
             * API to get Option ID
             * @return unsigned integer option ID
index 1cad339..53209b9 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCPlatform.h
-
-/// @brief  This file contains the declaration of classes and its members related to
-///         OCPlatform.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * OCPlatform.
+ */
 
 #ifndef __OCPLATFORM_H
 #define __OCPLATFORM_H
@@ -38,10 +40,10 @@ namespace OC
     namespace OCPlatform
     {
         /**
-         * 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
-         */
+        * 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
+        */
         void Configure(const PlatformConfig& config);
 
         // typedef for handle to cancel presence info with
@@ -95,6 +97,8 @@ namespace OC
         *        empty, performs multicast resource discovery query
         * @param resourceURI - name of the resource. If null or empty, performs search for all
         *       resource names
+        * @param connectivityType - @ref OCConnectivityType type of connectivity indicating the
+        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
         * @param handler - Handles callbacks, success states and failure states.
         *
         *        Four modes of discovery defined as follows:
@@ -115,24 +119,48 @@ namespace OC
         * NOTE: OCStackResult is defined in ocstack.h.
         */
         OCStackResult findResource(const std::string& host, const std::string& resourceURI,
-                    FindCallback resourceHandler);
+                    OCConnectivityType connectivityType, FindCallback resourceHandler);
         OCStackResult findResource(const std::string& host, const std::string& resourceURI,
-                    FindCallback resourceHandler, QualityOfService QoS);
+                    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
+        * API for Device Discovery
+        *
+        *
+        * @param host - Host IP Address. If null or empty, Multicast is performed.
+        * @param deviceURI - Uri containing address to the virtual device in C Stack
                                 ("/oc/core/d")
-         * @param QualityOfService the quality of communication
-         *
-         */
+        * @param connectivityType - @ref OCConnectivityType type of connectivity indicating the
+        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+        * @param deviceInfoHandler - device discovery callback
+        * @param QoS the quality of communication
+        *
+        */
         OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
-                    FindDeviceCallback deviceInfoHandler);
+                    OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler);
         OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
-                    FindDeviceCallback deviceInfoHandler, QualityOfService QoS);
+                    OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler,
+                    QualityOfService QoS);
+
+        /**
+        * API for Platform Discovery
+        *
+        *
+        * @param host - Host IP Address. If null or empty, Multicast is performed.
+        * @param platformURI - Uri containing address to the virtual platform in C Stack
+                                ("/oic/p")
+        * @param connectivityType - @ref OCConnectivityType type of connectivity indicating the
+        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+        * @param platformInfoHandler - platform discovery callback
+        * @param QoS the quality of communication
+        *
+        */
+        OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
+                    OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler);
+        OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
+                    OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler,
+                    QualityOfService QoS);
 
         /**
         * This API registers a resource with the server
@@ -157,7 +185,7 @@ namespace OC
         *   //192.168.1.1/oc/a/light"
         * First parameter can take a relative URI and core will take care of preparing the fully
         * qualified URI OR
-        * first paramter can take fully qualified URI and core will take that as is for further
+        * first parameter can take fully qualified URI and core will take that as is for further
         * operations
         * NOTE: OCStackResult is defined in ocstack.h.
         */
@@ -169,31 +197,40 @@ namespace OC
                         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.
-         */
+        * 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);
 
         /**
-         * Register Device Info
-         *
-         * @param deviceInfo - structure containing all the device specific information
-         *
-         * @return
-         *      OC_STACK_OK   - no errors
-         *      OC_STACK_ERROR - stack process error
-         */
-
+        * Register Device Info
+        *
+        * @param deviceInfo - structure containing all the device specific information
+        *
+        * @return
+        *      OC_STACK_OK   - no errors
+        *      OC_STACK_ERROR - stack process error
+        */
         OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo);
 
         /**
+        * Register Platform Info
+        *
+        * @param platformInfo - structure containing all the platform specific information
+        *
+        * @return
+        *      OC_STACK_OK   - no errors
+        *      OC_STACK_ERROR - stack process error
+        */
+        OCStackResult registerPlatformInfo(const OCPlatformInfo platformInfo);
+
+        /**
         * Set default device entity handler
         *
         * @param entityHandler - entity handler to handle requests for
@@ -344,6 +381,11 @@ namespace OC
         * Start Presence announcements.
         *
         * @param ttl - time to live
+        * Note: If ttl is '0', then the default stack value will be used (60 Seconds).
+        *
+        *       If ttl is greater than OC_MAX_PRESENCE_TTL_SECONDS, then the ttl will be set to
+        *       OC_MAX_PRESENCE_TTL_SECONDS.
+        *
         * @return OCStackResult - Returns OCSTACK_OK if success <br>
         *
         * Server can call this function when it comes online for the
@@ -351,7 +393,6 @@ namespace OC
         * or when it re enters network.
         *
         */
-
         OCStackResult startPresence(const unsigned int ttl);
 
         /**
@@ -363,7 +404,6 @@ namespace OC
         * going offline, or when going away from network.
         *
         */
-
         OCStackResult stopPresence();
 
         /**
@@ -375,6 +415,9 @@ namespace OC
         *               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.
+        *               This should be in the format coap://address:port
+        * @param connectivityType - @ref OCConnectivityType type of connectivity indicating the
+        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
         * @param resourceType - a resource type specified as a filter for subscription callbacks.
         * @param presenceHandler - callback function that will receive notifications/subscription
         *               events
@@ -382,9 +425,10 @@ namespace OC
         * @return OCStackResult - return value of the API.  Returns OCSTACK_OK if success <br>
         */
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
-                        SubscribeCallback presenceHandler);
+                        OCConnectivityType connectivityType, SubscribeCallback presenceHandler);
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
-                        const std::string& resourceType, SubscribeCallback presenceHandler);
+                        const std::string& resourceType, OCConnectivityType connectivityType,
+                        SubscribeCallback presenceHandler);
 
         /**
         * unsubscribes from a previously subscribed server's presence events. Note that
@@ -416,6 +460,9 @@ namespace OC
         * @param uri - the rest of the resource's URI that will permit messages to be
         *           properly routed.  Example: /a/light
         *
+        * @param connectivityType - @ref OCConnectivityType type of connectivity indicating the
+        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+        *
         * @param isObservable - a boolean containing whether the resource supports observation
         *
         * @param resourceTypes - a collection of resource types implemented by the resource
@@ -424,7 +471,8 @@ namespace OC
         * @return OCResource::Ptr - a shared pointer to the new resource object
         */
         OCResource::Ptr constructResourceObject(const std::string& host, const std::string& uri,
-                        bool isObservable, const std::vector<std::string>& resourceTypes,
+                        OCConnectivityType connectivityType, bool isObservable,
+                        const std::vector<std::string>& resourceTypes,
                         const std::vector<std::string>& interfaces);
 
         /**
@@ -441,3 +489,4 @@ namespace OC
 #endif //__OCPLATFORM_H
 
 
+
index f25ce2e..83c17bc 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCPlatform_impl.h
-
-/// @brief Implementation of the OCPlatform functionality.  It contains
-/// a singleton interface that is used only by the OCPlatform namespace and is the
-/// central entrance to the stack.
+/**
+ * @file
+ *
+ * Implementation of the OCPlatform functionality. It contains a singleton
+ * interface that is used only by the OCPlatform namespace and is the
+ * central entrance to the stack.
+ */
 
 #ifndef __OCPLATFORM_IMPL_H
 #define __OCPLATFORM_IMPL_H
 
 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,
-                    FindCallback resourceHandler);
+                    OCConnectivityType connectivityType, FindCallback resourceHandler);
+
         OCStackResult findResource(const std::string& host, const std::string& resourceURI,
-                    FindCallback resourceHandler, QualityOfService QoS);
+                    OCConnectivityType connectivityType, FindCallback resourceHandler,
+                    QualityOfService QoS);
+
+        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);
+
+        OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
+                    OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler);
+
+        OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
+                    OCConnectivityType connectivityType, FindPlatformCallback platformInfoHandler,
+                    QualityOfService QoS);
 
         /**
          * API for Device Discovery
@@ -161,6 +109,21 @@ namespace OC
                     FindDeviceCallback deviceInfoHandler, QualityOfService QoS);
 
         /**
+         * API for Platform Discovery
+         *
+         * @param host - Host IP Address. If null or empty, Multicast is performed.
+         * @param resourceURI - Uri containing address to the virtual platform in C Stack
+         *                       ("/oic/p")
+         *
+         * @param QualityOfService the quality of communication
+         *
+         */
+        OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
+                    FindPlatformCallback platformInfoHandler);
+        OCStackResult getPlatformInfo(const std::string& host, const std::string& platformURI,
+                    FindPlatformCallback platformInfoHandler, QualityOfService QoS);
+
+        /**
         * This API registers a resource with the server
         * NOTE: This API applies to server side only.
         *
@@ -183,7 +146,7 @@ namespace OC
         *   //192.168.1.1/oc/a/light"
         * First parameter can take a relative URI and core will take care of preparing the fully
         * qualified URI OR
-        * first paramter can take fully qualified URI and core will take that as is for further
+        * first parameter can take fully qualified URI and core will take that as is for further
         * operations
         * NOTE: OCStackResult is defined in ocstack.h.
         */
@@ -194,16 +157,6 @@ 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);
 
@@ -219,243 +172,54 @@ namespace OC
         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
-        */
+         * This API registers all the platform specific information
+         *
+         * @param OCPlatformInfo - Structure containing all the platform related information
+         *
+         * @return OCStackResult return value of the API. Returns OC_STACK_OK if success
+         *
+         * Note: OCPlatformInfo is defined in OCStack.h
+         */
+        OCStackResult registerPlatformInfo(const OCPlatformInfo platformInfo);
+
         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,
-                        SubscribeCallback presenceHandler);
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
-                        const std::string& resourceType, SubscribeCallback presenceHandler);
+                        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 subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
+                        const std::string& resourceType, OCConnectivityType connectivityType,
+                        SubscribeCallback presenceHandler);
         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,
-                        bool isObservable, const std::vector<std::string>& resourceTypes,
+                        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:
@@ -469,15 +233,15 @@ 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.
         */
         OCPlatform_impl(const PlatformConfig& config);
 
         /**
-        * Private function to initalize the platfrom
+        * Private function to initialize the platform
         */
         void init(const PlatformConfig& config);
 
@@ -494,3 +258,4 @@ namespace OC
 #endif //__OCPLATFORM_IMPL_H
 
 
+
index 2e64fcd..534bb5a 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCRepresentation.h
-
-/// @brief  This file contains the declaration of classes and its members
-///         related to OCRepresentation
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related
+ * to OCRepresentation.
+ */
 
 #ifndef __OCREPRESENTATION_H
 #define __OCREPRESENTATION_H
@@ -75,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;
 
@@ -98,7 +100,25 @@ namespace OC
     class OCRepresentation
     {
         public:
-            OCRepresentation();
+            // Note: Implementation of all constructors and destructors
+            // are all placed in the same location due to a crash that
+            // was observed in Android, where merely constructing/destructing
+            // an OCRepresentation object was enough to cause an invalid 'free'.
+            // It is believed that this is a result of incompatible compiler
+            // options between the gradle JNI and armeabi scons build, however
+            // this fix will work in the meantime.
+            OCRepresentation(): m_interfaceType(InterfaceType::None){}
+
+            OCRepresentation(OCRepresentation&&) = default;
+
+            OCRepresentation(const OCRepresentation&) = default;
+
+            OCRepresentation& operator=(const OCRepresentation&) = default;
+
+            OCRepresentation& operator=(OCRepresentation&&) = default;
+
+            virtual ~OCRepresentation(){}
+
             std::string getJSONRepresentation() const;
 
             void addChild(const OCRepresentation&);
@@ -121,7 +141,7 @@ namespace OC
 
             void setResourceInterfaces(const std::vector<std::string>& resourceInterfaces);
 
-            bool empty() const;
+            bool emptyData() const;
 
             int numberOfAttributes() const;
 
@@ -133,6 +153,14 @@ namespace OC
                 m_values[str] = val;
             }
 
+            /**
+             *  Retrieve the attribute value associated with the supplied name
+             *
+             *  @param str Name of the attribute
+             *  @param val Value of the attribute
+             *  @return The getValue method returns true if the attribute was
+             *        found in the representation.  Otherwise it returns false.
+             */
             template <typename T>
             bool getValue(const std::string& str, T& val) const
             {
@@ -150,6 +178,14 @@ namespace OC
                 }
             }
 
+            /**
+             *  Return the attribute value associated with the supplied name
+             *
+             *  @param str Name of the attribute
+             *  @return When the representation contains the attribute, the
+             *       the associated value is returned.  Otherwise, getValue
+             *       returns the default contructed value for the type.
+             */
             template <typename T>
             T getValue(const std::string& str) const
             {
@@ -162,11 +198,195 @@ namespace OC
                 return val;
             }
 
+          /**
+            *  Retrieve the attributevalue structure associated with the supplied name
+            *
+            *  @param str Name of the attribute
+            *  @param attrValue Attribute Value structure
+            *  @return The getAttributeValue method returns true if the attribute was
+            *        found in the representation.  Otherwise it returns false.
+            */
+            bool getAttributeValue(const std::string& str, AttributeValue& attrValue) const
+            {
+                auto x = m_values.find(str);
+
+                if (x != m_values.end())
+                {
+                    attrValue = x->second;
+                    return true;
+                }
+                else
+                {
+                    return false;
+                }
+            }
+
+            std::string getValueToString(const std::string& key) const;
             bool hasAttribute(const std::string& str) const;
 
             void setNULL(const std::string& str);
 
             bool isNULL(const std::string& str) const;
+
+            // STL Container stuff
+        public:
+            class iterator;
+            class const_iterator;
+            // Shim class to allow iterating and indexing of the OCRepresentation
+            // object.
+            class AttributeItem
+            {
+                friend class OCRepresentation;
+                friend class iterator;
+                friend class const_iterator;
+                public:
+                    const std::string& attrname() const;
+                    AttributeType type() const;
+                    AttributeType base_type() const;
+                    size_t depth() const;
+                    template<typename T>
+                    T getValue() const
+                    {
+                        return boost::get<T>(m_values[m_attrName]);
+                    }
+
+                    std::string getValueToString() const;
+
+                    template<typename T>
+                    AttributeItem& operator=(T&& rhs)
+                    {
+                        m_values[m_attrName] = std::forward<T>(rhs);
+                        return *this;
+                    }
+
+                    AttributeItem& operator=(std::nullptr_t rhs)
+                    {
+                        NullType t;
+                        m_values[m_attrName] = t;
+                        return *this;
+                    }
+
+                    // Enable-if required to prevent conversions to alternate types.  This prevents
+                    // ambigious conversions in the case where conversions can include a number of
+                    // types, such as the string constructor.
+                    template<typename T, typename= typename std::enable_if<
+                     std::is_same<T, int>::value ||
+                     std::is_same<T, double>::value ||
+                     std::is_same<T, bool>::value ||
+                     std::is_same<T, std::string>::value ||
+                     std::is_same<T, OCRepresentation>::value ||
+                     std::is_same<T, std::vector<int>>::value ||
+                     std::is_same<T, std::vector<std::vector<int>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<int>>>>::value ||
+                     std::is_same<T, std::vector<double>>::value ||
+                     std::is_same<T, std::vector<std::vector<double>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<double>>>>::value ||
+                     std::is_same<T, std::vector<bool>>::value ||
+                     std::is_same<T, std::vector<std::vector<bool>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<bool>>>>::value ||
+                     std::is_same<T, std::vector<std::string>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::string>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<std::string>>>>::value ||
+                     std::is_same<T, std::vector<OCRepresentation>>::value ||
+                     std::is_same<T, std::vector<std::vector<OCRepresentation>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<OCRepresentation>>>>::value
+                     >::type // enable_if
+                    >
+                    operator T() const
+                    {
+                        return this->getValue<T>();
+                    }
+
+                    operator std::nullptr_t() const
+                    {
+                        this->getValue<NullType>();
+                        return nullptr;
+                    }
+
+                private:
+                    AttributeItem(const std::string& name,
+                            std::map<std::string, AttributeValue>& vals);
+                    AttributeItem(const AttributeItem&) = default;
+                    std::string m_attrName;
+                    std::map<std::string, AttributeValue>& m_values;
+            };
+
+            // Iterator to allow iteration via STL containers/methods
+            class iterator
+            {
+                friend class OCRepresentation;
+                public:
+                    typedef iterator self_type;
+                    typedef AttributeItem value_type;
+                    typedef value_type& reference;
+                    typedef value_type* pointer;
+                    typedef std::forward_iterator_tag iterator_category;
+                    typedef int difference_type;
+
+                    iterator(const iterator&) = default;
+                    ~iterator() = default;
+
+                    bool operator ==(const iterator&) const;
+                    bool operator !=(const iterator&) const;
+
+                    iterator& operator++();
+                    iterator operator++(int);
+
+                    reference operator*();
+                    pointer operator->();
+                private:
+                    iterator(std::map<std::string, AttributeValue>::iterator&& itr,
+                            std::map<std::string, AttributeValue>& vals)
+                        : m_iterator(std::move(itr)),
+                        m_item(m_iterator != vals.end() ? m_iterator->first:"", vals){}
+                    std::map<std::string, AttributeValue>::iterator m_iterator;
+                    AttributeItem m_item;
+            };
+
+            class const_iterator
+            {
+                friend class OCRepresentation;
+                public:
+                    typedef iterator self_type;
+                    typedef const AttributeItem value_type;
+                    typedef value_type& const_reference;
+                    typedef value_type* const_pointer;
+                    typedef std::forward_iterator_tag iterator_category;
+                    typedef int difference_type;
+
+                    const_iterator(const iterator& rhs)
+                        :m_iterator(rhs.m_iterator), m_item(rhs.m_item){}
+                    const_iterator(const const_iterator&) = default;
+                    ~const_iterator() = default;
+
+                    bool operator ==(const const_iterator&) const;
+                    bool operator !=(const const_iterator&) const;
+
+                    const_iterator& operator++();
+                    const_iterator operator++(int);
+
+                    const_reference operator*() const;
+                    const_pointer operator->() const;
+                private:
+                    const_iterator(std::map<std::string, AttributeValue>::const_iterator&& itr,
+                            std::map<std::string, AttributeValue>& vals)
+                        : m_iterator(std::move(itr)),
+                        m_item(m_iterator != vals.end() ? m_iterator->first: "", vals){}
+                    std::map<std::string, AttributeValue>::const_iterator m_iterator;
+                    AttributeItem m_item;
+            };
+
+            iterator begin();
+            const_iterator begin() const;
+            const_iterator cbegin() const;
+            iterator end();
+            const_iterator end() const;
+            const_iterator cend() const;
+            size_t size() const;
+            bool empty() const;
+
+            AttributeItem operator[](const std::string& key);
+            const AttributeItem operator[](const std::string& key) const;
         private:
             friend class OCResourceResponse;
             friend class cereal::access;
@@ -217,13 +437,16 @@ namespace OC
         private:
             std::string m_uri;
             std::vector<OCRepresentation> m_children;
-            std::map<std::string, AttributeValue> m_values;
+            mutable std::map<std::string, AttributeValue> m_values;
             std::vector<std::string> m_resourceTypes;
             std::vector<std::string> m_interfaces;
 
             InterfaceType m_interfaceType;
     };
+
+    std::ostream& operator <<(std::ostream& os, const OCRepresentation::AttributeItem& ai);
 } // namespace OC
 
 
 #endif //__OCREPRESENTATION_H
+
index 63c4253..bc0109c 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCResource.h
-
-/// @brief  This file contains the declaration of classes and its members related to
-///         Resource.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * Resource.
+ */
 
 #ifndef __OCRESOURCE_H
 #define __OCRESOURCE_H
 
 namespace OC
 {
+    class OCResource;
+    class OCResourceIdentifier;
+    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
+    *          OCResource on or across networks.
+    *          Equality operators are implemented.  However, internal representation is subject
+    *          to change and thus should not be accessed or depended on.
+    */
+    class OCResourceIdentifier
+    {
+        friend class OCResource;
+        friend std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri);
+
+        public:
+            OCResourceIdentifier() = delete;
+
+            OCResourceIdentifier(const OCResourceIdentifier&) = default;
+
+            OCResourceIdentifier(OCResourceIdentifier&&) = default;
+
+            OCResourceIdentifier& operator=(const OCResourceIdentifier&) = delete;
+
+            OCResourceIdentifier& operator=(OCResourceIdentifier&&) = delete;
+
+            bool operator==(const OCResourceIdentifier &other) const;
+
+            bool operator!=(const OCResourceIdentifier &other) const;
+
+            bool operator<(const OCResourceIdentifier &other) const;
+
+            bool operator>(const OCResourceIdentifier &other) const;
+
+            bool operator<=(const OCResourceIdentifier &other) const;
+
+            bool operator>=(const OCResourceIdentifier &other) const;
+
+        private:
+
+            OCResourceIdentifier(const std::string& wireServerIdentifier,
+                    const std::string& resourceUri );
+
+        private:
+            std::string m_representation;
+            const std::string& m_resourceUri;
+    };
+
     /**
     *   @brief  OCResource represents an OC resource. A resource could be a light controller,
     *           temperature sensor, smoke detector, etc. A resource comes with a well-defined
@@ -52,6 +102,10 @@ namespace OC
     friend class ListenOCContainer;
     public:
         typedef std::shared_ptr<OCResource> Ptr;
+
+        OCResource(OCResource&&) = default;
+        OCResource& operator=(OCResource&&) = default;
+
         /**
         * Virtual destructor
         */
@@ -64,11 +118,21 @@ namespace OC
         *        The callback function will be invoked with a map of attribute name and values.
         *        The callback function will also have the result from this Get operation
         *        This will have error codes
-        * @param QualityOfService the quality of communication
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
         * NOTE: OCStackResult is defined in ocstack.h.
         */
         OCStackResult get(const QueryParamsMap& queryParametersMap, GetCallback attributeHandler);
+        /**
+        * Function to get the attributes of a resource.
+        * @param queryParametersMap map which can have the query parameter name and value
+        * @param attributeHandler handles callback
+        *        The callback function will be invoked with a map of attribute name and values.
+        *        The callback function will also have the result from this Get operation
+        *        This will have error codes
+        * @param QoS the quality of communication
+        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+        * NOTE: OCStackResult is defined in ocstack.h.
+        */
         OCStackResult get(const QueryParamsMap& queryParametersMap, GetCallback attributeHandler,
                           QualityOfService QoS);
 
@@ -84,7 +148,6 @@ namespace OC
         *        resource container (list will be empty if not a container)
         *        The callback function will also have the result from this Get operation. This will
         *        have error codes
-        * @param QualityOfService the quality of communication
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
         * NOTE: OCStackResult is defined in ocstack.h.<br>
         * <b>Example:</b><br>
@@ -105,6 +168,37 @@ namespace OC
         */
         OCStackResult get(const std::string& resourceType, const std::string& resourceInterface,
                         const QueryParamsMap& queryParametersMap, GetCallback attributeHandler);
+        /**
+        * Function to get the attributes of a resource.
+        *
+        * @param resourceType resourceType of the resource operate on
+        * @param resourceInterface interface type of the resource to operate on
+        * @param queryParametersMap map which can have the query parameter name and value
+        * @param attributeHandler handles callback
+        *        The callback function will be invoked with a map of attribute name and values.
+        *        The callback function will be invoked with a list of URIs if 'get' is invoked on a
+        *        resource container (list will be empty if not a container)
+        *        The callback function will also have the result from this Get operation. This will
+        *        have error codes
+        * @param QoS the quality of communication
+        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
+        * NOTE: OCStackResult is defined in ocstack.h.<br>
+        * <b>Example:</b><br>
+        * Consider resource "a/home" (with link interface and resource type as home) contains links
+        *  to "a/kitchen" and "a/room".
+        * Step 1: get("home", Link_Interface, &onGet)<br>
+        * Callback onGet will receive a) Empty attribute map because there are no attributes for
+        * a/home b) list with
+        * full URI of "a/kitchen" and "a/room" resources and their properties c) error code for GET
+        * operation<br>
+        * NOTE: A resource may contain single or multiple resource types. Also, a resource may
+        * contain single or multiple interfaces.<br>
+        * Currently, single GET request is allowed to do operate on single resource type or resource
+        * interface. In future, a single GET <br>
+        * can operate on multiple resource types and interfaces. <br>
+        * NOTE: A client can traverse a tree or graph by doing successive GETs on the returned
+        * resources at a node.<br>
+        */
         OCStackResult get(const std::string& resourceType, const std::string& resourceInterface,
                         const QueryParamsMap& queryParametersMap, GetCallback attributeHandler,
                         QualityOfService QoS);
@@ -119,12 +213,25 @@ namespace OC
         *        This will have error codes
         * @param queryParametersMap map which can have the query parameter name and value
         * @param attributeHandler attribute handler
-        * @param QualityOfService the quality of communication
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
         * NOTE: OCStackResult is defined in ocstack.h.
         */
         OCStackResult put(const OCRepresentation& representation,
                         const QueryParamsMap& queryParametersMap, PutCallback attributeHandler);
+        /**
+        * Function to set the representation of a resource (via PUT)
+        * @param representation which can either have all the attribute names and values
+                 (which will represent entire state of the resource) or a
+        *        set of attribute names and values which needs to be modified
+        *        The callback function will be invoked with a map of attribute name and values.
+        *        The callback function will also have the result from this Put operation
+        *        This will have error codes
+        * @param queryParametersMap map which can have the query parameter name and value
+        * @param attributeHandler attribute handler
+        * @param QoS the quality of communication
+        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+        * NOTE: OCStackResult is defined in ocstack.h.
+        */
         OCStackResult put(const OCRepresentation& representation,
                         const QueryParamsMap& queryParametersMap, PutCallback attributeHandler,
                         QualityOfService QoS);
@@ -143,13 +250,30 @@ namespace OC
         *        and values
         *        (which will represent entire state of the resource) or a
         *        set of attribute names and values which needs to be modified
-        * @param QualityOfService the quality of communication
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
         * NOTE: OCStackResult is defined in ocstack.h. <br>
         */
         OCStackResult put(const std::string& resourceType, const std::string& resourceInterface,
                         const OCRepresentation& representation, const QueryParamsMap& queryParametersMap,
                         PutCallback attributeHandler);
+        /**
+        * Function to set the attributes of a resource (via PUT)
+        * @param resourceType resource type of the resource to operate on
+        * @param resourceInterface interface type of the resource to operate on
+        * @param representation representation of the resource
+        * @param queryParametersMap Map which can have the query parameter name and value
+        * @param attributeHandler attribute handler
+        *        The callback function will be invoked with a map of attribute name and values.
+        *        The callback function will also have the result from this Put operation
+        *        This will have error codes.
+        *        The Representation parameter maps which can either have all the attribute names
+        *        and values
+        *        (which will represent entire state of the resource) or a
+        *        set of attribute names and values which needs to be modified
+        * @param QoS the quality of communication
+        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
+        * NOTE: OCStackResult is defined in ocstack.h. <br>
+        */
         OCStackResult put(const std::string& resourceType, const std::string& resourceInterface,
                         const OCRepresentation& representation, const QueryParamsMap& queryParametersMap,
                         PutCallback attributeHandler, QualityOfService QoS);
@@ -157,19 +281,32 @@ namespace OC
         /**
         * Function to post on a resource
         * @param representation which can either have all the attribute names and values
-                 (which will represent entire state of the resource) or a
+        *        (which will represent entire state of the resource) or a
         *        set of attribute names and values which needs to be modified
         *        The callback function will be invoked with a map of attribute name and values.
         *        The callback function will also have the result from this Put operation
         *        This will have error codes
         * @param queryParametersMap map which can have the query parameter name and value
         * @param attributeHandler attribute handler
-        * @param QualityOfService the quality of communication
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
         * NOTE: OCStackResult is defined in ocstack.h.
         */
         OCStackResult post(const OCRepresentation& representation,
                         const QueryParamsMap& queryParametersMap, PostCallback attributeHandler);
+        /**
+        * Function to post on a resource
+        * @param representation which can either have all the attribute names and values
+        *        (which will represent entire state of the resource) or a
+        *        set of attribute names and values which needs to be modified
+        *        The callback function will be invoked with a map of attribute name and values.
+        *        The callback function will also have the result from this Put operation
+        *        This will have error codes
+        * @param queryParametersMap map which can have the query parameter name and value
+        * @param attributeHandler attribute handler
+        * @param QoS the quality of communication
+        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+        * NOTE: OCStackResult is defined in ocstack.h.
+        */
         OCStackResult post(const OCRepresentation& representation,
                         const QueryParamsMap& queryParametersMap, PostCallback attributeHandler,
                         QualityOfService QoS);
@@ -188,20 +325,37 @@ namespace OC
         *        and values
         *        (which will represent entire state of the resource) or a
         *        set of attribute names and values which needs to be modified
-        * @param QualityOfService the quality of communication
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
         * NOTE: OCStackResult is defined in ocstack.h. <br>
         */
         OCStackResult post(const std::string& resourceType, const std::string& resourceInterface,
                         const OCRepresentation& representation, const QueryParamsMap& queryParametersMap,
                         PostCallback attributeHandler);
+        /**
+        * Function to post on a resource
+        * @param resourceType resource type of the resource to operate on
+        * @param resourceInterface interface type of the resource to operate on
+        * @param representation representation of the resource
+        * @param queryParametersMap Map which can have the query parameter name and value
+        * @param attributeHandler attribute handler
+        *        The callback function will be invoked with a map of attribute name and values.
+        *        The callback function will also have the result from this Put operation
+        *        This will have error codes.
+        *        The Representation parameter maps which can either have all the attribute names
+        *        and values
+        *        (which will represent entire state of the resource) or a
+        *        set of attribute names and values which needs to be modified
+        * @param QoS the quality of communication
+        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
+        * NOTE: OCStackResult is defined in ocstack.h. <br>
+        */
         OCStackResult post(const std::string& resourceType, const std::string& resourceInterface,
                         const OCRepresentation& representation, const QueryParamsMap& queryParametersMap,
                         PostCallback attributeHandler, QualityOfService QoS);
 
         /**
         * Function to perform DELETE operation
-        * @param observeHandler handles callback
+        * @param deleteHandler handles callback
         *        The callback function will have headerOptions and result from this Delete
         *        operation. This will have error codes
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
@@ -218,12 +372,23 @@ namespace OC
         *        The callback function will be invoked with a map of attribute name and values.
         *        The callback function will also have the result from this observe operation
         *        This will have error codes
-        * @param QualityOfService the quality of communication
         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
         * NOTE: OCStackResult is defined in ocstack.h.
         */
         OCStackResult observe(ObserveType observeType, const QueryParamsMap& queryParametersMap,
                         ObserveCallback observeHandler);
+        /**
+        * Function to set observation on the resource
+        * @param observeType allows the client to specify how it wants to observe.
+        * @param queryParametersMap map which can have the query parameter name and value
+        * @param observeHandler handles callback
+        *        The callback function will be invoked with a map of attribute name and values.
+        *        The callback function will also have the result from this observe operation
+        *        This will have error codes
+        * @param qos the quality of communication
+        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+        * NOTE: OCStackResult is defined in ocstack.h.
+        */
         OCStackResult observe(ObserveType observeType, const QueryParamsMap& queryParametersMap,
                         ObserveCallback observeHandler, QualityOfService qos);
 
@@ -275,6 +440,12 @@ namespace OC
         std::string uri() const;
 
         /**
+        * Function to get the connectivity type of this resource
+        * @return uint8_t connectivity type
+        */
+        OCConnectivityType connectivityType() const;
+
+        /**
         * Function to provide ability to check if this resource is observable or not
         * @return bool true indicates resource is observable; false indicates resource is
         *         not observable.
@@ -299,10 +470,45 @@ namespace OC
             return m_interfaces;
         }
 
+        // TODO-CA Revisit this since we are exposing two identifiers
+        /**
+        * Function to get a unique identifier for this
+        * resource across network interfaces.  This will
+        * be guaranteed unique for every resource-per-server
+        * independent of how this was discovered.
+        * @return OCResourceIdentifier object, which can
+        * be used for all comparison and hashing.
+        */
+        OCResourceIdentifier uniqueIdentifier() const;
+
+        /**
+        * Function to get a string representation of the resource's server ID.
+        * This is unique per- server independent on how it was discovered.
+        * Note: The format of the return value is subject to change and will
+        * likely change both in size and contents in the future.
+        */
+        std::string sid() const;
+
+        // overloaded operators allow for putting into a 'set'
+        // the uniqueidentifier allows for putting into a hash
+        bool operator==(const OCResource &other) const;
+
+        bool operator!=(const OCResource &other) const;
+
+        bool operator<(const OCResource &other) const;
+
+        bool operator>(const OCResource &other) const;
+
+        bool operator<=(const OCResource &other) const;
+
+        bool operator>=(const OCResource &other) const;
+
     private:
         std::weak_ptr<IClientWrapper> m_clientWrapper;
         std::string m_uri;
+        OCResourceIdentifier m_resourceId;
         std::string m_host;
+        OCConnectivityType m_connectivityType;
         bool m_isObservable;
         bool m_isCollection;
         std::vector<std::string> m_resourceTypes;
@@ -313,10 +519,13 @@ namespace OC
 
     private:
         OCResource(std::weak_ptr<IClientWrapper> clientWrapper, const std::string& host,
-            const std::string& uri, bool observable, const std::vector<std::string>& resourceTypes,
+            const std::string& uri, const std::string& serverId,
+            OCConnectivityType m_connectivityType, bool observable,
+            const std::vector<std::string>& resourceTypes,
             const std::vector<std::string>& interfaces);
     };
 
 } // namespace OC
 
 #endif //__OCRESOURCE_H
+
index 101f6fb..f4b8f84 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCResourceRequest.h
-
-/// @brief  This file contains the declaration of classes and its members related to
-///         ResourceRequest.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * ResourceRequest.
+ */
 
 #ifndef __OCRESOURCEREQUEST_H
 #define __OCRESOURCEREQUEST_H
@@ -44,6 +46,21 @@ namespace OC
     public:
         typedef std::shared_ptr<OCResourceRequest> Ptr;
 
+        OCResourceRequest():
+            m_requestType{},
+            m_resourceUri{},
+            m_queryParameters{},
+            m_requestHandlerFlag{},
+            m_representation{},
+            m_observationInfo{},
+            m_headerOptions{},
+            m_requestHandle{nullptr},
+            m_resourceHandle{nullptr}
+        {
+        }
+
+        OCResourceRequest(OCResourceRequest&&) = default;
+        OCResourceRequest& operator=(OCResourceRequest&&) = default;
         /**
         *  Virtual destructor
         */
@@ -157,34 +174,7 @@ namespace OC
             m_requestType = requestType;
         }
 
-        void setPayload(const std::string& requestPayload)
-        {
-            if(requestPayload.empty())
-            {
-                return;
-            }
-
-            MessageContainer info;
-            info.setJSONRepresentation(requestPayload);
-
-            const std::vector<OCRepresentation>& reps = info.representations();
-            if(reps.size() >0)
-            {
-                std::vector<OCRepresentation>::const_iterator itr = reps.begin();
-                std::vector<OCRepresentation>::const_iterator back = reps.end();
-                m_representation = *itr;
-                ++itr;
-
-                for(;itr != back; ++itr)
-                {
-                    m_representation.addChild(*itr);
-                }
-            }
-            else
-            {
-                throw OCException(OC::Exception::INVALID_REPRESENTATION);
-            }
-        }
+        void setPayload(const std::string& requestPayload);
 
         void setQueryParams(QueryParamsMap& queryParams)
         {
index 1c8e3fa..c654834 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCResourceResponse.h
-
-/// @brief  This file contains the declaration of classes and its members related to
-///         ResourceResponse.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * ResourceResponse.
+ */
 
 #ifndef __OCRESOURCERESPONSE_H
 #define __OCRESOURCERESPONSE_H
@@ -31,8 +33,6 @@
 #include <ocstack.h>
 #include <OCRepresentation.h>
 
-using namespace std;
-
 namespace OC
 {
     class InProcServerWrapper;
@@ -45,9 +45,20 @@ namespace OC
     public:
         typedef std::shared_ptr<OCResourceResponse> Ptr;
 
-        OCResourceResponse()
-        {}
+        OCResourceResponse():
+            m_newResourceUri{},
+            m_errorCode{},
+            m_headerOptions{},
+            m_interface{},
+            m_representation{},
+            m_requestHandle{nullptr},
+            m_resourceHandle{nullptr},
+            m_responseResult{}
+        {
+        }
 
+        OCResourceResponse(OCResourceResponse&&) = default;
+        OCResourceResponse& operator=(OCResourceResponse&&) = default;
         virtual ~OCResourceResponse(void) {}
 
         /**
@@ -115,8 +126,7 @@ namespace OC
 
         /**
         *  API to set the entire resource attribute representation
-        *  @param attributeMap reference containing the name value pairs representing
-        *         the resource's attributes
+        *  @param rep reference to the resource's representation
         *  @param interface specifies the interface
         */
         void setResourceRepresentation(OCRepresentation& rep, std::string interface) {
@@ -126,8 +136,7 @@ namespace OC
 
         /**
         *  API to set the entire resource attribute representation
-        *  @param attributeMap rvalue reference containing the name value pairs representing
-        *         the resource's attributes
+        *  @param rep rvalue reference to the resource's representation
         *  @param interface specifies the interface
         */
         void setResourceRepresentation(OCRepresentation&& rep, std::string interface) {
@@ -136,8 +145,7 @@ namespace OC
 
         /**
         *  API to set the entire resource attribute representation
-        *  @param attributeMap reference containing the name value pairs representing the resource's
-        *  attributes
+        *  @param rep reference to the resource's representation
         */
         void setResourceRepresentation(OCRepresentation& rep) {
             // Call the default
@@ -147,8 +155,7 @@ namespace OC
 
         /**
         *  API to set the entire resource attribute representation
-        *  @param attributeMap rvalue reference containing the name value pairs representing the
-        *  resource's attributes
+        *  @param rep rvalue reference to the resource's representation
         */
         void setResourceRepresentation(OCRepresentation&& rep) {
             // Call the above function
@@ -215,7 +222,10 @@ namespace OC
         /**
         * Get error code
         */
-        int getErrorCode() const;
+        int getErrorCode() const
+        {
+            return m_errorCode;
+        }
 
         /**
          * Get the Response Representation
@@ -266,3 +276,4 @@ namespace OC
 } // namespace OC
 
 #endif //__OCRESOURCERESPONSE_H
+
diff --git a/resource/include/OCSecurityModel.h b/resource/include/OCSecurityModel.h
deleted file mode 100644 (file)
index 9c447aa..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/// @file OCSecurityModel.h 
-
-/// @brief     This file contains the declaration of classes and its members required to provide 
-///                    security model support. 
-
-#ifndef __OCSECURITYMODEL_H
-#define __OCSECURITYMODEL_H
-
-#include "OCApi.h"
-
-namespace OC
-{
-       /**
-       * @brief        This class provides the required security model to 
-       *                       access a service or a particular resource.
-       */
-       class OCSecurityModel
-       {
-       public:
-               OCSecurityModel(void);
-
-               virtual ~OCSecurityModel(void);
-
-               /**
-               * @fn   checks the security access
-               * 
-               * @param sourceURI - source URI 
-               * @param destinationURI - destination URI of the resoruce to access 
-               * @param encryptionLevel - Encryption level
-               * @param remoteIdentity - remote identity
-               */
-               void checkAccess(URI sourceURI, URI destinationURI, int encryptionLevel, int remoteIdentity);
-       };
-}
-
-#endif //__OCSECURITYMODEL_H
index f611407..898fde7 100644 (file)
@@ -122,6 +122,15 @@ namespace OC
                 }
                 try
                 {
+                    ar(cereal::make_nvp(OC::Key::SERVERIDKEY, m_serverId));
+                    m_loaded=true;
+                }
+                catch(cereal::Exception&)
+                {
+                    ar.setNextName(nullptr);
+                }
+                try
+                {
                     ar(cereal::make_nvp(OC::Key::PROPERTYKEY, m_props));
                     m_loaded=true;
                 }
@@ -133,6 +142,7 @@ namespace OC
 
 
             std::string m_uri;
+            std::string m_serverId;
             bool m_loaded;
             ListenResourcePropertiesContainer m_props;
 
@@ -177,8 +187,8 @@ namespace OC
             }
         public:
             ListenOCContainer(std::weak_ptr<IClientWrapper> cw, const OCDevAddr& address,
-                    std::stringstream& json):
-                m_clientWrapper(cw), m_address(address)
+                    OCConnectivityType connectivityType, std::stringstream& json):
+                m_clientWrapper(cw), m_address(address), m_connectivityType(connectivityType)
             {
                 LoadFromJson(json);
             }
@@ -191,10 +201,8 @@ namespace OC
         private:
             std::string ConvertOCAddrToString(OCSecureType sec, int secureport)
             {
-                char stringAddress[DEV_ADDR_SIZE_MAX];
                 uint16_t port;
-
-                ostringstream os;
+                std::ostringstream os;
 
                 if(sec== OCSecureType::IPv4)
                 {
@@ -210,18 +218,19 @@ namespace OC
                     throw ResourceInitException(false, false, false, false, false, true);
                 }
 
-                if(0== OCDevAddrToString(&m_address, stringAddress))
-                {
-                    // nothing to do, successful case.
-                }
-                else
+                uint8_t a;
+                uint8_t b;
+                uint8_t c;
+                uint8_t d;
+                if(OCDevAddrToIPv4Addr(&m_address, &a, &b, &c, &d) != 0)
                 {
                     oclog() << "ConvertOCAddrToString(): Invalid Ip"
-                        << std::flush;
+                            << std::flush;
                     throw ResourceInitException(false, false, false, false, false, true);
                 }
 
-                os<<stringAddress;
+                os<<static_cast<int>(a)<<"."<<static_cast<int>(b)
+                        <<"."<<static_cast<int>(c)<<"."<<static_cast<int>(d);
 
                 if(sec == OCSecureType::IPv4Secure && secureport>0 && secureport<=65535)
                 {
@@ -234,7 +243,7 @@ namespace OC
                 else
                 {
                     oclog() << "ConvertOCAddrToString() : Invalid Port"
-                        <<std::flush;
+                            <<std::flush;
                     throw ResourceInitException(false, false, false, false, true, false);
                 }
 
@@ -261,8 +270,8 @@ namespace OC
                             m_resources.push_back(std::shared_ptr<OCResource>(
                                 new OCResource(m_clientWrapper,
                                     ConvertOCAddrToString(res.secureType(),res.port()),
-                                    res.m_uri, res.observable(), res.resourceTypes(),
-                                    res.interfaces())));
+                                    res.m_uri, res.m_serverId, m_connectivityType, res.observable(),
+                                    res.resourceTypes(), res.interfaces())));
                         }
 
                     }
@@ -276,5 +285,7 @@ namespace OC
             std::vector<std::shared_ptr<OC::OCResource>> m_resources;
             std::weak_ptr<IClientWrapper> m_clientWrapper;
             OCDevAddr m_address;
+            OCConnectivityType m_connectivityType;
     };
 }
+
index a736820..65ea6af 100644 (file)
 #include <utility>
 #include <exception>
 
-#include "OCException.h"
+#include <OCException.h>
+#include <StringConstants.h>
 
 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);
-
     }
 }
 
 /* The C++11 standard unfortunately forgot to provide make_unique<>! However, if we're
 using C++14 or later, we want to take the standard library's implementation: */
-#if defined(__cplusplus) && __cplusplus < 201300
 namespace OC {
+#if defined(__cplusplus) && __cplusplus < 201300
 
     template<typename T, typename ...XS>
     std::unique_ptr<T> make_unique(XS&& ...xs)
@@ -62,15 +58,13 @@ namespace OC {
         return std::unique_ptr<T>(new T(std::forward<XS>(xs)...));
     }
 
-} // namespace OC
 #else
     using std::make_unique;
 #endif
+} // namespace OC
 
 namespace OC {
 
-    using OC::make_unique;
-
     /* Examine an OCStackResult, and either forward its value or raise an exception: */
     OCStackResult result_guard(const OCStackResult r);
 
@@ -98,4 +92,24 @@ namespace OC {
 
 } // namespace OC
 
+namespace OC
+{
+    template<typename T, typename = void>
+    struct is_vector
+    {
+        constexpr static bool value = false;
+    };
+
+    template<typename T>
+    struct is_vector<T,
+        typename std::enable_if<
+            std::is_same<T, std::vector<typename T::value_type, typename T::allocator_type>>::value
+        >::type
+    >
+    {
+        constexpr static bool value = true;
+    };
+} // namespace OC
+
 #endif
+
index d7eb98e..280ac28 100644 (file)
@@ -72,7 +72,7 @@ namespace cereal
 {
   // ######################################################################
   //! An output archive designed to save data to JSON
-  /*! This archive uses RapidJSON to build serialie data to JSON.
+  /*! This archive uses RapidJSON to build serialized data to JSON.
 
       JSON archives provides a human readable output but at decreased
       performance (both in time and space) compared to binary archives.
index 049c445..db00d40 100644 (file)
@@ -33,7 +33,13 @@ namespace OC
         {}
 
         virtual OCStackResult ListenForResource(const std::string& serviceUrl,
-            const std::string& resourceType, FindCallback& callback, QualityOfService QoS)
+            const std::string& resourceType, OCConnectivityType connectivityType,
+            FindCallback& callback, QualityOfService QoS)
+            {return OC_STACK_NOTIMPL;}
+
+        virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
+            const std::string& deviceURI, OCConnectivityType connectivityType,
+            FindDeviceCallback& callback, QualityOfService QoS)
             {return OC_STACK_NOTIMPL;}
 
         virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
@@ -42,41 +48,40 @@ namespace OC
             {return OC_STACK_NOTIMPL;}
 
         virtual OCStackResult GetResourceRepresentation(const std::string& host,
-            const std::string& uri, const QueryParamsMap& queryParams,
-            const HeaderOptions& headerOptions, GetCallback& callback,
-            QualityOfService QoS)
+            const std::string& uri, OCConnectivityType connectivityType,
+            const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
+            GetCallback& callback, QualityOfService QoS)
             {return OC_STACK_NOTIMPL;}
 
         virtual OCStackResult PutResourceRepresentation(const std::string& host,
-            const std::string& uri, const OCRepresentation& attributes,
-            const QueryParamsMap& queryParams,
+            const std::string& uri, OCConnectivityType connectivityType,
+            const OCRepresentation& attributes, const QueryParamsMap& queryParams,
             const HeaderOptions& headerOptions, PutCallback& callback,
             QualityOfService QoS)
             {return OC_STACK_NOTIMPL;}
 
         virtual OCStackResult PostResourceRepresentation(const std::string& host,
-            const std::string& uri, const OCRepresentation& attributes,
-            const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
-            PostCallback& callback, QualityOfService QoS)
+            const std::string& uri, OCConnectivityType connectivityType,
+            const OCRepresentation& attributes, const QueryParamsMap& queryParams,
+            const HeaderOptions& headerOptions, PostCallback& callback, QualityOfService QoS)
             {return OC_STACK_NOTIMPL;}
 
         virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri,
-            const HeaderOptions& headerOptions, DeleteCallback& callback,
-            QualityOfService QoS) {return OC_STACK_NOTIMPL;}
+            OCConnectivityType connectivityType, const HeaderOptions& headerOptions,
+            DeleteCallback& callback, QualityOfService QoS)
+            {return OC_STACK_NOTIMPL;}
 
         virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle,
-            const std::string& host, const std::string& uri, const QueryParamsMap& queryParams,
-            const HeaderOptions& headerOptions,
+            const std::string& host, const std::string& uri, OCConnectivityType connectivityType,
+            const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
             ObserveCallback& callback, QualityOfService QoS){return OC_STACK_NOTIMPL;}
-
         virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host,
             const std::string& uri,
             const HeaderOptions& headerOptions, QualityOfService QoS){return OC_STACK_NOTIMPL;}
-
         virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host,
-            const std::string& resourceType, SubscribeCallback& presenceHandler)
+            const std::string& resourceType, OCConnectivityType connectivityType,
+            SubscribeCallback& presenceHandler)
         {return OC_STACK_NOTIMPL;}
-
         virtual OCStackResult UnsubscribePresence(OCDoHandle handle){return OC_STACK_NOTIMPL;}
 
         virtual OCStackResult GetDefaultQos(QualityOfService& QoS){return OC_STACK_NOTIMPL;}
@@ -84,3 +89,4 @@ namespace OC
 }
 
 #endif
+
index 91c6f15..c9c364c 100644 (file)
@@ -51,6 +51,13 @@ namespace OC
             return OC_STACK_NOTIMPL;
         }
 
+        virtual OCStackResult registerPlatformInfo(
+                    const OCPlatformInfo deviceInfo)
+        {
+            // Not implemented
+            return OC_STACK_NOTIMPL;
+        }
+
         virtual OCStackResult registerResourceWithHost(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceHOST,
index 048a476..4bb245b 100644 (file)
 
 #include <string>
 
-using namespace std;
-
 namespace OC
 {
     namespace InitException
     {
-        static const std::string NO_ERROR                   = "No Error";
-        static const std::string INVALID_URI                = "Invalid URI";
-        static const std::string INVALID_PORT               = "Invalid Port";
-        static const std::string INVALID_IP                 = "Invalid IP";
-        static const std::string INVALID_CB                 = "Invalid Callback";
-        static const std::string INVALID_METHOD             = "Invalid Method";
-        static const std::string GENERAL_FAULT              = "General Fault";
-        static const std::string UNKNOWN_ERROR              = "Unknown Error";
+        static const char NO_ERROR[]                   = "No Error";
+        static const char INVALID_URI[]                = "Invalid URI";
+        static const char INVALID_PORT[]               = "Invalid Port";
+        static const char INVALID_IP[]                 = "Invalid IP";
+        static const char INVALID_CB[]                 = "Invalid Callback";
+        static const char INVALID_METHOD[]             = "Invalid Method";
+        static const char GENERAL_FAULT[]              = "General Fault";
+        static const char UNKNOWN_ERROR[]              = "Unknown Error";
 
-        static const std::string STACK_INIT_ERROR           = "Error Initializing Stack";
-        static const std::string NOT_CONFIGURED_AS_SERVER   =
+        static const char STACK_INIT_ERROR[]           = "Error Initializing Stack";
+        static const char NOT_CONFIGURED_AS_SERVER[]   =
                           "Cannot static construct a Server when configured as a client";
-        static const std::string INVALID_PARAM              = "Invalid Param";
-        static const std::string MISSING_URI                = "Missing URI;";
-        static const std::string MISSING_TYPE               = "Missing Resource Type;";
-        static const std::string MISSING_INTERFACE          = "Missing Interface;";
-        static const std::string MISSING_CLIENT_WRAPPER     = "Missing ClientWrapper;";
+        static const char INVALID_PARAM[]              = "Invalid Param";
+        static const char MISSING_URI[]                = "Missing URI;";
+        static const char MISSING_TYPE[]               = "Missing Resource Type;";
+        static const char MISSING_INTERFACE[]          = "Missing Interface;";
+        static const char MISSING_CLIENT_WRAPPER[]     = "Missing ClientWrapper;";
     }
 
     namespace Exception // Not To Be Confused With 'InitException'
     {
-        static const std::string SVCTYPE_OUTOFPROC          = "ServiceType::OutOfProc";
-        static const std::string BIND_TYPE_FAILED           = "Bind Type to resource failed";
-        static const std::string BIND_INTERFACE_FAILED      = "Bind Interface to resource failed";
-        static const std::string START_PRESENCE_FAILED      = "startPresence failed";
-        static const std::string END_PRESENCE_FAILED        = "stopPresence failed";
-        static const std::string INVALID_ARRAY              = "Array type should have at least []";
-        static const std::string STR_NULL_RESPONSE          = "Response is NULL";
-        static const std::string STR_PAYLOAD_OVERFLOW       = "Payload overflow";
-        static const std::string NIL_GUARD_NULL             = "nullptr at nil_guard()";
-        static const std::string GENERAL_JSON_PARSE_FAILED  = "JSON Parser Error";
-        static const std::string RESOURCE_UNREG_FAILED      = "Unregistering resource failed";
-        static const std::string OPTION_ID_RANGE_INVALID    =
+        static const char SVCTYPE_OUTOFPROC[]          = "ServiceType::OutOfProc";
+        static const char BIND_TYPE_FAILED[]           = "Bind Type to resource failed";
+        static const char BIND_INTERFACE_FAILED[]      = "Bind Interface to resource failed";
+        static const char START_PRESENCE_FAILED[]      = "startPresence failed";
+        static const char END_PRESENCE_FAILED[]        = "stopPresence failed";
+        static const char INVALID_ARRAY[]              = "Array type should have at least []";
+        static const char STR_NULL_RESPONSE[]          = "Response is NULL";
+        static const char STR_PAYLOAD_OVERFLOW[]       = "Payload overflow";
+        static const char NIL_GUARD_NULL[]             = "nullptr at nil_guard()";
+        static const char GENERAL_JSON_PARSE_FAILED[]  = "JSON Parser Error";
+        static const char RESOURCE_UNREG_FAILED[]      = "Unregistering resource failed";
+        static const char OPTION_ID_RANGE_INVALID[]    =
                             "Error: OptionID valid only from 2048 to 3000 inclusive.";
+        static const char NO_ERROR[]                   = "No Error";
+        static const char RESOURCE_CREATED[]           = "Resource Created";
+        static const char RESOURCE_DELETED[]           = "Resource Deleted";
+        static const char INVALID_URI[]                = "Invalid URI";
+        static const char INVALID_IP[]                 = "Invalid IP";
+        static const char INVALID_PORT[]               = "Invalid Port";
+        static const char INVALID_CB[]                 = "Invalid Callback";
+        static const char INVALID_METHOD[]             = "Invalid Method";
+        static const char INVALID_QUERY[]              = "Invalid Query";
+        static const char INVALID_PARAM[]              = "Invalid Param";
+        static const char INVALID_OBESERVE[]           = "Invalid Observe Param";
+        static const char NO_MEMORY[]                  = "No Memory";
+        static const char COMM_ERROR[]                 = "Communication Error";
+        static const char TIMEOUT[]                    = "Timeout";
+        static const char ADAPTER_NOT_ENABLED[]        = "Adapter Not Enabled";
+        static const char NOT_IMPL[]                   = "Not Implemented";
+        static const char NOT_FOUND[]                  = "Resource Not Found";
+        static const char RESOURCE_ERROR[]             = "Resource Error";
+        static const char SLOW_RESOURCE[]              = "Slow Resource";
+        static const char NO_OBSERVERS[]               = "No Observers";
+        static const char OBSV_NO_FOUND[]              = "Stack observer not found";
+        static const char OBSV_NOT_ADDED[]             = "Stack observer not added";
+        static const char OBSV_NOT_REMOVED[]           = "Stack observer not removed";
+        static const char STACK_RESOURCE_DELETED[]     = "The specified resource has been deleted";
+        static const char PRESENCE_STOPPED[]           = "Stack presence stopped";
+        static const char PRESENCE_TIMEOUT[]           = "Stack presence timed out";
+        static const char PRESENCE_NOT_HANDLED[]       = "Stack presence should not be handled";
+        static const char INVALID_OPTION[]             = "Invalid option";
+        static const char GENERAL_FAULT[]              = "General Fault";
+        static const char MALFORMED_STACK_RESPONSE[]   = "Response from OC_STACK is malformed";
+        static const char VIRTUAL_DO_NOT_HANDLE[]      = "Virtual Do Not Handle";
+        static const char PERSISTENT_BUFFER_REQUIRED[] = "Persistent response buffer required";
+        static const char STACK_CONTINUE[]             = "Stack continue";
+        static const char INVALID_REQUEST_HANDLE[]     = "Invalid request handle";
+        static const char UNKNOWN_ERROR[]              = "Unknown Error";
+        static const char INVALID_REPRESENTATION[]     = "Invalid Payload JSON";
+        static const char INVALID_JSON_TYPE[]          = "Unrecognized JSON Type ";
+        static const char INVALID_JSON_NUMERIC[]       = "Unrecognized JSON Numeric ";
+        static const char INVALID_JSON_ARRAY_DEPTH[]   = "Max JSON Array Depth exceeded";
+        static const char INVALID_JSON_TYPE_TAG[]      = "Invalid JSON Type Tag";
+        static const char INVALID_ATTRIBUTE[]          = "Invalid Attribute: ";
+        static const char INVALID_DEVICE_INFO[]        = "Invalid Device Information";
 
-        static const std::string NO_ERROR                   = "No Error";
-        static const std::string RESOURCE_CREATED           = "Resource Created";
-        static const std::string RESOURCE_DELETED           = "Resource Deleted";
-        static const std::string INVALID_URI                = "Invalid URI";
-        static const std::string INVALID_IP                 = "Invalid IP";
-        static const std::string INVALID_PORT               = "Invalid Port";
-        static const std::string INVALID_CB                 = "Invalid Callback";
-        static const std::string INVALID_METHOD             = "Invalid Method";
-        static const std::string INVALID_QUERY              = "Invalid Query";
-        static const std::string INVALID_PARAM              = "Invalid Param";
-        static const std::string INVALID_OBESERVE           = "Invalid Observe Param";
-        static const std::string NO_MEMORY                  = "No Memory";
-        static const std::string COMM_ERROR                 = "Communication Error";
-        static const std::string NOT_IMPL                   = "Not Implemented";
-        static const std::string NOT_FOUND                  = "Resource Not Found";
-        static const std::string RESOURCE_ERROR             = "Resource Error";
-        static const std::string SLOW_RESOURCE              = "Slow Resource";
-        static const std::string NO_OBSERVERS               = "No Observers";
-        static const std::string OBSV_NO_FOUND              = "Stack observer not found";
-        static const std::string OBSV_NOT_ADDED             = "Stack observer not added";
-        static const std::string OBSV_NOT_REMOVED           = "Stack observer not removed";
-        static const std::string STACK_RESOURCE_DELETED     = "The specified resource has been deleted";
-        static const std::string PRESENCE_STOPPED           = "Stack presence stopped";
-        static const std::string PRESENCE_TIMEOUT           = "Stack presence timed out";
-        static const std::string PRESENCE_NOT_HANDLED       = "Stack presence should not be handled";
-        static const std::string INVALID_OPTION             = "Invalid option";
-        static const std::string GENERAL_FAULT              = "General Fault";
-        static const std::string MALFORMED_STACK_RESPONSE   = "Response from OC_STACK is malformed";
-        static const std::string VIRTUAL_DO_NOT_HANDLE      = "Virtual Do Not Handle";
-        static const std::string PERSISTENT_BUFFER_REQUIRED = "Persistent response buffer required";
-        static const std::string STACK_CONTINUE             = "Stack continue";
-        static const std::string INVALID_REQUEST_HANDLE     = "Invalid request handle";
-        static const std::string UNKNOWN_ERROR              = "Unknown Error";
-        static const std::string INVALID_REPRESENTATION     = "Invalid Payload JSON";
-        static const std::string INVALID_JSON_TYPE          = "Unrecognized JSON Type ";
-        static const std::string INVALID_JSON_NUMERIC       = "Unrecognized JSON Numeric ";
-        static const std::string INVALID_JSON_ARRAY_DEPTH   = "Max JSON Array Depth exceeded";
-        static const std::string INVALID_JSON_TYPE_TAG      = "Invalid JSON Type Tag";
-        static const std::string INVALID_ATTRIBUTE          = "Invalid Attribute: ";
     }
 
     namespace Error
     {
-        static const std::string INVALID_IP                 = "Invalid IP";
+        static const char INVALID_IP[]                 = "Invalid IP";
     }
 
     namespace PlatformCommands
@@ -129,8 +130,10 @@ namespace OC
         static const std::string REPKEY                     = "rep";
         static const std::string SECUREKEY                  = "sec";
         static const std::string PORTKEY                    = "port";
-  }
+        static const std::string SERVERIDKEY                = "sid";
+    }
 
 }
 
 #endif // _STRING_CONSTANTS_H_
+
diff --git a/resource/makefile b/resource/makefile
deleted file mode 100644 (file)
index a710781..0000000
+++ /dev/null
@@ -1,129 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD     := release
-CXX       := g++
-#CXX     := clang
-
-ifeq ($(ROOT_DIR), )
-       ROOT_DIR := $(PWD)
-endif
-ifeq ($(PLATFORM), )
-       PLATFORM := "linux"
-endif
-
-DEPEND_DIR:= $(ROOT_DIR)/dependencies
-CEREAL_DIR:= $(DEPEND_DIR)/cereal
-
-OUT_DIR          := $(ROOT_DIR)/$(BUILD)
-OBJ_DIR          := $(OUT_DIR)/obj
-
-CXX_FLAGS.debug     := -g3 -std=c++0x -Wall -pthread -O0
-CXX_FLAGS.release   := -std=c++0x -Wall -pthread -O3
-
-CXX_INC          := -I./include/
-CXX_INC          += -I./oc_logger/include
-
-CXX_INC          += -I./csdk/stack/include
-CXX_INC          += -I./csdk/ocsocket/include
-CXX_INC          += -I./csdk/ocrandom/include
-CXX_INC          += -I./csdk/logger/include
-CXX_INC          += -I./csdk/libcoap
-CXX_INC   += -I$(CEREAL_DIR)/include
-# Force metatargets to build:
-all.PHONY: applyDepPatches prep_dirs c_sdk oc_logger_target liboc.a examples
-
-buildScript_all.PHONY: applyDepPatches prep_dirs oc_logger_target liboc.a
-
-all:   all.PHONY
-
-buildScript_all:  buildScript_all.PHONY
-
-prep_dirs: deps
-       -mkdir -p $(OUT_DIR)
-       -mkdir -p $(OBJ_DIR)
-
-# used to fetch all dependencies
-deps:
-       -mkdir -p $(DEPEND_DIR)
-#cereal fetch
-       if [ ! -d "$(CEREAL_DIR)" ]; then\
-               cd $(DEPEND_DIR) && git clone https://github.com/USCiLab/cereal.git;\
-               cd $(CEREAL_DIR) && git checkout 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245;\
-       fi
-
-applyDepPatches: deps
-#reset git to the 'base version', so we can apply our patch without issues
-       cd $(CEREAL_DIR) && git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245;
-       cd $(CEREAL_DIR) && git apply $(ROOT_DIR)/patches/cereal_gcc46.patch
-
-c_sdk:
-       cd csdk && $(MAKE) "BUILD=$(BUILD)" "PLATFORM=$(PLATFORM)"
-
-oc_logger_target:
-       cd oc_logger && $(MAKE) "BUILD=$(BUILD)"
-
-cpp_sdk: prep_dirs c_sdk liboc.a
-
-examples: liboc.a
-       cd examples && $(MAKE) apps "BUILD=$(BUILD)"
-
-liboc.a: OCPlatform_impl.o OCPlatform.o OCResource.o OCException.o OCUtilities.o InProcServerWrapper.o InProcClientWrapper.o OCRepresentation.o
-       ar -cvq $(OBJ_DIR)/liboc.a $(OBJ_DIR)/OCPlatform_impl.o $(OBJ_DIR)/OCPlatform.o $(OBJ_DIR)/OCResource.o $(OBJ_DIR)/OCException.o $(OBJ_DIR)/OCUtilities.o $(OBJ_DIR)/InProcServerWrapper.o $(OBJ_DIR)/InProcClientWrapper.o $(OBJ_DIR)/OCRepresentation.o
-
-OCPlatform_impl.o: src/OCPlatform_impl.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCPlatform_impl.cpp $(CXX_INC)
-
-OCPlatform.o: src/OCPlatform.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCPlatform.cpp $(CXX_INC)
-
-OCRepresentation.o: src/OCRepresentation.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCRepresentation.cpp $(CXX_INC)
-
-OCResource.o: src/OCResource.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCResource.cpp $(CXX_INC)
-
-OCException.o: src/OCException.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCException.cpp $(CXX_INC)
-
-OCUtilities.o: src/OCUtilities.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCUtilities.cpp $(CXX_INC)
-
-InProcServerWrapper.o: src/InProcServerWrapper.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/InProcServerWrapper.cpp $(CXX_INC)
-
-InProcClientWrapper.o: src/InProcClientWrapper.cpp
-       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/InProcClientWrapper.cpp $(CXX_INC)
-
-clean: clean_legacy
-       -rm -rf release
-       -rm -rf debug
-       cd oc_logger && $(MAKE) clean
-
-clean_cpp_sdk: clean_legacy
-       -rm -rf release
-       -rm -rf debug
-
-clean_legacy:
-       -rm -f -v $(OBJ_DIR)/liboc.a $(OBJ_DIR)/*.o
-       cd csdk && $(MAKE) clean
-       cd csdk && $(MAKE) deepclean
diff --git a/resource/oc_logger/Makefile b/resource/oc_logger/Makefile
deleted file mode 100644 (file)
index 5637e5e..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD := release
-
-LIB_DIR=./lib/
-BIN_DIR=./bin/
-
-.PHONY: c_lib cpp_lib static_libs examples samples
-
-all: dirs c_lib cpp_lib static_libs examples samples
-
-dirs:
-       -mkdir -p $(LIB_DIR) $(BIN_DIR)
-
-c_lib:
-       cd c && $(MAKE) "BUILD=$(BUILD)"
-
-cpp_lib:
-       cd cpp && $(MAKE) "BUILD=$(BUILD)"
-
-static_libs:
-       ar -cvq $(LIB_DIR)/oc_logger_core.a $(BIN_DIR)/oc_logger.o
-       ar -cvq $(LIB_DIR)/oc_logger.a $(BIN_DIR)/oc_logger.o $(BIN_DIR)/targets/*.o
-
-examples:
-       cd examples && $(MAKE) "BUILD=$(BUILD)"
-
-samples:
-       cd samples/linux && $(MAKE) "BUILD=$(BUILD)"
-
-clean:
-       cd examples && $(MAKE) "clean"
-       cd samples/linux && $(MAKE) "clean"
-       rm -rf $(BIN_DIR)/targets/*.o
-       cd cpp && $(MAKE) clean
-       cd c && $(MAKE) clean
index 5cb21cb..8bd1edc 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
 ##
@@ -16,7 +36,7 @@ liboc_logger_env.PrependUnique(CPPPATH = ['include'])
 target_os = env.get('TARGET_OS')
 if target_os == 'android':
        liboc_logger_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       liboc_logger_env.AppendUnique(LIBS = ['gnustl_static', 'log'])
+       liboc_logger_env.AppendUnique(LIBS = ['gnustl_shared', 'log'])
 
 if target_os not in ['arduino', 'windows', 'winrt']:
        liboc_logger_env.AppendUnique(CFLAGS = ['-Wall', '-std=c99', '-fPIC'])
@@ -25,11 +45,12 @@ if target_os not in ['arduino', 'windows', 'winrt']:
 ######################################################################
 # Source files and Targets
 ######################################################################
-shared_liboc_logger_core = liboc_logger_env.SharedLibrary('oc_logger_core', 'c/oc_logger.c',  OBJPREFIX='core_')
-shared_liboc_logger      = liboc_logger_env.SharedLibrary('oc_logger', ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp'])
-static_liboc_logger      = liboc_logger_env.StaticLibrary('oc_logger', ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp'])
+liboc_logger_core = liboc_logger_env.SharedLibrary('oc_logger_core', 'c/oc_logger.c',  OBJPREFIX='core_')
+liboc_logger = liboc_logger_env.SharedLibrary('oc_logger',
+               ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp'])
 
-liboc_logger_env.InstallTarget([shared_liboc_logger_core, shared_liboc_logger, static_liboc_logger ], 'liboc_logger')
+liboc_logger_env.InstallTarget([liboc_logger_core, liboc_logger], 'liboc_logger')
 
-if target_os not in ['ios']:
+if target_os not in ['ios', 'android']:
        SConscript('examples/SConscript')
+
diff --git a/resource/oc_logger/c/Makefile b/resource/oc_logger/c/Makefile
deleted file mode 100644 (file)
index 5d55318..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-BUILD := release
-
-CC_FLAGS.debug=-Wall -std=c99 -Werror -O0 -g
-CC_FLAGS.release=-Wall -std=c99 -Werror -O2
-
-INC=-I../include/
-CC:=gcc
-
-BIN_DIR=../bin
-LIB_DIR=../lib
-TEST_DIR=../test
-
-LIB=$(LIB_DIR)/oc_logger.a
-
-CCX=$(CC) $(CC_FLAGS.$(BUILD))
-
-all: setup c_lib c_targets
-
-setup:
-       mkdir -p $(BIN_DIR) $(LIB_DIR)
-       mkdir -p $(BIN_DIR)/targets
-       mkdir -p $(TEST_DIR)
-
-c_lib:
-       $(CCX) $(INC) -c -o $(BIN_DIR)/oc_logger.o oc_logger.c
-
-c_targets:
-       $(CCX) $(INC) -c -o $(BIN_DIR)/targets/oc_console_logger.o oc_console_logger.c
-
-clean:
-       rm -rf -v \*\.o test_logging $(BIN_DIR)/* $(LIB_DIR)/*
index 4c3db1a..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__ > level || __OC_LOG_MAX__ < level)
-  return 0;
+ if(OC_LOG_MIN_VAL__ >= level || OC_LOG_MAX_VAL__ <= level)
+ {
+     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);
 }
 
+
diff --git a/resource/oc_logger/cpp/Makefile b/resource/oc_logger/cpp/Makefile
deleted file mode 100644 (file)
index 0b2c41e..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-BIN_DIR=../bin
-LIB_DIR=../lib
-
-INC=-I../include/
-
-LIB=$(LIB_DIR)/oc_logger.a
-
-BUILD := release
-
-CXX_FLAGS.debug=-Wall -std=c++0x -O0 -g
-CXX_FLAGS.release=-Wall -std=c++0x -O2
-
-CXX := g++
-
-CXX_X=$(CXX) $(CXX_FLAGS.$(BUILD)) $(INC)
-
-all: dirs targets
-
-dirs:
-       -mkdir -p $(BIN_DIR)/targets
-
-targets:
-       $(CXX_X) -c -o $(BIN_DIR)/targets/oc_ostream_logger.o oc_ostream_logger.cpp
-
-clean:
-       rm -f ./test_logging ./*.o
diff --git a/resource/oc_logger/examples/Makefile b/resource/oc_logger/examples/Makefile
deleted file mode 100644 (file)
index 7cf1073..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-BUILD := release
-
-CC_FLAGS.debug=-Wall -std=c99 -Werror -O0 -g
-CC_FLAGS.release=-Wall -std=c99 -Werror -O2
-
-CXX_FLAGS.debug=-Wall -std=c++0x -O0 -g
-CXX_FLAGS.release=-Wall -std=c++0x -O2
-
-CXX_STDLIB=-lstdc++
-
-CC:=gcc
-CXX:=g++
-CXX_X=$(CXX) $(CXX_FLAGS.$(BUILD)) $(INC)
-
-INC=-I../include/
-
-BIN_DIR=../bin
-LIB_DIR=../lib
-
-CC_LIB=$(LIB_DIR)/oc_logger.a $(CXX_STDLIB)
-CXX_LIB=$(LIB_DIR)/oc_logger.a $(CXX_STDLIB)
-
-CCX=$(CC) $(CC_FLAGS.$(BUILD))
-
-all: examples_c examples_cpp
-
-examples_c:
-       $(CCX) $(INC) -o $(BIN_DIR)/test_logging test_logging.c $(CC_LIB)
-
-examples_cpp:
-       $(CXX_X) -o $(BIN_DIR)/test_logging_cpp test_logging.cpp $(CXX_LIB)
-
-clean:
-       rm -f $(BIN_DIR)/test_logging $(BIN_DIR)/test_logging_cpp
-
index de1ab4a..a3a4c91 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
 ##
@@ -18,7 +38,7 @@ examples_env.AppendUnique(LIBS = ['oc_logger', 'stdc++'])
 target_os = env.get('TARGET_OS')
 if target_os == 'android':
        examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       examples_env.AppendUnique(LIBS = ['gnustl_static'])
+       examples_env.AppendUnique(LIBS = ['gnustl_shared'])
 
 if target_os not in ['arduino', 'windows', 'winrt']:
        examples_env.AppendUnique(CFLAGS = Split('-Wall -std=c99 -Werror'))
@@ -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 4789711..2c807c7 100644 (file)
@@ -27,8 +27,9 @@
  extern "C" {
 #endif
 
- typedef enum {
-     __OC_LOG_MIN__     = -1,
+ typedef enum
+ {
+     OC_LOG_MIN_VAL__   = -1,
      OC_LOG_ALL         = 0,
      OC_LOG_FATAL,
      OC_LOG_ERROR,
@@ -36,7 +37,7 @@
      OC_LOG_INFO,
      OC_LOG_DEBUG,
      OC_LOG_DISABLED,
-     __OC_LOG_MAX__
+     OC_LOG_MAX_VAL__
  } oc_log_level;
 
 typedef struct _oc_log_ctx
@@ -82,3 +83,4 @@ typedef int    (*oc_log_try_lock_t)      (oc_log_ctx_t *);
 #endif
 
 #endif
+
diff --git a/resource/oc_logger/samples/linux/makefile b/resource/oc_logger/samples/linux/makefile
deleted file mode 100644 (file)
index 6c3bb87..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD   := release
-PLATFORM := linux
-CC      := g++
-OUT_DIR          := $(BUILD)
-OBJ_DIR          := $(OUT_DIR)/obj
-
-ifeq ($(ROOT_DIR), )
-ROOT_DIR       = ../../../csdk
-endif
-
-OUT_DIR        = ./
-
-OCLOGGER_DIR   = $(ROOT_DIR)/logger
-OC_LOG_DIR             = $(ROOT_DIR)/../oc_logger
-OCRANDOM_DIR   = $(ROOT_DIR)/ocrandom
-OCSOCKET_DIR   = $(ROOT_DIR)/ocsocket
-LCOAP_DIR              = $(ROOT_DIR)/libcoap-4.1.1
-OCCOAP_DIR             = $(ROOT_DIR)/occoap
-OCTBSTACK_DIR  = $(ROOT_DIR)/stack
-
-OC_LOG_INC             = $(OC_LOG_DIR)/include
-OC_LOG_LIB             = $(OC_LOG_DIR)/lib/oc_logger.a  
-
-OCLOGGER_INC   = $(OCLOGGER_DIR)/include
-OCRANDOM_INC   = $(OCRANDOM_DIR)/include
-OCSOCKET_INC   = $(OCSOCKET_DIR)/include
-LCOAP_INC              = $(LCOAP_DIR)
-OCCOAP_INC             = $(OCCOAP_DIR)/include
-OCTBSTACK_INC  = $(OCTBSTACK_DIR)/include
-
-INC_DIRS               := -I$(OCLOGGER_INC)
-INC_DIRS               += -I$(OC_LOG_INC)
-INC_DIRS               += -I$(OCRANDOM_INC)
-INC_DIRS               += -I$(OCSOCKET_INC)
-INC_DIRS               += -I$(LCOAP_INC)
-INC_DIRS               += -I$(OCCOAP_INC)
-INC_DIRS               += -I$(OCTBSTACK_INC)
-
-CC_FLAGS.debug      := -O0 -g3 -Wall -ffunction-sections -fdata-sections \
-                        -std=c99 $(INC_DIRS) -L$(ROOT_DIR)/$(PLATFORM)/$(BUILD) -DTB_LOG
-CC_FLAGS.release    := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s \
-                        -std=c99 $(INC_DIRS) -L$(ROOT_DIR)/$(PLATFORM)/$(BUILD)
-
-LDLIBS         += $(OC_LOG_LIB) -loctbstack -lpthread 
-CPPFLAGS       += $(CC_FLAGS.$(BUILD)) $(LDLIBS)
-
-SOURCES     := test_logging.c
-
-OBJECTS:= $(patsubst %.c, $(OBJ_DIR)/%.o, $(SOURCES))
-
-PROGRAMS       += test_logging
-
-all:   prep_dirs $(OBJECTS) $(PROGRAMS)
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-       -mkdir -p $(OBJ_DIR)
-
-$(OBJ_DIR)/%.o: %.c
-       $(CC) -c $(CPPFLAGS) $< -o $@
-
-test_logging: $(OBJ_DIR)/test_logging.o 
-       $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@
-
-.PHONY: clean
-
-clean: legacy_clean
-       -rm -rf release
-       -rm -rf debug
-
-legacy_clean:
-       rm -f *.o $(PROGRAMS)
diff --git a/resource/patches/user-config-arm-linux-androideabi.jam b/resource/patches/user-config-arm-linux-androideabi.jam
new file mode 100644 (file)
index 0000000..bea3cee
--- /dev/null
@@ -0,0 +1,137 @@
+# Copyright 2003, 2005 Douglas Gregor
+# Copyright 2004 John Maddock
+# Copyright 2002, 2003, 2004, 2007 Vladimir Prus
+# Distributed under the Boost Software License, Version 1.0.
+# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
+
+#   This file is used to configure your Boost.Build installation. You can modify
+# this file in place, or you can place it in a permanent location so that it
+# does not get overwritten should you get a new version of Boost.Build. See:
+#
+#   http://www.boost.org/boost-build2/doc/html/bbv2/overview/configuration.html
+#
+# for documentation about possible permanent locations.
+
+#   This file specifies which toolsets (C++ compilers), libraries, and other
+# tools are available. Often, you should be able to just uncomment existing
+# example lines and adjust them to taste. The complete list of supported tools,
+# and configuration instructions can be found at:
+#
+#   http://boost.org/boost-build2/doc/html/bbv2/reference/tools.html
+#
+
+#   This file uses Jam language syntax to describe available tools. Mostly,
+# there are 'using' lines, that contain the name of the used tools, and
+# parameters to pass to those tools -- where paremeters are separated by
+# semicolons. Important syntax notes:
+#
+#   - Both ':' and ';' must be separated from other tokens by whitespace
+#   - The '\' symbol is a quote character, so when specifying Windows paths you
+#     should use '/' or '\\' instead.
+#
+# More details about the syntax can be found at:
+#
+#   http://boost.org/boost-build2/doc/html/bbv2/advanced.html#bbv2.advanced.jam_language
+#
+
+# ------------------
+# GCC configuration.
+# ------------------
+
+# Configure gcc (default version).
+# using gcc ;
+
+# Configure specific gcc version, giving alternative name to use.
+# using gcc : 3.2 : g++-3.2 ;
+
+import os ;
+
+local androidNDK = [ os.environ ANDROID_NDK ] ;
+local platform = [ os.environ PLATFORM ] ;
+local version = [ os.environ VERSION ] ;
+
+using gcc : : arm-linux-androideabi-g++ :
+     <archiver>arm-linux-androideabi-ar
+     <ranlib>arm-linux-androideabi-ranlib
+    <compileflags>-fexceptions
+    <compileflags>-frtti
+    <compileflags>-fpic
+    <compileflags>-ffunction-sections
+    <compileflags>-funwind-tables
+    <compileflags>-D__ARM_ARCH_5__
+    <compileflags>-D__ARM_ARCH_5T__
+    <compileflags>-D__ARM_ARCH_5E__
+    <compileflags>-D__ARM_ARCH_5TE__
+    <compileflags>-Wno-psabi
+    <compileflags>-march=armv5te
+    <compileflags>-mtune=xscale
+    <compileflags>-msoft-float
+    <compileflags>-mthumb
+    <compileflags>-Os
+    <compileflags>-fomit-frame-pointer
+    <compileflags>-fno-strict-aliasing
+    <compileflags>-finline-limit=64
+    <compileflags>-I$(androidNDK)/platforms/$(platform)/arch-arm/usr/include
+    <compileflags>-Wa,--noexecstack
+    <compileflags>-DANDROID
+    <compileflags>-D__ANDROID__
+    <compileflags>-DNDEBUG
+    <compileflags>-O2
+    <compileflags>-g
+    <compileflags>-I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/include
+    <compileflags>-I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/libs/armeabi/include
+    # @Moss - Above are the 'oficial' android flags
+    <architecture>arm
+    <compileflags>-fvisibility=hidden
+    <compileflags>-fvisibility-inlines-hidden
+    <compileflags>-fdata-sections
+    <cxxflags>-D__arm__
+    <cxxflags>-D_REENTRANT
+    <cxxflags>-D_GLIBCXX__PTHREADS
+         ;
+
+# -------------------
+# MSVC configuration.
+# -------------------
+
+# Configure msvc (default version, searched for in standard locations and PATH).
+# using msvc ;
+
+# Configure specific msvc version (searched for in standard locations and PATH).
+# using msvc : 8.0 ;
+
+
+# ----------------------
+# Borland configuration.
+# ----------------------
+# using borland ;
+
+
+# ----------------------
+# STLPort configuration.
+# ----------------------
+
+#   Configure specifying location of STLPort headers. Libraries must be either
+# not needed or available to the compiler by default.
+# using stlport : : /usr/include/stlport ;
+
+# Configure specifying location of both headers and libraries explicitly.
+# using stlport : : /usr/include/stlport /usr/lib ;
+
+
+# -----------------
+# QT configuration.
+# -----------------
+
+# Configure assuming QTDIR gives the installation prefix.
+# using qt ;
+
+# Configure with an explicit installation prefix.
+# using qt : /usr/opt/qt ;
+
+# ---------------------
+# Python configuration.
+# ---------------------
+
+# Configure specific Python version.
+# using python : 3.1 : /usr/bin/python3 : /usr/include/python3.1 : /usr/lib ;
diff --git a/resource/patches/user-config-x86.jam b/resource/patches/user-config-x86.jam
new file mode 100644 (file)
index 0000000..bb0a2e3
--- /dev/null
@@ -0,0 +1,137 @@
+# Copyright 2003, 2005 Douglas Gregor
+# Copyright 2004 John Maddock
+# Copyright 2002, 2003, 2004, 2007 Vladimir Prus
+# Distributed under the Boost Software License, Version 1.0.
+# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
+
+#   This file is used to configure your Boost.Build installation. You can modify
+# this file in place, or you can place it in a permanent location so that it
+# does not get overwritten should you get a new version of Boost.Build. See:
+#
+#   http://www.boost.org/boost-build2/doc/html/bbv2/overview/configuration.html
+#
+# for documentation about possible permanent locations.
+
+#   This file specifies which toolsets (C++ compilers), libraries, and other
+# tools are available. Often, you should be able to just uncomment existing
+# example lines and adjust them to taste. The complete list of supported tools,
+# and configuration instructions can be found at:
+#
+#   http://boost.org/boost-build2/doc/html/bbv2/reference/tools.html
+#
+
+#   This file uses Jam language syntax to describe available tools. Mostly,
+# there are 'using' lines, that contain the name of the used tools, and
+# parameters to pass to those tools -- where paremeters are separated by
+# semicolons. Important syntax notes:
+#
+#   - Both ':' and ';' must be separated from other tokens by whitespace
+#   - The '\' symbol is a quote character, so when specifying Windows paths you
+#     should use '/' or '\\' instead.
+#
+# More details about the syntax can be found at:
+#
+#   http://boost.org/boost-build2/doc/html/bbv2/advanced.html#bbv2.advanced.jam_language
+#
+
+# ------------------
+# GCC configuration.
+# ------------------
+
+# Configure gcc (default version).
+# using gcc ;
+
+# Configure specific gcc version, giving alternative name to use.
+# using gcc : 3.2 : g++-3.2 ;
+
+import os ;
+
+local androidNDK = [ os.environ ANDROID_NDK ] ;
+local platform = [ os.environ PLATFORM ] ;
+local version = [ os.environ VERSION ] ;
+
+using gcc : : i686-linux-android-g++ :
+     <archiver>i686-linux-android-ar
+     <ranlib>i686-linux-android-ranlib
+    <compileflags>-fexceptions
+    <compileflags>-frtti
+    <compileflags>-fpic
+    <compileflags>-ffunction-sections
+    <compileflags>-funwind-tables
+#    <compileflags>-D__ARM_ARCH_5__
+#    <compileflags>-D__ARM_ARCH_5T__
+#    <compileflags>-D__ARM_ARCH_5E__
+#    <compileflags>-D__ARM_ARCH_5TE__
+    <compileflags>-Wno-psabi
+#    <compileflags>-march=armv5te
+#    <compileflags>-mtune=xscale
+#    <compileflags>-msoft-float
+#    <compileflags>-mthumb
+    <compileflags>-Os
+    <compileflags>-fomit-frame-pointer
+    <compileflags>-fno-strict-aliasing
+    <compileflags>-finline-limit=64
+    <compileflags>-I$(androidNDK)/platforms/$(platform)/arch-x86/usr/include
+    <compileflags>-Wa,--noexecstack
+    <compileflags>-DANDROID
+    <compileflags>-D__ANDROID__
+    <compileflags>-DNDEBUG
+    <compileflags>-O2
+    <compileflags>-g
+    <compileflags>-I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/include
+    <compileflags>-I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/libs/armeabi/include
+    # @Moss - Above are the 'oficial' android flags
+    <architecture>x86
+    <compileflags>-fvisibility=hidden
+    <compileflags>-fvisibility-inlines-hidden
+    <compileflags>-fdata-sections
+#    <cxxflags>-D__arm__
+    <cxxflags>-D_REENTRANT
+    <cxxflags>-D_GLIBCXX__PTHREADS
+         ;
+
+# -------------------
+# MSVC configuration.
+# -------------------
+
+# Configure msvc (default version, searched for in standard locations and PATH).
+# using msvc ;
+
+# Configure specific msvc version (searched for in standard locations and PATH).
+# using msvc : 8.0 ;
+
+
+# ----------------------
+# Borland configuration.
+# ----------------------
+# using borland ;
+
+
+# ----------------------
+# STLPort configuration.
+# ----------------------
+
+#   Configure specifying location of STLPort headers. Libraries must be either
+# not needed or available to the compiler by default.
+# using stlport : : /usr/include/stlport ;
+
+# Configure specifying location of both headers and libraries explicitly.
+# using stlport : : /usr/include/stlport /usr/lib ;
+
+
+# -----------------
+# QT configuration.
+# -----------------
+
+# Configure assuming QTDIR gives the installation prefix.
+# using qt ;
+
+# Configure with an explicit installation prefix.
+# using qt : /usr/opt/qt ;
+
+# ---------------------
+# Python configuration.
+# ---------------------
+
+# Configure specific Python version.
+# using python : 3.1 : /usr/bin/python3 : /usr/include/python3.1 : /usr/lib ;
diff --git a/resource/releaseNotes/Feb1st2015.txt b/resource/releaseNotes/Feb1st2015.txt
new file mode 100644 (file)
index 0000000..e80246e
--- /dev/null
@@ -0,0 +1,82 @@
+Release notes
+****************************************************************************
+Release date: Feb 1st, 2015.
+OS: Ubuntu 12.0.4 and above
+Requires boost version 1.55 to build.
+Code buildable in gcc 4.6.3 and above.
+NOTE: Boost is not distributed but should be installed in the Ubuntu machine.
+*****************************************************************************
+
+Branch: master; commit id: 3deba10f91d5d5990bf29cab4f6283e98dacf12a
+*******************************************************************
+
+What is new?
+
+1. Fixed issues found in C++ stack and samples using static code analysis tool.
+
+2. Bug fixes
+- tinyDTLS rehandshake issue fixed.
+- IOT 273
+- IOT 114
+
+General notes:
+--------------
+Maximum length of URI supported is 64 bytes (sent from the client)
+Maximum length of query supported is 64 bytes (sent from the client)
+Maximum length of request from client and response from server for Arduino is is 256 bytes
+Maximum length of request from client and response from server for non-Ardunio is is 1024 bytes
+
+OIC base supports Arduino WiFi shield.
+This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library.
+Please refer to oic-resource/csdk/README file for building OIC base with WiFi support.
+
+--------
+Samples:
+--------
+
+C++ Samples
+-----------
+
+A basic sample for hosting a resource on a server and a sample for client for discovering resources
+are provided here:
+Simple server sample location: oic-resource/examples/simpleserver.cpp
+Simple client sample location: oic-resource/examples/simpleclient.cpp
+Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp
+Simpleserver and simpleclient samples also provide examples for doing POST operation.
+Simpleserver also demonstrates slow response case for a GET request.
+
+Garage samples provide usage of OCRepresentation, get/set attribute values
+oic-resource/examples/garageclient.cpp
+oic-resource/examples/garageserver.cpp
+
+Fridge samples provide usage of constructResourceObject API, std bind
+(for mapping request and responses), default
+device entity handler, header options support and Delete operation.
+oic-resource/examples/fridgeclient.cpp
+oic-resource/examples/fridgeserver.cpp
+
+Presence samples provides examples to use presence APIs
+Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp
+Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp
+
+Room samples provides examples to use resource collection.
+oic-resource/examples/roomclient.cpp
+oic-resource/examples/roomserver.cpp
+
+After building the code in oic-resource, executables for samples are in directory named
+'oic-resource/samples/release'.
+After building the code in oic-resource, executables are in directory named 'oic-resource/release'.
+
+C Samples
+---------
+Collection samples are demonstrated in:
+ocservercoll and occlientcoll
+
+Slow response feature is demonstrated in:
+ocserverslow and occlientslow
+
+Client and server basic operations -- discovery, GET, PUT, POST (NON messages) demonstrated in:
+ocserverbasicops and occlientbasicops
+
+Client and server - discovery, GET,PUT,POST,DELETE,OBS for both NON and CON demonstrated in:
+ocserver and occlient
diff --git a/resource/releaseNotes/Jan17th2015.txt b/resource/releaseNotes/Jan17th2015.txt
new file mode 100644 (file)
index 0000000..0024a3a
--- /dev/null
@@ -0,0 +1,85 @@
+Release notes
+****************************************************************************
+Release date: Jan 17th, 2015.
+OS: Ubuntu 12.0.4 and above
+Requires boost version 1.55 to build.
+Code buildable in gcc 4.6.3 and above.
+NOTE: Boost is not distributed but should be installed in the Ubuntu machine.
+*****************************************************************************
+
+Branch: master
+***************
+
+What is new?
+
+1. OICSensorBoard Sample app added for Intel Edison platform
+- Location: iotivity/examples/OICSensorBoard
+- Details and instructions provided in iotivity/examples/OICSensorBoard/OICSensorBoardREADME.pdf
+
+2. OICMiddle Sample app added for demonstrating OIC Yocto capability
+- Location: iotivity/examples/OICMiddle
+- Details and instructions provided in iotivity/examples/OICMiddle/README
+
+3. Multiple bug fixes updated in Jira.
+
+General notes:
+--------------
+Maximum length of URI supported is 64 bytes (sent from the client)
+Maximum length of query supported is 64 bytes (sent from the client)
+Maximum length of request from client and response from server for Arduino is is 256 bytes
+Maximum length of request from client and response from server for non-Ardunio is is 1024 bytes
+
+OIC base supports Arduino WiFi shield.
+This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library.
+Please refer to oic-resource/csdk/README file for building OIC base with WiFi support.
+
+--------
+Samples:
+--------
+
+C++ Samples
+-----------
+
+A basic sample for hosting a resource on a server and a sample for client for discovering resources
+are provided here:
+Simple server sample location: oic-resource/examples/simpleserver.cpp
+Simple client sample location: oic-resource/examples/simpleclient.cpp
+Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp
+Simpleserver and simpleclient samples also provide examples for doing POST operation.
+Simpleserver also demonstrates slow response case for a GET request.
+
+Garage samples provide usage of OCRepresentation, get/set attribute values
+oic-resource/examples/garageclient.cpp
+oic-resource/examples/garageserver.cpp
+
+Fridge samples provide usage of constructResourceObject API, std bind
+(for mapping request and responses), default
+device entity handler, header options support and Delete operation.
+oic-resource/examples/fridgeclient.cpp
+oic-resource/examples/fridgeserver.cpp
+
+Presence samples provides examples to use presence APIs
+Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp
+Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp
+
+Room samples provides examples to use resource collection.
+oic-resource/examples/roomclient.cpp
+oic-resource/examples/roomserver.cpp
+
+After building the code in oic-resource, executables for samples are in directory named
+'oic-resource/samples/release'.
+After building the code in oic-resource, executables are in directory named 'oic-resource/release'.
+
+C Samples
+---------
+Collection samples are demonstrated in:
+ocservercoll and occlientcoll
+
+Slow response feature is demonstrated in:
+ocserverslow and occlientslow
+
+Client and server basic operations -- discovery, GET, PUT, POST (NON messages) demonstrated in:
+ocserverbasicops and occlientbasicops
+
+Client and server - discovery, GET,PUT,POST,DELETE,OBS for both NON and CON demonstrated in:
+ocserver and occlient
index 83e4ef8..84a8f93 100644 (file)
@@ -96,16 +96,31 @@ namespace OC
     {
         if(clientResponse->resJSONPayload == nullptr || clientResponse->resJSONPayload[0] == '\0')
         {
-            throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_ERROR);
+            return OCRepresentation();
         }
 
         MessageContainer oc;
-        oc.setJSONRepresentation(clientResponse->resJSONPayload);
+        try
+        {
+            oc.setJSONRepresentation(clientResponse->resJSONPayload);
+        }
+        catch (cereal::RapidJSONException& ex)
+        {
+            oclog() <<"RapidJSON Exception in parseGetSetCallback: "<<ex.what() <<std::endl<<
+                "Data was:"<< clientResponse->resJSONPayload<< ":" << std::flush;
+            throw OCException(OC::Exception::INVALID_REPRESENTATION, OC_STACK_INVALID_JSON);
+        }
+        catch (cereal::Exception& ex)
+        {
+            oclog() <<"Cereal Exception in parseGetSetCallback: "<<ex.what() <<std::endl<<
+                "Data was:"<< clientResponse->resJSONPayload<< ":" << std::flush;
+            throw OCException(OC::Exception::INVALID_REPRESENTATION, OC_STACK_INVALID_JSON);
+        }
 
         std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
         if(it == oc.representations().end())
         {
-            throw OCException(OC::Exception::INVALID_REPRESENTATION, OC_STACK_ERROR);
+            return OCRepresentation();
         }
 
         // first one is considered the root, everything else is considered a child of this one.
@@ -148,9 +163,9 @@ namespace OC
 
         try
         {
-            ListenOCContainer container(clientWrapper, *clientResponse->addr,
-                    requestStream);
 
+            ListenOCContainer container(clientWrapper, *clientResponse->addr,
+                    clientResponse->connType, requestStream);
             // loop to ensure valid construction of all resources
             for(auto resource : container.Resources())
             {
@@ -163,7 +178,9 @@ namespace OC
         {
             oclog() << "listenCallback failed to parse a malformed message: "
                     << e.what()
-                    << std::endl <<std::endl
+                    << std::endl
+                    << clientResponse->resJSONPayload
+                    << std::endl
                     << clientResponse->result
                     << std::flush;
             return OC_STACK_KEEP_TRANSACTION;
@@ -173,8 +190,14 @@ namespace OC
     }
 
     OCStackResult InProcClientWrapper::ListenForResource(const std::string& serviceUrl,
-        const std::string& resourceType, FindCallback& callback, QualityOfService QoS)
+        const std::string& resourceType, OCConnectivityType connectivityType,
+        FindCallback& callback, QualityOfService QoS)
     {
+        if(!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+
         OCStackResult result;
 
         OCCallbackData cbdata = {0};
@@ -191,13 +214,12 @@ namespace OC
         if(cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
-            OCDoHandle handle;
-            result = OCDoResource(&handle, OC_REST_GET,
+            result = OCDoResource(nullptr, OC_REST_GET,
                                   resourceType.c_str(),
-                                  nullptr, nullptr,
+                                  nullptr, nullptr, connectivityType,
                                   static_cast<OCQualityOfService>(QoS),
                                   &cbdata,
-                                  NULL, 0);
+                                  nullptr, 0);
         }
         else
         {
@@ -213,25 +235,36 @@ namespace OC
         ClientCallbackContext::DeviceListenContext* context =
             static_cast<ClientCallbackContext::DeviceListenContext*>(ctx);
 
-        OCRepresentation rep = parseGetSetCallback(clientResponse);
-        std::thread exec(context->callback, rep);
-        exec.detach();
+        try
+        {
+            OCRepresentation rep = parseGetSetCallback(clientResponse);
+            std::thread exec(context->callback, rep);
+            exec.detach();
+        }
+        catch(OC::OCException& e)
+        {
+            oclog() <<"Exception in listenDeviceCallback, ignoring response: "
+                <<e.what() <<std::flush;
+        }
 
         return OC_STACK_KEEP_TRANSACTION;
     }
 
     OCStackResult InProcClientWrapper::ListenForDevice(const std::string& serviceUrl,
-        const std::string& deviceURI, FindDeviceCallback& callback, QualityOfService QoS)
+        const std::string& deviceURI, OCConnectivityType connectivityType,
+        FindDeviceCallback& callback, QualityOfService QoS)
     {
+        if(!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
         OCStackResult result;
 
         OCCallbackData cbdata = {0};
-
         ClientCallbackContext::DeviceListenContext* context =
             new ClientCallbackContext::DeviceListenContext();
         context->callback = callback;
         context->clientWrapper = shared_from_this();
-
         cbdata.context =  static_cast<void*>(context);
         cbdata.cb = listenDeviceCallback;
         cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);};
@@ -240,16 +273,16 @@ namespace OC
         if(cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
-            OCDoHandle handle;
-            result = OCDoResource(&handle, OC_REST_GET,
+            result = OCDoResource(nullptr, OC_REST_GET,
                                   deviceURI.c_str(),
-                                  nullptr, nullptr,
+                                  nullptr, nullptr, connectivityType,
                                   static_cast<OCQualityOfService>(QoS),
                                   &cbdata,
-                                  NULL, 0);
+                                  nullptr, 0);
         }
         else
         {
+            delete context;
             result = OC_STACK_ERROR;
         }
         return result;
@@ -289,22 +322,34 @@ namespace OC
 
         OCRepresentation rep;
         HeaderOptions serverHeaderOptions;
-        if(clientResponse->result == OC_STACK_OK)
+        OCStackResult result = clientResponse->result;
+        if(result == OC_STACK_OK)
         {
             parseServerHeaderOptions(clientResponse, serverHeaderOptions);
-            rep = parseGetSetCallback(clientResponse);
+            try
+            {
+                rep = parseGetSetCallback(clientResponse);
+            }
+            catch(OC::OCException& e)
+            {
+                result = e.code();
+            }
         }
 
-        std::thread exec(context->callback, serverHeaderOptions, rep, clientResponse->result);
+        std::thread exec(context->callback, serverHeaderOptions, rep, result);
         exec.detach();
         return OC_STACK_DELETE_TRANSACTION;
     }
 
     OCStackResult InProcClientWrapper::GetResourceRepresentation(const std::string& host,
-        const std::string& uri, const QueryParamsMap& queryParams,
-        const HeaderOptions& headerOptions, GetCallback& callback,
-        QualityOfService QoS)
+        const std::string& uri, OCConnectivityType connectivityType,
+        const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
+        GetCallback& callback, QualityOfService QoS)
     {
+        if(!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
         OCStackResult result;
         OCCallbackData cbdata = {0};
 
@@ -322,15 +367,14 @@ namespace OC
             os << host << assembleSetResourceUri(uri, queryParams).c_str();
 
             std::lock_guard<std::recursive_mutex> lock(*cLock);
-            OCDoHandle handle;
             OCHeaderOption options[MAX_HEADER_OPTIONS];
 
-            assembleHeaderOptions(options, headerOptions);
-            result = OCDoResource(&handle, OC_REST_GET, os.str().c_str(),
-                                  nullptr, nullptr,
+            result = OCDoResource(nullptr, OC_REST_GET, os.str().c_str(),
+                                  nullptr, nullptr, connectivityType,
                                   static_cast<OCQualityOfService>(QoS),
                                   &cbdata,
-                                  options, headerOptions.size());
+                                  assembleHeaderOptions(options, headerOptions),
+                                  headerOptions.size());
         }
         else
         {
@@ -349,15 +393,23 @@ namespace OC
         OCRepresentation attrs;
         HeaderOptions serverHeaderOptions;
 
-        if (OC_STACK_OK               == clientResponse->result ||
-            OC_STACK_RESOURCE_CREATED == clientResponse->result ||
-            OC_STACK_RESOURCE_DELETED == clientResponse->result)
+        OCStackResult result = clientResponse->result;
+        if (OC_STACK_OK               == result ||
+            OC_STACK_RESOURCE_CREATED == result ||
+            OC_STACK_RESOURCE_DELETED == result)
         {
             parseServerHeaderOptions(clientResponse, serverHeaderOptions);
-            attrs = parseGetSetCallback(clientResponse);
+            try
+            {
+                attrs = parseGetSetCallback(clientResponse);
+            }
+            catch(OC::OCException& e)
+            {
+                result = e.code();
+            }
         }
 
-        std::thread exec(context->callback, serverHeaderOptions, attrs, clientResponse->result);
+        std::thread exec(context->callback, serverHeaderOptions, attrs, result);
         exec.detach();
         return OC_STACK_DELETE_TRANSACTION;
     }
@@ -399,10 +451,14 @@ namespace OC
     }
 
     OCStackResult InProcClientWrapper::PostResourceRepresentation(const std::string& host,
-        const std::string& uri, const OCRepresentation& rep,
+        const std::string& uri, OCConnectivityType connectivityType, const OCRepresentation& rep,
         const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
         PostCallback& callback, QualityOfService QoS)
     {
+        if(!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
         OCStackResult result;
         OCCallbackData cbdata = {0};
 
@@ -423,14 +479,14 @@ namespace OC
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCHeaderOption options[MAX_HEADER_OPTIONS];
-            OCDoHandle handle;
 
-            assembleHeaderOptions(options, headerOptions);
-            result = OCDoResource(&handle, OC_REST_POST,
+            result = OCDoResource(nullptr, OC_REST_POST,
                                   os.str().c_str(), nullptr,
-                                  assembleSetResourcePayload(rep).c_str(),
+                                  assembleSetResourcePayload(rep).c_str(), connectivityType,
                                   static_cast<OCQualityOfService>(QoS),
-                                  &cbdata, options, headerOptions.size());
+                                  &cbdata,
+                                  assembleHeaderOptions(options, headerOptions),
+                                  headerOptions.size());
         }
         else
         {
@@ -441,12 +497,15 @@ namespace OC
         return result;
     }
 
-
     OCStackResult InProcClientWrapper::PutResourceRepresentation(const std::string& host,
-        const std::string& uri, const OCRepresentation& rep,
+        const std::string& uri, OCConnectivityType connectivityType, const OCRepresentation& rep,
         const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
         PutCallback& callback, QualityOfService QoS)
     {
+        if(!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
         OCStackResult result;
         OCCallbackData cbdata = {0};
 
@@ -469,13 +528,13 @@ namespace OC
             OCDoHandle handle;
             OCHeaderOption options[MAX_HEADER_OPTIONS];
 
-            assembleHeaderOptions(options, headerOptions);
             result = OCDoResource(&handle, OC_REST_PUT,
                                   os.str().c_str(), nullptr,
-                                  assembleSetResourcePayload(rep).c_str(),
+                                  assembleSetResourcePayload(rep).c_str(), connectivityType,
                                   static_cast<OCQualityOfService>(QoS),
                                   &cbdata,
-                                  options, headerOptions.size());
+                                  assembleHeaderOptions(options, headerOptions),
+                                  headerOptions.size());
         }
         else
         {
@@ -503,9 +562,13 @@ namespace OC
     }
 
     OCStackResult InProcClientWrapper::DeleteResource(const std::string& host,
-        const std::string& uri, const HeaderOptions& headerOptions,
-         DeleteCallback& callback, QualityOfService QoS)
+        const std::string& uri, OCConnectivityType connectivityType,
+        const HeaderOptions& headerOptions, DeleteCallback& callback, QualityOfService QoS)
     {
+        if(!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
         OCStackResult result;
         OCCallbackData cbdata = {0};
 
@@ -523,16 +586,16 @@ namespace OC
         if(cLock)
         {
             OCHeaderOption options[MAX_HEADER_OPTIONS];
-            OCDoHandle handle;
-
-            assembleHeaderOptions(options, headerOptions);
 
             std::lock_guard<std::recursive_mutex> lock(*cLock);
 
-            result = OCDoResource(&handle, OC_REST_DELETE,
+            result = OCDoResource(nullptr, OC_REST_DELETE,
                                   os.str().c_str(), nullptr,
-                                  nullptr, static_cast<OCQualityOfService>(m_cfg.QoS),
-                                  &cbdata, options, headerOptions.size());
+                                  nullptr, connectivityType,
+                                  static_cast<OCQualityOfService>(m_cfg.QoS),
+                                  &cbdata,
+                                  assembleHeaderOptions(options, headerOptions),
+                                  headerOptions.size());
         }
         else
         {
@@ -551,22 +614,38 @@ namespace OC
         OCRepresentation attrs;
         HeaderOptions serverHeaderOptions;
         uint32_t sequenceNumber = clientResponse->sequenceNumber;
-
+        OCStackResult result = clientResponse->result;
         if(clientResponse->result == OC_STACK_OK)
         {
             parseServerHeaderOptions(clientResponse, serverHeaderOptions);
-            attrs = parseGetSetCallback(clientResponse);
+            try
+            {
+                attrs = parseGetSetCallback(clientResponse);
+            }
+            catch(OC::OCException& e)
+            {
+                result = e.code();
+            }
         }
         std::thread exec(context->callback, serverHeaderOptions, attrs,
-                    clientResponse->result, sequenceNumber);
+                    result, sequenceNumber);
         exec.detach();
+        if(sequenceNumber == OC_OBSERVE_DEREGISTER)
+        {
+            return OC_STACK_DELETE_TRANSACTION;
+        }
         return OC_STACK_KEEP_TRANSACTION;
     }
 
     OCStackResult InProcClientWrapper::ObserveResource(ObserveType observeType, OCDoHandle* handle,
-        const std::string& host, const std::string& uri, const QueryParamsMap& queryParams,
-        const HeaderOptions& headerOptions, ObserveCallback& callback, QualityOfService QoS)
+        const std::string& host, const std::string& uri, OCConnectivityType connectivityType,
+        const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
+        ObserveCallback& callback, QualityOfService QoS)
     {
+        if(!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
         OCStackResult result;
         OCCallbackData cbdata = {0};
 
@@ -600,13 +679,13 @@ namespace OC
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCHeaderOption options[MAX_HEADER_OPTIONS];
 
-            assembleHeaderOptions(options, headerOptions);
             result = OCDoResource(handle, method,
                                   os.str().c_str(), nullptr,
-                                  nullptr,
+                                  nullptr, connectivityType,
                                   static_cast<OCQualityOfService>(QoS),
                                   &cbdata,
-                                  options, headerOptions.size());
+                                  assembleHeaderOptions(options, headerOptions),
+                                  headerOptions.size());
         }
         else
         {
@@ -629,8 +708,9 @@ namespace OC
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCHeaderOption options[MAX_HEADER_OPTIONS];
 
-            assembleHeaderOptions(options, headerOptions);
-            result = OCCancel(handle, static_cast<OCQualityOfService>(QoS), options,
+            result = OCCancel(handle,
+                    static_cast<OCQualityOfService>(QoS),
+                    assembleHeaderOptions(options, headerOptions),
                     headerOptions.size());
         }
         else
@@ -644,14 +724,18 @@ namespace OC
     OCStackApplicationResult subscribePresenceCallback(void* ctx, OCDoHandle handle,
             OCClientResponse* clientResponse)
     {
-        char stringAddress[DEV_ADDR_SIZE_MAX];
         ostringstream os;
         uint16_t port;
+        uint8_t a;
+        uint8_t b;
+        uint8_t c;
+        uint8_t d;
 
-        if(OCDevAddrToString(clientResponse->addr, stringAddress) == 0 &&
+        if(OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) == 0 &&
                 OCDevAddrToPort(clientResponse->addr, &port) == 0)
         {
-            os<<stringAddress<<":"<<port;
+            os<<static_cast<int>(a)<<"."<<static_cast<int>(b)<<"."<<static_cast<int>(c)
+                    <<"."<<static_cast<int>(d)<<":"<<static_cast<int>(port);
 
             ClientCallbackContext::SubscribePresenceContext* context =
                 static_cast<ClientCallbackContext::SubscribePresenceContext*>(ctx);
@@ -663,7 +747,7 @@ namespace OC
         }
         else
         {
-            oclog() << "subscribePresenceCallback(): OCDevAddrToString() or OCDevAddrToPort() "
+            oclog() << "subscribePresenceCallback(): OCDevAddrToIPv4Addr() or OCDevAddrToPort() "
                     <<"failed"<< std::flush;
         }
         return OC_STACK_KEEP_TRANSACTION;
@@ -671,8 +755,12 @@ namespace OC
 
     OCStackResult InProcClientWrapper::SubscribePresence(OCDoHandle* handle,
         const std::string& host, const std::string& resourceType,
-        SubscribeCallback& presenceHandler)
+        OCConnectivityType connectivityType, SubscribeCallback& presenceHandler)
     {
+        if(!presenceHandler)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
         OCCallbackData cbdata = {0};
 
         ClientCallbackContext::SubscribePresenceContext* ctx =
@@ -685,7 +773,7 @@ namespace OC
         auto cLock = m_csdkLock.lock();
 
         std::ostringstream os;
-        os << host << "/oc/presence";
+        os << host << OC_PRESENCE_URI;
 
         if(!resourceType.empty())
         {
@@ -699,7 +787,7 @@ namespace OC
         }
 
         return OCDoResource(handle, OC_REST_PRESENCE, os.str().c_str(), nullptr, nullptr,
-                            OC_LOW_QOS, &cbdata, NULL, 0);
+                            connectivityType, OC_LOW_QOS, &cbdata, NULL, 0);
     }
 
     OCStackResult InProcClientWrapper::UnsubscribePresence(OCDoHandle handle)
@@ -726,11 +814,16 @@ namespace OC
         return OC_STACK_OK;
     }
 
-    void InProcClientWrapper::assembleHeaderOptions(OCHeaderOption options[],
+    OCHeaderOption* InProcClientWrapper::assembleHeaderOptions(OCHeaderOption options[],
            const HeaderOptions& headerOptions)
     {
         int i = 0;
 
+        if( headerOptions.size() == 0)
+        {
+            return nullptr;
+        }
+
         for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it)
         {
             options[i].protocolID = OC_COAP_ID;
@@ -740,5 +833,7 @@ namespace OC
                     (it->getOptionData()).length() + 1);
             i++;
         }
+
+        return options;
     }
 }
index 0159bb8..f42a18c 100644 (file)
 #include <OCResourceResponse.h>
 #include <ocstack.h>
 #include <OCApi.h>
+#include <ocmalloc.h>
 #include <OCPlatform.h>
 #include <OCUtilities.h>
 
 using namespace std;
 using namespace OC;
 
-std::map <OCResourceHandle, OC::EntityHandler>  entityHandlerMap;
-std::map <OCResourceHandle, std::string> resourceUriMap;
-EntityHandler defaultDeviceEntityHandler = 0;
+namespace OC
+{
+    namespace details
+    {
+        std::mutex serverWrapperLock;
+        std::map <OCResourceHandle, OC::EntityHandler>  entityHandlerMap;
+        std::map <OCResourceHandle, std::string> resourceUriMap;
+        EntityHandler defaultDeviceEntityHandler = 0;
+    }
+}
 
 void formResourceRequest(OCEntityHandlerFlag flag,
                          OCEntityHandlerRequest * entityHandlerRequest,
                          std::shared_ptr<OCResourceRequest> pRequest)
 {
-    pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
-    pRequest->setResourceHandle(entityHandlerRequest->resource);
-
-    if(flag & OC_INIT_FLAG)
+    if(pRequest && entityHandlerRequest)
     {
-        pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::InitFlag);
+        pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
+        pRequest->setResourceHandle(entityHandlerRequest->resource);
     }
 
     if(flag & OC_REQUEST_FLAG)
@@ -63,9 +69,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)
                 {
@@ -150,9 +155,15 @@ OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
 
     pRequest->setResourceUri(std::string(uri));
 
-    if(defaultDeviceEntityHandler)
+    EntityHandler defHandler;
     {
-        result = defaultDeviceEntityHandler(pRequest);
+        std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
+        defHandler = OC::details::defaultDeviceEntityHandler;
+    }
+
+    if(defHandler)
+    {
+        result = defHandler(pRequest);
     }
     else
     {
@@ -181,9 +192,15 @@ OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
 
     formResourceRequest(flag, entityHandlerRequest, pRequest);
 
+    std::map <OCResourceHandle, std::string>::iterator resourceUriEntry;
+    std::map <OCResourceHandle, std::string>::iterator resourceUriEnd;
+    {
+        std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
+        resourceUriEntry = OC::details::resourceUriMap.find(entityHandlerRequest->resource);
+        resourceUriEnd = OC::details::resourceUriMap.end();
+    }
     // Finding the corresponding URI for a resource handle and set the URI in the request
-    auto resourceUriEntry = resourceUriMap.find(entityHandlerRequest->resource);
-    if(resourceUriEntry != resourceUriMap.end())
+    if(resourceUriEntry != resourceUriEnd)
     {
         pRequest->setResourceUri(resourceUriEntry->second);
     }
@@ -193,10 +210,16 @@ OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
         return OC_EH_ERROR;
     }
 
-    // Finding the corresponding CPP Application entityHandler for a given resource
-    auto entityHandlerEntry = entityHandlerMap.find(entityHandlerRequest->resource);
+    std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEntry;
+    std::map <OCResourceHandle, OC::EntityHandler>::iterator entityHandlerEnd;
+    {
+        // Finding the corresponding CPP Application entityHandler for a given resource
+        std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
+        entityHandlerEntry = OC::details::entityHandlerMap.find(entityHandlerRequest->resource);
+        entityHandlerEnd = OC::details::entityHandlerMap.end();
+    }
 
-    if(entityHandlerEntry != entityHandlerMap.end())
+    if(entityHandlerEntry != entityHandlerEnd)
     {
         // Call CPP Application Entity Handler
         if(entityHandlerEntry->second)
@@ -263,9 +286,11 @@ namespace OC
                 result = OCProcess();
             }
 
-            // ...the value of variable result is simply ignored for now.
             if(OC_STACK_ERROR == result)
-             ;
+            {
+                oclog() << "OCProcess failed with result " << result <<std::flush;
+                // ...the value of variable result is simply ignored for now.
+            }
 
             std::this_thread::sleep_for(std::chrono::milliseconds(10));
         }
@@ -283,6 +308,18 @@ namespace OC
         return result;
     }
 
+     OCStackResult InProcServerWrapper::registerPlatformInfo(const OCPlatformInfo platformInfo)
+    {
+        auto cLock = m_csdkLock.lock();
+        OCStackResult result = OC_STACK_ERROR;
+        if(cLock)
+        {
+            std::lock_guard<std::recursive_mutex> lock(*cLock);
+            result = OCSetPlatformInfo(platformInfo);
+        }
+        return result;
+    }
+
     OCStackResult InProcServerWrapper::registerResource(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceURI,
@@ -327,8 +364,9 @@ namespace OC
             }
             else
             {
-                entityHandlerMap[resourceHandle] = eHandler;
-                resourceUriMap[resourceHandle] = resourceURI;
+                std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
+                OC::details::entityHandlerMap[resourceHandle] = eHandler;
+                OC::details::resourceUriMap[resourceHandle] = resourceURI;
             }
         }
         else
@@ -386,8 +424,9 @@ namespace OC
             }
             else
             {
-                entityHandlerMap[resourceHandle] = eHandler;
-                resourceUriMap[resourceHandle] = resourceURI;
+                std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
+                OC::details::entityHandlerMap[resourceHandle] = eHandler;
+                OC::details::resourceUriMap[resourceHandle] = resourceURI;
             }
         }
         else
@@ -403,7 +442,10 @@ namespace OC
     {
         OCStackResult result = OC_STACK_ERROR;
 
-        defaultDeviceEntityHandler = entityHandler;
+        {
+            std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
+            OC::details::defaultDeviceEntityHandler = entityHandler;
+        }
 
         if(entityHandler)
         {
@@ -430,7 +472,8 @@ namespace OC
 
             if(result == OC_STACK_OK)
             {
-                resourceUriMap.erase(resourceHandle);
+                std::lock_guard<std::mutex> lock(OC::details::serverWrapperLock);
+                OC::details::resourceUriMap.erase(resourceHandle);
             }
             else
             {
@@ -548,7 +591,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;
 
@@ -582,6 +633,7 @@ namespace OC
             }
             else
             {
+                OCFree(response.payload);
                 result = OC_STACK_ERROR;
             }
 
@@ -604,3 +656,4 @@ namespace OC
         OCStop();
     }
 }
+
index 9bea2e2..64d1cfd 100644 (file)
@@ -51,6 +51,10 @@ std::string OC::OCException::reason(const OCStackResult sr)
             return OC::Exception::NO_MEMORY;
         case OC_STACK_COMM_ERROR:
             return OC::Exception::COMM_ERROR;
+        case OC_STACK_TIMEOUT:
+            return OC::Exception::TIMEOUT;
+        case OC_STACK_ADAPTER_NOT_ENABLED:
+            return OC::Exception::ADAPTER_NOT_ENABLED;
         case OC_STACK_NOTIMPL:
             return OC::Exception::NOT_IMPL;
         case OC_STACK_NO_RESOURCE:
@@ -85,8 +89,13 @@ std::string OC::OCException::reason(const OCStackResult sr)
             return OC::Exception::INVALID_REQUEST_HANDLE;
         case OC_STACK_ERROR:
             return OC::Exception::GENERAL_FAULT;
+        case OC_STACK_INVALID_DEVICE_INFO:
+            return OC::Exception::INVALID_DEVICE_INFO;
+        case OC_STACK_INVALID_JSON:
+            return OC::Exception::INVALID_REPRESENTATION;
     }
 
     return OC::Exception::UNKNOWN_ERROR;
 }
 
+
index 9a17833..8093aa2 100644 (file)
@@ -72,45 +72,71 @@ namespace OC
 
         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)
         {
-            return OCPlatform_impl::Instance().constructResourceObject(host, uri, isObservable,
+            return OCPlatform_impl::Instance().constructResourceObject(host, uri, connectivityType,
+                                                isObservable,
                                                 resourceTypes, interfaces);
         }
 
         OCStackResult findResource(const std::string& host,
                                                 const std::string& resourceName,
+                                                OCConnectivityType connectivityType,
                                                 FindCallback resourceHandler)
         {
-            return OCPlatform_impl::Instance().findResource(host, resourceName, resourceHandler);
+            return OCPlatform_impl::Instance().findResource(host, resourceName,
+                   connectivityType, resourceHandler);
         }
 
         OCStackResult findResource(const std::string& host,
                                                 const std::string& resourceName,
+                                                OCConnectivityType connectivityType,
                                                 FindCallback resourceHandler, QualityOfService QoS)
         {
-            return OCPlatform_impl::Instance().findResource(host, resourceName,
+            return OCPlatform_impl::Instance().findResource(host, resourceName, connectivityType,
                                                 resourceHandler, QoS);
         }
 
         OCStackResult getDeviceInfo(const std::string& host,
                                                 const std::string& deviceURI,
+                                                OCConnectivityType connectivityType,
                                                 FindDeviceCallback deviceInfoHandler)
         {
-            return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI, deviceInfoHandler);
+            return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI,
+                   connectivityType, deviceInfoHandler);
         }
 
         OCStackResult getDeviceInfo(const std::string& host,
                                                 const std::string& deviceURI,
+                                                OCConnectivityType connectivityType,
                                                 FindDeviceCallback deviceInfoHandler,
                                                 QualityOfService QoS)
         {
-            return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI,
+            return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI, connectivityType,
                     deviceInfoHandler, QoS);
         }
 
+        OCStackResult getPlatformInfo(const std::string& host,
+                                                const std::string& platformURI,
+                                                OCConnectivityType connectivityType,
+                                                FindPlatformCallback platformInfoHandler)
+        {
+            return OCPlatform_impl::Instance().getPlatformInfo(host, platformURI,
+                   connectivityType, platformInfoHandler);
+        }
+
+        OCStackResult getPlatformInfo(const std::string& host,
+                                                const std::string& platformURI,
+                                                OCConnectivityType connectivityType,
+                                                FindPlatformCallback platformInfoHandler,
+                                                QualityOfService QoS)
+        {
+            return OCPlatform_impl::Instance().getPlatformInfo(host, platformURI, connectivityType,
+                    platformInfoHandler, QoS);
+        }
 
         OCStackResult registerResource(OCResourceHandle& resourceHandle,
                                                 std::string& resourceURI,
@@ -135,6 +161,11 @@ namespace OC
             return OCPlatform_impl::Instance().registerDeviceInfo(deviceInfo);
         }
 
+        OCStackResult registerPlatformInfo(const OCPlatformInfo platformInfo)
+        {
+            return OCPlatform_impl::Instance().registerPlatformInfo(platformInfo);
+        }
+
         OCStackResult unregisterResource(const OCResourceHandle& resourceHandle)
         {
             return OCPlatform_impl::Instance().unregisterResource(resourceHandle);
@@ -191,19 +222,21 @@ namespace OC
 
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle,
                                                 const std::string& host,
+                                                OCConnectivityType connectivityType,
                                                 SubscribeCallback presenceHandler)
         {
             return OCPlatform_impl::Instance().subscribePresence(presenceHandle, host,
-                                                presenceHandler);
+                                                connectivityType, presenceHandler);
         }
 
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle,
                                                 const std::string& host,
                                                 const std::string& resourceType,
+                                                OCConnectivityType connectivityType,
                                                 SubscribeCallback presenceHandler)
         {
             return OCPlatform_impl::Instance().subscribePresence(presenceHandle, host,
-                                                resourceType, presenceHandler);
+                                                resourceType, connectivityType, presenceHandler);
         }
 
         OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle)
@@ -217,3 +250,4 @@ namespace OC
         }
     } // namespace OCPlatform
 } //namespace OC
+
index 9d9ae52..e694bab 100644 (file)
@@ -30,6 +30,8 @@
 //
 //*********************************************************************
 
+#include "OCPlatform_impl.h"
+
 #include <random>
 #include <utility>
 #include <functional>
@@ -85,7 +87,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,12 +136,13 @@ 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)));
     }
 
     OCResource::Ptr OCPlatform_impl::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)
@@ -151,7 +154,7 @@ namespace OC
 
         return std::shared_ptr<OCResource>(new OCResource(m_client,
                                             host,
-                                            uri,
+                                            uri, "", connectivityType,
                                             isObservable,
                                             resourceTypes,
                                             interfaces));
@@ -159,33 +162,58 @@ namespace OC
 
     OCStackResult OCPlatform_impl::findResource(const std::string& host,
                                             const std::string& resourceName,
+                                            OCConnectivityType connectivityType,
                                             FindCallback resourceHandler)
     {
-        return findResource(host, resourceName, resourceHandler, m_cfg.QoS);
+        return findResource(host, resourceName, connectivityType, resourceHandler, m_cfg.QoS);
     }
 
     OCStackResult OCPlatform_impl::findResource(const std::string& host,
                                             const std::string& resourceName,
+                                            OCConnectivityType connectivityType,
                                             FindCallback resourceHandler, QualityOfService QoS)
     {
+
         return checked_guard(m_client, &IClientWrapper::ListenForResource,
-                             host, resourceName, resourceHandler, QoS);
+                             host, resourceName, connectivityType, resourceHandler, QoS);
     }
 
     OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
                                             const std::string& deviceURI,
+                                            OCConnectivityType connectivityType,
                                             FindDeviceCallback deviceInfoHandler)
     {
-        return result_guard(getDeviceInfo(host, deviceURI, deviceInfoHandler, m_cfg.QoS));
+        return result_guard(getDeviceInfo(host, deviceURI, connectivityType,
+               deviceInfoHandler, m_cfg.QoS));
     }
 
     OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
                                             const std::string& deviceURI,
+                                            OCConnectivityType connectivityType,
                                             FindDeviceCallback deviceInfoHandler,
                                             QualityOfService QoS)
     {
         return checked_guard(m_client, &IClientWrapper::ListenForDevice,
-                             host, deviceURI, deviceInfoHandler, QoS);
+                             host, deviceURI, connectivityType, deviceInfoHandler, QoS);
+    }
+
+    OCStackResult OCPlatform_impl::getPlatformInfo(const std::string& host,
+                                            const std::string& platformURI,
+                                            OCConnectivityType connectivityType,
+                                            FindPlatformCallback platformInfoHandler)
+    {
+        return result_guard(getPlatformInfo(host, platformURI, connectivityType,
+               platformInfoHandler, m_cfg.QoS));
+    }
+
+    OCStackResult OCPlatform_impl::getPlatformInfo(const std::string& host,
+                                            const std::string& platformURI,
+                                            OCConnectivityType connectivityType,
+                                            FindPlatformCallback platformInfoHandler,
+                                            QualityOfService QoS)
+    {
+        return checked_guard(m_client, &IClientWrapper::ListenForDevice,
+                             host, platformURI, connectivityType, platformInfoHandler, QoS);
     }
 
     OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
@@ -196,7 +224,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);
     }
 
@@ -205,6 +233,11 @@ namespace OC
         return checked_guard(m_server, &IServerWrapper::registerDeviceInfo, deviceInfo);
     }
 
+    OCStackResult OCPlatform_impl::registerPlatformInfo(const OCPlatformInfo platformInfo)
+    {
+        return checked_guard(m_server, &IServerWrapper::registerPlatformInfo, platformInfo);
+    }
+
     OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
                                             const std::shared_ptr< OCResource > resource)
     {
@@ -212,7 +245,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"*/, DEFAULT_INTERFACE,
                 (EntityHandler) nullptr, resourceProperty);
     }
 
@@ -225,7 +259,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,
@@ -293,24 +327,28 @@ namespace OC
 
     OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle,
                                             const std::string& host,
+                                            OCConnectivityType connectivityType,
                                             SubscribeCallback presenceHandler)
     {
-        return subscribePresence(presenceHandle, host, "", presenceHandler);
+        return subscribePresence(presenceHandle, host, "", connectivityType, presenceHandler);
     }
 
+
     OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle,
                                             const std::string& host,
                                             const std::string& resourceType,
+                                            OCConnectivityType connectivityType,
                                             SubscribeCallback presenceHandler)
     {
         return checked_guard(m_client, &IClientWrapper::SubscribePresence,
-                             &presenceHandle, host, resourceType, presenceHandler);
+                             &presenceHandle, host, resourceType, connectivityType,
+                             presenceHandler);
     }
 
     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)
@@ -319,3 +357,4 @@ namespace OC
                              pResponse);
     }
 } //namespace OC
+
index 99b3e65..6f73435 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file OCRepresentation.cpp
+/**
+ * @file
+ *
+ * This file contains the implementation of classes and its members related
+ * to OCRepresentation.
+ */
 
-/// @brief  This file contains the implementation of classes and its members
-///         related to OCRepresentation
-
-#ifdef __ANDROID__
-#include "OCAndroid.h"
-#endif
 
 #include <OCRepresentation.h>
 
+#include <boost/lexical_cast.hpp>
 #include <cereal/cereal.hpp>
 #include <cereal/types/map.hpp>
 #include <cereal/types/vector.hpp>
@@ -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
@@ -135,7 +135,7 @@ namespace OC
                 bool firstPrinted = false;
                 for(std::vector<OCRepresentation>::size_type i = 0; i< m_reps.size();++i)
                 {
-                    if(!m_reps[i].empty())
+                    if(!m_reps[i].emptyData())
                     {
                         if(firstPrinted)
                         {
@@ -163,12 +163,9 @@ namespace OC
 
 namespace OC
 {
-    OCRepresentation::OCRepresentation()
-    :m_interfaceType(InterfaceType::None)
-    { }
     std::string OCRepresentation::getJSONRepresentation() const
     {
-        if(empty())
+        if(emptyData())
         {
             return "{}";
         }
@@ -201,6 +198,11 @@ namespace OC
         return m_children;
     }
 
+    void OCRepresentation::setChildren(const std::vector<OCRepresentation>& children)
+    {
+        m_children = children;
+    }
+
     void OCRepresentation::setUri(const std::string& uri)
     {
         m_uri = uri;
@@ -236,7 +238,7 @@ namespace OC
         return m_values.find(str) != m_values.end();
     }
 
-    bool OCRepresentation::empty() const
+    bool OCRepresentation::emptyData() const
     {
         // This logic is meant to determine whether based on the JSON serialization rules
         // if this object will result in empty JSON.  URI is only serialized if there is valid
@@ -310,7 +312,7 @@ namespace OC
         {
             ar(v);
         }
-        catch(cereal::Exception& e)
+        catch(cereal::Exception&)
         {
             ar.setNextName(nullptr);
             // Loading a key that doesn't exist results in an exception
@@ -649,3 +651,331 @@ namespace cereal
        }
    }
 }
+
+namespace OC
+{
+    std::ostream& operator <<(std::ostream& os, const AttributeType at)
+    {
+        switch(at)
+        {
+            case AttributeType::Null:
+                os << "Null";
+                break;
+            case AttributeType::Integer:
+                os << "Integer";
+                break;
+            case AttributeType::Double:
+                os << "Double";
+                break;
+            case AttributeType::Boolean:
+                os << "Boolean";
+                break;
+            case AttributeType::String:
+                os << "String";
+                break;
+            case AttributeType::OCRepresentation:
+                os << "OCRepresentation";
+                break;
+            case AttributeType::Vector:
+                os << "Vector";
+                break;
+        }
+        return os;
+    }
+}
+
+// STL Container For OCRepresentation
+namespace OC
+{
+    OCRepresentation::AttributeItem::AttributeItem(const std::string& name,
+            std::map<std::string, AttributeValue>& vals):
+            m_attrName(name), m_values(vals){}
+
+    OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key)
+    {
+        OCRepresentation::AttributeItem attr{key, m_values};
+        return std::move(attr);
+    }
+
+    const OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key) const
+    {
+        OCRepresentation::AttributeItem attr{key, m_values};
+        return std::move(attr);
+    }
+
+    const std::string& OCRepresentation::AttributeItem::attrname() const
+    {
+        return m_attrName;
+    }
+
+    template<typename T, typename = void>
+    struct type_info
+    {
+        // contains the actual type
+        typedef T type;
+        // contains the inner most vector-type
+        typedef T base_type;
+        // contains the AttributeType for this item
+        constexpr static AttributeType enum_type =
+            AttributeTypeConvert<T>::type;
+        // contains the AttributeType for this base-type
+        constexpr static AttributeType enum_base_type =
+            AttributeTypeConvert<T>::type;
+        // depth of the vector
+        constexpr static size_t depth = 0;
+    };
+
+    template<typename T>
+    struct type_info<T, typename std::enable_if<is_vector<T>::value>::type>
+    {
+        typedef T type;
+        typedef typename type_info<typename T::value_type>::base_type base_type;
+        constexpr static AttributeType enum_type = AttributeType::Vector;
+        constexpr static AttributeType enum_base_type =
+            type_info<typename T::value_type>::enum_base_type;
+        constexpr static size_t depth = 1 +
+            type_info<typename T::value_type>::depth;
+    };
+
+    struct type_introspection_visitor : boost::static_visitor<>
+    {
+        AttributeType type;
+        AttributeType base_type;
+        size_t depth;
+
+        type_introspection_visitor() : boost::static_visitor<>(),
+            type(AttributeType::Null), base_type(AttributeType::Null), depth(0){}
+
+        template <typename T>
+        void operator()(T const& item)
+        {
+            type = type_info<T>::enum_type;
+            base_type = type_info<T>::enum_base_type;
+            depth = type_info<T>::depth;
+        }
+    };
+
+    AttributeType OCRepresentation::AttributeItem::type() const
+    {
+        type_introspection_visitor vis;
+        boost::apply_visitor(vis, m_values[m_attrName]);
+        return vis.type;
+    }
+
+    AttributeType OCRepresentation::AttributeItem::base_type() const
+    {
+        type_introspection_visitor vis;
+        boost::apply_visitor(vis, m_values[m_attrName]);
+        return vis.base_type;
+    }
+
+    size_t OCRepresentation::AttributeItem::depth() const
+    {
+        type_introspection_visitor vis;
+        boost::apply_visitor(vis, m_values[m_attrName]);
+        return vis.depth;
+    }
+
+    OCRepresentation::iterator OCRepresentation::begin()
+    {
+        return OCRepresentation::iterator(m_values.begin(), m_values);
+    }
+
+    OCRepresentation::const_iterator OCRepresentation::begin() const
+    {
+         return OCRepresentation::const_iterator(m_values.begin(), m_values);
+    }
+
+    OCRepresentation::const_iterator OCRepresentation::cbegin() const
+    {
+        return OCRepresentation::const_iterator(m_values.cbegin(), m_values);
+    }
+
+    OCRepresentation::iterator OCRepresentation::end()
+    {
+        return OCRepresentation::iterator(m_values.end(), m_values);
+    }
+
+    OCRepresentation::const_iterator OCRepresentation::end() const
+    {
+        return OCRepresentation::const_iterator(m_values.end(), m_values);
+    }
+
+    OCRepresentation::const_iterator OCRepresentation::cend() const
+    {
+        return OCRepresentation::const_iterator(m_values.cend(), m_values);
+    }
+
+    size_t OCRepresentation::size() const
+    {
+        return m_values.size();
+    }
+
+    bool OCRepresentation::empty() const
+    {
+        return m_values.empty();
+    }
+
+    bool OCRepresentation::iterator::operator==(const OCRepresentation::iterator& rhs) const
+    {
+        return m_iterator == rhs.m_iterator;
+    }
+
+    bool OCRepresentation::iterator::operator!=(const OCRepresentation::iterator& rhs) const
+    {
+        return m_iterator != rhs.m_iterator;
+    }
+
+    bool OCRepresentation::const_iterator::operator==(
+            const OCRepresentation::const_iterator& rhs) const
+    {
+        return m_iterator == rhs.m_iterator;
+    }
+
+    bool OCRepresentation::const_iterator::operator!=(
+            const OCRepresentation::const_iterator& rhs) const
+    {
+        return m_iterator != rhs.m_iterator;
+    }
+
+    OCRepresentation::iterator::reference OCRepresentation::iterator::operator*()
+    {
+        return m_item;
+    }
+
+    OCRepresentation::const_iterator::const_reference
+        OCRepresentation::const_iterator::operator*() const
+    {
+        return m_item;
+    }
+
+    OCRepresentation::iterator::pointer OCRepresentation::iterator::operator->()
+    {
+        return &m_item;
+    }
+
+    OCRepresentation::const_iterator::const_pointer
+        OCRepresentation::const_iterator::operator->() const
+    {
+        return &m_item;
+    }
+
+    OCRepresentation::iterator& OCRepresentation::iterator::operator++()
+    {
+        m_iterator++;
+        if(m_iterator != m_item.m_values.end())
+        {
+            m_item.m_attrName = m_iterator->first;
+        }
+        else
+        {
+            m_item.m_attrName = "";
+        }
+        return *this;
+    }
+
+    OCRepresentation::const_iterator& OCRepresentation::const_iterator::operator++()
+    {
+        m_iterator++;
+        if(m_iterator != m_item.m_values.end())
+        {
+            m_item.m_attrName = m_iterator->first;
+        }
+        else
+        {
+            m_item.m_attrName = "";
+        }
+        return *this;
+    }
+
+    OCRepresentation::iterator OCRepresentation::iterator::operator++(int)
+    {
+        OCRepresentation::iterator itr(*this);
+        ++(*this);
+        return itr;
+    }
+
+    OCRepresentation::const_iterator OCRepresentation::const_iterator::operator++(int)
+    {
+        OCRepresentation::const_iterator itr(*this);
+        ++(*this);
+        return itr;
+    }
+
+    struct to_string_visitor : boost::static_visitor<>
+    {
+        std::string str;
+        template <typename T>
+        void operator()(T const& item)
+        {
+            str = boost::lexical_cast<std::string>(item);
+        }
+
+        template <typename T>
+        void operator()(std::vector<T> const& item)
+        {
+            to_string_visitor vis;
+            std::ostringstream stream;
+            stream << "[";
+
+            for(const auto& i : item)
+            {
+                vis(i);
+                stream << vis.str  << " ";
+            }
+            stream << "]";
+            str = stream.str();
+        }
+    };
+
+    template<>
+    void to_string_visitor::operator()(bool const& item)
+    {
+        str = item ? "true" : "false";
+    }
+
+    template<>
+    void to_string_visitor::operator()(std::string const& item)
+    {
+        str = item;
+    }
+
+    template<>
+    void to_string_visitor::operator()(NullType const& item)
+    {
+        str = "(null)";
+    }
+
+    template<>
+    void to_string_visitor::operator()(OCRepresentation const& item)
+    {
+        str = "OC::OCRepresentation";
+    }
+
+    std::string OCRepresentation::getValueToString(const std::string& key) const
+    {
+        auto x = m_values.find(key);
+        if(x != m_values.end())
+        {
+            to_string_visitor vis;
+            boost::apply_visitor(vis, x->second);
+            return std::move(vis.str);
+        }
+
+        return "";
+    }
+
+    std::string OCRepresentation::AttributeItem::getValueToString() const
+    {
+        to_string_visitor vis;
+        boost::apply_visitor(vis, m_values[m_attrName]);
+        return std::move(vis.str);
+    }
+
+    std::ostream& operator<<(std::ostream& os, const OCRepresentation::AttributeItem& ai)
+    {
+        os << ai.getValueToString();
+        return os;
+    }
+}
+
index df5ff60..2ad836a 100644 (file)
@@ -21,6 +21,8 @@
 #include "OCResource.h"
 #include "OCUtilities.h"
 
+#include <boost/lexical_cast.hpp>
+
 namespace OC {
 
 using OC::nil_guard;
@@ -28,9 +30,14 @@ using OC::result_guard;
 using OC::checked_guard;
 
 OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper, const std::string& host,
-                       const std::string& uri, bool observable, const std::vector<std::string>& resourceTypes,
+                       const std::string& uri, const std::string& serverId,
+                       OCConnectivityType connectivityType, bool observable,
+                       const std::vector<std::string>& resourceTypes,
                        const std::vector<std::string>& interfaces)
- :  m_clientWrapper(clientWrapper), m_uri(uri), m_host(host), m_isObservable(observable),
+ :  m_clientWrapper(clientWrapper), m_uri(uri), m_resourceId(serverId, m_uri),
+    m_host(host),
+    m_connectivityType(connectivityType),
+    m_isObservable(observable),
     m_isCollection(false), m_resourceTypes(resourceTypes), m_interfaces(interfaces),
     m_observeHandle(nullptr)
 {
@@ -55,7 +62,8 @@ OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap,
                               GetCallback attributeHandler, QualityOfService QoS)
 {
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetResourceRepresentation,
-                         m_host, m_uri, queryParametersMap, m_headerOptions, attributeHandler, QoS);
+                         m_host, m_uri, m_connectivityType, queryParametersMap, m_headerOptions,
+                         attributeHandler, QoS);
 }
 
 OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap,
@@ -99,7 +107,8 @@ OCStackResult OCResource::put(const OCRepresentation& rep,
                               QualityOfService QoS)
 {
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PutResourceRepresentation,
-                         m_host, m_uri, rep, queryParametersMap, m_headerOptions, attributeHandler, QoS);
+                         m_host, m_uri, m_connectivityType, rep, queryParametersMap,
+                         m_headerOptions, attributeHandler, QoS);
 }
 
 OCStackResult OCResource::put(const OCRepresentation& rep,
@@ -148,7 +157,8 @@ OCStackResult OCResource::post(const OCRepresentation& rep,
                                QualityOfService QoS)
 {
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PostResourceRepresentation,
-                         m_host, m_uri, rep, queryParametersMap, m_headerOptions, attributeHandler, QoS);
+                         m_host, m_uri, m_connectivityType, rep, queryParametersMap,
+                         m_headerOptions, attributeHandler, QoS);
 }
 
 OCStackResult OCResource::post(const OCRepresentation& rep,
@@ -195,7 +205,7 @@ OCStackResult OCResource::post(const std::string& resourceType,
 OCStackResult OCResource::deleteResource(DeleteCallback deleteHandler, QualityOfService QoS)
 {
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::DeleteResource,
-                         m_host, m_uri, m_headerOptions, deleteHandler, QoS);
+                         m_host, m_uri, m_connectivityType, m_headerOptions, deleteHandler, QoS);
 }
 
 OCStackResult OCResource::deleteResource(DeleteCallback deleteHandler)
@@ -217,7 +227,8 @@ OCStackResult OCResource::observe(ObserveType observeType,
 
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::ObserveResource,
                          observeType, &m_observeHandle, m_host,
-                         m_uri, queryParametersMap, m_headerOptions, observeHandler, QoS);
+                         m_uri, m_connectivityType, queryParametersMap, m_headerOptions,
+                         observeHandler, QoS);
 }
 
 OCStackResult OCResource::observe(ObserveType observeType,
@@ -265,9 +276,103 @@ std::string OCResource::uri() const
     return m_uri;
 }
 
+OCConnectivityType OCResource::connectivityType() const
+{
+    return m_connectivityType;
+}
+
 bool OCResource::isObservable() const
 {
     return m_isObservable;
 }
 
+
+OCResourceIdentifier OCResource::uniqueIdentifier() const
+{
+    return m_resourceId;
+}
+
+std::string OCResource::sid() const
+{
+    return this->uniqueIdentifier().m_representation;
+}
+
+bool OCResource::operator==(const OCResource &other) const
+{
+    return m_resourceId == other.m_resourceId;
+}
+
+bool OCResource::operator!=(const OCResource &other) const
+{
+    return m_resourceId != other.m_resourceId;
+}
+
+bool OCResource::operator<(const OCResource &other) const
+{
+    return m_resourceId < other.m_resourceId;
+}
+
+bool OCResource::operator>(const OCResource &other) const
+{
+    return m_resourceId > other.m_resourceId;
+}
+
+bool OCResource::operator<=(const OCResource &other) const
+{
+    return m_resourceId <= other.m_resourceId;
+}
+
+bool OCResource::operator>=(const OCResource &other) const
+{
+    return m_resourceId >= other.m_resourceId;
+}
+
+OCResourceIdentifier::OCResourceIdentifier(const std::string& wireServerIdentifier,
+        const std::string& resourceUri)
+    :m_representation(wireServerIdentifier), m_resourceUri(resourceUri)
+{
+}
+
+std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri)
+{
+
+    os << ri.m_representation<<ri.m_resourceUri;
+
+    return os;
+}
+
+bool OCResourceIdentifier::operator==(const OCResourceIdentifier &other) const
+{
+    return m_representation == other.m_representation
+        && m_resourceUri == other.m_resourceUri;
+}
+
+bool OCResourceIdentifier::operator!=(const OCResourceIdentifier &other) const
+{
+    return !(*this == other);
+}
+
+bool OCResourceIdentifier::operator<(const OCResourceIdentifier &other) const
+{
+    return m_resourceUri < other.m_resourceUri
+        || (m_resourceUri == other.m_resourceUri &&
+                m_representation < other.m_representation);
+}
+
+bool OCResourceIdentifier::operator>(const OCResourceIdentifier &other) const
+{
+    return *this != other && !(*this<other);
+}
+
+bool OCResourceIdentifier::operator<=(const OCResourceIdentifier &other) const
+{
+    return !(*this > other);
+}
+
+bool OCResourceIdentifier::operator>=(const OCResourceIdentifier &other) const
+{
+    return !(*this < other);
+}
+
 } // namespace OC
+
diff --git a/resource/src/OCResourceRequest.cpp b/resource/src/OCResourceRequest.cpp
new file mode 100644 (file)
index 0000000..16abce1
--- /dev/null
@@ -0,0 +1,74 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <OCResourceRequest.h>
+
+#include <vector>
+#include <map>
+#include <cereal/cereal.hpp>
+#include <OicJsonSerializer.hpp>
+
+using namespace OC;
+using namespace std;
+
+void OCResourceRequest::setPayload(const std::string& requestPayload)
+{
+    MessageContainer info;
+
+    if(requestPayload.empty())
+    {
+        return;
+    }
+
+    try
+    {
+        info.setJSONRepresentation(requestPayload);
+    }
+    catch(cereal::RapidJSONException& ex)
+    {
+        oclog() << "RapidJSON Exception in setPayload: "<<ex.what()<<std::endl<<
+            "Data was:"<<requestPayload<<std::flush;
+        return;
+    }
+    catch(cereal::Exception& ex)
+    {
+        oclog() << "Cereal Exception in setPayload: "<<ex.what()<<std::endl<<
+            "Data was:"<<requestPayload<<std::flush;
+        return;
+    }
+
+    const std::vector<OCRepresentation>& reps = info.representations();
+    if(reps.size() >0)
+    {
+        std::vector<OCRepresentation>::const_iterator itr = reps.begin();
+        std::vector<OCRepresentation>::const_iterator back = reps.end();
+        m_representation = *itr;
+        ++itr;
+
+        for(;itr != back; ++itr)
+        {
+            m_representation.addChild(*itr);
+        }
+    }
+    else
+    {
+        oclog() << "setPayload Error: "<<OC::Exception::INVALID_REPRESENTATION<< std::flush;
+    }
+}
diff --git a/resource/src/OCSecurityModel.cpp b/resource/src/OCSecurityModel.cpp
deleted file mode 100644 (file)
index c9bb57f..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "OCSecurityModel.h"
-
-namespace OC {
-       OCSecurityModel::OCSecurityModel(void)
-       {
-       }
-
-
-       OCSecurityModel::~OCSecurityModel(void)
-       {
-       }
-}
\ No newline at end of file
index 530f673..8fc0f03 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);
+        auto index = it.find('=');
 
-    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())
+        if(index == std::string::npos)
         {
-            break;
+            qp[it] = "";
         }
-
-        coap_uri_t coapuri = {{0}};
-        unsigned char* uristr = reinterpret_cast<unsigned char*>(const_cast<char*>(_uri.c_str()));
-
-        if(coap_split_uri(uristr, _uri.length(), &coapuri) < 0)
+        else
         {
-            break;
-        }
-
-        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)
-        {
-            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 {
 
@@ -206,7 +95,6 @@ OCStackResult result_guard(const OCStackResult r)
     case OC_STACK_PRESENCE_TIMEOUT:
     case OC_STACK_PRESENCE_DO_NOT_HANDLE:
 #endif
-
     break;
  }
 
@@ -214,3 +102,4 @@ OCStackResult result_guard(const OCStackResult r)
 }
 
 } // namespace OC
+
index 3a50c87..2e2c94f 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
 ##
@@ -14,11 +34,11 @@ oclib_env = lib_env.Clone()
 oclib_env.AppendUnique(CPPPATH = [
                '../include/',
                '../csdk/stack/include',
-               '../csdk/ocsocket/include',
                '../csdk/ocrandom/include',
+               '../csdk/ocmalloc/include',
                '../csdk/logger/include',
-               '../csdk/libcoap',
-               '../oc_logger/include'
+               '../oc_logger/include',
+               '../csdk/connectivity/lib/libcoap-4.1.1'
                ])
 
 target_os = env.get('TARGET_OS')
@@ -28,11 +48,11 @@ 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', 'coap', 'oc_logger', 'boost_thread', 'gnustl_static', 'log', 'compatibility'])
+       oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'boost_thread', 'gnustl_shared', 'log'])
 
 if target_os in ['darwin', 'ios']:
        oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-       oclib_env.AppendUnique(LIBS = ['octbstack', 'coap', 'oc_logger'])
+       oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger'])
 
 ######################################################################
 # Source files and Targets
@@ -45,9 +65,11 @@ oclib_src = [
                'OCException.cpp',
                'OCRepresentation.cpp',
                'InProcServerWrapper.cpp',
-               'InProcClientWrapper.cpp'
+               'InProcClientWrapper.cpp',
+               'OCResourceRequest.cpp'
        ]
 
-shared_oclib = oclib_env.SharedLibrary('oc', oclib_src)
-static_oclib = oclib_env.StaticLibrary('oc', oclib_src)
-oclib_env.InstallTarget([shared_oclib, static_oclib], 'liboc')
+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 4b1c902..46b80bd 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,17 +41,12 @@ 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
 
                conf = Configure(lib_env)
-
-               if not conf.CheckLib('boost_program_options'):
-                       print 'Did not find boost_program_options, exiting!'
-                       Exit(1)
-
                conf.Finish()
 
 
@@ -58,3 +73,4 @@ elif target_os == 'ios':
 elif target_os == 'darwin':
        lib_env.AppendUnique(CPPPATH = ['/usr/local/include'])
        lib_env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+
diff --git a/resource/unit_tests.scons b/resource/unit_tests.scons
new file mode 100644 (file)
index 0000000..41a10bc
--- /dev/null
@@ -0,0 +1,58 @@
+#******************************************************************
+#
+# 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('env')
+
+target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+build_dir = env.get('BUILD_DIR')
+
+if target_os == 'linux':
+       # Verify that 'google unit test' library is installed.  If not,
+       # get it and install it
+       SConscript(src_dir + '/extlibs/gtest/SConscript')
+
+       # Verify that 'hippomocks' mocking code is installed.  If not,
+       # get it and install it
+       SConscript(src_dir + '/extlibs/hippomocks.scons')
+
+       # Build C unit tests
+       SConscript('csdk/stack/test/SConscript')
+       SConscript('csdk/ocrandom/test/SConscript')
+
+       SConscript('csdk/connectivity/test/SConscript')
+
+       # Build C++ unit tests
+       SConscript('unittests/SConscript')
+
+elif target_os == 'darwin':
+       # Verify that 'google unit test' library is installed.  If not,
+       # get it and install it
+       SConscript(src_dir + '/extlibs/gtest/SConscript')
+
+       # Build C stack's unit tests.
+       SConscript('csdk/stack/test/SConscript')
+       SConscript('csdk/connectivity/test/SConscript')
+
diff --git a/resource/unittests/ConstructResourceTest.cpp b/resource/unittests/ConstructResourceTest.cpp
new file mode 100644 (file)
index 0000000..a9228f6
--- /dev/null
@@ -0,0 +1,68 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <OCPlatform.h>
+#include <OCApi.h>
+
+//Uncomment the below line for testing with Mocks
+//TODO enable these tests (unconditionally) after CA code clean up
+//#define WITH_MOCKS
+#ifdef WITH_MOCKS
+
+#include "hippomocks.h"
+#include "Framework.h"
+
+#define GTEST_DONT_DEFINE_TEST 1
+
+#include <gtest/gtest.h>
+
+namespace ConstructResourceTest
+{
+    using namespace OC;
+    std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
+    //using mocks framework
+    GTEST_TEST(ConstructResourceObjectTest, ConstructResourceObjectValidReturnValue)
+    {
+        MockRepository mocks;
+        OCResource::Ptr rightdoor = std::shared_ptr<OCResource>();
+        OCConnectivityType connectivityType = OC_WIFI;
+        mocks.ExpectCallFunc(OCPlatform::constructResourceObject).Return(rightdoor);
+        std::vector<std::string> types = {"core.leftdoor"};
+        OCResource::Ptr leftdoor = OCPlatform::constructResourceObject("192.168.1.2:5000",
+                "a/leftdoor", connectivityType, false, types, ifaces);
+        EXPECT_EQ(leftdoor, rightdoor);
+
+    }
+
+    GTEST_TEST(ConstructResourceObjectTest, ConstructResourceObjectInValidReturnValue)
+    {
+        MockRepository mocks;
+        OCResource::Ptr rightdoor = std::shared_ptr<OCResource>();
+        OCConnectivityType connectivityType = OC_WIFI;
+        mocks.ExpectCallFunc(OCPlatform::constructResourceObject).Return(NULL);
+        std::vector<std::string> types = {"core.rightdoor"};
+        OCResource::Ptr leftdoor = OCPlatform::constructResourceObject("192.168.1.2:5000",
+                "a/rightdoor", connectivityType, false, types, ifaces);
+        bool value = (leftdoor == NULL);
+        EXPECT_EQ(true, value);
+    }
+}
+#endif
+
diff --git a/resource/unittests/OCExceptionTest.cpp b/resource/unittests/OCExceptionTest.cpp
new file mode 100644 (file)
index 0000000..0e0d4a6
--- /dev/null
@@ -0,0 +1,152 @@
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <algorithm>
+#include <gtest/gtest.h>
+#include <OCException.h>
+#include <StringConstants.h>
+
+namespace OC
+{
+    namespace test
+    {
+        namespace OCExceptionTests
+        {
+            using namespace OC;
+
+            OCStackResult resultCodes[] =
+            {
+                OC_STACK_OK,
+                OC_STACK_RESOURCE_CREATED,
+                OC_STACK_RESOURCE_DELETED,
+                OC_STACK_CONTINUE,
+                OC_STACK_INVALID_URI,
+                OC_STACK_INVALID_QUERY,
+                OC_STACK_INVALID_IP,
+                OC_STACK_INVALID_PORT,
+                OC_STACK_INVALID_CALLBACK,
+                OC_STACK_INVALID_METHOD,
+                OC_STACK_INVALID_PARAM,
+                OC_STACK_INVALID_OBSERVE_PARAM,
+                OC_STACK_NO_MEMORY,
+                OC_STACK_COMM_ERROR,
+                OC_STACK_TIMEOUT,
+                OC_STACK_ADAPTER_NOT_ENABLED,
+                OC_STACK_NOTIMPL,
+                OC_STACK_NO_RESOURCE,
+                OC_STACK_RESOURCE_ERROR,
+                OC_STACK_SLOW_RESOURCE,
+                OC_STACK_NO_OBSERVERS,
+                OC_STACK_OBSERVER_NOT_FOUND,
+                OC_STACK_VIRTUAL_DO_NOT_HANDLE,
+                OC_STACK_INVALID_OPTION,
+                OC_STACK_MALFORMED_RESPONSE,
+                OC_STACK_PERSISTENT_BUFFER_REQUIRED,
+                OC_STACK_INVALID_REQUEST_HANDLE,
+                OC_STACK_INVALID_DEVICE_INFO,
+                OC_STACK_INVALID_JSON,
+                OC_STACK_PRESENCE_STOPPED,
+                OC_STACK_PRESENCE_TIMEOUT,
+                OC_STACK_PRESENCE_DO_NOT_HANDLE,
+                OC_STACK_ERROR
+            };
+
+            std::string resultMessages[]=
+            {
+                OC::Exception::NO_ERROR,
+                OC::Exception::RESOURCE_CREATED,
+                OC::Exception::RESOURCE_DELETED,
+                OC::Exception::STACK_CONTINUE,
+                OC::Exception::INVALID_URI,
+                OC::Exception::INVALID_QUERY,
+                OC::Exception::INVALID_IP,
+                OC::Exception::INVALID_PORT,
+                OC::Exception::INVALID_CB,
+                OC::Exception::INVALID_METHOD,
+                OC::Exception::INVALID_PARAM,
+                OC::Exception::INVALID_OBESERVE,
+                OC::Exception::NO_MEMORY,
+                OC::Exception::COMM_ERROR,
+                OC::Exception::TIMEOUT,
+                OC::Exception::ADAPTER_NOT_ENABLED,
+                OC::Exception::NOT_IMPL,
+                OC::Exception::NOT_FOUND,
+                OC::Exception::RESOURCE_ERROR,
+                OC::Exception::SLOW_RESOURCE,
+                OC::Exception::NO_OBSERVERS,
+                OC::Exception::OBSV_NO_FOUND,
+                OC::Exception::VIRTUAL_DO_NOT_HANDLE,
+                OC::Exception::INVALID_OPTION,
+                OC::Exception::MALFORMED_STACK_RESPONSE,
+                OC::Exception::PERSISTENT_BUFFER_REQUIRED,
+                OC::Exception::INVALID_REQUEST_HANDLE,
+                OC::Exception::INVALID_DEVICE_INFO,
+                OC::Exception::INVALID_REPRESENTATION,
+                OC::Exception::PRESENCE_STOPPED,
+                OC::Exception::PRESENCE_TIMEOUT,
+                OC::Exception::PRESENCE_NOT_HANDLED,
+                OC::Exception::GENERAL_FAULT
+            };
+            TEST(OCExceptionTest, ReasonCodeMatches)
+            {
+                for(OCStackResult res : resultCodes)
+                {
+                    OCException ex{"", res};
+                    EXPECT_EQ(res, ex.code());
+                }
+            }
+
+            TEST(OCExceptionTest, MessageCodeMatches)
+            {
+                std::string exceptionMessage = "This is the exception message!";
+                OCException ex {exceptionMessage, OC_STACK_OK};
+
+                EXPECT_EQ(exceptionMessage, ex.what());
+            }
+
+            TEST(OCExceptionTest, ReasonMapping)
+            {
+                int i=0;
+                for(OCStackResult res : resultCodes)
+                {
+                    OCException ex{"", res};
+                    EXPECT_EQ(resultMessages[i], ex.reason());
+                    ++i;
+                }
+            }
+
+            TEST(OCExceptionTest, UnknownReasonMappings)
+            {
+                for(int i = 0; i < OC_STACK_ERROR; ++i)
+                {
+                    if(std::find(
+                                std::begin(resultCodes),
+                                std::end(resultCodes),
+                                static_cast<OCStackResult>(i))
+                            == std::end(resultCodes))
+                    {
+                        OCException ex {"", static_cast<OCStackResult>(i)};
+                        EXPECT_EQ(OC::Exception::UNKNOWN_ERROR, ex.reason());
+                    }
+                }
+            }
+        } //namespace OCExceptionTests
+    } //namespace test
+} //namespace OC
diff --git a/resource/unittests/OCHeaderOptionTest.cpp b/resource/unittests/OCHeaderOptionTest.cpp
new file mode 100644 (file)
index 0000000..df1a5e3
--- /dev/null
@@ -0,0 +1,82 @@
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <algorithm>
+#include <gtest/gtest.h>
+#include <OCHeaderOption.h>
+#include <OCException.h>
+#include <StringConstants.h>
+
+namespace OC
+{
+    namespace test
+    {
+        namespace OCHeaderOptionTests
+        {
+            using namespace OC;
+
+            TEST(OCHeaderOptionTest, ConstructorValidRangeTest)
+            {
+                // Note: this test just assures that none of these
+                // constructors throw an exception
+                for(uint16_t i = HeaderOption::MIN_HEADER_OPTIONID;
+                        i < HeaderOption::MAX_HEADER_OPTIONID;
+                        ++i)
+                {
+                    HeaderOption::OCHeaderOption{i, ""};
+                }
+            }
+
+            TEST(OCHeaderOptionTest, ConstructorTooLowOptionIdTest)
+            {
+                for(uint16_t i = 0; i < HeaderOption::MIN_HEADER_OPTIONID; ++i)
+                {
+                    ASSERT_THROW(
+                            HeaderOption::OCHeaderOption(i,""),
+                            OCException);
+                }
+            }
+
+            TEST(OCHeaderOptionTest, ConstructorTooHighOptionIdTest)
+            {
+                for(uint16_t i = HeaderOption::MAX_HEADER_OPTIONID +1 ; i <UINT16_MAX;++i)
+                {
+                    ASSERT_THROW(
+                            HeaderOption::OCHeaderOption(i,""),
+                            OCException);
+                }
+            }
+
+            TEST(OCHeaderOptionTest, OptionIDTest)
+            {
+                HeaderOption::OCHeaderOption opt {HeaderOption::MIN_HEADER_OPTIONID + 5, ""};
+                EXPECT_EQ(HeaderOption::MIN_HEADER_OPTIONID + 5, opt.getOptionID());
+            }
+
+            TEST(OCHeaderOptionTest, OptionDataTest)
+            {
+                std::string optionData {"134kl5jt iopdfgj;lwe45 puiondj;vlk345t89o sdkl;ag"};
+                HeaderOption::OCHeaderOption opt {HeaderOption::MIN_HEADER_OPTIONID, optionData};
+                EXPECT_EQ(optionData, opt.getOptionData());
+            }
+
+        } //namespace OCHeaderOptionTests
+    } //namespace test
+} //namespace OC
diff --git a/resource/unittests/OCPlatformTest.cpp b/resource/unittests/OCPlatformTest.cpp
new file mode 100644 (file)
index 0000000..2264e37
--- /dev/null
@@ -0,0 +1,724 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <OCPlatform.h>
+#include <OCApi.h>
+#include <gtest/gtest.h>
+
+namespace OCPlatformTest
+{
+    using namespace OC;
+
+    const OCResourceHandle HANDLE_ZERO = 0;
+    const std::string gResourceTypeName = "core.res";
+    const std::string gResourceInterface = DEFAULT_INTERFACE;
+    const uint8_t gResourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+    OCResourceHandle resourceHandle;
+
+    // Callbacks
+    OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
+    {
+        return OC_EH_OK;
+    }
+
+    void foundResource(std::shared_ptr<OCResource> resource)
+    {
+    }
+
+    void receivedDeviceInfo(const OCRepresentation& rep)
+    {
+    }
+
+    void presenceHandler(OCStackResult result,
+            const unsigned int nonce, const std::string& hostAddress)
+    {
+    }
+
+    //Helper methods
+    void DeleteDeviceInfo(OCDeviceInfo deviceInfo)
+    {
+        delete[] deviceInfo.contentType;
+        delete[] deviceInfo.dateOfManufacture;
+        delete[] deviceInfo.deviceName;
+        delete[] deviceInfo.deviceUUID;
+        delete[] deviceInfo.firmwareVersion;
+        delete[] deviceInfo.hostName;
+        delete[] deviceInfo.manufacturerName;
+        delete[] deviceInfo.manufacturerUrl;
+        delete[] deviceInfo.modelNumber;
+        delete[] deviceInfo.platformVersion;
+        delete[] deviceInfo.supportUrl;
+        delete[] deviceInfo.version;
+    }
+
+    void DuplicateString(char ** targetString, std::string sourceString)
+    {
+        *targetString = new char[sourceString.length() + 1];
+        strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
+    }
+
+    OCResourceHandle RegisterResource(std::string uri, std::string type, std::string iface)
+    {
+        PlatformConfig cfg = {};
+        OCPlatform::Configure(cfg);
+        EXPECT_EQ(OC_STACK_OK,OCPlatform::registerResource(
+                                        resourceHandle, uri, type,
+                                        iface, entityHandler, gResourceProperty));
+        return resourceHandle;
+    }
+
+    OCResourceHandle RegisterResource(std::string uri, std::string type)
+    {
+        PlatformConfig cfg = {};
+        OCPlatform::Configure(cfg);
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::registerResource(
+                                        resourceHandle, uri, type,
+                                        gResourceInterface, entityHandler, gResourceProperty));
+        return resourceHandle;
+    }
+
+    OCResourceHandle RegisterResource(std::string uri)
+    {
+        PlatformConfig cfg = {};
+        OCPlatform::Configure(cfg);
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::registerResource(
+                                        resourceHandle, uri, gResourceTypeName,
+                                        gResourceInterface, entityHandler, gResourceProperty));
+        return resourceHandle;
+    }
+
+    //Configure
+    // Enable it when the stack throw an exception
+    // https://jira.iotivity.org/browse/IOT-428
+    TEST(ConfigureTest, DISABLED_ConfigureInvalidModeType)
+    {
+        PlatformConfig cfg {
+             OC::ServiceType::InProc,
+            (OC::ModeType)99,
+             "0.0.0.0",
+             0,
+             OC::QualityOfService::LowQos
+         };
+         OCPlatform::Configure(cfg);
+         EXPECT_ANY_THROW(OCPlatform::setDefaultDeviceEntityHandler(NULL));
+     }
+
+    // Enable it when the stack throw an exception
+    // https://jira.iotivity.org/browse/IOT-428
+    TEST(ConfigureTest, DISABLED_ConfigureInvalidServiceType)
+    {
+        PlatformConfig cfg {
+             (OC::ServiceType)99,
+            OC::ModeType::Client,
+             "0.0.0.0",
+             0,
+             OC::QualityOfService::LowQos
+         };
+         OCPlatform::Configure(cfg);
+         EXPECT_ANY_THROW(OCPlatform::setDefaultDeviceEntityHandler(NULL));
+     }
+
+    // Enable it when the stack throw an exception
+    // https://jira.iotivity.org/browse/IOT-428
+    TEST(ConfigureTest, DISABLED_ConfigureClientOutProc)
+    {
+        PlatformConfig cfg {
+            OC::ServiceType::OutOfProc,
+            OC::ModeType::Client,
+            "0.0.0.0",
+            0,
+            OC::QualityOfService::LowQos
+        };
+        std::string uri = "/a/light66";
+        std::string type = "core.light";
+        uint8_t gResourceProperty = 0;
+        OCPlatform::Configure(cfg);
+        EXPECT_ANY_THROW(OCPlatform::registerResource(
+             resourceHandle, uri, type,
+             gResourceInterface, entityHandler, gResourceProperty));
+    }
+
+    TEST(ConfigureTest, ConfigureServerOutProc)
+    {
+        PlatformConfig cfg {
+            OC::ServiceType::OutOfProc,
+            OC::ModeType::Server,
+            "0.0.0.0",
+            0,
+            OC::QualityOfService::LowQos
+        };
+        std::string uri = "/a/light67";
+        std::string type = "core.light";
+        uint8_t gResourceProperty = 0;
+        OCPlatform::Configure(cfg);
+
+        EXPECT_ANY_THROW(OCPlatform::registerResource(
+             resourceHandle, uri, type,
+             gResourceInterface, entityHandler, gResourceProperty));
+    }
+
+    TEST(ConfigureTest, ConfigureDefault)
+    {
+        std::string uri = "/a/light68";
+        std::string type = "core.light";
+        uint8_t gResourceProperty = 0;
+        PlatformConfig cfg = {};
+        OCPlatform::Configure(cfg);
+
+        EXPECT_NO_THROW(OCPlatform::registerResource(
+                 resourceHandle, uri, type,
+                 gResourceInterface, entityHandler, gResourceProperty));
+    }
+
+    TEST(ConfigureTest, ConfigureServer)
+    {
+        std::string uri = "/a/light69";
+        std::string type = "core.light";
+        uint8_t gResourceProperty = 0;
+        PlatformConfig cfg {
+            OC::ServiceType::InProc,
+            OC::ModeType::Server,
+            "0.0.0.0",
+            0,
+            OC::QualityOfService::LowQos
+        };
+        OCPlatform::Configure(cfg);
+
+        EXPECT_NO_THROW(OCPlatform::registerResource(
+                 resourceHandle, uri, type,
+                 gResourceInterface, entityHandler, gResourceProperty));
+    }
+
+    TEST(ConfigureTest, ConfigureClient)
+    {
+        std::string uri = "/a/light70";
+        std::string type = "core.light";
+        uint8_t gResourceProperty = 0;
+        PlatformConfig cfg {
+            OC::ServiceType::InProc,
+            OC::ModeType::Client,
+            "0.0.0.0",
+            0,
+            OC::QualityOfService::LowQos
+        };
+        OCPlatform::Configure(cfg);
+
+        EXPECT_NO_THROW(OCPlatform::registerResource(
+                 resourceHandle, uri, type,
+                 gResourceInterface, entityHandler, gResourceProperty));
+    }
+
+    //RegisterResourceTest
+    TEST(RegisterResourceTest, RegisterSingleResource)
+    {
+        std::string uri = "/a/res2";
+        EXPECT_NE(HANDLE_ZERO, RegisterResource(uri));
+    }
+
+    TEST(RegisterResourceTest, RegisterMultipleResources)
+    {
+        std::string uri = "/a/multi";
+        //Good enough for 5 resources.
+        for(int i=0; i< 5; i++)
+        {
+            uri +=std::to_string(i);
+            EXPECT_NE(HANDLE_ZERO, RegisterResource(uri));
+        }
+    }
+
+    TEST(RegisterResourceTest, ReregisterResource)
+    {
+        OCResourceHandle resourceHandle = RegisterResource(std::string("/a/light5"),
+            std::string("core.light"));
+        EXPECT_EQ(OC_STACK_OK, OC::OCPlatform::unregisterResource(resourceHandle));
+
+        EXPECT_NE(HANDLE_ZERO, RegisterResource(std::string("/a/light5"),
+            std::string("core.light")));
+
+    }
+
+    TEST(RegisterResourceTest, RegisterEmptyResource)
+    {
+        // We should not allow empty URI.
+        std::string emptyStr = "";
+        EXPECT_ANY_THROW(OCPlatform::registerResource(resourceHandle, emptyStr, emptyStr,
+                                        emptyStr, entityHandler, gResourceProperty));
+    }
+
+    TEST(RegisterResourceTest, RegisterZeroResourceProperty)
+    {
+        std::string uri = "/a/light6";
+        std::string type = "core.light";
+        uint8_t gResourceProperty = 0;
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::registerResource(
+                resourceHandle, uri, type,
+                gResourceInterface, entityHandler, gResourceProperty));
+    }
+
+    //UnregisterTest
+    TEST(UnregisterTest, UnregisterZeroHandleValue)
+    {
+        EXPECT_ANY_THROW(OC::OCPlatform::unregisterResource(HANDLE_ZERO));
+    }
+
+    //UnbindResourcesTest
+    TEST(UnbindResourcesTest, UnbindResources)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("a/home"),
+            std::string("core.home"));
+        OCResourceHandle resourceKitchen = RegisterResource(std::string("a/kitchen"),
+            std::string("core.kitchen"), LINK_INTERFACE);
+        OCResourceHandle resourceRoom = RegisterResource(std::string("a/office"),
+            std::string("core.office"), LINK_INTERFACE);
+
+        std::vector<OCResourceHandle> rList;
+        rList.push_back(resourceKitchen);
+        rList.push_back(resourceRoom);
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::bindResources(resourceHome, rList));
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::unbindResources(resourceHome, rList));
+    }
+
+    TEST(UnbindResourcesTest, UnbindResourcesWithZero)
+    {
+        OCResourceHandle resourceHandle1 = 0;
+        OCResourceHandle resourceHandle2 = 0;
+        OCResourceHandle resourceHandle3 = 0;
+
+        std::vector<OCResourceHandle> rList;
+
+        rList.push_back(resourceHandle2);
+        rList.push_back(resourceHandle3);
+
+        EXPECT_ANY_THROW(OCPlatform::unbindResources(resourceHandle1, rList));
+    }
+
+    //BindInterfaceToResourceTest
+    TEST(BindInterfaceToResourceTest, BindResourceInterface)
+    {
+        OCResourceHandle resourceHandle = RegisterResource(std::string("/a/light"),
+            std::string("core.light"));
+        OCStackResult result = OC::OCPlatform::bindInterfaceToResource(resourceHandle,
+            BATCH_INTERFACE);
+        EXPECT_EQ(OC_STACK_OK, result);
+    }
+
+    TEST(BindInterfaceToResourceTest, BindZeroResourceInterface)
+    {
+        OCResourceHandle resourceHandle = RegisterResource(std::string("/a/light1"),
+            std::string("core.light"));
+        EXPECT_ANY_THROW(OC::OCPlatform::bindInterfaceToResource(resourceHandle, 0));
+    }
+
+    //BindTypeToResourceTest
+    TEST(BindTypeToResourceTest, BindResourceType)
+    {
+        OCResourceHandle resourceHandle = RegisterResource(std::string("/a/light3"),
+            std::string("core.light"));
+        OCStackResult result = OC::OCPlatform::bindTypeToResource(resourceHandle,
+            "core.brightlight");
+        EXPECT_EQ(OC_STACK_OK, result);
+    }
+
+    TEST(BindTypeToResourceTest, BindZeroResourceType)
+    {
+        OCResourceHandle resourceHandle = RegisterResource(std::string("/a/light4"),
+            std::string("core.light"));
+        EXPECT_ANY_THROW(OC::OCPlatform::bindTypeToResource(resourceHandle, 0));
+    }
+
+    //UnbindResourceTest
+    TEST(UnbindResourceTest, BindAndUnbindResource)
+    {
+        OCResourceHandle resourceHandle1 = RegisterResource(std::string("a/unres"),
+            std::string("core.unres"));
+        OCResourceHandle resourceHandle2 = RegisterResource(std::string("a/unres2"),
+            std::string("core.unres"), LINK_INTERFACE);
+
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::bindResource(resourceHandle1, resourceHandle2));
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::unbindResource(resourceHandle1, resourceHandle2));
+    }
+
+    //PresenceTest
+    TEST(PresenceTest, DISABLED_StartAndStopPresence)
+    {
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::startPresence(30));
+        EXPECT_NE(HANDLE_ZERO, RegisterResource( std::string("/a/Presence"),
+            std::string("core.Presence")));
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::stopPresence());
+    }
+
+    TEST(OCPlatformTest, UnbindZeroRsourceHandleValue)
+    {
+        EXPECT_ANY_THROW(OCPlatform::unbindResource(HANDLE_ZERO, HANDLE_ZERO));
+    }
+
+    //NotifyAllObserverTest
+    TEST(NotifyAllObserverTest, NotifyAllObservers)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs1"),
+            std::string("core.obs"));
+        EXPECT_EQ(OC_STACK_NO_OBSERVERS, OCPlatform::notifyAllObservers(resourceHome));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyAllObserversWithLowQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs2"),
+            std::string("core.obs"));
+        EXPECT_EQ(OC_STACK_NO_OBSERVERS, OCPlatform::notifyAllObservers(resourceHome,
+                OC::QualityOfService::LowQos));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyAllObserversWithMidQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs3"),
+            std::string("core.obs"));
+        EXPECT_EQ(OC_STACK_NO_OBSERVERS, OCPlatform::notifyAllObservers(resourceHome,
+                OC::QualityOfService::MidQos));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyAllObserversWithNaQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs4"),
+            std::string("core.obs"));
+        EXPECT_EQ(OC_STACK_NO_OBSERVERS, OCPlatform::notifyAllObservers(resourceHome,
+                OC::QualityOfService::NaQos));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyAllObserversWithHighQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs5"),
+            std::string("core.obs"));
+        EXPECT_EQ(OC_STACK_NO_OBSERVERS, OCPlatform::notifyAllObservers(resourceHome,
+                OC::QualityOfService::HighQos));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyListOfObservers)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs6"),
+            std::string("core.obs"));
+
+        std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+        ObservationIds interestedObservers;
+        EXPECT_ANY_THROW(OCPlatform::notifyListOfObservers(resourceHome,
+            interestedObservers, resourceResponse));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyListOfObserversWithLowQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs7"),
+            std::string("core.obs"));
+
+        std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+        ObservationIds interestedObservers;
+        EXPECT_ANY_THROW(OCPlatform::notifyListOfObservers(resourceHome,
+            interestedObservers, resourceResponse,OC::QualityOfService::LowQos));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyListOfObserversWithMidQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs8"),
+            std::string("core.obs"));
+
+        std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+        ObservationIds interestedObservers;
+        EXPECT_ANY_THROW(OCPlatform::notifyListOfObservers(resourceHome,
+            interestedObservers, resourceResponse,OC::QualityOfService::MidQos));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyListOfObserversWithNaQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs9"),
+            std::string("core.obs"));
+
+        std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+        ObservationIds interestedObservers;
+        EXPECT_ANY_THROW(OCPlatform::notifyListOfObservers(resourceHome,
+            interestedObservers, resourceResponse,OC::QualityOfService::NaQos));
+    }
+
+    TEST(NotifyAllObserverTest, NotifyListOfObserversWithHighQos)
+    {
+        OCResourceHandle resourceHome = RegisterResource(std::string("/a/obs10"),
+            std::string("core.obs"));
+
+        std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+        ObservationIds interestedObservers;
+        EXPECT_ANY_THROW(OCPlatform::notifyListOfObservers(resourceHome,
+            interestedObservers, resourceResponse,OC::QualityOfService::HighQos));
+    }
+
+    //DeviceEntityHandlerTest
+    TEST(DeviceEntityHandlerTest, SetDefaultDeviceEntityHandler)
+    {
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::setDefaultDeviceEntityHandler(entityHandler));
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::setDefaultDeviceEntityHandler(NULL));
+    }
+
+
+    //FindResource test
+    TEST(FindResourceTest, DISABLED_FindResourceValid)
+    {
+      std::ostringstream requestURI;
+      requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+      EXPECT_EQ(OC_STACK_OK, OCPlatform::findResource("", requestURI.str(),
+              OC_IPV4, &foundResource));
+    }
+
+    TEST(FindResourceTest, FindResourceNullResourceURI)
+    {
+      EXPECT_ANY_THROW(OCPlatform::findResource("", nullptr,
+              OC_IPV4, &foundResource));
+    }
+
+    TEST(FindResourceTest, FindResourceNullResourceURI1)
+    {
+      std::ostringstream requestURI;
+      requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+      EXPECT_ANY_THROW(OCPlatform::findResource(nullptr, requestURI.str(),
+              OC_IPV4, &foundResource));
+    }
+
+    TEST(FindResourceTest, FindResourceNullHost)
+    {
+      std::ostringstream requestURI;
+      requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+      EXPECT_ANY_THROW(OCPlatform::findResource(nullptr, requestURI.str(),
+              OC_IPV4, &foundResource));
+    }
+
+    TEST(FindResourceTest, FindResourceNullresourceHandler)
+    {
+      std::ostringstream requestURI;
+      requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+      EXPECT_THROW(OCPlatform::findResource("", requestURI.str(),
+              OC_IPV4, NULL), OC::OCException);
+    }
+
+    TEST(FindResourceTest, DISABLED_FindResourceWithLowQoS)
+    {
+        std::ostringstream requestURI;
+        requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+                        OC::QualityOfService::LowQos));
+    }
+
+    TEST(FindResourceTest, DISABLED_FindResourceWithMidQos)
+    {
+        std::ostringstream requestURI;
+        requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+                        OC::QualityOfService::MidQos));
+    }
+
+    TEST(FindResourceTest, DISABLED_FindResourceWithHighQos)
+    {
+        std::ostringstream requestURI;
+        requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+                        OC::QualityOfService::HighQos));
+    }
+
+    TEST(FindResourceTest, DISABLED_FindResourceWithNaQos)
+    {
+        std::ostringstream requestURI;
+        requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+                        OC::QualityOfService::NaQos));
+    }
+
+    //GetDeviceInfo Test
+    TEST(GetDeviceInfoTest, DISABLED_GetDeviceInfoWithValidParameters)
+    {
+        std::string deviceDiscoveryURI = "/oc/core/d";
+        PlatformConfig cfg;
+        OCPlatform::Configure(cfg);
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo));
+    }
+
+    TEST(GetDeviceInfoTest, GetDeviceInfoNullDeviceURI)
+    {
+        PlatformConfig cfg;
+        OCPlatform::Configure(cfg);
+        EXPECT_ANY_THROW(
+                OCPlatform::getDeviceInfo("", nullptr, OC_IPV4, &receivedDeviceInfo));
+    }
+
+    TEST(GetDeviceInfoTest, GetDeviceInfoWithNullDeviceInfoHandler)
+    {
+        std::string deviceDiscoveryURI = "/oc/core/d";
+        PlatformConfig cfg;
+        OCPlatform::Configure(cfg);
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
+        EXPECT_THROW(
+                OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, NULL),
+                OC::OCException);
+    }
+
+    TEST(GetDeviceInfoTest, DISABLED_GetDeviceInfoWithLowQos)
+    {
+        std::string deviceDiscoveryURI = "/oc/core/d";
+        PlatformConfig cfg;
+        OCPlatform::Configure(cfg);
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+                        OC::QualityOfService::LowQos));
+    }
+
+    TEST(GetDeviceInfoTest, DISABLED_GetDeviceInfoWithMidQos)
+    {
+        std::string deviceDiscoveryURI = "/oc/core/d";
+        PlatformConfig cfg;
+        OCPlatform::Configure(cfg);
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+                        OC::QualityOfService::MidQos));
+    }
+
+    TEST(GetDeviceInfoTest, DISABLED_GetDeviceInfoWithHighQos)
+    {
+        std::string deviceDiscoveryURI = "/oc/core/d";
+        PlatformConfig cfg;
+        OCPlatform::Configure(cfg);
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+                        OC::QualityOfService::HighQos));
+    }
+
+    TEST(GetDeviceInfoTest, DISABLED_GetDeviceInfoWithNaQos)
+    {
+        std::string deviceDiscoveryURI = "/oc/core/d";
+        PlatformConfig cfg;
+        OCPlatform::Configure(cfg);
+        std::ostringstream requestURI;
+        requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
+        EXPECT_EQ(OC_STACK_OK,
+                OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+                        OC::QualityOfService::NaQos));
+    }
+
+    //RegisterDeviceInfo test
+    TEST(RegisterDeviceInfoTest, RegisterDeviceInfoWithValidParameters)
+    {
+        OCDeviceInfo deviceInfo;
+
+        DuplicateString(&deviceInfo.contentType, "myContentType");
+        DuplicateString(&deviceInfo.dateOfManufacture, "myDateOfManufacture");
+        DuplicateString(&deviceInfo.deviceName, "myDeviceName");
+        DuplicateString(&deviceInfo.deviceUUID, "myDeviceUUID");
+        DuplicateString(&deviceInfo.firmwareVersion, "myFirmwareVersion");
+        DuplicateString(&deviceInfo.hostName, "myHostName");
+        DuplicateString(&deviceInfo.manufacturerName, "myManufacturerNa");
+        DuplicateString(&deviceInfo.manufacturerUrl, "myManufacturerUrl");
+        DuplicateString(&deviceInfo.modelNumber, "myModelNumber");
+        DuplicateString(&deviceInfo.platformVersion, "myPlatformVersion");
+        DuplicateString(&deviceInfo.supportUrl, "mySupportUrl");
+        DuplicateString(&deviceInfo.version, "myVersion");
+
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::registerDeviceInfo(deviceInfo));
+        EXPECT_NO_THROW(DeleteDeviceInfo(deviceInfo));
+    }
+
+    TEST(RegisterDeviceInfoTest, RegisterDeviceInfoWithEmptyObject)
+    {
+        OCDeviceInfo di = {};
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::registerDeviceInfo(di));
+    }
+
+    //SubscribePresence Test
+    TEST(SubscribePresenceTest, DISABLED_SubscribePresenceWithValidParameters)
+    {
+        std::string hostAddress = "192.168.1.2:5000";
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle, hostAddress,
+                 OC_IPV4, &presenceHandler));
+    }
+
+    TEST(SubscribePresenceTest, SubscribePresenceWithNullHost)
+    {
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+
+        EXPECT_ANY_THROW(OCPlatform::subscribePresence(presenceHandle, nullptr,
+                 OC_IPV4, &presenceHandler));
+    }
+
+    TEST(SubscribePresenceTest, SubscribePresenceWithNullPresenceHandler)
+    {
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+
+        EXPECT_ANY_THROW(OCPlatform::subscribePresence(presenceHandle, nullptr,
+                 OC_IPV4, NULL));
+    }
+
+    TEST(SubscribePresenceTest, DISABLED_SubscribePresenceWithResourceType)
+    {
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle,
+                OC_MULTICAST_IP, "core.light", OC_IPV4, &presenceHandler));
+    }
+
+    TEST(SubscribePresenceTest, SubscribePresenceWithNullResourceType)
+    {
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+
+        EXPECT_ANY_THROW(OCPlatform::subscribePresence(presenceHandle,
+                OC_MULTICAST_IP, nullptr, OC_IPV4, &presenceHandler));
+    }
+
+    TEST(SubscribePresenceTest, DISABLED_UnsubscribePresenceWithValidHandleAndRT)
+    {
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle,
+                OC_MULTICAST_IP, "core.light", OC_IPV4, &presenceHandler));
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::unsubscribePresence(presenceHandle));
+    }
+
+    TEST(SubscribePresenceTest, UnsubscribePresenceWithNullHandle)
+    {
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+        EXPECT_ANY_THROW(OCPlatform::unsubscribePresence(presenceHandle));
+    }
+
+    TEST(SubscribePresenceTest, DISABLED_UnsubscribePresenceWithValidHandle)
+    {
+        OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle,
+                OC_MULTICAST_IP, OC_IPV4, &presenceHandler));
+        EXPECT_EQ(OC_STACK_OK, OCPlatform::unsubscribePresence(presenceHandle));
+    }
+
+}
diff --git a/resource/unittests/OCRepresentationTest.cpp b/resource/unittests/OCRepresentationTest.cpp
new file mode 100644 (file)
index 0000000..befcdcb
--- /dev/null
@@ -0,0 +1,1313 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <gtest/gtest.h>
+#include <OCApi.h>
+#include <string>
+#include <limits>
+#include <boost/lexical_cast.hpp>
+namespace OCRepresentationTest
+{
+    using namespace OC;
+    using std::string;
+    using std::vector;
+
+    void parsedEqual(double expected, const std::string& actualStr)
+    {
+        double actual = boost::lexical_cast<double>(actualStr);
+        EXPECT_GE(actual, expected - .0000001);
+        EXPECT_LE(actual, expected + .0000001);
+    }
+
+    // getValueToString(all types)
+    TEST(OCRepresentationValueToString, Null)
+    {
+        static const std::string AttrName = "NullTest";
+        OCRepresentation rep;
+        rep.setNULL(AttrName);
+
+        EXPECT_TRUE(rep.isNULL(AttrName));
+        EXPECT_EQ("(null)", rep.getValueToString(AttrName));
+        EXPECT_EQ("(null)", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, Integer)
+    {
+        static const std::string AttrName = "IntTest";
+        OCRepresentation rep;
+
+        rep.setValue(AttrName, -5);
+        EXPECT_EQ("-5", rep.getValueToString(AttrName));
+        EXPECT_EQ("-5", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 0);
+        EXPECT_EQ("0", rep.getValueToString(AttrName));
+        EXPECT_EQ("0", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 5);
+        EXPECT_EQ("5", rep.getValueToString(AttrName));
+        EXPECT_EQ("5", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 54321);
+        EXPECT_EQ("54321", rep.getValueToString(AttrName));
+        EXPECT_EQ("54321", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, Double)
+    {
+        static const std::string AttrName = "DoubleTest";
+        OCRepresentation rep;
+
+        rep.setValue(AttrName, -5.0);
+        parsedEqual(-5.0, rep.getValueToString(AttrName));
+        parsedEqual(-5.0, rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 0.0);
+        parsedEqual(0.0, rep.getValueToString(AttrName));
+        parsedEqual(0.0, rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 5.0);
+        parsedEqual(5.0, rep.getValueToString(AttrName));
+        parsedEqual(5.0, rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 54321.0);
+        parsedEqual(54321.0, rep.getValueToString(AttrName));
+        parsedEqual(54321.0, rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 3.55);
+        parsedEqual(3.55, rep.getValueToString(AttrName));
+        parsedEqual(3.55, rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, -4.95);
+        parsedEqual(-4.95, rep.getValueToString(AttrName));
+        parsedEqual(-4.95, rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, 99999.5555);
+        parsedEqual(99999.5555, rep.getValueToString(AttrName));
+        parsedEqual(99999.5555, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, Boolean)
+    {
+        static const std::string AttrName = "BooleanTest";
+        OCRepresentation rep;
+
+        rep.setValue(AttrName, false);
+        EXPECT_EQ("false", rep.getValueToString(AttrName));
+        EXPECT_EQ("false", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, true);
+        EXPECT_EQ("true", rep.getValueToString(AttrName));
+        EXPECT_EQ("true", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, String)
+    {
+        static const std::string AttrName = "StringTest";
+        OCRepresentation rep;
+
+        rep.setValue(AttrName, std::string("test 1"));
+        EXPECT_EQ("test 1", rep.getValueToString(AttrName));
+        EXPECT_EQ("test 1", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, std::string("test 2"));
+        EXPECT_EQ("test 2", rep.getValueToString(AttrName));
+        EXPECT_EQ("test 2", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, SubRepresentation)
+    {
+        static const std::string AttrName = "SubRepTest";
+        OCRepresentation rep;
+        OCRepresentation sub1;
+        OCRepresentation sub2;
+
+        rep.setValue(AttrName, sub1);
+        EXPECT_EQ("OC::OCRepresentation", rep.getValueToString(AttrName));
+        EXPECT_EQ("OC::OCRepresentation", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, sub2);
+        EXPECT_EQ("OC::OCRepresentation", rep.getValueToString(AttrName));
+        EXPECT_EQ("OC::OCRepresentation", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, IntegerVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<int> vect {1,2,3,4,5,6,7,8,9};
+        vector<int> vect2 {-5,-3,-1,0,5,3,2};
+        rep.setValue(AttrName, vect);
+        EXPECT_EQ("[1 2 3 4 5 6 7 8 9 ]", rep.getValueToString(AttrName));
+        EXPECT_EQ("[1 2 3 4 5 6 7 8 9 ]", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, vect2);
+        EXPECT_EQ("[-5 -3 -1 0 5 3 2 ]", rep.getValueToString(AttrName));
+        EXPECT_EQ("[-5 -3 -1 0 5 3 2 ]", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, IntegerVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<int> vect1 {1,2,3,4,5,6,7,8,9};
+        vector<int> vect2 {-5,-3,-1,0,5,3,2};
+        vector<vector<int>> vect{vect1, vect2};
+
+        rep.setValue(AttrName, vect);
+        static const string Expected = "[[1 2 3 4 5 6 7 8 9 ] [-5 -3 -1 0 5 3 2 ] ]";
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, IntegerVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<int> vect11 {1,2,3,4,5,6,7,8,9};
+        vector<int> vect12 {-5,-3,-1,0,5,3,2};
+        vector<vector<int>> vect1{vect11, vect12};
+        vector<int> vect21 {2,0,1,6,9,3,8};
+        vector<int> vect22 {9,7,8,100003};
+        vector<vector<int>> vect2{vect21, vect22};
+        vector<vector<vector<int>>> vect{vect1, vect2};
+        rep.setValue(AttrName, vect);
+        static const std::string Expected =
+            "[[[1 2 3 4 5 6 7 8 9 ] [-5 -3 -1 0 5 3 2 ] ] [[2 0 1 6 9 3 8 ] [9 7 8 100003 ] ] ]";
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, DoubleVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<double> vect {3.12, -5.3, 7.5, 1.110};
+        vector<double> vect2 {2.1, -555.5, 0.0001, -0.2};
+        rep.setValue(AttrName, vect);
+        EXPECT_EQ(rep.getValueToString(AttrName), rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, vect2);
+        EXPECT_EQ(rep.getValueToString(AttrName), rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, DoubleVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<double> vect1 {30.1,5.88,-22.0,0};
+        vector<double> vect2 {2.1,-55.5,0.1100,-.2};
+        vector<vector<double>> vect{vect1, vect2};
+
+        rep.setValue(AttrName, vect);
+        EXPECT_EQ(rep.getValueToString(AttrName), rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, DoubleVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<double> vect11 {3.01, 5.88, -22.0, 0.0};
+        vector<double> vect12 {99.3,8.0,.01236,-.22};
+        vector<vector<double>> vect1{vect11, vect12};
+        vector<double> vect21 {9.0,-1};
+        vector<double> vect22 {-99.2};
+        vector<vector<double>> vect2{vect21, vect22};
+        vector<vector<vector<double>>> vect{vect1, vect2};
+        rep.setValue(AttrName, vect);
+        EXPECT_EQ(rep.getValueToString(AttrName), rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, BooleanVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<bool> vect {true, false, false, true};
+        vector<bool> vect2 {false, false, false, true};
+        rep.setValue(AttrName, vect);
+        EXPECT_EQ("[true false false true ]", rep.getValueToString(AttrName));
+        EXPECT_EQ("[true false false true ]", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, vect2);
+        EXPECT_EQ("[false false false true ]", rep.getValueToString(AttrName));
+        EXPECT_EQ("[false false false true ]", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, BooleanVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<bool> vect1 {true, false, false, true};
+        vector<bool> vect2 {false, false, false, true};
+        vector<vector<bool>> vect{vect1, vect2};
+
+        rep.setValue(AttrName, vect);
+        static const string Expected="[[true false false true ] [false false false true ] ]";
+
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, BooleanVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<bool> vect11 {true, false, false, true};
+        vector<bool> vect12 {false, false, false, true};
+        vector<vector<bool>> vect1{vect11, vect12};
+        vector<bool> vect21 {false, true, true, false};
+        vector<bool> vect22 {true, true, true, false};
+        vector<vector<bool>> vect2{vect21, vect22};
+        vector<vector<vector<bool>>> vect{vect1, vect2};
+        rep.setValue(AttrName, vect);
+        static const std::string Expected =
+            "[[[true false false true ] [false false false true ] ]"
+            " [[false true true false ] [true true true false ] ] ]";
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, StringVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<string> vect {"s1", "s2", "s3"};
+        vector<string> vect2 {"s4", "s5", "s6"};
+        rep.setValue(AttrName, vect);
+        EXPECT_EQ("[s1 s2 s3 ]", rep.getValueToString(AttrName));
+        EXPECT_EQ("[s1 s2 s3 ]", rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, vect2);
+        EXPECT_EQ("[s4 s5 s6 ]", rep.getValueToString(AttrName));
+        EXPECT_EQ("[s4 s5 s6 ]", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, StringVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<string> vect1 {"s1", "s2", "s3"};
+        vector<string> vect2 {"s4", "s5", "s6"};
+        vector<vector<string>> vect{vect1, vect2};
+
+        rep.setValue(AttrName, vect);
+        static const string Expected="[[s1 s2 s3 ] [s4 s5 s6 ] ]";
+
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, StringVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        vector<string> vect11 {"s1", "s2", "s3"};
+        vector<string> vect12 {"s4", "s5", "s6"};
+        vector<vector<string>> vect1{vect11, vect12};
+        vector<string> vect21 {"s7", "s8"};
+        vector<string> vect22 {"s9"};
+        vector<vector<string>> vect2{vect21, vect22};
+        vector<vector<vector<string>>> vect{vect1, vect2};
+        rep.setValue(AttrName, vect);
+        static const std::string Expected =
+            "[[[s1 s2 s3 ] [s4 s5 s6 ] ]"
+            " [[s7 s8 ] [s9 ] ] ]";
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, SubRepresentationVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        OCRepresentation sub1;
+        OCRepresentation sub2;
+        vector<OCRepresentation> vect {sub1, sub2};
+        rep.setValue(AttrName, vect);
+        EXPECT_EQ("[OC::OCRepresentation OC::OCRepresentation ]", rep.getValueToString(AttrName));
+        EXPECT_EQ("[OC::OCRepresentation OC::OCRepresentation ]", rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, SubRepresentationVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        OCRepresentation sub1;
+        OCRepresentation sub2;
+        OCRepresentation sub3;
+        OCRepresentation sub4;
+        vector<OCRepresentation> vect1 {sub1, sub2};
+        vector<OCRepresentation> vect2 {sub3, sub4};
+        vector<vector<OCRepresentation>> vect{vect1, vect2};
+        rep.setValue(AttrName, vect);
+        static const string Expected = "[[OC::OCRepresentation OC::OCRepresentation ]"
+            " [OC::OCRepresentation OC::OCRepresentation ] ]";
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToString, SubRepresentationVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        OCRepresentation sub1;
+        OCRepresentation sub2;
+        OCRepresentation sub3;
+        OCRepresentation sub4;
+        OCRepresentation sub5;
+        OCRepresentation sub6;
+
+        vector<OCRepresentation> vect11 {sub1, sub2};
+        vector<OCRepresentation> vect12 {sub3, sub4};
+        vector<vector<OCRepresentation>> vect1{vect11, vect12};
+        vector<OCRepresentation> vect21 {sub5};
+        vector<OCRepresentation> vect22 {sub6};
+        vector<vector<OCRepresentation>> vect2{vect21, vect22};
+        vector<vector<vector<OCRepresentation>>> vect{vect1, vect2};
+
+        rep.setValue(AttrName, vect);
+        static const string Expected =
+            "[[[OC::OCRepresentation OC::OCRepresentation ] "
+            "[OC::OCRepresentation OC::OCRepresentation ] ] "
+            "[[OC::OCRepresentation ] [OC::OCRepresentation ] ] ]";
+        EXPECT_EQ(Expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(Expected, rep[AttrName].getValueToString());
+    }
+
+    // Subscript get/set (all types)
+    TEST(OCRepresentationSubscript, NullPtr)
+    {
+        static const std::string AttrName = "NullTest";
+        OCRepresentation rep;
+        rep[AttrName] = nullptr;
+        EXPECT_TRUE(rep.isNULL(AttrName));
+
+        std::nullptr_t repout = rep[AttrName];
+        std::nullptr_t repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(nullptr, repout);
+        EXPECT_EQ(nullptr, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, Integer)
+    {
+        static const std::string AttrName = "IntTest";
+        OCRepresentation rep;
+        int repsource = -5;
+        rep[AttrName] = repsource;
+        int repout = rep[AttrName];
+        int repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, Double)
+    {
+        static const std::string AttrName = "DoubleTest";
+        OCRepresentation rep;
+        double repsource = -5.33;
+        rep[AttrName] = repsource;
+        double repout = rep[AttrName];
+        double repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        int badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    //Disabled this test due to older GCC v4.6 fails for this test.
+    //We will enable it when we have a fix for it.
+    TEST(OCRepresentationSubscript, DISABLED_Boolean)
+    {
+        static const std::string AttrName = "BooleanTest";
+        OCRepresentation rep;
+        bool repsource = true;
+        rep[AttrName] = repsource;
+        bool repout = rep[AttrName];
+        bool repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        repsource = false;
+        rep[AttrName] = repsource;
+        repout = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+
+        int badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, String)
+    {
+        static const std::string AttrName = "StringTest";
+        OCRepresentation rep;
+        string repsource = "This is a string!";
+        rep[AttrName] = repsource;
+        string repout = rep[AttrName];
+        string repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        (void)badout;
+    }
+
+    TEST(OCRepresentationSubscript, SubRepresentation)
+    {
+        static const std::string AttrName = "SubRepresentationTest";
+        OCRepresentation rep;
+        OCRepresentation repsource;
+        repsource.setUri("This is a uri");
+
+        rep[AttrName] = repsource;
+        OCRepresentation repout = rep[AttrName];
+        OCRepresentation repout2;
+        repout2 = rep[AttrName];
+
+        //OCRepresentation doesn't overload equality, so this just compares
+        //the value we set to ensure we got the same one out;
+        EXPECT_EQ(repsource.getUri(), repout.getUri());
+        EXPECT_EQ(repsource.getUri(), repout2.getUri());
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, IntegerVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<int> repsource {1,2,3,4};
+        rep[AttrName] = repsource;
+        vector<int> repout = rep[AttrName];
+        vector<int> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, IntegerVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<int>> repsource {{1,2,3,4},{5,6,7,8}};
+        rep[AttrName] = repsource;
+        vector<vector<int>> repout = rep[AttrName];
+        vector<vector<int>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, IntegerVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<vector<int>>> repsource {{{1,2,3,4},{5,6,7,8}},{{9,10,11},{21,13}}};
+        rep[AttrName] = repsource;
+        vector<vector<vector<int>>> repout = rep[AttrName];
+        vector<vector<vector<int>>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, DoubleVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<double> repsource {1.1,2.2,3.2,4.2};
+        rep[AttrName] = repsource;
+        vector<double> repout = rep[AttrName];
+        vector<double> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, DoubleVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<double>> repsource {{1.1,2.2,3.2,4.3},{5.5,6.6,7.8,.8}};
+        rep[AttrName] = repsource;
+        vector<vector<double>> repout = rep[AttrName];
+        vector<vector<double>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, DoubleVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<vector<double>>> repsource {{{1.1,2.5,3.5,4.4},{.5,.6,7.8,8.9}},
+            {{9.8,10.8,11.8},{2.1,1.3}}};
+        rep[AttrName] = repsource;
+        vector<vector<vector<double>>> repout = rep[AttrName];
+        vector<vector<vector<double>>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, BooleanVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<bool> repsource {false, false, true};
+        rep[AttrName] = repsource;
+        vector<bool> repout = rep[AttrName];
+        vector<bool> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, BooleanVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<bool>> repsource {{true, true},{false, true}};
+        rep[AttrName] = repsource;
+        vector<vector<bool>> repout = rep[AttrName];
+        vector<vector<bool>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, BooleanVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<vector<bool>>> repsource {{{true, true, false},{true}},
+            {{true, false, false},{false, true, true}}};
+        rep[AttrName] = repsource;
+        vector<vector<vector<bool>>> repout = rep[AttrName];
+        vector<vector<vector<bool>>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, StringVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<string> repsource {"str1", "str2"};
+        rep[AttrName] = repsource;
+        vector<string> repout = rep[AttrName];
+        vector<string> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, StringVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<string>> repsource {{"str1", "str2"},{"str3", "str4"}};
+        rep[AttrName] = repsource;
+        vector<vector<string>> repout = rep[AttrName];
+        vector<vector<string>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, StringVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        vector<vector<vector<string>>> repsource {{{"str1", "str2"},{"str3", "str4"}},
+            {{"str5"},{"str6"}}};
+        rep[AttrName] = repsource;
+        vector<vector<vector<string>>> repout = rep[AttrName];
+        vector<vector<vector<string>>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(repsource, repout);
+        EXPECT_EQ(repsource, repout2);
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, SubRepresentationVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        OCRepresentation inner1, inner2;
+        inner1.setUri("inner1");
+        inner2.setUri("inner2");
+        vector<OCRepresentation> repsource {inner1, inner2};
+        rep[AttrName] = repsource;
+        vector<OCRepresentation> repout = rep[AttrName];
+        vector<OCRepresentation> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(2u, repout.size());
+        EXPECT_EQ(inner1.getUri(), repout[0].getUri());
+        EXPECT_EQ(inner2.getUri(), repout[1].getUri());
+        EXPECT_EQ(2u, repout2.size());
+        EXPECT_EQ(inner1.getUri(), repout2[0].getUri());
+        EXPECT_EQ(inner2.getUri(), repout2[1].getUri());
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, SubRepresentationVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        OCRepresentation inner1, inner2, inner3, inner4;
+        inner1.setUri("inner1");
+        inner2.setUri("inner2");
+        inner3.setUri("inner3");
+        inner4.setUri("inner4");
+
+        vector<vector<OCRepresentation>> repsource {{inner1, inner2}, {inner3, inner4}};
+        rep[AttrName] = repsource;
+        vector<vector<OCRepresentation>> repout = rep[AttrName];
+        vector<vector<OCRepresentation>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(2u, repout.size());
+        EXPECT_EQ(2u, repout[0].size());
+        EXPECT_EQ(inner1.getUri(), repout[0][0].getUri());
+        EXPECT_EQ(inner2.getUri(), repout[0][1].getUri());
+        EXPECT_EQ(2u, repout.size());
+        EXPECT_EQ(2u, repout[1].size());
+        EXPECT_EQ(inner3.getUri(), repout[1][0].getUri());
+        EXPECT_EQ(inner4.getUri(), repout[1][1].getUri());
+
+        EXPECT_EQ(2u, repout2.size());
+        EXPECT_EQ(2u, repout2[0].size());
+        EXPECT_EQ(inner1.getUri(), repout2[0][0].getUri());
+        EXPECT_EQ(inner2.getUri(), repout2[0][1].getUri());
+        EXPECT_EQ(2u, repout2.size());
+        EXPECT_EQ(2u, repout2[1].size());
+        EXPECT_EQ(inner3.getUri(), repout2[1][0].getUri());
+        EXPECT_EQ(inner4.getUri(), repout2[1][1].getUri());
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationSubscript, SubRepresentationVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+        OCRepresentation inner1, inner2, inner3, inner4, inner5, inner6, inner7, inner8;
+        inner1.setUri("inner1");
+        inner2.setUri("inner2");
+        inner3.setUri("inner3");
+        inner4.setUri("inner4");
+        inner5.setUri("inner5");
+        inner6.setUri("inner6");
+        inner7.setUri("inner7");
+        inner8.setUri("inner8");
+
+        vector<vector<vector<OCRepresentation>>> repsource
+            {{{inner1, inner2},{inner3, inner4}},{{inner5, inner6},{inner7,inner8}}};
+
+        rep[AttrName] = repsource;
+        vector<vector<vector<OCRepresentation>>> repout = rep[AttrName];
+        vector<vector<vector<OCRepresentation>>> repout2;
+        repout2 = rep[AttrName];
+
+        EXPECT_EQ(2u, repout.size());
+        EXPECT_EQ(2u, repout[0].size());
+        EXPECT_EQ(2u, repout[0][0].size());
+        EXPECT_EQ(inner1.getUri(), repout[0][0][0].getUri());
+        EXPECT_EQ(inner2.getUri(), repout[0][0][1].getUri());
+        EXPECT_EQ(2u, repout[0][1].size());
+        EXPECT_EQ(inner3.getUri(), repout[0][1][0].getUri());
+        EXPECT_EQ(inner4.getUri(), repout[0][1][1].getUri());
+        EXPECT_EQ(2u, repout[1].size());
+        EXPECT_EQ(2u, repout[1][0].size());
+        EXPECT_EQ(inner5.getUri(), repout[1][0][0].getUri());
+        EXPECT_EQ(inner6.getUri(), repout[1][0][1].getUri());
+        EXPECT_EQ(2u, repout[1][1].size());
+        EXPECT_EQ(inner7.getUri(), repout[1][1][0].getUri());
+        EXPECT_EQ(inner8.getUri(), repout[1][1][1].getUri());
+
+        EXPECT_EQ(2u, repout2.size());
+        EXPECT_EQ(2u, repout2[0].size());
+        EXPECT_EQ(2u, repout2[0][0].size());
+        EXPECT_EQ(inner1.getUri(), repout2[0][0][0].getUri());
+        EXPECT_EQ(inner2.getUri(), repout2[0][0][1].getUri());
+        EXPECT_EQ(2u, repout[0][1].size());
+        EXPECT_EQ(inner3.getUri(), repout2[0][1][0].getUri());
+        EXPECT_EQ(inner4.getUri(), repout2[0][1][1].getUri());
+        EXPECT_EQ(2u, repout[1].size());
+        EXPECT_EQ(2u, repout[1][0].size());
+        EXPECT_EQ(inner5.getUri(), repout2[1][0][0].getUri());
+        EXPECT_EQ(inner6.getUri(), repout2[1][0][1].getUri());
+        EXPECT_EQ(2u, repout[1][1].size());
+        EXPECT_EQ(inner7.getUri(), repout2[1][1][0].getUri());
+        EXPECT_EQ(inner8.getUri(), repout2[1][1][1].getUri());
+
+        double badout;
+        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        string badoutstr;
+        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        (void)badout;
+        (void)badoutstr;
+    }
+
+    TEST(OCRepresentationIterator, constiterator)
+    {
+        OCRepresentation rep;
+
+        EXPECT_TRUE(rep.empty());
+        rep.setValue("int", 8);
+        EXPECT_FALSE(rep.empty());
+        rep.setValue("double", 8.8);
+        rep.setValue("bool", true);
+        rep.setValue("string", std::string("this is a string"));
+
+        EXPECT_EQ(4u, rep.size());
+        EXPECT_FALSE(rep.empty());
+
+        OCRepresentation::const_iterator itr = rep.cbegin();
+        OCRepresentation::const_iterator endItr = rep.cend();
+        for(;itr!=endItr;++itr);
+
+        const OCRepresentation& rep2(rep);
+        OCRepresentation::const_iterator itr2 = rep2.begin();
+        OCRepresentation::const_iterator endItr2 = rep2.end();
+        for(;itr2!=endItr2;++itr2);
+
+    }
+
+    TEST(OCRepresentationIterator, constautoiterator)
+    {
+        OCRepresentation rep;
+
+        EXPECT_TRUE(rep.empty());
+        rep.setValue("int", 8);
+        EXPECT_FALSE(rep.empty());
+        rep.setValue("double", 8.8);
+        rep.setValue("bool", true);
+        rep.setValue("string", std::string("this is a string"));
+
+        EXPECT_EQ(4u, rep.size());
+        EXPECT_FALSE(rep.empty());
+
+        for(const auto& a : rep)
+        {
+            (void)a;
+        }
+
+        const OCRepresentation& rep2(rep);
+        for(const auto& a : rep2)
+        {
+            (void)a;
+        }
+    }
+    TEST(OCRepresentationIterator, autoiterator)
+    {
+        OCRepresentation rep;
+
+        EXPECT_TRUE(rep.empty());
+        rep.setValue("int", 8);
+        EXPECT_FALSE(rep.empty());
+        rep.setValue("double", 8.8);
+        rep.setValue("bool", true);
+        rep.setValue("string", std::string("this is a string"));
+
+        EXPECT_EQ(4u, rep.size());
+        EXPECT_FALSE(rep.empty());
+
+        for(auto& cur : rep)
+        {
+            if(cur.attrname() == "int")
+            {
+                EXPECT_EQ("int", cur.attrname());
+                EXPECT_EQ(AttributeType::Integer, cur.type());
+                EXPECT_EQ(AttributeType::Integer, cur.base_type());
+                EXPECT_EQ(0u, cur.depth());
+                int curInt = cur.getValue<int>();
+                EXPECT_EQ(8, curInt);
+            }
+            if(cur.attrname() == "double")
+            {
+                EXPECT_EQ("double", cur.attrname());
+                EXPECT_EQ(AttributeType::Double, cur.type());
+                EXPECT_EQ(AttributeType::Double, cur.base_type());
+                EXPECT_EQ(0u, cur.depth());
+                double curDouble = cur.getValue<double>();
+                EXPECT_EQ(8.8, curDouble);
+            }
+            if(cur.attrname() == "bool")
+            {
+                EXPECT_EQ("bool", cur.attrname());
+                EXPECT_EQ(AttributeType::Boolean, cur.type());
+                EXPECT_EQ(AttributeType::Boolean, cur.base_type());
+                EXPECT_EQ(0u, cur.depth());
+                bool curBool = cur.getValue<bool>();
+                EXPECT_EQ(true, curBool);
+            }
+            if(cur.attrname() == "string")
+            {
+                EXPECT_EQ("string", cur.attrname());
+                EXPECT_EQ(AttributeType::String, cur.type());
+                EXPECT_EQ(AttributeType::String, cur.base_type());
+                EXPECT_EQ(0u, cur.depth());
+                string curStr = cur.getValue<string>();
+                EXPECT_EQ("this is a string", curStr);
+            }
+        }
+    }
+    // Iterator usage
+    TEST(OCRepresentationIterator, iterator)
+    {
+        OCRepresentation rep;
+        OCRepresentation sub1;
+        sub1.setUri("sub rep1 URI");
+        OCRepresentation sub2;
+        sub2.setUri("sub rep2 URI");
+        OCRepresentation sub3;
+        sub3.setUri("sub rep3 URI");
+        OCRepresentation sub4;
+        sub4.setUri("sub rep4 URI");
+        OCRepresentation sub5;
+        sub5.setUri("sub rep5 URI");
+        OCRepresentation sub6;
+        sub6.setUri("sub rep6 URI");
+
+
+        EXPECT_TRUE(rep.empty());
+        rep.setValue("int", 8);
+        EXPECT_FALSE(rep.empty());
+        rep.setValue("double", 8.8);
+        rep.setValue("bool", true);
+        rep.setValue("string", std::string("this is a string"));
+        rep.setValue("rep", sub1);
+
+        vector<int> intv {1,2,3,4};
+        rep.setValue("intv", intv);
+        vector<double> doublev {1.1,2.2,3.3,4.4};
+        rep.setValue("doublev", doublev);
+        vector<bool> boolv{false, false, true};
+        rep.setValue("boolv", boolv);
+        vector<string> strv{"abc", "def", "ghi"};
+        rep.setValue("strv", strv);
+        vector<OCRepresentation> repv { sub1, sub2 };
+        rep.setValue("repv", repv);
+
+        vector<vector<int>> intvv{{1,2,3},{4,5,6}};
+        rep.setValue("intvv", intvv);
+        vector<vector<vector<int>>> intvvv{{{1,2},{3,4}},{{5,6},{8,7}}};
+        rep.setValue("intvvv", intvvv);
+
+        vector<vector<double>> doublevv{{1.1,2.1,3},{4.4,5.4,6.4}};
+        rep.setValue("doublevv", doublevv);
+        vector<vector<vector<double>>> doublevvv{{{1.1,2.1},{3.1,4.1}},{{5.1,6.1},{8.1,7.1}}};
+        rep.setValue("doublevvv", doublevvv);
+
+        vector<vector<bool>> boolvv{{false, true},{true, false}};
+        rep.setValue("boolvv", boolvv);
+        vector<vector<vector<bool>>> boolvvv{{{true, false},{true}},{{false},{true}}};
+        rep.setValue("boolvvv", boolvvv);
+
+        vector<vector<string>> strvv{{"abc", "def"},{"wer", "qwer"}};
+        rep.setValue("strvv", strvv);
+        vector<vector<vector<string>>> strvvv{{{"wqr", "xcv"},{"234"}},{{"we"},{"wert"}}};
+        rep.setValue("strvvv", strvvv);
+
+        vector<vector<OCRepresentation>> repvv{{sub1, sub2},{sub3, sub4}};
+        rep.setValue("repvv", repvv);
+        vector<vector<vector<OCRepresentation>>> repvvv{{{sub5},{sub6}},{{sub3},{sub2}}};
+        rep.setValue("repvvv", repvvv);
+
+        EXPECT_EQ(20u, rep.size());
+        EXPECT_FALSE(rep.empty());
+
+        OCRepresentation::iterator itr= rep.begin();
+        OCRepresentation::iterator endItr = rep.end();
+
+        for(;itr!=endItr;++itr)
+        {
+            if(itr->attrname() == "int")
+            {
+                EXPECT_EQ("int", itr->attrname());
+                EXPECT_EQ(AttributeType::Integer, itr->type());
+                EXPECT_EQ(AttributeType::Integer, itr->base_type());
+                EXPECT_EQ(0u, itr->depth());
+                int curInt = (*itr).getValue<int>();
+                EXPECT_EQ(8, curInt);
+            }
+            else if (itr->attrname() == "double")
+            {
+                EXPECT_EQ("double", itr->attrname());
+                EXPECT_EQ(AttributeType::Double, itr->type());
+                EXPECT_EQ(AttributeType::Double, itr->base_type());
+                EXPECT_EQ(0u, itr->depth());
+                double curDouble = (*itr).getValue<double>();
+                EXPECT_EQ(8.8, curDouble);
+            }
+            else if (itr->attrname() == "bool")
+            {
+                EXPECT_EQ("bool", itr->attrname());
+                EXPECT_EQ(AttributeType::Boolean, itr->type());
+                EXPECT_EQ(AttributeType::Boolean, itr->base_type());
+                EXPECT_EQ(0u, itr->depth());
+                bool curBool = (*itr).getValue<bool>();
+                EXPECT_EQ(true, curBool);
+            }
+            else if (itr->attrname() == "string")
+            {
+                EXPECT_EQ("string", itr->attrname());
+                EXPECT_EQ(AttributeType::String, itr->type());
+                EXPECT_EQ(AttributeType::String, itr->base_type());
+                EXPECT_EQ(0u, itr->depth());
+                string curString = (*itr).getValue<string>();
+                EXPECT_EQ("this is a string", curString);
+            }
+            else if (itr->attrname() == "rep")
+            {
+                EXPECT_EQ("rep", itr->attrname());
+                EXPECT_EQ(AttributeType::OCRepresentation, itr->type());
+                EXPECT_EQ(AttributeType::OCRepresentation, itr->base_type());
+                EXPECT_EQ(0u, itr->depth());
+                OCRepresentation curRep = (*itr).getValue<OCRepresentation>();
+                EXPECT_EQ(sub1.getUri(), curRep.getUri());
+            }
+            else if (itr->attrname() == "intv")
+            {
+                EXPECT_EQ("intv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Integer, itr->base_type());
+                EXPECT_EQ(1u, itr->depth());
+                vector<int> curv = (*itr).getValue<vector<int>>();
+                EXPECT_EQ(intv, curv);
+            }
+            else if (itr->attrname() == "doublev")
+            {
+                EXPECT_EQ("doublev", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Double, itr->base_type());
+                EXPECT_EQ(1u, itr->depth());
+                vector<double> curv = (*itr).getValue<vector<double>>();
+                EXPECT_EQ(doublev, curv);
+            }
+            else if (itr->attrname() == "boolv")
+            {
+                EXPECT_EQ("boolv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Boolean, itr->base_type());
+                EXPECT_EQ(1u, itr->depth());
+                vector<bool> curv = (*itr).getValue<vector<bool>>();
+                EXPECT_EQ(boolv, curv);
+            }
+            else if (itr->attrname() == "strv")
+            {
+                EXPECT_EQ("strv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::String, itr->base_type());
+                EXPECT_EQ(1u, itr->depth());
+                vector<string> curv = (*itr).getValue<vector<string>>();
+                EXPECT_EQ(strv, curv);
+            }
+            else if (itr->attrname() == "repv")
+            {
+                EXPECT_EQ("repv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::OCRepresentation, itr->base_type());
+                EXPECT_EQ(1u, itr->depth());
+                vector<OCRepresentation> curv = (*itr).getValue<vector<OCRepresentation>>();
+                EXPECT_EQ(2u, repv.size());
+                EXPECT_EQ(sub1.getUri(), repv[0].getUri());
+                EXPECT_EQ(sub2.getUri(), repv[1].getUri());
+            }
+            else if (itr->attrname() == "intvv")
+            {
+                EXPECT_EQ("intvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Integer, itr->base_type());
+                EXPECT_EQ(2u, itr->depth());
+                vector<vector<int>> curv = (*itr).getValue<vector<vector<int>>>();
+                EXPECT_EQ(intvv, curv);
+            }
+            else if (itr->attrname() == "intvvv")
+            {
+                EXPECT_EQ("intvvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Integer, itr->base_type());
+                EXPECT_EQ(3u, itr->depth());
+                vector<vector<vector<int>>> curv = (*itr).getValue<vector<vector<vector<int>>>>();
+                EXPECT_EQ(intvvv, curv);
+            }
+            else if (itr->attrname() == "doublevv")
+            {
+                EXPECT_EQ("doublevv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Double, itr->base_type());
+                EXPECT_EQ(2u, itr->depth());
+                vector<vector<double>> curv = (*itr).getValue<vector<vector<double>>>();
+                EXPECT_EQ(doublevv, curv);
+            }
+            else if (itr->attrname() == "doublevvv")
+            {
+                EXPECT_EQ("doublevvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Double, itr->base_type());
+                EXPECT_EQ(3u, itr->depth());
+                vector<vector<vector<double>>> curv =
+                    (*itr).getValue<vector<vector<vector<double>>>>();
+                EXPECT_EQ(doublevvv, curv);
+            }
+            else if (itr->attrname() == "boolvv")
+            {
+                EXPECT_EQ("boolvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Boolean, itr->base_type());
+                EXPECT_EQ(2u, itr->depth());
+                vector<vector<bool>> curv = (*itr).getValue<vector<vector<bool>>>();
+                EXPECT_EQ(boolvv, curv);
+            }
+            else if (itr->attrname() == "boolvvv")
+            {
+                EXPECT_EQ("boolvvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::Boolean, itr->base_type());
+                EXPECT_EQ(3u, itr->depth());
+                vector<vector<vector<bool>>> curv = (*itr).getValue<vector<vector<vector<bool>>>>();
+                EXPECT_EQ(boolvvv, curv);
+            }
+            else if (itr->attrname() == "strvv")
+            {
+                EXPECT_EQ("strvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::String, itr->base_type());
+                EXPECT_EQ(2u, itr->depth());
+                vector<vector<string>> curv = (*itr).getValue<vector<vector<string>>>();
+                EXPECT_EQ(strvv, curv);
+            }
+            else if (itr->attrname() == "strvvv")
+            {
+                EXPECT_EQ("strvvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::String, itr->base_type());
+                EXPECT_EQ(3u, itr->depth());
+                vector<vector<vector<string>>> curv =
+                    (*itr).getValue<vector<vector<vector<string>>>>();
+                EXPECT_EQ(strvvv, curv);
+            }
+            else if (itr->attrname() == "repvv")
+            {
+                EXPECT_EQ("repvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::OCRepresentation, itr->base_type());
+                EXPECT_EQ(2u, itr->depth());
+                vector<vector<OCRepresentation>> curv =
+                    (*itr).getValue<vector<vector<OCRepresentation>>>();
+                EXPECT_EQ(2u, curv.size());
+                EXPECT_EQ(2u, curv[0].size());
+                EXPECT_EQ(sub1.getUri(), curv[0][0].getUri());
+                EXPECT_EQ(sub2.getUri(), curv[0][1].getUri());
+                EXPECT_EQ(2u, curv[1].size());
+                EXPECT_EQ(sub3.getUri(), curv[1][0].getUri());
+                EXPECT_EQ(sub4.getUri(), curv[1][1].getUri());
+            }
+            else if (itr->attrname() == "repvvv")
+            {
+                EXPECT_EQ("repvvv", itr->attrname());
+                EXPECT_EQ(AttributeType::Vector, itr->type());
+                EXPECT_EQ(AttributeType::OCRepresentation, itr->base_type());
+                EXPECT_EQ(3u, itr->depth());
+                vector<vector<vector<OCRepresentation>>> curv =
+                    (*itr).getValue<vector<vector<vector<OCRepresentation>>>>();
+                EXPECT_EQ(2u, curv.size());
+                EXPECT_EQ(2u, curv[0].size());
+                EXPECT_EQ(1u, curv[0][0].size());
+                EXPECT_EQ(sub5.getUri(), curv[0][0][0].getUri());
+                EXPECT_EQ(1u, curv[0][1].size());
+                EXPECT_EQ(sub6.getUri(), curv[0][1][0].getUri());
+                EXPECT_EQ(1u, curv[1][0].size());
+                EXPECT_EQ(sub3.getUri(), curv[1][0][0].getUri());
+                EXPECT_EQ(1u, curv[1][1].size());
+                EXPECT_EQ(sub2.getUri(), curv[1][1][0].getUri());
+            }
+            else
+            {
+                EXPECT_TRUE(false) << itr->attrname();
+            }
+        }
+    }
+}
diff --git a/resource/unittests/OCResourceResponseTest.cpp b/resource/unittests/OCResourceResponseTest.cpp
new file mode 100644 (file)
index 0000000..0768836
--- /dev/null
@@ -0,0 +1,189 @@
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <OCPlatform.h>
+#include <OCApi.h>
+#include <gtest/gtest.h>
+#include <OCResourceResponse.h>
+#include <ocserverrequest.h>
+#include <InProcServerWrapper.h>
+
+namespace PH = std::placeholders;
+namespace OCResourceResponseTest
+{
+    using namespace OC;
+    using namespace std;
+
+    TEST(ErrorCodeTest, SetGetErrorCodeValidCode)
+    {
+        OCResourceResponse response;
+        int setCode = 200;
+        EXPECT_NO_THROW(response.setErrorCode(setCode));
+        EXPECT_EQ(setCode, response.getErrorCode());
+    }
+
+    TEST(NewResourceUriTest, SetGetNewResourceUriValidUri)
+    {
+        OCResourceResponse response;
+        std::string uri = "/a/light";
+        EXPECT_NO_THROW(response.setNewResourceUri(uri));
+        EXPECT_EQ(uri, response.getNewResourceUri());
+    }
+
+    TEST(NewResourceUriTest, SetGetNewResourceUriEmpty)
+    {
+        OCResourceResponse response;
+        std::string uri = "/a/light";
+        EXPECT_NO_THROW(response.setNewResourceUri(uri));
+        EXPECT_NE("", response.getNewResourceUri());
+    }
+
+    TEST(ResposeHeaderOptionsTest, SetGetHeaderOptionsValidOption)
+    {
+        OCResourceResponse response;
+        const uint16_t API_VERSION = 2048;
+        const std::string FRIDGE_CLIENT_API_VERSION = "v.1.0";
+        HeaderOptions headerOptions;
+        HeaderOption::OCHeaderOption apiVersion(API_VERSION, FRIDGE_CLIENT_API_VERSION);
+        headerOptions.push_back(apiVersion);
+
+        EXPECT_NO_THROW(response.setHeaderOptions(headerOptions));
+        EXPECT_FALSE(headerOptions.empty());
+        EXPECT_EQ(apiVersion.getOptionID(),
+                response.getHeaderOptions()[0].getOptionID());
+        EXPECT_EQ(apiVersion.getOptionData(),
+                response.getHeaderOptions()[0].getOptionData());
+     }
+
+    TEST(ResposeHeaderOptionsTest, SetGetHeaderOptionsEmpty)
+    {
+        OCResourceResponse response;
+        HeaderOptions headerOptions;
+
+        EXPECT_NO_THROW(response.setHeaderOptions(headerOptions));
+        EXPECT_TRUE(headerOptions.empty());
+    }
+
+    TEST(RequestHandleTest, SetGetRequestHandleValidHandle)
+    {
+        char query[] = "?rt=core.light";
+        char address[] = "127.0.0.1";
+        OCResourceResponse response;
+        OCServerRequest request;
+        request.method = OC_REST_GET;
+        strncpy(request.query, query, sizeof(query));
+        request.connectivityType = CA_IPV4;
+        strncpy(request.addressInfo.IP.ipAddress, address, sizeof(query));
+        request.addressInfo.IP.port = 5364;
+        request.qos =  OC_LOW_QOS;
+        request.coapID = 0;
+        request.delayedResNeeded = 0;
+        request.secured = 0;
+
+        OCRequestHandle handle = static_cast<OCRequestHandle>(&request);
+        EXPECT_EQ(NULL, response.getRequestHandle());
+        EXPECT_NO_THROW(response.setRequestHandle(handle));
+        EXPECT_NE(static_cast<OCRequestHandle>(NULL), response.getRequestHandle());
+    }
+
+    TEST(RequestHandleTest, SetGetRequestHandleNullHandle)
+    {
+        OCResourceResponse response;
+        OCRequestHandle handle = nullptr;
+
+        EXPECT_EQ(NULL, response.getRequestHandle());
+        EXPECT_NO_THROW(response.setRequestHandle(handle));
+        EXPECT_EQ(NULL, response.getRequestHandle());
+    }
+
+    TEST(ResourceHandleTest, SetGetResourceHandleValidHandle)
+    {
+        OCResourceResponse response;
+        OCResourceHandle resHandle;
+
+        std::string resourceURI = "/a/light1";
+        std::string resourceTypeName = "core.light";
+        std::string resourceInterface = DEFAULT_INTERFACE;
+        uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+
+        EXPECT_EQ(OC_STACK_OK, OCCreateResource(&resHandle, resourceURI.c_str(),
+                resourceTypeName.c_str(), resourceInterface.c_str(), nullptr,
+                resourceProperty));
+        EXPECT_EQ(NULL, response.getResourceHandle());
+        EXPECT_NO_THROW(response.setResourceHandle(resHandle));
+        EXPECT_NE(static_cast<OCResourceHandle>(NULL), response.getResourceHandle());
+    }
+
+    TEST(ResourceHandleTest, SetGetResourceHandleNullHandle)
+    {
+        OCResourceResponse response;
+        OCResourceHandle handle = nullptr;
+
+        EXPECT_EQ(NULL, response.getResourceHandle());
+        EXPECT_NO_THROW(response.setResourceHandle(handle));
+        EXPECT_EQ(NULL, response.getResourceHandle());
+    }
+
+    TEST(ResponseResultTest, SetGetResponseResultValidInput)
+    {
+        OCResourceResponse response;
+        OCEntityHandlerResult result = OC_EH_SLOW;
+        EXPECT_NO_THROW(response.setResponseResult(result));
+        EXPECT_EQ(result, response.getResponseResult());
+    }
+
+    TEST(ResourceRepresentation, SetGetResourceRepresentationWithValidRepresentation)
+    {
+        OCResourceResponse response;
+        OCRepresentation lightRepresentation;
+        const std::string LIGHT_RESOURCE_KEY = "light";
+        lightRepresentation.setValue(LIGHT_RESOURCE_KEY, 0);
+        EXPECT_TRUE(response.getResourceRepresentation().emptyData());
+        EXPECT_NO_THROW(response.setResourceRepresentation(lightRepresentation));
+        EXPECT_FALSE(response.getResourceRepresentation().emptyData());
+    }
+
+    TEST(ResourceRepresentation,
+            SetGetResourceRepresentationWithRepresentationAndEmptyInterface)
+    {
+        OCResourceResponse response;
+        OCRepresentation lightRepresentation;
+
+        const std::string LIGHT_RESOURCE_KEY = "light";
+        lightRepresentation.setValue(LIGHT_RESOURCE_KEY, 0);
+        EXPECT_TRUE(response.getResourceRepresentation().emptyData());
+        EXPECT_NO_THROW(response.setResourceRepresentation(lightRepresentation, ""));
+        EXPECT_FALSE(response.getResourceRepresentation().emptyData());
+    }
+
+    TEST(ResourceRepresentation,
+            SetGetResourceRepresentationWithRepresentationAndInterface)
+    {
+        OCResourceResponse response;
+        OCRepresentation lightRepresentation;
+
+        const std::string LIGHT_RESOURCE_KEY = "light";
+        lightRepresentation.setValue(LIGHT_RESOURCE_KEY, 0);
+        EXPECT_TRUE(response.getResourceRepresentation().emptyData());
+        EXPECT_NO_THROW(response.setResourceRepresentation(lightRepresentation,
+                LINK_INTERFACE));
+        EXPECT_FALSE(response.getResourceRepresentation().emptyData());
+    }
+}
diff --git a/resource/unittests/OCResourceTest.cpp b/resource/unittests/OCResourceTest.cpp
new file mode 100644 (file)
index 0000000..501857d
--- /dev/null
@@ -0,0 +1,508 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#include <OCPlatform.h>
+#include <OCApi.h>
+#include <gtest/gtest.h>
+#include <string>
+#include <map>
+
+namespace OCResourceTest
+{
+    using namespace OC;
+    // Callbacks
+    void onObserve(const HeaderOptions, const OCRepresentation&, const int&, const int&)
+    {
+    }
+
+    void onGetPut(const HeaderOptions&, const OCRepresentation& , const int eCode)
+    {
+        EXPECT_EQ(eCode, OC_STACK_OK);
+    }
+
+    void foundResource(std::shared_ptr<OCResource> )
+    {
+    }
+
+    void deleteResponse(const HeaderOptions&, const int)
+    {
+    }
+
+    //Helper method
+    OCResource::Ptr ConstructResourceObject(std::string host, std::string uri)
+    {
+        OCConnectivityType connectivityType = OC_IPV4;
+        std::vector<std::string> types = {"intel.rpost"};
+        std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
+
+        auto ret = OCPlatform::constructResourceObject(host, uri,
+                connectivityType, false, types, ifaces);
+
+        if(!ret)
+        {
+            ADD_FAILURE() << "ConstructResourceObject result was null";
+            throw std::runtime_error("ConstructResourceObject result was null");
+        }
+
+        return ret;
+    }
+
+     //Get Test
+    TEST(ConstructResourceTest, ConstructResourceObject)
+    {
+        EXPECT_ANY_THROW(ConstructResourceObject(std::string(""), std::string("")));
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetForValidUri)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->get(OC::QueryParamsMap(), &onGetPut));
+
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetForBadUri)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("", "coap://192.168.1.2:5000");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_THROW(resource->get(OC::QueryParamsMap(), &onGetPut), OC::OCException);
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithHighQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->get(OC::QueryParamsMap(), &onGetPut, QualityOfService::HighQos));
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithLowQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->get(OC::QueryParamsMap(), &onGetPut, QualityOfService::LowQos));
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithMidQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->get(OC::QueryParamsMap(), &onGetPut, QualityOfService::MidQos));
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithNaQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->get(OC::QueryParamsMap(), &onGetPut, QualityOfService::NaQos));
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithRTIFNaQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), &onGetPut,
+                        QualityOfService::NaQos));
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithNullResourceType)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_ANY_THROW(
+                resource->get(nullptr, DEFAULT_INTERFACE, QueryParamsMap(), &onGetPut,
+                        QualityOfService::NaQos));
+    }
+
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithNullResourceInterface)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_ANY_THROW(
+                resource->get("", nullptr, QueryParamsMap(), &onGetPut, QualityOfService::NaQos));
+    }
+
+    TEST(ResourceGetTest, DISABLED_ResourceGetWithTypeAndInterface)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), &onGetPut));
+    }
+
+    //Post Test
+    TEST(ResourcePostTest, DISABLED_ResourcePostValidConfiguration)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->post(rep, query, &onGetPut));
+    }
+
+    TEST(ResourcePostTest, DISABLED_ResourcePostWithNaQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->post(rep, query, &onGetPut, QualityOfService::NaQos));
+    }
+
+    TEST(ResourcePostTest, DISABLED_ResourcePostWithMidQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->post(rep, query, &onGetPut, QualityOfService::MidQos));
+    }
+
+    TEST(ResourcePostTest, DISABLED_ResourcePostWithLowQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->post(rep, query, &onGetPut, QualityOfService::LowQos));
+    }
+
+    TEST(ResourcePostTest, DISABLED_ResourcePostWithHighQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->post(rep, query, &onGetPut, QualityOfService::HighQos));
+    }
+
+    //Put Test
+    TEST(ResourcePutTest, DISABLED_ResourcePutForValid)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->put(rep, query, &onGetPut));
+    }
+
+    TEST(ResourcePutTest, DISABLED_ResourcePutWithNaQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->put(rep, query, &onGetPut, QualityOfService::NaQos));
+    }
+
+    TEST(ResourcePutTest, DISABLED_ResourcePutWithLowQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->put(rep, query, &onGetPut, QualityOfService::LowQos));
+    }
+
+    TEST(ResourcePutTest, DISABLED_ResourcePutWithMidQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->put(rep, query, &onGetPut, QualityOfService::MidQos));
+    }
+
+    TEST(ResourcePutTest, DISABLED_ResourcePutWithHighQos)
+    {
+        OCRepresentation rep;
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->put(rep, query, &onGetPut, QualityOfService::HighQos));
+    }
+
+    TEST(ResourcePutTest, DISABLED_ResourcePutWithTypeAndInterface)
+    {
+        OCRepresentation rep;
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->put("", DEFAULT_INTERFACE, rep, QueryParamsMap(), &onGetPut));
+    }
+
+    TEST(ResourcePutTest, DISABLED_ResourcePutWithNullType)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        OCRepresentation rep;
+        EXPECT_ANY_THROW(
+                resource->put(nullptr, DEFAULT_INTERFACE, rep, QueryParamsMap(), &onGetPut));
+        HeaderOptions headerOptions;
+        onGetPut(headerOptions, rep, OC_STACK_OK);
+    }
+
+    TEST(ResourcePutTest, DISABLED_ResourcePutWithNullInterface)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        OCRepresentation rep;
+        EXPECT_ANY_THROW(resource->put("", nullptr, rep, QueryParamsMap(), &onGetPut));
+    }
+
+    // Observer Test
+    TEST(ResourceObserveTest, DISABLED_ResourceObserveValidUri)
+    {
+        OCResource::Ptr resource =
+                ConstructResourceObject("coap://192.168.1.2:5000", "/Observe");
+        EXPECT_TRUE(resource != NULL);
+        QueryParamsMap query = {};
+        EXPECT_EQ(OC_STACK_OK, resource->observe(ObserveType::ObserveAll, query, &onObserve));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceObserveLoQos)
+    {
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/Observe");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::LowQos));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceObserveNaQos)
+    {
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/Observe");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::NaQos));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceObserveMidQos)
+    {
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/Observe");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::MidQos));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceObserveHighQos)
+    {
+        QueryParamsMap query = {};
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/Observe");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::HighQos));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceCancelObserveValidUri)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        QueryParamsMap query = {};
+        EXPECT_EQ(OC_STACK_OK, resource->observe(ObserveType::ObserveAll, query, &onObserve));
+        EXPECT_EQ(OC_STACK_OK, resource->cancelObserve());
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceCancelObserveWithNaQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        QueryParamsMap query = {};
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::NaQos));
+        EXPECT_EQ(OC_STACK_OK, resource->cancelObserve(QualityOfService::NaQos));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceCancelObserveWithLowQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        QueryParamsMap query = {};
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::LowQos));
+        EXPECT_EQ(OC_STACK_OK, resource->cancelObserve(QualityOfService::LowQos));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceCancelObserveWithMidQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+            QueryParamsMap query = {};
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::MidQos));
+        EXPECT_EQ(OC_STACK_OK, resource->cancelObserve(QualityOfService::MidQos));
+    }
+
+    TEST(ResourceObserveTest, DISABLED_ResourceCancelObserveWithHighQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+            QueryParamsMap query = {};
+        EXPECT_EQ(OC_STACK_OK,
+                resource->observe(ObserveType::ObserveAll, query, &onObserve,
+                        QualityOfService::HighQos));
+        EXPECT_EQ(OC_STACK_OK, resource->cancelObserve(QualityOfService::HighQos));
+    }
+
+    //DeleteResource
+    TEST(DeleteResourceTest, DISABLED_DeleteResourceValidUri)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->deleteResource(&deleteResponse));
+    }
+
+    TEST(DeleteResourceTest, DISABLED_DeleteResourceWithLowQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->deleteResource(&deleteResponse, QualityOfService::LowQos));
+    }
+
+    TEST(DeleteResourceTest, DISABLED_DeleteResourceWithMidQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->deleteResource(&deleteResponse, QualityOfService::MidQos));
+    }
+
+    TEST(DeleteResourceTest, DISABLED_DeleteResourceWithHighQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK,
+                resource->deleteResource(&deleteResponse, QualityOfService::HighQos));
+    }
+    TEST(DeleteResourceTest, DISABLED_DeleteResourceWithNaQos)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_EQ(OC_STACK_OK, resource->deleteResource(&deleteResponse, QualityOfService::NaQos));
+    }
+
+    //GetResourceInterfaces Test
+    TEST(GetResourceInterfacesTest, GetResourceInterfaces)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_TRUE(resource->getResourceInterfaces().front() == DEFAULT_INTERFACE);
+    }
+
+    //GetResourceTypes Test
+    TEST(GetResourceTypesTest, GetResourceTypes)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_TRUE(resource->getResourceTypes().front() == "intel.rpost");
+    }
+
+    // Host Test
+    TEST(HostTest, Host)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_TRUE(resource->host() == "coap://192.168.1.2:5000");
+    }
+
+    //Uri Test
+    TEST(UriTest, Uri)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_TRUE(resource->uri() == "/resource");
+    }
+
+    //ConnectivityType Test
+    TEST(ConnectivityTypeTest, ConnectivityType)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_TRUE(resource->connectivityType() == OC_IPV4);
+    }
+
+    //IsObservable Test
+    TEST(IsObservableTest, isObservable)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_FALSE(resource->isObservable());
+    }
+
+    //SID Test
+    TEST(SidTest, sid)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_TRUE(resource->sid() == "");
+    }
+
+    //UniqueIdentifier Test
+    TEST(UniqueIdentifierTest, uniqueIdentifier)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        std::ostringstream ss;
+        ss << resource->uniqueIdentifier();
+        EXPECT_TRUE(ss.str() == "/resource");
+    }
+
+    // HeaderOptions Test
+    TEST(HeaderOptionsTest, SetHeaderOptionsValidInput)
+    {
+        const uint16_t API_VERSION = 2048;
+        const uint16_t TOKEN = 3000;
+        HeaderOptions headerOptions;
+        HeaderOption::OCHeaderOption apiVersion(API_VERSION, "v.1.0");
+        HeaderOption::OCHeaderOption clientToken(TOKEN, "21ae43gf");
+        headerOptions.push_back(apiVersion);
+        headerOptions.push_back(clientToken);
+
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        EXPECT_NO_THROW(resource->setHeaderOptions(headerOptions));
+        EXPECT_NO_THROW(resource->unsetHeaderOptions());
+    }
+
+    TEST(HeaderOptionsTest, SetHeaderOptionsEmptyInput)
+    {
+        OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
+        EXPECT_TRUE(resource != NULL);
+        HeaderOptions headerOptions;
+        EXPECT_NO_THROW(resource->setHeaderOptions(headerOptions));
+        EXPECT_NO_THROW(resource->unsetHeaderOptions());
+    }
+}
+
index 0fd09ea..3794765 100644 (file)
@@ -2,26 +2,34 @@
 // NOTICE - Transition to SCONS
 //---------------------------------------------------------------------
 
-The IoTivity build system is transitioning to SCONS. Although the 
-makefiles are still available (until v1.0) and some developers are 
-still using them, they are currently no longer supported. To learn more 
-about building using SCONS see Readme.scons.txt in the repository root 
+The IoTivity build system is transitioning to SCONS. Although the
+makefiles are still available (until v1.0) and some developers are
+still using them, they are currently no longer supported. To learn more
+about building using SCONS see Readme.scons.txt in the repository root
 directory. The build steps used in continuous integration can be found
 in auto_build.sh which is also in the the repository root directory.
 
+To dynamically link with the Google Unit test library,
+add <src_dir>/extlibs/gtest/gtest-1.7.0/lib/.libs/ to LD_LIBRARY_PATH
+
 //---------------------------------------------------------------------
 
-tests.cpp contains unittests for C++ APIs. It uses Google Test for the unit
-tests.  Note that the unit tests are only to test the functionality of OCApi.h.
+The unittests folder contains unit tests for C++ APIs.
+It uses Google Test for the unit tests. Please note that the unit tests are
+only to test the functionality of public APIs.
 It is not a system or end-to-end test.
 
-Unit Test Requirements:
-
 1. To run the unit test, first build the unit tests with the following command
-   from <oic-resource>:
+   from root 'iotivity' folder:
+   scons unittests
+   NOTE: Just running 'scons' from 'iotivity' folder will build the entire stack along
+   with unit tests.
 
-   make -f buildScript.mk linux_ub_unittests
+2. Export LD_LIBRARY_PATH before running the unit tests.
+   Example:
+   export LD_LIBRARY_PATH=/home/tester/Documents/iotivity/extlibs/gtest/gtest-1.7.0/lib/.libs/
 
-2. Run the unit test by issuing the following command from <oic-resource>:
+3. Run the unit test by issuing the following command from root 'iotivity' folder:
+   ./out/<TARGET_OS>/<TARGET_ARCH>/<release/debug>/resource/unittests/unittests
+   Example: ./out/linux/x86_64/release/resource/unittests/unittests
 
-   ./unittests/tests
diff --git a/resource/unittests/SConscript b/resource/unittests/SConscript
new file mode 100644 (file)
index 0000000..cdb9ca7
--- /dev/null
@@ -0,0 +1,91 @@
+#******************************************************************
+#
+# 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
+unittests_env = env.Clone()
+
+src_dir = unittests_env.get('SRC_DIR')
+######################################################################
+# Build flags
+######################################################################
+unittests_env.PrependUnique(CPPPATH = [
+               '../include',
+               '../oc_logger/include',
+               '../csdk/stack/include',
+               '../csdk/security/include',
+               '../csdk/stack/include/internal',
+               '../csdk/connectivity/api',
+               '../csdk/ocsocket/include',
+               '../csdk/ocrandom/include',
+               '../csdk/logger/include',
+               '../../extlibs/gtest/gtest-1.7.0/include',
+               '../../extlibs/hippomocks-master/HippoMocks',
+               '../../extlibs/hippomocks-master/HippoMocksTest'
+               ])
+
+unittests_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+unittests_env.AppendUnique(LIBS = ['-lpthread'])
+unittests_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+unittests_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
+unittests_env.PrependUnique(LIBS = [
+               'oc',
+               'octbstack',
+               'oc_logger',
+               'connectivity_abstraction',
+               'coap',
+               'gtest',
+               'gtest_main'
+               ])
+
+if env.get('SECURED') == '1':
+    unittests_env.AppendUnique(LIBS = ['tinydtls'])
+
+if env.get('LOGGING'):
+       unittests_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+unittests = unittests_env.Program('unittests', ['ConstructResourceTest.cpp',
+                                                'OCPlatformTest.cpp',
+                                                'OCRepresentationTest.cpp',
+                                                'OCResourceTest.cpp',
+                                                'OCExceptionTest.cpp',
+                                                'OCResourceResponseTest.cpp',
+                                                'OCHeaderOptionTest.cpp'])
+
+Alias("unittests", [unittests])
+
+env.AppendTarget('unittests')
+if env.get('TEST') == '1':
+       target_os = env.get('TARGET_OS')
+       if target_os == 'linux':
+               out_dir = env.get('BUILD_DIR')
+               result_dir = env.get('BUILD_DIR') + '/test_out/'
+               if not os.path.isdir(result_dir):
+                       os.makedirs(result_dir)
+               unittests_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
+               unittests_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+               unittests_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
+               ut = unittests_env.Command ('ut', None,
+                [ 'valgrind --leak-check=full --xml=yes --xml-file=resource_unittests_unittests.memcheck ' + out_dir + 'resource/unittests/unittests'])
+               AlwaysBuild ('ut')
diff --git a/resource/unittests/makefile b/resource/unittests/makefile
deleted file mode 100644 (file)
index 6a05e80..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-# //******************************************************************
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-# override with `make BUILD=debug`
-# default to release build
-BUILD   := release
-PLATFORM := linux
-CXX     := g++
-
-ROOT_DIR       = ./
-
-# You must create the file "local.properties" on your local machine which contains any local paths, etc
-# local.properties should NOT be committed to repo
-include $(ROOT_DIR)/../csdk/local.properties
-
-GTEST_DIR= ../../extlibs/gtest-1.7.0
-OUT_DIR          := $(BUILD)
-
-ifeq ($(ROOT_DIR),)
-       ROOT_DIR:=$(PWD)
-endif
-
-INC_DIRS  := -I../include/
-INC_DIRS  += -I../oc_logger/include
-INC_DIRS  += -I../csdk/stack/include
-INC_DIRS  += -I../csdk/ocsocket/include
-INC_DIRS  += -I../csdk/ocrandom/include
-INC_DIRS  += -I../csdk/logger/include
-INC_DIRS  += -I../csdk/libcoap
-INC_DIRS  += -I$(GTEST_DIR)/include
-
-LIB_OC_LOGGER := ../oc_logger/lib/oc_logger.a
-
-GTEST_LIBS := $(GTEST_DIR)/lib/.libs/libgtest.a $(GTEST_DIR)/lib/.libs/libgtest_main.a 
-CXX_LIBS  := ../$(BUILD)/obj/liboc.a ../csdk/$(PLATFORM)/$(BUILD)/liboctbstack.a $(LIB_OC_LOGGER)
-CXX_LIBS  += $(GTEST_LIBS)
-
-CC_FLAGS.debug      := -g -O0 -g3 -Wall -ffunction-sections -fdata-sections \
-                        -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/$(BUILD) -DTB_LOG
-CC_FLAGS.release    := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s \
-                        -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/$(BUILD)
-
-CPPFLAGS       += $(CC_FLAGS.$(BUILD)) $(CXX_LIBS) -lpthread
-
-all: prep_dirs tests
-
-prep_dirs:
-       -mkdir -p $(OUT_DIR)
-
-tests: tests.cpp $(GTEST_LIBS)
-       $(CXX) $^ $(CPPFLAGS) -o $(OUT_DIR)/$@
-
-$(GTEST_LIBS): $(GTEST_DIR)
-       cd $(GTEST_DIR) && ./configure && make
-
-$(GTEST_DIR):
-       cd ../../extlibs && \
-       wget -q https://googletest.googlecode.com/files/gtest-1.7.0.zip && \
-       unzip gtest-1.7.0.zip
-
-.PHONY: clean
-
-clean:
-       -rm -rf release
-       -rm -rf debug
diff --git a/resource/unittests/tests.cpp b/resource/unittests/tests.cpp
deleted file mode 100644 (file)
index e299b43..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#include <iostream>
-#include <thread>
-#include <functional>
-#include <condition_variable>
-
-#include <OCPlatform.h>
-#include <OCApi.h>
-
-#include <gtest/gtest.h>
-
-namespace PH = std::placeholders;
-
-using namespace OC;
-using namespace std;
-
-// Entity handler used for register and find test
-OCEntityHandlerResult entityHandler_rf(std::shared_ptr<OCResourceRequest> request)
-{
-    return OC_EH_OK;
-}
-
-// Condition variables used for register and find
-std::mutex mutex_rf;
-std::condition_variable cv_rf;
-std::shared_ptr <OCResource> res_rf;
-
-void foundResource_rf(std::shared_ptr<OCResource> resource)
-{
-    if(resource)
-    {
-        res_rf = resource;
-        cv_rf.notify_all();
-    }
-}
-
-// Resource : Register and find test
-TEST(Resource, rf) {
-    // Create PlatformConfig object
-    PlatformConfig cfg {
-        OC::ServiceType::InProc,
-        OC::ModeType::Both,
-        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
-        0,         // Uses randomly available port
-        OC::QualityOfService::LowQos
-    };
-    OCPlatform::Configure(cfg);
-
-    std::string resourceURI = "/a/res";
-    std::string resourceTypeName = "core.res";
-    std::string resourceInterface = DEFAULT_INTERFACE;
-
-    uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
-
-    OCResourceHandle resourceHandle;
-
-    // This will internally create and register the resource.
-    if(OC_STACK_OK == OCPlatform::registerResource(
-                                    resourceHandle, resourceURI, resourceTypeName,
-                                    resourceInterface, entityHandler_rf, resourceProperty))
-    {
-        OCPlatform::findResource("","coap://224.0.1.187/oc/core?rt=core.res", foundResource_rf);
-
-        {
-            std::unique_lock<std::mutex> lk(mutex_rf);
-            cv_rf.wait(lk);
-        }
-
-        if(res_rf)
-        {
-            EXPECT_EQ(res_rf->uri(), "/a/res");
-            vector<std::string> rts = res_rf->getResourceTypes();
-            EXPECT_EQ(rts.size(), (unsigned) 1);
-            EXPECT_EQ(rts[0], "core.res");
-            vector<std::string> ifs = res_rf->getResourceInterfaces();
-            EXPECT_EQ(ifs.size(), (unsigned) 1);
-            EXPECT_EQ(ifs[0], DEFAULT_INTERFACE);
-        }
-    }
-}
-
index 5c49533..4e34cc2 100644 (file)
@@ -90,8 +90,8 @@ When write IoTivity project build script, you can get this environment as
 following:
        Import('env')
 
-You can use 'env' directly after import it. You can also clone a new environment
-and update its keys.
+You can use 'env' directly after import it(it isn't recommended). You can also
+clone a new environment and update its keys(recommended).
 
        new_env1 = Clone('env')
        new_env2 = Clone('env')
@@ -108,20 +108,19 @@ XXX is the information name, below are the extra information added by IoTivity
 common scrirpts:
 BUILD_DIR: the path of the build directory, all output are in this directory
 SRC_DIR: the path of the top directory of the source code
-OIC_UTILS: the path of oic-utilities project
 RELEASE: build type, boolean. True - release build, False - debug build
 TARGET_OS: the name of the target OS. The possible value depends on the host
        platform. Bellow is the list of host and possible target OS. (darwin means
        MAC OSX)
-               linux: linux / android / arduino / tizen
-(the line means on Linux, you can build the project for Linux/Android/Arduino/Tizen)
+               linux: linux / android / arduino / tizen (means on Linux, you can build the
+                       project for Linux/Android/Arduino/Tizen)
                windows: windows / winrt / android / arduino
                darwin: darwin / ios / android / arduino
 
-TARGET_ARCH: the target CPU arch. Its possible value depend on the target OS.
+TARGET_ARCH: the target CPU arch. Its possible value depends on the target OS.
        Bellow list the target OS and allowed CPU architecture.
-               linux: x86 / x86_64 / arm / arm64
-(above line means if the target OS is Linux, the CPU arch can be x86/x86_64/arm/arm64)
+               linux: x86 / x86_64 / arm / arm64 (means if the target OS is Linux, the CPU
+                       arch can be x86/x86_64/arm/arm64)
                android: x86 / x86_64 / armeabi / armeabi-v7a / armeabi-v7a-hard / arm64-v8a
                windows: x86 / amd64 / arm
                winrt: arm
@@ -133,9 +132,12 @@ TARGET_ARCH: the target CPU arch. Its possible value depend on the target OS.
 
 For convenience, in the common scripts, some extra functions are added.
 
-PrintTargets(): print all targets in the help information.
-AppendTarget(target): add 'target' into targets list, when use PrintTargets,
-       the 'target' will be print.
+PrintTargets(): print all target names in the help information.
+AppendTarget(name, target = None): add a target name into targets list, when use
+       PrintTargets, the target name will be print
+# @param name - the name of the target(s)(user defined name)
+# @param target - Final binary, file(s) etc genereted after build.
+
 InstallTarget(files, name): it takes the same action as AppendTarget, besides,
        it installs the 'files' to BUILD_DIR.
 
@@ -146,14 +148,40 @@ this function. 'lib' is the name of the library to import. The 'include' path
 will be auto added to the environment and the library will be built and linked
 into the final binary.
 
-CreateBin('bin', src): For Arduino, after build the program, it's required to
+CreateBin(bin, src): For Arduino, after build the program, it's required to
 be converted into specific format (e.g .hex). This function will genearate the
-required .hex (and .eep if target arch is avr) file.
+required .hex (and .eep if target arch is avr) file from 'bin'.
 
 UploadHelp(): For different board, the upload command line is different, this
 function print the recommended upload command line. You can see the recommended
 upload command line in the help information(the output of command "scons
 [options] -h")
+Functions for external library management:
+PrepareLib(libname, lib = None, path = None, script = None): Check whether a
+library exists, if not, notify user to install it or try to download the source
+code and build it
+# @param libname - the name of the library try to prepare
+# @param lib - the lib(.so, .a etc) to check (a library may include more then
+#      one lib, e.g. boost, includes boost_thread, boost_system ...
+# @param path - the path of the library building script, if it's not set,
+#                      by default, it's <src_dir>/extlibs/<libname>/
+# @param script - the building script, by default, it's 'SConscript'
+
+Download(target, url): Download source code from URL 'url' and save as 'target'.
+# @param target - the name of the source code package to be saved as
+# @param url - the URL from which to download the source code
+
+Configure(cwd, cmd): Run configure command(such as: boostrap, configure etc.
+usually it's done before build a library)
+# @param cwd - the work directory, full path or relative path to the directory
+               where the library build script in
+# @param cmd - the command to run, can be a script or system command
+
+Install_head_file(file): Install header file(s) to <src_dir>/deps/<target_os>/include
+# @param file - the head file(s) to install
+
+Install_lib(lib): Install library binaries to <src_dir>/deps/<target_os>/lib/<arch>
+# @param lib - the library binary(.so, .a etc) to install
 
 ==== Scripts Hierarchy ====
 
@@ -192,7 +220,7 @@ SConscript('sub_prj_11/SConscript')
 SConscript('sub_prj_1n/SConscript')
 
 The path is relevant to 'prj_1/SConscript'. You can also use the full path
-build_dir + 'prj_1/sub_prj_1x/SConscript', but it's not recommended.
+(build_dir + 'prj_1/sub_prj_1x/SConscript'), but it's not recommended.
 
 Above just to show a recommended way to manage subsidiary scripts. You don't
 need restrictly follow it.
@@ -203,7 +231,7 @@ After run the scripts in build_common (usally it's done at the beginning of
 SConstruct), an global environment 'env' is exported, 'env' has include the
 default configuration of the target OS and arch. 'env' is used in all projects,
 should avoid to change its keys. To avoid change 'env', usually clone 'env' and
-update it accroding to the requirement of cuurent sub project. Then specify the
+update it accroding to the requirement of current sub project. Then specify the
 target(usually binary) to build.
 
 Below is an example:
@@ -215,7 +243,7 @@ Below is an example:
 
        # Update the new enviroment, usally include add header file paths,
        # library path, libs to link and other compiler flags. This part is
-       # optional. If not present, the default configuration will be used
+       # optional.
        new_env.AppeneUnique(xxx = [ .... ])
 
        # Specify the target(application, library, object or others) to build
@@ -225,16 +253,17 @@ Below is an example:
        # If it's an important library or daemon to be published
        new_env.InstallTarget(ts, 'target_name')
 or
-       # If is't examples or test program or others will not be published
-       new_env.Alias('target_name', ts)
-       new_env.AppendTarget('target_name')
+       # If it's examples or test program or others will not be published
+       new_env.AppendTarget('target_name', ts)
 
 ==== Tips ====
-1. library order: if A lib use B lib, both A and B are linked to target T, the
-       when specify libraries, A should in front of B, otherwise there may be link
-       error.
+1. library order: if A lib use B lib, both A and B are linked to target T, when
+       specify libraries, A should in front of B, otherwise there may be link
+       error. e.g.
+               xx_env.AppendUnique(LIBS = ['A', 'B'])
+
 2. On android:
        (1)'pthread' is in libc. So don't use '-lpthread' for android
        (2)By default 'rtti' and 'exception' is disabled, to enable it, you need
        add flags '-frtti' and '-fexceptions'
-       (3)If STL is used, need link 'gnustl_static' library
+       (3)If STL is used, need link 'gnustl_shared' library
index e8d873e..a3bd70e 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
 #
@@ -6,7 +26,7 @@ Import('env')
 
 target_os = env.get('TARGET_OS')
 
-if target_os != 'arduino':
+if target_os not in ['arduino','darwin','ios']:
        # Build things manager project
        SConscript('things-manager/SConscript')
 
@@ -15,10 +35,11 @@ if target_os != 'arduino':
 
        # Build protocol plugin project
        # protocol-plugin use 'inotify', this feature isn't support by MAC OSX
-       if target_os not in ['darwin', 'ios', 'android']:
+       if target_os not in ['darwin', 'ios']:
                SConscript('protocol-plugin/SConscript')
 
        # Build notification manager project
-#      SConscript('notification-manager/SConscript')
+       SConscript('notification-manager/SConscript')
 #else:
 #      SConscript('notification-manager/SampleApp/arduino/SConscript')
+
diff --git a/service/docs/Control Manager-Programmer's guide_v0.9.0.pdf b/service/docs/Control Manager-Programmer's guide_v0.9.0.pdf
deleted file mode 100644 (file)
index 4af41b9..0000000
Binary files a/service/docs/Control Manager-Programmer's guide_v0.9.0.pdf and /dev/null differ
diff --git a/service/docs/NM Programmer_s Guide v0.9.1 for Android.pdf b/service/docs/NM Programmer_s Guide v0.9.1 for Android.pdf
new file mode 100644 (file)
index 0000000..70c66a5
Binary files /dev/null and b/service/docs/NM Programmer_s Guide v0.9.1 for Android.pdf differ
diff --git a/service/docs/NM Programmer_s Guide v0.9.1 for Linux.pdf b/service/docs/NM Programmer_s Guide v0.9.1 for Linux.pdf
new file mode 100644 (file)
index 0000000..a6e4495
Binary files /dev/null and b/service/docs/NM Programmer_s Guide v0.9.1 for Linux.pdf differ
diff --git a/service/docs/PPM - Programmer's Guide_v0.9.0.pdf b/service/docs/PPM - Programmer's Guide_v0.9.0.pdf
deleted file mode 100644 (file)
index 03cb35a..0000000
Binary files a/service/docs/PPM - Programmer's Guide_v0.9.0.pdf and /dev/null differ
diff --git a/service/docs/PPM Programmer_s Guide v0.9.1 for Android.pdf b/service/docs/PPM Programmer_s Guide v0.9.1 for Android.pdf
new file mode 100644 (file)
index 0000000..18725cf
Binary files /dev/null and b/service/docs/PPM Programmer_s Guide v0.9.1 for Android.pdf differ
diff --git a/service/docs/PPM Programmer_s Guide v0.9.1 for Linux.pdf b/service/docs/PPM Programmer_s Guide v0.9.1 for Linux.pdf
new file mode 100644 (file)
index 0000000..4bdfe40
Binary files /dev/null and b/service/docs/PPM Programmer_s Guide v0.9.1 for Linux.pdf differ
diff --git a/service/docs/PPM Programmer_s Guide v0.9.1 for Tizen.pdf b/service/docs/PPM Programmer_s Guide v0.9.1 for Tizen.pdf
new file mode 100644 (file)
index 0000000..8a62e80
Binary files /dev/null and b/service/docs/PPM Programmer_s Guide v0.9.1 for Tizen.pdf differ
diff --git a/service/docs/SSM - Programmer's guide_v0.9.0.pdf b/service/docs/SSM - Programmer's guide_v0.9.0.pdf
deleted file mode 100644 (file)
index ebf8178..0000000
Binary files a/service/docs/SSM - Programmer's guide_v0.9.0.pdf and /dev/null differ
diff --git a/service/docs/SSM Programmer_s Guide v0.9.1 for Android.pdf b/service/docs/SSM Programmer_s Guide v0.9.1 for Android.pdf
new file mode 100644 (file)
index 0000000..2d4e720
Binary files /dev/null and b/service/docs/SSM Programmer_s Guide v0.9.1 for Android.pdf differ
diff --git a/service/docs/SSM Programmer_s Guide v0.9.1 for Linux.pdf b/service/docs/SSM Programmer_s Guide v0.9.1 for Linux.pdf
new file mode 100644 (file)
index 0000000..09805c0
Binary files /dev/null and b/service/docs/SSM Programmer_s Guide v0.9.1 for Linux.pdf differ
diff --git a/service/docs/TM Programmer_s Guide v0.9.1 for Android.pdf b/service/docs/TM Programmer_s Guide v0.9.1 for Android.pdf
new file mode 100644 (file)
index 0000000..9f9d374
Binary files /dev/null and b/service/docs/TM Programmer_s Guide v0.9.1 for Android.pdf differ
diff --git a/service/docs/TM Programmer_s Guide v0.9.1 for Linux.pdf b/service/docs/TM Programmer_s Guide v0.9.1 for Linux.pdf
new file mode 100644 (file)
index 0000000..12a6641
Binary files /dev/null and b/service/docs/TM Programmer_s Guide v0.9.1 for Linux.pdf differ
diff --git a/service/docs/Things Manager - Programmer's guide_v0.9.0.pdf b/service/docs/Things Manager - Programmer's guide_v0.9.0.pdf
deleted file mode 100644 (file)
index 7d98810..0000000
Binary files a/service/docs/Things Manager - Programmer's guide_v0.9.0.pdf and /dev/null differ
diff --git a/service/notification-manager/NotificationManager/build/linux/Makefile b/service/notification-manager/NotificationManager/build/linux/Makefile
deleted file mode 100644 (file)
index d1e9288..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-VPATH = ../../src:../../src/linux:../../../SampleApp/linux/sampleConsumer:../../../SampleApp/linux/sampleProvider
-
-OCPATH = ../../../../../resource
-OCINCLUDE = $(OCPATH)/include
-STACKINCLUDE = $(OCPATH)/csdk/stack/include
-SOCKETINCLUDE = $(OCPATH)/csdk/ocsocket/include
-OCLOGGERINCLUDE = $(OCPATH)/oc_logger/include
-NOTIFICATIONINCLUDE = ../../include
-BOOSTPATH = ../../../../../boost_1_51_0
-
-CXX=g++
-CXXFLAGS = -O2 -g -Wall -fmessage-length=0 -std=c++0x -I$(NOTIFICATIONINCLUDE) -I$(OCINCLUDE) -I$(STACKINCLUDE) -I$(SOCKETINCLUDE) -I$(OCLOGGERINCLUDE) -I$(BOOSTPATH)
-
-#OBJS =         ResourceManager.o RegistrationManager.o VirtualRepresentation.o NotificationManager.o LinuxMain.o
-OBJS =  OICPlatformConfig.o HostingHandler.o HostingInterface.o ResourceManager.o RegistrationManager.o VirtualRepresentation.o NotificationManager.o main.o
-
-LIBS = $(OCPATH)/release/obj/liboc.a $(OCPATH)/csdk/linux/release/liboctbstack.a $(OCPATH)/oc_logger/lib/oc_logger.a
-
-all:   NotificationManager SampleProvider SampleConsumer
-
-NotificationManager:   $(OBJS)
-       $(CXX) -o NotificationManager $(OBJS)  $(LIBS) -pthread 
-
-SampleProvider:        SampleProvider.o
-       $(CXX) -o SampleProvider SampleProvider.o  $(LIBS) -pthread
-
-SampleConsumer:        SampleConsumer.o
-       $(CXX) -o SampleConsumer SampleConsumer.o  $(LIBS) -pthread
-
-clean:
-       rm -f $(OBJS) SampleConsumer.o SampleProvider.o NotificationManager SampleProvider SampleConsumer
diff --git a/service/notification-manager/NotificationManager/include/HostingConfig.h b/service/notification-manager/NotificationManager/include/HostingConfig.h
deleted file mode 100644 (file)
index 98a09e4..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-
-#ifndef HOSTINGCONFIG_H_
-#define HOSTINGCONFIG_H_
-
-#include "NotificationManager.h"
-
-
-enum class HostingMode
-{
-       None,
-       ManualMode,
-       AutomaticMode,
-};
-
-enum class AutomaticMethod
-{
-       None,
-       NetworkStatusChange,
-       Timer,
-       DeviceStatus
-};
-
-enum class NotifyMethod
-{
-       Frequence,
-       Equalization,
-       Granularity,
-       None
-};
-
-enum class NotifyFrequency
-{
-       OnTime,
-       Periodically,
-       None
-};
-
-
-struct HostingConfig
-{
-       HostingMode             hostingMode;
-       AutomaticMethod automaticMethod;
-       NotifyMethod            notifyMethod;
-       NotifyFrequency frequency;
-};
-
-#endif /* HOSTINGCONFIG_H_ */
diff --git a/service/notification-manager/NotificationManager/include/HostingHandler.h b/service/notification-manager/NotificationManager/include/HostingHandler.h
deleted file mode 100644 (file)
index 3f8a6fb..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * HostingHandler.h
- *
- *  Created on: 2014. 10. 15.
- *      Author: jyong2
- */
-
-#ifndef HOSTINGHANDLER_H_
-#define HOSTINGHANDLER_H_
-
-#include "NotificationManager.h"
-
-class HostingHandler
-{
-public:
-
-       static void initialize();
-       static void initialize(HostingConfig cfg);
-       static HostingHandler *getInstance();
-
-       void setHostingConfig(HostingConfig cfg);
-
-       void changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod = AutomaticMethod::None);
-       void changeAutomaticHostingMethod(AutomaticMethod autoMethod);
-       void changeNotifiyMethod(NotifyMethod notifyMethod);
-       void changeNotifyFrequencyType(NotifyFrequency notifyFrequency);
-
-private:
-
-       HostingHandler();
-       ~HostingHandler();
-
-       static HostingHandler *s_instance;
-       static mutex s_mutexForCreation;
-
-       HostingConfig hostingCfg;
-
-       static std::function< void(bool isHosting) > s_findHostingCandidate;
-       static std::function< void(std::string) > s_addExtraStr;
-       static std::function< void(std::shared_ptr< OCResource > resource) > s_startHosting;
-       static std::function< void(OCResourceHandle resourceHandle) > s_notify;
-
-       void startFindHost();
-       void onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle);
-       void onFoundCandidate(std::shared_ptr< OCResource > resource);
-
-       void runAutomaticHosting(AutomaticMethod autoMethod);
-       void stopAutomaticHosting();
-
-       void notifyFrequence(OCResourceHandle resourceHandle);
-
-};
-
-#endif /* HOSTINGHANDLER_H_ */
diff --git a/service/notification-manager/NotificationManager/include/HostingInterface.h b/service/notification-manager/NotificationManager/include/HostingInterface.h
deleted file mode 100644 (file)
index 4fb2164..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * HostingInterface.h
- *
- *  Created on: 2014. 10. 15.
- *      Author: jyong2
- */
-
-#ifndef HOSTINGINTERFACE_H_
-#define HOSTINGINTERFACE_H_
-
-#include "NotificationManager.h"
-
-using namespace OC;
-using namespace OCPlatform;
-
-class HostingInterface
-{
-
-public:
-       HostingInterface();
-       ~HostingInterface();
-
-       int setOnFoundHostingCandidate(
-                       std::function< void(std::shared_ptr< OCResource > resource) > func);
-       int setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func);
-
-       int setFindHosting(std::function< void(bool isHosting) > &func);
-       int setStartHosting(std::function< void(std::shared_ptr< OCResource > resource) > &func);
-       int setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func);
-       int setAddExtraStr(std::function< void(std::string) > &func);
-
-};
-
-#endif /* HOSTINGINTERFACE_H_ */
diff --git a/service/notification-manager/NotificationManager/include/NotificationManager.h b/service/notification-manager/NotificationManager/include/NotificationManager.h
deleted file mode 100644 (file)
index 294b12e..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef NOTIFICATIONMANAGER_H_
-#define NOTIFICATIONMANAGER_H_
-
-#include <iostream>
-#include <functional>
-#include <pthread.h>
-#include <cstdint>
-#include <memory>
-#include <string>
-#include <vector>
-#include <list>
-#include <condition_variable>
-
-#include "OICPlatformConfig.h"
-#include "HostingConfig.h"
-#include "ResourceManager.h"
-#include "RegistrationManager.h"
-#include "VirtualRepresentation.h"
-#include "HostingHandler.h"
-#include "HostingInterface.h"
-
-#include <sys/ioctl.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <unistd.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <net/if.h>
-
-#define IN
-#define OUT
-
-using namespace OC;
-using namespace OCPlatform;
-
-const std::string VIRTURL_TAG = "/virtual";
-
-class NotificationManager
-{
-
-private:
-
-    NotificationManager();
-    NotificationManager(HostingConfig cfg);
-    ~NotificationManager();
-
-    static NotificationManager *s_instance;
-    static mutex s_mutexForCreation;
-
-    int getNetInfo(IN int& sck, IN struct ifreq* item, OUT std::string& ip_addres);
-    bool scanAndGetNetworkInterface(OUT std::string& ip_addres);
-
-public:
-
-    static void initialize();
-    static void initialize(HostingConfig cfg);
-    static NotificationManager *getInstance();
-
-    void registerHostingEventListener();
-
-};
-
-#endif /* NOTIFICATIONMANAGER_H_ */
diff --git a/service/notification-manager/NotificationManager/include/OICPlatformConfig.h b/service/notification-manager/NotificationManager/include/OICPlatformConfig.h
deleted file mode 100644 (file)
index 4c4ffc8..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * OICPlatformConfig.h
- *
- *  Created on: 2014. 10. 15.
- *      Author: jyong2
- */
-
-#ifndef OICPLATFORMCONFIG_H_
-#define OICPLATFORMCONFIG_H_
-
-#include "OCApi.h"
-#include "OCPlatform.h"
-#include "OCResource.h"
-#include "OCResourceRequest.h"
-#include "OCResourceResponse.h"
-#include "ocstack.h"
-
-using namespace OC;
-using namespace OCPlatform;
-
-class OICPlatformConfig
-{
-private:
-
-       OICPlatformConfig();
-       ~OICPlatformConfig();
-
-       static OICPlatformConfig *s_instance;
-       static mutex s_mutexForCreation;
-       static PlatformConfig s_cfg;
-
-public:
-
-       void initialize();
-       static OICPlatformConfig *getInstance();
-       void setIP(std::string ipaddress);
-};
-
-#endif /* OICPLATFORMCONFIG_H_ */
diff --git a/service/notification-manager/NotificationManager/include/RegistrationManager.h b/service/notification-manager/NotificationManager/include/RegistrationManager.h
deleted file mode 100644 (file)
index 6cf39bf..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef REGISTRATIONMANAGER_H_
-#define REGISTRATIONMANAGER_H_
-
-#include "NotificationManager.h"
-
-using namespace OC;
-using namespace OCPlatform;
-
-class OICPlatformConfig;
-class VirtualRepresentation;
-
-class RegistrationManager
-{
-
-private:
-    RegistrationManager();
-    ~RegistrationManager();
-
-    static RegistrationManager *s_instance;
-    static mutex s_mutexForCreation;
-
-public:
-
-    static RegistrationManager *getInstance();
-
-    bool registerNMResource(VirtualRepresentation &resourceObject ,
-            std::shared_ptr< OCResource > resource);
-
-    int addResource();
-    int removeResource();
-    int updateResource();
-    bool unregisterResource();
-
-};
-
-#endif /* REGISTRATIONMANAGER_H_ */
diff --git a/service/notification-manager/NotificationManager/include/ResourceManager.h b/service/notification-manager/NotificationManager/include/ResourceManager.h
deleted file mode 100644 (file)
index 216d815..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef RESOURCEMANAGER_H_
-#define RESOURCEMANAGER_H_
-
-#include "NotificationManager.h"
-
-using namespace OC;
-using namespace OCPlatform;
-
-
-class OICPlatformConfig;
-class VirtualRepresentation;
-
-class ResourceManager
-{
-
-private:
-    ResourceManager();
-    ~ResourceManager();
-
-    static ResourceManager *s_instance;
-    static mutex s_mutexForCreation;
-    static std::list< VirtualRepresentation > s_resourceList;
-    static std::string s_extraStr;
-
-    void foundResourceforhosting(std::shared_ptr< OCResource > resource);
-
-    void checkResourceDBPolicy();
-    void saveResourceDB();
-
-public:
-
-       std::function< void(std::shared_ptr< OCResource > resource) > m_onFoundforHosting;
-       std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > m_onObserve;
-       std::function< void(OCResourceHandle resourceHandle) > m_notify;
-
-    static ResourceManager *getInstance();
-
-    void findNMResource(bool isHosting);
-
-    void onFoundforHostingDefault(std::shared_ptr< OCResource > resource);
-    void onObserveDefault(AttributeMap &inputAttMap, OCResourceHandle resourceHandle);
-    void notifyObserversDefault(OCResourceHandle resourceHandle);
-
-    void startHosting(std::shared_ptr< OCResource > resource);
-    void notifyObservers(OCResourceHandle resourceHandle);
-
-    VirtualRepresentation findVirtualRepresentation(std::string uri);
-    AttributeMap copyAttributeMap(AttributeMap &inputAttMap);
-    bool isEmptyAttributeMap(AttributeMap &inputAttMap);
-    void printAttributeMap(AttributeMap &inputAttMap);
-
-    void addExtraStr(std::string str);
-    std::string getExtraStr();
-};
-
-#endif /* RESOURCEMANAGER_H_ */
diff --git a/service/notification-manager/NotificationManager/include/VirtualRepresentation.h b/service/notification-manager/NotificationManager/include/VirtualRepresentation.h
deleted file mode 100644 (file)
index 7702f7f..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef VIRTUALREPRESENTATION_H_
-#define VIRTUALREPRESENTATION_H_
-
-#include "NotificationManager.h"
-
-#define SUCCESS_RESPONSE 0
-
-using namespace OC;
-using namespace OCPlatform;
-using namespace std;
-
-class ResourceManager;
-
-class VirtualRepresentation
-{
-
-private:
-    std::string m_virtualUri;
-    std::string m_originHostIP;
-    std::string m_resourceTypeName;
-    std::string m_resourceInterface;
-    uint8_t m_resourceProperty;
-
-    OCResourceHandle m_resourceHandle;
-
-    static AttributeMap s_attributeMap;
-    static std::mutex s_mutexAttributeMap;
-    static std::condition_variable s_conditionAttributeMap;
-    static bool m_isReadyAttributeMap;
-
-    int getRepresentation(OCRepresentation& oc);
-
-public:
-
-    std::string getUri();
-    std::string getHostIP();
-    std::string getResourceTypeName();
-    std::string getResourceInterface();
-    uint8_t getResourceProperty();
-    OCResourceHandle getResourceHandle();
-
-    int setUri(std::string uri);
-    int setHostIP(std::string ip);
-    int setResourceTypeName(std::string typeName);
-    int setResourceInterface(std::string interface);
-    int setResourceProperty(uint8_t property);
-    int setResourceHandle(OCResourceHandle & handle);
-
-public:
-    VirtualRepresentation();
-    virtual ~VirtualRepresentation();
-
-    std::string addVirtualTag(std::string uri);
-
-    OCEntityHandlerResult entityHandler(const std::shared_ptr<OCResourceRequest> request ,
-                       const std::shared_ptr<OCResourceResponse> response);
-    void onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep ,
-                const int eCode , const int sequenceNumber);
-
-};
-
-#endif /* VIRTUALREPRESENTATION_H_ */
diff --git a/service/notification-manager/NotificationManager/include/hosting.h b/service/notification-manager/NotificationManager/include/hosting.h
new file mode 100644 (file)
index 0000000..5a18a0a
--- /dev/null
@@ -0,0 +1,62 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _HOSTING_H_
+#define _HOSTING_H_
+
+// Standard API
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+// Iotivity Base CAPI
+#include "ocstack.h"
+#include "logger.h"
+
+//#define OC_TRANSPORT OC_ALL
+#define OC_TRANSPORT OC_IPV4
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#define HOSTING_TAG  PCF("Hosting")
+
+/**
+ * Start resource coordinator.
+ * This function will create mirrorResourceList and start to discover coordinatee candidate.
+ *
+ * @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR is returned except the case that OC_STACK_SUCCESS is returned.
+ */
+OCStackResult OICStartCoordinate();
+
+/**
+ * Stop resource coordinator.
+ * This function will stop the resource hosting and delete mirrorResourceList used.
+ *
+ * @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR is returned except the case that OC_STACK_SUCCESS is returned.
+ */
+OCStackResult OICStopCoordinate();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif //_HOSTING_H_
diff --git a/service/notification-manager/NotificationManager/src/HostingHandler.cpp b/service/notification-manager/NotificationManager/src/HostingHandler.cpp
deleted file mode 100644 (file)
index 7e45a85..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * HostingHandler.cpp
- *
- *  Created on: 2014. 10. 15.
- *      Author: jyong2
- */
-
-#include "HostingHandler.h"
-
-HostingHandler *HostingHandler::s_instance = NULL;
-mutex HostingHandler::s_mutexForCreation;
-
-std::function< void(bool isHosting) > HostingHandler::s_findHostingCandidate;
-std::function< void(std::shared_ptr< OCResource > resource) > HostingHandler::s_startHosting;
-std::function< void(OCResourceHandle resourceHandle) > HostingHandler::s_notify;
-std::function< void(std::string) > HostingHandler::s_addExtraStr;
-
-HostingHandler::HostingHandler()
-{
-
-}
-
-HostingHandler::~HostingHandler()
-{
-
-}
-
-HostingHandler *HostingHandler::getInstance()
-{
-       if(!s_instance)
-       {
-               s_mutexForCreation.lock();
-               if(!s_instance)
-               {
-                       s_instance = new HostingHandler();
-               }
-               s_mutexForCreation.unlock();
-       }
-
-       return s_instance;
-}
-
-void HostingHandler::initialize()
-{
-       // Create Hosting Handler instance
-       HostingHandler *ptr = HostingHandler::getInstance();
-
-       // Registration interface about hosting
-       HostingInterface hostingInterface;
-
-       hostingInterface.setFindHosting(ptr->s_findHostingCandidate);
-       hostingInterface.setStartHosting(ptr->s_startHosting);
-       hostingInterface.setNotifyObservers(ptr->s_notify);
-       hostingInterface.setAddExtraStr(ptr->s_addExtraStr);
-
-       hostingInterface.setOnFoundHostingCandidate(
-                       std::function< void(std::shared_ptr< OCResource > resource) >(
-                                       std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , std::placeholders::_1)));
-       hostingInterface.setOnObserve(
-                       std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
-                                       std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, std::placeholders::_2)));
-
-       ptr->s_addExtraStr("virtual");
-       ptr->startFindHost();
-}
-
-void HostingHandler::initialize(HostingConfig cfg)
-{
-       // Create Hosting Handler instance
-       HostingHandler *ptr = HostingHandler::getInstance();
-
-       // Registration interface about hosting
-       HostingInterface hostingInterface;
-
-       hostingInterface.setFindHosting(ptr->s_findHostingCandidate);
-       hostingInterface.setStartHosting(ptr->s_startHosting);
-       hostingInterface.setNotifyObservers(ptr->s_notify);
-       hostingInterface.setAddExtraStr(ptr->s_addExtraStr);
-
-       hostingInterface.setOnFoundHostingCandidate(
-                       std::function< void(std::shared_ptr< OCResource > resource) >(
-                                       std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , std::placeholders::_1)));
-       hostingInterface.setOnObserve(
-                       std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
-                                       std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, std::placeholders::_2)));
-
-       // Set Hosting Config
-       ptr->setHostingConfig(cfg);
-       ptr->changeHostingMode(ptr->hostingCfg.hostingMode);
-
-       ptr->s_addExtraStr("virtual");
-       ptr->startFindHost();
-}
-
-void HostingHandler::setHostingConfig(HostingConfig cfg)
-{
-       hostingCfg.automaticMethod      = cfg.automaticMethod;
-       hostingCfg.frequency            = cfg.frequency;
-       hostingCfg.hostingMode          = cfg.hostingMode;
-       hostingCfg.notifyMethod         = cfg.notifyMethod;
-}
-
-void HostingHandler::changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod)
-{
-       if(hostingCfg.hostingMode != hostingMode)
-       {
-               hostingCfg.hostingMode = hostingMode;
-               if(hostingCfg.hostingMode == HostingMode::AutomaticMode)
-               {
-                       runAutomaticHosting(autoMethod);
-               }
-               else
-               {
-                       stopAutomaticHosting();
-               }
-       }
-}
-
-void HostingHandler::runAutomaticHosting(AutomaticMethod autoMethod)
-{
-       // TODO Triggering from Event Listener.
-       if(hostingCfg.automaticMethod != autoMethod)
-       {
-               hostingCfg.automaticMethod = autoMethod;
-               switch(hostingCfg.automaticMethod)
-               {
-               case AutomaticMethod::None:
-                       break;
-               case AutomaticMethod::Timer:
-               case AutomaticMethod::DeviceStatus:
-               case AutomaticMethod::NetworkStatusChange:
-               default:
-                       break;
-               }
-       }
-}
-
-void HostingHandler::stopAutomaticHosting()
-{
-       if(hostingCfg.automaticMethod != AutomaticMethod::None)
-       {
-// TODO
-       }
-}
-
-void HostingHandler::changeAutomaticHostingMethod(AutomaticMethod autoMethod)
-{
-//     TODO
-}
-void HostingHandler::changeNotifiyMethod(NotifyMethod notifyMethod)
-{
-//     TODO
-}
-void HostingHandler::changeNotifyFrequencyType(NotifyFrequency notifyFrequency)
-{
-//     TODO
-}
-
-void HostingHandler::startFindHost()
-{
-       if(hostingCfg.hostingMode != HostingMode::None)
-       {
-               s_findHostingCandidate(true);
-       }
-}
-
-void HostingHandler::onFoundCandidate(std::shared_ptr< OCResource > resource)
-{
-       // TODO
-       // Condition of Hosting
-       s_startHosting(resource);
-}
-
-void HostingHandler::onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle)
-{
-
-       switch(hostingCfg.notifyMethod)
-       {
-       case NotifyMethod::None:
-               break;
-       case NotifyMethod::Equalization:
-       case NotifyMethod::Granularity:
-       case NotifyMethod::Frequence:
-       default:
-               notifyFrequence(resourceHandle);
-               break;
-       }
-}
-
-void HostingHandler::notifyFrequence(OCResourceHandle resourceHandle)
-{
-
-       switch(hostingCfg.frequency)
-       {
-       case NotifyFrequency::None:
-               break;
-       case NotifyFrequency::Periodically:
-       case NotifyFrequency::OnTime:
-       default:
-               s_notify(resourceHandle);
-               break;
-       }
-}
diff --git a/service/notification-manager/NotificationManager/src/HostingInterface.cpp b/service/notification-manager/NotificationManager/src/HostingInterface.cpp
deleted file mode 100644 (file)
index 61c9d60..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * HostingInterface.cpp
- *
- *  Created on: 2014. 10. 15.
- *      Author: jyong2
- */
-
-#include "HostingInterface.h"
-
-HostingInterface::HostingInterface()
-{
-
-}
-
-HostingInterface::~HostingInterface()
-{
-       // TODO Auto-generated destructor stub
-}
-
-int HostingInterface::setOnFoundHostingCandidate(
-        std::function< void(std::shared_ptr< OCResource > resource) > func)
-{
-    if(func != NULL)
-    {
-        try
-        {
-               ResourceManager::getInstance()->m_onFoundforHosting = func;
-        }
-        catch(exception &e)
-        {
-            return false;
-        }
-    }
-    else
-    {
-        ResourceManager::getInstance()->m_onFoundforHosting = std::function<
-                void(std::shared_ptr< OCResource > resource) >(
-                std::bind(&ResourceManager::onFoundforHostingDefault , ResourceManager::getInstance() ,
-                        std::placeholders::_1));
-    }
-
-    return true;
-}
-
-int HostingInterface::setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func)
-{
-    if(func != NULL)
-    {
-        try
-        {
-               ResourceManager::getInstance()->m_onObserve = func;
-        }
-        catch(exception &e)
-        {
-            return false;
-        }
-    }
-    else
-    {
-       ResourceManager::getInstance()->m_onObserve = std::function<
-                       void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
-                       std::bind(&ResourceManager::onObserveDefault , ResourceManager::getInstance() ,
-                               std::placeholders::_1, std::placeholders::_2));
-    }
-
-    return true;
-}
-
-int HostingInterface::setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func)
-{
-       try
-       {
-               func = std::function< void(OCResourceHandle resourceHandle) >(
-                               std::bind(&ResourceManager::notifyObservers , ResourceManager::getInstance() ,
-                                               std::placeholders::_1));
-       }
-       catch(exception &e)
-       {
-               return false;
-       }
-
-       return true;
-}
-
-int HostingInterface::setStartHosting(
-        std::function< void(std::shared_ptr< OCResource > resource) > &func)
-{
-    try
-    {
-        func = std::function< void(std::shared_ptr< OCResource > resource) >(
-                std::bind(&ResourceManager::startHosting , ResourceManager::getInstance() ,
-                        std::placeholders::_1));
-    }
-    catch(exception &e)
-    {
-        return false;
-    }
-
-    return true;
-}
-
-int HostingInterface::setFindHosting(std::function< void(bool isHosting) > &func)
-{
-    try
-    {
-        func = std::function< void(bool isHosting) >(
-                       std::bind(&ResourceManager::findNMResource ,
-                                       ResourceManager::getInstance() ,
-                                               std::placeholders::_1));
-    }
-    catch(exception &e)
-    {
-        return false;
-    }
-
-    return true;
-}
-
-int HostingInterface::setAddExtraStr(std::function< void(std::string) > &func)
-{
-    try
-    {
-        func = std::function< void(std::string str) >(
-                std::bind(&ResourceManager::addExtraStr , ResourceManager::getInstance() ,
-                        std::placeholders::_1));
-    }
-    catch(exception &e)
-    {
-        return false;
-    }
-
-    return true;
-}
diff --git a/service/notification-manager/NotificationManager/src/NotificationManager.cpp b/service/notification-manager/NotificationManager/src/NotificationManager.cpp
deleted file mode 100644 (file)
index d03b1b9..0000000
+++ /dev/null
@@ -1,162 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "NotificationManager.h"
-
-NotificationManager *NotificationManager::s_instance = NULL;
-mutex NotificationManager::s_mutexForCreation;
-
-NotificationManager::NotificationManager()
-{
-
-}
-
-NotificationManager::NotificationManager(HostingConfig cfg)
-{
-
-}
-
-NotificationManager::~NotificationManager()
-{
-
-}
-
-void NotificationManager::initialize()
-{
-       // find local ip address
-    std::string ipAddress;
-    NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress);
-
-    // set ip address
-    OICPlatformConfig::getInstance()->setIP(ipAddress);
-
-    // initialize hosting handler
-    HostingHandler::initialize();
-}
-
-void NotificationManager::initialize(HostingConfig cfg)
-{
-       // find local ip address
-    std::string ipAddress;
-    NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress);
-
-    // set ip address
-    OICPlatformConfig::getInstance()->setIP(ipAddress);
-
-    // initialize hosting handler
-    HostingHandler::initialize(cfg);
-}
-
-void NotificationManager::registerHostingEventListener()
-{
-    // TODO : Initial HostingEventListener (v1.0)
-}
-
-NotificationManager *NotificationManager::getInstance()
-{
-       if(!s_instance)
-       {
-               s_mutexForCreation.lock();
-               if(!s_instance)
-               {
-                       s_instance = new NotificationManager();
-               }
-               s_mutexForCreation.unlock();
-       }
-
-    return s_instance;
-}
-
-int NotificationManager::getNetInfo(IN int& sck, IN struct ifreq* item, OUT std::string& ip_addres)
-{
-       struct ifreq temp_ifr;
-       memset(&temp_ifr, 0, sizeof(temp_ifr));
-       strcpy(temp_ifr.ifr_name, item->ifr_name);
-
-       if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr))
-       {
-               return -1;
-       }
-
-       if (!((temp_ifr.ifr_flags & IFF_UP) && (temp_ifr.ifr_flags & IFF_RUNNING)))
-       {
-               return -1;
-       }
-
-       std::string ip(inet_ntoa(((struct sockaddr_in *) &item->ifr_addr)->sin_addr));
-       if (ip.empty())
-       {
-               return -1;
-       }
-
-       if (ip.find("127.0.0") == 0)
-       {
-               return -1;
-       }
-
-       ip_addres = ip;
-       return 0;
-}
-
-bool NotificationManager::scanAndGetNetworkInterface(OUT std::string& ip_addres)
-{
-       while(1)
-       {
-               char buf[1024] =        { 0, };
-               struct ifconf ifc;
-               struct ifreq *ifr;
-               int sck;
-               int interfaces;
-               int i;
-
-               sck = socket(AF_INET, SOCK_DGRAM, 0);
-               if (sck < 0)
-               {
-                       usleep(10);
-                       continue;
-               }
-
-               ifc.ifc_len = sizeof(buf);
-               ifc.ifc_buf = buf;
-               if (ioctl(sck, SIOCGIFCONF, &ifc) < 0)
-               {
-                       printf( "SIOCGIFCONF Failed ");
-                       close(sck);
-                       usleep(10);
-                       continue;
-               }
-
-               ifr = ifc.ifc_req;
-               interfaces = ifc.ifc_len / sizeof(struct ifreq);
-
-               for (i = 0; i < interfaces; i++)
-               {
-                       if(  getNetInfo(sck, &ifr[i], ip_addres) == 0 )
-                       {
-                               return 0;
-                       }
-                       continue;
-               }
-               close(sck);
-               usleep(10);
-       }
-
-       return 0;
-}
diff --git a/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp b/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp
deleted file mode 100644 (file)
index e9e1756..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * OICPlatformConfig.cpp
- *
- *  Created on: 2014. 10. 15.
- *      Author: jyong2
- */
-
-#include "OICPlatformConfig.h"
-
-
-OICPlatformConfig *OICPlatformConfig::s_instance = NULL;
-mutex OICPlatformConfig::s_mutexForCreation;
-//OCPlatform *OICPlatformConfig::s_nmOCPlatform = NULL;
-PlatformConfig OICPlatformConfig::s_cfg;
-//(ServiceType::InProc, ModeType::Both,"", 5683, QualityOfService::NonConfirmable);
-
-OICPlatformConfig::OICPlatformConfig()
-{
-       // TODO Auto-generated constructor stub
-
-}
-
-OICPlatformConfig::~OICPlatformConfig()
-{
-       // TODO Auto-generated destructor stub
-}
-
-
-OICPlatformConfig *OICPlatformConfig::getInstance()
-{
-       if(!s_instance)
-       {
-               s_mutexForCreation.lock();
-               if(!s_instance)
-               {
-                       s_instance = new OICPlatformConfig();
-                       Configure(s_cfg);
-               }
-               s_mutexForCreation.unlock();
-       }
-
-       return s_instance;
-}
-
-//void OICPlatformConfig::getOCPlatform()
-//{
-////   if(!s_nmOCPlatform)
-////   {
-////           if(s_cfg.ipAddress.empty())
-////           {
-////                   return NULL;
-////           }
-////           s_nmOCPlatform = new OCPlatform(s_cfg);
-////           Configure(s_cfg);
-////   }
-////   return s_nmOCPlatform;
-//}
-
-void OICPlatformConfig::initialize()
-{
-
-}
-
-void OICPlatformConfig::setIP(std::string ipaddress)
-{
-       s_cfg.ipAddress = ipaddress;
-}
diff --git a/service/notification-manager/NotificationManager/src/RegistrationManager.cpp b/service/notification-manager/NotificationManager/src/RegistrationManager.cpp
deleted file mode 100644 (file)
index 0649da6..0000000
+++ /dev/null
@@ -1,109 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "RegistrationManager.h"
-
-RegistrationManager *RegistrationManager::s_instance = NULL;
-mutex RegistrationManager::s_mutexForCreation;
-
-RegistrationManager::RegistrationManager()
-{
-}
-
-RegistrationManager::~RegistrationManager()
-{
-}
-
-RegistrationManager *RegistrationManager::getInstance()
-{
-       if(!s_instance)
-       {
-               s_mutexForCreation.lock();
-               if(s_instance)
-               {
-                       s_instance = new RegistrationManager();
-               }
-               s_mutexForCreation.unlock();
-       }
-
-       return s_instance;
-}
-
-int RegistrationManager::addResource()
-{
-    return 0;
-}
-
-int RegistrationManager::removeResource()
-{
-    return 0;
-}
-
-int RegistrationManager::updateResource()
-{
-    return 0;
-}
-
-bool RegistrationManager::registerNMResource(VirtualRepresentation &resourceObject ,
-        std::shared_ptr< OCResource > resource)
-{
-    std::string uri = resourceObject.getUri();
-    std::string type = resourceObject.getResourceTypeName();
-    std::string interface = resourceObject.getResourceInterface();
-
-    OCResourceHandle resourceHandle;
-
-    OCStackResult result;
-    result = registerResource(resourceHandle , uri , type ,
-                interface ,
-                std::function<
-                        OCEntityHandlerResult(const std::shared_ptr< OCResourceRequest > request ,
-                                const std::shared_ptr< OCResourceResponse > response) >(
-                        std::bind(&VirtualRepresentation::entityHandler , resourceObject ,
-                                       std::placeholders::_1 , std::placeholders::_2)) ,
-                resourceObject.getResourceProperty());
-
-    resourceObject.setResourceHandle(resourceHandle);
-
-    if(OC_STACK_OK != result)
-    {
-        return false;
-    }
-    else
-    {
-        QueryParamsMap queryParmaMap;
-        resource->observe(ObserveType::Observe , queryParmaMap ,
-                std::function<
-                        void(const HeaderOptions headerOption,
-                                       const OCRepresentation& rep , const int& eCode ,
-                                const int& sequenceNumber) >(
-                        std::bind(&VirtualRepresentation::onObserve , resourceObject ,
-                                std::placeholders::_1 , std::placeholders::_2 ,
-                                std::placeholders::_3 , std::placeholders::_4)));
-    }
-
-    return true;
-}
-
-bool RegistrationManager::unregisterResource()
-{
-    return true;
-}
-
diff --git a/service/notification-manager/NotificationManager/src/ResourceManager.cpp b/service/notification-manager/NotificationManager/src/ResourceManager.cpp
deleted file mode 100644 (file)
index 19fb8bd..0000000
+++ /dev/null
@@ -1,232 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "ResourceManager.h"
-
-ResourceManager *ResourceManager::s_instance = NULL;
-mutex ResourceManager::s_mutexForCreation;
-std::list< VirtualRepresentation > ResourceManager::s_resourceList;
-
-std::string ResourceManager::s_extraStr;
-
-ResourceManager::ResourceManager()
-{
-       m_onFoundforHosting     = NULL;
-       m_onObserve                     = NULL;
-       m_notify                                = NULL;
-}
-
-ResourceManager::~ResourceManager()
-{
-}
-
-ResourceManager *ResourceManager::getInstance()
-{
-    if(!s_instance)
-    {
-        s_mutexForCreation.lock();
-        if(!s_instance)
-        {
-               s_instance = new ResourceManager();
-        }
-        s_mutexForCreation.unlock();
-    }
-    return s_instance;
-}
-
-VirtualRepresentation ResourceManager::findVirtualRepresentation(std::string uri)
-{
-
-    VirtualRepresentation retObject;
-
-    for(auto it = s_resourceList.begin() ; it != s_resourceList.end() ; it++)
-    {
-        if(it->getUri().compare(uri) == 0)
-        {
-            retObject = *it;
-            return retObject;
-        }
-    }
-
-    return retObject;
-}
-
-void ResourceManager::findNMResource(bool isHosting)
-{
-       if(isHosting)
-       {
-               findResource("" , "coap://224.0.1.187/oc/core",
-                               std::function< void(std::shared_ptr< OCResource > resource) >(
-                                                                       std::bind(&ResourceManager::foundResourceforhosting , ResourceManager::getInstance() ,
-                                                                                       std::placeholders::_1)));
-       }
-}
-
-void ResourceManager::foundResourceforhosting(std::shared_ptr< OCResource > resource)
-{
-    try
-    {
-        if(resource)
-        {
-            if(resource->uri().find("/a/NM") != std::string::npos)
-            {
-                ResourceManager::getInstance()->m_onFoundforHosting(resource);
-            }
-        }
-        else
-        {
-               // TODO
-        }
-
-    }
-    catch(std::exception &e)
-    {
-    }
-}
-
-void ResourceManager::startHosting(std::shared_ptr< OCResource > resource)
-{
-
-       cout << "start hosting" << endl;
-    VirtualRepresentation tmp = findVirtualRepresentation( resource->uri() );
-
-    if( !tmp.getUri().empty() )
-    {
-        return;
-    }
-
-    VirtualRepresentation resourceObject;
-    resourceObject.setUri(resource->uri());
-
-    std::cout << "resourceObject uri: " << resourceObject.getUri() << std::endl;
-
-    std::string resourceHostIP;
-    std::string resourceType;
-    std::string resourceInterface;
-    uint8_t resourceProperty;
-
-    resourceHostIP = resource->host();
-    resourceType = *(resource->getResourceTypes().data());
-    resourceInterface = *(resource->getResourceInterfaces().data());
-    resourceProperty = (OC_DISCOVERABLE | resource->isObservable());
-
-    resourceObject.setHostIP(resourceHostIP);
-    resourceObject.setResourceTypeName(resourceType);
-    resourceObject.setResourceInterface(resourceInterface);
-    resourceObject.setResourceProperty(resourceProperty);
-
-    RegistrationManager::getInstance()->registerNMResource(resourceObject , resource);
-
-    s_resourceList.push_back(resourceObject);
-
-}
-
-void ResourceManager::notifyObservers(OCResourceHandle resourceHandle)
-{
-       OCStackResult result = OC_STACK_OK;
-
-       result = notifyAllObservers(resourceHandle);
-
-       if(OC_STACK_NO_OBSERVERS == result)
-       {
-               // No observers.
-               // TODO
-       }
-}
-
-AttributeMap ResourceManager::copyAttributeMap(AttributeMap &inputAttMap)
-{
-
-    AttributeMap retAttMap;
-
-    retAttMap = inputAttMap;
-//    for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it)
-//    {
-//        AttributeValues tmpVal;
-//
-//        for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
-//        {
-//            std::string tmpStr;
-//
-//            tmpStr.append(*valueItr);
-//
-//            tmpVal.push_back(tmpStr);
-//        }
-//        retAttMap[it->first] = tmpVal;
-//
-//    }
-    return retAttMap;
-}
-
-bool ResourceManager::isEmptyAttributeMap(AttributeMap &inputAttMap)
-{
-    for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it)
-    {
-        if(inputAttMap.find(it->first) == inputAttMap.end())
-        {
-            return true;
-        }
-    }
-    return false;
-}
-
-void ResourceManager::onFoundforHostingDefault(std::shared_ptr< OCResource > resource)
-{
-    ResourceManager::getInstance()->startHosting(resource);
-}
-void ResourceManager::onObserveDefault(AttributeMap &inputAttMap , OCResourceHandle resourceHandle)
-{
-       ResourceManager::getInstance()->notifyObservers(resourceHandle);
-}
-
-void ResourceManager::printAttributeMap(AttributeMap &inputAttMap)
-{
-    for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it)
-    {
-        std::cout << "\tAttribute name: " << it->first << " value: ";
-
-        for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
-        {
-            std::cout << "\t" << *valueItr << " ";
-        }
-
-        std::cout << std::endl;
-    }
-}
-
-void ResourceManager::addExtraStr(std::string str)
-{
-    s_extraStr = str;
-}
-
-std::string ResourceManager::getExtraStr()
-{
-    return s_extraStr;
-}
-
-void ResourceManager::checkResourceDBPolicy()
-{
-
-}
-
-void ResourceManager::saveResourceDB()
-{
-
-}
diff --git a/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp b/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp
deleted file mode 100644 (file)
index 4e2ce1c..0000000
+++ /dev/null
@@ -1,247 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "VirtualRepresentation.h"
-
-AttributeMap VirtualRepresentation::s_attributeMap;
-
-std::mutex VirtualRepresentation::s_mutexAttributeMap;
-std::condition_variable VirtualRepresentation::s_conditionAttributeMap;
-bool VirtualRepresentation::m_isReadyAttributeMap = true;
-
-int g_num = 0;
-
-VirtualRepresentation::VirtualRepresentation()
-{
-    m_resourceHandle = NULL;
-    m_resourceProperty = 0x00;
-}
-
-VirtualRepresentation::~VirtualRepresentation()
-{
-}
-
-std::string VirtualRepresentation::addVirtualTag(std::string uri)
-{
-    std::string ret = uri;
-    return ret.append(VIRTURL_TAG + std::to_string(g_num++));
-}
-
-OCResourceHandle VirtualRepresentation::getResourceHandle()
-{
-    return m_resourceHandle;
-}
-
-std::string VirtualRepresentation::getUri()
-{
-    return m_virtualUri;
-}
-
-std::string VirtualRepresentation::getHostIP()
-{
-    return m_originHostIP;
-}
-
-std::string VirtualRepresentation::getResourceTypeName()
-{
-    return m_resourceTypeName;
-}
-
-std::string VirtualRepresentation::getResourceInterface()
-{
-    return m_resourceInterface;
-}
-
-uint8_t VirtualRepresentation::getResourceProperty()
-{
-    return m_resourceProperty;
-}
-
-int VirtualRepresentation::setUri(std::string uri)
-{
-    m_virtualUri = addVirtualTag(uri);
-    return true;
-}
-
-int VirtualRepresentation::setHostIP(std::string ip)
-{
-    m_originHostIP = ip;
-    return true;
-}
-
-int VirtualRepresentation::setResourceTypeName(std::string typeName)
-{
-    m_resourceTypeName = typeName;
-    return true;
-}
-
-int VirtualRepresentation::setResourceInterface(std::string interface)
-{
-    m_resourceInterface = interface;
-    return true;
-}
-
-int VirtualRepresentation::setResourceProperty(uint8_t property)
-{
-    m_resourceProperty = property;
-    return true;
-}
-
-int VirtualRepresentation::setResourceHandle(OCResourceHandle & handle)
-{
-    m_resourceHandle = handle;
-    return true;
-}
-
-int VirtualRepresentation::getRepresentation(OCRepresentation& oc)
-{
-    oc.setAttributeMap(s_attributeMap);
-    oc.setUri(this->getUri().c_str());
-    return true;
-}
-
-OCEntityHandlerResult VirtualRepresentation::entityHandler(const std::shared_ptr<OCResourceRequest> request ,
-               const std::shared_ptr<OCResourceResponse> response)
-{
-    if(request)
-    {
-        std::string requestType = request->getRequestType();
-        int requestFlag = request->getRequestHandlerFlag();
-
-        if(requestFlag == RequestHandlerFlag::InitFlag)
-               {
-               }
-
-        else if(requestFlag == RequestHandlerFlag::RequestFlag)
-        {
-            if( (requestType == "GET") && response )
-            {
-
-                               std::unique_lock< std::mutex > lck(s_mutexAttributeMap);
-                               while(!m_isReadyAttributeMap)
-                               {
-                                       s_conditionAttributeMap.wait(lck);
-                               }
-                               m_isReadyAttributeMap = false;
-
-                               OCRepresentation rep;
-                               getRepresentation(rep);
-
-                               response->setErrorCode(200);
-                               response->setResourceRepresentation(rep , DEFAULT_INTERFACE);
-
-                               m_isReadyAttributeMap = true;
-                               s_conditionAttributeMap.notify_all();
-                       }
-            else if(requestType == "PUT")
-            {
-               // TODO
-            }
-            else if(requestType == "POST")
-            {
-               // TODO
-            }
-            else if(requestType == "DELETE")
-            {
-               // TODO
-            }
-            else
-            {
-               // TODO
-            }
-        }
-        else if(requestFlag == RequestHandlerFlag::InitFlag)
-               {
-                       // TODO
-               }
-        else if(requestFlag == RequestHandlerFlag::ObserverFlag)
-        {
-               // TODO
-               cout << "requestFlag == RequestHandlerFlag::ObserverFlag\n";
-        }
-        else
-        {
-               // requestFlag is not [Request, Init, Observer]
-               // TODO
-        }
-    }
-    else
-    {
-       // Param(request) is empty.
-       // TODO
-    }
-    return OC_EH_OK;
-}
-
-void VirtualRepresentation::onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep , const int eCode , const int sequenceNumber)
-{
-       cout << "VirtualRepresentation::onObserve Enter\n";
-    if(eCode == SUCCESS_RESPONSE)
-    {
-       cout << "1\n";
-        AttributeMap inputAttributeMap = rep.getAttributeMap();
-
-        if(ResourceManager::getInstance()->isEmptyAttributeMap(inputAttributeMap))
-        {
-               cout << "2\n";
-            return;
-        }
-        cout << "3\n";
-        VirtualRepresentation tmpObj = *this;
-        if(!tmpObj.getUri().empty())
-        {
-               cout << "4\n";
-            AttributeMap tmpAttMap = ResourceManager::getInstance()->copyAttributeMap(inputAttributeMap);
-            cout << "5\n";
-            {
-               cout << "6\n";
-                std::unique_lock< std::mutex > lck(s_mutexAttributeMap);
-                cout << "7\n";
-                while(!m_isReadyAttributeMap)
-                {
-                       cout << "8\n";
-                    s_conditionAttributeMap.wait(lck);
-                }
-                cout << "9\n";
-                m_isReadyAttributeMap = false;
-                cout << "10\n";
-                s_attributeMap = tmpAttMap;
-                cout << "11\n";
-                m_isReadyAttributeMap = true;
-                cout << "12\n";
-                s_conditionAttributeMap.notify_all();
-                cout << "13\n";
-            }
-
-            if(ResourceManager::getInstance()->m_onObserve)
-                       {
-               cout << "14\n";
-                               ResourceManager::getInstance()->m_onObserve(inputAttributeMap, tmpObj.getResourceHandle());
-                               cout << "15\n";
-                       }
-        }
-    }
-    else
-    {
-       // Check the error.
-       // TODO
-    }
-    cout << "VirtualRepresentation::onObserve Out\n";
-}
diff --git a/service/notification-manager/NotificationManager/src/hosting.c b/service/notification-manager/NotificationManager/src/hosting.c
new file mode 100644 (file)
index 0000000..dc74925
--- /dev/null
@@ -0,0 +1,1550 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Hosting Header
+#include "hosting.h"
+#include "virtualResource.h"
+
+// External Lib
+#include "cJSON.h"
+
+/*
+ * internal function & static variable
+ */
+///////////////////////////////////////////////////////////////////////////////////////////////////
+static MirrorResourceList *s_mirrorResourceList = NULL;
+static RequestHandleList *s_requestHandleList = NULL;
+
+#define OIC_COORDINATING_FLAG "/hosting"
+#define OIC_STRING_MAX_VALUE 100
+
+#define OC_DEFAULT_ADDRESS               "224.0.1.187"
+#define OC_WELL_KNOWN_COORDINATING_QUERY "coap://224.0.1.187:5683/oc/core?rt=Resource.Hosting"
+#define OC_COORDINATING_QUERY            "/oc/core?rt=Resource.Hosting"
+#define DEFAULT_CONTEXT_VALUE 0x99
+
+/*
+ * Presence Func for hosting
+ */
+
+/**
+ *
+ * request presence for coordinating
+ *
+ * @param[in] originResourceAddr - pointer of address string of original resource
+ *
+ * @return
+ *     OC_STACK_OK
+ *     OC_STACK_ERROR
+ */
+OCStackResult requestPresence(char *originResourceAddr);
+
+/**
+ *
+ * callback function that call when response of presence request received
+ *
+ * @param[in] originResourceAddr - pointer of address string of original resource
+ *
+ * @return
+ *     OC_STACK_OK
+ *     OC_STACK_ERROR
+ */
+OCStackApplicationResult requestPresenceCB(void *context, OCDoHandle handle,
+        OCClientResponse *clientResponse);
+
+/**
+ *
+ * build mirror resource list by clientResponse
+ *
+ * @param[in] handle - not using...
+ * @param[in] clientResponse - client response that mirror resources are stored
+ *
+ * @return
+ *     pointer of result MirrorResourceList
+ */
+MirrorResourceList *buildMirrorResourceList(OCDoHandle handle, OCClientResponse *clientResponse);
+
+/**
+ *
+ * build mirror resource by JSON payload
+ *
+ * @param[in] ocArray_sub - pointer of json payload string
+ *
+ * @return
+ *     pointer of result MirrorResource
+ */
+MirrorResource *buildMirrorResource(cJSON *ocArray_sub);
+
+/**
+ *
+ * This method is used when setting queryUri, registering callback function and starting OCDoResource() Function in order to find Coordinatee Candidate
+ *
+ * @brief discover coordinatee candidate
+ *
+ * @return
+ *     OC_STACK_OK               - no errors
+ *     OC_STACK_INVALID_CALLBACK - invalid callback function pointer
+ *     OC_STACK_INVALID_METHOD   - invalid resource method
+ *     OC_STACK_INVALID_URI      - invalid required or reference URI
+ *     OC_STACK_INVALID_QUERY    - number of resource types specified for filtering presence
+ *                                 notifications exceeds @ref MAX_PRESENCE_FILTERS.
+ *     OC_STACK_ERROR            - otherwise error(initialized value)
+ */
+int requestCoordinateeCandidateDiscovery(char *address);
+
+/**
+ *
+ * This method is used to add a coordinator resource callback method in mirrorResourceList when host resource discovered.
+ *
+ * @param[in] context
+ *              Context for callback method
+ * @param[in] handle
+ *              Handle to an @ref OCDoResource invocation.
+ * @param[in] clientResponse
+ *              Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
+ *
+ * @brief callback for receiving response of discoverCoordinateeCandidate()
+ *
+ * @return
+ *     PRINT("Callback Context for DISCOVER query recvd successfully")      - context is DEFAULT_CONTEXT_VALUE
+ *     call the buildMirrorResource() method                                    - clientResponse is not NULL && clientResponse->result is OC_STACK_OK
+ *     OC_STACK_KEEP_TRANSACTION                                                - otherwise case
+ */
+OCStackApplicationResult requestCoordinateeCandidateDiscoveryCB(void *context, OCDoHandle handle,
+        OCClientResponse *clientResponse);
+
+/**
+ *
+ * This method is used when setting queryUri, registering callback function and starting OCDoResource() Function in order to request resource coordination
+ *
+ * @brief
+ *
+ * @param[in] mirrorResource
+ *          mirrorResource for using in order to request resource coordination
+ *
+ * @return
+ *     OC_STACK_OK               - no errors
+ *     OC_STACK_INVALID_CALLBACK - invalid callback function pointer
+ *     OC_STACK_INVALID_METHOD   - invalid resource method
+ *     OC_STACK_INVALID_URI      - invalid required or reference URI
+ *     OC_STACK_INVALID_QUERY    - number of resource types specified for filtering presence
+ *                                 notifications exceeds @ref MAX_PRESENCE_FILTERS.
+ *     OC_STACK_ERROR            - otherwise error(initialized value)
+ */
+OCStackResult requestResourceObservation(MirrorResource *mirrorResource);
+
+/**
+ *
+ * This method is used to handle callback of requestCoordination method.
+ *
+ * @param[in] context
+ *              Context for callback method
+ * @param[in] handle
+ *              Handle to update mirror resource and check errorResponse
+ * @param[in] clientResponse
+ *              Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
+ *
+ * @brief callback when receiving response of coordinating requestion.
+ *
+ * @todo diverge return value
+ *
+ * @return
+ *
+ *     OC_STACK_KEEP_TRANSACTION                                            - otherwise case
+ */
+OCStackApplicationResult requestResourceObservationCB(void *context, OCDoHandle handle,
+        OCClientResponse *clientResponse);
+
+/**
+ *
+ * This method is used to check resource validation and delete resource if it is not exist(not alive).
+ *
+ * @brief check mirror resource is alive
+ *
+ * @param[in] requestHandle
+ *              Handle to check mirror resource
+ *
+ * @return
+ *
+ *     OC_STACK_DELETE_TRANSACTION                                              - otherwise case
+ */
+OCStackApplicationResult checkResourceValidation(OCDoHandle requestHandle);
+
+/**
+ *
+ * register Mirror resource in the base resource list
+ *
+ * @param[in] requestHandle
+ *              Handle to check mirror resource
+ *
+ * @return
+ *     OC_STACK_OK
+ *     OC_STACK_ERROR
+ */
+OCStackResult registerMirrorResource(MirrorResource *node);
+
+/**
+ *
+ * update resource
+ *
+ * @param[in] sourceHandle - handle of source resource
+ * @param[in] payload - pointer of json payload string that update items stored
+ *
+ * @return
+ *     pointer of mirror resource. return NULL if there is any error.
+ */
+MirrorResource *updateMirrorResource(OCDoHandle sourceHandle, const char *payload);
+
+/**
+ *
+ * build response payload
+ *
+ * @param[in] ehRequest - pointer of handler of entity handler request that to be responded
+ *
+ * @return
+ *     OC_STACK_OK
+ *     OC_STACK_ERROR
+ */
+char *buildResponsePayload (OCEntityHandlerRequest *ehRequest);
+
+/**
+ *
+ * handle "Get" request
+ *
+ * @param[in] ehRequest - pointer of handler of entity handler request
+ * @param[out] payload - pointer of payload to be responded
+ * @param[in] maxPayloadSize - size of payload
+ *
+ * @return
+ *     OC_EH_OK - success to copy response payload
+ *     OC_EH_ERROR - error to copy response payload
+ */
+OCEntityHandlerResult handleGetRequest (OCEntityHandlerRequest *ehRequest,
+                                        char *payload, uint16_t maxPayloadSize);
+
+/**
+ *
+ * handle request for non-existing resource
+ *
+ * @param[in] ehRequest - pointer of handler of entity handler request
+ * @param[out] payload - pointer of payload to be responded
+ * @param[in] maxPayloadSize - size of payload
+ *
+ * @return
+ *     OC_EH_RESOURCE_DELETED - resource deleted
+ */
+OCEntityHandlerResult handleNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
+        char *payload, uint16_t maxPayloadSize);
+
+/**
+ *
+ * callback function that called when source resource changed
+ *
+ * @param[in] flag - entity handler flag
+ * @param[in] entityHandlerRequest - pointer of entity handler request
+ *
+ * @return
+ *     OC_EH_OK
+ *     OC_EH_ERROR
+ */
+OCEntityHandlerResult resourceEntityHandlerCB (OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest *entityHandlerRequest);
+
+/**
+ *
+ * request that address is alive
+ *
+ * @param[in] address - pointer of address string
+ *
+ * @return
+ *     OC_STACK_OK
+ *     OC_STACK_ERROR
+ */
+OCStackResult requestIsAlive(const char *address);
+
+/**
+ *
+ * get string value of OCStackResult code
+ *
+ * @param[in] result - OCStringResult code
+ *
+ * @return
+ *     pointer of result string value
+ */
+const char *getResultString(OCStackResult result);
+
+OCStackResult requestQuery(RequestHandle *request, OCMethod method,
+                           const char *queryAddress, const char *queryUri);
+OCStackApplicationResult requestQueryCB(void *context, OCDoHandle handle,
+                                        OCClientResponse *clientResponse);
+OCEntityHandlerResponse buildEntityHandlerResponse(OCEntityHandlerRequest *entityHandlerRequest,
+        const char *clientPayload);
+OCEntityHandlerResult handleRequestPayload (OCEntityHandlerRequest *entityHandlerRequest,
+        char *payload, uint16_t maxPayloadSize);
+
+/*
+ * for Lite Device Side
+ */
+
+/**
+ *
+ * register resource as coordinatable
+ *
+ * @param[in] handle - resource handle
+ * @param[in] resourceTypeName - resource type name
+ * @param[in] resourceInterfaceName - resource interface name
+ * @param[in] resourceUri - resource URI
+ * @param[in] entityHandler - entity handler
+ * @param[in] resourceProperties - resource properties
+ *
+ * @return
+ *     pointer of result string value
+ */
+OCStackResult registerResourceAsCoordinatable(OCResourceHandle *handle,
+        const char *resourceTypeName, const char *resourceInterfaceName,
+        const char *resourceUri, OCEntityHandler entityHandler, uint8_t resourceProperties);
+
+OCStackResult registerResourceAsCoordinatable(OCResourceHandle *handle,
+        const char *resourceTypeName,
+        const char *resourceInterfaceName,
+        const char *resourceUri,
+        OCEntityHandler entityHandler,
+        uint8_t resourceProperties)
+{
+    OCStackResult ret = OC_STACK_OK;
+    size_t coordinateUriLen = sizeof(char) * (strlen(resourceUri) +
+            strlen(OIC_COORDINATING_FLAG) + 1);
+    char *coordinatingURI = (char *)malloc(coordinateUriLen);
+    if(coordinatingURI == NULL)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail : coordinatingURI");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    snprintf(coordinatingURI, coordinateUriLen,"%s%s", resourceUri, OIC_COORDINATING_FLAG);
+
+    OC_LOG_V(DEBUG, HOSTING_TAG, "requiredUri+coordinatingFlag = %s", coordinatingURI);
+
+    ret = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
+            coordinatingURI, entityHandler, resourceProperties);
+    free(coordinatingURI);
+    return ret;
+}
+
+/*
+ *  for Hosting Device Side
+ */
+OCStackResult OICStartCoordinate()
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    if (OCInit((char *) NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, HOSTING_TAG, PCF("OCStack init ERROR"));
+    }
+    else
+    {
+        s_mirrorResourceList = createMirrorResourceList();
+        s_requestHandleList = createRequestHandleList();
+        ret = requestPresence(OC_MULTICAST_PREFIX);
+    }
+
+    return ret;
+}
+
+OCStackResult OICStopCoordinate()
+{
+    OCStackResult result = OC_STACK_ERROR;
+
+    if (OCStop() == OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "OCStack Stop OK");
+    }
+
+    result = destroyMirrorResourceList(s_mirrorResourceList);
+    s_mirrorResourceList = NULL;
+    if(result != OC_STACK_OK)
+    {
+        return OC_STACK_ERROR;
+    }
+
+    return result;
+}
+
+int requestCoordinateeCandidateDiscovery(char *sourceResourceAddress)
+{
+    OCStackResult result;
+    OCCallbackData cbData;
+    OCDoHandle handle;
+
+    /* Start a discovery query*/
+    char queryUri[OIC_STRING_MAX_VALUE] = { '\0' };
+    if (sourceResourceAddress == NULL)
+    {
+        strncpy(queryUri, OC_WELL_KNOWN_COORDINATING_QUERY, sizeof(queryUri));
+    }
+    else
+    {
+        snprintf(queryUri, sizeof(queryUri), "coap://%s%s",
+                sourceResourceAddress , OC_COORDINATING_QUERY);
+    }
+
+    cbData.cb = requestCoordinateeCandidateDiscoveryCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    result = OCDoResource(&handle, OC_REST_GET, queryUri, OIC_COORDINATING_FLAG, 0,
+            OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
+    if (result != OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "OCStack resource error");
+    }
+    else
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Host Resource Finding...");
+    }
+    return result;
+}
+
+OCStackResult requestPresence(char *sourceResourceAddress)
+{
+    OCStackResult result = OC_STACK_ERROR;
+    OCCallbackData cbData;
+    OCDoHandle handle;
+
+    if (sourceResourceAddress == NULL)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "SourceResourceAddress is not available.");
+        return result;
+    }
+
+    cbData.cb = requestPresenceCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    char queryUri[OIC_STRING_MAX_VALUE] = { '\0' };
+    snprintf(queryUri, sizeof(queryUri), "coap://%s%s", sourceResourceAddress , OC_PRESENCE_URI);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "initializePresenceForCoordinating Query : %s", queryUri);
+
+    result = OCDoResource(&handle, OC_REST_PRESENCE, queryUri, 0, 0,
+            OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
+
+    if (result != OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "initializePresenceForCoordinating error");
+        result = OC_STACK_ERROR;
+    }
+    else
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Success initializePresenceForCoordinating");
+    }
+
+    return result;
+}
+
+OCStackApplicationResult requestPresenceCB(void *context, OCDoHandle handle,
+        OCClientResponse *clientResponse)
+{
+    uint8_t remoteIpAddress[4];
+    uint16_t remotePortNumber;
+    char address[OIC_STRING_MAX_VALUE] = { '\0' };
+
+    if (context == (void *) DEFAULT_CONTEXT_VALUE)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "\tCallback Context for presence CB recv successfully");
+    }
+    if (clientResponse)
+    {
+        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddress,
+                            remoteIpAddress + 1, remoteIpAddress + 2, remoteIpAddress + 3);
+        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNumber);
+        OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %s",  getResultString(clientResponse->result));
+        OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %d",  clientResponse->result);
+        OC_LOG_V(DEBUG, HOSTING_TAG,
+                 "\tPresence Device =============> Presence %s @ %d.%d.%d.%d:%d",
+                 clientResponse->resJSONPayload, remoteIpAddress[0], remoteIpAddress[1],
+                 remoteIpAddress[2], remoteIpAddress[3], remotePortNumber);
+
+        snprintf(address, sizeof(address), "%d.%d.%d.%d:%d", remoteIpAddress[0], remoteIpAddress[1],
+                remoteIpAddress[2], remoteIpAddress[3], remotePortNumber);
+        if (clientResponse->result == OC_STACK_OK)
+        {
+            requestCoordinateeCandidateDiscovery(address);
+        }
+        if (clientResponse->result == OC_STACK_PRESENCE_STOPPED
+            || clientResponse->result == OC_STACK_PRESENCE_TIMEOUT
+            || clientResponse->result == OC_STACK_PRESENCE_DO_NOT_HANDLE)
+        {
+            requestIsAlive(address);
+        }
+
+    }
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCStackApplicationResult requestCoordinateeCandidateDiscoveryCB(void *ctx, OCDoHandle handle,
+        OCClientResponse *clientResponse)
+{
+    OC_LOG(DEBUG, HOSTING_TAG, "Found Host Resource");
+    OCStackResult ret = OC_STACK_DELETE_TRANSACTION;
+
+    if (ctx == (void *) DEFAULT_CONTEXT_VALUE)
+    {
+        OC_LOG(DEBUG, HOSTING_TAG, "Callback Context for DISCOVER query recvd successfully");
+    }
+    if (clientResponse && clientResponse->result == OC_STACK_OK)
+    {
+        MirrorResourceList *vList = buildMirrorResourceList(handle, clientResponse);
+        if (vList != NULL)
+        {
+
+            if (vList->headerNode == NULL)
+            {
+                OC_LOG(DEBUG, HOSTING_TAG, "This Discover Response is empty");
+                destroyMirrorResourceList(vList);
+                return ret;
+            }
+
+            // register All of VirtualResource
+            while (vList->headerNode)
+            {
+                MirrorResource *mirrorResource = vList->headerNode;
+                ret = ejectMirrorResource(vList, mirrorResource);
+                mirrorResource->next = NULL;
+                OC_LOG_V(DEBUG, HOSTING_TAG,
+                        "register virtual resource uri : %s", mirrorResource->uri);
+                if (ret != OC_STACK_OK)
+                {
+                    continue;
+                }
+
+                ret = registerMirrorResource(mirrorResource);
+                if (ret != OC_STACK_OK)
+                {
+                    continue;
+                }
+
+                ret = insertMirrorResource(s_mirrorResourceList, mirrorResource);
+                if (ret != OC_STACK_OK)
+                {
+                    OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
+                    continue;
+                }
+                printMirrorResourceList(s_mirrorResourceList);
+
+                ret = requestResourceObservation(mirrorResource);
+                if (ret != OC_STACK_OK)
+                {
+                    OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
+                    deleteMirrorResourceFromList(s_mirrorResourceList, mirrorResource);
+                    continue;
+                }
+            }
+            destroyMirrorResourceList(vList);
+            if (ret != OC_STACK_OK)
+            {
+                return ret;
+            }
+        }
+        ret = OC_STACK_KEEP_TRANSACTION;
+    }
+    return ret;
+}
+
+MirrorResourceList *buildMirrorResourceList(OCDoHandle handle, OCClientResponse *clientResponse)
+{
+
+    cJSON *discoveryJson = cJSON_CreateObject();
+    discoveryJson = cJSON_Parse((char *)clientResponse->resJSONPayload);
+
+    cJSON *ocArray = cJSON_GetObjectItem(discoveryJson, "oc");
+    char *ocArray_str = cJSON_PrintUnformatted(ocArray);
+
+    if ( strstr(ocArray_str, "[{}") == ocArray_str )
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "invalid payload : %s", ocArray_str);
+        cJSON_Delete(discoveryJson);
+        return NULL;
+    }
+
+    MirrorResourceList *retList = createMirrorResourceList();
+
+    uint8_t remoteIpAddr[4];
+    uint16_t remotePortNum;
+
+    OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
+                        remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
+    OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNum);
+
+    char sourceaddr[OIC_STRING_MAX_VALUE] = {'\0'};
+    snprintf(sourceaddr, sizeof(sourceaddr), "%d.%d.%d.%d:%d", remoteIpAddr[0], remoteIpAddr[1],
+            remoteIpAddr[2], remoteIpAddr[3], remotePortNum);
+
+    OC_LOG_V(DEBUG, HOSTING_TAG, "Host Device =============> Discovered %s @ %s",
+             clientResponse->resJSONPayload, sourceaddr);
+
+    int arraySize = cJSON_GetArraySize(ocArray);
+    for (int i = 0; i < arraySize; ++i)
+    {
+        cJSON *ocArray_sub = cJSON_GetArrayItem(ocArray, i);
+        MirrorResource *mirrorResource = buildMirrorResource(ocArray_sub);
+
+        if (mirrorResource == NULL)
+        {
+            continue;
+        }
+        mirrorResource->address[OIC_SOURCE_ADDRESS] =
+                (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
+        if(mirrorResource->address[OIC_SOURCE_ADDRESS] == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail : mirrorResource address_source");
+            destroyMirrorResource(mirrorResource);
+            continue;
+        }
+        snprintf(mirrorResource->address[OIC_SOURCE_ADDRESS],
+                sizeof(char) * OIC_STRING_MAX_VALUE, "%s", sourceaddr);
+
+        mirrorResource->address[OIC_MIRROR_ADDRESS] =
+                (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
+        if(mirrorResource->address[OIC_MIRROR_ADDRESS] == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail : mirrorResource address_mirror");
+            destroyMirrorResource(mirrorResource);
+            continue;
+        }
+        snprintf(mirrorResource->address[OIC_MIRROR_ADDRESS],
+                sizeof(char) * OIC_STRING_MAX_VALUE, "0.0.0.0:00");
+
+        if (OC_STACK_OK != insertMirrorResource(retList, mirrorResource))
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "buildVirtualResourceList : insert resource fail");
+            destroyMirrorResource(mirrorResource);
+        }
+    }
+
+    cJSON_Delete(discoveryJson);
+    return retList;
+}
+
+MirrorResource *buildMirrorResource(cJSON *ocArray_sub)
+{
+    MirrorResource *mirrorResource = NULL;
+    const char *curValuestring = cJSON_GetObjectItem(ocArray_sub, "href")->valuestring;
+
+    if ( strstr(curValuestring, OIC_COORDINATING_FLAG) )
+    {
+        mirrorResource = createMirrorResource();
+        if(mirrorResource == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail for mirrorResource");
+            goto RET_ERROR;
+        }
+
+        mirrorResource->uri = (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
+        if(mirrorResource->uri == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail for mirrorResource uri");
+            goto RET_ERROR;
+        }
+        strncpy(mirrorResource->uri, curValuestring, strlen(curValuestring) - strlen(OIC_COORDINATING_FLAG));
+        mirrorResource->uri[strlen(curValuestring) - strlen(OIC_COORDINATING_FLAG)] = '\0';
+        OC_LOG_V(DEBUG, HOSTING_TAG, "VirtualResource URI : %s", mirrorResource->uri);
+
+        cJSON *inArray_sub = cJSON_GetObjectItem(ocArray_sub, "prop");
+
+        cJSON *tmpJSON = NULL;
+        int sizetemp = 0;
+
+        tmpJSON = cJSON_GetObjectItem(inArray_sub, "rt");
+        sizetemp = cJSON_GetArraySize(tmpJSON);
+        mirrorResource->prop.countResourceType = sizetemp;
+        mirrorResource->prop.resourceType = (char **)malloc(sizeof(char *)*sizetemp);
+        if (mirrorResource->prop.resourceType == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG,
+                    "memory alloc fail for mirrorResource number of resourceType");
+            goto RET_ERROR;
+        }
+        else
+        {
+            for (int k = 0; k < sizetemp; ++k)
+            {
+                mirrorResource->prop.resourceType[k] =
+                        (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
+                if (mirrorResource->prop.resourceType[k] == NULL)
+                {
+                    OC_LOG_V(DEBUG, HOSTING_TAG,
+                            "memory alloc fail for mirrorResource resourceType[n]");
+                    goto RET_ERROR;
+                }
+                memset(mirrorResource->prop.resourceType[k], '\0', OIC_STRING_MAX_VALUE);
+                strncpy(mirrorResource->prop.resourceType[k],
+                        cJSON_GetArrayItem(tmpJSON, k)->valuestring,
+                        sizeof(char) * OIC_STRING_MAX_VALUE);
+            }
+        }
+
+        tmpJSON = cJSON_GetObjectItem(inArray_sub, "if");
+        sizetemp = cJSON_GetArraySize(tmpJSON);
+        mirrorResource->prop.countInterface = sizetemp;
+        mirrorResource->prop.resourceInterfaceName = (char **)malloc(sizeof(char *)*sizetemp);
+        if (mirrorResource->prop.resourceInterfaceName == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG,
+                    "memory alloc fail for mirrorResource number of resourceInterfaceName");
+            goto RET_ERROR;
+        }
+
+        for (int k = 0; k < sizetemp; ++k)
+        {
+            mirrorResource->prop.resourceInterfaceName[k] =
+                    (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
+            if (mirrorResource->prop.resourceInterfaceName[k] == NULL)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG,
+                        "memory alloc fail for mirrorResource resourceInterfaceName[n]");
+                goto RET_ERROR;
+            }
+
+            memset(mirrorResource->prop.resourceInterfaceName[k], '\0', OIC_STRING_MAX_VALUE);
+            strncpy(mirrorResource->prop.resourceInterfaceName[k],
+                    cJSON_GetArrayItem(tmpJSON, k)->valuestring,
+                    sizeof(char) * OIC_STRING_MAX_VALUE);
+        }
+    }
+
+    return mirrorResource;
+
+RET_ERROR:
+    destroyMirrorResource(mirrorResource);
+    return NULL;
+}
+
+OCStackResult registerMirrorResource(MirrorResource *mirrorResource)
+{
+    OCStackResult result = OC_STACK_ERROR;
+
+    MirrorResource *foundMirrorResource = findMirrorResourceUsingAddressAndURI(s_mirrorResourceList,
+                                          mirrorResource->address[OIC_MIRROR_ADDRESS], OIC_MIRROR_ADDRESS, mirrorResource->uri);
+    if (foundMirrorResource != NULL)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Already registered resource");
+        goto RETURN_ERR;
+    }
+
+    result = OCCreateResource(&(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]),
+                              mirrorResource->prop.resourceType[0],
+                              mirrorResource->prop.resourceInterfaceName[0],
+                              mirrorResource->uri,
+                              resourceEntityHandlerCB,
+                              OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    OC_LOG_V(DEBUG, HOSTING_TAG, "created mirror resource Handle : %u",mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
+
+    if (result != OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "error return = %s", getResultString(result));
+        mirrorResource->next = NULL;
+        destroyMirrorResource(mirrorResource);
+        return result;
+    }
+
+    if (mirrorResource->prop.countResourceType > 1)
+    {
+        int i = 0;
+        for (i = 1; i < mirrorResource->prop.countResourceType; ++i)
+        {
+            result = OCBindResourceTypeToResource(
+                             mirrorResource->resourceHandle[OIC_MIRROR_HANDLE],
+                             mirrorResource->prop.resourceType[i]);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG, "Virtual Resource Registration Fail : BindResourceType");
+                goto RETURN_ERR;
+            }
+        }
+    }
+
+    if (mirrorResource->prop.countInterface > 1)
+    {
+        int i = 0;
+        for (i = 1; i < mirrorResource->prop.countInterface; ++i)
+        {
+            result = OCBindResourceInterfaceToResource(
+                         mirrorResource->resourceHandle[OIC_MIRROR_HANDLE],
+                         mirrorResource->prop.resourceInterfaceName[i]);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG,
+                        "Virtual Resource Registration Fail : BindResourceInterfaceName");
+                goto RETURN_ERR;
+            }
+        }
+    }
+
+    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource Registration Success");
+    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource uri : %s", mirrorResource->uri);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource source address : %s",
+             mirrorResource->address[OIC_SOURCE_ADDRESS]);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource virtual address : %s",
+             mirrorResource->address[OIC_MIRROR_ADDRESS]);
+    return result;
+
+RETURN_ERR:
+    OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
+    mirrorResource->next = NULL;
+    destroyMirrorResource(mirrorResource);
+
+    return result;
+}
+
+OCStackResult requestResourceObservation(MirrorResource *mirrorResource)
+{
+    OCStackResult result;
+    OCCallbackData cbData;
+
+    cbData.cb = requestResourceObservationCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    char query[OIC_STRING_MAX_VALUE] = {'\0'};
+    snprintf(query, sizeof(query), "coap://%s%s%s", mirrorResource->address[OIC_SOURCE_ADDRESS], mirrorResource->uri,
+            OIC_COORDINATING_FLAG);
+
+    result = OCDoResource(&mirrorResource->resourceHandle[OIC_REQUEST_HANDLE], OC_REST_OBSERVE, query,
+                          0, NULL, OC_TRANSPORT,
+                          OC_HIGH_QOS, &cbData, NULL, 0);
+
+    if (result != OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "OCDoResource returns error %s with method %d",
+                 getResultString(result), OC_REST_OBSERVE);
+    }
+
+    return result;
+}
+
+OCStackApplicationResult requestResourceObservationCB(void *context, OCDoHandle handle,
+        OCClientResponse *clientResponse)
+{
+    OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
+
+    if (context == (void *)DEFAULT_CONTEXT_VALUE)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Callback Context for OBS query recvd successfully");
+    }
+
+    if (clientResponse && clientResponse->result != OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "observeCB result error = %s",
+                 getResultString(clientResponse->result));
+        return checkResourceValidation(handle);
+    }
+
+    if (clientResponse && clientResponse->result == OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG,
+                 "<=============Callback Context for OBSERVE notification recvd successfully");
+        OC_LOG_V(DEBUG, HOSTING_TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+        OC_LOG_V(DEBUG, HOSTING_TAG, "JSON = %s =============> Obs Response",
+                 clientResponse->resJSONPayload);
+
+        MirrorResource *foundMirrorResource = updateMirrorResource(handle, clientResponse->resJSONPayload);
+        if (foundMirrorResource == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource : Fail");
+            return ret;
+        }
+
+        if ( OC_STACK_OK != OCNotifyAllObservers(foundMirrorResource->resourceHandle[OIC_MIRROR_HANDLE],
+                OC_HIGH_QOS) )
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Notify Mirror Resource's Subscriber : Fail");
+        }
+        else
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Notify Mirror Resource's Subscriber : Success");
+        }
+
+        if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "This also serves as a registration confirmation");
+        }
+        else if (clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "This also serves as a deregistration confirmation");
+            return ret;
+        }
+        else if (clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "This also tells you that registration/deregistration failed");
+            return ret;
+        }
+        ret = OC_STACK_KEEP_TRANSACTION;
+    }
+    return ret;
+}
+
+OCStackApplicationResult checkResourceValidation(OCDoHandle handle)
+{
+    OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
+
+    RequestHandle *foundRequestHandle = findRequestHandle(s_requestHandleList, handle,
+                                        OIC_REQUEST_BY_COORDINATOR);
+
+    if (foundRequestHandle == NULL)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Not found any request.");
+        return ret;
+    }
+
+    if (foundRequestHandle->isAliveCheck)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "This response is Alive Check : Expired resource");
+        OCDeleteResource(foundRequestHandle->requestHandle[OIC_REQUEST_BY_CLIENT]);
+    }
+    deleteRequestHandleFromList(s_requestHandleList, foundRequestHandle);
+    return ret;
+}
+
+MirrorResource *updateMirrorResource(OCDoHandle handle, const char *payload)
+{
+    MirrorResource *foundMirrorResource = findMirrorResourceUsingHandle(
+            s_mirrorResourceList, handle, OIC_REQUEST_HANDLE);
+
+    if (!foundMirrorResource)
+    {
+        // TODO
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource. In updateMirrorResource");
+        return NULL;
+    }
+
+    cJSON *repData = NULL;
+    cJSON *observeJson = cJSON_Parse(payload);
+
+    if (observeJson)
+    {
+        cJSON *ocArray = cJSON_GetObjectItem(observeJson, "oc");
+        cJSON *ocArray_sub = cJSON_GetArrayItem(ocArray, 0);
+        cJSON *tempData = cJSON_GetObjectItem(ocArray_sub, "rep");
+        char *temp = cJSON_PrintUnformatted(tempData);
+
+        repData = cJSON_Parse(temp);
+        if (temp != NULL)
+        {
+            free(temp);
+        }
+        cJSON_Delete(observeJson);
+    }
+    else
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror resource payload is not correct");
+        return NULL;
+    }
+
+    if (foundMirrorResource->rep)
+    {
+        cJSON_Delete(foundMirrorResource->rep);
+        foundMirrorResource->rep = NULL;
+    }
+    foundMirrorResource->rep = repData;
+
+    cJSON *json = cJSON_CreateObject();
+
+    char nodeData[OIC_STRING_MAX_VALUE] = {'\0'};
+    snprintf(nodeData, sizeof(nodeData), "%s", foundMirrorResource->uri);
+    cJSON_AddStringToObject(json, "href", nodeData);
+
+    cJSON *nodeRep = cJSON_Parse(cJSON_PrintUnformatted(foundMirrorResource->rep));
+    cJSON_AddItemToObject(json, "rep", nodeRep);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "It will notify resource : %s", cJSON_PrintUnformatted(json));
+
+    cJSON_Delete(json);
+
+    return foundMirrorResource;
+}
+
+char *buildResponsePayload (OCEntityHandlerRequest *entityHandlerRequest)
+{
+    MirrorResource *mirrorResource = findMirrorResourceUsingHandle(s_mirrorResourceList,
+                                     entityHandlerRequest->resource, OIC_MIRROR_HANDLE);
+    if (!mirrorResource)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource. In buildResponsePayload()");
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource's Handle : %x.", entityHandlerRequest->resource);
+        return NULL;
+    }
+
+    if (entityHandlerRequest->method == OC_REST_PUT)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "oc_rest_put");
+        if (mirrorResource->rep)
+        {
+            cJSON_Delete(mirrorResource->rep);
+            mirrorResource->rep = NULL;
+        }
+        mirrorResource->rep = cJSON_CreateObject();
+        mirrorResource->rep = cJSON_Parse(entityHandlerRequest->reqJSONPayload);
+    }
+
+    OC_LOG_V(DEBUG, HOSTING_TAG, "node's uri : %s", mirrorResource->uri);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "node's source address : %s", mirrorResource->address[0]);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "node's mirror address : %s", mirrorResource->address[1]);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "node's rep : %s", cJSON_PrintUnformatted(mirrorResource->rep));
+
+    cJSON *jsonObject = cJSON_CreateObject();
+
+    char uriString[OIC_STRING_MAX_VALUE] = {'\0'};
+    snprintf(uriString, sizeof(uriString), "%s", mirrorResource->uri);
+    cJSON_AddStringToObject(jsonObject, "href", uriString);
+
+    cJSON *itemRep = cJSON_Parse(cJSON_PrintUnformatted(mirrorResource->rep));
+    cJSON_AddItemToObject(jsonObject, "rep", itemRep);
+    OC_LOG_V(DEBUG, HOSTING_TAG, "Will response resource : %s", cJSON_PrintUnformatted(jsonObject));
+
+    char *jsonResponse = cJSON_Print(jsonObject);
+    cJSON_Delete(jsonObject);
+
+    return jsonResponse;
+}
+
+OCEntityHandlerResult
+resourceEntityHandlerCB (OCEntityHandlerFlag entifyHandlerFlag,
+                         OCEntityHandlerRequest *entityHandlerRequest)
+{
+    OC_LOG_V(DEBUG, HOSTING_TAG, "Inside device default entity handler - flags: 0x%x",
+             entifyHandlerFlag);
+
+    OCEntityHandlerResult entityHandlerResult = OC_EH_OK;
+    OCEntityHandlerResponse entityHandlerResponse;
+    char payload[MAX_RESPONSE_LENGTH] = {0};
+
+    // Validate pointer
+    if (!entityHandlerRequest)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Invalid request pointer");
+        return OC_EH_ERROR;
+    }
+
+    // Initialize certain response fields
+    entityHandlerResponse.numSendVendorSpecificHeaderOptions = 0;
+    memset(entityHandlerResponse.sendVendorSpecificHeaderOptions, 0,
+           sizeof entityHandlerResponse.sendVendorSpecificHeaderOptions);
+    memset(entityHandlerResponse.resourceUri, 0, sizeof entityHandlerResponse.resourceUri);
+
+    if (entifyHandlerFlag & OC_REQUEST_FLAG)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Flag includes OC_REQUEST_FLAG");
+        if (entityHandlerRequest->resource == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Received request from client to a non-existing resource");
+            entityHandlerResult = handleNonExistingResourceRequest(entityHandlerRequest, payload,
+                                  sizeof(payload) - 1);
+        }
+        else if (OC_REST_GET == entityHandlerRequest->method)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_REST_GET from client");
+            entityHandlerResult = handleGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+        }
+        else if (OC_REST_PUT == entityHandlerRequest->method ||
+                 OC_REST_DELETE == entityHandlerRequest->method )
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_REST_PUT/DELETE from client");
+
+            RequestHandle *request = createRequestHandle();
+
+            request->requestHandle[OIC_REQUEST_BY_CLIENT] = entityHandlerRequest;
+            request->resourceHandle = entityHandlerRequest->resource;
+            request->method = entityHandlerRequest->method;
+            request->entityRequestHandle = entityHandlerRequest->requestHandle;
+
+            OCStackResult result = insertRequestHandle(s_requestHandleList, request);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG, "Insert request list : fail2(%d)", result);
+                return result;
+            }
+
+            MirrorResource *mirrorResource = findMirrorResourceUsingHandle(s_mirrorResourceList,
+                                             entityHandlerRequest->resource, OIC_MIRROR_HANDLE);
+            if (mirrorResource == NULL)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG, "Not found requested resource");
+                return OC_EH_ERROR;
+            }
+
+            result = requestQuery(request,
+                    entityHandlerRequest->method, mirrorResource->address[OIC_SOURCE_ADDRESS],
+                    mirrorResource->uri);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG, "Request query failed");
+                deleteRequestHandleFromList(s_requestHandleList, request);
+            }
+            return OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Received unsupported method %d from client",
+                     entityHandlerRequest->method);
+            entityHandlerResult = OC_EH_ERROR;
+        }
+
+        // If the result isn't an error or forbidden, send response
+        if (!((entityHandlerResult == OC_EH_ERROR) || (entityHandlerResult == OC_EH_FORBIDDEN)))
+        {
+            // Format the response.  Note this requires some info about the request
+            entityHandlerResponse.requestHandle = entityHandlerRequest->requestHandle;
+            entityHandlerResponse.resourceHandle = entityHandlerRequest->resource;
+            entityHandlerResponse.ehResult = entityHandlerResult;
+            entityHandlerResponse.payload = (char *)payload;
+            entityHandlerResponse.payloadSize = strlen(payload);
+            // Indicate that response is NOT in a persistent buffer
+            entityHandlerResponse.persistentBufferFlag = 0;
+
+            // Handle vendor specific options
+            if (entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
+                entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG, "Received vendor specific options");
+                OCHeaderOption *receivedVenderSpecificHeaderOptions =
+                    entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
+                for ( int i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
+                {
+                    if (((OCHeaderOption)receivedVenderSpecificHeaderOptions[i]).protocolID == OC_COAP_ID)
+                    {
+                        OC_LOG_V(DEBUG, HOSTING_TAG, "Received option with OC_COAP_ID and ID %u with",
+                                 ((OCHeaderOption)receivedVenderSpecificHeaderOptions[i]).optionID );
+                    }
+                }
+                OCHeaderOption *sendVenderSpecificHeaderOptions =
+                    entityHandlerResponse.sendVendorSpecificHeaderOptions;
+                uint8_t option2[] = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
+                uint8_t option3[] = {31, 32, 33, 34, 35, 36, 37, 38, 39, 40};
+                sendVenderSpecificHeaderOptions[0].protocolID = OC_COAP_ID;
+                sendVenderSpecificHeaderOptions[0].optionID = 2248;
+                memcpy(sendVenderSpecificHeaderOptions[0].optionData, option2, sizeof(option2));
+                sendVenderSpecificHeaderOptions[0].optionLength = 10;
+                sendVenderSpecificHeaderOptions[1].protocolID = OC_COAP_ID;
+                sendVenderSpecificHeaderOptions[1].optionID = 2600;
+                memcpy(sendVenderSpecificHeaderOptions[1].optionData, option3, sizeof(option3));
+                sendVenderSpecificHeaderOptions[1].optionLength = 10;
+                entityHandlerResponse.numSendVendorSpecificHeaderOptions = 2;
+            }
+
+            // Send the response
+            if (OCDoResponse(&entityHandlerResponse) != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, HOSTING_TAG, "Error sending response");
+                entityHandlerResult = OC_EH_ERROR;
+            }
+        }
+    }
+    if (entifyHandlerFlag & OC_OBSERVE_FLAG)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Flag includes OC_OBSERVE_FLAG");
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_OBSERVE_REGISTER from client");
+        }
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_OBSERVE_DEREGISTER from client");
+        }
+    }
+
+    return entityHandlerResult;
+}
+OCEntityHandlerResult
+handleGetRequest (OCEntityHandlerRequest *entityHandlerRequest,
+        char *payload, uint16_t maxPayloadSize)
+{
+    OC_LOG_V(DEBUG, HOSTING_TAG, "ProcessGetRequest in....");
+
+    OCEntityHandlerResult entityHandlerResult = OC_EH_ERROR;
+    char *responsePayload = buildResponsePayload(entityHandlerRequest);
+    if(!responsePayload)
+    {
+        return entityHandlerResult;
+    }
+
+    if (maxPayloadSize > strlen ((char *)responsePayload))
+    {
+        strncpy(payload, responsePayload, strlen((char *)responsePayload));
+        entityHandlerResult = OC_EH_OK;
+    }
+    else
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Response buffer: %d bytes is too small", maxPayloadSize);
+    }
+
+    free(responsePayload);
+
+    return entityHandlerResult;
+}
+OCEntityHandlerResult
+handleNonExistingResourceRequest(OCEntityHandlerRequest *entityHandlerRequest,
+        char *payload, uint16_t maxPayloadSize)
+{
+    OC_LOG_V(INFO, HOSTING_TAG, "Executing %s ", __func__);
+
+    char responsePayload[OIC_STRING_MAX_VALUE] = {'\0'};
+    strncpy(responsePayload, "{App determines payload: The resource does not exist.}",
+            sizeof(responsePayload));
+
+    if ( (entityHandlerRequest != NULL) &&
+         (maxPayloadSize > strlen ((char *)responsePayload)) )
+    {
+        strncpy((char *)payload, responsePayload, strlen((char *)responsePayload));
+    }
+    else
+    {
+        OC_LOG_V (INFO, HOSTING_TAG, "Response buffer: %d bytes is too small",
+                  maxPayloadSize);
+    }
+
+    return OC_EH_RESOURCE_DELETED;
+}
+
+OCStackResult requestIsAlive(const char *address)
+{
+    MirrorResourceList *requestMirrorResourceList = findMirrorResourceListUsingAddress(
+                s_mirrorResourceList, address, OIC_SOURCE_ADDRESS);
+
+    if (requestMirrorResourceList == NULL)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found any mirror resource1");
+        return OC_STACK_ERROR;
+    }
+
+    if (requestMirrorResourceList->headerNode == NULL)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found any mirror resource2");
+        return OC_STACK_ERROR;
+    }
+
+    MirrorResource *mirrorResource = requestMirrorResourceList->headerNode;
+    while (mirrorResource)
+    {
+        RequestHandle *requestAlive = createRequestHandle();
+        requestAlive->isAliveCheck = 1;
+        requestAlive->requestHandle[OIC_REQUEST_BY_CLIENT] =
+            mirrorResource->resourceHandle[OIC_MIRROR_HANDLE];
+
+        OCStackResult result = insertRequestHandle(s_requestHandleList, requestAlive);
+        if (result != OC_STACK_OK)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Insert request list : fail3");
+            destroyRequestHandle(requestAlive);
+            mirrorResource = mirrorResource->next;
+            continue;
+        }
+
+        result = requestQuery(requestAlive, OC_REST_GET, address, mirrorResource->uri);
+        if (result != OC_STACK_OK)
+        {
+            deleteRequestHandleFromList(s_requestHandleList, requestAlive);
+        }
+        mirrorResource = mirrorResource->next;
+    }
+    destroyMirrorResourceList(requestMirrorResourceList);
+
+    return OC_STACK_OK;
+}
+
+const char *getResultString(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_RESOURCE_CREATED:
+            return "OC_STACK_RESOURCE_CREATED";
+        case OC_STACK_RESOURCE_DELETED:
+            return "OC_STACK_RESOURCE_DELETED";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+        case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
+            return "OC_STACK_VIRTUAL_DO_NOT_HANDLE";
+        case OC_STACK_PRESENCE_STOPPED:
+            return "OC_STACK_PRESENCE_STOPPED";
+        case OC_STACK_PRESENCE_TIMEOUT:
+            return "OC_STACK_PRESENCE_TIMEOUT";
+        case OC_STACK_PRESENCE_DO_NOT_HANDLE:
+            return "OC_STACK_PRESENCE_DO_NOT_HANDLE";
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
+    }
+}
+
+void getJsonArrayPair(cJSON *tempData)
+{
+    int countofrep = cJSON_GetArraySize(tempData);
+    OC_LOG_V(DEBUG, HOSTING_TAG,
+             "//////////////////////////////////////////////////////////////////////////");
+    OC_LOG_V(DEBUG, HOSTING_TAG, "//Test");
+    OC_LOG_V(DEBUG, HOSTING_TAG, "rep Size : %d", countofrep);
+
+    for (int i = 0; i < countofrep; ++i)
+    {
+        cJSON *arrayJSON = cJSON_GetArrayItem(tempData, i);
+        OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's name : %s", i, arrayJSON->string);
+
+        switch (arrayJSON->type)
+        {
+            case cJSON_False:
+            case cJSON_True:
+                OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %d", i, arrayJSON->valueint);
+                break;
+            case cJSON_Number:
+                OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %f", i, arrayJSON->valuedouble);
+                break;
+            case cJSON_String:
+                OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %s", i, arrayJSON->valuestring);
+                break;
+            case cJSON_NULL:
+            default:
+                OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : NULL", i);
+                break;
+        }
+    }
+    OC_LOG_V(DEBUG, HOSTING_TAG,
+             "//////////////////////////////////////////////////////////////////////////");
+}
+
+OCStackResult requestQuery(RequestHandle *request, OCMethod method,
+                           const char *queryAddress, const char *queryUri)
+{
+
+    OCStackResult result = OC_STACK_ERROR;
+    OCCallbackData cbData;
+
+    /* Start a discovery query*/
+    char queryFullUri[OIC_STRING_MAX_VALUE] = {'\0'};
+    if (queryAddress == NULL)
+    {
+        return result;
+    }
+    else
+    {
+        snprintf(queryFullUri, sizeof(queryFullUri) ,"coap://%s%s%s", queryAddress , queryUri, OIC_COORDINATING_FLAG);
+    }
+
+    cbData.cb = requestQueryCB;
+    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    if(method == OC_REST_PUT)
+    {
+        char payload[OIC_STRING_MAX_VALUE] = {'\0'};
+        snprintf(payload , sizeof(payload), "%s" ,
+         ((OCEntityHandlerRequest*)request->requestHandle[OIC_REQUEST_BY_CLIENT])->reqJSONPayload);
+
+        result = OCDoResource(&request->requestHandle[OIC_REQUEST_BY_COORDINATOR],
+                method, queryFullUri, NULL, payload, OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
+    }
+    else
+    {
+        result = OCDoResource(&request->requestHandle[OIC_REQUEST_BY_COORDINATOR],
+                method, queryFullUri, NULL, 0, OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
+    }
+
+    if (result != OC_STACK_OK)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "OCStack resource error");
+    }
+
+    return result;
+}
+
+OCStackApplicationResult requestQueryCB(void *context, OCDoHandle handle,
+                                        OCClientResponse *clientResponse)
+{
+    OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
+
+    if (context == (void *) DEFAULT_CONTEXT_VALUE)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Callback Context for Request query recvd successfully");
+    }
+
+    if (clientResponse && clientResponse->result != OC_STACK_OK && clientResponse->result != OC_STACK_RESOURCE_DELETED)
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "requestQueryCB result error = %s",
+                 getResultString(clientResponse->result));
+        return checkResourceValidation(handle);
+    }
+
+    if (clientResponse && (clientResponse->result == OC_STACK_OK || clientResponse->result == OC_STACK_RESOURCE_DELETED))
+    {
+        RequestHandle *request = findRequestHandle(s_requestHandleList, handle, OIC_REQUEST_BY_COORDINATOR);
+        if (request == NULL)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "Not found Any request");
+            return ret;
+        }
+        if (request->isAliveCheck == 1)
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "This response is Alive Check : Keep resource");
+        }
+        else
+        {
+            OC_LOG_V(DEBUG, HOSTING_TAG, "requestCB's payload: %s", clientResponse->resJSONPayload);
+            OCEntityHandlerRequest *entityHandler = (OCEntityHandlerRequest *)(
+                    request->requestHandle[OIC_REQUEST_BY_CLIENT]);
+            OC_LOG_V(DEBUG, HOSTING_TAG, "requested resource handle : %u", entityHandler->resource
+                    );
+
+            entityHandler->resource = request->resourceHandle;
+            entityHandler->method = request->method;
+            entityHandler->requestHandle = request->entityRequestHandle;
+
+            OCEntityHandlerResponse response = buildEntityHandlerResponse(
+                                                   entityHandler, clientResponse->resJSONPayload);
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, HOSTING_TAG, "Error sending response");
+                deleteRequestHandleFromList(s_requestHandleList, request);
+                return ret;
+            }
+            if (entityHandler->method == OC_REST_DELETE)
+            {
+                OCDeleteResource(entityHandler->resource);
+            }
+        }
+        deleteRequestHandleFromList(s_requestHandleList, request);
+        ret = OC_STACK_KEEP_TRANSACTION;
+    }
+
+    return ret;
+}
+
+OCEntityHandlerResponse buildEntityHandlerResponse(OCEntityHandlerRequest *entityHandlerRequest,
+        const char *clientPayload)
+{
+    OC_LOG_V(DEBUG, HOSTING_TAG, "enter buildEntityHandlerResponse");
+    OCEntityHandlerResponse response;
+    memset(&response, 0, sizeof(response));
+    OCEntityHandlerResult entityHandlerResult = OC_EH_OK;
+    char payload[MAX_RESPONSE_LENGTH] = {'\0'};
+
+    // Initialize certain response fields
+    response.numSendVendorSpecificHeaderOptions = 0;
+    memset(response.sendVendorSpecificHeaderOptions, 0,
+           sizeof response.sendVendorSpecificHeaderOptions);
+    memset(response.resourceUri, 0, sizeof response.resourceUri);
+
+    char *temp = NULL;
+    if(entityHandlerRequest->method == OC_REST_PUT)
+    {
+        cJSON *observeJson = cJSON_CreateObject();
+        observeJson = cJSON_Parse(clientPayload);
+
+        cJSON *ocArray = cJSON_GetObjectItem(observeJson, "oc");
+        cJSON *ocArray_sub = cJSON_GetArrayItem(ocArray, 0);
+
+        cJSON *tempData = cJSON_GetObjectItem(ocArray_sub, "rep");
+        temp = cJSON_PrintUnformatted(tempData);
+
+        cJSON_Delete(observeJson);
+
+        entityHandlerRequest->reqJSONPayload = temp;
+    }
+    entityHandlerResult = handleRequestPayload(entityHandlerRequest, payload, sizeof(payload) - 1);
+
+    // Format the response.  Note this requires some info about the request
+    response.requestHandle = entityHandlerRequest->requestHandle;
+    response.resourceHandle = entityHandlerRequest->resource;
+    response.ehResult = entityHandlerResult;
+
+    response.payload = (char *)payload;
+    response.payloadSize = strlen(payload);
+    // Indicate that response is NOT in a persistent buffer
+    response.persistentBufferFlag = 0;
+
+    if(entityHandlerRequest->method == OC_REST_PUT){
+        if(temp){
+            free(temp);
+        }
+    }
+
+    return response;
+}
+
+OCEntityHandlerResult handleRequestPayload (OCEntityHandlerRequest *entityHandlerRequest,
+        char *payload, uint16_t maxPayloadSize)
+{
+    OC_LOG_V(DEBUG, HOSTING_TAG, "enter handleRequestPayload");
+    OCEntityHandlerResult entityHandlerResult = OC_EH_ERROR;
+
+    if (entityHandlerRequest->method == OC_REST_DELETE)
+    {
+        memset(payload, '\0', sizeof(char) * (maxPayloadSize + 1));
+        OC_LOG_V(DEBUG, HOSTING_TAG, "DELETE");
+        return OC_EH_RESOURCE_DELETED;
+    }
+
+    char *responsePayload = buildResponsePayload(entityHandlerRequest);
+    if(!responsePayload)
+    {
+        return entityHandlerResult;
+    }
+
+    if (maxPayloadSize > strlen ((char *)responsePayload))
+    {
+        strncpy(payload, responsePayload, strlen ((char *)responsePayload));
+        entityHandlerResult = OC_EH_OK;
+    }
+    else
+    {
+        OC_LOG_V(DEBUG, HOSTING_TAG, "Response buffer: %d bytes is too small", maxPayloadSize);
+        entityHandlerResult = OC_EH_ERROR;
+    }
+
+    free(responsePayload);
+
+    return entityHandlerResult;
+}
diff --git a/service/notification-manager/NotificationManager/src/linux/main.cpp b/service/notification-manager/NotificationManager/src/linux/main.cpp
deleted file mode 100644 (file)
index 26724da..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <iostream>
-#include "NotificationManager.h"
-
-using namespace OC;
-
-int main(void)
-{
-
-    std::cout << endl;
-    std::cout << "========================================================" << endl;
-    std::cout << "Start Notification Manager : Hosting v0.5\n";
-
-
-       HostingConfig cfg;
-       cfg.hostingMode         = HostingMode::ManualMode;
-       cfg.automaticMethod     = AutomaticMethod::None;
-       cfg.notifyMethod                = NotifyMethod::Frequence;
-       cfg.frequency                   = NotifyFrequency::OnTime;
-
-       NotificationManager::initialize(cfg);
-
-    while(true)
-    {
-       char signal;
-       cin >> signal;
-
-       switch(signal)
-       {
-       case 'q':
-       case 'Q':
-               std::cout << endl;
-                       std::cout << "========================================================" << endl;
-                       std::cout << "End Notification Manager : Hosting v0.5\n";
-               return true;
-       default:
-               break;
-       }
-
-    }
-
-    std::cout << endl;
-    std::cout << "========================================================" << endl;
-    std::cout << "End Notification Manager : Hosting v0.5\n";
-
-    return true;
-}
diff --git a/service/notification-manager/NotificationManager/src/requestHandler.c b/service/notification-manager/NotificationManager/src/requestHandler.c
new file mode 100644 (file)
index 0000000..8508d9d
--- /dev/null
@@ -0,0 +1,208 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "virtualResource.h"
+
+RequestHandleList *createRequestHandleList()
+{
+    RequestHandleList *requestHandleList = (RequestHandleList*)malloc(sizeof(RequestHandleList));
+    if(!requestHandleList)
+    {
+        OC_LOG(DEBUG, RH_TAG,"Request Handle List Creation Fail.");
+    }
+    else
+    {
+        requestHandleList->headerNode = NULL;
+        requestHandleList->tailNode = NULL;
+    }
+
+    return requestHandleList;
+}
+
+RequestHandle *createRequestHandle()
+{
+    RequestHandle *requestHandle = (RequestHandle*)malloc(sizeof(RequestHandle));
+    if(!requestHandle)
+    {
+        OC_LOG(DEBUG, RH_TAG,"Request Handle Creation Fail.");
+    }
+    else
+    {
+        requestHandle->requestHandle[OIC_REQUEST_BY_CLIENT] = NULL;
+        requestHandle->requestHandle[OIC_REQUEST_BY_COORDINATOR] = NULL;
+        requestHandle->resourceHandle = NULL;
+
+        requestHandle->isAliveCheck = 0;
+
+        requestHandle->next = NULL;
+    }
+
+    return requestHandle;
+
+}
+OCStackResult insertRequestHandle(RequestHandleList *requestHandleList,
+        RequestHandle *requestHandle)
+{
+    if(requestHandleList == NULL || requestHandle == NULL)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if(requestHandleList->headerNode == NULL)
+    {
+        requestHandleList->headerNode = requestHandle;
+        requestHandleList->tailNode = requestHandle;
+    }
+    else
+    {
+        requestHandleList->tailNode->next = requestHandle;
+        requestHandleList->tailNode = requestHandle;
+    }
+
+    return OC_STACK_OK;
+}
+
+OCStackResult deleteRequestHandleFromList(RequestHandleList *requestHandleList,
+        RequestHandle *requestHandle)
+{
+    if(requestHandleList == NULL || requestHandle == NULL)
+    {
+        OC_LOG(DEBUG, RH_TAG,"Delete Request Handle : invalid parameter.");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if(requestHandleList->headerNode == NULL)
+    {
+        OC_LOG(DEBUG, RH_TAG,"Delete Request Handle : Empty Request Handle List.");
+        return OC_STACK_ERROR;
+    }
+
+    if(requestHandle == requestHandleList->headerNode)
+    {
+        requestHandleList->headerNode = requestHandleList->headerNode->next;
+        requestHandle->next = NULL;
+        return destroyRequestHandle(requestHandle);
+    }
+
+    RequestHandle *preNode = requestHandleList->headerNode;
+    RequestHandle *curNode = preNode->next;
+    while(curNode != NULL)
+    {
+        if(curNode == requestHandle)
+        {
+            if(curNode == requestHandleList->tailNode)
+            {
+                requestHandleList->tailNode = preNode;
+                preNode->next = NULL;
+            }
+            else
+            {
+                preNode->next = curNode->next;
+            }
+            requestHandle->next = NULL;
+            return destroyRequestHandle(requestHandle);
+        }
+        preNode = curNode;
+        curNode = curNode->next;
+    }
+
+    return OC_STACK_ERROR;
+}
+
+OCStackResult destroyRequestHandle(RequestHandle *requestHandle)
+{
+    if(requestHandle)
+    {
+        if(requestHandle->next)
+        {
+//            destroyRequestHandle(requestHandle->next);
+            requestHandle->next = NULL;
+        }
+
+        requestHandle->requestHandle[OIC_REQUEST_BY_CLIENT] = NULL;
+        requestHandle->requestHandle[OIC_REQUEST_BY_COORDINATOR] = NULL;
+
+        requestHandle->isAliveCheck = 0;
+
+        free(requestHandle);
+    }
+    else
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    return OC_STACK_OK;
+}
+
+OCStackResult destroyRequestHandleList(RequestHandleList *requestHandleList){
+    if(requestHandleList)
+    {
+        while(requestHandleList->headerNode)
+        {
+            deleteRequestHandleFromList(requestHandleList,requestHandleList->headerNode);
+        }
+        free(requestHandleList);
+    }
+    else{
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    return OC_STACK_OK;
+}
+
+RequestHandle *findRequestHandle(RequestHandleList *requestHandleList,
+        OCDoHandle handle, OICResourceCoordinatorParamType paramType)
+{
+    if(requestHandleList == NULL || handle == NULL)
+    {
+        OC_LOG(DEBUG, RH_TAG,"Find Virtual Resource : invalid parameter.");
+        return NULL;
+    }
+    if(requestHandleList->headerNode == NULL)
+    {
+        OC_LOG(DEBUG, RH_TAG,"Find Virtual Resource : Empty Virtual Resource List.");
+        return NULL;
+    }
+
+    if(paramType == OIC_REQUEST_BY_CLIENT)
+    {
+        RequestHandle *tempRequestHandle = requestHandleList->headerNode;
+        while(tempRequestHandle != NULL)
+        {
+            if((OCEntityHandlerRequest*)tempRequestHandle->requestHandle[paramType] == handle)
+            {
+                return tempRequestHandle;
+            }
+            tempRequestHandle = tempRequestHandle->next;
+        }
+    }
+    else
+    {
+        RequestHandle *tempRequestHandle = requestHandleList->headerNode;
+        while(tempRequestHandle != NULL)
+        {
+            if((OCDoHandle)tempRequestHandle->requestHandle[paramType] == handle)
+            {
+                return tempRequestHandle;
+            }
+            tempRequestHandle = tempRequestHandle->next;
+        }
+    }
+    return NULL;
+}
diff --git a/service/notification-manager/NotificationManager/src/resourceCoordinator_JNI.cpp b/service/notification-manager/NotificationManager/src/resourceCoordinator_JNI.cpp
new file mode 100644 (file)
index 0000000..7f30a1c
--- /dev/null
@@ -0,0 +1,152 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+extern "C" {
+#include "hosting.h"
+}
+#include "resourceCoordinator_JNI.h"
+#include "android_cpp11_compat.h"
+
+using namespace std;
+
+atomic_bool threadRun;
+thread ocProcessThread;
+/*
+ * To execute OCProcess when threadRun value is only true
+ */
+void ocProcessFunc()
+{
+    while (threadRun)
+    {
+
+        if (OCProcess() != OC_STACK_OK)
+        {
+            //OCProcess ERROR
+        }
+
+        sleep(2);
+    }
+}
+/*
+ * To callback log message from C++ to Java for android
+ */
+void messageCallback(JNIEnv *env, jobject obj, const char *c_str)
+{
+      jstring jstr = (env)->NewStringUTF(c_str);
+      jclass cls = env->GetObjectClass(obj);
+      jmethodID cbMessage = env->GetMethodID(cls, "cbMessage", "(Ljava/lang/String;)V");
+      env->CallVoidMethod(obj,cbMessage, jstr);
+}
+/*
+ *  for Hosting Device Side
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStart
+(JNIEnv *env, jobject obj)
+{
+    jint result = 0;
+    if(threadRun==true)
+    {
+
+        messageCallback(env,obj,"already execute OICCoordinatorStart");
+        result = (jint)HOSTING_THREAD_ERROR;
+        return result;
+    }
+    else
+    {
+        messageCallback(env,obj,"OICCoordinatorStart");
+        result = (jint)OICStartCoordinate();
+        string str = "OICStartCoordinate result : ";
+        string result_str = std::to_string(result);
+        str += result_str;
+        messageCallback(env,obj,str.c_str());
+        threadRun = true;
+        ocProcessThread = thread(ocProcessFunc);
+        return result;
+    }
+}
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStop
+(JNIEnv *env, jobject obj)
+{
+    messageCallback(env,obj,"OICCoordinatorStop");
+    jint result = 0;
+    //terminate Thread
+    if (ocProcessThread.joinable())
+    {
+        threadRun = false;
+        ocProcessThread.join();
+    }
+    else
+    {
+            messageCallback(env,obj,"The thread may be not running.");
+            result = (jint)HOSTING_THREAD_ERROR;
+            return result;
+    }
+    result = (jint)OICStopCoordinate();
+    string str = "OICStopCoordinate result : ";
+    string result_str = std::to_string(result);
+    str += result_str;
+    messageCallback(env,obj,str.c_str());
+    return result;
+}
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingInit
+(JNIEnv *env, jobject obj,jstring j_addr)
+{
+    messageCallback(env,obj,"ResourceHostingInit");
+    const char* addr = env->GetStringUTFChars(j_addr,NULL);
+
+    if (NULL == j_addr)
+        return (jint)OCSTACK_ERROR;
+
+    if(OCInit(addr,USE_RANDOM_PORT,OC_CLIENT_SERVER)!=OC_STACK_OK)
+    {
+        messageCallback(env,obj,"OCStack init Error");
+        return (jint)OCSTACK_ERROR;
+    }
+
+    env->ReleaseStringUTFChars(j_addr,addr);
+    return (jint)OCSTACK_OK;
+}
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingTerminate
+(JNIEnv *env, jobject obj)
+{
+    messageCallback(env,obj,"ResourceHostingTerminate");
+    if (OCStop() != OC_STACK_OK)
+    {
+
+        messageCallback(env,obj,"OCStack stop error");
+        return (jint)OCSTACK_ERROR;
+    }
+    //terminate Thread
+    if (ocProcessThread.joinable())
+    {
+        threadRun = false;
+        ocProcessThread.join();
+    }
+    else
+    {
+        messageCallback(env,obj,"The thread may be not running.");
+        return (jint)HOSTING_THREAD_ERROR;
+    }
+
+    return (jint)OCSTACK_OK;
+}
diff --git a/service/notification-manager/NotificationManager/src/resourceCoordinator_JNI.h b/service/notification-manager/NotificationManager/src/resourceCoordinator_JNI.h
new file mode 100644 (file)
index 0000000..cce1e35
--- /dev/null
@@ -0,0 +1,75 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#ifndef RESOURCECOORDINATOR_JNI_H_
+#define RESOURCECOORDINATOR_JNI_H_
+
+#include <jni.h>
+#include <thread>
+#include <atomic>
+#include <unistd.h>
+
+#define TAG "OIC-JNI"
+
+#define JNI_CURRENT_VERSION JNI_VERSION_1_6
+#define OCSTACK_OK  0
+#define OCSTACK_ERROR  255
+#define HOSTING_THREAD_ERROR  -2
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Class:     org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Method:    OICCoordinatorStart
+ * Signature: ()V
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStart
+(JNIEnv *, jobject);
+/*
+ * @Class:     org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * @Method:    OICCoordinatorStop
+ * @Signature: ()V
+ */
+
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_OICCoordinatorStop
+(JNIEnv *, jobject);
+/*
+ * Class:     org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Method:    ResourceHostingInit
+ * Signature: ()V
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingInit
+(JNIEnv *env, jobject obj,jstring j_addr);
+/*
+ * Class:     org_iotivity_service_resourcehostingsampleapp_ResourceHosting
+ * Method:    ResourceHostingTerminate
+ * Signature: (Ljava/lang/String;)V
+ */
+JNIEXPORT jint JNICALL Java_com_example_resourcehostingsampleapp_ResourceHosting_ResourceHostingTerminate
+(JNIEnv *env, jobject obj);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* RESOURCECOORDINATOR_JNI_H_ */
diff --git a/service/notification-manager/NotificationManager/src/virtualResource.c b/service/notification-manager/NotificationManager/src/virtualResource.c
new file mode 100644 (file)
index 0000000..9dae0b2
--- /dev/null
@@ -0,0 +1,406 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "virtualResource.h"
+
+
+MirrorResourceList *createMirrorResourceList()
+{
+    MirrorResourceList *mirrorResourceList = (MirrorResourceList *)malloc(sizeof(MirrorResourceList));
+    if (!mirrorResourceList)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Virtual Resource List Creation Fail.");
+    }
+    else
+    {
+        mirrorResourceList->headerNode = NULL;
+        mirrorResourceList->tailNode = NULL;
+    }
+
+    return mirrorResourceList;
+}
+
+MirrorResource *createMirrorResource()
+{
+    MirrorResource *mirrorResource = (MirrorResource*)malloc(sizeof(MirrorResource));
+    if (!mirrorResource)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Virtual Resource List Creation Fail.");
+    }
+    else
+    {
+        mirrorResource->resourceHandle[OIC_REQUEST_HANDLE] = NULL;
+        mirrorResource->resourceHandle[OIC_MIRROR_HANDLE] = NULL;
+        mirrorResource->address[OIC_SOURCE_ADDRESS]    = NULL;
+        mirrorResource->address[OIC_MIRROR_ADDRESS]   = NULL;
+
+        mirrorResource->rep    = NULL;
+        mirrorResource->uri    = NULL;
+        mirrorResource->next   = NULL;
+
+        mirrorResource->prop.countResourceType = 0;
+        mirrorResource->prop.resourceType = NULL;
+        mirrorResource->prop.countInterface = 0;
+        mirrorResource->prop.resourceInterfaceName = NULL;
+    }
+
+    return mirrorResource;
+}
+
+OCStackResult destroyMirrorResourceList(MirrorResourceList *mirrorResourceList)
+{
+    OC_LOG_V(DEBUG, VR_TAG,"enter destroyVirtualResourceList");
+    if(mirrorResourceList)
+    {
+        while (mirrorResourceList->headerNode)
+        {
+            deleteMirrorResourceFromList(mirrorResourceList, mirrorResourceList->headerNode);
+        }
+
+        free(mirrorResourceList);
+    }
+    else
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    return OC_STACK_OK;
+}
+
+OCStackResult destroyMirrorResource(MirrorResource *mirrorResource)
+{
+    OC_LOG_V(DEBUG, VR_TAG,"enter destroy virtual resource.");
+    if(mirrorResource)
+    {
+        if(mirrorResource->next)
+        {
+            mirrorResource->next = NULL;
+        }
+        if (mirrorResource->rep)
+        {
+            cJSON_Delete(mirrorResource->rep);
+        }
+        if (mirrorResource->uri)
+        {
+            free(mirrorResource->uri);
+        }
+        if (mirrorResource->address[OIC_SOURCE_ADDRESS])
+        {
+            free(mirrorResource->address[OIC_SOURCE_ADDRESS]);
+        }
+        if (mirrorResource->address[OIC_MIRROR_ADDRESS])
+        {
+            free(mirrorResource->address[OIC_MIRROR_ADDRESS]);
+        }
+        if (mirrorResource->prop.resourceType)
+        {
+            int i = 0;
+            for (i = 0; i < mirrorResource->prop.countResourceType; ++i)
+            {
+                free(mirrorResource->prop.resourceType[i]);
+                mirrorResource->prop.resourceType[i] = NULL;
+            }
+            free(mirrorResource->prop.resourceType);
+            mirrorResource->prop.countResourceType = 0;
+        }
+        if (mirrorResource->prop.resourceInterfaceName)
+        {
+            int i = 0;
+            for (i = 0; i < mirrorResource->prop.countInterface; ++i)
+            {
+                free(mirrorResource->prop.resourceInterfaceName[i]);
+                mirrorResource->prop.resourceInterfaceName[i] = NULL;
+            }
+            free(mirrorResource->prop.resourceInterfaceName);
+            mirrorResource->prop.countInterface = 0;
+        }
+        free(mirrorResource);
+    }
+    else
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    return OC_STACK_OK;
+}
+
+OCStackResult insertMirrorResource(MirrorResourceList *mirrorResourceList,
+                                   MirrorResource *mirrorResource)
+{
+    if (mirrorResourceList == NULL || mirrorResource == NULL)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if (mirrorResourceList->headerNode == NULL)
+    {
+        mirrorResourceList->headerNode = mirrorResource;
+        mirrorResourceList->tailNode = mirrorResource;
+    }
+    else
+    {
+        mirrorResourceList->tailNode->next = mirrorResource;
+        mirrorResourceList->tailNode = mirrorResource;
+    }
+
+    return OC_STACK_OK;
+}
+
+MirrorResource *findMirrorResourceUsingAddressAndURI(MirrorResourceList *mirrorResourceList,
+        const char *address, OICResourceCoordinatorParamType paramType, const char *uri)
+{
+    if (mirrorResourceList == NULL || address == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Find Virtual Resource : invalid parameter.");
+        return NULL;
+    }
+    if (mirrorResourceList->headerNode == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Find Virtual Resource : Empty Virtual Resource List.");
+        return NULL;
+    }
+
+    MirrorResource *tempMirrorResource = mirrorResourceList->headerNode;
+    while (tempMirrorResource != NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"node's uri = %s", tempMirrorResource->uri);
+        if (strcmp(tempMirrorResource->address[paramType], address) == 0) // if(It is Same)
+        {
+            if (strcmp(tempMirrorResource->uri, uri) == 0) // if(It is Same)
+            {
+                return tempMirrorResource;
+            }
+        }
+        tempMirrorResource = tempMirrorResource->next;
+    }
+
+    return NULL;
+}
+
+MirrorResource *findMirrorResourceUsingHandle(MirrorResourceList *mirrorResourceList,
+        OCResourceHandle handle, OICResourceCoordinatorParamType paramType)
+{
+    if (mirrorResourceList == NULL || handle == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Find Virtual Resource : invalid parameter.");
+        return NULL;
+    }
+    if (mirrorResourceList->headerNode == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Find Virtual Resource : Empty Virtual Resource List.");
+        return NULL;
+    }
+
+    MirrorResource *tempMirrorResource = mirrorResourceList->headerNode;
+    while (tempMirrorResource != NULL)
+    {
+        if (tempMirrorResource->resourceHandle[paramType] == handle)
+        {
+            return tempMirrorResource;
+        }
+        tempMirrorResource = tempMirrorResource->next;
+    }
+
+    return NULL;
+}
+
+OCStackResult deleteMirrorResourceFromList(MirrorResourceList *mirrorResourceList,
+        MirrorResource *mirrorResource)
+{
+
+    OC_LOG_V(DEBUG, VR_TAG,"enter delete virtual resource.");
+
+    if (mirrorResourceList == NULL || mirrorResource == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Delete Virtual Resource : invalid parameter.");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (mirrorResourceList->headerNode == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Delete Virtual Resource : Empty Virtual Resource List.");
+        return OC_STACK_ERROR;
+    }
+
+    if (mirrorResource == mirrorResourceList->headerNode)
+    {
+        mirrorResourceList->headerNode = mirrorResourceList->headerNode->next;
+        mirrorResource->next = NULL;
+        return destroyMirrorResource(mirrorResource);
+    }
+
+    MirrorResource *preNode = mirrorResourceList->headerNode;
+    MirrorResource *curNode = preNode->next;
+    while (curNode != NULL)
+    {
+        if (curNode == mirrorResource)
+        {
+            if (curNode == mirrorResourceList->tailNode)
+            {
+                mirrorResourceList->tailNode = preNode;
+                preNode->next = NULL;
+            }
+            else
+            {
+                preNode->next = curNode->next;
+            }
+            mirrorResource->next = NULL;
+            return destroyMirrorResource(mirrorResource);
+        }
+        preNode = curNode;
+        curNode = curNode->next;
+    }
+
+    return OC_STACK_ERROR;
+}
+
+OCStackResult ejectMirrorResource(MirrorResourceList *mirrorResourceList,
+                                  MirrorResource *mirrorResource)
+{
+    if (mirrorResourceList == NULL || mirrorResource == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Eject Virtual Resource : invalid parameter.");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (mirrorResourceList->headerNode == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG, "Eject Virtual Resource : Empty Virtual Resource List.");
+        return OC_STACK_ERROR;
+    }
+
+    if (mirrorResource == mirrorResourceList->headerNode)
+    {
+        mirrorResourceList->headerNode = mirrorResourceList->headerNode->next;
+        return OC_STACK_OK;
+    }
+
+    MirrorResource *preNode = mirrorResourceList->headerNode;
+    MirrorResource *curNode = preNode->next;
+    while (curNode != NULL)
+    {
+        if (curNode == mirrorResource)
+        {
+            if(curNode == mirrorResourceList->headerNode)
+            {
+                mirrorResourceList->headerNode = NULL;
+                mirrorResourceList->tailNode = NULL;
+            }
+            else if(curNode == mirrorResourceList->tailNode)
+            {
+                mirrorResourceList->tailNode = preNode;
+            }
+            else
+            {
+            preNode->next = curNode->next;
+            }
+            return OC_STACK_OK;
+        }
+        preNode = curNode;
+        curNode = curNode->next;
+    }
+
+    return OC_STACK_ERROR;
+
+}
+
+MirrorResource *cloneMirrorResource(MirrorResource *sourceMirrorResource)
+{
+    MirrorResource *clonedMirrorResource = createMirrorResource();
+
+    int sizeofstr = 0;
+    int i = 0;
+
+    clonedMirrorResource->rep = cJSON_Parse(cJSON_PrintUnformatted(sourceMirrorResource->rep));
+
+    sizeofstr = strlen(sourceMirrorResource->uri) + 1;
+    clonedMirrorResource->uri = (char *)malloc(sizeof(char) * sizeofstr);
+    memset(clonedMirrorResource->uri, '\0', sizeofstr);
+    strcpy(clonedMirrorResource->uri, sourceMirrorResource->uri);
+
+    for (i = OIC_SOURCE_ADDRESS; i < OIC_MIRROR_ADDRESS; ++i)
+    {
+        sizeofstr = strlen(sourceMirrorResource->address[i]) + 1;
+        clonedMirrorResource->address[i] = (char *)malloc(sizeof(char) * sizeofstr);
+        memset(clonedMirrorResource->address[i], '\0', sizeofstr);
+        strcpy(clonedMirrorResource->address[i], sourceMirrorResource->address[i]);
+    }
+
+    return clonedMirrorResource;
+}
+
+MirrorResourceList *findMirrorResourceListUsingAddress(MirrorResourceList *mirrorResourceList,
+        const char *address, OICResourceCoordinatorParamType paramType)
+{
+    if (mirrorResourceList == NULL || address == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Find Virtual Resource List : invalid parameter.");
+        return NULL;
+    }
+    if (mirrorResourceList->headerNode == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG,"Find Virtual Resource List : Empty Virtual Resource List.");
+        return NULL;
+    }
+
+    MirrorResource *tempNode = mirrorResourceList->headerNode;
+    while (tempNode != NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG, "uri = %s", tempNode->uri);
+        tempNode = tempNode->next;
+    }
+
+
+    MirrorResourceList *resultMirrorResourceList = createMirrorResourceList();
+    MirrorResource *mirrorResource = mirrorResourceList->headerNode;
+    while (mirrorResource != NULL)
+    {
+        if (strcmp(mirrorResource->address[paramType], address) == 0) // if(It is Same)
+        {
+            insertMirrorResource(resultMirrorResourceList, cloneMirrorResource(mirrorResource));
+        }
+        mirrorResource = mirrorResource->next;
+    }
+
+    return resultMirrorResourceList;
+}
+
+
+OCStackResult printMirrorResourceList(MirrorResourceList *mirrorResourceList)
+{
+    if (mirrorResourceList == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG, "print Virtual Resource list : invalid parameter.");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (mirrorResourceList->headerNode == NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG, "print Virtual Resource list : Empty Virtual Resource List.");
+        return OC_STACK_INVALID_PARAM;
+    }
+    OC_LOG_V(DEBUG, VR_TAG, "==============================================================");
+    MirrorResource *mirrorResource = mirrorResourceList->headerNode;
+    while (mirrorResource != NULL)
+    {
+        OC_LOG_V(DEBUG, VR_TAG, "uri = %s", mirrorResource->uri);
+        mirrorResource = mirrorResource->next;
+    }
+    OC_LOG_V(DEBUG, VR_TAG, "==============================================================");
+
+    return OC_STACK_OK;
+}
diff --git a/service/notification-manager/NotificationManager/src/virtualResource.h b/service/notification-manager/NotificationManager/src/virtualResource.h
new file mode 100644 (file)
index 0000000..44885ab
--- /dev/null
@@ -0,0 +1,302 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _VIRTUAL_RESOURCE_H_
+#define _VIRTUAL_RESOURCE_H_
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "ocstack.h"
+#include "logger.h"
+
+#include "cJSON.h"
+#define TAG  PCF("MirrorResource")
+//-----------------------------------------------------------------------------
+// Definition of Constant
+//-----------------------------------------------------------------------------
+#define VR_TAG "__NM__"
+#define RH_TAG "__RM__"
+
+//-----------------------------------------------------------------------------
+// Typedefs
+//-----------------------------------------------------------------------------
+
+/**
+* Resource Coordinating Parameter Type
+*/
+typedef enum
+{
+    /*
+     * for mirrorResourceHandle
+     */
+    OIC_SOURCE_ADDRESS  = 0,
+    OIC_MIRROR_ADDRESS  = 1,
+    OIC_REQUEST_HANDLE  = 0,
+    OIC_MIRROR_HANDLE       = 1,
+
+    /*
+     * for requestHandle
+     */
+    OIC_REQUEST_BY_CLIENT       = 0,
+    OIC_REQUEST_BY_COORDINATOR  = 1,
+
+    OIC_NONE                        = 255
+} OICResourceCoordinatorParamType;
+
+/**
+* Property of Mirror Resource
+*/
+typedef struct MirrorResourceProperty
+{
+    int countResourceType;
+    int countInterface;
+    char **resourceType;
+    char **resourceInterfaceName;
+} MirrorResourceProperty;
+
+/**
+* Mirror Resource Object
+*/
+typedef struct MirrorResource
+{
+    OCDoHandle resourceHandle[2];   // OIC_REQUEST_HANDLE = 0, OIC_VIRTUAL_HANDLE = 1
+    char *address[2];               // OIC_SOURCE_ADDRESS = 0, OIC_VIRTUAL_ADDRESS = 1
+    cJSON *rep;
+    char *uri;
+    MirrorResourceProperty prop;
+
+    struct MirrorResource *next;
+
+    /*
+     * for multiple resource
+     */
+//  virtualRepresentation rep2;
+
+} MirrorResource;
+
+/**
+* Mirror Resource List
+*/
+typedef struct MirrorResourceList
+{
+    struct MirrorResource *headerNode;
+    struct MirrorResource *tailNode;
+} MirrorResourceList;
+
+/**
+* Request Object
+*/
+typedef struct RequestHandle
+{
+    void *requestHandle[2];         // OIC_REQUEST_BY_CLIENT = 0, OIC_REQUEST_BY_COORDINATOR = 1
+    OCResourceHandle resourceHandle;
+    OCRequestHandle entityRequestHandle;
+
+    OCMethod method;
+
+    unsigned char isAliveCheck;
+
+    struct RequestHandle *next;
+} RequestHandle;
+
+/**
+* Request Object List
+*/
+typedef struct RequestHandleList
+{
+    struct RequestHandle *headerNode;
+    struct RequestHandle *tailNode;
+} RequestHandleList;
+
+//-----------------------------------------------------------------------------
+// Function prototypes for mirrorResourceHandle
+//-----------------------------------------------------------------------------
+
+/**
+* Create an empty mirror resource list
+*
+* @return
+*     pointer to empty Mirror resource list
+*/
+MirrorResourceList *createMirrorResourceList();
+
+/**
+* Create an empty mirror resource.
+*
+* @return
+*     pointer to empty mirror resource
+*/
+MirrorResource *createMirrorResource();
+
+/**
+* Insert the mirror resource in the mirror resource list
+*
+* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be inserted
+* @param mirrorResource - pointer to mirror resource list to be inserted
+* @return
+*     OIC_HOSTING_INVALID_PARAM - if list or vResource is null
+*     OIC_HOSTING_OK - successfully inserted
+*/
+OCStackResult insertMirrorResource(MirrorResourceList *mirrorResourceList,
+                                   MirrorResource *mirrorResource);
+
+/**
+* Delete the mirror resource from the mirror resource list
+*
+* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be deleted
+* @param mirrorResource - pointer to mirror resource list to be deleted
+* @return
+*     OIC_HOSTING_INVALID_PARAM - if mirrorResourceList or mirrorResource is null
+*     OIC_HOSTING_ERROR - mirror resource delete process error
+*     OIC_HOSTING_OK - successfully deleted
+*/
+OCStackResult deleteMirrorResourceFromList(MirrorResourceList *mirrorResourceList,
+        MirrorResource *mirrorResource);
+
+/**
+* Destroy mirror resource
+*
+* @param mirrorResource - pointer to mirror resource to be destroyed
+* @return
+*     OIC_HOSTING_INVALID_PARAM - if mirrorResource is null
+*     OIC_HOSTING_OK - successfully destroyed
+*/
+OCStackResult destroyMirrorResource(MirrorResource *mirrorResource);
+
+/**
+* Destroy mirror resource list
+*
+* @param mirrorResourceList - pointer to mirror resource list to be destroyed
+* @return
+*     OIC_HOSTING_INVALID_PARAM - if mirrorResourceList is null
+*     OIC_HOSTING_OK - successfully destroyed
+*/
+OCStackResult destroyMirrorResourceList(MirrorResourceList *mirrorResourceList);
+
+/**
+* Find mirror resource using handle
+*
+* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found
+* @param handle - handle value to be found
+* @param paramType - handle type to be found
+*
+* NOTE: every parameter(handle and type) will be compared
+*
+* @return
+*     pointer to the found mirror resource
+*     NULL - mirror resource not found
+*/
+MirrorResource *findMirrorResourceUsingHandle(MirrorResourceList *mirrorResourceList,
+        OCResourceHandle handle, OICResourceCoordinatorParamType paramType);
+
+/*
+ * find virtual resource using address function 사용하는지 확인 필요.
+ */
+//virtualResource *findvResourceUsingAddress(virtualResourceList *list,
+//        const char *Address, OICResourceHostingParamType type, const char *subData);
+
+/**
+* Find mirror resource using Address and URI
+*
+* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found
+* @param address - pointer to address to be found
+* @param paramType - address type to be found
+* @param uri - pointer to uri to be found
+*
+* NOTE: every parameter(address, type and uri) will be compared
+*
+* @return
+*     pointer to the found mirror resource
+*     NULL - invalid input parameter or mirror resource not found
+*/
+MirrorResource *findMirrorResourceUsingAddressAndURI(MirrorResourceList *mirrorResourceList,
+        const char *address, OICResourceCoordinatorParamType paramType, const char *uri);
+
+/**
+* Find mirror resource list using Address and Hosting Parameter Type
+*
+* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found
+* @param address - pointer to address to be found
+* @param paramType - address type to be found
+*
+* NOTE: every parameter(address, type and uri) will be compared
+*
+* @return
+*     pointer to the found mirror resource
+*     NULL - invalid input parameter or mirror resource list not found
+*/
+MirrorResourceList *findMirrorResourceListUsingAddress(MirrorResourceList *mirrorResourceList,
+        const char *address, OICResourceCoordinatorParamType paramType);
+
+/**
+* Copy mirror resource
+*
+* @param sourceMirrorResource - pointer to source mirror resource
+*
+* @return
+*     pointer to the copied mirror resource
+*/
+MirrorResource *cloneMirrorResource(MirrorResource *sourceMirrorResource);
+
+/**
+* Eject mirror resource from mirror resource list
+*
+* @param mirrorResourceList - pointer to the target mirror resource list that mirror resource will be found
+* @param mirrorResource - pointer to mirror resource to be ejected
+*
+* @return
+*     OIC_HOSTING_INVALID_PARAM - mirrorResourceList or mirrorResource is null
+*     OIC_HOSTING_OK - ejected successfully
+*     OIC_HOSTING_ERROR - cannot found mirror resource from mirrorResourceList same with mirrorResource
+*/
+OCStackResult ejectMirrorResource(MirrorResourceList *mirrorResourceList,
+                                  MirrorResource *mirrorResource);
+
+/**
+* Print mirror resources from mirror resource list
+*
+* @param mirrorResourceList - pointer to the mirror resource list that mirror resource will be printed
+*
+* @return
+*     OIC_HOSTING_INVALID_PARAM - mirrorResourceList is null or mirrorResourceList is empty
+*     OIC_HOSTING_OK - print successfully
+*/
+OCStackResult printMirrorResourceList(MirrorResourceList *mirrorResourceList);
+
+//-----------------------------------------------------------------------------
+// Function prototypes for RequestHandle
+//-----------------------------------------------------------------------------
+RequestHandleList *createRequestHandleList();
+RequestHandle *createRequestHandle();
+OCStackResult insertRequestHandle(RequestHandleList *requestHandleList,
+                                  RequestHandle *requestHandle);
+
+OCStackResult deleteRequestHandleFromList(RequestHandleList *requestHandleList,
+        RequestHandle *requestHandle);
+OCStackResult destroyRequestHandle(RequestHandle *requestHandle);
+
+OCStackResult destroyRequestHandleList(RequestHandleList *requestHandleList);
+
+RequestHandle *findRequestHandle(RequestHandleList *requestHandleList,
+                                 OCDoHandle handle, OICResourceCoordinatorParamType paramType);
+
+#endif //_MIRROR_RESOURCE_H_
index 4c5dd05..39c4eb5 100644 (file)
@@ -1,9 +1,38 @@
+#******************************************************************
+#
+# 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
 ##
 
 Import('env')
 
+if env.get('RELEASE'):
+       env.AppendUnique(CCFLAGS = ['-Os'])
+       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+       env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+       env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
 lib_env = env.Clone()
 SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
 notimgr_env = lib_env.Clone()
@@ -13,7 +42,9 @@ target_os = env.get('TARGET_OS')
 # Build flags
 ######################################################################
 notimgr_env.AppendUnique(CPPPATH = ['NotificationManager/include'])
-notimgr_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap'])
+notimgr_env.AppendUnique(CPPPATH = ['../../extlibs/cjson'])
+notimgr_env.AppendUnique(CPPPATH = ['../../resource/csdk/logger/include'])
+notimgr_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap'])
 
 if target_os not in ['windows', 'winrt']:
        notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
@@ -23,7 +54,7 @@ if target_os == 'linux':
 
 if target_os == 'android':
        notimgr_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       notimgr_env.AppendUnique(LIBS = ['gnustl_static'])
+       notimgr_env.AppendUnique(LIBS = ['gnustl_shared','log'])
 
        if not env.get('RELEASE'):
                notimgr_env.AppendUnique(LIBS = ['log'])
@@ -33,15 +64,20 @@ if target_os == 'android':
 ######################################################################
 NOTI_SRC_DIR = 'NotificationManager/src/'
 notimgr_src = [
-               NOTI_SRC_DIR + 'LinuxMain.cpp',
-               NOTI_SRC_DIR + 'NotificationManager.cpp',
-               NOTI_SRC_DIR + 'RegistrationManager.cpp',
-               NOTI_SRC_DIR + 'ResourceManager.cpp',
-               NOTI_SRC_DIR + 'VirtualRepresentation.cpp']
+        NOTI_SRC_DIR + 'hosting.c',
+        NOTI_SRC_DIR + 'requestHandler.c',
+        NOTI_SRC_DIR + 'virtualResource.c']
 
-notificationmanager = notimgr_env.Program('noti_manager', notimgr_src)
+if target_os == 'android':
+        notimgr_src.append(NOTI_SRC_DIR + 'resourceCoordinator_JNI.cpp')
+
+if target_os in ['tizen','android'] :
+    notificationsdk = notimgr_env.SharedLibrary('NotificationManager', notimgr_src)
+else :
+    notificationsdk = notimgr_env.StaticLibrary('NotificationManager', notimgr_src)
 
-notimgr_env.InstallTarget(notificationmanager, 'notificationmanager')
+notimgr_env.InstallTarget(notificationsdk, 'libResouceHosting')
 
 # Go to build sample apps
 SConscript('SampleApp/SConscript')
+
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/.classpath b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/.classpath
new file mode 100644 (file)
index 0000000..c2653d9
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="src" path="gen"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
+       <classpathentry kind="output" path="bin/classes"/>
+</classpath>
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/.project b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/.project
new file mode 100644 (file)
index 0000000..22c971c
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>ResourceHosting</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+       </natures>
+</projectDescription>
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/AndroidManifest.xml b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..31ac554
--- /dev/null
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.resourcehostingsampleapp"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="19" />
+    
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.INTERNET_ACCESS" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+    <uses-permission android:name="android.permission.GET_TASKS"/>
+    <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>
+    <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY"/>
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name="com.example.resourcehostingsampleapp.ResourceHosting"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/ic_launcher-web.png b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/ic_launcher-web.png
new file mode 100644 (file)
index 0000000..a18cbb4
Binary files /dev/null and b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/ic_launcher-web.png differ
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/Android.mk b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/Android.mk
new file mode 100644 (file)
index 0000000..f2f39d8
--- /dev/null
@@ -0,0 +1,31 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := ca
+LOCAL_SRC_FILES := ../libs/libconnectivity_abstraction.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc_logger_core
+LOCAL_SRC_FILES := ../libs/liboc_logger_core.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc_logger
+LOCAL_SRC_FILES := ../libs/liboc_logger.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := octbstack
+LOCAL_SRC_FILES := ../libs/liboctbstack.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc
+LOCAL_SRC_FILES := ../libs/liboc.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libNotificationManager
+LOCAL_SRC_FILES := ../libs/libNotificationManager.so
+include $(PREBUILT_SHARED_LIBRARY)
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/Application.mk b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/Application.mk
new file mode 100644 (file)
index 0000000..3baa444
--- /dev/null
@@ -0,0 +1,2 @@
+APP_STL:=gnustl_shared
+NDK_TOOLCHAIN_VERSION := 4.9
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/armeabi b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/armeabi
new file mode 100644 (file)
index 0000000..a2f1b66
Binary files /dev/null and b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/jni/armeabi differ
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/project.properties b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/project.properties
new file mode 100644 (file)
index 0000000..4ab1256
--- /dev/null
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-19
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-hdpi/ic_launcher.png b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-hdpi/ic_launcher.png differ
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-mdpi/ic_launcher.png b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..6ae570b
Binary files /dev/null and b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-mdpi/ic_launcher.png differ
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xhdpi/ic_launcher.png b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..d4fb7cd
Binary files /dev/null and b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xxhdpi/ic_launcher.png b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..85a6081
Binary files /dev/null and b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/layout/activity_main.xml b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..3cb37b5
--- /dev/null
@@ -0,0 +1,80 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical"
+    android:paddingBottom="5dp"
+    android:paddingLeft="10dp"
+    android:paddingRight="10dp"
+    android:paddingTop="10dp" >
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content" >
+        
+            <Button
+                android:id="@+id/btnStartHosting"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:text="startHosting"
+                android:textSize="18sp" />    
+    </LinearLayout>
+    
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content" >
+        
+            <Button
+                android:id="@+id/btnStopHosting"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:text="StopHosting"
+                android:textSize="18sp" />    
+    </LinearLayout>
+
+       
+       <Space
+               android:layout_width="match_parent"
+               android:layout_height="10dp" />
+
+       <LinearLayout
+           android:layout_width="match_parent"
+           android:layout_height="5dp"
+           android:orientation="vertical"
+           android:background="#111111" >
+       </LinearLayout>
+
+       <Space
+           android:layout_width="match_parent"
+           android:layout_height="5dp" />
+      
+       <LinearLayout
+           android:layout_width="match_parent"
+           android:layout_height="wrap_content"
+           android:orientation="vertical"
+           android:paddingTop="0dp" >
+
+               <Button
+                   android:id="@+id/btLogClear"
+                   android:layout_width="match_parent"
+                   android:layout_height="wrap_content"
+                   android:text="CLEAR LOG"
+                   android:textSize="18sp" />
+
+               <ScrollView
+                   android:id="@+id/sclLog"
+                   android:layout_width="match_parent"
+                   android:layout_height="match_parent" >
+                       
+                       <TextView
+                           android:id="@+id/txtLog"
+                           android:layout_width="match_parent"
+                           android:layout_height="match_parent"
+                           android:layout_alignParentBottom="true"
+                           android:layout_alignParentLeft="true"
+                           android:textSize="15sp" />
+          
+               </ScrollView>
+       
+       </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values-v11/styles.xml b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..3c02242
--- /dev/null
@@ -0,0 +1,11 @@
+<resources>
+
+    <!--
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+        <!-- API 11 theme customizations can go here. -->
+    </style>
+
+</resources>
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values-v14/styles.xml b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..a91fd03
--- /dev/null
@@ -0,0 +1,12 @@
+<resources>
+
+    <!--
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+        <!-- API 14 theme customizations can go here. -->
+    </style>
+
+</resources>
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values/strings.xml b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values/strings.xml
new file mode 100644 (file)
index 0000000..9ac731d
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="app_name">ResourceHostingSampleApp</string>
+    <string name="hello_world">Hello world!</string>
+
+</resources>
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values/styles.xml b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/res/values/styles.xml
new file mode 100644 (file)
index 0000000..6ce89c7
--- /dev/null
@@ -0,0 +1,20 @@
+<resources>
+
+    <!--
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!--
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        -->
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+    </style>
+
+</resources>
diff --git a/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/src/com/example/resourcehostingsampleapp/ResourceHosting.java b/service/notification-manager/SampleApp/android/ResourceHostingSampleApp/src/com/example/resourcehostingsampleapp/ResourceHosting.java
new file mode 100644 (file)
index 0000000..53576c2
--- /dev/null
@@ -0,0 +1,289 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+package com.example.resourcehostingsampleapp;
+
+import java.net.Inet4Address;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.Enumeration;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.TextView;
+import android.widget.Toast;
+
+/**
+ * To execute resource hosting function for android sample application .
+ * @author Copyright 2015 Samsung Electronics All Rights Reserved.
+ * @see className class :   ResourceHosting</br>
+ *
+ */
+
+public class ResourceHosting extends Activity implements OnClickListener
+{
+        private final int OCSTACK_OK = 0;
+        private final int OCSTACK_ERROR = 255;
+        private final int RESOURCEHOSTING_DO_NOT_THREADRUNNING = -2;
+
+        private String TAG = "ResourceHosting";
+        private OcResourceHandle mResourceHandle;
+        private String  mIpAddress;
+        private TextView mLogTextView;
+        private String mLog = "";
+        /**
+         * To initialize UI Function Setting.
+         * @see Class   class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method : onCreate</br>
+         */
+        protected void onCreate(Bundle savedInstanceState)
+        {
+            super.onCreate(savedInstanceState);
+            setContentView(R.layout.activity_main);
+            mLogTextView = (TextView) findViewById(R.id.txtLog);
+            findViewById(R.id.btnStartHosting).setOnClickListener(this);
+            findViewById(R.id.btnStopHosting).setOnClickListener(this);
+            findViewById(R.id.btLogClear).setOnClickListener(this);
+
+            PlatformConfig platformConfigObj;
+
+            platformConfigObj = new PlatformConfig(this,ServiceType.IN_PROC,
+                    ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+
+            Log.i(TAG, "Before Calling Configure of ocPlatform");
+            OcPlatform.Configure(platformConfigObj);
+            Log.i(TAG, "Configuration done Successfully");
+        }
+
+        /**
+         * To execute initOICStack for running Resource hosting.
+         * @see Class   class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method : onStart</br>
+         */
+        @Override
+        protected void onStart()
+        {
+            super.onStart();
+            initOICStack();
+        }
+
+        /**
+         * To terminate Resource hosting.
+         * @see Class   class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method : onStop</br>
+         */
+        @Override
+        protected void onStop()
+        {
+            super.onStop();
+            int result;
+            result = ResourceHostingTerminate();
+            Log.d(TAG, "ResourceHostingTerminate : "+ result);
+        }
+
+        protected void onResume()
+        {
+            super.onResume();
+        }
+
+        /**
+         * To execute initOICStack for running Resource hosting.
+         * @see Class   class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method : onRestart</br>
+         */
+        @Override
+        protected void onRestart()
+        {
+            super.onRestart();
+            initOICStack();
+        }
+
+        /**
+         * @see Class   class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method : onDestroy</br>
+         */
+        protected void onDestroy()
+        {
+            super.onDestroy();
+        }
+
+        /**
+         * get IpAddress and execute resourceHostingInit() method.
+         * @see Class   class : com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method : initOICStack</br>
+         */
+        private void initOICStack()
+        {
+            try
+            {
+                mIpAddress = getIpAddress();
+                int result;
+                result = ResourceHostingInit(mIpAddress);
+                Log.d(TAG, "ResourceHostingInit : " + result);
+            }
+            catch (Exception e)
+            {
+                e.printStackTrace();
+            }
+        }
+
+        /**
+         * @see Class   class :  com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method :  getIpAddress</br>
+         */
+        private String getIpAddress()
+        {
+            try
+            {
+                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
+                     en.hasMoreElements();)
+                {
+                    NetworkInterface intf = (NetworkInterface) en.nextElement();
+                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
+                    {
+                        InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
+                        if (!inetAddress.isLoopbackAddress())
+                        {
+                            if (inetAddress instanceof Inet4Address)
+                                return inetAddress.getHostAddress().toString();
+                        }
+                    }
+                }
+            }
+            catch (SocketException e)
+            {
+                e.printStackTrace();
+            }
+            return null;
+        }
+
+        /**
+         * @see Class  class :   com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method method :   onClick</br>
+         * @param v view to choice
+         */
+        public void onClick(View v)
+        {
+            int getId = v.getId();
+
+            switch (getId)
+            {
+                case R.id.btnStartHosting:
+                    try
+                    {
+                        int result;
+                        result = OICCoordinatorStart();
+                        Log.d(TAG, "OICCoordinatorStart : " + result);
+                    }
+                    catch (Exception e)
+                    {
+                        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
+                    }
+                    break;
+                case R.id.btnStopHosting:
+                    int result;
+                    result = OICCoordinatorStop();
+                    Log.d(TAG, "OICCoordinatorStop : "+ result);
+                    break;
+                case R.id.btLogClear:
+                    clearLog();
+                default:
+                    break;
+            }
+        }
+
+        /**
+         * all clear log view
+         * @see Class   class :  com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method :  clearLog</br>
+         */
+        private void clearLog()
+        {
+            mLog = "";
+            mLogTextView.setText(mLog);
+        }
+
+        /**
+         * recieve the callback log message.
+         * @see Class   class :  com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method :  cbMessage</br>
+         * @param msg callback log message
+         */
+        public void cbMessage(String msg)
+        {
+            mLog += msg + "\n";
+            mLogTextView.setText(mLog);
+        }
+
+        /**
+         * jni function - OicCorrdinatorstart() method.
+         * @see Class   class :    com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method :  OICCoordinatorStart</br>
+         * @see Signature signature : ()V</br>
+         */
+        public native int OICCoordinatorStart();
+
+        /**
+         * jni function - OICCoordinatorStop() method.
+         * @see Class   class :  com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method :  OICCoordinatorStop</br>
+         * @see signature  signature : ()V</br>
+         */
+        public native int OICCoordinatorStop();
+
+        /**
+         * jni function - ResourceHostingInit() method in order to execute OICCoordinatorStart() method.
+         * @see Class   class :  com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method :  ResourceHostingInit</br>
+         * @param addr ipAddress
+         * @see signature signature : (Ljava/lang/String;)V</br>
+         */
+        public native int ResourceHostingInit(String addr);
+
+        /**
+         * jni function - ResourceHostingTerminate() method in order to terminate resource hosting
+         * @see Class   class  : com_example_resourcehostingsampleapp_ResourceHosting</br>
+         * @see Method  method : ResourceHostingTerminate</br>
+         * @see signature signature : ()V</br>
+         */
+        public native int ResourceHostingTerminate();
+
+    static
+    {
+        System.loadLibrary("gnustl_shared");
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("connectivity_abstraction");
+        System.loadLibrary("ca-interface");
+        System.loadLibrary("octbstack");
+        System.loadLibrary("oc");
+        System.loadLibrary("ocstack-jni");
+        System.loadLibrary("NotificationManager");
+    }
+}
diff --git a/service/notification-manager/SampleApp/android/SampleConsumer/.classpath b/service/notification-manager/SampleApp/android/SampleConsumer/.classpath
new file mode 100644 (file)
index 0000000..e262cf6
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="src" path="gen"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
+       <classpathentry kind="output" path="bin/classes"/>
+</classpath>
diff --git a/service/notification-manager/SampleApp/android/SampleConsumer/.project b/service/notification-manager/SampleApp/android/SampleConsumer/.project
new file mode 100644 (file)
index 0000000..3684f99
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>SampleConsumer</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+       </natures>
+</projectDescription>
diff --git a/service/notification-manager/SampleApp/android/SampleConsumer/AndroidManifest.xml b/service/notification-manager/SampleApp/android/SampleConsumer/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..2a74ea8
--- /dev/null
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.sec.android.iot.sampleconsumer"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />
+    
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+    <uses-permission android:name="android.permission.GET_TASKS"/>
+    <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>
+    <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY"/>
+
+    <application android:label="@string/app_name" >
+        <activity
+            android:name="com.example.sample.consumer.SampleConsumer"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/SampleConsumer/project.properties b/service/notification-manager/SampleApp/android/SampleConsumer/project.properties
new file mode 100644 (file)
index 0000000..4ab1256
--- /dev/null
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-19
diff --git a/service/notification-manager/SampleApp/android/SampleConsumer/res/layout/sampleconsumer_layout.xml b/service/notification-manager/SampleApp/android/SampleConsumer/res/layout/sampleconsumer_layout.xml
new file mode 100644 (file)
index 0000000..1fa4751
--- /dev/null
@@ -0,0 +1,156 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical"
+    android:paddingBottom="5dp"
+    android:paddingLeft="10dp"
+    android:paddingRight="10dp"
+    android:paddingTop="10dp" >
+
+    <LinearLayout
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:orientation="vertical" >
+
+        <TextView
+            android:id="@+id/tv_found_resource"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:text="@string/found_resource"
+            android:textAppearance="?android:attr/textAppearanceLarge" />
+
+       <TextView
+            android:id="@+id/tv_found_resource_result"
+            android:layout_width="200dp"
+            android:layout_height="wrap_content"
+            android:layout_below="@+id/tv_found_resource"
+            android:hint="@string/none" />
+
+        <LinearLayout
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal" >
+
+            <Button
+                android:id="@+id/btn_observe"
+                android:layout_width="60dp"
+                android:layout_height="50dp"
+                android:layout_below="@+id/tv_found_resource_result"
+                android:layout_marginLeft="5dp"
+                android:layout_marginTop="5dp"
+                android:text="@string/observe"
+                android:textSize="12sp" />
+
+            <Button
+                android:id="@+id/btn_get"
+                android:layout_width="60dp"
+                android:layout_height="50dp"
+                android:layout_alignBottom="@+id/btn_observe"
+                android:layout_below="@+id/tv_found_resource_result"
+                android:layout_marginLeft="5dp"
+                android:layout_marginTop="5dp"
+                android:text="@string/get"
+                android:textSize="12sp" />
+
+            <Button
+                android:id="@+id/btn_put"
+                android:layout_width="60dp"
+                android:layout_height="50dp"
+                android:layout_alignBottom="@+id/btn_observe"
+                android:layout_below="@+id/tv_found_resource_result"
+                android:layout_marginLeft="5dp"
+                android:layout_marginTop="5dp"
+                android:text="@string/put"
+                android:textSize="12sp" />
+
+            <Button
+                android:id="@+id/btn_post"
+                android:layout_width="60dp"
+                android:layout_height="50dp"
+                android:layout_alignBottom="@+id/btn_observe"
+                android:layout_below="@+id/tv_found_resource_result"
+                android:layout_marginLeft="5dp"
+                android:layout_marginTop="5dp"
+                android:text="@string/post"
+                android:textSize="12sp" />
+
+            <Button
+                android:id="@+id/btn_delete"
+                android:layout_width="60dp"
+                android:layout_height="50dp"
+                android:layout_alignBottom="@+id/btn_observe"
+                android:layout_below="@+id/tv_found_resource_result"
+                android:layout_marginLeft="5dp"
+                android:layout_marginTop="5dp"
+                android:text="@string/delete"
+                android:textSize="12sp" />
+        </LinearLayout>
+
+        <TextView
+            android:id="@+id/tv_selected_method_type"
+            android:layout_width="200dp"
+            android:layout_height="wrap_content"
+            android:layout_below="@+id/btn_observe"
+            android:layout_marginTop="10dp"
+            android:hint="@string/select_method_type" />
+
+        <TextView
+            android:id="@+id/tv_receive"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_alignParentLeft="true"
+            android:layout_below="@+id/tv_selected_method_type"
+            android:layout_marginLeft="10dp"
+            android:layout_marginTop="10dp"
+            android:text="@string/received"
+            android:textAppearance="?android:attr/textAppearanceLarge" />
+
+        <TextView
+            android:id="@+id/tv_receive_result"
+            android:layout_width="200dp"
+            android:layout_height="wrap_content"
+            android:layout_alignParentLeft="true"
+            android:layout_below="@+id/tv_receive"
+            android:layout_marginLeft="10dp"
+            android:layout_marginTop="10dp"
+            android:hint="@string/none" />
+
+        <LinearLayout
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal" >
+
+            <LinearLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="vertical">
+
+                <Button
+                    android:id="@+id/btn_clean"
+                    android:layout_width="fill_parent"
+                    android:layout_height="wrap_content"
+                    android:text="@string/clean"
+                    android:textSize="18sp" />
+
+                <ScrollView
+                    android:id="@+id/sclLog"
+                    android:layout_width="match_parent"
+                    android:layout_height="0dp"
+                    android:layout_weight="1"
+                    android:fillViewport="true"
+                    >
+
+                    <TextView
+                        android:id="@+id/tv_current_log_result"
+                        android:layout_width="match_parent"
+                        android:layout_height="wrap_content"
+                        android:gravity="bottom"
+                        android:text="@string/current_log"
+                        android:textSize="15sp" />
+                </ScrollView>
+            </LinearLayout>
+        </LinearLayout> 
+ -
+    </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/SampleConsumer/res/values/strings.xml b/service/notification-manager/SampleApp/android/SampleConsumer/res/values/strings.xml
new file mode 100644 (file)
index 0000000..eb7743b
--- /dev/null
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">SampleConsumer</string>
+    <string name="observe">Obv</string>
+    <string name="get">Get</string>
+    <string name="put">Put</string>
+    <string name="post">Post</string>
+    <string name="delete">Del</string>
+    <string name="select_method_type">Select Method Type</string>
+    <string name="received">Received</string>
+    <string name="current_log">Current Log</string>
+    <string name="none">None</string>
+    <string name="quit">Quit</string>
+    <string name="clean">Clear Log</string>
+    <string name="found_resource">Found Resource</string>
+</resources>
diff --git a/service/notification-manager/SampleApp/android/SampleConsumer/src/com/example/sample/consumer/SampleConsumer.java b/service/notification-manager/SampleApp/android/SampleConsumer/src/com/example/sample/consumer/SampleConsumer.java
new file mode 100644 (file)
index 0000000..b24ab35
--- /dev/null
@@ -0,0 +1,587 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+package com.example.sample.consumer;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResource.OnDeleteListener;
+import org.iotivity.base.OcResource.OnGetListener;
+import org.iotivity.base.OcResource.OnObserveListener;
+import org.iotivity.base.OcResource.OnPutListener;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import com.sec.android.iot.sampleconsumer.R;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+public class SampleConsumer extends Activity implements View.OnClickListener,
+    OcPlatform.OnResourceFoundListener, OnGetListener, OnDeleteListener,
+    OnObserveListener, OnPutListener
+{
+        private final String TAG = "sample_consumer";
+
+        public static final int OC_STACK_OK = 0;
+        public static final String OBSERVE = "Observe";
+        public static final String GET = "Get";
+        public static final String PUT = "Put";
+        public static final String DELETE = "Delete";
+        public static final String POST = "Post";
+        public static final String MESSAGE = "message";
+        public static String outputString = "";
+
+        private Button btn_observe;
+        private Button btn_get;
+        private Button btn_put;
+        private Button btn_post;
+        private Button btn_delete;
+        private Button btn_clean;
+
+        public TextView tv_found_uri;
+        public TextView tv_select_method_type;
+        public TextView tv_receive_result;
+        public TextView tv_current_log_result;
+
+        public String current_log_result = "";
+        public String found_uri = "";
+        public String select_method_type = "";
+        public String receive_result = "";
+
+        public static OcResource curResource;
+        public OcPlatform.OnResourceFoundListener OnResourceFoundListener;
+
+        public static int oc = 0;
+        /*
+         * To initialize UI Function Setting
+         * To execute initOICStack for running find resource
+         */
+        @Override
+        public void onCreate(Bundle savedInstanceState)
+        {
+            super.onCreate(savedInstanceState);
+
+            setContentView(R.layout.sampleconsumer_layout);
+
+            btn_observe = (Button) findViewById(R.id.btn_observe);
+            btn_get = (Button) findViewById(R.id.btn_get);
+            btn_put = (Button) findViewById(R.id.btn_put);
+            btn_post = (Button) findViewById(R.id.btn_post);
+            btn_delete = (Button) findViewById(R.id.btn_delete);
+            btn_clean = (Button) findViewById(R.id.btn_clean);
+            tv_found_uri = (TextView) findViewById(R.id.tv_found_resource_result);
+            tv_select_method_type = (TextView) findViewById(R.id.tv_selected_method_type);
+            tv_receive_result = (TextView) findViewById(R.id.tv_receive_result);
+            tv_current_log_result = (TextView) findViewById(R.id.tv_current_log_result);
+            btn_observe.setOnClickListener(this);
+            btn_get.setOnClickListener(this);
+            btn_put.setOnClickListener(this);
+            btn_post.setOnClickListener(this);
+            btn_delete.setOnClickListener(this);
+            btn_clean.setOnClickListener(this);
+
+            initOICStack();
+        }
+
+        @Override
+        protected void onDestroy()
+        {
+            super.onDestroy();
+            onStop();
+        }
+        /*
+         * To reset text String is null for cleaning log
+         *
+         */
+        @Override
+        protected void onStop()
+        {
+            super.onStop();
+
+            tv_found_uri = null;
+            tv_select_method_type = null;
+            tv_receive_result = null;
+            tv_current_log_result = null;
+
+            current_log_result = "";
+            found_uri = "";
+            select_method_type = "";
+            receive_result = "";
+            btn_observe.setClickable(true);
+            btn_get.setClickable(true);
+            btn_put.setClickable(true);
+            btn_delete.setClickable(true);
+        }
+
+        public void cleanLogString()
+        {
+            current_log_result = "";
+            found_uri = "";
+            select_method_type = "";
+            receive_result = "";
+
+            tv_current_log_result.setText(current_log_result);
+            tv_found_uri.setText(found_uri);
+            tv_select_method_type.setText(select_method_type);
+            tv_receive_result.setText(receive_result);
+        }
+
+        public void initOICStack()
+        {
+            PlatformConfig cfg = new PlatformConfig(this,ServiceType.IN_PROC,
+                                                    ModeType.CLIENT, "0.0.0.0", 0, QualityOfService.LOW);
+            OcPlatform.Configure(cfg);
+            current_log_result += "Created Platform...\n";
+            tv_current_log_result.setText(current_log_result);
+            findResourceCandidate();
+            PRINT();
+        }
+
+        public void findResourceCandidate()
+        {
+            nmfindResource("", "/oc/core?rt=Resource.Hosting");
+            current_log_result += "Finding Resource... \n";
+            tv_current_log_result.setText(current_log_result);
+        }
+
+        public void nmfindResource(String host, String resourceName)
+        {
+            try
+            {
+                OcPlatform.findResource(host, resourceName, OcConnectivityType.ALL,this);
+
+            }
+            catch (OcException e)
+            {
+                e.printStackTrace();
+                current_log_result += e.getMessage() + "\n";
+                tv_current_log_result.setText(current_log_result);
+            }
+        }
+
+        /*
+         * No Use until Yet
+         */
+        public void getRepresentation(OcResource resource)
+        {
+            if (resource != null)
+            {
+                current_log_result += "Getting Light Representation...\n";
+                tv_current_log_result.setText(current_log_result);
+            }
+        }
+
+        /*
+         * No Use until Yet
+         */
+        public void getLightRepresentation(OcResource resource)
+        {
+            if (resource != null)
+            {
+                current_log_result += "Getting Light Representation...\n";
+                tv_current_log_result.setText(current_log_result);
+
+                try
+                {
+                    Map<String, String> queryParamsMap = new HashMap<String, String>();
+                    resource.get(queryParamsMap, this);
+                }
+                catch (OcException e)
+                {
+                    e.printStackTrace();
+                    current_log_result += e.getMessage() + "\n";
+                    tv_current_log_result.setText(current_log_result);
+                }
+            }
+        }
+
+        public void PRINT()
+        {
+            current_log_result += "********************************************\n";
+            current_log_result += "*  method Type : 1 - Observe               *\n";
+            current_log_result += "*  method Type : 2 - Get                   *\n";
+            current_log_result += "*  method Type : 3 - Put                   *\n";
+            current_log_result += "*  method Type : 4 - Delete                *\n";
+            current_log_result += "********************************************\n";
+        }
+
+        public void startObserve(OcResource resource)
+        {
+            if (resource != null)
+            {
+                Map<String, String> queryParamsMap = new HashMap<String, String>();
+                current_log_result += "startObserve\n";
+                tv_current_log_result.setText(current_log_result);
+
+                try
+                {
+                    resource.observe(ObserveType.OBSERVE, queryParamsMap, this);
+                }
+                catch (OcException e)
+                {
+                    e.printStackTrace();
+                    current_log_result += e.getMessage() + "\n";
+                    tv_current_log_result.setText(current_log_result);
+                }
+            }
+        }
+
+        public void startGet(OcResource resource)
+        {
+            if (resource != null)
+            {
+                Map<String, String> queryParamsMap = new HashMap<String, String>();
+                current_log_result += "startGet\n";
+                tv_current_log_result.setText(current_log_result);
+
+                try
+                {
+                    resource.get(queryParamsMap, this);
+                }
+                catch (OcException e)
+                {
+                    e.printStackTrace();
+                    current_log_result += e.getMessage() + "\n";
+                    tv_current_log_result.setText(current_log_result);
+                }
+            }
+        }
+
+        public void startPut(OcResource resource)
+        {
+            if (resource != null)
+            {
+                curResource = resource;
+                OcRepresentation rep = new OcRepresentation();
+                rep.setValueInt("temperature", 25);
+                rep.setValueInt("humidity", 10);
+                Map<String, String> queryParamsMap = new HashMap<String, String>();
+                current_log_result += "startPut\n";
+                tv_current_log_result.setText(current_log_result);
+
+                try
+                {
+                    resource.put(rep, queryParamsMap, this);
+                }
+                catch (OcException e)
+                {
+                    e.printStackTrace();
+                    current_log_result += e.getMessage() + "\n";
+                    tv_current_log_result.setText(current_log_result);
+                }
+            }
+        }
+
+        public void startDelete(OcResource resource) throws OcException
+        {
+            curResource = resource;
+            if (resource != null)
+            {
+                resource.deleteResource(this);
+            }
+        }
+
+        @Override
+        public void onClick(View v)
+        {
+            switch (v.getId())
+            {
+                case R.id.btn_observe:
+                    tv_select_method_type.setText(OBSERVE);
+                    startObserve(curResource);
+                    btn_observe.setClickable(false);
+                    break;
+                case R.id.btn_get:
+                    tv_select_method_type.setText(GET);
+                    startGet(curResource);
+                    btn_get.setClickable(false);
+                    break;
+                case R.id.btn_put:
+                    tv_select_method_type.setText(PUT);
+                    startPut(curResource);
+                    btn_put.setClickable(false);
+                    break;
+                case R.id.btn_post:
+                    tv_select_method_type.setText(POST);
+                    Toast.makeText(this, "Not Supported Yet", Toast.LENGTH_SHORT)
+                    .show();
+                    break;
+                case R.id.btn_delete:
+                    tv_select_method_type.setText(DELETE);
+                try {
+                    startDelete(curResource);
+                } catch (OcException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+                    btn_delete.setClickable(false);
+                    break;
+                case R.id.btn_clean:
+                    cleanLogString();
+                    break;
+
+                default:
+                    break;
+            }
+
+        }
+
+        protected static int observe_count()
+        {
+            return ++oc;
+        }
+
+        public void viewText()
+        {
+            SampleConsumer.this.runOnUiThread(new Runnable()
+            {
+                public void run()
+                {
+                    if (receive_result != null)
+                    {
+                        tv_receive_result.setText(receive_result);
+                    }
+                    if (found_uri != null)
+                    {
+                        tv_found_uri.setText(found_uri);
+                    }
+                    if (current_log_result != null)
+                    {
+                        tv_current_log_result.setText(current_log_result);
+                    }
+
+                }
+            });
+        }
+
+        @Override
+        public synchronized void onResourceFound(OcResource resource)
+        {
+            // synchronized (this) {
+            receive_result = "FoundResource";
+            String resourceURI;
+            String hostAddress;
+            if (SampleConsumer.curResource != null)
+            {
+                current_log_result += "Found another resource, ignoring\n";
+            }
+            if (resource != null)
+            {
+                if (resource.getUri().equals("/a/TempHumSensor"))
+                {
+                    current_log_result += "==============================\n";
+                    current_log_result += "DISCOVERED Resource(Consumer):\n";
+                    resourceURI = resource.getUri();
+                    hostAddress = resource.getHost();
+                    current_log_result += "URI of the resource: " + resourceURI
+                                          + "\n";
+                    current_log_result += "Host address of the resource: "
+                                          + hostAddress + "\n";
+                    SampleConsumer.curResource = resource;
+                }
+                else
+                {
+                    current_log_result += "Uri is not correct.";
+                }
+            }
+            else
+            {
+                current_log_result += "Resource is invalid\n";
+            }
+
+            viewText();
+        }
+
+        public String getCurrent_log_result()
+        {
+            return current_log_result;
+        }
+
+        public void setCurrent_log_result(String current_log_result)
+        {
+            this.current_log_result = current_log_result;
+        }
+
+        public String getFound_uri()
+        {
+            return found_uri;
+        }
+
+        public void setFound_uri(String found_uri)
+        {
+            this.found_uri = found_uri;
+        }
+
+        public String getSelect_method_type()
+        {
+            return select_method_type;
+        }
+
+        public void setSelect_method_type(String select_method_type)
+        {
+            this.select_method_type = select_method_type;
+        }
+
+        public String getReceive_result()
+        {
+            return receive_result;
+        }
+
+        public void setReceive_result(String recieve_result)
+        {
+            this.receive_result = recieve_result;
+        }
+        public class MessageReceiver extends BroadcastReceiver
+        {
+                @Override
+                public void onReceive(Context context, Intent intent)
+                {
+                    final String message = intent
+                                           .getStringExtra(MESSAGE);
+                    tv_current_log_result.setText(message);
+                    viewText();
+                }
+        }
+
+        @Override
+        public void onGetCompleted(List<OcHeaderOption> options,
+                                   OcRepresentation rep)
+        {
+            setReceive_result("onGet");
+            setCurrent_log_result(getCurrent_log_result()
+                                  + "GET request was successful\n"
+                                  + "GET request was successful\n"
+                                  + "URI: " + rep.getUri() + "\n"
+                                  + "Temperature: " + rep.getValueInt("temperature") + "\n"
+                                  + "Humidity: " + rep.getValueInt("humidity") + "\n");
+            viewText();
+            btn_get.setClickable(true);
+        }
+
+        @Override
+        public void onPutCompleted(List<OcHeaderOption> options,
+                                   OcRepresentation rep)
+        {
+            setReceive_result("onPut");
+            current_log_result += "PUT request was successful\n";
+
+            int humidity;
+            int temperature;
+            humidity = rep.getValueInt("humidity");
+            temperature = rep.getValueInt("temperature");
+
+            setCurrent_log_result(getCurrent_log_result() + "temperature: "
+                                  + temperature + "\n");
+            setCurrent_log_result(getCurrent_log_result() + "humidity: " + humidity
+                                  + "\n");
+            viewText();
+            btn_put.setClickable(true);
+        }
+
+        @Override
+        public void onObserveCompleted(List<OcHeaderOption> options,
+                                       OcRepresentation rep, int seqNum)
+        {
+            setReceive_result("onObserve");
+            setCurrent_log_result(getCurrent_log_result() + "SequenceNumber : "
+                                  + seqNum + "\n");
+            setCurrent_log_result("========================================================\n"
+                                  + "Receive OBSERVE RESULT:\n"
+                                  + "URI: "
+                                  + rep.getUri()
+                                  + "\n"
+                                  + "SequenceNumber: "
+                                  + seqNum
+                                  + "\n"
+                                  + "Temperature: "
+                                  + rep.getValueInt("temperature")
+                                  + "\n"
+                                  + "Humidity: "
+                                  + rep.getValueInt("humidity") + "\n");
+            if (SampleConsumer.observe_count() > 30)
+            {
+                setCurrent_log_result(getCurrent_log_result()
+                                      + "Cancelling Observe...\n");
+                try
+                {
+                    SampleConsumer.curResource.cancelObserve();
+                }
+                catch (OcException e)
+                {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                    setCurrent_log_result(getCurrent_log_result()
+                                          + "Cancel result :" + e.getMessage() + "\n");
+                }
+            }
+            viewText();
+        }
+
+        @Override
+        public void onDeleteCompleted(List<OcHeaderOption> options)
+        {
+            setReceive_result("onDelete");
+            viewText();
+            btn_delete.setClickable(true);
+        }
+
+        @Override
+        public void onPutFailed(Throwable arg0) {
+            // TODO Auto-generated method stub
+
+        }
+
+        @Override
+        public void onObserveFailed(Throwable arg0) {
+            // TODO Auto-generated method stub
+
+        }
+
+        @Override
+        public void onDeleteFailed(Throwable arg0) {
+            // TODO Auto-generated method stub
+
+        }
+
+        @Override
+        public void onGetFailed(Throwable arg0) {
+            // TODO Auto-generated method stub
+
+        }
+}
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/.classpath b/service/notification-manager/SampleApp/android/SampleProviderApp/.classpath
new file mode 100644 (file)
index 0000000..31cbdad
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="src" path="gen"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/android-support-v4.jar"/>
+       <classpathentry kind="output" path="bin/classes"/>
+</classpath>
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/.project b/service/notification-manager/SampleApp/android/SampleProviderApp/.project
new file mode 100644 (file)
index 0000000..b0145cf
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>SampleProvider</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+       </natures>
+</projectDescription>
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/AndroidManifest.xml b/service/notification-manager/SampleApp/android/SampleProviderApp/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..4e1326b
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.sample.provider"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+    <uses-permission android:name="android.permission.GET_TASKS"/>
+    <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>
+    <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY"/>
+     
+    <application android:label="@string/app_name">
+        <activity
+            android:name="com.example.sample.provider.SampleProvider"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/jni/Android.mk b/service/notification-manager/SampleApp/android/SampleProviderApp/jni/Android.mk
new file mode 100644 (file)
index 0000000..470870f
--- /dev/null
@@ -0,0 +1,66 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-oc_logger
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-octbstack
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-oc
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-ca
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_SRC_PATH := ../../../resource
+OIC_OUT_PATH := ../../../out
+LOCAL_MODULE    := ocstack-jni
+LOCAL_SRC_FILES :=  JniOcStack.cpp                                     \
+                    JniUtils.cpp                                       \
+                    JniEntityHandler.cpp                       \
+                    JniOnResourceFoundListener.cpp     \
+                    JniOnDeviceInfoListener.cpp                \
+                    JniOnPresenceListener.cpp          \
+                    JniOnGetListener.cpp                       \
+                    JniOnPutListener.cpp                       \
+                    JniOnPostListener.cpp                      \
+                    JniOnDeleteListener.cpp                    \
+                    JniOnObserveListener.cpp           \
+                    JniOcRepresentation.cpp                    \
+                    JniOcResourceHandle.cpp                    \
+                    JniOcPresenceHandle.cpp                    \
+                    JniOcRequestHandle.cpp                     \
+                    JniOcResourceRequest.cpp           \
+                    JniOcResourceResponse.cpp          \
+                    JniOcPlatform.cpp                          \
+                    JniOcResource.cpp
+
+LOCAL_LDLIBS := -llog
+LOCAL_STATIC_LIBRARIES := android-oc
+LOCAL_STATIC_LIBRARIES += android-octbstack
+LOCAL_STATIC_LIBRARIES += android-ca
+LOCAL_STATIC_LIBRARIES += android-oc_logger
+LOCAL_CPPFLAGS += -std=c++0x
+LOCAL_CPP_FEATURES := rtti exceptions
+LOCAL_C_INCLUDES := $(OIC_SRC_PATH)/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/stack/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/ocsocket/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/oc_logger/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../extlibs/boost/boost_1_58_0
+
+include $(BUILD_SHARED_LIBRARY)
+
+
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/jni/Application.mk b/service/notification-manager/SampleApp/android/SampleProviderApp/jni/Application.mk
new file mode 100644 (file)
index 0000000..a74997f
--- /dev/null
@@ -0,0 +1,2 @@
+NDK_TOOLCHAIN_VERSION := 4.9
+APP_STL               := gnustl_shared
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/project.properties b/service/notification-manager/SampleApp/android/SampleProviderApp/project.properties
new file mode 100644 (file)
index 0000000..4ab1256
--- /dev/null
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-19
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/res/layout/sampleprovider_layout.xml b/service/notification-manager/SampleApp/android/SampleProviderApp/res/layout/sampleprovider_layout.xml
new file mode 100644 (file)
index 0000000..5ffd8c6
--- /dev/null
@@ -0,0 +1,177 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical"
+    android:paddingBottom="5dp"
+    android:paddingLeft="10dp"
+    android:paddingRight="10dp"
+    android:paddingTop="10dp" >
+
+    <LinearLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal" >
+
+        <LinearLayout
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="20dp"
+            android:paddingTop="10dp" 
+            android:orientation="horizontal">
+
+            <TextView
+                android:id="@+id/temperature"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="Temperature : "
+                android:textSize="20sp"
+                android:textStyle="bold" />
+
+            <TextView
+                android:id="@+id/temperatureValue"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="0"
+                android:textSize="15sp"
+                android:textStyle="bold" />
+        </LinearLayout>
+
+        <LinearLayout
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal" >
+
+            <Button
+                android:id="@+id/btnTemperatureUP"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:text="Up"
+                android:textSize="18sp" />
+
+            <Button
+                android:id="@+id/btnTemperatureDown"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginRight="0dp"
+                android:text="Down"
+                android:textSize="18sp" />
+        </LinearLayout>
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal" >
+
+        <LinearLayout
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="20dp"
+            android:paddingTop="10dp" 
+            android:orientation="horizontal">
+
+            <TextView
+                android:id="@+id/humidity"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="Humidity : "
+                android:textSize="20sp"
+                android:textStyle="bold" />
+
+            <TextView
+                android:id="@+id/humidityValue"
+                android:layout_width="fill_parent"
+                android:layout_height="wrap_content"
+                android:text="0"
+                android:textSize="15sp"
+                android:textStyle="bold" />
+        </LinearLayout>
+
+        <LinearLayout
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal" >
+
+            <Button
+                android:id="@+id/btnHumidityUP"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:text="Up"
+                android:textSize="18sp" />
+
+            <Button
+                android:id="@+id/btnHumidityDown"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginRight="0dp"
+                android:text="Down"
+                android:textSize="18sp" />
+        </LinearLayout>
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal"
+        android:paddingTop="10dp" >
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Received Method Type : "
+            android:textSize="15sp"
+            android:textStyle="bold" />
+
+        <TextView
+            android:id="@+id/receivedMethodType"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="None"
+            android:textSize="15sp"
+            android:textStyle="bold" />
+    </LinearLayout>
+
+    <Space
+        android:layout_width="match_parent"
+        android:layout_height="10dp" />
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="5dp"
+        android:background="#111111"
+        android:orientation="vertical" >
+    </LinearLayout>
+
+    <Space
+        android:layout_width="match_parent"
+        android:layout_height="5dp" />
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="vertical"
+        android:paddingTop="0dp" >
+
+        <Button
+            android:id="@+id/btnLogClear"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:text="CLEAR LOG"
+            android:textSize="18sp" />
+
+        <ScrollView
+            android:id="@+id/sclLog"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent" >
+
+            <TextView
+                android:id="@+id/txtLog"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
+                android:layout_alignParentBottom="true"
+                android:layout_alignParentLeft="true"
+                android:textSize="15sp" />
+        </ScrollView>
+    </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/res/values/strings.xml b/service/notification-manager/SampleApp/android/SampleProviderApp/res/values/strings.xml
new file mode 100644 (file)
index 0000000..6763cb9
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">SampleProvider</string>
+    <string name="start">Start</string>
+    <string name="stop">Stop</string>
+    <string name="received">Received</string>
+    <string name="current_log">Current Log</string>
+    <string name="none">None</string>
+    <string name="quit">Quit</string>
+</resources>
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/IMessageLogger.java b/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/IMessageLogger.java
new file mode 100644 (file)
index 0000000..6312b84
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package com.example.sample.provider;
+
+public interface IMessageLogger
+{
+    public void logMessage(String msg);
+}
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/SampleProvider.java b/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/SampleProvider.java
new file mode 100644 (file)
index 0000000..26bd9b5
--- /dev/null
@@ -0,0 +1,271 @@
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+package com.example.sample.provider;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Message;
+import android.support.v4.content.LocalBroadcastManager;
+import android.util.Log;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+
+
+public class SampleProvider extends Activity implements OnClickListener,
+    IMessageLogger
+{
+        private final static String TAG = "SampleProvider : ";
+        private TextView mLogTextView;
+        private TextView mTempValue;
+        private TextView mHumValue;
+        private TemperatureResource mySensor;
+        private boolean isExecutePresence;
+        private ScrollView sv_sclLog;
+        private MessageReceiver mMessageReceiver = new MessageReceiver();
+        /*
+         * To initialize UI Function Setting
+         * To execute initOICStack for running find resource
+         */
+        @Override
+        public void onCreate(Bundle savedInstanceState)
+        {
+
+            super.onCreate(savedInstanceState);
+            setContentView(R.layout.sampleprovider_layout);
+            registerReceiver(mMessageReceiver, new IntentFilter(
+                                 "com.example.sample.provider.SampleProvider"));
+
+            mLogTextView = (TextView) findViewById(R.id.txtLog);
+            mTempValue = (TextView) findViewById(R.id.temperatureValue);
+            mHumValue = (TextView) findViewById(R.id.humidityValue);
+
+            sv_sclLog = (ScrollView)findViewById(R.id.sclLog);
+            sv_sclLog.fullScroll(View.FOCUS_DOWN);
+            findViewById(R.id.btnTemperatureUP).setOnClickListener(this);
+            findViewById(R.id.btnTemperatureDown).setOnClickListener(this);
+            findViewById(R.id.btnHumidityUP).setOnClickListener(this);
+            findViewById(R.id.btnHumidityDown).setOnClickListener(this);
+            findViewById(R.id.btnLogClear).setOnClickListener(this);
+
+            isExecutePresence = false;
+        }
+
+        private void initOICStack()
+        {
+            // create platform config
+            PlatformConfig cfg = new PlatformConfig(this,ServiceType.IN_PROC,
+                                                    ModeType.SERVER, "0.0.0.0", // bind to all available interfaces
+                                                    0, QualityOfService.LOW);
+
+            OcPlatform.Configure(cfg);
+
+            try
+            {
+                OcPlatform.startPresence(30);
+                isExecutePresence = true;
+            }
+            catch (OcException e)
+            {
+                e.printStackTrace();
+            }
+
+            mySensor = new TemperatureResource(this);
+            // create and register a resource
+            mySensor.createResource();
+        }
+        /*
+         * To execute initOICStack for running find resource
+         */
+        @Override
+        protected void onStart()
+        {
+            super.onStart();
+            initOICStack();
+
+        }
+        /*
+         * To execute initOICStack for running find resource
+         */
+        @Override
+        protected void onRestart()
+        {
+            super.onRestart();
+            initOICStack();
+
+        }
+        /*
+         * To terminate presence process and unregister messageHandler(to get message from JNI Function)
+         */
+        @Override
+        protected void onDestroy()
+        {
+            super.onDestroy();
+
+            try
+            {
+                mySensor.destroyResource();
+
+                if (isExecutePresence == true)
+                {
+                    OcPlatform.stopPresence();
+                    isExecutePresence = false;
+                }
+            }
+            catch (OcException e)
+            {
+                e.printStackTrace();
+            }
+            LocalBroadcastManager.getInstance(this).unregisterReceiver(
+                mMessageReceiver);
+        }
+
+        public class MessageReceiver extends BroadcastReceiver
+        {
+                @Override
+                public void onReceive(Context context, Intent intent)
+                {
+                    final String message = intent
+                                           .getStringExtra(StringConstants.MESSAGE);
+                    logMessage(message);
+
+                }
+        }
+
+        public void logMessage(final String text)
+        {
+            runOnUiThread(new Runnable()
+            {
+                public void run()
+                {
+                    final Message msg = new Message();
+                    msg.obj = text;
+                    mLogTextView.append("\n");
+                    mLogTextView.append(text);
+                }
+            });
+            Log.i(TAG, text);
+        }
+        /*
+         * To terminate presence process and unregister messagehandler(to get message from JNI Function)
+         */
+        @Override
+        protected void onStop()
+        {
+            super.onStop();
+            try
+            {
+                mySensor.destroyResource();
+
+                if (isExecutePresence == true)
+                {
+                    OcPlatform.stopPresence();
+                    isExecutePresence = false;
+                }
+
+            }
+            catch (OcException e)
+            {
+
+                e.printStackTrace();
+            }
+            LocalBroadcastManager.getInstance(this).unregisterReceiver(
+                mMessageReceiver);
+        }
+
+        @Override
+        public void onClick(View v)
+        {
+            int getId = v.getId();
+
+            switch (getId)
+            {
+                case R.id.btnTemperatureUP:
+                    logMessage(TAG + "Click temerature up btn");
+                    mySensor.mtemp++;
+                    mySensor.notifyObserver();
+                    break;
+                case R.id.btnTemperatureDown:
+                    logMessage(TAG + "Click temerature down btn");
+                    mySensor.mtemp--;
+                    mySensor.notifyObserver();
+                    break;
+                case R.id.btnHumidityUP:
+                    logMessage(TAG + "Click Humidity up btn");
+                    mySensor.mhumidity++;
+                    mySensor.notifyObserver();
+                    break;
+                case R.id.btnHumidityDown:
+                    logMessage(TAG + "Click Humidity down btn");
+                    mySensor.mhumidity--;
+                    mySensor.notifyObserver();
+                    break;
+                case R.id.btnLogClear:
+                    mLogTextView.setText("");
+                    break;
+            }
+
+            mTempValue.setText(String.valueOf(mySensor.getTemp()));
+            mHumValue.setText(String.valueOf(mySensor.getHumidity()));
+
+        }
+        /*
+         * To handle event about back button
+         */
+        @Override
+        public boolean onKeyDown(int keyCode, KeyEvent event)
+        {
+            if (keyCode == KeyEvent.KEYCODE_BACK )
+            {
+                try
+                {
+                    mySensor.destroyResource();
+
+                    if (isExecutePresence == true)
+                    {
+                        OcPlatform.stopPresence();
+                        isExecutePresence = false;
+                    }
+                }
+                catch (OcException e)
+                {
+
+                    e.printStackTrace();
+                }
+                LocalBroadcastManager.getInstance(this).unregisterReceiver(
+                    mMessageReceiver);
+            }
+            return super.onKeyDown(keyCode, event);
+        }
+}
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/StringConstants.java b/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/StringConstants.java
new file mode 100644 (file)
index 0000000..38d603b
--- /dev/null
@@ -0,0 +1,15 @@
+package com.example.sample.provider;
+
+import org.iotivity.base.OcPlatform;
+
+public class StringConstants
+{
+        public static final String RESOURCE_URI = "/a/TempHumSensor/hosting";
+        public static final String RESOURCE_TYPENAME = "Resource.Hosting";
+        public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE; //resource interface
+        public static final String HUMIDITY = "humidity";
+        public static final String TEMPERATURE = "temperature";
+        public static final String MESSAGE = "message";
+        public static final int ERROR_CODE = 200;
+
+}
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/TemperatureResource.java b/service/notification-manager/SampleApp/android/SampleProviderApp/src/com/example/sample/provider/TemperatureResource.java
new file mode 100644 (file)
index 0000000..98f6f47
--- /dev/null
@@ -0,0 +1,272 @@
+package com.example.sample.provider;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.ObservationInfo;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.base.ResourceProperty;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+public class TemperatureResource implements IMessageLogger
+{
+        private Context mContext;
+        public int mtemp;
+        public int mhumidity;
+        private OcRepresentation mTempRep;
+        private OcResourceHandle mResourceHandle;
+        private List<Byte> mObservationIds;
+
+        private static String TAG = "SampleProvider : ";
+
+        TemperatureResource(Context context)
+        {
+            mContext = context;
+            mtemp = 0;
+            mhumidity = 0;
+            mResourceHandle = null;
+            mObservationIds = new LinkedList<Byte>();
+            mTempRep = new OcRepresentation();
+            mTempRep.setValueInt(StringConstants.TEMPERATURE, mtemp);
+            mTempRep.setValueInt(StringConstants.HUMIDITY, mhumidity);
+        }
+
+        // accessor methods
+        protected int getTemp()
+        {
+            return mtemp;
+        }
+
+        protected void setTemp(int temp)
+        {
+            mtemp = temp;
+        }
+
+        protected int getHumidity()
+        {
+            return mhumidity;
+        }
+
+        protected void setHumidity(int humidity)
+        {
+            mhumidity = humidity;
+        }
+
+        protected OcResourceHandle getHandle()
+        {
+            return mResourceHandle;
+        }
+        protected OcResourceHandle destroyResource()
+        {
+            if (mResourceHandle != null)
+            {
+                try
+                {
+                    OcPlatform.unregisterResource(mResourceHandle);
+                }
+                catch (OcException e)
+                {
+                    e.printStackTrace();
+                }
+                mResourceHandle = null;
+            }
+            return null;
+        }
+        protected OcResourceHandle createResource()
+        {
+
+            OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler()
+            {
+                @Override
+                public EntityHandlerResult handleEntity(
+                    OcResourceRequest ocResourceRequest)
+                {
+                    // this is where the main logic of simpleserver is handled as
+                    // different requests (GET, PUT, POST, OBSERVE, DELETE) are
+                    // handled
+                    return entityHandler(ocResourceRequest);
+                }
+            };
+
+            try
+            {
+                Log.e(TAG, "before registerResource!");
+                mResourceHandle = OcPlatform.registerResource(
+                                      StringConstants.RESOURCE_URI,
+                                      StringConstants.RESOURCE_TYPENAME,
+                                      StringConstants.RESOURCE_INTERFACE, eh, EnumSet.of(
+                                          ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));
+                Log.e(TAG, "after regiterResource");
+            }
+            catch (OcException e)
+            {
+                Log.e(TAG, "go exception");
+                logMessage(TAG + "RegisterResource error. " + e.getMessage());
+                Log.e(TAG, e.getMessage());
+            }
+
+            // logMessage(TAG + "Successfully registered resource");
+            return mResourceHandle;
+        }
+
+        private void put(OcRepresentation rep)
+        {
+            mtemp = rep.getValueInt(StringConstants.TEMPERATURE);
+            mhumidity = rep.getValueInt(StringConstants.HUMIDITY);
+            logMessage(TAG + "temperature : " + mtemp + "humidity : " + mhumidity);
+            // " Power: " + mPower);
+        }
+
+        protected OcRepresentation get()
+        {
+            mTempRep.setValueInt(StringConstants.TEMPERATURE, mtemp);
+            mTempRep.setValueInt(StringConstants.HUMIDITY, mhumidity);
+            return mTempRep;
+        }
+
+        private EntityHandlerResult entityHandler(OcResourceRequest request)
+        {
+            EntityHandlerResult result = EntityHandlerResult.ERROR;
+            if (null != request)
+            {
+                RequestType requestType = request.getRequestType();
+                EnumSet<RequestHandlerFlag> requestFlag = request
+                        .getRequestHandlerFlagSet();
+
+
+
+                if (requestFlag.contains(RequestHandlerFlag.INIT))
+                {
+                    logMessage(TAG + "Init");
+                }
+
+                if (requestFlag.contains(RequestHandlerFlag.REQUEST))
+                {
+                    try
+                    {
+                        logMessage(TAG + "Request");
+                        OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                        ocResourceResponse.setRequestHandle(request
+                                                            .getRequestHandle());
+                        ocResourceResponse.setResourceHandle(request
+                                                             .getResourceHandle());
+
+                        switch (requestType)
+                        {
+                            // handle GET request
+                            case GET:
+                                logMessage("GET");
+                                ocResourceResponse
+                                .setResponseResult(EntityHandlerResult.OK);
+                                ocResourceResponse
+                                .setErrorCode(StringConstants.ERROR_CODE);
+                                ocResourceResponse.setResourceRepresentation(get());
+                                OcPlatform.sendResponse(ocResourceResponse);
+                                break;
+                            // handle PUT request
+                            case PUT:
+                                logMessage(TAG + "PUT");
+                                OcRepresentation rep = request
+                                                       .getResourceRepresentation();
+                                put(rep);
+                                ocResourceResponse
+                                .setErrorCode(StringConstants.ERROR_CODE);
+                                ocResourceResponse
+                                .setResponseResult(EntityHandlerResult.OK);
+                                ocResourceResponse.setResourceRepresentation(get());
+                                OcPlatform.sendResponse(ocResourceResponse);
+                                break;
+                            // handle POST request
+                            case POST:
+                                break;
+                            // handle DELETE request
+                            case DELETE:
+                                logMessage(TAG + "DELETE");
+                                OcPlatform.unregisterResource(getHandle());
+                                break;
+
+                        }
+
+                        result = EntityHandlerResult.OK;
+                    }
+                    catch (Exception e)
+                    {
+                        logMessage(TAG + "Error in Request " + e.getMessage());
+                        Log.e(TAG, e.getMessage());
+                    }
+                }
+                // handle OBSERVER request
+                if (requestFlag.contains(RequestHandlerFlag.OBSERVER))
+                {
+                    logMessage(TAG + "OBSERVER");
+                    ObservationInfo observationInfo = request.getObservationInfo();
+                    switch (observationInfo.getObserveAction())
+                    {
+                        case REGISTER:
+                            mObservationIds.add(observationInfo
+                                                .getOcObservationId());
+
+                            break;
+                        case UNREGISTER:
+                            mObservationIds.remove(observationInfo
+                                                   .getOcObservationId());
+                            break;
+                    }
+
+                    result = EntityHandlerResult.OK;
+                }
+            }
+            return result;
+        }
+
+        public void logMessage(String msg)
+        {
+            logMsg(msg);
+        }
+
+        public void logMsg(final String text)
+        {
+            Intent intent = new Intent("com.example.sample.provider.SampleProvider");
+            intent.putExtra(StringConstants.MESSAGE, text);
+            mContext.sendBroadcast(intent);
+        }
+
+        public void notifyObserver()
+        {
+            try
+            {
+                // if observationList is not empty, call notifyListOfObservers
+                if (mObservationIds.size() > 0)
+                {
+                    OcResourceResponse ocResourceResponse = new OcResourceResponse();
+                    ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
+                    ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+                    OcRepresentation r = get();
+                    ocResourceResponse.setResourceRepresentation
+                    (r, OcPlatform.DEFAULT_INTERFACE);
+                    OcPlatform.notifyListOfObservers(getHandle(), mObservationIds, ocResourceResponse);
+                }
+                else
+                {
+                    // notify all observers if mObservationList is empty
+                    OcPlatform.notifyAllObservers(getHandle());
+                }
+            }
+            catch (OcException e)
+            {
+                Log.e(TAG, e.getMessage());
+            }
+        }
+}
diff --git a/service/notification-manager/SampleApp/arduino/SConscript b/service/notification-manager/SampleApp/arduino/SConscript
deleted file mode 100644 (file)
index 04602f6..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-##
-# NotificationManager build script
-##
-
-Import('env')
-
-notimgr_env = env.Clone()
-
-######################################################################
-# Build flags
-######################################################################
-resource_path = env.get('SRC_DIR') + '/resource'
-
-notimgr_env.AppendUnique(CPPPATH = [
-               resource_path + '/oc_logger/include',
-               resource_path + '/csdk/stack/include',
-               resource_path + '/csdk/ocsocket/include',
-               resource_path + '/csdk/logger/include'
-               ])
-
-notimgr_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-notimgr_env.PrependUnique(LIBS = ['octbstack', 'coap'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-thserver = notimgr_env.Program('thserver', 'thserver.cpp')
-notimgr_env.CreateBin('thserver')
-
-i_thserver = notimgr_env.Install(env.get('BUILD_DIR'), thserver)
-
-Alias('thserver_arduino', i_thserver)
-env.AppendTarget('thserver_arduino')
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/arduino/Time/DateStrings.cpp b/service/notification-manager/SampleApp/arduino/Time/DateStrings.cpp
deleted file mode 100644 (file)
index 4facb73..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-/* DateStrings.cpp
- * Definitions for date strings for use with the Time library
- *
- * No memory is consumed in the sketch if your code does not call any of the string methods
- * You can change the text of the strings, make sure the short strings are each exactly 3 characters 
- * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h
- * 
- */
-
-#if defined(__AVR__)
-#include <avr/pgmspace.h>
-#else
-// for compatiblity with Arduino Due and Teensy 3.0 and maybe others?
-#define PROGMEM
-#define PGM_P  const char *
-#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
-#define pgm_read_word(addr) (*(const unsigned char **)(addr))
-#define strcpy_P(dest, src) strcpy((dest), (src))
-#endif
-#include <string.h> // for strcpy_P or strcpy
-#include "Time.h"
-// the short strings for each day or month must be exactly dt_SHORT_STR_LEN
-#define dt_SHORT_STR_LEN  3 // the length of short strings
-
-static char buffer[dt_MAX_STRING_LEN+1];  // must be big enough for longest string and the terminating null
-
-const char monthStr1[] PROGMEM = "January";
-const char monthStr2[] PROGMEM = "February";
-const char monthStr3[] PROGMEM = "March";
-const char monthStr4[] PROGMEM = "April";
-const char monthStr5[] PROGMEM = "May";
-const char monthStr6[] PROGMEM = "June";
-const char monthStr7[] PROGMEM = "July";
-const char monthStr8[] PROGMEM = "August";
-const char monthStr9[] PROGMEM = "September";
-const char monthStr10[] PROGMEM = "October";
-const char monthStr11[] PROGMEM = "November";
-const char monthStr12[] PROGMEM = "December";
-
-PGM_P monthNames_P[] PROGMEM = 
-{
-    "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
-       monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
-};
-
-const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";
-
-const char dayStr0[] PROGMEM = "Err";
-const char dayStr1[] PROGMEM = "Sunday";
-const char dayStr2[] PROGMEM = "Monday";
-const char dayStr3[] PROGMEM = "Tuesday";
-const char dayStr4[] PROGMEM = "Wednesday";
-const char dayStr5[] PROGMEM = "Thursday";
-const char dayStr6[] PROGMEM = "Friday";
-const char dayStr7[] PROGMEM = "Saturday";
-
-PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
-char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
-
-/* functions to return date strings */
-
-char* monthStr(uint8_t month)
-{
-    strcpy_P(buffer, (PGM_P)pgm_read_word(&(monthNames_P[month])));
-       return buffer;
-}
-
-char* monthShortStr(uint8_t month)
-{
-   for (int i=0; i < dt_SHORT_STR_LEN; i++)      
-      buffer[i] = pgm_read_byte(&(monthShortNames_P[i+ (month*dt_SHORT_STR_LEN)]));  
-   buffer[dt_SHORT_STR_LEN] = 0;
-   return buffer;
-}
-
-char* dayStr(uint8_t day) 
-{
-   strcpy_P(buffer, (PGM_P)pgm_read_word(&(dayNames_P[day])));
-   return buffer;
-}
-
-char* dayShortStr(uint8_t day) 
-{
-   uint8_t index = day*dt_SHORT_STR_LEN;
-   for (int i=0; i < dt_SHORT_STR_LEN; i++)      
-      buffer[i] = pgm_read_byte(&(dayShortNames_P[index + i]));  
-   buffer[dt_SHORT_STR_LEN] = 0; 
-   return buffer;
-}
diff --git a/service/notification-manager/SampleApp/arduino/Time/Readme.txt b/service/notification-manager/SampleApp/arduino/Time/Readme.txt
deleted file mode 100644 (file)
index 67b148e..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-Readme file for Arduino Time Library
-
-Time is a library that provides timekeeping functionality for Arduino.
-
-The code is derived from the Playground DateTime library but is updated
-to provide an API that is more flexable and easier to use.
-
-A primary goal was to enable date and time functionality that can be used with
-a variety of external time sources with minimum differences required in sketch logic.
-
-Example sketches illustrate how similar sketch code can be used with: a Real Time Clock,
-internet NTP time service, GPS time data, and Serial time messages from a computer
-for time synchronization.
-
-The functions available in the library include:
-
-hour();            // the hour now  (0-23)
-minute();          // the minute now (0-59)          
-second();          // the second now (0-59) 
-day();             // the day now (1-31)
-weekday();         // day of the week, Sunday is day 0 
-month();           // the month now (1-12)
-year();            // the full four digit year: (2009, 2010 etc) 
-
-there are also functions to return the hour in 12 hour format
-hourFormat12();    // the hour now in 12 hour format
-isAM();            // returns true if time now is AM 
-isPM();            // returns true if time now is PM
-
-now();             // returns the current time as seconds since Jan 1 1970 
-
-The time and date functions can take an optional parameter for the time. This prevents
-errors if the time rolls over between elements. For example, if a new minute begins
-between getting the minute and second, the values will be inconsistent. Using the 
-following functions eliminates this probglem 
-  time_t t = now(); // store the current time in time variable t 
-  hour(t);          // returns the hour for the given time t
-  minute(t);        // returns the minute for the given time t
-  second(t);        // returns the second for the given time t 
-  day(t);           // the day for the given time t 
-  weekday(t);       // day of the week for the given time t  
-  month(t);         // the month for the given time t 
-  year(t);          // the year for the given time t  
-  
-  
-Functions for managing the timer services are:  
-setTime(t);             // set the system time to the give time t
-setTime(hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010)
-adjustTime(adjustment); // adjust system time by adding the adjustment value
-
-timeStatus();       // indicates if time has been set and recently synchronized
-                    // returns one of the following enumerations:
-    timeNotSet      // the time has never been set, the clock started at Jan 1 1970
-    timeNeedsSync   // the time had been set but a sync attempt did not succeed
-    timeSet         // the time is set and is synced
-Time and Date values are not valid if the status is timeNotSet. Otherwise values can be used but 
-the returned time may have drifted if the status is timeNeedsSync.     
-
-setSyncProvider(getTimeFunction);  // set the external time provider
-setSyncInterval(interval);         // set the number of seconds between re-sync
-
-
-There are many convenience macros in the time.h file for time constants and conversion of time units.
-
-To use the library, copy the download to the Library directory.
-
-The Time directory contains the Time library and some example sketches
-illustrating how the library can be used with various time sources:
-
-- TimeSerial.pde shows Arduino as a clock without external hardware.
-  It is synchronized by time messages sent over the serial port.
-  A companion Processing sketch will automatically provide these messages
-  if it is running and connected to the Arduino serial port. 
-
-- TimeSerialDateStrings.pde adds day and month name strings to the sketch above
-  Short (3 character) and long strings are available to print the days of 
-  the week and names of the months. 
-  
-- TimeRTC uses a DS1307 real time clock to provide time synchronization.
-  A basic RTC library named DS1307RTC is included in the download.
-  To run this sketch the DS1307RTC library must be installed.
-
-- TimeRTCSet is similar to the above and adds the ability to set the Real Time Clock 
-
-- TimeRTCLog demonstrates how to calculate the difference between times. 
-  It is a vary simple logger application that monitors events on digtial pins
-  and prints (to the serial port) the time of an event and the time period since the previous event.
-  
-- TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service.
-  The NTP protocol uses UDP and the UdpBytewise library is required, see:
-  http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Ethernet/
-
-- TimeGPS gets time from a GPS
-  This requires the TinyGPS library from Mikal Hart:
-  http://arduiniana.org/libraries/TinyGPS
-
-Differences between this code and the playground DateTime library
-although the Time library is based on the DateTime codebase, the API has changed.
-Changes in the Time library API:
-- time elements are functions returning int (they are variables in DateTime)
-- Years start from 1970 
-- days of the week and months start from 1 (they start from 0 in DateTime)
-- DateStrings do not require a seperate library
-- time elements can be accessed non-atomically (in DateTime they are always atomic)
-- function added to automatically sync time with extrnal source
-- localTime and maketime parameters changed, localTime renamed to breakTime
-Technical notes:
-
-Internal system time is based on the standard Unix time_t.
-The value is the number of seconds since Jan 1 1970.
-System time begins at zero when the sketch starts.
-  
-The internal time can be automatically synchronized at regular intervals to an external time source.
-This is enabled by calling the setSyncProvider(provider) function - the provider argument is
-the address of a function that returns the current time as a time_t.
-See the sketches in the examples directory for usage.
-
-The default interval for re-syncing the time is 5 minutes but can be changed by calling the 
-setSyncInterval( interval) method to set the number of seconds between re-sync attempts.
-
-The Time library defines a structure for holding time elements that is a compact version of the  C tm structure.
-All the members of the Arduino tm structure are bytes and the year is offset from 1970.
-Convenience macros provide conversion to and from the Arduino format.
-
-Low level functions to convert between system time and individual time elements are provided:                    
-  breakTime( time, &tm);  // break time_t into elements stored in tm struct
-  makeTime( &tm);  // return time_t  from elements stored in tm struct 
-
-The DS1307RTC library included in the download provides an example of how a time provider
-can use the low level functions to interface with the Time library.
diff --git a/service/notification-manager/SampleApp/arduino/Time/Time.cpp b/service/notification-manager/SampleApp/arduino/Time/Time.cpp
deleted file mode 100644 (file)
index 9d53cd7..0000000
+++ /dev/null
@@ -1,318 +0,0 @@
-/*
-  time.c - low level time and date functions
-  Copyright (c) Michael Margolis 2009
-
-  This library is free software; you can redistribute it and/or
-  modify it under the terms of the GNU Lesser General Public
-  License as published by the Free Software Foundation; either
-  version 2.1 of the License, or (at your option) any later version.
-
-  This library is distributed in the hope that it will be useful,
-  but WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-  Lesser General Public License for more details.
-
-  You should have received a copy of the GNU Lesser General Public
-  License along with this library; if not, write to the Free Software
-  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-  
-  6  Jan 2010 - initial release 
-  12 Feb 2010 - fixed leap year calculation error
-  1  Nov 2010 - fixed setTime bug (thanks to Korman for this)
-  24 Mar 2012 - many edits by Paul Stoffregen: fixed timeStatus() to update
-                status, updated examples for Arduino 1.0, fixed ARM
-                compatibility issues, added TimeArduinoDue and TimeTeensy3
-                examples, add error checking and messages to RTC examples,
-                add examples to DS1307RTC library.
-*/
-
-#if ARDUINO >= 100
-#include <Arduino.h> 
-#else
-#include <WProgram.h> 
-#endif
-
-#include "Time.h"
-
-static tmElements_t tm;          // a cache of time elements
-static time_t cacheTime;   // the time the cache was updated
-static uint32_t syncInterval = 300;  // time sync will be attempted after this many seconds
-
-void refreshCache(time_t t) {
-  if (t != cacheTime) {
-    breakTime(t, tm); 
-    cacheTime = t; 
-  }
-}
-
-int hour() { // the hour now 
-  return hour(now()); 
-}
-
-int hour(time_t t) { // the hour for the given time
-  refreshCache(t);
-  return tm.Hour;  
-}
-
-int hourFormat12() { // the hour now in 12 hour format
-  return hourFormat12(now()); 
-}
-
-int hourFormat12(time_t t) { // the hour for the given time in 12 hour format
-  refreshCache(t);
-  if( tm.Hour == 0 )
-    return 12; // 12 midnight
-  else if( tm.Hour  > 12)
-    return tm.Hour - 12 ;
-  else
-    return tm.Hour ;
-}
-
-uint8_t isAM() { // returns true if time now is AM
-  return !isPM(now()); 
-}
-
-uint8_t isAM(time_t t) { // returns true if given time is AM
-  return !isPM(t);  
-}
-
-uint8_t isPM() { // returns true if PM
-  return isPM(now()); 
-}
-
-uint8_t isPM(time_t t) { // returns true if PM
-  return (hour(t) >= 12); 
-}
-
-int minute() {
-  return minute(now()); 
-}
-
-int minute(time_t t) { // the minute for the given time
-  refreshCache(t);
-  return tm.Minute;  
-}
-
-int second() {
-  return second(now()); 
-}
-
-int second(time_t t) {  // the second for the given time
-  refreshCache(t);
-  return tm.Second;
-}
-
-int day(){
-  return(day(now())); 
-}
-
-int day(time_t t) { // the day for the given time (0-6)
-  refreshCache(t);
-  return tm.Day;
-}
-
-int weekday() {   // Sunday is day 1
-  return  weekday(now()); 
-}
-
-int weekday(time_t t) {
-  refreshCache(t);
-  return tm.Wday;
-}
-   
-int month(){
-  return month(now()); 
-}
-
-int month(time_t t) {  // the month for the given time
-  refreshCache(t);
-  return tm.Month;
-}
-
-int year() {  // as in Processing, the full four digit year: (2009, 2010 etc) 
-  return year(now()); 
-}
-
-int year(time_t t) { // the year for the given time
-  refreshCache(t);
-  return tmYearToCalendar(tm.Year);
-}
-
-/*============================================================================*/       
-/* functions to convert to and from system time */
-/* These are for interfacing with time serivces and are not normally needed in a sketch */
-
-// leap year calulator expects year argument as years offset from 1970
-#define LEAP_YEAR(Y)     ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )
-
-static  const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
-void breakTime(time_t timeInput, tmElements_t &tm){
-// break the given time_t into time components
-// this is a more compact version of the C library localtime function
-// note that year is offset from 1970 !!!
-
-  uint8_t year;
-  uint8_t month, monthLength;
-  uint32_t time;
-  unsigned long days;
-
-  time = (uint32_t)timeInput;
-  tm.Second = time % 60;
-  time /= 60; // now it is minutes
-  tm.Minute = time % 60;
-  time /= 60; // now it is hours
-  tm.Hour = time % 24;
-  time /= 24; // now it is days
-  tm.Wday = ((time + 4) % 7) + 1;  // Sunday is day 1 
-  
-  year = 0;  
-  days = 0;
-  while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
-    year++;
-  }
-  tm.Year = year; // year is offset from 1970 
-  
-  days -= LEAP_YEAR(year) ? 366 : 365;
-  time  -= days; // now it is days in this year, starting at 0
-  
-  days=0;
-  month=0;
-  monthLength=0;
-  for (month=0; month<12; month++) {
-    if (month==1) { // february
-      if (LEAP_YEAR(year)) {
-        monthLength=29;
-      } else {
-        monthLength=28;
-      }
-    } else {
-      monthLength = monthDays[month];
-    }
-    
-    if (time >= monthLength) {
-      time -= monthLength;
-    } else {
-        break;
-    }
-  }
-  tm.Month = month + 1;  // jan is month 1  
-  tm.Day = time + 1;     // day of month
-}
-
-time_t makeTime(tmElements_t &tm){   
-// assemble time elements into time_t 
-// note year argument is offset from 1970 (see macros in time.h to convert to other formats)
-// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
-  
-  int i;
-  uint32_t seconds;
-
-  // seconds from 1970 till 1 jan 00:00:00 of the given year
-  seconds= tm.Year*(SECS_PER_DAY * 365);
-  for (i = 0; i < tm.Year; i++) {
-    if (LEAP_YEAR(i)) {
-      seconds +=  SECS_PER_DAY;   // add extra days for leap years
-    }
-  }
-  
-  // add days for this year, months start from 1
-  for (i = 1; i < tm.Month; i++) {
-    if ( (i == 2) && LEAP_YEAR(tm.Year)) { 
-      seconds += SECS_PER_DAY * 29;
-    } else {
-      seconds += SECS_PER_DAY * monthDays[i-1];  //monthDay array starts from 0
-    }
-  }
-  seconds+= (tm.Day-1) * SECS_PER_DAY;
-  seconds+= tm.Hour * SECS_PER_HOUR;
-  seconds+= tm.Minute * SECS_PER_MIN;
-  seconds+= tm.Second;
-  return (time_t)seconds; 
-}
-/*=====================================================*/      
-/* Low level system time functions  */
-
-static uint32_t sysTime = 0;
-static uint32_t prevMillis = 0;
-static uint32_t nextSyncTime = 0;
-static timeStatus_t Status = timeNotSet;
-
-getExternalTime getTimePtr;  // pointer to external sync function
-//setExternalTime setTimePtr; // not used in this version
-
-#ifdef TIME_DRIFT_INFO   // define this to get drift data
-time_t sysUnsyncedTime = 0; // the time sysTime unadjusted by sync  
-#endif
-
-
-time_t now() {
-  while (millis() - prevMillis >= 1000){      
-    sysTime++;
-    prevMillis += 1000;        
-#ifdef TIME_DRIFT_INFO
-    sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift     
-#endif
-  }
-  if (nextSyncTime <= sysTime) {
-    if (getTimePtr != 0) {
-      time_t t = getTimePtr();
-      if (t != 0) {
-        setTime(t);
-      } else {
-        nextSyncTime = sysTime + syncInterval;
-        Status = (Status == timeNotSet) ?  timeNotSet : timeNeedsSync;
-      }
-    }
-  }  
-  return (time_t)sysTime;
-}
-
-void setTime(time_t t) { 
-#ifdef TIME_DRIFT_INFO
- if(sysUnsyncedTime == 0) 
-   sysUnsyncedTime = t;   // store the time of the first call to set a valid Time   
-#endif
-
-  sysTime = (uint32_t)t;  
-  nextSyncTime = (uint32_t)t + syncInterval;
-  Status = timeSet;
-  prevMillis = millis();  // restart counting from now (thanks to Korman for this fix)
-} 
-
-void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
- // year can be given as full four digit year or two digts (2010 or 10 for 2010);  
- //it is converted to years since 1970
-  if( yr > 99)
-      yr = yr - 1970;
-  else
-      yr += 30;  
-  tm.Year = yr;
-  tm.Month = mnth;
-  tm.Day = dy;
-  tm.Hour = hr;
-  tm.Minute = min;
-  tm.Second = sec;
-  setTime(makeTime(tm));
-}
-
-void adjustTime(long adjustment) {
-  sysTime += adjustment;
-}
-
-// indicates if time has been set and recently synchronized
-timeStatus_t timeStatus() {
-  now(); // required to actually update the status
-  return Status;
-}
-
-void setSyncProvider( getExternalTime getTimeFunction){
-  getTimePtr = getTimeFunction;  
-  nextSyncTime = sysTime;
-  now(); // this will sync the clock
-}
-
-void setSyncInterval(time_t interval){ // set the number of seconds between re-sync
-  syncInterval = (uint32_t)interval;
-  nextSyncTime = sysTime + syncInterval;
-}
diff --git a/service/notification-manager/SampleApp/arduino/Time/Time.h b/service/notification-manager/SampleApp/arduino/Time/Time.h
deleted file mode 100644 (file)
index 61519f7..0000000
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
-  time.h - low level time and date functions
-*/
-
-/*
-  July 3 2011 - fixed elapsedSecsThisWeek macro (thanks Vincent Valdy for this)
-              - fixed  daysToTime_t macro (thanks maniacbug)
-*/     
-
-#ifndef _Time_h
-#ifdef __cplusplus
-#define _Time_h
-
-#include <inttypes.h>
-#ifndef __AVR__
-#include <sys/types.h> // for __time_t_defined, but avr libc lacks sys/types.h
-#endif
-
-
-#if !defined(__time_t_defined) // avoid conflict with newlib or other posix libc
-typedef unsigned long time_t;
-#endif
-
-
-// This ugly hack allows us to define C++ overloaded functions, when included
-// from within an extern "C", as newlib's sys/stat.h does.  Actually it is
-// intended to include "time.h" from the C library (on ARM, but AVR does not
-// have that file at all).  On Mac and Windows, the compiler will find this
-// "Time.h" instead of the C library "time.h", so we may cause other weird
-// and unpredictable effects by conflicting with the C library header "time.h",
-// but at least this hack lets us define C++ functions as intended.  Hopefully
-// nothing too terrible will result from overriding the C library header?!
-extern "C++" {
-typedef enum {timeNotSet, timeNeedsSync, timeSet
-}  timeStatus_t ;
-
-typedef enum {
-    dowInvalid, dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, dowSaturday
-} timeDayOfWeek_t;
-
-typedef enum {
-    tmSecond, tmMinute, tmHour, tmWday, tmDay,tmMonth, tmYear, tmNbrFields
-} tmByteFields;           
-
-typedef struct  { 
-  uint8_t Second; 
-  uint8_t Minute; 
-  uint8_t Hour; 
-  uint8_t Wday;   // day of week, sunday is day 1
-  uint8_t Day;
-  uint8_t Month; 
-  uint8_t Year;   // offset from 1970; 
-}      tmElements_t, TimeElements, *tmElementsPtr_t;
-
-//convenience macros to convert to and from tm years 
-#define  tmYearToCalendar(Y) ((Y) + 1970)  // full four digit year 
-#define  CalendarYrToTm(Y)   ((Y) - 1970)
-#define  tmYearToY2k(Y)      ((Y) - 30)    // offset is from 2000
-#define  y2kYearToTm(Y)      ((Y) + 30)   
-
-typedef time_t(*getExternalTime)();
-//typedef void  (*setExternalTime)(const time_t); // not used in this version
-
-
-/*==============================================================================*/
-/* Useful Constants */
-#define SECS_PER_MIN  (60UL)
-#define SECS_PER_HOUR (3600UL)
-#define SECS_PER_DAY  (SECS_PER_HOUR * 24UL)
-#define DAYS_PER_WEEK (7UL)
-#define SECS_PER_WEEK (SECS_PER_DAY * DAYS_PER_WEEK)
-#define SECS_PER_YEAR (SECS_PER_WEEK * 52UL)
-#define SECS_YR_2000  (946684800UL) // the time at the start of y2k
-/* Useful Macros for getting elapsed time */
-#define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN)  
-#define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN) 
-#define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR)
-#define dayOfWeek(_time_)  ((( _time_ / SECS_PER_DAY + 4)  % DAYS_PER_WEEK)+1) // 1 = Sunday
-#define elapsedDays(_time_) ( _time_ / SECS_PER_DAY)  // this is number of days since Jan 1 1970
-#define elapsedSecsToday(_time_)  (_time_ % SECS_PER_DAY)   // the number of seconds since last midnight 
-// The following macros are used in calculating alarms and assume the clock is set to a date later than Jan 1 1971
-// Always set the correct time before settting alarms
-#define previousMidnight(_time_) (( _time_ / SECS_PER_DAY) * SECS_PER_DAY)  // time at the start of the given day
-#define nextMidnight(_time_) ( previousMidnight(_time_)  + SECS_PER_DAY )   // time at the end of the given day 
-#define elapsedSecsThisWeek(_time_)  (elapsedSecsToday(_time_) +  ((dayOfWeek(_time_)-1) * SECS_PER_DAY) )   // note that week starts on day 1
-#define previousSunday(_time_)  (_time_ - elapsedSecsThisWeek(_time_))      // time at the start of the week for the given time
-#define nextSunday(_time_) ( previousSunday(_time_)+SECS_PER_WEEK)          // time at the end of the week for the given time
-
-
-/* Useful Macros for converting elapsed time to a time_t */
-#define minutesToTime_t ((M)) ( (M) * SECS_PER_MIN)  
-#define hoursToTime_t   ((H)) ( (H) * SECS_PER_HOUR)  
-#define daysToTime_t    ((D)) ( (D) * SECS_PER_DAY) // fixed on Jul 22 2011
-#define weeksToTime_t   ((W)) ( (W) * SECS_PER_WEEK)   
-
-/*============================================================================*/
-/*  time and date functions   */
-int     hour();            // the hour now 
-int     hour(time_t t);    // the hour for the given time
-int     hourFormat12();    // the hour now in 12 hour format
-int     hourFormat12(time_t t); // the hour for the given time in 12 hour format
-uint8_t isAM();            // returns true if time now is AM
-uint8_t isAM(time_t t);    // returns true the given time is AM
-uint8_t isPM();            // returns true if time now is PM
-uint8_t isPM(time_t t);    // returns true the given time is PM
-int     minute();          // the minute now 
-int     minute(time_t t);  // the minute for the given time
-int     second();          // the second now 
-int     second(time_t t);  // the second for the given time
-int     day();             // the day now 
-int     day(time_t t);     // the day for the given time
-int     weekday();         // the weekday now (Sunday is day 1) 
-int     weekday(time_t t); // the weekday for the given time 
-int     month();           // the month now  (Jan is month 1)
-int     month(time_t t);   // the month for the given time
-int     year();            // the full four digit year: (2009, 2010 etc) 
-int     year(time_t t);    // the year for the given time
-
-time_t now();              // return the current time as seconds since Jan 1 1970 
-void    setTime(time_t t);
-void    setTime(int hr,int min,int sec,int day, int month, int yr);
-void    adjustTime(long adjustment);
-
-/* date strings */ 
-#define dt_MAX_STRING_LEN 9 // length of longest date string (excluding terminating null)
-char* monthStr(uint8_t month);
-char* dayStr(uint8_t day);
-char* monthShortStr(uint8_t month);
-char* dayShortStr(uint8_t day);
-       
-/* time sync functions */
-timeStatus_t timeStatus(); // indicates if time has been set and recently synchronized
-void    setSyncProvider( getExternalTime getTimeFunction); // identify the external time provider
-void    setSyncInterval(time_t interval); // set the number of seconds between re-sync
-
-/* low level functions to convert to and from system time                     */
-void breakTime(time_t time, tmElements_t &tm);  // break time_t into elements
-time_t makeTime(tmElements_t &tm);  // convert time elements into time_t
-
-} // extern "C++"
-#endif // __cplusplus
-#endif /* _Time_h */
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde b/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde
deleted file mode 100644 (file)
index 4313be3..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * SyncArduinoClock. 
- *
- * portIndex must be set to the port connected to the Arduino
- * 
- * The current time is sent in response to request message from Arduino 
- * or by clicking the display window 
- *
- * The time message is 11 ASCII text characters; a header (the letter 'T')
- * followed by the ten digit system time (unix time)
- */
-
-import processing.serial.*;
-import java.util.Date;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-
-public static final short portIndex = 0;  // select the com port, 0 is the first port
-public static final String TIME_HEADER = "T"; //header for arduino serial time message 
-public static final char TIME_REQUEST = 7;  // ASCII bell character 
-public static final char LF = 10;     // ASCII linefeed
-public static final char CR = 13;     // ASCII linefeed
-Serial myPort;     // Create object from Serial class
-
-void setup() {  
-  size(200, 200);
-  println(Serial.list());
-  println(" Connecting to -> " + Serial.list()[portIndex]);
-  myPort = new Serial(this,Serial.list()[portIndex], 9600);
-  println(getTimeNow());
-}
-
-void draw()
-{
-  textSize(20);
-  textAlign(CENTER);
-  fill(0);
-  text("Click to send\nTime Sync", 0, 75, 200, 175);
-  if ( myPort.available() > 0) {  // If data is available,
-    char val = char(myPort.read());         // read it and store it in val
-    if(val == TIME_REQUEST){
-       long t = getTimeNow();
-       sendTimeMessage(TIME_HEADER, t);   
-    }
-    else
-    { 
-       if(val == LF)
-           ; //igonore
-       else if(val == CR)           
-         println();
-       else  
-         print(val); // echo everying but time request
-    }
-  }  
-}
-
-void mousePressed() {  
-  sendTimeMessage( TIME_HEADER, getTimeNow());   
-}
-
-
-void sendTimeMessage(String header, long time) {  
-  String timeStr = String.valueOf(time);  
-  myPort.write(header);  // send header and time to arduino
-  myPort.write(timeStr); 
-  myPort.write('\n');  
-}
-
-long getTimeNow(){
-  // java time is in ms, we want secs    
-  Date d = new Date();
-  Calendar cal = new GregorianCalendar();
-  long current = d.getTime()/1000;
-  long timezone = cal.get(cal.ZONE_OFFSET)/1000;
-  long daylight = cal.get(cal.DST_OFFSET)/1000;
-  return current + timezone + daylight; 
-}
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/readme.txt b/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/readme.txt
deleted file mode 100644 (file)
index da9721d..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-SyncArduinoClock is a Processing sketch that responds to Arduino requests for 
-time synchronization messages.
-
-The portIndex must be set the Serial port connected to Arduino.
-
-Download TimeSerial.pde onto Arduino and you should see the time 
-message displayed when you run SyncArduinoClock in Processing.
-The Arduino time is set from the time on your computer through the 
-Processing sketch. 
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeArduinoDue/TimeArduinoDue.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeArduinoDue/TimeArduinoDue.ino
deleted file mode 100644 (file)
index acd80d2..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * TimeRTC.pde
- * example code illustrating Time library with Real Time Clock.
- *
- * This example requires Markus Lange's Arduino Due RTC Library 
- * https://github.com/MarkusLange/Arduino-Due-RTC-Library
- */
-
-#include <Time.h>
-#include <rtc_clock.h>
-
-// Select the Slowclock source
-//RTC_clock rtc_clock(RC);
-RTC_clock rtc_clock(XTAL);
-
-void setup()  {
-  Serial.begin(9600);
-  rtc_clock.init();
-  if (rtc_clock.date_already_set() == 0) {
-    // Unfortunately, the Arduino Due hardware does not seem to
-    // be designed to maintain the RTC clock state when the
-    // board resets.  Markus described it thusly: "Uhh the Due
-    // does reset with the NRSTB pin.  This resets the full chip
-    // with all backup regions including RTC, RTT and SC.  Only
-    // if the reset is done with the NRST pin will these regions
-    // stay with their old values."
-    rtc_clock.set_time(__TIME__);
-    rtc_clock.set_date(__DATE__);
-  }
-  setSyncProvider(getArduinoDueTime);
-  if(timeStatus()!= timeSet) 
-     Serial.println("Unable to sync with the RTC");
-  else
-     Serial.println("RTC has set the system time");      
-}
-
-time_t getArduinoDueTime()
-{
-  return rtc_clock.unixtime();
-}
-
-void loop()
-{
-   digitalClockDisplay();
-   delay(1000);
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeGPS/TimeGPS.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeGPS/TimeGPS.ino
deleted file mode 100644 (file)
index 7a0213b..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * TimeGPS.pde
- * example code illustrating time synced from a GPS
- * 
- */
-
-#include <Time.h>
-#include <TinyGPS.h>       // http://arduiniana.org/libraries/TinyGPS/
-#include <SoftwareSerial.h>
-// TinyGPS and SoftwareSerial libraries are the work of Mikal Hart
-
-SoftwareSerial SerialGPS = SoftwareSerial(10, 11);  // receive on pin 10
-TinyGPS gps; 
-
-// To use a hardware serial port, which is far more efficient than
-// SoftwareSerial, uncomment this line and remove SoftwareSerial
-//#define SerialGPS Serial1
-
-// Offset hours from gps time (UTC)
-const int offset = 1;   // Central European Time
-//const int offset = -5;  // Eastern Standard Time (USA)
-//const int offset = -4;  // Eastern Daylight Time (USA)
-//const int offset = -8;  // Pacific Standard Time (USA)
-//const int offset = -7;  // Pacific Daylight Time (USA)
-
-// Ideally, it should be possible to learn the time zone
-// based on the GPS position data.  However, that would
-// require a complex library, probably incorporating some
-// sort of database using Eric Muller's time zone shape
-// maps, at http://efele.net/maps/tz/
-
-time_t prevDisplay = 0; // when the digital clock was displayed
-
-void setup()
-{
-  Serial.begin(9600);
-  while (!Serial) ; // Needed for Leonardo only
-  SerialGPS.begin(4800);
-  Serial.println("Waiting for GPS time ... ");
-}
-
-void loop()
-{
-  while (SerialGPS.available()) {
-    if (gps.encode(SerialGPS.read())) { // process gps messages
-      // when TinyGPS reports new data...
-      unsigned long age;
-      int Year;
-      byte Month, Day, Hour, Minute, Second;
-      gps.crack_datetime(&Year, &Month, &Day, &Hour, &Minute, &Second, NULL, &age);
-      if (age < 500) {
-        // set the Time to the latest GPS reading
-        setTime(Hour, Minute, Second, Day, Month, Year);
-        adjustTime(offset * SECS_PER_HOUR);
-      }
-    }
-  }
-  if (timeStatus()!= timeNotSet) {
-    if (now() != prevDisplay) { //update the display only if the time has changed
-      prevDisplay = now();
-      digitalClockDisplay();  
-    }
-  }
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-void printDigits(int digits) {
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeNTP/TimeNTP.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeNTP/TimeNTP.ino
deleted file mode 100644 (file)
index 0d3820e..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Time_NTP.pde
- * Example showing time sync to NTP time source
- *
- * This sketch uses the Ethernet library
- */
-#include <Time.h> 
-#include <Ethernet.h>
-#include <EthernetUdp.h>
-#include <SPI.h>
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 
-// NTP Servers:
-IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
-// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
-// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov
-
-
-const int timeZone = 1;     // Central European Time
-//const int timeZone = -5;  // Eastern Standard Time (USA)
-//const int timeZone = -4;  // Eastern Daylight Time (USA)
-//const int timeZone = -8;  // Pacific Standard Time (USA)
-//const int timeZone = -7;  // Pacific Daylight Time (USA)
-
-
-EthernetUDP Udp;
-unsigned int localPort = 8888;  // local port to listen for UDP packets
-
-void setup() 
-{
-  Serial.begin(9600);
-  while (!Serial) ; // Needed for Leonardo only
-  delay(250);
-  Serial.println("TimeNTP Example");
-  if (Ethernet.begin(mac) == 0) {
-    // no point in carrying on, so do nothing forevermore:
-    while (1) {
-      Serial.println("Failed to configure Ethernet using DHCP");
-      delay(10000);
-    }
-  }
-  Serial.print("IP number assigned by DHCP is ");
-  Serial.println(Ethernet.localIP());
-  Udp.begin(localPort);
-  Serial.println("waiting for sync");
-  setSyncProvider(getNtpTime);
-}
-
-time_t prevDisplay = 0; // when the digital clock was displayed
-
-void loop()
-{  
-  if (timeStatus() != timeNotSet) {
-    if (now() != prevDisplay) { //update the display only if time has changed
-      prevDisplay = now();
-      digitalClockDisplay();  
-    }
-  }
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-void printDigits(int digits){
-  // utility for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
-/*-------- NTP code ----------*/
-
-const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
-byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
-
-time_t getNtpTime()
-{
-  while (Udp.parsePacket() > 0) ; // discard any previously received packets
-  Serial.println("Transmit NTP Request");
-  sendNTPpacket(timeServer);
-  uint32_t beginWait = millis();
-  while (millis() - beginWait < 1500) {
-    int size = Udp.parsePacket();
-    if (size >= NTP_PACKET_SIZE) {
-      Serial.println("Receive NTP Response");
-      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
-      unsigned long secsSince1900;
-      // convert four bytes starting at location 40 to a long integer
-      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
-      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
-      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
-      secsSince1900 |= (unsigned long)packetBuffer[43];
-      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
-    }
-  }
-  Serial.println("No NTP Response :-(");
-  return 0; // return 0 if unable to get the time
-}
-
-// send an NTP request to the time server at the given address
-void sendNTPpacket(IPAddress &address)
-{
-  // set all bytes in the buffer to 0
-  memset(packetBuffer, 0, NTP_PACKET_SIZE);
-  // Initialize values needed to form NTP request
-  // (see URL above for details on the packets)
-  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
-  packetBuffer[1] = 0;     // Stratum, or type of clock
-  packetBuffer[2] = 6;     // Polling Interval
-  packetBuffer[3] = 0xEC;  // Peer Clock Precision
-  // 8 bytes of zero for Root Delay & Root Dispersion
-  packetBuffer[12]  = 49;
-  packetBuffer[13]  = 0x4E;
-  packetBuffer[14]  = 49;
-  packetBuffer[15]  = 52;
-  // all NTP fields have been given values, now
-  // you can send a packet requesting a timestamp:                 
-  Udp.beginPacket(address, 123); //NTP requests are to port 123
-  Udp.write(packetBuffer, NTP_PACKET_SIZE);
-  Udp.endPacket();
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTC/TimeRTC.pde b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTC/TimeRTC.pde
deleted file mode 100644 (file)
index 42e7e7f..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * TimeRTC.pde
- * example code illustrating Time library with Real Time Clock.
- * 
- */
-
-#include <Time.h>  
-#include <Wire.h>  
-#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
-
-void setup()  {
-  Serial.begin(9600);
-  while (!Serial) ; // wait until Arduino Serial Monitor opens
-  setSyncProvider(RTC.get);   // the function to get the time from the RTC
-  if(timeStatus()!= timeSet) 
-     Serial.println("Unable to sync with the RTC");
-  else
-     Serial.println("RTC has set the system time");      
-}
-
-void loop()
-{
-  if (timeStatus() == timeSet) {
-    digitalClockDisplay();
-  } else {
-    Serial.println("The time has not been set.  Please run the Time");
-    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
-    Serial.println();
-    delay(4000);
-  }
-  delay(1000);
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCLog/TimeRTCLog.pde b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCLog/TimeRTCLog.pde
deleted file mode 100644 (file)
index 5715eb0..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * TimeRTCLogger.pde
- * example code illustrating adding and subtracting Time.
- * 
- * this sketch logs pin state change events
- * the time of the event and time since the previous event is calculated and sent to the serial port. 
- */
-
-#include <Time.h>  
-#include <Wire.h>  
-#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
-
-const int nbrInputPins  = 6;             // monitor 6 digital pins 
-const int inputPins[nbrInputPins] = {2,3,4,5,6,7};  // pins to monitor
-boolean state[nbrInputPins] ;            // the state of the monitored pins
-time_t  prevEventTime[nbrInputPins] ;    // the time of the previous event
-
-void setup()  {
-  Serial.begin(9600);
-  setSyncProvider(RTC.get);   // the function to sync the time from the RTC  
-  for(int i=0; i < nbrInputPins; i++){
-     pinMode( inputPins[i], INPUT);
-     // uncomment these lines if pull-up resistors are wanted
-     // pinMode( inputPins[i], INPUT_PULLUP);
-     // state[i] = HIGH;
-  }
-}
-
-void loop()
-{
-   for(int i=0; i < nbrInputPins; i++)
-   {
-     boolean val = digitalRead(inputPins[i]); 
-     if(val != state[i])
-     {
-        time_t duration = 0; // the time since the previous event
-        state[i] = val;
-        time_t timeNow = now();
-        if(prevEventTime[i] > 0)  
-           // if this was not the first state change, calculate the time from the previous change
-           duration = duration = timeNow - prevEventTime[i];         
-        logEvent(inputPins[i], val, timeNow, duration );  // log the event
-        prevEventTime[i] = timeNow;                       // store the time for this event  
-     }
-   }
-}
-
-void logEvent( int pin, boolean state, time_t timeNow, time_t duration)
-{
-   Serial.print("Pin ");
-   Serial.print(pin);
-   if( state == HIGH)
-      Serial.print(" went High at ");
-   else   
-     Serial.print(" went  Low at ");
-   showTime(timeNow); 
-   if(duration > 0){
-     // only display duration if greater than 0  
-     Serial.print(", Duration was ");
-     showDuration(duration);
-   }
-   Serial.println();
-}
-
-
-void showTime(time_t t){
-  // display the given time 
-  Serial.print(hour(t));
-  printDigits(minute(t));
-  printDigits(second(t));
-  Serial.print(" ");
-  Serial.print(day(t));
-  Serial.print(" ");
-  Serial.print(month(t));
-  Serial.print(" ");
-  Serial.print(year(t)); 
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
-void showDuration(time_t duration){
-// prints the duration in days, hours, minutes and seconds
-  if(duration >= SECS_PER_DAY){
-     Serial.print(duration / SECS_PER_DAY);
-     Serial.print(" day(s) "); 
-     duration = duration % SECS_PER_DAY;     
-  }
-  if(duration >= SECS_PER_HOUR){
-     Serial.print(duration / SECS_PER_HOUR);
-     Serial.print(" hour(s) "); 
-     duration = duration % SECS_PER_HOUR;     
-  }
-  if(duration >= SECS_PER_MIN){
-     Serial.print(duration / SECS_PER_MIN);
-     Serial.print(" minute(s) "); 
-     duration = duration % SECS_PER_MIN;     
-  }
-  Serial.print(duration);
-  Serial.print(" second(s) ");   
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCSet/TimeRTCSet.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCSet/TimeRTCSet.ino
deleted file mode 100644 (file)
index b4e4854..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * TimeRTCSet.pde
- * example code illustrating Time library with Real Time Clock.
- *
- * RTC clock is set in response to serial port time message 
- * A Processing example sketch to set the time is included in the download
- * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
- */
-
-#include <Time.h>  
-#include <Wire.h>  
-#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
-
-
-void setup()  {
-  Serial.begin(9600);
-  while (!Serial) ; // Needed for Leonardo only
-  setSyncProvider(RTC.get);   // the function to get the time from the RTC
-  if (timeStatus() != timeSet) 
-     Serial.println("Unable to sync with the RTC");
-  else
-     Serial.println("RTC has set the system time");      
-}
-
-void loop()
-{
-  if (Serial.available()) {
-    time_t t = processSyncMessage();
-    if (t != 0) {
-      RTC.set(t);   // set the RTC and the system time to the received value
-      setTime(t);          
-    }
-  }
-  digitalClockDisplay();  
-  delay(1000);
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
-/*  code to process time sync messages from the serial port   */
-#define TIME_HEADER  "T"   // Header tag for serial time sync message
-
-unsigned long processSyncMessage() {
-  unsigned long pctime = 0L;
-  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 
-
-  if(Serial.find(TIME_HEADER)) {
-     pctime = Serial.parseInt();
-     return pctime;
-     if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
-       pctime = 0L; // return 0 to indicate that the time is not valid
-     }
-  }
-  return pctime;
-}
-
-
-
-
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerial/TimeSerial.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerial/TimeSerial.ino
deleted file mode 100644 (file)
index 15aee0a..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-/* 
- * TimeSerial.pde
- * example code illustrating Time library set through serial port messages.
- *
- * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
- * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2013
- T1357041600  
- *
- * A Processing example sketch to automatically send the messages is inclided in the download
- * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
- */ 
-#include <Time.h>  
-
-#define TIME_HEADER  "T"   // Header tag for serial time sync message
-#define TIME_REQUEST  7    // ASCII bell character requests a time sync message 
-
-void setup()  {
-  Serial.begin(9600);
-  while (!Serial) ; // Needed for Leonardo only
-  pinMode(13, OUTPUT);
-  setSyncProvider( requestSync);  //set function to call when sync required
-  Serial.println("Waiting for sync message");
-}
-
-void loop(){    
-  if (Serial.available()) {
-    processSyncMessage();
-  }
-  if (timeStatus()!= timeNotSet) {
-    digitalClockDisplay();  
-  }
-  if (timeStatus() == timeSet) {
-    digitalWrite(13, HIGH); // LED on if synced
-  } else {
-    digitalWrite(13, LOW);  // LED off if needs refresh
-  }
-  delay(1000);
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
-
-void processSyncMessage() {
-  unsigned long pctime;
-  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-
-  if(Serial.find(TIME_HEADER)) {
-     pctime = Serial.parseInt();
-     if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
-       setTime(pctime); // Sync Arduino clock to the time received on the serial port
-     }
-  }
-}
-
-time_t requestSync()
-{
-  Serial.write(TIME_REQUEST);  
-  return 0; // the time will be sent later in response to serial mesg
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino
deleted file mode 100644 (file)
index f181c3d..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-/* 
- * TimeSerialDateStrings.pde
- * example code illustrating Time library date strings
- *
- * This sketch adds date string functionality to TimeSerial sketch
- * Also shows how to handle different messages
- *
- * A message starting with a time header sets the time
- * A Processing example sketch to automatically send the messages is inclided in the download
- * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
- *
- * A message starting with a format header sets the date format
- *
- * send: Fs\n for short date format
- * send: Fl\n for long date format 
- */ 
-#include <Time.h>  
-
-// single character message tags
-#define TIME_HEADER   'T'   // Header tag for serial time sync message
-#define FORMAT_HEADER 'F'   // Header tag indicating a date format message
-#define FORMAT_SHORT  's'   // short month and day strings
-#define FORMAT_LONG   'l'   // (lower case l) long month and day strings
-
-#define TIME_REQUEST  7     // ASCII bell character requests a time sync message 
-
-static boolean isLongFormat = true;
-
-void setup()  {
-  Serial.begin(9600);
-  while (!Serial) ; // Needed for Leonardo only
-  setSyncProvider( requestSync);  //set function to call when sync required
-  Serial.println("Waiting for sync message");
-}
-
-void loop(){    
-  if (Serial.available()) {
-    char c = Serial.read();
-    if( c == TIME_HEADER) {
-      processSyncMessage();
-    }
-    else if( c== FORMAT_HEADER) {
-      processFormatMessage();
-    }
-  }
-  if (timeStatus()!= timeNotSet) {
-    digitalClockDisplay();  
-  }
-  delay(1000);
-}
-
-void digitalClockDisplay(){
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  if(isLongFormat)
-    Serial.print(dayStr(weekday()));
-  else  
-   Serial.print(dayShortStr(weekday()));
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  if(isLongFormat)
-     Serial.print(monthStr(month()));
-  else
-     Serial.print(monthShortStr(month()));
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
-void  processFormatMessage() {
-   char c = Serial.read();
-   if( c == FORMAT_LONG){
-      isLongFormat = true;
-      Serial.println("Setting long format");
-   }
-   else if( c == FORMAT_SHORT){
-      isLongFormat = false;   
-      Serial.println("Setting short format");
-   }
-}
-
-void processSyncMessage() {
-  unsigned long pctime;
-  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 - paul, perhaps we define in time.h?
-
-   pctime = Serial.parseInt();
-   if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
-     setTime(pctime); // Sync Arduino clock to the time received on the serial port
-   } 
-}
-
-time_t requestSync()
-{
-  Serial.write(TIME_REQUEST);  
-  return 0; // the time will be sent later in response to serial mesg
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeTeensy3/TimeTeensy3.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeTeensy3/TimeTeensy3.ino
deleted file mode 100644 (file)
index a06a7f9..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * TimeRTC.pde
- * example code illustrating Time library with Real Time Clock.
- * 
- */
-
-#include <Time.h>  
-
-void setup()  {
-  // set the Time library to use Teensy 3.0's RTC to keep time
-  setSyncProvider(getTeensy3Time);
-
-  Serial.begin(115200);
-  while (!Serial);  // Wait for Arduino Serial Monitor to open
-  delay(100);
-  if (timeStatus()!= timeSet) {
-    Serial.println("Unable to sync with the RTC");
-  } else {
-    Serial.println("RTC has set the system time");
-  }
-}
-
-void loop() {
-  if (Serial.available()) {
-    time_t t = processSyncMessage();
-    if (t != 0) {
-      Teensy3Clock.set(t); // set the RTC
-      setTime(t);
-    }
-  }
-  digitalClockDisplay();  
-  delay(1000);
-}
-
-void digitalClockDisplay() {
-  // digital clock display of the time
-  Serial.print(hour());
-  printDigits(minute());
-  printDigits(second());
-  Serial.print(" ");
-  Serial.print(day());
-  Serial.print(" ");
-  Serial.print(month());
-  Serial.print(" ");
-  Serial.print(year()); 
-  Serial.println(); 
-}
-
-time_t getTeensy3Time()
-{
-  return Teensy3Clock.get();
-}
-
-/*  code to process time sync messages from the serial port   */
-#define TIME_HEADER  "T"   // Header tag for serial time sync message
-
-unsigned long processSyncMessage() {
-  unsigned long pctime = 0L;
-  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 
-
-  if(Serial.find(TIME_HEADER)) {
-     pctime = Serial.parseInt();
-     return pctime;
-     if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
-       pctime = 0L; // return 0 to indicate that the time is not valid
-     }
-  }
-  return pctime;
-}
-
-void printDigits(int digits){
-  // utility function for digital clock display: prints preceding colon and leading 0
-  Serial.print(":");
-  if(digits < 10)
-    Serial.print('0');
-  Serial.print(digits);
-}
-
diff --git a/service/notification-manager/SampleApp/arduino/Time/keywords.txt b/service/notification-manager/SampleApp/arduino/Time/keywords.txt
deleted file mode 100644 (file)
index 85b357e..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-#######################################
-# Syntax Coloring Map For Time
-#######################################
-
-#######################################
-# Datatypes (KEYWORD1)
-#######################################
-time_t KEYWORD1
-#######################################
-# Methods and Functions (KEYWORD2)
-#######################################
-now    KEYWORD2
-second KEYWORD2
-minute KEYWORD2
-hour   KEYWORD2
-day    KEYWORD2
-month  KEYWORD2
-year   KEYWORD2
-isAM   KEYWORD2
-isPM   KEYWORD2
-weekday        KEYWORD2
-setTime        KEYWORD2
-adjustTime     KEYWORD2
-setSyncProvider        KEYWORD2
-setSyncInterval        KEYWORD2
-timeStatus     KEYWORD2
-#######################################
-# Instances (KEYWORD2)
-#######################################
-
-#######################################
-# Constants (LITERAL1)
-#######################################
diff --git a/service/notification-manager/SampleApp/arduino/local.properties b/service/notification-manager/SampleApp/arduino/local.properties
deleted file mode 100644 (file)
index 1057fdc..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-#ARDUINO_DIR = /home/choi/devel/arduino-1.0.5
-ARDUINO_DIR = /usr/share/arduino
-#ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
-CC=avr-g++
-CCPLUS=avr-g++
-AR=avr-ar
-RANLIB=avr-ranlib
\ No newline at end of file
diff --git a/service/notification-manager/SampleApp/arduino/makefile b/service/notification-manager/SampleApp/arduino/makefile
deleted file mode 100644 (file)
index c4d0084..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-CC=avr-gcc
-CCPLUS=avr-g++
-AR=avr-ar
-RANLIB=avr-ranlib
-
-APP_NAME := thserver
-#BUILD := release
-BUILD := debug
-ARDUINO_PORT := /dev/ttyACM0
-
-OBJ_DIR := ./bin
-
-TB_DIR = ../../../../oic-resource_a/csdk
-
-include $(TB_DIR)/local.properties
-CC=avr-gcc
-LOGGER_DIR = $(TB_DIR)/logger
-TBSTACK_DIR = $(TB_DIR)/stack
-TBSOCKET_DIR = $(TB_DIR)/ocsocket
-
-#Source directories
-SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-SDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI
-SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet
-SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility
-SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time
-
-VPATH := $(SDIR_ARD_CORE):$(SDIR_ARD_SPI):$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL):$(OCSOCK_DIR)/src
-
-#include directories
-INCD_ARD_CORE = -I$(ARDUINO_DIR)/hardware/arduino/cores/arduino
-INCD_ARD_VARIANT = -I$(ARDUINO_DIR)/hardware/arduino/variants/mega
-INCD_ARD_SPI = -I$(ARDUINO_DIR)/libraries/SPI
-INCD_ARD_ETH = -I$(ARDUINO_DIR)/libraries/Ethernet
-INCD_ARD_ETH_UTIL = -I$(ARDUINO_DIR)/libraries/Ethernet/utility
-INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time
-INCD_TBLOGGER = -I$(LOGGER_DIR)/include
-INCD_TBSTACK = -I$(TBSTACK_DIR)/include
-INCD_TBSOCKET = -I$(TBSOCKET_DIR)/include
-
-CPPFLAGSZ := -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -MMD
-
-CPPFLAGS := -Wall -Os -c
-CPPFLAGS +=  $(CPPFLAGSZ) $(INCD_ARD_CORE) $(INCD_ARD_VARIANT) $(INCD_ARD_SPI) $(INCD_ARD_ETH) $(INCD_ARD_ETH_UTIL) $(INCD_ARD_TIME) $(INCD_TBLOGGER) $(INCD_TBSTACK) $(INCD_TBSOCKET)
-CPPFLAGS += -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 -DTB_LOG
-
-SERVER_CPP_SRC := $(APP_NAME).cpp
-
-CORE_COBJ = WInterrupts.o wiring.o wiring_digital.o
-CORE_CPPOBJ = main.o Stream.o WMath.o WString.o HardwareSerial.o Print.o SPI.o IPAddress.o
-ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o
-ETH_UTIL_CPPOBJ = socket.o w5100.o
-OCDEPENDENT_CPPOBJ = wiring_analog.o
-
-SERVER_OBJ := $(SERVER_CPP_SRC:.cpp=.o)
-
-#all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-all: preclean prebuild precopy prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-
-precopy:
-       @cd $(TB_DIR) && mkdir debug && cp release/liboctbstack.a debug
-
-preclean: 
-       @cd $(TB_DIR) && make deepclean 
-       
-prebuild:
-       @cd $(TB_DIR) && make PLATFORM=arduino
-
-core.a: $(CORE_COBJ) $(CORE_CPPOBJ) $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
-       @cd $(OBJ_DIR) && $(AR) -x ../$(TB_DIR)/$(BUILD)/liboctbstack.a 
-       $(AR) rcs $@ $^ $(OBJ_DIR)/*.o
-       $(RANLIB) $@
-
-prep_dirs:
-       -mkdir -p $(OBJ_DIR)
-
-%.o: %.cpp
-       $(CCPLUS) $(CPPFLAGS) $< -o $@
-
-$(APP_NAME).elf: $(APP_NAME).o core.a $(OCDEPENDENT_CPPOBJ)
-       $(CCPLUS) -Os -Wl,--gc-sections,--relax $(CPPFLAGSZ) -nodefaultlibs $^ -lm -lgcc -lc -lgcc -o $@
-
-$(APP_NAME).hex: $(APP_NAME).elf
-       avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(APP_NAME).eep
-       avr-objcopy -O ihex -R .eeprom $< $@
-
-install: all
-       avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i
-
-.PHONY: clean
-
-clean:
-       @rm -f *.o *.d *.elf *.eep *.a *.hex *-
-       @rm -rf $(OBJ_DIR)
diff --git a/service/notification-manager/SampleApp/arduino/readme.txt b/service/notification-manager/SampleApp/arduino/readme.txt
deleted file mode 100644 (file)
index 834e348..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-
-Followings should be done befor building Arudno applications 
-
-1. Applications on arduino conform  the Iotivity Base released on 22-Aug-2014.
-   (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6]))
-
-   For successful execution, you have to copy the file, local.properties, into the following pathes:
-    - oic-resource/csdk/
-    - oic-resource/csdk/libcoap-4.1.1
-
-
-2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings
-
-   Makefile path:  / oic-resource / csdk / libcoap-4.1.1 / makefile
-
-   path to be modified: 
-  
-     - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h
-     - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c
diff --git a/service/notification-manager/SampleApp/arduino/thserver.cpp b/service/notification-manager/SampleApp/arduino/thserver.cpp
deleted file mode 100644 (file)
index 35b6c25..0000000
+++ /dev/null
@@ -1,310 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "Arduino.h"
-
-#include "logger.h"
-#include "ocstack.h"
-#include  <string.h>
-
-#include <EthernetServer.h>
-#include <Ethernet.h>
-#include <Dns.h>
-#include <EthernetClient.h>
-#include <util.h>
-#include <EthernetUdp.h>
-#include <Dhcp.h>
-
-const char *getResult(OCStackResult result);
-
-#define PCF(str) ((const prog_char*)(F(str)))
-#define dht11_pin 7  //Temperature & Humidity pin
-
-const prog_char TAG[] PROGMEM = "THServer";
-
-int gQuitFlag = 0;
-int gTHUnderObservation = 0;
-
-void createTHResource();
-typedef struct THRESOURCE {
-    OCResourceHandle handle;
-    int temp;
-    int humid;
-} THResource;
-
-static THResource TH;
-
-String responsePayloadPut = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"0\",\"humidity\":\"0\"}}]}";
-String responsePayloadGet = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"0\",\"humidity\":\"0\"}}]}";
-
-
-/* read pin data */
-byte read_dht11_dat()
-{
-  byte i = 0;
-  byte result=0;
-  for(i=0; i< 8; i++)
-  {
-    while (!digitalRead(dht11_pin));
-    delayMicroseconds(30);
-    if (digitalRead(dht11_pin) != 0 )
-      bitSet(result, 7-i);
-    while (digitalRead(dht11_pin));
-  }
-  return result;
-}
-
-/* Json Generator */
-String JsonGenerator(THResource TH){
-   String a = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"";
-   String b = "\",\"humidity\":\"";
-   String c = "\"}}]}";
-
-   String ss;
-
-    ss = a + TH.temp + b + TH.humid + c;
-       return ss;
-}
-
-static uint8_t modCounter = 0;
-void *ChangeTHRepresentation (void *param)
-{
-    (void)param;
-    OCStackResult result = OC_STACK_ERROR;
-
-    modCounter += 1;
-    if(modCounter % 10 == 0)  // Matching the timing that the Linux Server App uses for the same functionality.
-    {
-         /* Temperature & Humidity value check */
-         byte dht11_dat[5];
-         byte i;// start condition
-
-         digitalWrite(dht11_pin, LOW);
-         delay(18);
-         digitalWrite(dht11_pin, HIGH);
-         delayMicroseconds(1);
-
-         pinMode(dht11_pin, INPUT);
-         delayMicroseconds(40);
-
-         if (digitalRead(dht11_pin))
-         {
-           Serial.println("dht11 start condition 1 not met");  // wait for DHT response signal: LOW
-           delay(1000);
-           return NULL;
-
-         }
-         delayMicroseconds(80);
-         if (!digitalRead(dht11_pin))
-         {
-           Serial.println("dht11 start condition 2 not met");  // wait for second response signal:HIGH
-           return NULL;
-         }
-
-         delayMicroseconds(80);                                // now ready for data reception
-         for (i=0; i<5; i++)
-         {  dht11_dat[i] = read_dht11_dat();}                  // recieved 40 bits data. 
-
-         pinMode(dht11_pin, OUTPUT);
-         digitalWrite(dht11_pin, HIGH);
-         byte dht11_check_sum = dht11_dat[0]+dht11_dat[2];     // check check_sum
-         if(dht11_dat[4]!= dht11_check_sum)
-         {
-           Serial.println("DHT11 checksum error");
-         }
-
-         delay(2000);                                  // fresh time
-         TH.humid = dht11_dat[0];
-         TH.temp = dht11_dat[2];
-
-         responsePayloadGet = JsonGenerator(TH);
-
-/* observe */
-        if (gTHUnderObservation)
-        {
-            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.humid);
-            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.temp);
-
-            result = OCNotifyObservers (TH.handle);
-
-            if (OC_STACK_NO_OBSERVERS == result)
-            {
-                gTHUnderObservation = 0;
-            }
-        }
-    }
-    return NULL;
-}
-
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest ) {
-    const char* typeOfMessage;
-
-    OCEntityHandlerResult ehRet = OC_EH_OK;
-
-    switch (flag) {
-    case OC_INIT_FLAG:
-        typeOfMessage = "OC_INIT_FLAG";
-        break;
-    case OC_REQUEST_FLAG:
-        typeOfMessage = "OC_REQUEST_FLAG";
-        break;
-    case OC_OBSERVE_FLAG:
-        typeOfMessage = "OC_OBSERVE_FLAG";
-        break;
-    default:
-        typeOfMessage = "UNKNOWN";
-    }
-    OC_LOG_V(INFO, TAG, "Receiving message type: %s", typeOfMessage);
-    if(entityHandlerRequest && flag == OC_REQUEST_FLAG) { 
-        if(OC_REST_GET == entityHandlerRequest->method) {
-
-            int str_len = responsePayloadGet.length() + 1;
-            char charBuf[str_len+1];
-
-            responsePayloadGet.toCharArray(charBuf, str_len);
-
-            if(strlen(charBuf) < entityHandlerRequest->resJSONPayloadLen)
-            {
-            strncpy((char *)entityHandlerRequest->resJSONPayload, charBuf, entityHandlerRequest->resJSONPayloadLen);
-            }
-            else
-                ehRet = OC_EH_ERROR;
-        }
-        if(OC_REST_PUT == entityHandlerRequest->method) {
-
-            int str_len1 = responsePayloadPut.length() + 1;
-            char charBuf1[str_len1];
-
-            responsePayloadPut.toCharArray(charBuf1, str_len1);
-
-             if(strlen(charBuf1) < entityHandlerRequest->resJSONPayloadLen)
-            {
-            strncpy((char *)entityHandlerRequest->resJSONPayload, charBuf1, entityHandlerRequest->resJSONPayloadLen);
-            }
-             else
-               ehRet = OC_EH_ERROR;
-        }
-    } else if (entityHandlerRequest && flag == OC_OBSERVE_FLAG) {
-        gTHUnderObservation = 1;
-    }
-
-    return ehRet;
-}
-
-/* The setup function is called once at startup of the sketch */
-void setup()
-{
-    pinMode(dht11_pin, OUTPUT);   
-    digitalWrite(dht11_pin, HIGH);
-
-    OC_LOG_INIT();
-
-    OC_LOG(DEBUG, TAG, PCF("THServer is starting..."));
-    uint16_t port = USE_RANDOM_PORT;
-
-    /* Mac address of my ethernet shield */
-    uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAB};
-    uint8_t error = Ethernet.begin(ETHERNET_MAC);
-    Serial.print(Ethernet.localIP());
-    if (error  == 0)
-    {
-        OC_LOG_V(ERROR, TAG, "error is: %d", error);
-        return;
-    }
-
-    if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, TAG, PCF("OCStack init error"));
-        return;
-    }
-
-    /*
-     * Declare and create the resource: TH
-     */
-
-    createTHResource();
-
-}
-
-/* The loop function is called in an endless loop */
-void loop()
-{
-    delay(1000);
-    if (OCProcess() != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, TAG, PCF("OCStack process error"));
-        return;
-    }
-    ChangeTHRepresentation(NULL);
-}
-
-void createTHResource() {
-    TH.humid = 0;
-    TH.temp = 0;
-
-    OCStackResult res = OCCreateResource(&TH.handle,
-                                         "SoftSensorManager.Sensor",
-                                         "oc.mi.def",
-                                         "/Thing_TempHumSensor",
-                                         OCEntityHandlerCb,
-                                         OC_DISCOVERABLE|OC_OBSERVABLE);
-    OC_LOG_V(INFO, TAG, "Created TH resource with result: %s", getResult(res));
-}
-
-const char *getResult(OCStackResult result) {
-    switch (result) {
-    case OC_STACK_OK:
-        return "OC_STACK_OK";
-    case OC_STACK_INVALID_URI:
-        return "OC_STACK_INVALID_URI";
-    case OC_STACK_INVALID_QUERY:
-        return "OC_STACK_INVALID_QUERY";
-    case OC_STACK_INVALID_IP:
-        return "OC_STACK_INVALID_IP";
-    case OC_STACK_INVALID_PORT:
-        return "OC_STACK_INVALID_PORT";
-    case OC_STACK_INVALID_CALLBACK:
-        return "OC_STACK_INVALID_CALLBACK";
-    case OC_STACK_INVALID_METHOD:
-        return "OC_STACK_INVALID_METHOD";
-    case OC_STACK_NO_MEMORY:
-        return "OC_STACK_NO_MEMORY";
-    case OC_STACK_COMM_ERROR:
-        return "OC_STACK_COMM_ERROR";
-    case OC_STACK_INVALID_PARAM:
-        return "OC_STACK_INVALID_PARAM";
-    case OC_STACK_NOTIMPL:
-        return "OC_STACK_NOTIMPL";
-    case OC_STACK_NO_RESOURCE:
-        return "OC_STACK_NO_RESOURCE";
-    case OC_STACK_RESOURCE_ERROR:
-        return "OC_STACK_RESOURCE_ERROR";
-    case OC_STACK_SLOW_RESOURCE:
-        return "OC_STACK_SLOW_RESOURCE";
-    case OC_STACK_NO_OBSERVERS:
-        return "OC_STACK_NO_OBSERVERS";
-    case OC_STACK_ERROR:
-        return "OC_STACK_ERROR";
-    default:
-        return "UNKNOWN";
-    }
-}
-
-
index be46453..0a436f6 100644 (file)
@@ -12,11 +12,29 @@ notimgr_env = lib_env.Clone()
 # Build flags
 ######################################################################
 notimgr_env.AppendUnique(CPPPATH = ['../../NotificationManager/include'])
-notimgr_env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap', 'pthread'])
+notimgr_env.AppendUnique(CPPPATH = ['../../../../extlibs/cjson'])
+notimgr_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/connectivity/api'])
 notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+notimgr_c_env = notimgr_env.Clone()
+notimgr_env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread'])
+notimgr_c_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'pthread','NotificationManager'])
 
-######################################################################
+if env.get('SECURED') == '1':
+    notimgr_env.AppendUnique(LIBS = ['tinydtls'])
+    notimgr_c_env.AppendUnique(LIBS = ['tinydtls'])
+if 'rt' in notimgr_env.get('LIBS'):
+    notimgr_env.Append(LIBS = ['rt'])
+if 'rt' in notimgr_c_env.get('LIBS'):
+    notimgr_c_env.Append(LIBS = ['rt'])
+
+####################################################################
 # 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')
+
+notificationmanager = notimgr_c_env.Program('notificationmanager', 'notificationManager/main.c')
+
+#notimgr_env.InstallTarget(sampleprovider, 'sampleprovider')
+#notimgr_env.InstallTarget(sampleconsumer, 'sampleconsumer')
+#notimgr_env.InstallTarget(notificationmanager, 'notificationmanager')
diff --git a/service/notification-manager/SampleApp/linux/notificationManager/main.c b/service/notification-manager/SampleApp/linux/notificationManager/main.c
new file mode 100644 (file)
index 0000000..830db3a
--- /dev/null
@@ -0,0 +1,96 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <signal.h>
+#include <unistd.h>
+
+#include "hosting.h"
+
+int g_quitFlag = 0;
+
+void handleSigInt(int signum);
+
+/*
+* This method is an entry point of Resource Hosting Manager.
+* This function should be run only on the device that it could be host device.
+*/
+int main()
+{
+    printf("OCResourceHosting is starting...\n");
+
+    if (OCInit((char *) NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
+    {
+        printf("OCStack init error\n");
+        return 0;
+    }
+
+    if (OICStartCoordinate() != OC_STACK_OK)
+    {
+        printf("OIC coordinate start fail\n");
+        return 0;
+    }
+
+    signal(SIGINT, handleSigInt);
+    while (!g_quitFlag)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OICStopCoordinate();
+            printf("OCStack process error\n");
+            return 0;
+        }
+
+        sleep(2);
+    }
+
+    if (OICStopCoordinate() != OC_STACK_OK)
+    {
+        printf("OIC coordinate stop error\n");
+    }
+    else
+    {
+        printf("OIC coordinate stop success\n");
+    }
+
+    printf("Exiting occlient main loop...\n");
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        printf("OCStack stop error\n");
+    }
+
+    return 0;
+
+}
+
+/*
+* This is a signal handling function for SIGINT(CTRL+C).
+* A Resource Coordinator handle the SIGINT signal for safe exit.
+*
+* @param[in] signal
+*                 signal number of caught signal.
+*/
+void handleSigInt(int signum)
+{
+    if (signum == SIGINT)
+    {
+        g_quitFlag = 1;
+    }
+}
index fd1e6f6..afb6de4 100644 (file)
@@ -1,6 +1,6 @@
 //******************************************************************
 //
-// Copyright 2014 Samsung Electronics All Rights Reserved.
+// Copyright 2015 Samsung Electronics All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-// OCClient.cpp : Defines the entry point for the console application.
-//
+/**
+ * @file SampleConsumer.cpp
+ * @brief Defines the entry point for the sample consumer application about Resource Hosting.
+ */
 
 #include <string>
 #include <cstdlib>
 #include <pthread.h>
 #include "OCPlatform.h"
 #include "OCApi.h"
+#include <mutex>
 
 using namespace OC;
 
 const int SUCCESS_RESPONSE = OC_STACK_OK;
-static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+
+#define OC_WELL_KNOWN_COORDINATING_QUERY "/oc/core?rt=Resource.Hosting"
+
+#define OBSERVE 1
+#define GET     2
+#define PUT     3
+#define DELETE  4
 
 std::shared_ptr< OCResource > g_curResource;
+std::shared_ptr< OCResource > g_curObserveResource;
+std::mutex curResourceLock;
+
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName);
+void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode,
+               const int &sequenceNumber);
+
+void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode);
+void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode);
+void onDelete(const HeaderOptions &headerOption , const int eCode);
 
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName);
-void onObserve(const HeaderOptions &headerOption , const OCRepresentation& rep , const int& eCode, const int& sequenceNumber);
 
 void findResourceCandidate()
 {
     try
     {
-        nmfindResource("" , "coap://224.0.1.187/oc/core?rt=NotificationManager.Hosting");
+        nmfindResource("" , OC_WELL_KNOWN_COORDINATING_QUERY);
         std::cout << "Finding Resource... " << std::endl;
-        while(true)
-        {
-               char signal;
-                       cin >> signal;
-
-                       switch(signal)
-                       {
-                       case 'q':
-                       case 'Q':
-                               exit(-1);
-                       default:
-                               break;
-                       }
-        }
 
     }
-    catch(OCException& e)
+    catch (OCException &e)
     {
+        std::cout << "Exception for find resource : " << e.reason() << std::endl;
     }
 }
 
 void startObserve(std::shared_ptr< OCResource > resource)
 {
-    g_curResource = resource;
+    if (resource == NULL)
+    {
+        std::cout << "startObserve() error : resource == null" << std::endl;
+        return;
+    }
+
+    if(g_curObserveResource == NULL)
+    {
+        g_curObserveResource = resource;
+        std::cout << "request for new observation" << std::endl;
+    }
+    else if(g_curObserveResource == g_curResource)
+    {
+        std::cout << "already registered same observation" << std::endl;
+        return;
+    }
+    else
+    {
+        std::cout << "change observed resource" << std::endl;
+        g_curObserveResource->cancelObserve();
+        g_curObserveResource = resource;
+    }
 
     QueryParamsMap test;
-    resource->observe(ObserveType::Observe , test , &onObserve);
+    if (OC_STACK_OK != resource->observe(ObserveType::Observe , test , &onObserve))
+        std::cout << "To Fail resource observe() process" << std::endl;
 }
 
-int observe_count()
+void startGet(std::shared_ptr< OCResource > resource)
 {
-    static int oc = 0;
-    return ++oc;
+
+    if (resource == NULL)
+    {
+        std::cout << "startObserve() error : resource == null" << std::endl;
+        return;
+    }
+
+    QueryParamsMap test;
+    std::cout << "URI :" << resource->uri() << std::endl;
+    if (OC_STACK_OK != resource->get(test, &onGet))
+        std::cout << "To Fail resource get() process" << std::endl;
 }
 
-void onObserve(const HeaderOptions &headerOption , const OCRepresentation& rep , const int& eCode, const int& sequenceNumber)
+void startPut(std::shared_ptr< OCResource > resource)
 {
-       std::cout << "onObserve" << std::endl;
-//    if(eCode == SUCCESS_RESPONSE)
-       if(eCode <= OC_STACK_RESOURCE_DELETED)
+    if (resource == NULL)
     {
+        std::cout << "startObserve() error : resource == null" << std::endl;
+        return;
+    }
 
-        AttributeMap attributeMap = rep.getAttributeMap();
+    g_curResource = resource;
+    OCRepresentation rep;
+    rep.setValue("temperature", 25);
+    rep.setValue("humidity", 10);
 
-        for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
-        {
-            if(attributeMap.find(it->first) == attributeMap.end())
-            {
-                return;
-            }
-        }
+    QueryParamsMap test;
+    if (OC_STACK_OK != resource->put(rep, test, &onPut))
+        std::cout << "To Fail resource put() process" << std::endl;
+}
 
-        if(rep.getUri().empty())
-        {
-               cout << "uri is null\n";
-            return;
-        }
+void startDelete(std::shared_ptr< OCResource > resource)
+{
+    if (resource == NULL)
+    {
+        std::cout << "startObserve() error : resource == null" << std::endl;
+        return;
+    }
 
+    g_curResource = resource;
+    if (OC_STACK_OK != resource->deleteResource(&onDelete))
+        std::cout << "To Fail resource delete() process" << std::endl;
+}
+
+int observe_count()
+{
+    static int oc = 0;
+    return ++oc;
+}
+
+void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode,
+               const int &sequenceNumber)
+{
+    std::cout << "onObserve" << std::endl;
+
+    if (eCode <= OC_STACK_OK)
+    {
         std::cout << std::endl;
         std::cout << "========================================================" << std::endl;
         std::cout << "Receive OBSERVE RESULT:" << std::endl;
+        std::cout << "\tUri: " << rep.getUri() << std::endl;
         std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
-        for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
-        {
-            std::cout << "\tAttribute name: " << it->first << " value: ";
-            for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
-            {
-                std::cout << "\t" << *valueItr << " ";
-            }
-
-            std::cout << std::endl;
-        }
+        std::cout << "\tTemperature : " << rep.getValue<int>("temperature") << std::endl;
+        std::cout << "\tHumidity : " << rep.getValue<int>("humidity") << std::endl;
 
-        if(observe_count() > 30)
+        if (observe_count() > 30)
         {
             std::cout << "Cancelling Observe..." << std::endl;
             OCStackResult result = g_curResource->cancelObserve();
@@ -138,12 +187,16 @@ void foundResource(std::shared_ptr< OCResource > resource)
 {
     std::string resourceURI;
     std::string hostAddress;
+
+    std::cout << "foundResource" << std::endl;
+
     try
     {
-        if(resource)
+        std::cout << "mutex lock passed" << std::endl;
+        if (resource)
         {
-//            if(resource->uri().find("/a/NM/TempHumSensor/virtual") != std::string::npos)
-                       if(resource->uri().find("/a/NM/TempHumSensor") != std::string::npos)
+            std::cout << resource->uri() << std::endl;
+            if (resource->uri() == "/a/TempHumSensor")
             {
                 std::cout << std::endl;
                 std::cout << "========================================================" << std::endl;
@@ -155,7 +208,7 @@ void foundResource(std::shared_ptr< OCResource > resource)
                 hostAddress = resource->host();
                 std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
 
-                startObserve(resource);
+                g_curResource = resource;
             }
         }
         else
@@ -164,120 +217,85 @@ void foundResource(std::shared_ptr< OCResource > resource)
         }
 
     }
-    catch(std::exception& e)
+    catch (std::exception &e)
     {
+        std::cout << "Exception: " << e.what() << " in foundResource" << std::endl;
     }
 }
 
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName)
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName)
 {
-    return OCPlatform::findResource(host , resourceName , &foundResource);
+    return OCPlatform::findResource(host , resourceName , OC_ALL, &foundResource);
 }
 
 void getRepresentation(std::shared_ptr< OCResource > resource)
 {
-    if(resource)
+    if (resource)
     {
         std::cout << "Getting Light Representation..." << std::endl;
     }
 }
 
-void onPut(const OCRepresentation& rep , const int eCode)
+void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode)
 {
-    if(eCode == SUCCESS_RESPONSE)
+    try
     {
-        std::cout << "PUT request was successful" << std::endl;
-
-        AttributeMap attributeMap = rep.getAttributeMap();
-
-        for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+        if (eCode == OC_STACK_OK)
         {
-            std::cout << "\tAttribute name: " << it->first << " value: ";
-            for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
-            {
-                std::cout << "\t" << *valueItr << " ";
-            }
+            std::cout << "PUT request was successful" << std::endl;
+            int humidity;
+            int temperature;
+            rep.getValue("temperature", temperature);
+            rep.getValue("humidity", humidity);
 
-            std::cout << std::endl;
-        }
-
-        std::vector< OCRepresentation > children = rep.getChildren();
 
-        for(auto oit = children.begin() ; oit != children.end() ; ++oit)
+            std::cout << "\t temperature: " << temperature << std::endl;
+            std::cout << "\t humidity: " << humidity << std::endl;
+        }
+        else
         {
-            attributeMap = oit->getAttributeMap();
-
-            for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
-            {
-                std::cout << "\tAttribute name: " << it->first << " value: ";
-                for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
-                {
-                    std::cout << "\t" << *valueItr << " ";
-                }
-
-                std::cout << std::endl;
-            }
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
         }
-
-        if(OBSERVE_TYPE_TO_USE == ObserveType::Observe)
-            std::cout << std::endl << "Observe is used." << std::endl << std::endl;
-        else if(OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
-            std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
-
-        QueryParamsMap test;
-
-        g_curResource->observe(ObserveType::Observe , test , &onObserve);
-
     }
-    else
+    catch (std::exception &e)
     {
-        std::cout << "onPut Response error: " << eCode << std::endl;
-        std::exit(-1);
+        std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
     }
 }
 
-// callback handler on GET request
-void onGet(const HeaderOptions &headerOption , const OCRepresentation& rep , const int eCode)
+//callback hadnler on DELETE request
+void onDelete(const HeaderOptions &headerOption , const int eCode)
 {
-    if(eCode == SUCCESS_RESPONSE)
+    try
     {
-        std::cout << "GET request was successful" << std::endl;
-
-        AttributeMap attributeMap = rep.getAttributeMap();
-
-        std::cout << "Resource URI: " << rep.getUri() << std::endl;
-
-        for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+        if (eCode == OC_STACK_RESOURCE_DELETED)
         {
-            std::cout << "\tAttribute name: " << it->first << " value: ";
-            for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
-            {
-                std::cout << "\t" << *valueItr << " ";
-            }
-
-            std::cout << std::endl;
+            std::cout << "DELETE request was successful" << std::endl;
         }
-
-        std::vector< OCRepresentation > children = rep.getChildren();
-
-        for(auto oit = children.begin() ; oit != children.end() ; ++oit)
+        else
         {
-            std::cout << "Child Resource URI: " << oit->getUri() << std::endl;
-
-            attributeMap = oit->getAttributeMap();
-
-            for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
-            {
-                std::cout << "\tAttribute name: " << it->first << " value: ";
-                for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
-                {
-                    std::cout << "\t" << *valueItr << " ";
-                }
-
-                std::cout << std::endl;
-            }
+            std::cout << "onDelete Response error: " << eCode << std::endl;
+            std::exit(-1);
         }
     }
+    catch (std::exception &e)
+    {
+        std::cout << "Exception: " << e.what() << " in onDelete" << std::endl;
+    }
+}
+
+// callback handler on GET request
+void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode)
+{
+    std::cout << "GET request was successful1" << std::endl;
+    if (eCode == SUCCESS_RESPONSE)
+    {
+        std::cout << "GET request was successful" << std::endl;
+        std::cout << "Resource URI: " << rep.getUri().c_str() << std::endl;
+        std::cout << "\tTemperature : " << rep.getValue<int>("temperature") << std::endl;
+        std::cout << "\tHumidity : " << rep.getValue<int>("humidity") << std::endl;
+    }
     else
     {
         std::cout << "onGET Response error: " << eCode << std::endl;
@@ -287,7 +305,7 @@ void onGet(const HeaderOptions &headerOption , const OCRepresentation& rep , con
 
 void getLightRepresentation(std::shared_ptr< OCResource > resource)
 {
-    if(resource)
+    if (resource)
     {
         std::cout << "Getting Light Representation..." << std::endl;
 
@@ -304,36 +322,76 @@ void PrintUsage()
     std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
 }
 
-int main(int argc , char* argv[])
+void PRINT()
 {
+    std::cout << std::endl;
+    std::cout << "********************************************" << std::endl;
+    std::cout << "*  method Type : 1 - Observe               *" << std::endl;
+    std::cout << "*  method Type : 2 - Get                   *" << std::endl;
+    std::cout << "*  method Type : 3 - Put                   *" << std::endl;
+    std::cout << "*  method Type : 4 - Delete                *" << std::endl;
+    std::cout << "********************************************" << std::endl;
+    std::cout << std::endl;
+}
 
-    if(argc == 1)
-    {
-        OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-    }
-    else if(argc == 2)
-    {
-        int value = atoi(argv[1]);
-        if(value == 1)
-            OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-        else if(value == 2)
-            OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
-        else
-            OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-    }
-    else
-    {
-        PrintUsage();
-        return -1;
-    }
+int main(int argc , char *argv[])
+{
 
+    int in;
     PlatformConfig cfg;
 
     OCPlatform::Configure(cfg);
 
     std::cout << "Created Platform..." << std::endl;
+
+    g_curResource = NULL;
+    g_curObserveResource = NULL;
+
     findResourceCandidate();
 
+    while (1)
+    {
+        sleep(2);
+        if(g_curResource == NULL)
+        {
+            continue;
+        }
+        PRINT();
+
+        in = 0;
+        std::cin >> in;
+
+        if(std::cin.fail())
+        {
+            std::cin.clear();
+            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+            std::cout << "Invalid input type, please try again" << std::endl;
+            continue;
+        }
+
+        try {
+            switch ((int)in)
+            {
+                case OBSERVE:
+                    startObserve(g_curResource);
+                    break;
+                case GET:
+                    startGet(g_curResource);
+                    break;
+                case PUT:
+                    startPut(g_curResource);
+                    break;
+                case DELETE:
+                    startDelete(g_curResource);
+                    break;
+                default:
+                    std::cout << "Invalid input, please try again" << std::endl;
+                    break;
+            }
+        }catch(OCException e) {
+            std::cout<< "Caught OCException [Code: "<<e.code()<<" Reason: "<<e.reason()<<std::endl;
+        }
+    }
+
     return 0;
 }
-
index 7cbec29..abb40db 100644 (file)
@@ -1,6 +1,6 @@
 //******************************************************************
 //
-// Copyright 2014 Samsung Electronics All Rights Reserved.
+// Copyright 2015 Samsung Electronics All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //
@@ -21,6 +21,7 @@
 #include <functional>
 
 #include <pthread.h>
+#include <signal.h>
 
 #include "OCPlatform.h"
 #include "OCApi.h"
 
 using namespace OC;
 using namespace std;
+using namespace OC::OCPlatform;
 
 int g_Observation = 0;
+int gQuitFlag = 0;
 
 pthread_cond_t m_cond = PTHREAD_COND_INITIALIZER;
 pthread_mutex_t m_mutex = PTHREAD_MUTEX_INITIALIZER;
 
-OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request ,
-                                    std::shared_ptr< OCResourceResponse > response);
+
+
+OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request);
 
 class TempHumidResource
 {
-public:
+    public:
+
+        int m_temp;
+        int m_humid;
+        std::string m_uri;
+        OCResourceHandle m_resourceHandle;
+        ObservationIds m_interestedObservers;
+        OCRepresentation m_Rep;
+
+    public:
+        TempHumidResource() :
+            m_temp(0), m_humid(0), m_uri("/a/TempHumSensor"), m_resourceHandle(NULL)
+        {
+        }
 
-    int m_temp;
-    int m_humid;
+        void createResource()
+        {
+            std::string resourceURI = "/a/TempHumSensor/hosting";
+            std::string resourceTypeName = "Resource.Hosting";
+            std::string resourceInterface = DEFAULT_INTERFACE;
 
-    std::string m_uri;
-    OCResourceHandle m_resourceHandle;
+            m_uri = resourceURI;
 
-    OCRepresentation m_Rep;
+            uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
 
-public:
-    TempHumidResource() :
-            m_temp(0), m_humid(0), m_uri("/a/TempHumSensor")
-    {
-    }
+            OCStackResult result = OCPlatform::registerResource(m_resourceHandle , resourceURI ,
+                                   resourceTypeName , resourceInterface , &entityHandler , resourceProperty);
 
-    void createResource()
-    {
-        std::string resourceURI = "/a/NM/TempHumSensor";
-        std::string resourceTypeName = "NotificationManager.Hosting";
-        std::string resourceInterface = DEFAULT_INTERFACE;
+            if (OC_STACK_OK != result)
+            {
+                cout << "Resource creation was unsuccessful\n";
+            }
+        }
 
-        m_uri = resourceURI;
+        OCStackResult createResource1()
+        {
+            std::string resourceURI = "/a/NM/TempHumSensor1"; // URI of the resource
+            std::string resourceTypeName =
+                "NotificationManager.Hosting"; // resource type name. In this case, it is light
+            std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
 
-        uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+            // OCResourceProperty is defined ocstack.h
+            uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
 
-        OCStackResult result = OCPlatform::registerResource(m_resourceHandle , resourceURI ,
-                resourceTypeName , resourceInterface , &entityHandler , resourceProperty);
+            OCResourceHandle resHandle;
 
-        if(OC_STACK_OK != result)
-        {
-            cout << "Resource creation was unsuccessful\n";
-        }
-    }
+            // This will internally create and register the resource.
+            OCStackResult result = OCPlatform::registerResource(
+                                       resHandle, resourceURI, resourceTypeName,
+                                       resourceInterface, &entityHandler, resourceProperty);
 
-    OCStackResult createResource1()
-       {
-               std::string resourceURI = "/a/NM/TempHumSensor1"; // URI of the resource
-               std::string resourceTypeName = "NotificationManager.Hosting"; // resource type name. In this case, it is light
-               std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
-
-               // OCResourceProperty is defined ocstack.h
-               uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+            if (OC_STACK_OK != result)
+            {
+                cout << "Resource creation was unsuccessful\n";
+            }
 
-               OCResourceHandle resHandle;
+            return result;
+        }
 
-               // This will internally create and register the resource.
-               OCStackResult result = OCPlatform::registerResource(
-                                                                       resHandle, resourceURI, resourceTypeName,
-                                                                       resourceInterface, &entityHandler, resourceProperty);
+        OCResourceHandle getHandle()
+        {
+            return m_resourceHandle;
+        }
 
-               if (OC_STACK_OK != result)
-               {
-                       cout << "Resource creation was unsuccessful\n";
-               }
+        OCRepresentation post(OCRepresentation &rep)
+        {
+            static int first = 1;
+            // for the first time it tries to create a resource
+            if (first)
+            {
+                first = 0;
 
-               return result;
-       }
+                if (OC_STACK_OK == createResource1())
+                {
+                    OCRepresentation rep1;
+                    rep1.setValue("createduri", std::string("/a/light1"));
 
-    OCResourceHandle getHandle()
-    {
-        return m_resourceHandle;
-    }
+                    return rep1;
+                }
+            }
 
-    OCRepresentation post(OCRepresentation& rep)
-    {
-        static int first = 1;
+            // from second time onwards it just puts
+            put(rep);
+            return get();
+        }
 
-        // for the first time it tries to create a resource
-        if(first)
+        void put(OCRepresentation &rep)
         {
-            first = 0;
-
-            if(OC_STACK_OK == createResource1())
+            try
             {
-                OCRepresentation rep1;
-                rep1.setValue("createduri", std::string("/a/light1"));
+                if (rep.getValue("temperature", m_temp))
+                {
+                    cout << "\t\t\t\t" << "temperature: " << m_temp << endl;
+                }
+                else
+                {
+                    cout << "\t\t\t\t" << "temperature not found in the representation" << endl;
+                }
 
-                return rep1;
+                if (rep.getValue("humidity", m_humid))
+                {
+                    cout << "\t\t\t\t" << "humidity: " << m_humid << endl;
+                }
+                else
+                {
+                    cout << "\t\t\t\t" << "humidity not found in the representation" << endl;
+                }
+            }
+            catch (exception &e)
+            {
+                cout << e.what() << endl;
             }
-        }
-
-        // from second time onwards it just puts
-        put(rep);
-        return get();
-    }
 
-    void put(OCRepresentation& rep)
-       {
-               try {
-                       if (rep.getValue("temperature", m_temp))
-                       {
-                               cout << "\t\t\t\t" << "temperature: " << m_temp << endl;
-                       }
-                       else
-                       {
-                               cout << "\t\t\t\t" << "temperature not found in the representation" << endl;
-                       }
-
-                       if (rep.getValue("humidity", m_humid))
-                       {
-                               cout << "\t\t\t\t" << "humidity: " << m_humid << endl;
-                       }
-                       else
-                       {
-                               cout << "\t\t\t\t" << "humidity not found in the representation" << endl;
-                       }
-               }
-               catch (exception& e)
-               {
-                       cout << e.what() << endl;
-               }
-
-       }
-
-    OCRepresentation get()
-       {
-       cout << "resource get\n";
-               m_Rep.setValue("temperature", m_temp);
-               m_Rep.setValue("humidity", m_humid);
-
-               cout << "resource get : done\n";
-
-               return m_Rep;
-       }
+        }
 
+        OCRepresentation get()
+        {
+            m_Rep.setValue("temperature", m_temp);
+            m_Rep.setValue("humidity", m_humid);
+            return m_Rep;
+        }
+        OCStackResult deleteDeviceResource()
+        {
+            OCStackResult result = OCPlatform::unregisterResource(m_resourceHandle);
+            if (OC_STACK_OK != result)
+            {
+                throw std::runtime_error(
+                    std::string("Device Resource failed to unregister/delete") + std::to_string(result));
+            }
+            return result;
+        }
 };
 
 TempHumidResource myResource;
 
 void *ChangeLightRepresentation(void *param)
 {
-       cout << "ChangeLigthRepresentation Enter\n";
-       while(1){
-               cout << "pthread_cond_wait\n";
-               pthread_cond_wait(&m_cond, &m_mutex);
-               cout << "pthread_cond_start\n";
-               if(g_Observation)
-               {
-
-                       cout << endl;
-                       cout << "========================================================" << endl;
-                       cout << "HUMTepm updated to : " << myResource.m_temp << endl;
-                       cout << "Notifying observers with resource handle: " << myResource.getHandle() << endl;
-
-                       cout << endl;
-                       cout << "========================================================" << endl;
-                       cout << "Send data : \n";
-                       cout << "Attribute Name: Temp\tvalue: " << myResource.m_temp << endl;
-                       cout << "Attribute Name: Humid\tvalue: " << myResource.m_humid << endl;
-
-                       OCStackResult result = OCPlatform::notifyAllObservers(myResource.getHandle());
-                       cout << "Notify Success\n";
-
-                       if(OC_STACK_NO_OBSERVERS == result)
-                       {
-                               cout << "No More observers, stopping notifications" << endl;
-                               g_Observation = 0;
-                       }
-               }
-               cout << "ChangeLigthRepresentation Out\n";
-
-       }
+    cout << "ChangeLigthRepresentation Enter\n";
+    while (1)
+    {
+        cout << "pthread_cond_wait\n";
+        pthread_cond_wait(&m_cond, &m_mutex);
+        cout << "pthread_cond_start\n";
+        if (g_Observation)
+        {
+
+            cout << endl;
+            cout << "========================================================" << endl;
+            cout << "HUMTepm updated to : " << myResource.m_temp << endl;
+            cout << "Notifying observers with resource handle: " << myResource.getHandle() << endl;
+
+            cout << endl;
+            cout << "========================================================" << endl;
+            cout << "Send data : \n";
+            cout << "Attribute Name: Temp\tvalue: " << myResource.m_temp << endl;
+            cout << "Attribute Name: Humid\tvalue: " << myResource.m_humid << endl;
+
+            OCStackResult result = OCPlatform::notifyAllObservers(myResource.getHandle());
+            cout << "Notify Success\n";
+
+            if (OC_STACK_NO_OBSERVERS == result)
+            {
+                cout << "No More observers, stopping notifications" << endl;
+                g_Observation = 0;
+            }
+        }
+        cout << "ChangeLigthRepresentation Out\n";
+
+    }
     return NULL;
 }
 
-OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request ,
-        std::shared_ptr< OCResourceResponse > response)
+OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
 {
-       cout << "Sample Provider entityHandler\n";
-    if(request)
+    cout << "Sample Provider entityHandler\n";
+
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+    if (request)
     {
-       cout << "flag : request\n";
+        cout << "flag : request\n";
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag == RequestHandlerFlag::InitFlag)
+        if (requestFlag == RequestHandlerFlag::RequestFlag)
         {
-               cout << "\t\trequestFlag : Init\n";
-        }
+            cout << "\t\trequestFlag : Request\n";
+            auto pResponse = std::make_shared<OC::OCResourceResponse>();
+            pResponse->setRequestHandle(request->getRequestHandle());
+            pResponse->setResourceHandle(request->getResourceHandle());
 
-        if(requestFlag == RequestHandlerFlag::RequestFlag)
-        {
-               cout << "\t\trequestFlag : Request\n";
-            if(requestType == "GET")
+            if (requestType == "GET")
             {
-               cout << "\t\trequestType : GET\n";
-               try
-               {
-                                       if(response)
-                                       {
-                                               OCRepresentation rep = myResource.get();
-                                               cout << rep.getJSONRepresentation() << endl;
-                                               response->setErrorCode(200);
-                                               response->setResourceRepresentation(rep, DEFAULT_INTERFACE);
-                                       }
-                                       else
-                                       {
-                                               cout << "response is null\n";
-                                       }
-               } catch(exception& e)
-               {
-                       cout << e.what() << endl;
-               }
+                cout << "\t\trequestType : GET\n";
+
+                pResponse->setErrorCode(200);
+                pResponse->setResponseResult(OC_EH_OK);
+                pResponse->setResourceRepresentation(myResource.get());
+                if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    ehResult = OC_EH_OK;
+                }
             }
-            else if(requestType == "PUT")
+
+            else if (requestType == "PUT")
             {
                 cout << "\t\t\trequestType : PUT\n";
 
                 OCRepresentation rep = request->getResourceRepresentation();
                 myResource.put(rep);
 
-                if(response)
+                if (pResponse)
+                {
+                    pResponse->setErrorCode(200);
+                    pResponse->setResourceRepresentation(myResource.get());
+                }
+                if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                 {
-                    response->setErrorCode(200);
-                    response->setResourceRepresentation(myResource.get());
+                    ehResult = OC_EH_OK;
+                }
+                else
+                {
+                    cout << "put request Error\n";
                 }
             }
-            else if(requestType == "POST")
+
+            else if (requestType == "POST")
             {
+                cout << "\t\t\trequestType : POST\n";
             }
-            else if(requestType == "DELETE")
+
+            else if (requestType == "DELETE")
             {
+                cout << "\t\trequestType : DELETE\n";
+                cout << "DeviceResource Delete Request" << std::endl;
+
+                if (myResource.deleteDeviceResource() == OC_STACK_OK)
+                {
+                    cout << "\tSuccess DELETE\n";
+                    pResponse->setErrorCode(200);
+                    pResponse->setResponseResult(OC_EH_RESOURCE_DELETED);
+                    ehResult = OC_EH_OK;
+                }
+                else
+                {
+                    pResponse->setResponseResult(OC_EH_ERROR);
+                    ehResult = OC_EH_ERROR;
+                }
+
+                OCPlatform::sendResponse(pResponse);
             }
         }
-        else if(requestFlag & RequestHandlerFlag::ObserverFlag)
+        if (requestFlag & RequestHandlerFlag::ObserverFlag)
         {
-               pthread_t threadId;
+            pthread_t threadId;
+
+            ObservationInfo observationInfo = request->getObservationInfo();
+            if (ObserveAction::ObserveRegister == observationInfo.action)
+            {
+                myResource.m_interestedObservers.push_back(observationInfo.obsId);
+            }
+            else if (ObserveAction::ObserveUnregister == observationInfo.action)
+            {
+                myResource.m_interestedObservers.erase(std::remove(
+                        myResource.m_interestedObservers.begin(),
+                        myResource.m_interestedObservers.end(),
+                        observationInfo.obsId),
+                                                       myResource.m_interestedObservers.end());
+            }
 
             cout << request->getResourceUri() << endl;
             cout << request->getResourceRepresentation().getUri() << endl;
@@ -280,12 +324,13 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request
 
             cout << "\t\trequestFlag : Observer\n";
             static int startedThread = 0;
-            if(!startedThread)
+            if (!startedThread)
             {
-               cout << "\t\tpthrerad_create\n";
+                cout << "\t\tpthrerad_create\n";
                 pthread_create(&threadId , NULL , ChangeLightRepresentation , (void *) NULL);
                 startedThread = 1;
             }
+            ehResult = OC_EH_OK;
         }
     }
     else
@@ -293,30 +338,48 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request
         std::cout << "Request invalid" << std::endl;
     }
 
-    return OC_EH_OK;
+    return ehResult;
 }
 
-int main()
+void quitProcess()
+{
+    unregisterResource(myResource.m_resourceHandle);
+    stopPresence();
+    exit(0);
+}
+
+void handleSigInt(int signum)
 {
+    if (signum == SIGINT)
+    {
+        std::cout << " handleSigInt in" << std::endl;
+        quitProcess();
+    }
+}
 
-       PlatformConfig cfg {
-               OC::ServiceType::InProc,
-               OC::ModeType::Server,
-               "0.0.0.0",
-               0,
-               OC::QualityOfService::LowQos
-           };
+int main()
+{
+    PlatformConfig cfg
+    {
+        OC::ServiceType::InProc,
+        OC::ModeType::Server,
+        "0.0.0.0",
+        0,
+        OC::QualityOfService::LowQos
+    };
 
-       OCPlatform::Configure(cfg);
+    OCPlatform::Configure(cfg);
 
     int number = 0;
 
     try
     {
+        startPresence(30);
 
         myResource.createResource();
 
-        while(true)
+        signal(SIGINT, handleSigInt);
+        while (true)
         {
             bool end = false;
             cout << endl;
@@ -325,46 +388,58 @@ int main()
             cout << "2. Temp is down" << endl;
             cout << "3. This Program will be ended." << endl;
             cout << "========================================================" << endl;
+
             cin >> number;
+            if(std::cin.fail())
+            {
+                std::cin.clear();
+                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+                std::cout << "Invalid input type, please try again" << std::endl;
+                continue;
+            }
 
-            switch(number)
+            switch (number)
             {
                 case 1:
-                {
-                    cout << "Temp is up!" << endl;
-                    myResource.m_temp += 10;
-                    pthread_cond_signal(&m_cond);
-                    cout << "ChangeLightRepresentation Done!" << endl;
-                    break;
-                }
+                    {
+                        cout << "Temp is up!" << endl;
+                        myResource.m_temp += 10;
+                        pthread_cond_signal(&m_cond);
+                        cout << "ChangeLightRepresentation Done!" << endl;
+                        break;
+                    }
                 case 2:
-                {
-                    cout << "Temp is down!" << endl;
-                    myResource.m_temp -= 10;
-                    pthread_cond_signal(&m_cond);
-                    cout << "ChangeLightRepresentation Done!" << endl;
-                    break;
-                }
+                    {
+                        cout << "Temp is down!" << endl;
+                        myResource.m_temp -= 10;
+                        pthread_cond_signal(&m_cond);
+                        cout << "ChangeLightRepresentation Done!" << endl;
+                        break;
+                    }
                 case 3:
-                {
-                    cout << "Bye!" << endl;
-                    end = true;
-                    break;
-                }
+                    {
+                        cout << "Bye!" << endl;
+                        stopPresence();
+                        end = true;
+                        quitProcess();
+                        break;
+                    }
                 default:
-                {
-                    cout << "You type wrong number. Try again!" << endl;
-                    break;
-                }
+                    {
+                        cout << "Invalid input. Please try again." << endl;
+                        break;
+                    }
             }
-            if(end == true)
+            if (end == true)
             {
                 break;
             }
         }
     }
-    catch(exception& e)
+    catch (exception &e)
     {
-       cout << "main exception  : " << e.what() << endl;
+        cout << "main exception  : " << e.what() << endl;
     }
+
+
 }
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/.cproject b/service/notification-manager/SampleApp/tizen/NMSampleApp/.cproject
new file mode 100644 (file)
index 0000000..cd1b3e5
--- /dev/null
@@ -0,0 +1,496 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+    <storageModule moduleId="org.eclipse.cdt.core.settings">
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.53616310">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.53616310" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="nmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.53616310" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.53616310." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.1603903371" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1811247058" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder arguments="--eval=&quot;SHELL=cmd&quot; -r" autoBuildTarget="all" buildPath="${workspace_loc:/NMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1744040274" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.2000114756" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1193339560" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.1925609872" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.120324276" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.1814902249" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1588081619" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1690699832" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.1698435591" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../extlibs/cjson"/>
+                                    <listOptionValue builtIn="false" value="../../../../NotificationManager/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../NotificationManager/src"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\stack\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\logger\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\occoap\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocrandom\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocsocket\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\oc_logger\include&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.856851155" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.preprocessor.def.31367874" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.other.other.59986195" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=gnu++0x" valueType="string"/>
+                                <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.515485991" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.167437283" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2116336374" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.10819828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.1243421357" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.650844806" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.513372299" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1836823633" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.271406536" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.330532772" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.preprocessor.def.symbols.983787413" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1670474416" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1173522371" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1477620595" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1601334380" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.973841668" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.libs.1032324584" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+                                    <listOptionValue builtIn="false" value="NOTISDKLibrary"/>
+                                    <listOptionValue builtIn="false" value="oc"/>
+                                    <listOptionValue builtIn="false" value="octbstack"/>
+                                    <listOptionValue builtIn="false" value="coap"/>
+                                    <listOptionValue builtIn="false" value="oc_logger"/>
+                                    <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.361234161" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1357205409" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.61363116" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.255372816" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.1865899333" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.333279395" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.75709762" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1241676789" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.388758876" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1937068221">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1937068221" moduleId="org.eclipse.cdt.core.settings" name="Release">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="nmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1937068221" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1937068221." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.695203103" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.197043478" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder buildPath="${workspace_loc:/NMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.1996554881" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.642020430" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1246939520" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.1912726782" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.219265095" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.cpp.compiler.option.1675457058" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.243679718" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.49564857" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.1495504815" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.473269013" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.965458948" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.1900937931" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.266625395" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.533032952" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.c.compiler.option.861161124" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.2063638314" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1268514055" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.2089552115" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.1115236395" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1549480707" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1065101605" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1995759576" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.882356104" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.470096082" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1260470197" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1113631268" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.36328338" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.1226070046" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.845522361" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.512485616" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.1561842929" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.298210611" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1166942225" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+    </storageModule>
+    <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+        <project id="NMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.772584317" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+    </storageModule>
+    <storageModule moduleId="scannerConfiguration">
+        <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.53616310">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1937068221">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+    </storageModule>
+    <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+    <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+    <storageModule moduleId="refreshScope"/>
+</cproject>
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/.exportMap b/service/notification-manager/SampleApp/tizen/NMSampleApp/.exportMap
new file mode 100644 (file)
index 0000000..43e310e
--- /dev/null
@@ -0,0 +1,4 @@
+{
+       global: main;
+       local: *;
+};
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/.project b/service/notification-manager/SampleApp/tizen/NMSampleApp/.project
new file mode 100644 (file)
index 0000000..8406f2e
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>NMSampleApp</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+            <triggers>full,incremental,</triggers>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.tizen.nativecore.apichecker.core.builder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.cdt.core.cnature</nature>
+        <nature>org.eclipse.cdt.core.ccnature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+        <nature>org.tizen.nativecore.apichecker.core.tizenCppNature</nature>
+    </natures>
+    <filteredResources>
+        <filter>
+            <id>1429160978568</id>
+            <name></name>
+            <type>26</type>
+            <matcher>
+                <id>org.eclipse.ui.ide.multiFilter</id>
+                <arguments>1.0-projectRelativePath-matches-false-false-*/.tpk</arguments>
+            </matcher>
+        </filter>
+    </filteredResources>
+</projectDescription>
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/.tproject b/service/notification-manager/SampleApp/tizen/NMSampleApp/.tproject
new file mode 100644 (file)
index 0000000..f1cc1fd
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<tproject xmlns="http://www.tizen.org/tproject">
+    <platforms>
+        <platform>
+            <name>mobile-2.3</name>
+        </platform>
+    </platforms>
+    <package>
+        <blacklist/>
+    </package>
+</tproject>
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/edc_resource/hosting_control.edc b/service/notification-manager/SampleApp/tizen/NMSampleApp/edc_resource/hosting_control.edc
new file mode 100644 (file)
index 0000000..d217dee
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd 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.
+ *
+ */
+
+group { name: "group_layout";
+   parts {
+      part { name: "start_button";
+         type: SWALLOW;
+         scale: 1;
+         description {
+            rel1.relative: 0.01 0.01;
+            rel2.relative: 0.5 0.09;
+         }
+      }
+      part { name: "stop_button";
+         type: SWALLOW;
+         scale: 1;
+         description {
+            rel1.relative: 0.01 0.2;
+            rel2.relative: 0.5 0.09;
+         }
+      }
+         part { name: "log_bg";
+         type: RECT;
+         scale: 1;
+         description { state: "default" 0.0;
+            rel1.relative: 0.01 0.71;
+                       rel2.relative: 0.98 1.0;
+                       color: 220 220 220 255;
+         }
+      }
+         part { name: "log";
+         type: SWALLOW;
+         scale: 1;
+         description {
+                       rel1.to: "log_bg";
+            rel2.to: "log_bg";
+         }
+      }
+   }
+}
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/inc/nmsampleapp.h b/service/notification-manager/SampleApp/tizen/NMSampleApp/inc/nmsampleapp.h
new file mode 100644 (file)
index 0000000..65860e4
--- /dev/null
@@ -0,0 +1,52 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef __NMSAMPLEAPP_H__
+#define __NMSAMPLEAPP_H__
+
+#include <app.h>
+#include <Elementary.h>
+#include <system_settings.h>
+#include <efl_extension.h>
+#include <dlog.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+#ifdef  LOG_TAG
+#undef  LOG_TAG
+#endif
+#define LOG_TAG "nmsampleapp"
+
+#if !defined(PACKAGE)
+#define PACKAGE "org.tizen.nmsampleapp"
+#endif
+
+#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.nmsampleapp/res/ui_controls.edj"
+
+void start_cb(void *data, Evas_Object *obj, void *event_info);
+
+void stop_cb(void *data, Evas_Object *obj, void *event_info);
+
+void stop_hosting();
+
+void *updateGroupLog(void *data);
+
+#endif // __NMSAMPLEAPP_H__
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/inc/nmutil.h b/service/notification-manager/SampleApp/tizen/NMSampleApp/inc/nmutil.h
new file mode 100644 (file)
index 0000000..692e1dd
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include<iostream>
+
+using namespace std;
+
+#ifndef NMUTIL_H_
+#define NMUTIL_H_
+
+#define LOGI(...) dlog_print(DLOG_INFO, LOG_TAG, __VA_ARGS__)
+#define LOGD(...) dlog_print(DLOG_DEBUG, LOG_TAG, __VA_ARGS__)
+#define LOGE(...) dlog_print(DLOG_ERROR, LOG_TAG, __VA_ARGS__)
+
+extern std::string getOCStackResultStringFromInt(int result);
+
+#endif // TMUTIL_H_
+
+
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/res/ui_controls.edc b/service/notification-manager/SampleApp/tizen/NMSampleApp/res/ui_controls.edc
new file mode 100644 (file)
index 0000000..151d32f
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd 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.
+ *
+ */
+
+collections {
+   base_scale: 1.8;
+   #include "../edc_resource/hosting_control.edc"
+}
+
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/shared/res/nmsampleapp.png b/service/notification-manager/SampleApp/tizen/NMSampleApp/shared/res/nmsampleapp.png
new file mode 100644 (file)
index 0000000..9765b1b
Binary files /dev/null and b/service/notification-manager/SampleApp/tizen/NMSampleApp/shared/res/nmsampleapp.png differ
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/src/main.cpp b/service/notification-manager/SampleApp/tizen/NMSampleApp/src/main.cpp
new file mode 100644 (file)
index 0000000..8ec9645
--- /dev/null
@@ -0,0 +1,107 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "nmsampleapp.h"
+#include "nmutil.h"
+#include <algorithm>
+#include <signal.h>
+#include "hosting.h"
+
+using namespace std;
+using namespace OC;
+
+namespace PH = std::placeholders;
+
+static uint8_t interfaceName[] = "wlan0";
+int g_quitFlag = 0;
+
+static void printLog(int logType, string data)
+{
+    (DLOG_ERROR == logType) ? LOGE(data.c_str()) : LOGI(data.c_str());
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                          &data);
+}
+
+// Method for Finding the resource and hosting it
+static void start_hosting(int seconds)
+{
+    string logMessage = "OCResourceHosting started <br>";
+    logMessage = logMessage + "Interface Name : " + reinterpret_cast<char *>(interfaceName) + "<br>";
+    printLog(DLOG_INFO, logMessage);
+
+    if (OCInit((char *) NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
+    {
+        logMessage = "OCStack init error <br>";
+        printLog(DLOG_ERROR, logMessage);
+        return;
+    }
+
+    OICStartCoordinate();
+    g_quitFlag = 0;
+    logMessage = "OICStartCoordinate done successfully";
+    printLog(DLOG_INFO, logMessage);
+
+    while (!g_quitFlag)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OICStopCoordinate();
+            logMessage = "OCStack process error <br>";
+            printLog(DLOG_ERROR, logMessage);
+            return;
+        }
+        sleep(seconds);
+    }
+
+    OICStopCoordinate();
+    logMessage = "OICStopCoordinate done successfully <br>";
+    printLog(DLOG_INFO, logMessage);
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        logMessage = "OCStack stop error <br>";
+        printLog(DLOG_ERROR, logMessage);
+    }
+    LOGI("start EXIT");
+}
+
+// Method for Finding the resource and hosting it
+void stop_hosting()
+{
+    string logMessage = "Terminating Resource Hosting <br>";
+    printLog(DLOG_INFO, logMessage);
+
+    g_quitFlag = 1;
+    LOGI("stop_hosting EXIT");
+}
+
+// Method to be called when the find and host UI Button is selected
+void start_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    std::thread exec(std::function< void(int second) >(start_hosting), 3);
+    exec.detach();
+}
+
+// Method to be called when the find and host UI Button is selected
+void stop_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    LOGI("Stopping resource hosting");
+    stop_hosting();
+}
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/src/nmsampleapp.cpp b/service/notification-manager/SampleApp/tizen/NMSampleApp/src/nmsampleapp.cpp
new file mode 100644 (file)
index 0000000..2e8e377
--- /dev/null
@@ -0,0 +1,308 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "nmsampleapp.h"
+#include "nmutil.h"
+#include <tizen.h>
+
+using namespace std;
+using namespace OC;
+
+static Evas_Object *log_entry = NULL;
+static Evas_Object *list = NULL;
+static Evas_Object *naviframe = NULL;
+
+typedef struct appdata
+{
+    Evas_Object *win;
+    Evas_Object *conform;
+    Evas_Object *layout;
+    Evas_Object *nf;
+    Evas_Object *findButton;
+    Evas_Object *logtext;
+    Evas_Object *listview;
+} appdata_s;
+
+// Function to update the log in UI
+void *updateGroupLog(void *data)
+{
+    string *log = (string *)data;
+    // Show the log
+    elm_entry_entry_append(log_entry, (*log).c_str());
+    elm_entry_cursor_end_set(log_entry);
+    return NULL;
+}
+
+static void
+win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    ui_app_exit();
+}
+
+static void
+list_selected_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    Elm_Object_Item *it = (Elm_Object_Item *)event_info;
+    elm_list_item_selected_set(it, EINA_FALSE);
+}
+
+static void
+win_back_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    appdata_s *ad = (appdata_s *)data;
+    // Let window go to hide state.
+    elm_win_lower(ad->win);
+}
+
+static Eina_Bool
+naviframe_pop_cb(void *data, Elm_Object_Item *it)
+{
+    stop_hosting();
+    ui_app_exit();
+    return EINA_FALSE;
+}
+
+static void
+create_list_view(appdata_s *ad)
+{
+    Evas_Object *layout;
+    Evas_Object *scroller;
+    Evas_Object *nf = ad->nf;
+    Evas_Object *start_button;
+    Evas_Object *stop_button;
+    Elm_Object_Item *nf_it;
+
+    naviframe = nf;
+
+    // scroller
+    scroller = elm_scroller_add(nf);
+    elm_scroller_bounce_set(scroller, EINA_FALSE, EINA_TRUE);
+    elm_scroller_policy_set(scroller, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_AUTO);
+
+    // layout
+    layout = elm_layout_add(nf);
+    elm_layout_file_set(layout, ELM_DEMO_EDJ, "group_layout");
+    evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+
+    elm_object_content_set(scroller, layout);
+
+    // button
+    start_button = elm_button_add(layout);
+    elm_object_part_content_set(layout, "start_button", start_button);
+    elm_object_text_set(start_button, "Find and Host");
+    evas_object_smart_callback_add(start_button, "clicked", start_cb, NULL);
+
+    // button
+    stop_button = elm_button_add(layout);
+    elm_object_part_content_set(layout, "stop_button", stop_button);
+    elm_object_text_set(stop_button, "Stop");
+    evas_object_smart_callback_add(stop_button, "clicked", stop_cb, NULL);
+
+    // entry - textarea for log
+    log_entry = elm_entry_add(layout);
+    elm_entry_scrollable_set(log_entry, EINA_TRUE);
+    elm_entry_editable_set(log_entry, EINA_FALSE);
+    elm_object_part_text_set(log_entry, "elm.guide", "Logs will be updated here!!!");
+    evas_object_size_hint_weight_set(log_entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    elm_object_part_content_set(layout, "log", log_entry);
+
+    nf_it = elm_naviframe_item_push(nf, "Notification Manager", NULL, NULL, scroller, NULL);
+    elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
+}
+
+
+static void
+create_base_gui(appdata_s *ad)
+{
+    // Window
+    ad->win = elm_win_util_standard_add(PACKAGE, PACKAGE);
+    elm_win_conformant_set(ad->win, EINA_TRUE);
+    elm_win_autodel_set(ad->win, EINA_TRUE);
+
+    if (elm_win_wm_rotation_supported_get(ad->win))
+    {
+        int rots[4] = { 0, 90, 180, 270 };
+        elm_win_wm_rotation_available_rotations_set(ad->win, (const int *)(&rots), 4);
+    }
+
+    evas_object_smart_callback_add(ad->win, "delete,request", win_delete_request_cb, NULL);
+
+    // Conformant
+    ad->conform = elm_conformant_add(ad->win);
+    evas_object_size_hint_weight_set(ad->conform, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_win_resize_object_add(ad->win, ad->conform);
+    evas_object_show(ad->conform);
+
+    // Base Layout
+    ad->layout = elm_layout_add(ad->conform);
+    evas_object_size_hint_weight_set(ad->layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_layout_theme_set(ad->layout, "layout", "application", "default");
+    evas_object_show(ad->layout);
+
+    elm_object_content_set(ad->conform, ad->layout);
+
+    // Naviframe
+    ad->nf = elm_naviframe_add(ad->layout);
+    create_list_view(ad);
+    elm_object_part_content_set(ad->layout, "elm.swallow.content", ad->nf);
+    eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_BACK, eext_naviframe_back_cb, NULL);
+    eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_MORE, eext_naviframe_more_cb, NULL);
+
+    // Show window after base gui is set up
+    evas_object_show(ad->win);
+}
+
+// Configures the OCPlatform
+static void
+configure_platform()
+{
+    try
+    {
+        PlatformConfig config
+        { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+        OCPlatform::Configure(config);
+
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration done!!!!");
+    }
+    catch (OCException &e)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration Exception!!!!");
+        dlog_print(DLOG_INFO, LOG_TAG, "#### (%s)", e.what());
+    }
+}
+
+static bool
+app_create(void *data)
+{
+    /* Hook to take necessary actions before main event loop starts
+        Initialize UI resources and application's data
+        If this function returns true, the main loop of application starts
+        If this function returns false, the application is terminated */
+    appdata_s *ad = (appdata_s *)data;
+
+    elm_app_base_scale_set(1.8);
+
+    create_base_gui(ad);
+
+    configure_platform();
+
+    return true;
+}
+
+static void
+app_control(app_control_h app_control, void *data)
+{
+    // Handle the launch request.
+}
+
+static void
+app_pause(void *data)
+{
+    // Take necessary actions when application becomes invisible.
+}
+
+static void
+app_resume(void *data)
+{
+    // Take necessary actions when application becomes visible.
+}
+
+static void
+app_terminate(void *data)
+{
+    // Release all resources.
+}
+
+static void
+ui_app_lang_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LANGUAGE_CHANGED
+    char *locale = NULL;
+    system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale);
+    elm_language_set(locale);
+    free(locale);
+    return;
+}
+
+static void
+ui_app_orient_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_DEVICE_ORIENTATION_CHANGED
+    return;
+}
+
+static void
+ui_app_region_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_REGION_FORMAT_CHANGED
+}
+
+static void
+ui_app_low_battery(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_BATTERY
+}
+
+static void
+ui_app_low_memory(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_MEMORY
+}
+
+int
+main(int argc, char *argv[])
+{
+    appdata_s ad = {0,};
+    int ret = 0;
+
+    ui_app_lifecycle_callback_s event_callback = {0,};
+    app_event_handler_h handlers[5] = {NULL, };
+
+    event_callback.create = app_create;
+    event_callback.terminate = app_terminate;
+    event_callback.pause = app_pause;
+    event_callback.resume = app_resume;
+    event_callback.app_control = app_control;
+
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY,
+                             ui_app_low_battery, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY,
+                             ui_app_low_memory, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED],
+                             APP_EVENT_DEVICE_ORIENTATION_CHANGED,
+                             ui_app_orient_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED],
+                             APP_EVENT_LANGUAGE_CHANGED,
+                             ui_app_lang_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED],
+                             APP_EVENT_REGION_FORMAT_CHANGED,
+                             ui_app_region_changed, &ad);
+    ui_app_remove_event_handler(handlers[APP_EVENT_LOW_MEMORY]);
+
+    ret = ui_app_main(argc, argv, &event_callback, &ad);
+    if (ret != APP_ERROR_NONE)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "app_main() is failed. err = %d", ret);
+    }
+
+    return ret;
+}
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/src/nmutil.cpp b/service/notification-manager/SampleApp/tizen/NMSampleApp/src/nmutil.cpp
new file mode 100644 (file)
index 0000000..ac2590b
--- /dev/null
@@ -0,0 +1,130 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "nmutil.h"
+
+// Utility function to return the string equivalent of OCStackResult for the given int value
+std::string getOCStackResultStringFromInt(int result)
+{
+    string ocresultstr;
+
+    switch (result)
+    {
+        case 0 :
+            ocresultstr = "OC_STACK_OK";
+            break;
+        case 1 :
+            ocresultstr = "OC_STACK_RESOURCE_CREATED";
+            break;
+        case 2 :
+            ocresultstr = "OC_STACK_RESOURCE_DELETED";
+            break;
+        case 3 :
+            ocresultstr = "OC_STACK_CONTINUE";
+            break;
+        case 20 :
+            ocresultstr = "OC_STACK_INVALID_URI";
+            break;
+        case 21 :
+            ocresultstr = "OC_STACK_INVALID_QUERY";
+            break;
+        case 22 :
+            ocresultstr = "OC_STACK_INVALID_QUERY";
+            break;
+        case 23 :
+            ocresultstr = "OC_STACK_INVALID_PORT";
+            break;
+        case 24 :
+            ocresultstr = "OC_STACK_INVALID_CALLBACK";
+            break;
+        case 25 :
+            ocresultstr = "OC_STACK_INVALID_METHOD";
+            break;
+        case 26 :
+            ocresultstr = "OC_STACK_INVALID_PARAM";
+            break;
+        case 27 :
+            ocresultstr = "OC_STACK_INVALID_OBSERVE_PARAM";
+            break;
+        case 28 :
+            ocresultstr = "OC_STACK_NO_MEMORY";
+            break;
+        case 29 :
+            ocresultstr = "OC_STACK_COMM_ERROR";
+            break;
+        case 30 :
+            ocresultstr = "OC_STACK_NOTIMPL";
+            break;
+        case 31 :
+            ocresultstr = "OC_STACK_NO_RESOURCE";
+            break;
+        case 32 :
+            ocresultstr = "OC_STACK_RESOURCE_ERROR";
+            break;
+        case 33 :
+            ocresultstr = "OC_STACK_SLOW_RESOURCE";
+            break;
+        case 34 :
+            ocresultstr = "OC_STACK_DUPLICATE_REQUEST";
+            break;
+        case 35 :
+            ocresultstr = "OC_STACK_NO_OBSERVERS";
+            break;
+        case 36 :
+            ocresultstr = "OC_STACK_OBSERVER_NOT_FOUND";
+            break;
+        case 37 :
+            ocresultstr = "OC_STACK_VIRTUAL_DO_NOT_HANDLE";
+            break;
+        case 38 :
+            ocresultstr = "OC_STACK_INVALID_OPTION";
+            break;
+        case 39 :
+            ocresultstr = "OC_STACK_MALFORMED_RESPONSE";
+            break;
+        case 40 :
+            ocresultstr = "OC_STACK_PERSISTENT_BUFFER_REQUIRED";
+            break;
+        case 41 :
+            ocresultstr = "OC_STACK_INVALID_REQUEST_HANDLE";
+            break;
+        case 42 :
+            ocresultstr = "OC_STACK_INVALID_DEVICE_INFO";
+            break;
+        case 43 :
+            ocresultstr = "OC_STACK_INVALID_JSON";
+            break;
+        case 128 :
+            ocresultstr = "OC_STACK_PRESENCE_STOPPED";
+            break;
+        case 129 :
+            ocresultstr = "OC_STACK_PRESENCE_TIMEOUT";
+            break;
+        case 130 :
+            ocresultstr = "OC_STACK_PRESENCE_DO_NOT_HANDLE";
+            break;
+        case 255 :
+            ocresultstr = "OC_STACK_ERROR";
+            break;
+        default :
+            ocresultstr = "OC_STACK_ERROR";
+    }
+    return ocresultstr;
+}
diff --git a/service/notification-manager/SampleApp/tizen/NMSampleApp/tizen-manifest.xml b/service/notification-manager/SampleApp/tizen/NMSampleApp/tizen-manifest.xml
new file mode 100644 (file)
index 0000000..1b160cd
--- /dev/null
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="2.3" package="org.tizen.nmsampleapp" version="1.0.0">
+    <profile name="mobile"/>
+    <ui-application appid="org.tizen.nmsampleapp" exec="nmsampleapp" multiple="false" nodisplay="false" taskmanage="true" type="capp">
+        <label>nmsampleapp</label>
+        <icon>nmsampleapp.png</icon>
+    </ui-application>
+    <privileges>
+        <privilege>http://tizen.org/privilege/network.get</privilege>
+        <privilege>http://tizen.org/privilege/systemsettings</privilege>
+        <privilege>http://tizen.org/privilege/network.set</privilege>
+        <privilege>http://tizen.org/privilege/internet</privilege>
+        <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
+    </privileges>
+    <feature name="http://tizen.org/feature/network.wifi">true</feature>
+</manifest>
index cc7830a..25c344e 100644 (file)
@@ -36,8 +36,8 @@ using namespace OC;
 const int SUCCESS_RESPONSE = 0;
 static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
 
-const charPREFIX_URI = "Uri : ";
-const charPREFIX_HOST = "Host : ";
+const char *PREFIX_URI = "Uri : ";
+const char *PREFIX_HOST = "Host : ";
 
 OCPlatform *g_platform = nullptr;
 PlatformConfig g_cfg;
@@ -49,8 +49,8 @@ oicappData *g_oicappClientAd;
 oicappData *g_oicFindAd;
 oicappData *g_oicObserveAd;
 
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName);
-void onObserve(const OCRepresentation& rep , const int& eCode , const int& sequenceNumber);
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName);
+void onObserve(const OCRepresentation &rep , const int &eCode , const int &sequenceNumber);
 void onfound();
 void onobserve();
 
@@ -62,15 +62,16 @@ void findResourceCandidate(oicappData *ad)
         std::cout << "Finding Resource... " << std::endl;
 
     }
-    catch(OCException& e)
+    catch (OCException &e)
     {
+        ERR("findResourceCandidate exception: %s" , e.what().c_str());
     }
     g_oicFindAd = ad;
 }
 
 void startObserve(oicappData *ad)
 {
-    if(g_curResource != nullptr)
+    if (g_curResource != nullptr)
     {
         g_oicObserveAd = ad;
         QueryParamsMap test;
@@ -80,10 +81,10 @@ void startObserve(oicappData *ad)
 
 void printAttributeMap(const AttributeMap attributeMap)
 {
-    for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+    for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
     {
         DBG("\tAttribute name: %s" , it->first.c_str());
-        for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+        for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
         {
             DBG("\t\tAttribute value: %s" , (*valueItr).c_str());
         }
@@ -102,7 +103,7 @@ void cancelObserve()
 
     OCStackResult result = OC_STACK_ERROR;
 
-    if(g_curResource != nullptr)
+    if (g_curResource != nullptr)
     {
         result = g_curResource->cancelObserve();
     }
@@ -110,17 +111,17 @@ void cancelObserve()
     DBG("Cancel result: %d" , result);
 }
 
-void onObserve(const OCRepresentation& rep , const int& eCode , const int& sequenceNumber)
+void onObserve(const OCRepresentation &rep , const int &eCode , const int &sequenceNumber)
 {
 
     AttributeMap attributeMap = rep.getAttributeMap();
-    if(eCode == SUCCESS_RESPONSE)
+    if (eCode == SUCCESS_RESPONSE)
     {
         DBG("OBSERVE RESULT:");
         DBG("\tSequenceNumber: %d" , sequenceNumber);
 
         printAttributeMap(attributeMap);
-//             updateAttribute(attributeMap);
+//      updateAttribute(attributeMap);
         g_curAttributeMap = attributeMap;
         onobserve();
     }
@@ -132,21 +133,21 @@ void onObserve(const OCRepresentation& rep , const int& eCode , const int& seque
 }
 
 // callback handler on PUT request
-void onPut(const OCRepresentationrep , const int eCode)
+void onPut(const OCRepresentation &rep , const int eCode)
 {
     AttributeMap attributeMap = rep.getAttributeMap();
-    if(eCode == SUCCESS_RESPONSE)
+    if (eCode == SUCCESS_RESPONSE)
     {
         DBG("PUT request was successful");
 
         printAttributeMap(attributeMap);
 
-        if(OBSERVE_TYPE_TO_USE == ObserveType::Observe)
+        if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
             INFO("Observe is used.");
-        else if(OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
+        else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
             INFO("ObserveAll is used.");
 
-        if(g_curResource != nullptr)
+        if (g_curResource != nullptr)
         {
             DBG("Observe Start");
             QueryParamsMap test;
@@ -161,11 +162,11 @@ void onPut(const OCRepresentation& rep , const int eCode)
 }
 
 // callback handler on GET request
-void onGet(const OCRepresentationrep , const int eCode)
+void onGet(const OCRepresentation &rep , const int eCode)
 {
 
     AttributeMap attributeMap = rep.getAttributeMap();
-    if(eCode == SUCCESS_RESPONSE)
+    if (eCode == SUCCESS_RESPONSE)
     {
         DBG("GET Succeeded:");
 
@@ -182,7 +183,7 @@ void onGet(const OCRepresentation& rep , const int eCode)
 // Local function to get representation of light resource
 void getLightRepresentation(std::shared_ptr< OCResource > resource)
 {
-    if(resource)
+    if (resource)
     {
         DBG("Getting Light Representation...");
         // Invoke resource's get API with the callback parameter
@@ -196,13 +197,13 @@ static void foundResource(std::shared_ptr< OCResource > resource)
 {
     try
     {
-        if(resource)
+        if (resource)
         {
             DBG("DISCOVERED Resource:");
             DBG("\tURI of the resource: %s" , resource->uri().c_str());
             DBG("\tHost address of the resource: %s" , resource->host().c_str());
 
-            if(resource->uri().find("/a/NM") != string::npos)
+            if (resource->uri().find("/a/NM") != string::npos)
             {
 
                 g_curResource = resource;
@@ -215,14 +216,15 @@ static void foundResource(std::shared_ptr< OCResource > resource)
         }
 
     }
-    catch(std::exception& e)
+    catch (std::exception &e)
     {
+        ERR("foundResource exception: %s" , e.what().c_str());
     }
 }
 
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName)
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName)
 {
-    if(g_platform != nullptr)
+    if (g_platform != nullptr)
     {
         return g_platform->findResource(host , resourceName , &foundResource);
     }
@@ -248,13 +250,13 @@ int oicapp_client_start(oicappData *ad)
 
 void oicapp_client_stop()
 {
-    if(g_curResource != nullptr)
+    if (g_curResource != nullptr)
     {
         cancelObserve();
         g_curResource = NULL;
     }
 
-    if(g_platform)
+    if (g_platform)
     {
         delete (g_platform);
         g_platform = NULL;
@@ -297,7 +299,7 @@ int oicapp_client_put(int power , int level)
 void onfound()
 {
 
-    if(g_curResource->uri().find("/a/NM/TempHumSensor/virtual") != string::npos)
+    if (g_curResource->uri().find("/a/NM/TempHumSensor/virtual") != string::npos)
     {
         oicappData *ad = g_oicFindAd;
 
@@ -322,11 +324,11 @@ void onobserve()
 
     std::string tmpStr[2];
     int index = 0;
-    for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+    for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
     {
         tmpStr[index] = it->first;
         tmpStr[index].append(" : ");
-        for(auto value = it->second.begin() ; value != it->second.end() ; ++value)
+        for (auto value = it->second.begin() ; value != it->second.end() ; ++value)
         {
             tmpStr[index].append(*value);
         }
index 4a7fdb3..a0b3484 100644 (file)
 #define LOG_TAG "OIC_TEST"
 #include <dlog.h>
 
-#define LOG_COLOR_RED          "\033[0;31m"
-#define LOG_COLOR_BROWN                "\033[0;33m"
-#define LOG_COLOR_BLUE         "\033[0;34m"
-#define LOG_COLOR_END          "\033[0;m"
+#define LOG_COLOR_RED       "\033[0;31m"
+#define LOG_COLOR_BROWN     "\033[0;33m"
+#define LOG_COLOR_BLUE      "\033[0;34m"
+#define LOG_COLOR_END       "\033[0;m"
 
 
 #if 1
 #define _ERR(fmt, arg...) SLOGE(fmt, ##arg)
 #else
 #define _DBG(fmt, arg...) \
-       printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
 #define _INFO(fmt, arg...) \
-       printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
 #define _WARN(fmt, arg...) \
-       printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
 #define _ERR(fmt, arg...) \
-       printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
 #endif
 
 #define DBG(fmt, arg...) _DBG(fmt, ##arg)
 #define INFO(fmt, arg...) _INFO(LOG_COLOR_BLUE fmt LOG_COLOR_END, ##arg)
 
 #define ret_if(expr) \
-       do { \
-               if (expr) { \
-                       ERR("(%s)", #expr); \
-                       return; \
-               }\
-       } while(0)
+    do { \
+        if (expr) { \
+            ERR("(%s)", #expr); \
+            return; \
+        }\
+    } while(0)
 #define retv_if(expr, val) \
-       do {\
-               if (expr) { \
-                       ERR("(%s)", #expr); \
-                       return (val); \
-               } \
-       } while(0)
+    do {\
+        if (expr) { \
+            ERR("(%s)", #expr); \
+            return (val); \
+        } \
+    } while(0)
 #define retm_if(expr, fmt, arg...) \
-       do {\
-               if (expr) { \
-                       ERR(fmt, ##arg); \
-                       return; \
-               }\
-       } while(0)
+    do {\
+        if (expr) { \
+            ERR(fmt, ##arg); \
+            return; \
+        }\
+    } while(0)
 #define retvm_if(expr, val, fmt, arg...) \
-       do {\
-               if (expr) { \
-                       ERR(fmt, ##arg); \
-                       return (val); \
-               } \
-       } while(0)
+    do {\
+        if (expr) { \
+            ERR(fmt, ##arg); \
+            return (val); \
+        } \
+    } while(0)
 #define warn_if(expr) \
-       do { \
-               if (expr) { \
-                       WARN("(%s)", #expr); \
-               } \
-       } while (0)
+    do { \
+        if (expr) { \
+            WARN("(%s)", #expr); \
+        } \
+    } while (0)
 
 
 #endif //__OICAPP_LOG_H__
index 25ac236..b46a699 100644 (file)
@@ -45,6 +45,11 @@ static Elm_Object_Item* _gl_append_item(oicappData *ad , Elm_Genlist_Item_Class
     oicappItemData *it_data;
 
     it_data = calloc(1 , sizeof(oicappItemData));
+    if (NULL == it_data)
+    {
+        DBG("calloc failed!!!!");
+        return NULL;
+    }
     it_data->title = title;
     it_data->ad = ad;
     item = elm_genlist_item_append(ad->genlist , itc , it_data , NULL , ELM_GENLIST_ITEM_NONE ,
@@ -58,6 +63,11 @@ void _gl_update_item(oicappData *ad , const char *title , Elm_Object_Item *item)
     oicappItemData *it_data;
 
     it_data = calloc(1 , sizeof(oicappItemData));
+    if (NULL == it_data)
+    {
+        DBG("calloc failed!!!!");
+        return;
+    }
     it_data->title = title;
     it_data->ad = ad;
 
index 230ee61..c7eb1ff 100644 (file)
@@ -35,65 +35,65 @@ extern "C"
 
 #define GRP_MAIN "main"
 
-    enum
-    {
-        OICAPP_GENLIST_GRP_NONE = 0,
-        OICAPP_GENLIST_GRP_TOP,
-        OICAPP_GENLIST_GRP_CENTER,
-        OICAPP_GENLIST_GRP_BOTTOM
-    };
-
-    typedef struct
-    {
-        Evas_Object *win;
-        Evas_Object *base;
-        Evas_Object *bg;
-        Evas_Object *navi;
-        Evas_Object *genlist;
-        Evas_Object *popup;
-        Evas_Object *conform;
-
-        Elm_Object_Item *itemConsumer;
-        Elm_Object_Item *itemConsumerUri;
-        Elm_Object_Item *itemConsumerHost;
-        Elm_Object_Item *itemConsumerTemp;
-        Elm_Object_Item *itemConsumerHumid;
-        Elm_Object_Item *itemFindResource;
-        Elm_Object_Item *itemObserve;
-        Elm_Object_Item *itemServer;
-        Elm_Object_Item *itemServerTemp;
-        Elm_Object_Item *itemServerHumid;
-
-        Elm_Genlist_Item_Class itcSeperator;
-        Elm_Genlist_Item_Class itcTitle;
-        Elm_Genlist_Item_Class itcText;
-        Elm_Genlist_Item_Class itcBtnFindResoruce;
-        Elm_Genlist_Item_Class itcBtnObserve;
-
-        char *ipAddr;
-        //oicapp_mode mode;
-        int clientOn;
-        int serverOn;
-        int power;
-        int level;
-
-        int temp;
-        int humid;
-
-        char *uri;
-        char *host;
-
-    } oicappData;
-
-    extern void _gl_update_item(oicappData *ad , const char *title , Elm_Object_Item *item);
-
-    typedef struct
-    {
-        oicappData *ad;
-        const char *title;
-        int group_style;
-
-    } oicappItemData;
+enum
+{
+    OICAPP_GENLIST_GRP_NONE = 0,
+    OICAPP_GENLIST_GRP_TOP,
+    OICAPP_GENLIST_GRP_CENTER,
+    OICAPP_GENLIST_GRP_BOTTOM
+};
+
+typedef struct
+{
+    Evas_Object *win;
+    Evas_Object *base;
+    Evas_Object *bg;
+    Evas_Object *navi;
+    Evas_Object *genlist;
+    Evas_Object *popup;
+    Evas_Object *conform;
+
+    Elm_Object_Item *itemConsumer;
+    Elm_Object_Item *itemConsumerUri;
+    Elm_Object_Item *itemConsumerHost;
+    Elm_Object_Item *itemConsumerTemp;
+    Elm_Object_Item *itemConsumerHumid;
+    Elm_Object_Item *itemFindResource;
+    Elm_Object_Item *itemObserve;
+    Elm_Object_Item *itemServer;
+    Elm_Object_Item *itemServerTemp;
+    Elm_Object_Item *itemServerHumid;
+
+    Elm_Genlist_Item_Class itcSeperator;
+    Elm_Genlist_Item_Class itcTitle;
+    Elm_Genlist_Item_Class itcText;
+    Elm_Genlist_Item_Class itcBtnFindResoruce;
+    Elm_Genlist_Item_Class itcBtnObserve;
+
+    char *ipAddr;
+    //oicapp_mode mode;
+    int clientOn;
+    int serverOn;
+    int power;
+    int level;
+
+    int temp;
+    int humid;
+
+    char *uri;
+    char *host;
+
+} oicappData;
+
+extern void _gl_update_item(oicappData *ad , const char *title , Elm_Object_Item *item);
+
+typedef struct
+{
+    oicappData *ad;
+    const char *title;
+    int group_style;
+
+} oicappItemData;
 
 #ifdef __cplusplus
 }
index 1f24e69..3d1e5bf 100644 (file)
@@ -18,22 +18,22 @@ extern "C"
 {
 #endif
 
-    void oicapp_fail_popup(oicappData *ad , char *title , char *text , int timeout);
-    void oicapp_util_update(oicappData *ad);
-    char* oicapp_util_wifi();
+void oicapp_fail_popup(oicappData *ad , char *title , char *text , int timeout);
+void oicapp_util_update(oicappData *ad);
+char *oicapp_util_wifi();
 
-    int oicapp_client_start(oicappData *ad);
-    void oicapp_client_stop();
-    int oicapp_client_put(int power , int level);
+int oicapp_client_start(oicappData *ad);
+void oicapp_client_stop();
+int oicapp_client_put(int power , int level);
 
-    int oicapp_server_start(oicappData *ad);
-    void oicapp_server_stop();
-    void oicapp_server_put(int power , int level);
+int oicapp_server_start(oicappData *ad);
+void oicapp_server_stop();
+void oicapp_server_put(int power , int level);
 
-    extern void *ChangeLightRepresentation(void *param);
+extern void *ChangeLightRepresentation(void *param);
 
-    void findResourceCandidate(oicappData *ad);
-    void startObserve(oicappData *ad);
+void findResourceCandidate(oicappData *ad);
+void startObserve(oicappData *ad);
 
 #ifdef __cplusplus
 }
diff --git a/service/notification-manager/build/linux/makefile/Makefile b/service/notification-manager/build/linux/makefile/Makefile
deleted file mode 100644 (file)
index 499b9a9..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-OCPATH = ../../../../../resource
-NOTIFICATIONMGRPATH = ../../../NotificationManager/build/linux
-
-.PHONY : resource NotificationManager
-
-all: .PHONY
-
-resource:
-       cd $(OCPATH) && $(MAKE)
-
-NotificationManager:
-       cd $(NOTIFICATIONMGRPATH) && $(MAKE) && cp ./NotificationManager ../../../build/linux/release/ && cp ./SampleConsumer ../../../build/linux/release/ && cp ./SampleProvider ../../../build/linux/release/
-
-clean:
-       cd ../release && rm *
-       cd $(OCPATH) && $(MAKE) clean
-       cd $(NOTIFICATIONMGRPATH) && $(MAKE) clean
index 3fa2393..5238429 100644 (file)
@@ -4,7 +4,6 @@ SET(NOTI_BASE_DIR "${BASE_SRC_DIR}/notification-manager")
 
 INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic)
 INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic/stack)
-INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic/ocsocket)
 INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/boost)
 INCLUDE_DIRECTORIES(${NOTI_BASE_DIR}/NotificationManager/include)
 
@@ -28,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 d8db971..01f5704 100644 (file)
@@ -1,12 +1,15 @@
 ##
 # protocol plugin build script
 ##
+import platform
+
 Import('env')
 
 SConscript('lib/cpluff/SConscript')
 SConscript('plugin-manager/SConscript')
 
-#The code include pthread_cancel method, can't build on android
+# The code include pthread_cancel method, can't build on android
+# MQTT requires openssl, forbid cross compile as it isn't ready
 if env.get('TARGET_OS') != 'android':
        SConscript('plugins/SConscript')
 
diff --git a/service/protocol-plugin/build/linux/Makefile b/service/protocol-plugin/build/linux/Makefile
deleted file mode 100644 (file)
index a3f6aa1..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-PROTOCOL_ROOT = ../../
-
-.PHONY:pre plugin-manager plugins sample-app
-
-all: .PHONY
-
-pre:
-       -mkdir release
-
-resource:
-       cd $(PROTOCOL_ROOT)../../resource && $(MAKE)
-
-plugin-manager:
-       cd $(PROTOCOL_ROOT)plugin-manager/build/linux && $(MAKE)
-       cp -Rdp $(PROTOCOL_ROOT)plugin-manager/build/linux/libppm.a release/
-       cp -Rdp $(PROTOCOL_ROOT)plugin-manager/build/linux/libpmimpl.so release/
-
-plugins:
-       cd $(PROTOCOL_ROOT)plugins/mqtt-fan/build/linux && $(MAKE)
-       cd $(PROTOCOL_ROOT)plugins/mqtt-light/build/linux && $(MAKE)
-
-sample-app:
-       cd $(PROTOCOL_ROOT)sample-app/linux/mqtt && $(MAKE)
-       cp -Rdp $(PROTOCOL_ROOT)plugin-manager/build/linux/libpmimpl.so $(PROTOCOL_ROOT)sample-app/linux/mqtt/
-       cp -Rdp $(PROTOCOL_ROOT)sample-app/linux/mqtt/mqttclient release/
-       cp -Rdp $(PROTOCOL_ROOT)sample-app/linux/mqtt/pluginmanager.xml release/
-
-clean:
-       cd $(PROTOCOL_ROOT)plugin-manager/build/linux && $(MAKE) clean
-       cd $(PROTOCOL_ROOT)plugins/mqtt-fan/build/linux && $(MAKE) clean
-       cd $(PROTOCOL_ROOT)plugins/mqtt-light/build/linux && $(MAKE) clean
-       cd $(PROTOCOL_ROOT)sample-app/linux/mqtt && $(MAKE) clean
-       rm -rf release
diff --git a/service/protocol-plugin/config.mk b/service/protocol-plugin/config.mk
deleted file mode 100644 (file)
index 4ba23a2..0000000
+++ /dev/null
@@ -1 +0,0 @@
-BOOST_DIR = /home/yh_.joo/Downloads/boost_1_51_0
diff --git a/service/protocol-plugin/lib/cpluff/doc/Makefile b/service/protocol-plugin/lib/cpluff/doc/Makefile
deleted file mode 100644 (file)
index fe2b195..0000000
+++ /dev/null
@@ -1,695 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# doc/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = doc
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
-       html-recursive info-recursive install-data-recursive \
-       install-dvi-recursive install-exec-recursive \
-       install-html-recursive install-info-recursive \
-       install-pdf-recursive install-ps-recursive install-recursive \
-       installcheck-recursive installdirs-recursive pdf-recursive \
-       ps-recursive uninstall-recursive
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(htmldocdir)"
-DATA = $(htmldoc_DATA)
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
-  distclean-recursive maintainer-clean-recursive
-AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
-       $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
-       distdir
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../
-top_builddir = ..
-top_srcdir = ..
-SUBDIRS = img
-EXTRA_DIST = index.en.html copyright.en.html cpluff_style.css common_style.css
-htmldocdir = $(docdir)/html
-htmldoc_DATA = index.en.html copyright.en.html cpluff_style.css common_style.css
-examplesdir = $(docdir)/examples
-all: all-recursive
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign doc/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-htmldocDATA: $(htmldoc_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(htmldocdir)" || $(MKDIR_P) "$(DESTDIR)$(htmldocdir)"
-       @list='$(htmldoc_DATA)'; test -n "$(htmldocdir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmldocdir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(htmldocdir)" || exit $$?; \
-       done
-
-uninstall-htmldocDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(htmldoc_DATA)'; test -n "$(htmldocdir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(htmldocdir)'; $(am__uninstall_files_from_dir)
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-#     (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       target=`echo $@ | sed s/-recursive//`; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           dot_seen=yes; \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done; \
-       if test "$$dot_seen" = "no"; then \
-         $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-       fi; test -z "$$fail"
-
-$(RECURSIVE_CLEAN_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       case "$@" in \
-         distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-         *) list='$(SUBDIRS)' ;; \
-       esac; \
-       rev=''; for subdir in $$list; do \
-         if test "$$subdir" = "."; then :; else \
-           rev="$$subdir $$rev"; \
-         fi; \
-       done; \
-       rev="$$rev ."; \
-       target=`echo $@ | sed s/-recursive//`; \
-       for subdir in $$rev; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done && test -z "$$fail"
-tags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
-       done
-ctags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
-       done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-         include_option=--etags-include; \
-         empty_fix=.; \
-       else \
-         include_option=--include; \
-         empty_fix=; \
-       fi; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test ! -f $$subdir/TAGS || \
-             set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-         fi; \
-       done; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test -d "$(distdir)/$$subdir" \
-           || $(MKDIR_P) "$(distdir)/$$subdir" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-           $(am__relativize); \
-           new_distdir=$$reldir; \
-           dir1=$$subdir; dir2="$(top_distdir)"; \
-           $(am__relativize); \
-           new_top_distdir=$$reldir; \
-           echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-           echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-           ($(am__cd) $$subdir && \
-             $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="$$new_top_distdir" \
-               distdir="$$new_distdir" \
-               am__remove_distdir=: \
-               am__skip_length_check=: \
-               am__skip_mode_fix=: \
-               distdir) \
-             || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(DATA)
-installdirs: installdirs-recursive
-installdirs-am:
-       for dir in "$(DESTDIR)$(htmldocdir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am: install-data-local install-htmldocDATA
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am: uninstall-htmldocDATA uninstall-local
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \
-       install-am install-strip tags-recursive
-
-.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
-       all all-am check check-am clean clean-generic clean-libtool \
-       ctags ctags-recursive distclean distclean-generic \
-       distclean-libtool distclean-tags distdir dvi dvi-am html \
-       html-am info info-am install install-am install-data \
-       install-data-am install-data-local install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-htmldocDATA install-info install-info-am install-man \
-       install-pdf install-pdf-am install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       installdirs-am maintainer-clean maintainer-clean-generic \
-       mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \
-       ps ps-am tags tags-recursive uninstall uninstall-am \
-       uninstall-htmldocDATA uninstall-local
-
-
-install-data-local: install-reference-doc install-examples-source
-
-install-reference-doc:
-       { test ! -d '$(DESTDIR)$(htmldocdir)/reference' || \
-               { chmod -R u+w '$(DESTDIR)$(htmldocdir)/reference' && \
-                       rm -rf '$(DESTDIR)$(htmldocdir)/reference'; }; } && \
-       $(MKDIR_P) '$(DESTDIR)$(htmldocdir)' && \
-       if test -d '$(srcdir)/reference'; then \
-               cp -r '$(srcdir)/reference' '$(DESTDIR)$(htmldocdir)'; \
-       else \
-               cd .. && \
-               $(MAKE) $(AM_MAKEFLAGS) doc && \
-               cp -r libcpluff/doc/reference '$(DESTDIR)$(htmldocdir)' && \
-               cd doc; \
-       fi && \
-       find '$(DESTDIR)$(htmldocdir)/reference' -type f -exec chmod 644 '{}' \; && \
-       cd '$(DESTDIR)$(htmldocdir)' && \
-       rm -f index.html && \
-       $(LN_S) index.en.html index.html
-
-install-examples-source:
-       { test ! -d '$(DESTDIR)$(examplesdir)' || \
-               { chmod -R u+w '$(DESTDIR)$(examplesdir)' && \
-                       rm -rf '$(DESTDIR)$(examplesdir)'; }; } && \
-       for d in \
-               cpfile/plugins/cext \
-               cpfile/plugins/core \
-               cpfile/plugins/extension \
-               cpfile/plugins/special; do \
-               $(MKDIR_P) "$(DESTDIR)$(examplesdir)/$$d"; \
-       done && \
-       cd '$(srcdir)/..' && \
-       find examples -type f \( -name 'autogen.sh' \
-               -or -name 'configure.ac' \
-               -or -name 'Makefile.am' \
-               -or -name 'cpfile.in' \
-               -or -name '*.nmake' \
-               -or -name '*.bat' \
-               -or -name '*.txt' \
-               -or -name '*.xml' \
-               -or -name '*.xsd' \
-               -or -name '*.c' \
-               -or -name '*.h' \) \
-               -exec $(INSTALL_DATA) '{}' '$(DESTDIR)$(docdir)/{}' \; && \
-       chmod 755 '$(DESTDIR)$(examplesdir)/autogen.sh'
-
-uninstall-local:
-       chmod -R u+w '$(DESTDIR)$(docdir)'
-       rm -rf '$(DESTDIR)$(docdir)'
-
-.PHONY: install-reference-doc install-examples-source
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/doc/img/Makefile b/service/protocol-plugin/lib/cpluff/doc/img/Makefile
deleted file mode 100644 (file)
index deaf2b9..0000000
+++ /dev/null
@@ -1,439 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# doc/img/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = doc/img
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(htmlimgdir)"
-DATA = $(htmlimg_DATA)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc/img
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc/img
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../
-top_builddir = ../..
-top_srcdir = ../..
-EXTRA_DIST = architecture.svg architecture.png pageborder.png
-htmlimgdir = $(docdir)/html/img
-htmlimg_DATA = architecture.png pageborder.png
-all: all-am
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/img/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign doc/img/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-htmlimgDATA: $(htmlimg_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(htmlimgdir)" || $(MKDIR_P) "$(DESTDIR)$(htmlimgdir)"
-       @list='$(htmlimg_DATA)'; test -n "$(htmlimgdir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmlimgdir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(htmlimgdir)" || exit $$?; \
-       done
-
-uninstall-htmlimgDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(htmlimg_DATA)'; test -n "$(htmlimgdir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(htmlimgdir)'; $(am__uninstall_files_from_dir)
-tags: TAGS
-TAGS:
-
-ctags: CTAGS
-CTAGS:
-
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(DATA)
-installdirs:
-       for dir in "$(DESTDIR)$(htmlimgdir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-htmlimgDATA
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-htmlimgDATA
-
-.MAKE: install-am install-strip
-
-.PHONY: all all-am check check-am clean clean-generic clean-libtool \
-       distclean distclean-generic distclean-libtool distdir dvi \
-       dvi-am html html-am info info-am install install-am \
-       install-data install-data-am install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-htmlimgDATA install-info install-info-am install-man \
-       install-pdf install-pdf-am install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-       uninstall uninstall-am uninstall-htmlimgDATA
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/docsrc/Makefile b/service/protocol-plugin/lib/cpluff/docsrc/Makefile
deleted file mode 100644 (file)
index 4fc3a1f..0000000
+++ /dev/null
@@ -1,385 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# docsrc/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = docsrc
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/docsrc
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/docsrc
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../
-top_builddir = ..
-top_srcdir = ..
-EXTRA_DIST = doxygen.css doxygen.footer
-all: all-am
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign docsrc/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign docsrc/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-tags: TAGS
-TAGS:
-
-ctags: CTAGS
-CTAGS:
-
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile
-installdirs:
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: install-am install-strip
-
-.PHONY: all all-am check check-am clean clean-generic clean-libtool \
-       distclean distclean-generic distclean-libtool distdir dvi \
-       dvi-am html html-am info info-am install install-am \
-       install-data install-data-am install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-info install-info-am install-man install-pdf \
-       install-pdf-am install-ps install-ps-am install-strip \
-       installcheck installcheck-am installdirs maintainer-clean \
-       maintainer-clean-generic mostlyclean mostlyclean-generic \
-       mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/examples/Makefile b/service/protocol-plugin/lib/cpluff/examples/Makefile
deleted file mode 100644 (file)
index 81e7e34..0000000
+++ /dev/null
@@ -1,588 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# examples/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = examples
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
-       html-recursive info-recursive install-data-recursive \
-       install-dvi-recursive install-exec-recursive \
-       install-html-recursive install-info-recursive \
-       install-pdf-recursive install-ps-recursive install-recursive \
-       installcheck-recursive installdirs-recursive pdf-recursive \
-       ps-recursive uninstall-recursive
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
-  distclean-recursive maintainer-clean-recursive
-AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
-       $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
-       distdir
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../
-top_builddir = ..
-top_srcdir = ..
-SUBDIRS = cpfile
-EXTRA_DIST = autogen.sh configure.ac INSTALL.txt COPYRIGHT.txt nmakedir.bat common.nmake Makefile.nmake
-all: all-recursive
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign examples/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-#     (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       target=`echo $@ | sed s/-recursive//`; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           dot_seen=yes; \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done; \
-       if test "$$dot_seen" = "no"; then \
-         $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-       fi; test -z "$$fail"
-
-$(RECURSIVE_CLEAN_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       case "$@" in \
-         distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-         *) list='$(SUBDIRS)' ;; \
-       esac; \
-       rev=''; for subdir in $$list; do \
-         if test "$$subdir" = "."; then :; else \
-           rev="$$subdir $$rev"; \
-         fi; \
-       done; \
-       rev="$$rev ."; \
-       target=`echo $@ | sed s/-recursive//`; \
-       for subdir in $$rev; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done && test -z "$$fail"
-tags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
-       done
-ctags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
-       done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-         include_option=--etags-include; \
-         empty_fix=.; \
-       else \
-         include_option=--include; \
-         empty_fix=; \
-       fi; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test ! -f $$subdir/TAGS || \
-             set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-         fi; \
-       done; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test -d "$(distdir)/$$subdir" \
-           || $(MKDIR_P) "$(distdir)/$$subdir" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-           $(am__relativize); \
-           new_distdir=$$reldir; \
-           dir1=$$subdir; dir2="$(top_distdir)"; \
-           $(am__relativize); \
-           new_top_distdir=$$reldir; \
-           echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-           echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-           ($(am__cd) $$subdir && \
-             $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="$$new_top_distdir" \
-               distdir="$$new_distdir" \
-               am__remove_distdir=: \
-               am__skip_length_check=: \
-               am__skip_mode_fix=: \
-               distdir) \
-             || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \
-       install-am install-strip tags-recursive
-
-.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
-       all all-am check check-am clean clean-generic clean-libtool \
-       ctags ctags-recursive distclean distclean-generic \
-       distclean-libtool distclean-tags distdir dvi dvi-am html \
-       html-am info info-am install install-am install-data \
-       install-data-am install-dvi install-dvi-am install-exec \
-       install-exec-am install-html install-html-am install-info \
-       install-info-am install-man install-pdf install-pdf-am \
-       install-ps install-ps-am install-strip installcheck \
-       installcheck-am installdirs installdirs-am maintainer-clean \
-       maintainer-clean-generic mostlyclean mostlyclean-generic \
-       mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \
-       uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile
deleted file mode 100644 (file)
index c045064..0000000
+++ /dev/null
@@ -1,658 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# examples/cpfile/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = examples/cpfile
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
-       $(srcdir)/cpfile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES = cpfile
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(bindir)"
-SCRIPTS = $(bin_SCRIPTS)
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
-       html-recursive info-recursive install-data-recursive \
-       install-dvi-recursive install-exec-recursive \
-       install-html-recursive install-info-recursive \
-       install-pdf-recursive install-ps-recursive install-recursive \
-       installcheck-recursive installdirs-recursive pdf-recursive \
-       ps-recursive uninstall-recursive
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
-  distclean-recursive maintainer-clean-recursive
-AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
-       $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
-       distdir
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../
-top_builddir = ../..
-top_srcdir = ../..
-SUBDIRS = plugins
-EXTRA_DIST = README.txt cpfile.in cpfile.bat Makefile.nmake
-bin_SCRIPTS = cpfile
-all: all-recursive
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign examples/cpfile/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-cpfile: $(top_builddir)/config.status $(srcdir)/cpfile.in
-       cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
-install-binSCRIPTS: $(bin_SCRIPTS)
-       @$(NORMAL_INSTALL)
-       test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-       @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \
-       done | \
-       sed -e 'p;s,.*/,,;n' \
-           -e 'h;s|.*|.|' \
-           -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \
-       $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \
-         { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \
-           if ($$2 == $$4) { files[d] = files[d] " " $$1; \
-             if (++n[d] == $(am__install_max)) { \
-               print "f", d, files[d]; n[d] = 0; files[d] = "" } } \
-           else { print "f", d "/" $$4, $$1 } } \
-         END { for (d in files) print "f", d, files[d] }' | \
-       while read type dir files; do \
-            if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \
-            test -z "$$files" || { \
-              echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \
-              $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
-            } \
-       ; done
-
-uninstall-binSCRIPTS:
-       @$(NORMAL_UNINSTALL)
-       @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \
-       files=`for p in $$list; do echo "$$p"; done | \
-              sed -e 's,.*/,,;$(transform)'`; \
-       dir='$(DESTDIR)$(bindir)'; $(am__uninstall_files_from_dir)
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-#     (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       target=`echo $@ | sed s/-recursive//`; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           dot_seen=yes; \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done; \
-       if test "$$dot_seen" = "no"; then \
-         $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-       fi; test -z "$$fail"
-
-$(RECURSIVE_CLEAN_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       case "$@" in \
-         distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-         *) list='$(SUBDIRS)' ;; \
-       esac; \
-       rev=''; for subdir in $$list; do \
-         if test "$$subdir" = "."; then :; else \
-           rev="$$subdir $$rev"; \
-         fi; \
-       done; \
-       rev="$$rev ."; \
-       target=`echo $@ | sed s/-recursive//`; \
-       for subdir in $$rev; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done && test -z "$$fail"
-tags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
-       done
-ctags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
-       done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-         include_option=--etags-include; \
-         empty_fix=.; \
-       else \
-         include_option=--include; \
-         empty_fix=; \
-       fi; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test ! -f $$subdir/TAGS || \
-             set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-         fi; \
-       done; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test -d "$(distdir)/$$subdir" \
-           || $(MKDIR_P) "$(distdir)/$$subdir" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-           $(am__relativize); \
-           new_distdir=$$reldir; \
-           dir1=$$subdir; dir2="$(top_distdir)"; \
-           $(am__relativize); \
-           new_top_distdir=$$reldir; \
-           echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-           echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-           ($(am__cd) $$subdir && \
-             $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="$$new_top_distdir" \
-               distdir="$$new_distdir" \
-               am__remove_distdir=: \
-               am__skip_length_check=: \
-               am__skip_mode_fix=: \
-               distdir) \
-             || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(SCRIPTS)
-installdirs: installdirs-recursive
-installdirs-am:
-       for dir in "$(DESTDIR)$(bindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am: install-binSCRIPTS
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am: uninstall-binSCRIPTS
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \
-       install-am install-strip tags-recursive
-
-.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
-       all all-am check check-am clean clean-generic clean-libtool \
-       ctags ctags-recursive distclean distclean-generic \
-       distclean-libtool distclean-tags distdir dvi dvi-am html \
-       html-am info info-am install install-am install-binSCRIPTS \
-       install-data install-data-am install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-info install-info-am install-man install-pdf \
-       install-pdf-am install-ps install-ps-am install-strip \
-       installcheck installcheck-am installdirs installdirs-am \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-       tags tags-recursive uninstall uninstall-am \
-       uninstall-binSCRIPTS
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile
deleted file mode 100644 (file)
index daa77a6..0000000
+++ /dev/null
@@ -1,588 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# examples/cpfile/plugins/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = examples/cpfile/plugins
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
-       html-recursive info-recursive install-data-recursive \
-       install-dvi-recursive install-exec-recursive \
-       install-html-recursive install-info-recursive \
-       install-pdf-recursive install-ps-recursive install-recursive \
-       installcheck-recursive installdirs-recursive pdf-recursive \
-       ps-recursive uninstall-recursive
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
-  distclean-recursive maintainer-clean-recursive
-AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
-       $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
-       distdir
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../
-top_builddir = ../../..
-top_srcdir = ../../..
-SUBDIRS = core special extension cext
-EXTRA_DIST = Makefile.nmake
-all: all-recursive
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign examples/cpfile/plugins/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-#     (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       target=`echo $@ | sed s/-recursive//`; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           dot_seen=yes; \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done; \
-       if test "$$dot_seen" = "no"; then \
-         $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-       fi; test -z "$$fail"
-
-$(RECURSIVE_CLEAN_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       case "$@" in \
-         distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-         *) list='$(SUBDIRS)' ;; \
-       esac; \
-       rev=''; for subdir in $$list; do \
-         if test "$$subdir" = "."; then :; else \
-           rev="$$subdir $$rev"; \
-         fi; \
-       done; \
-       rev="$$rev ."; \
-       target=`echo $@ | sed s/-recursive//`; \
-       for subdir in $$rev; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done && test -z "$$fail"
-tags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
-       done
-ctags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
-       done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-         include_option=--etags-include; \
-         empty_fix=.; \
-       else \
-         include_option=--include; \
-         empty_fix=; \
-       fi; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test ! -f $$subdir/TAGS || \
-             set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-         fi; \
-       done; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test -d "$(distdir)/$$subdir" \
-           || $(MKDIR_P) "$(distdir)/$$subdir" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-           $(am__relativize); \
-           new_distdir=$$reldir; \
-           dir1=$$subdir; dir2="$(top_distdir)"; \
-           $(am__relativize); \
-           new_top_distdir=$$reldir; \
-           echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-           echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-           ($(am__cd) $$subdir && \
-             $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="$$new_top_distdir" \
-               distdir="$$new_distdir" \
-               am__remove_distdir=: \
-               am__skip_length_check=: \
-               am__skip_mode_fix=: \
-               distdir) \
-             || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \
-       install-am install-strip tags-recursive
-
-.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
-       all all-am check check-am clean clean-generic clean-libtool \
-       ctags ctags-recursive distclean distclean-generic \
-       distclean-libtool distclean-tags distdir dvi dvi-am html \
-       html-am info info-am install install-am install-data \
-       install-data-am install-dvi install-dvi-am install-exec \
-       install-exec-am install-html install-html-am install-info \
-       install-info-am install-man install-pdf install-pdf-am \
-       install-ps install-ps-am install-strip installcheck \
-       installcheck-am installdirs installdirs-am maintainer-clean \
-       maintainer-clean-generic mostlyclean mostlyclean-generic \
-       mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \
-       uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile
deleted file mode 100644 (file)
index a8c0d16..0000000
+++ /dev/null
@@ -1,440 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# examples/cpfile/plugins/cext/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = examples/cpfile/plugins/cext
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(plugindir)"
-DATA = $(plugin_DATA)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../../
-top_builddir = ../../../..
-top_srcdir = ../../../..
-EXTRA_DIST = plugin.xml Makefile.nmake
-pluginsdir = $(libdir)/cpfile/plugins
-plugindir = $(pluginsdir)/cext
-plugin_DATA = plugin.xml
-all: all-am
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/cext/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign examples/cpfile/plugins/cext/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-pluginDATA: $(plugin_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-tags: TAGS
-TAGS:
-
-ctags: CTAGS
-CTAGS:
-
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(DATA)
-installdirs:
-       for dir in "$(DESTDIR)$(plugindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-pluginDATA
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-pluginDATA
-
-.MAKE: install-am install-strip
-
-.PHONY: all all-am check check-am clean clean-generic clean-libtool \
-       distclean distclean-generic distclean-libtool distdir dvi \
-       dvi-am html html-am info info-am install install-am \
-       install-data install-data-am install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-info install-info-am install-man install-pdf \
-       install-pdf-am install-pluginDATA install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-       uninstall uninstall-am uninstall-pluginDATA
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile
deleted file mode 100644 (file)
index c7ad256..0000000
+++ /dev/null
@@ -1,609 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# examples/cpfile/plugins/core/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = examples/cpfile/plugins/core
-DIST_COMMON = $(plugin_HEADERS) $(srcdir)/Makefile.am \
-       $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" \
-       "$(DESTDIR)$(plugindir)"
-LTLIBRARIES = $(plugin_LTLIBRARIES)
-libcore_la_LIBADD =
-am_libcore_la_OBJECTS = core.lo
-libcore_la_OBJECTS = $(am_libcore_la_OBJECTS)
-libcore_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(libcore_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(libcore_la_SOURCES)
-DIST_SOURCES = $(libcore_la_SOURCES)
-DATA = $(plugin_DATA)
-HEADERS = $(plugin_HEADERS)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../../
-top_builddir = ../../../..
-top_srcdir = ../../../..
-EXTRA_DIST = plugin.xml classifiers.xsd Makefile.nmake
-pluginsdir = $(libdir)/cpfile/plugins
-plugindir = $(pluginsdir)/core
-plugin_LTLIBRARIES = libcore.la
-plugin_DATA = plugin.xml classifiers.xsd
-plugin_HEADERS = core.h
-libcore_la_SOURCES = core.c core.h
-libcore_la_LDFLAGS = -no-undefined -module -avoid-version
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/core/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign examples/cpfile/plugins/core/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       list2=; for p in $$list; do \
-         if test -f $$p; then \
-           list2="$$list2 $$p"; \
-         else :; fi; \
-       done; \
-       test -z "$$list2" || { \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \
-       }
-
-uninstall-pluginLTLIBRARIES:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         $(am__strip_dir) \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \
-       done
-
-clean-pluginLTLIBRARIES:
-       -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES)
-       @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \
-         dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
-         test "$$dir" != "$$p" || dir=.; \
-         echo "rm -f \"$${dir}/so_locations\""; \
-         rm -f "$${dir}/so_locations"; \
-       done
-libcore.la: $(libcore_la_OBJECTS) $(libcore_la_DEPENDENCIES) $(EXTRA_libcore_la_DEPENDENCIES) 
-       $(libcore_la_LINK) -rpath $(plugindir) $(libcore_la_OBJECTS) $(libcore_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/core.Plo
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-pluginDATA: $(plugin_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-install-pluginHEADERS: $(plugin_HEADERS)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_HEADERS)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_HEADER) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginHEADERS:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_HEADERS)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS)
-installdirs:
-       for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \
-       mostlyclean-am
-
-distclean: distclean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-pluginDATA install-pluginHEADERS \
-       install-pluginLTLIBRARIES
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-pluginDATA uninstall-pluginHEADERS \
-       uninstall-pluginLTLIBRARIES
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
-       clean-libtool clean-pluginLTLIBRARIES ctags distclean \
-       distclean-compile distclean-generic distclean-libtool \
-       distclean-tags distdir dvi dvi-am html html-am info info-am \
-       install install-am install-data install-data-am install-dvi \
-       install-dvi-am install-exec install-exec-am install-html \
-       install-html-am install-info install-info-am install-man \
-       install-pdf install-pdf-am install-pluginDATA \
-       install-pluginHEADERS install-pluginLTLIBRARIES install-ps \
-       install-ps-am install-strip installcheck installcheck-am \
-       installdirs maintainer-clean maintainer-clean-generic \
-       mostlyclean mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \
-       uninstall-am uninstall-pluginDATA uninstall-pluginHEADERS \
-       uninstall-pluginLTLIBRARIES
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile
deleted file mode 100644 (file)
index 0decee9..0000000
+++ /dev/null
@@ -1,583 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# examples/cpfile/plugins/extension/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = examples/cpfile/plugins/extension
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"
-LTLIBRARIES = $(plugin_LTLIBRARIES)
-libextension_la_LIBADD =
-am_libextension_la_OBJECTS = extension.lo
-libextension_la_OBJECTS = $(am_libextension_la_OBJECTS)
-libextension_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(libextension_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(libextension_la_SOURCES)
-DIST_SOURCES = $(libextension_la_SOURCES)
-DATA = $(plugin_DATA)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS = -I$(srcdir)/../core  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../../
-top_builddir = ../../../..
-top_srcdir = ../../../..
-EXTRA_DIST = plugin.xml file_types.xsd Makefile.nmake
-pluginsdir = $(libdir)/cpfile/plugins
-plugindir = $(pluginsdir)/extension
-plugin_LTLIBRARIES = libextension.la
-plugin_DATA = plugin.xml file_types.xsd
-libextension_la_SOURCES = extension.c
-libextension_la_LDFLAGS = -no-undefined -module -avoid-version
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/extension/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign examples/cpfile/plugins/extension/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       list2=; for p in $$list; do \
-         if test -f $$p; then \
-           list2="$$list2 $$p"; \
-         else :; fi; \
-       done; \
-       test -z "$$list2" || { \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \
-       }
-
-uninstall-pluginLTLIBRARIES:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         $(am__strip_dir) \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \
-       done
-
-clean-pluginLTLIBRARIES:
-       -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES)
-       @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \
-         dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
-         test "$$dir" != "$$p" || dir=.; \
-         echo "rm -f \"$${dir}/so_locations\""; \
-         rm -f "$${dir}/so_locations"; \
-       done
-libextension.la: $(libextension_la_OBJECTS) $(libextension_la_DEPENDENCIES) $(EXTRA_libextension_la_DEPENDENCIES) 
-       $(libextension_la_LINK) -rpath $(plugindir) $(libextension_la_OBJECTS) $(libextension_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/extension.Plo
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-pluginDATA: $(plugin_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES) $(DATA)
-installdirs:
-       for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \
-       mostlyclean-am
-
-distclean: distclean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-pluginDATA install-pluginLTLIBRARIES
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
-       clean-libtool clean-pluginLTLIBRARIES ctags distclean \
-       distclean-compile distclean-generic distclean-libtool \
-       distclean-tags distdir dvi dvi-am html html-am info info-am \
-       install install-am install-data install-data-am install-dvi \
-       install-dvi-am install-exec install-exec-am install-html \
-       install-html-am install-info install-info-am install-man \
-       install-pdf install-pdf-am install-pluginDATA \
-       install-pluginLTLIBRARIES install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-       pdf pdf-am ps ps-am tags uninstall uninstall-am \
-       uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile
deleted file mode 100644 (file)
index f46bccc..0000000
+++ /dev/null
@@ -1,583 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# examples/cpfile/plugins/special/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = examples/cpfile/plugins/special
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"
-LTLIBRARIES = $(plugin_LTLIBRARIES)
-libspecial_la_LIBADD =
-am_libspecial_la_OBJECTS = special.lo
-libspecial_la_OBJECTS = $(am_libspecial_la_OBJECTS)
-libspecial_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(libspecial_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(libspecial_la_SOURCES)
-DIST_SOURCES = $(libspecial_la_SOURCES)
-DATA = $(plugin_DATA)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS = -I$(srcdir)/../core  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../../
-top_builddir = ../../../..
-top_srcdir = ../../../..
-EXTRA_DIST = plugin.xml Makefile.nmake
-pluginsdir = $(libdir)/cpfile/plugins
-plugindir = $(pluginsdir)/special
-plugin_LTLIBRARIES = libspecial.la
-plugin_DATA = plugin.xml
-libspecial_la_SOURCES = special.c
-libspecial_la_LDFLAGS = -no-undefined -module -avoid-version
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/special/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign examples/cpfile/plugins/special/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       list2=; for p in $$list; do \
-         if test -f $$p; then \
-           list2="$$list2 $$p"; \
-         else :; fi; \
-       done; \
-       test -z "$$list2" || { \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \
-       }
-
-uninstall-pluginLTLIBRARIES:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         $(am__strip_dir) \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \
-       done
-
-clean-pluginLTLIBRARIES:
-       -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES)
-       @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \
-         dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
-         test "$$dir" != "$$p" || dir=.; \
-         echo "rm -f \"$${dir}/so_locations\""; \
-         rm -f "$${dir}/so_locations"; \
-       done
-libspecial.la: $(libspecial_la_OBJECTS) $(libspecial_la_DEPENDENCIES) $(EXTRA_libspecial_la_DEPENDENCIES) 
-       $(libspecial_la_LINK) -rpath $(plugindir) $(libspecial_la_OBJECTS) $(libspecial_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/special.Plo
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-pluginDATA: $(plugin_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES) $(DATA)
-installdirs:
-       for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \
-       mostlyclean-am
-
-distclean: distclean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-pluginDATA install-pluginLTLIBRARIES
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
-       clean-libtool clean-pluginLTLIBRARIES ctags distclean \
-       distclean-compile distclean-generic distclean-libtool \
-       distclean-tags distdir dvi dvi-am html html-am info info-am \
-       install install-am install-data install-data-am install-dvi \
-       install-dvi-am install-exec install-exec-am install-html \
-       install-html-am install-info install-info-am install-man \
-       install-pdf install-pdf-am install-pluginDATA \
-       install-pluginLTLIBRARIES install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-       pdf pdf-am ps ps-am tags uninstall uninstall-am \
-       uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/Makefile b/service/protocol-plugin/lib/cpluff/libcpluff/Makefile
deleted file mode 100644 (file)
index 0778232..0000000
+++ /dev/null
@@ -1,820 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# libcpluff/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-am__append_1 = thread_posix.c
-#am__append_2 = thread_windows.c
-subdir = libcpluff
-DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \
-       $(srcdir)/Makefile.in $(srcdir)/cpluffdef.h.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES = cpluffdef.h
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"
-LTLIBRARIES = $(lib_LTLIBRARIES)
-libcpluff_la_LIBADD =
-am__libcpluff_la_SOURCES_DIST = psymbol.c pscan.c ploader.c pinfo.c \
-       pcontrol.c serial.c logging.c context.c cpluff.c util.c \
-       ../kazlib/list.c ../kazlib/list.h ../kazlib/hash.c \
-       ../kazlib/hash.h internal.h thread.h util.h defines.h \
-       thread_posix.c thread_windows.c
-am__objects_1 = thread_posix.lo
-#am__objects_2 = thread_windows.lo
-am_libcpluff_la_OBJECTS = psymbol.lo pscan.lo ploader.lo pinfo.lo \
-       pcontrol.lo serial.lo logging.lo context.lo cpluff.lo util.lo \
-       list.lo hash.lo $(am__objects_1) $(am__objects_2)
-libcpluff_la_OBJECTS = $(am_libcpluff_la_OBJECTS)
-libcpluff_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(libcpluff_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(libcpluff_la_SOURCES)
-DIST_SOURCES = $(am__libcpluff_la_SOURCES_DIST)
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
-       html-recursive info-recursive install-data-recursive \
-       install-dvi-recursive install-exec-recursive \
-       install-html-recursive install-info-recursive \
-       install-pdf-recursive install-ps-recursive install-recursive \
-       installcheck-recursive installdirs-recursive pdf-recursive \
-       ps-recursive uninstall-recursive
-HEADERS = $(include_HEADERS)
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
-  distclean-recursive maintainer-clean-recursive
-AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
-       $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
-       distdir
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG -I. -DCP_C_API=CP_EXPORT -DCP_HOST="\"$(host)\"" \
-       -DCP_DATADIR="\"$(datadir)\""
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = -lexpat -ldl   
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../
-top_builddir = ..
-top_srcdir = ..
-SUBDIRS = docsrc
-DOXYGEN = doxygen
-DOXYGEN_SOURCE = cpluffdef.h $(srcdir)/cpluff.h $(srcdir)/docsrc/*.dox
-DOXYGEN_STYLE = $(top_srcdir)/docsrc/doxygen.footer $(top_srcdir)/docsrc/doxygen.css
-lib_LTLIBRARIES = libcpluff.la
-libcpluff_la_SOURCES = psymbol.c pscan.c ploader.c pinfo.c pcontrol.c \
-       serial.c logging.c context.c cpluff.c util.c ../kazlib/list.c \
-       ../kazlib/list.h ../kazlib/hash.c ../kazlib/hash.h internal.h \
-       thread.h util.h defines.h $(am__append_1) $(am__append_2)
-libcpluff_la_LDFLAGS = -no-undefined -version-info $(CP_C_LIB_VERSION)
-include_HEADERS = cpluff.h cpluffdef.h
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libcpluff/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign libcpluff/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-cpluffdef.h: $(top_builddir)/config.status $(srcdir)/cpluffdef.h.in
-       cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
-install-libLTLIBRARIES: $(lib_LTLIBRARIES)
-       @$(NORMAL_INSTALL)
-       test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-       @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
-       list2=; for p in $$list; do \
-         if test -f $$p; then \
-           list2="$$list2 $$p"; \
-         else :; fi; \
-       done; \
-       test -z "$$list2" || { \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
-       }
-
-uninstall-libLTLIBRARIES:
-       @$(NORMAL_UNINSTALL)
-       @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
-       for p in $$list; do \
-         $(am__strip_dir) \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \
-       done
-
-clean-libLTLIBRARIES:
-       -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
-       @list='$(lib_LTLIBRARIES)'; for p in $$list; do \
-         dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
-         test "$$dir" != "$$p" || dir=.; \
-         echo "rm -f \"$${dir}/so_locations\""; \
-         rm -f "$${dir}/so_locations"; \
-       done
-libcpluff.la: $(libcpluff_la_OBJECTS) $(libcpluff_la_DEPENDENCIES) $(EXTRA_libcpluff_la_DEPENDENCIES) 
-       $(libcpluff_la_LINK) -rpath $(libdir) $(libcpluff_la_OBJECTS) $(libcpluff_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/context.Plo
-include ./$(DEPDIR)/cpluff.Plo
-include ./$(DEPDIR)/hash.Plo
-include ./$(DEPDIR)/list.Plo
-include ./$(DEPDIR)/logging.Plo
-include ./$(DEPDIR)/pcontrol.Plo
-include ./$(DEPDIR)/pinfo.Plo
-include ./$(DEPDIR)/ploader.Plo
-include ./$(DEPDIR)/pscan.Plo
-include ./$(DEPDIR)/psymbol.Plo
-include ./$(DEPDIR)/serial.Plo
-include ./$(DEPDIR)/thread_posix.Plo
-include ./$(DEPDIR)/thread_windows.Plo
-include ./$(DEPDIR)/util.Plo
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-list.lo: ../kazlib/list.c
-       $(LIBTOOL)  --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT list.lo -MD -MP -MF $(DEPDIR)/list.Tpo -c -o list.lo `test -f '../kazlib/list.c' || echo '$(srcdir)/'`../kazlib/list.c
-       $(am__mv) $(DEPDIR)/list.Tpo $(DEPDIR)/list.Plo
-#      source='../kazlib/list.c' object='list.lo' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LIBTOOL)  --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o list.lo `test -f '../kazlib/list.c' || echo '$(srcdir)/'`../kazlib/list.c
-
-hash.lo: ../kazlib/hash.c
-       $(LIBTOOL)  --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hash.lo -MD -MP -MF $(DEPDIR)/hash.Tpo -c -o hash.lo `test -f '../kazlib/hash.c' || echo '$(srcdir)/'`../kazlib/hash.c
-       $(am__mv) $(DEPDIR)/hash.Tpo $(DEPDIR)/hash.Plo
-#      source='../kazlib/hash.c' object='hash.lo' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LIBTOOL)  --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hash.lo `test -f '../kazlib/hash.c' || echo '$(srcdir)/'`../kazlib/hash.c
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-includeHEADERS: $(include_HEADERS)
-       @$(NORMAL_INSTALL)
-       test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-       @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
-         $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
-       done
-
-uninstall-includeHEADERS:
-       @$(NORMAL_UNINSTALL)
-       @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir)
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-#     (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       target=`echo $@ | sed s/-recursive//`; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           dot_seen=yes; \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done; \
-       if test "$$dot_seen" = "no"; then \
-         $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-       fi; test -z "$$fail"
-
-$(RECURSIVE_CLEAN_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       case "$@" in \
-         distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-         *) list='$(SUBDIRS)' ;; \
-       esac; \
-       rev=''; for subdir in $$list; do \
-         if test "$$subdir" = "."; then :; else \
-           rev="$$subdir $$rev"; \
-         fi; \
-       done; \
-       rev="$$rev ."; \
-       target=`echo $@ | sed s/-recursive//`; \
-       for subdir in $$rev; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done && test -z "$$fail"
-tags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
-       done
-ctags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
-       done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-         include_option=--etags-include; \
-         empty_fix=.; \
-       else \
-         include_option=--include; \
-         empty_fix=; \
-       fi; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test ! -f $$subdir/TAGS || \
-             set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-         fi; \
-       done; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test -d "$(distdir)/$$subdir" \
-           || $(MKDIR_P) "$(distdir)/$$subdir" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-           $(am__relativize); \
-           new_distdir=$$reldir; \
-           dir1=$$subdir; dir2="$(top_distdir)"; \
-           $(am__relativize); \
-           new_top_distdir=$$reldir; \
-           echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-           echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-           ($(am__cd) $$subdir && \
-             $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="$$new_top_distdir" \
-               distdir="$$new_distdir" \
-               am__remove_distdir=: \
-               am__skip_length_check=: \
-               am__skip_mode_fix=: \
-               distdir) \
-             || exit 1; \
-         fi; \
-       done
-       $(MAKE) $(AM_MAKEFLAGS) \
-         top_distdir="$(top_distdir)" distdir="$(distdir)" \
-         dist-hook
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(LTLIBRARIES) $(HEADERS)
-installdirs: installdirs-recursive
-installdirs-am:
-       for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libLTLIBRARIES clean-libtool clean-local \
-       mostlyclean-am
-
-distclean: distclean-recursive
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am: install-includeHEADERS
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am: install-libLTLIBRARIES
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \
-       install-am install-strip tags-recursive
-
-.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
-       all all-am check check-am clean clean-generic \
-       clean-libLTLIBRARIES clean-libtool clean-local ctags \
-       ctags-recursive dist-hook distclean distclean-compile \
-       distclean-generic distclean-libtool distclean-tags distdir dvi \
-       dvi-am html html-am info info-am install install-am \
-       install-data install-data-am install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-includeHEADERS install-info install-info-am \
-       install-libLTLIBRARIES install-man install-pdf install-pdf-am \
-       install-ps install-ps-am install-strip installcheck \
-       installcheck-am installdirs installdirs-am maintainer-clean \
-       maintainer-clean-generic mostlyclean mostlyclean-compile \
-       mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-       tags tags-recursive uninstall uninstall-am \
-       uninstall-includeHEADERS uninstall-libLTLIBRARIES
-
-
-doc: refdoc
-
-refdoc: doc/reference/c-api/index.html
-
-doc/reference/c-api/index.html: $(DOXYGEN_SOURCE) $(top_srcdir)/doc/img/architecture.png docsrc/Doxyfile-ref $(DOXYGEN_STYLE)
-       rm -rf doxygen-ref
-       mkdir -p doxygen-ref
-       cp -p $^ doxygen-ref
-       cd doxygen-ref && $(DOXYGEN) Doxyfile-ref
-       mkdir -p doc/reference
-       rm -rf doc/reference/c-api
-       mv doxygen-ref/html doc/reference/c-api
-       rm -rf doxygen-ref
-
-impldoc: doc/implementation/c-api/index.html
-
-doc/implementation/c-api/index.html: $(srcdir)/*.h $(srcdir)/*.c cpluffdef.h ../config.h docsrc/Doxyfile-impl $(DOXYGEN_STYLE)
-       rm -rf doxygen-impl
-       mkdir -p doxygen-impl
-       cp -p $^ doxygen-impl
-       cd doxygen-impl && $(DOXYGEN) Doxyfile-impl
-       mkdir -p doc/implementation
-       rm -rf doc/implementation/c-api
-       mv doxygen-impl/html doc/implementation/c-api
-       rm -rf doxygen-impl
-
-dist-hook: refdoc
-       mkdir -p $(top_distdir)/doc/reference
-       cp -rp doc/reference/c-api $(top_distdir)/doc/reference
-
-clean-local:
-       rm -rf doc
-
-.PHONY: doc refdoc impldoc
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
index c529386..b27b241 100644 (file)
@@ -1,7 +1,7 @@
 /*-------------------------------------------------------------------------
  * C-Pluff, a plug-in framework for C
  * Copyright 2007 Johannes Lehtinen
- * 
+ *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
  * to deal in the Software without restriction, including without limitation
diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile
deleted file mode 100644 (file)
index 6bc1c78..0000000
+++ /dev/null
@@ -1,390 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# libcpluff/docsrc/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = libcpluff/docsrc
-DIST_COMMON = $(srcdir)/Doxyfile-impl.in $(srcdir)/Doxyfile-ref.in \
-       $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES = Doxyfile-ref Doxyfile-impl
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff/docsrc
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff/docsrc
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../
-top_builddir = ../..
-top_srcdir = ../..
-EXTRA_DIST = mainpage.dox architecture.dox mainprog.dox plugin.dox
-all: all-am
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libcpluff/docsrc/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign libcpluff/docsrc/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-Doxyfile-ref: $(top_builddir)/config.status $(srcdir)/Doxyfile-ref.in
-       cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
-Doxyfile-impl: $(top_builddir)/config.status $(srcdir)/Doxyfile-impl.in
-       cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-tags: TAGS
-TAGS:
-
-ctags: CTAGS
-CTAGS:
-
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile
-installdirs:
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: install-am install-strip
-
-.PHONY: all all-am check check-am clean clean-generic clean-libtool \
-       distclean distclean-generic distclean-libtool distdir dvi \
-       dvi-am html html-am info info-am install install-am \
-       install-data install-data-am install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-info install-info-am install-man install-pdf \
-       install-pdf-am install-ps install-ps-am install-strip \
-       installcheck installcheck-am installdirs maintainer-clean \
-       maintainer-clean-generic mostlyclean mostlyclean-generic \
-       mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
index 83a24cb..e3ac85b 100644 (file)
 #include "config.h"
 #endif
 
+#ifdef __linux__
+// Defining _POSIX_C_SOURCE macro with 200809L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2008 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2008 base specification,
+// Refer http://pubs.opengroup.org/stage7tc1/
+//
+// For this specific file, see use of strndup,
+// Refer http://man7.org/linux/man-pages/man3/strdup.3.html
+#ifndef _POSIX_C_SOURCE
+#define _POSIX_C_SOURCE 200809L
+#endif
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <assert.h>
index b700569..b12df64 100644 (file)
  * Plug-in descriptor loader
  */
 
+#ifdef __linux__
+#ifndef _POSIX_C_SOURCE
+// Defining _POSIX_C_SOURCE macro with 200809L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2008 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2008 base specification,
+// Refer http://pubs.opengroup.org/stage7tc1/
+//
+// For this specific file, see use of strndup,
+// Refer http://man7.org/linux/man-pages/man3/strdup.3.html
+#define _POSIX_C_SOURCE 200809L
+#endif
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
index 38b3297..b7d5a6f 100644 (file)
  * Plug-in scanning functionality
  */
 
+#ifdef __linux__
+#ifndef _POSIX_C_SOURCE
+// Defining _POSIX_C_SOURCE macro with 200809L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2008 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2008 base specification,
+// Refer http://pubs.opengroup.org/stage7tc1/
+//
+// For this specific file, see use of strndup,
+// Refer http://man7.org/linux/man-pages/man3/strdup.3.html
+#define _POSIX_C_SOURCE 200809L
+#endif
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
index a2bca4a..6338d0d 100644 (file)
  * Dynamic plug-in symbols
  */
 
+#ifdef __linux__
+#ifndef _POSIX_C_SOURCE
+// Defining _POSIX_C_SOURCE macro with 200809L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2008 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2008 base specification,
+// Refer http://pubs.opengroup.org/stage7tc1/
+//
+// For this specific file, see use of strndup,
+// Refer http://man7.org/linux/man-pages/man3/strdup.3.html
+#define _POSIX_C_SOURCE 200809L
+#endif
+#endif
+
 #include <stdlib.h>
 #include <string.h>
 #include <assert.h>
diff --git a/service/protocol-plugin/lib/cpluff/loader/Makefile b/service/protocol-plugin/lib/cpluff/loader/Makefile
deleted file mode 100644 (file)
index 447b13d..0000000
+++ /dev/null
@@ -1,539 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# loader/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-bin_PROGRAMS = cpluff-loader$(EXEEXT)
-subdir = loader
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__installdirs = "$(DESTDIR)$(bindir)"
-PROGRAMS = $(bin_PROGRAMS)
-am_cpluff_loader_OBJECTS = loader.$(OBJEXT)
-cpluff_loader_OBJECTS = $(am_cpluff_loader_OBJECTS)
-cpluff_loader_LDADD = $(LDADD)
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(cpluff_loader_SOURCES)
-DIST_SOURCES = $(cpluff_loader_SOURCES)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = $(top_builddir)/libcpluff/libcpluff.la   
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/loader
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/loader
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../
-top_builddir = ..
-top_srcdir = ..
-cpluff_loader_SOURCES = loader.c
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign loader/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign loader/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-binPROGRAMS: $(bin_PROGRAMS)
-       @$(NORMAL_INSTALL)
-       test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-       @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
-       for p in $$list; do echo "$$p $$p"; done | \
-       sed 's/$(EXEEXT)$$//' | \
-       while read p p1; do if test -f $$p || test -f $$p1; \
-         then echo "$$p"; echo "$$p"; else :; fi; \
-       done | \
-       sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
-           -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
-       sed 'N;N;N;s,\n, ,g' | \
-       $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \
-         { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \
-           if ($$2 == $$4) files[d] = files[d] " " $$1; \
-           else { print "f", $$3 "/" $$4, $$1; } } \
-         END { for (d in files) print "f", d, files[d] }' | \
-       while read type dir files; do \
-           if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \
-           test -z "$$files" || { \
-           echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \
-           $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
-           } \
-       ; done
-
-uninstall-binPROGRAMS:
-       @$(NORMAL_UNINSTALL)
-       @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
-       files=`for p in $$list; do echo "$$p"; done | \
-         sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
-             -e 's/$$/$(EXEEXT)/' `; \
-       test -n "$$list" || exit 0; \
-       echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
-       cd "$(DESTDIR)$(bindir)" && rm -f $$files
-
-clean-binPROGRAMS:
-       @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
-       echo " rm -f" $$list; \
-       rm -f $$list || exit $$?; \
-       test -n "$(EXEEXT)" || exit 0; \
-       list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-       echo " rm -f" $$list; \
-       rm -f $$list
-cpluff-loader$(EXEEXT): $(cpluff_loader_OBJECTS) $(cpluff_loader_DEPENDENCIES) $(EXTRA_cpluff_loader_DEPENDENCIES) 
-       @rm -f cpluff-loader$(EXEEXT)
-       $(LINK) $(cpluff_loader_OBJECTS) $(cpluff_loader_LDADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/loader.Po
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(PROGRAMS)
-installdirs:
-       for dir in "$(DESTDIR)$(bindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am: install-binPROGRAMS
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-binPROGRAMS
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \
-       clean-generic clean-libtool ctags distclean distclean-compile \
-       distclean-generic distclean-libtool distclean-tags distdir dvi \
-       dvi-am html html-am info info-am install install-am \
-       install-binPROGRAMS install-data install-data-am install-dvi \
-       install-dvi-am install-exec install-exec-am install-html \
-       install-html-am install-info install-info-am install-man \
-       install-pdf install-pdf-am install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-       pdf pdf-am ps ps-am tags uninstall uninstall-am \
-       uninstall-binPROGRAMS
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/po/Makefile b/service/protocol-plugin/lib/cpluff/po/Makefile
deleted file mode 100644 (file)
index 3aff28b..0000000
+++ /dev/null
@@ -1,507 +0,0 @@
-# Makefile for PO directory in any package using GNU gettext.
-# Copyright (C) 1995-1997, 2000-2006 by Ulrich Drepper <drepper@gnu.ai.mit.edu>
-#
-# This file can be copied and used freely without restrictions.  It can
-# be used in projects which are not available under the GNU General Public
-# License but which still want to provide support for the GNU gettext
-# functionality.
-# Please note that the actual code of GNU gettext is covered by the GNU
-# General Public License and is *not* in the public domain.
-#
-# Origin: gettext-0.16
-
-PACKAGE = cpluff
-VERSION = 0.1.3
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-
-SHELL = /bin/sh
-
-
-srcdir = .
-top_srcdir = ..
-
-
-prefix = /usr/local
-exec_prefix = ${prefix}
-datarootdir = ${prefix}/share
-datadir = ${datarootdir}
-localedir = ${datarootdir}/locale
-gettextsrcdir = $(datadir)/gettext/po
-
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-
-# We use $(mkdir_p).
-# In automake <= 1.9.x, $(mkdir_p) is defined either as "mkdir -p --" or as
-# "$(mkinstalldirs)" or as "$(install_sh) -d". For these automake versions,
-# ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh does not start with $(SHELL), so we add it.
-# In automake >= 1.10, /bin/mkdir -p is derived from ${MKDIR_P}, which is defined
-# either as "/path/to/mkdir -p" or ".../install-sh -c -d". For these automake
-# versions, $(mkinstalldirs) and $(install_sh) are unused.
-mkinstalldirs = $(SHELL) ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh -d
-install_sh = $(SHELL) ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-MKDIR_P = /bin/mkdir -p
-mkdir_p = /bin/mkdir -p
-
-GMSGFMT_ = /usr/bin/msgfmt
-GMSGFMT_no = /usr/bin/msgfmt
-GMSGFMT_yes = /usr/bin/msgfmt
-GMSGFMT = $(GMSGFMT_$(USE_MSGCTXT))
-MSGFMT_ = /usr/bin/msgfmt
-MSGFMT_no = /usr/bin/msgfmt
-MSGFMT_yes = /usr/bin/msgfmt
-MSGFMT = $(MSGFMT_$(USE_MSGCTXT))
-XGETTEXT_ = /usr/bin/xgettext
-XGETTEXT_no = /usr/bin/xgettext
-XGETTEXT_yes = /usr/bin/xgettext
-XGETTEXT = $(XGETTEXT_$(USE_MSGCTXT))
-MSGMERGE = msgmerge
-MSGMERGE_UPDATE = /usr/bin/msgmerge --update
-MSGINIT = msginit
-MSGCONV = msgconv
-MSGFILTER = msgfilter
-
-POFILES =  en@quot.po en@boldquot.po fi.po
-GMOFILES =  en@quot.gmo en@boldquot.gmo fi.gmo
-UPDATEPOFILES =  en@quot.po-update en@boldquot.po-update fi.po-update
-DUMMYPOFILES =  en@quot.nop en@boldquot.nop fi.nop
-DISTFILES.common = Makefile.in.in remove-potcdate.sin \
-$(DISTFILES.common.extra1) $(DISTFILES.common.extra2) $(DISTFILES.common.extra3)
-DISTFILES = $(DISTFILES.common) Makevars POTFILES.in \
-$(POFILES) $(GMOFILES) \
-$(DISTFILES.extra1) $(DISTFILES.extra2) $(DISTFILES.extra3)
-
-POTFILES = \
-     ../console/cmdinput_basic.c \
-     ../console/cmdinput_readline.c \
-     ../console/console.c \
-     ../libcpluff/context.c \
-     ../libcpluff/cpluff.c \
-     ../libcpluff/logging.c \
-     ../libcpluff/pcontrol.c \
-     ../libcpluff/pinfo.c \
-     ../libcpluff/ploader.c \
-     ../libcpluff/pscan.c \
-     ../libcpluff/psymbol.c \
-     ../libcpluff/serial.c \
-     ../libcpluff/thread_posix.c \
-     ../libcpluff/thread_windows.c \
-     ../libcpluff/util.c \
-     ../loader/loader.c
-
-CATALOGS =  en@quot.gmo en@boldquot.gmo fi.gmo
-
-# Makevars gets inserted here. (Don't remove this line!)
-# Makefile variables for PO directory in any package using GNU gettext.
-
-# Usually the message domain is the same as the package name.
-DOMAIN = $(PACKAGE)
-
-# These two variables depend on the location of this directory.
-subdir = po
-top_builddir = ..
-
-# These options get passed to xgettext.
-XGETTEXT_OPTIONS = --keyword=_ --keyword=N_
-
-# This is the copyright holder that gets inserted into the header of the
-# $(DOMAIN).pot file.  Set this to the copyright holder of the surrounding
-# package.  (Note that the msgstr strings, extracted from the package's
-# sources, belong to the copyright holder of the package.)  Translators are
-# expected to transfer the copyright for their translations to this person
-# or entity, or to disclaim their copyright.  The empty string stands for
-# the public domain; in this case the translators are expected to disclaim
-# their copyright.
-COPYRIGHT_HOLDER = Johannes Lehtinen
-
-# This is the email address or URL to which the translators shall report
-# bugs in the untranslated strings:
-# - Strings which are not entire sentences, see the maintainer guidelines
-#   in the GNU gettext documentation, section 'Preparing Strings'.
-# - Strings which use unclear terms or require additional context to be
-#   understood.
-# - Strings which make invalid assumptions about notation of date, time or
-#   money.
-# - Pluralisation problems.
-# - Incorrect English spelling.
-# - Incorrect formatting.
-# It can be your email address, or a mailing list address where translators
-# can write to without being subscribed, or the URL of a web page through
-# which the translators can contact you.
-MSGID_BUGS_ADDRESS = johannes.lehtinen@iki.fi
-
-# This is the list of locale categories, beyond LC_MESSAGES, for which the
-# message catalogs shall be used.  It is usually empty.
-EXTRA_LOCALE_CATEGORIES =
-
-.SUFFIXES:
-.SUFFIXES: .po .gmo .mo .sed .sin .nop .po-create .po-update
-
-.po.mo:
-       @echo "$(MSGFMT) -c -o $@ $<"; \
-       $(MSGFMT) -c -o t-$@ $< && mv t-$@ $@
-
-.po.gmo:
-       @lang=`echo $* | sed -e 's,.*/,,'`; \
-       test "$(srcdir)" = . && cdcmd="" || cdcmd="cd $(srcdir) && "; \
-       echo "$${cdcmd}rm -f $${lang}.gmo && $(GMSGFMT) -c --statistics -o $${lang}.gmo $${lang}.po"; \
-       cd $(srcdir) && rm -f $${lang}.gmo && $(GMSGFMT) -c --statistics -o t-$${lang}.gmo $${lang}.po && mv t-$${lang}.gmo $${lang}.gmo
-
-.sin.sed:
-       sed -e '/^#/d' $< > t-$@
-       mv t-$@ $@
-
-
-all: all-yes
-
-all-yes: stamp-po
-all-no:
-
-# $(srcdir)/$(DOMAIN).pot is only created when needed. When xgettext finds no
-# internationalized messages, no $(srcdir)/$(DOMAIN).pot is created (because
-# we don't want to bother translators with empty POT files). We assume that
-# LINGUAS is empty in this case, i.e. $(POFILES) and $(GMOFILES) are empty.
-# In this case, stamp-po is a nop (i.e. a phony target).
-
-# stamp-po is a timestamp denoting the last time at which the CATALOGS have
-# been loosely updated. Its purpose is that when a developer or translator
-# checks out the package via CVS, and the $(DOMAIN).pot file is not in CVS,
-# "make" will update the $(DOMAIN).pot and the $(CATALOGS), but subsequent
-# invocations of "make" will do nothing. This timestamp would not be necessary
-# if updating the $(CATALOGS) would always touch them; however, the rule for
-# $(POFILES) has been designed to not touch files that don't need to be
-# changed.
-stamp-po: $(srcdir)/$(DOMAIN).pot
-       test ! -f $(srcdir)/$(DOMAIN).pot || \
-         test -z "$(GMOFILES)" || $(MAKE) $(GMOFILES)
-       @test ! -f $(srcdir)/$(DOMAIN).pot || { \
-         echo "touch stamp-po" && \
-         echo timestamp > stamp-poT && \
-         mv stamp-poT stamp-po; \
-       }
-
-# Note: Target 'all' must not depend on target '$(DOMAIN).pot-update',
-# otherwise packages like GCC can not be built if only parts of the source
-# have been downloaded.
-
-# This target rebuilds $(DOMAIN).pot; it is an expensive operation.
-# Note that $(DOMAIN).pot is not touched if it doesn't need to be changed.
-$(DOMAIN).pot-update: $(POTFILES) $(srcdir)/POTFILES.in remove-potcdate.sed
-       if test -n '$(MSGID_BUGS_ADDRESS)' || test '$(PACKAGE_BUGREPORT)' = '@'PACKAGE_BUGREPORT'@'; then \
-         msgid_bugs_address='$(MSGID_BUGS_ADDRESS)'; \
-       else \
-         msgid_bugs_address='$(PACKAGE_BUGREPORT)'; \
-       fi; \
-       $(XGETTEXT) --default-domain=$(DOMAIN) --directory=$(top_srcdir) \
-         --add-comments=TRANSLATORS: $(XGETTEXT_OPTIONS) \
-         --files-from=$(srcdir)/POTFILES.in \
-         --copyright-holder='$(COPYRIGHT_HOLDER)' \
-         --msgid-bugs-address="$$msgid_bugs_address"
-       test ! -f $(DOMAIN).po || { \
-         if test -f $(srcdir)/$(DOMAIN).pot; then \
-           sed -f remove-potcdate.sed < $(srcdir)/$(DOMAIN).pot > $(DOMAIN).1po && \
-           sed -f remove-potcdate.sed < $(DOMAIN).po > $(DOMAIN).2po && \
-           if cmp $(DOMAIN).1po $(DOMAIN).2po >/dev/null 2>&1; then \
-             rm -f $(DOMAIN).1po $(DOMAIN).2po $(DOMAIN).po; \
-           else \
-             rm -f $(DOMAIN).1po $(DOMAIN).2po $(srcdir)/$(DOMAIN).pot && \
-             mv $(DOMAIN).po $(srcdir)/$(DOMAIN).pot; \
-           fi; \
-         else \
-           mv $(DOMAIN).po $(srcdir)/$(DOMAIN).pot; \
-         fi; \
-       }
-
-# This rule has no dependencies: we don't need to update $(DOMAIN).pot at
-# every "make" invocation, only create it when it is missing.
-# Only "make $(DOMAIN).pot-update" or "make dist" will force an update.
-$(srcdir)/$(DOMAIN).pot:
-       $(MAKE) $(DOMAIN).pot-update
-
-# This target rebuilds a PO file if $(DOMAIN).pot has changed.
-# Note that a PO file is not touched if it doesn't need to be changed.
-$(POFILES): $(srcdir)/$(DOMAIN).pot
-       @lang=`echo $@ | sed -e 's,.*/,,' -e 's/\.po$$//'`; \
-       if test -f "$(srcdir)/$${lang}.po"; then \
-         test "$(srcdir)" = . && cdcmd="" || cdcmd="cd $(srcdir) && "; \
-         echo "$${cdcmd}$(MSGMERGE_UPDATE) $${lang}.po $(DOMAIN).pot"; \
-         cd $(srcdir) && $(MSGMERGE_UPDATE) $${lang}.po $(DOMAIN).pot; \
-       else \
-         $(MAKE) $${lang}.po-create; \
-       fi
-
-
-install: install-exec install-data
-install-exec:
-install-data: install-data-yes
-       if test "$(PACKAGE)" = "gettext-tools"; then \
-         $(mkdir_p) $(DESTDIR)$(gettextsrcdir); \
-         for file in $(DISTFILES.common) Makevars.template; do \
-           $(INSTALL_DATA) $(srcdir)/$$file \
-                           $(DESTDIR)$(gettextsrcdir)/$$file; \
-         done; \
-         for file in Makevars; do \
-           rm -f $(DESTDIR)$(gettextsrcdir)/$$file; \
-         done; \
-       else \
-         : ; \
-       fi
-install-data-no: all
-install-data-yes: all
-       $(mkdir_p) $(DESTDIR)$(datadir)
-       @catalogs='$(CATALOGS)'; \
-       for cat in $$catalogs; do \
-         cat=`basename $$cat`; \
-         lang=`echo $$cat | sed -e 's/\.gmo$$//'`; \
-         dir=$(localedir)/$$lang/LC_MESSAGES; \
-         $(mkdir_p) $(DESTDIR)$$dir; \
-         if test -r $$cat; then realcat=$$cat; else realcat=$(srcdir)/$$cat; fi; \
-         $(INSTALL_DATA) $$realcat $(DESTDIR)$$dir/$(DOMAIN).mo; \
-         echo "installing $$realcat as $(DESTDIR)$$dir/$(DOMAIN).mo"; \
-         for lc in '' $(EXTRA_LOCALE_CATEGORIES); do \
-           if test -n "$$lc"; then \
-             if (cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc 2>/dev/null) | grep ' -> ' >/dev/null; then \
-               link=`cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc | sed -e 's/^.* -> //'`; \
-               mv $(DESTDIR)$(localedir)/$$lang/$$lc $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
-               mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
-               (cd $(DESTDIR)$(localedir)/$$lang/$$lc.old && \
-                for file in *; do \
-                  if test -f $$file; then \
-                    ln -s ../$$link/$$file $(DESTDIR)$(localedir)/$$lang/$$lc/$$file; \
-                  fi; \
-                done); \
-               rm -f $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
-             else \
-               if test -d $(DESTDIR)$(localedir)/$$lang/$$lc; then \
-                 :; \
-               else \
-                 rm -f $(DESTDIR)$(localedir)/$$lang/$$lc; \
-                 mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
-               fi; \
-             fi; \
-             rm -f $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo; \
-             ln -s ../LC_MESSAGES/$(DOMAIN).mo $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo 2>/dev/null || \
-             ln $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(DOMAIN).mo $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo 2>/dev/null || \
-             cp -p $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(DOMAIN).mo $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo; \
-             echo "installing $$realcat link as $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo"; \
-           fi; \
-         done; \
-       done
-
-install-strip: install
-
-installdirs: installdirs-exec installdirs-data
-installdirs-exec:
-installdirs-data: installdirs-data-yes
-       if test "$(PACKAGE)" = "gettext-tools"; then \
-         $(mkdir_p) $(DESTDIR)$(gettextsrcdir); \
-       else \
-         : ; \
-       fi
-installdirs-data-no:
-installdirs-data-yes:
-       $(mkdir_p) $(DESTDIR)$(datadir)
-       @catalogs='$(CATALOGS)'; \
-       for cat in $$catalogs; do \
-         cat=`basename $$cat`; \
-         lang=`echo $$cat | sed -e 's/\.gmo$$//'`; \
-         dir=$(localedir)/$$lang/LC_MESSAGES; \
-         $(mkdir_p) $(DESTDIR)$$dir; \
-         for lc in '' $(EXTRA_LOCALE_CATEGORIES); do \
-           if test -n "$$lc"; then \
-             if (cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc 2>/dev/null) | grep ' -> ' >/dev/null; then \
-               link=`cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc | sed -e 's/^.* -> //'`; \
-               mv $(DESTDIR)$(localedir)/$$lang/$$lc $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
-               mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
-               (cd $(DESTDIR)$(localedir)/$$lang/$$lc.old && \
-                for file in *; do \
-                  if test -f $$file; then \
-                    ln -s ../$$link/$$file $(DESTDIR)$(localedir)/$$lang/$$lc/$$file; \
-                  fi; \
-                done); \
-               rm -f $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
-             else \
-               if test -d $(DESTDIR)$(localedir)/$$lang/$$lc; then \
-                 :; \
-               else \
-                 rm -f $(DESTDIR)$(localedir)/$$lang/$$lc; \
-                 mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
-               fi; \
-             fi; \
-           fi; \
-         done; \
-       done
-
-# Define this as empty until I found a useful application.
-installcheck:
-
-uninstall: uninstall-exec uninstall-data
-uninstall-exec:
-uninstall-data: uninstall-data-yes
-       if test "$(PACKAGE)" = "gettext-tools"; then \
-         for file in $(DISTFILES.common) Makevars.template; do \
-           rm -f $(DESTDIR)$(gettextsrcdir)/$$file; \
-         done; \
-       else \
-         : ; \
-       fi
-uninstall-data-no:
-uninstall-data-yes:
-       catalogs='$(CATALOGS)'; \
-       for cat in $$catalogs; do \
-         cat=`basename $$cat`; \
-         lang=`echo $$cat | sed -e 's/\.gmo$$//'`; \
-         for lc in LC_MESSAGES $(EXTRA_LOCALE_CATEGORIES); do \
-           rm -f $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo; \
-         done; \
-       done
-
-check: all
-
-info dvi ps pdf html tags TAGS ctags CTAGS ID:
-
-mostlyclean:
-       rm -f remove-potcdate.sed
-       rm -f stamp-poT
-       rm -f core core.* $(DOMAIN).po $(DOMAIN).1po $(DOMAIN).2po *.new.po
-       rm -fr *.o
-
-clean: mostlyclean
-
-distclean: clean
-       rm -f Makefile Makefile.in POTFILES *.mo
-
-maintainer-clean: distclean
-       @echo "This command is intended for maintainers to use;"
-       @echo "it deletes files that may require special tools to rebuild."
-       rm -f stamp-po $(GMOFILES)
-
-distdir = $(top_builddir)/$(PACKAGE)-$(VERSION)/$(subdir)
-dist distdir:
-       $(MAKE) update-po
-       @$(MAKE) dist2
-# This is a separate target because 'update-po' must be executed before.
-dist2: stamp-po $(DISTFILES)
-       dists="$(DISTFILES)"; \
-       if test "$(PACKAGE)" = "gettext-tools"; then \
-         dists="$$dists Makevars.template"; \
-       fi; \
-       if test -f $(srcdir)/$(DOMAIN).pot; then \
-         dists="$$dists $(DOMAIN).pot stamp-po"; \
-       fi; \
-       if test -f $(srcdir)/ChangeLog; then \
-         dists="$$dists ChangeLog"; \
-       fi; \
-       for i in 0 1 2 3 4 5 6 7 8 9; do \
-         if test -f $(srcdir)/ChangeLog.$$i; then \
-           dists="$$dists ChangeLog.$$i"; \
-         fi; \
-       done; \
-       if test -f $(srcdir)/LINGUAS; then dists="$$dists LINGUAS"; fi; \
-       for file in $$dists; do \
-         if test -f $$file; then \
-           cp -p $$file $(distdir) || exit 1; \
-         else \
-           cp -p $(srcdir)/$$file $(distdir) || exit 1; \
-         fi; \
-       done
-
-update-po: Makefile
-       $(MAKE) $(DOMAIN).pot-update
-       test -z "$(UPDATEPOFILES)" || $(MAKE) $(UPDATEPOFILES)
-       $(MAKE) update-gmo
-
-# General rule for creating PO files.
-
-.nop.po-create:
-       @lang=`echo $@ | sed -e 's/\.po-create$$//'`; \
-       echo "File $$lang.po does not exist. If you are a translator, you can create it through 'msginit'." 1>&2; \
-       exit 1
-
-# General rule for updating PO files.
-
-.nop.po-update:
-       @lang=`echo $@ | sed -e 's/\.po-update$$//'`; \
-       if test "$(PACKAGE)" = "gettext-tools"; then PATH=`pwd`/../src:$$PATH; fi; \
-       tmpdir=`pwd`; \
-       echo "$$lang:"; \
-       test "$(srcdir)" = . && cdcmd="" || cdcmd="cd $(srcdir) && "; \
-       echo "$${cdcmd}$(MSGMERGE) $$lang.po $(DOMAIN).pot -o $$lang.new.po"; \
-       cd $(srcdir); \
-       if $(MSGMERGE) $$lang.po $(DOMAIN).pot -o $$tmpdir/$$lang.new.po; then \
-         if cmp $$lang.po $$tmpdir/$$lang.new.po >/dev/null 2>&1; then \
-           rm -f $$tmpdir/$$lang.new.po; \
-         else \
-           if mv -f $$tmpdir/$$lang.new.po $$lang.po; then \
-             :; \
-           else \
-             echo "msgmerge for $$lang.po failed: cannot move $$tmpdir/$$lang.new.po to $$lang.po" 1>&2; \
-             exit 1; \
-           fi; \
-         fi; \
-       else \
-         echo "msgmerge for $$lang.po failed!" 1>&2; \
-         rm -f $$tmpdir/$$lang.new.po; \
-       fi
-
-$(DUMMYPOFILES):
-
-update-gmo: Makefile $(GMOFILES)
-       @:
-
-Makefile: Makefile.in.in Makevars $(top_builddir)/config.status POTFILES.in LINGUAS
-       cd $(top_builddir) \
-         && $(SHELL) ./config.status $(subdir)/$@.in po-directories
-
-force:
-
-# Tell versions [3.59,3.63) of GNU make not to export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
-# Special Makefile rules for English message catalogs with quotation marks.
-
-DISTFILES.common.extra1 = quot.sed boldquot.sed en@quot.header en@boldquot.header insert-header.sin Rules-quot
-
-.SUFFIXES: .insert-header .po-update-en
-
-en@quot.po-create:
-       $(MAKE) en@quot.po-update
-en@boldquot.po-create:
-       $(MAKE) en@boldquot.po-update
-
-en@quot.po-update: en@quot.po-update-en
-en@boldquot.po-update: en@boldquot.po-update-en
-
-.insert-header.po-update-en:
-       @lang=`echo $@ | sed -e 's/\.po-update-en$$//'`; \
-       if test "$(PACKAGE)" = "gettext"; then PATH=`pwd`/../src:$$PATH; GETTEXTLIBDIR=`cd $(top_srcdir)/src && pwd`; export GETTEXTLIBDIR; fi; \
-       tmpdir=`pwd`; \
-       echo "$$lang:"; \
-       ll=`echo $$lang | sed -e 's/@.*//'`; \
-       LC_ALL=C; export LC_ALL; \
-       cd $(srcdir); \
-       if $(MSGINIT) -i $(DOMAIN).pot --no-translator -l $$ll -o - 2>/dev/null | sed -f $$tmpdir/$$lang.insert-header | $(MSGCONV) -t UTF-8 | $(MSGFILTER) sed -f `echo $$lang | sed -e 's/.*@//'`.sed 2>/dev/null > $$tmpdir/$$lang.new.po; then \
-         if cmp $$lang.po $$tmpdir/$$lang.new.po >/dev/null 2>&1; then \
-           rm -f $$tmpdir/$$lang.new.po; \
-         else \
-           if mv -f $$tmpdir/$$lang.new.po $$lang.po; then \
-             :; \
-           else \
-             echo "creation of $$lang.po failed: cannot move $$tmpdir/$$lang.new.po to $$lang.po" 1>&2; \
-             exit 1; \
-           fi; \
-         fi; \
-       else \
-         echo "creation of $$lang.po failed!" 1>&2; \
-         rm -f $$tmpdir/$$lang.new.po; \
-       fi
-
-en@quot.insert-header: insert-header.sin
-       sed -e '/^#/d' -e 's/HEADER/en@quot.header/g' $(srcdir)/insert-header.sin > en@quot.insert-header
-
-en@boldquot.insert-header: insert-header.sin
-       sed -e '/^#/d' -e 's/HEADER/en@boldquot.header/g' $(srcdir)/insert-header.sin > en@boldquot.insert-header
-
-mostlyclean: mostlyclean-quot
-mostlyclean-quot:
-       rm -f *.insert-header
diff --git a/service/protocol-plugin/lib/cpluff/test/Makefile b/service/protocol-plugin/lib/cpluff/test/Makefile
deleted file mode 100644 (file)
index 2abe252..0000000
+++ /dev/null
@@ -1,770 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# test/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-check_PROGRAMS = testsuite$(EXEEXT)
-subdir = test
-SUBDIRS =
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am_testsuite_OBJECTS = psymbolusage.$(OBJEXT) extcfg.$(OBJEXT) \
-       pdependencies.$(OBJEXT) pcallbacks.$(OBJEXT) \
-       pscanning.$(OBJEXT) pinstallation.$(OBJEXT) ploading.$(OBJEXT) \
-       loggers.$(OBJEXT) collections.$(OBJEXT) initdestroy.$(OBJEXT) \
-       fatalerror.$(OBJEXT) cpinfo.$(OBJEXT) testmain.$(OBJEXT)
-testsuite_OBJECTS = $(am_testsuite_OBJECTS)
-testsuite_LDADD = $(LDADD)
-testsuite_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(testsuite_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(testsuite_SOURCES)
-DIST_SOURCES = $(testsuite_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
-       html-recursive info-recursive install-data-recursive \
-       install-dvi-recursive install-exec-recursive \
-       install-html-recursive install-info-recursive \
-       install-pdf-recursive install-ps-recursive install-recursive \
-       installcheck-recursive installdirs-recursive pdf-recursive \
-       ps-recursive uninstall-recursive
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
-  distclean-recursive maintainer-clean-recursive
-AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
-       $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
-       distdir
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG -DCP_HOST="\"$(host)\""
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = $(top_builddir)/libcpluff/libcpluff.la  
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../
-top_builddir = ..
-top_srcdir = ..
-
-# This can be defined to a debugging wrapper program such as Valgrind.
-TEST_WRAPPER = 
-
-# This can be defined to a subset of test cases to be performed
-SELECTED_TESTS = all
-DIST_SUBDIRS = plugins-source
-EXTRA_DIST = tests.txt
-testsuite_SOURCES = psymbolusage.c extcfg.c pdependencies.c pcallbacks.c pscanning.c pinstallation.c ploading.c loggers.c collections.c initdestroy.c fatalerror.c cpinfo.c testmain.c test.h
-testsuite_LDFLAGS = -dlopen self
-tmpinstalldir = $(CURDIR)/tmp/install
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign test/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign test/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-checkPROGRAMS:
-       @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
-       echo " rm -f" $$list; \
-       rm -f $$list || exit $$?; \
-       test -n "$(EXEEXT)" || exit 0; \
-       list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-       echo " rm -f" $$list; \
-       rm -f $$list
-testsuite$(EXEEXT): $(testsuite_OBJECTS) $(testsuite_DEPENDENCIES) $(EXTRA_testsuite_DEPENDENCIES) 
-       @rm -f testsuite$(EXEEXT)
-       $(testsuite_LINK) $(testsuite_OBJECTS) $(testsuite_LDADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/collections.Po
-include ./$(DEPDIR)/cpinfo.Po
-include ./$(DEPDIR)/extcfg.Po
-include ./$(DEPDIR)/fatalerror.Po
-include ./$(DEPDIR)/initdestroy.Po
-include ./$(DEPDIR)/loggers.Po
-include ./$(DEPDIR)/pcallbacks.Po
-include ./$(DEPDIR)/pdependencies.Po
-include ./$(DEPDIR)/pinstallation.Po
-include ./$(DEPDIR)/ploading.Po
-include ./$(DEPDIR)/pscanning.Po
-include ./$(DEPDIR)/psymbolusage.Po
-include ./$(DEPDIR)/testmain.Po
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-#     (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       target=`echo $@ | sed s/-recursive//`; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           dot_seen=yes; \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done; \
-       if test "$$dot_seen" = "no"; then \
-         $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-       fi; test -z "$$fail"
-
-$(RECURSIVE_CLEAN_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       case "$@" in \
-         distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-         *) list='$(SUBDIRS)' ;; \
-       esac; \
-       rev=''; for subdir in $$list; do \
-         if test "$$subdir" = "."; then :; else \
-           rev="$$subdir $$rev"; \
-         fi; \
-       done; \
-       rev="$$rev ."; \
-       target=`echo $@ | sed s/-recursive//`; \
-       for subdir in $$rev; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done && test -z "$$fail"
-tags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
-       done
-ctags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
-       done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-         include_option=--etags-include; \
-         empty_fix=.; \
-       else \
-         include_option=--include; \
-         empty_fix=; \
-       fi; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test ! -f $$subdir/TAGS || \
-             set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-         fi; \
-       done; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test -d "$(distdir)/$$subdir" \
-           || $(MKDIR_P) "$(distdir)/$$subdir" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-           $(am__relativize); \
-           new_distdir=$$reldir; \
-           dir1=$$subdir; dir2="$(top_distdir)"; \
-           $(am__relativize); \
-           new_top_distdir=$$reldir; \
-           echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-           echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-           ($(am__cd) $$subdir && \
-             $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="$$new_top_distdir" \
-               distdir="$$new_distdir" \
-               am__remove_distdir=: \
-               am__skip_length_check=: \
-               am__skip_mode_fix=: \
-               distdir) \
-             || exit 1; \
-         fi; \
-       done
-       $(MAKE) $(AM_MAKEFLAGS) \
-         top_distdir="$(top_distdir)" distdir="$(distdir)" \
-         dist-hook
-check-am: all-am
-       $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
-       $(MAKE) $(AM_MAKEFLAGS) check-local
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-checkPROGRAMS clean-generic clean-libtool clean-local \
-       mostlyclean-am
-
-distclean: distclean-recursive
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) check-am \
-       ctags-recursive install-am install-strip tags-recursive
-
-.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
-       all all-am check check-am check-local clean \
-       clean-checkPROGRAMS clean-generic clean-libtool clean-local \
-       ctags ctags-recursive dist-hook distclean distclean-compile \
-       distclean-generic distclean-libtool distclean-tags distdir dvi \
-       dvi-am html html-am info info-am install install-am \
-       install-data install-data-am install-dvi install-dvi-am \
-       install-exec install-exec-am install-html install-html-am \
-       install-info install-info-am install-man install-pdf \
-       install-pdf-am install-ps install-ps-am install-strip \
-       installcheck installcheck-am installdirs installdirs-am \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-       pdf pdf-am ps ps-am tags tags-recursive uninstall uninstall-am
-
-
-check-local: install-plugins
-       @numf=0; numt=0; \
-       run_test () { \
-               local test="$$1"; \
-               if test -x "$(srcdir)/test-$$test"; then \
-                       srcdir='$(srcdir)' TEST_WRAPPER='$(TEST_WRAPPER)' "$(srcdir)/test-$$test"; \
-                       rc=$$?; \
-               else \
-                       eval srcdir='$(srcdir)' libtool --mode=execute $(TEST_WRAPPER) ./testsuite "\$$test"; \
-                       rc=$$?; \
-               fi; \
-               case $$rc in \
-                       77) \
-                               echo "SKIPPED: $$test"; \
-                               ;; \
-                       0) \
-                               echo "OK: $$test"; \
-                               numt=$$(($$numt + 1)); \
-                               ;; \
-                       *) \
-                               echo "FAIL: $$test"; \
-                               numt=$$(($$numt + 1)); \
-                               numf=$$(($$numf + 1)); \
-                               ;; \
-               esac; \
-       }; \
-       echo; \
-       echo '===================================================================='; \
-       echo 'C-Pluff Test Suite'; \
-       echo '===================================================================='; \
-       if test '$(SELECTED_TESTS)' = all; then \
-               while read test; do \
-                       run_test "$$test"; \
-               done < '$(srcdir)/tests.txt'; \
-       else \
-               for test in $(SELECTED_TESTS); do \
-                       run_test "$$test"; \
-               done; \
-       fi; \
-       echo '===================================================================='; \
-       if test $$numf -gt 0; then \
-               echo "FAILED: $$numf/$$numt"; \
-       else \
-               echo 'ALL OK!'; \
-       fi; \
-       echo '===================================================================='; \
-       echo; \
-       test $$numf -eq 0
-
-clean-local:
-       rm -rf tmp
-       test ! -f plugins-source/Makefile || (cd plugins-source && $(MAKE) $(AM_MAKEFLAGS) clean)
-
-dist-hook:
-       $(MKDIR_P) '$(distdir)'
-       cp -p '$(srcdir)'/test-* '$(distdir)'
-       $(MKDIR_P) '$(distdir)/expected'
-       cp -p '$(srcdir)'/expected/*.txt '$(distdir)'/expected
-       $(MKDIR_P) '$(distdir)'/plugins
-       cd '$(srcdir)'/plugins && \
-               for d in *; do \
-                       ( mkdir '$(distdir)'/plugins/"$$d" && \
-                               cp -p "$$d/plugin.xml" '$(distdir)'/plugins/"$$d" ) \
-                       || exit 1; \
-               done
-       $(MKDIR_P) '$(distdir)'/pcollections
-       cd '$(srcdir)'/pcollections && \
-               for d in */*; do \
-                       ( $(MKDIR_P) '$(distdir)'/pcollections/"$$d" && \
-                               cp -p "$$d/plugin.xml" '$(distdir)'/pcollections/"$$d" ) \
-                       || exit 1; \
-               done
-
-install-plugins: build-plugins install-libcpluff
-       cd plugins-source && $(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(tmpinstalldir)' install
-
-build-plugins:
-       cd plugins-source && $(MAKE)
-
-install-libcpluff:
-       cd ../libcpluff && $(MAKE) $(AM_MAKEFLAGS) DESTDIR='$(tmpinstalldir)' install
-
-.PHONY: build-plugins install-plugins install-libcpluff
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/test/plugins-source/Makefile b/service/protocol-plugin/lib/cpluff/test/plugins-source/Makefile
deleted file mode 100644 (file)
index 80244b4..0000000
+++ /dev/null
@@ -1,587 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# test/plugins-source/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = test/plugins-source
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
-       html-recursive info-recursive install-data-recursive \
-       install-dvi-recursive install-exec-recursive \
-       install-html-recursive install-info-recursive \
-       install-pdf-recursive install-ps-recursive install-recursive \
-       installcheck-recursive installdirs-recursive pdf-recursive \
-       ps-recursive uninstall-recursive
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
-  distclean-recursive maintainer-clean-recursive
-AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \
-       $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \
-       distdir
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = 
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../
-top_builddir = ../..
-top_srcdir = ../..
-SUBDIRS = callbackcounter symuser symprovider
-all: all-recursive
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign test/plugins-source/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign test/plugins-source/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-#     (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       target=`echo $@ | sed s/-recursive//`; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           dot_seen=yes; \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done; \
-       if test "$$dot_seen" = "no"; then \
-         $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-       fi; test -z "$$fail"
-
-$(RECURSIVE_CLEAN_TARGETS):
-       @fail= failcom='exit 1'; \
-       for f in x $$MAKEFLAGS; do \
-         case $$f in \
-           *=* | --[!k]*);; \
-           *k*) failcom='fail=yes';; \
-         esac; \
-       done; \
-       dot_seen=no; \
-       case "$@" in \
-         distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-         *) list='$(SUBDIRS)' ;; \
-       esac; \
-       rev=''; for subdir in $$list; do \
-         if test "$$subdir" = "."; then :; else \
-           rev="$$subdir $$rev"; \
-         fi; \
-       done; \
-       rev="$$rev ."; \
-       target=`echo $@ | sed s/-recursive//`; \
-       for subdir in $$rev; do \
-         echo "Making $$target in $$subdir"; \
-         if test "$$subdir" = "."; then \
-           local_target="$$target-am"; \
-         else \
-           local_target="$$target"; \
-         fi; \
-         ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-         || eval $$failcom; \
-       done && test -z "$$fail"
-tags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
-       done
-ctags-recursive:
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
-       done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-         include_option=--etags-include; \
-         empty_fix=.; \
-       else \
-         include_option=--include; \
-         empty_fix=; \
-       fi; \
-       list='$(SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test ! -f $$subdir/TAGS || \
-             set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-         fi; \
-       done; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           test -d "$(distdir)/$$subdir" \
-           || $(MKDIR_P) "$(distdir)/$$subdir" \
-           || exit 1; \
-         fi; \
-       done
-       @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-         if test "$$subdir" = .; then :; else \
-           dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-           $(am__relativize); \
-           new_distdir=$$reldir; \
-           dir1=$$subdir; dir2="$(top_distdir)"; \
-           $(am__relativize); \
-           new_top_distdir=$$reldir; \
-           echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-           echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-           ($(am__cd) $$subdir && \
-             $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="$$new_top_distdir" \
-               distdir="$$new_distdir" \
-               am__remove_distdir=: \
-               am__skip_length_check=: \
-               am__skip_mode_fix=: \
-               distdir) \
-             || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-       -rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \
-       install-am install-strip tags-recursive
-
-.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
-       all all-am check check-am clean clean-generic clean-libtool \
-       ctags ctags-recursive distclean distclean-generic \
-       distclean-libtool distclean-tags distdir dvi dvi-am html \
-       html-am info info-am install install-am install-data \
-       install-data-am install-dvi install-dvi-am install-exec \
-       install-exec-am install-html install-html-am install-info \
-       install-info-am install-man install-pdf install-pdf-am \
-       install-ps install-ps-am install-strip installcheck \
-       installcheck-am installdirs installdirs-am maintainer-clean \
-       maintainer-clean-generic mostlyclean mostlyclean-generic \
-       mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \
-       uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/test/plugins-source/callbackcounter/Makefile b/service/protocol-plugin/lib/cpluff/test/plugins-source/callbackcounter/Makefile
deleted file mode 100644 (file)
index 0130bfb..0000000
+++ /dev/null
@@ -1,582 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# test/plugins-source/callbackcounter/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = test/plugins-source/callbackcounter
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"
-LTLIBRARIES = $(plugin_LTLIBRARIES)
-libruntime_la_LIBADD =
-am_libruntime_la_OBJECTS = callbackcounter.lo
-libruntime_la_OBJECTS = $(am_libruntime_la_OBJECTS)
-libruntime_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(libruntime_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(libruntime_la_SOURCES)
-DIST_SOURCES = $(libruntime_la_SOURCES)
-DATA = $(plugin_DATA)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = $(top_builddir)/libcpluff/libcpluff.la  
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source/callbackcounter
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source/callbackcounter
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../
-top_builddir = ../../..
-top_srcdir = ../../..
-EXTRA_DIST = plugin.xml
-plugindir = /plugins/callbackcounter
-plugin_LTLIBRARIES = libruntime.la
-plugin_DATA = plugin.xml
-libruntime_la_SOURCES = callbackcounter.c callbackcounter.h
-libruntime_la_LDFLAGS = -module -avoid-version
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign test/plugins-source/callbackcounter/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign test/plugins-source/callbackcounter/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       list2=; for p in $$list; do \
-         if test -f $$p; then \
-           list2="$$list2 $$p"; \
-         else :; fi; \
-       done; \
-       test -z "$$list2" || { \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \
-       }
-
-uninstall-pluginLTLIBRARIES:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         $(am__strip_dir) \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \
-       done
-
-clean-pluginLTLIBRARIES:
-       -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES)
-       @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \
-         dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
-         test "$$dir" != "$$p" || dir=.; \
-         echo "rm -f \"$${dir}/so_locations\""; \
-         rm -f "$${dir}/so_locations"; \
-       done
-libruntime.la: $(libruntime_la_OBJECTS) $(libruntime_la_DEPENDENCIES) $(EXTRA_libruntime_la_DEPENDENCIES) 
-       $(libruntime_la_LINK) -rpath $(plugindir) $(libruntime_la_OBJECTS) $(libruntime_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/callbackcounter.Plo
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-pluginDATA: $(plugin_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES) $(DATA)
-installdirs:
-       for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \
-       mostlyclean-am
-
-distclean: distclean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-pluginDATA install-pluginLTLIBRARIES
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
-       clean-libtool clean-pluginLTLIBRARIES ctags distclean \
-       distclean-compile distclean-generic distclean-libtool \
-       distclean-tags distdir dvi dvi-am html html-am info info-am \
-       install install-am install-data install-data-am install-dvi \
-       install-dvi-am install-exec install-exec-am install-html \
-       install-html-am install-info install-info-am install-man \
-       install-pdf install-pdf-am install-pluginDATA \
-       install-pluginLTLIBRARIES install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-       pdf pdf-am ps ps-am tags uninstall uninstall-am \
-       uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/test/plugins-source/symprovider/Makefile b/service/protocol-plugin/lib/cpluff/test/plugins-source/symprovider/Makefile
deleted file mode 100644 (file)
index 52bb0c7..0000000
+++ /dev/null
@@ -1,582 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# test/plugins-source/symprovider/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = test/plugins-source/symprovider
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"
-LTLIBRARIES = $(plugin_LTLIBRARIES)
-libruntime_la_LIBADD =
-am_libruntime_la_OBJECTS = symprovider.lo
-libruntime_la_OBJECTS = $(am_libruntime_la_OBJECTS)
-libruntime_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(libruntime_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(libruntime_la_SOURCES)
-DIST_SOURCES = $(libruntime_la_SOURCES)
-DATA = $(plugin_DATA)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = $(top_builddir)/libcpluff/libcpluff.la  
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source/symprovider
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source/symprovider
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../
-top_builddir = ../../..
-top_srcdir = ../../..
-EXTRA_DIST = plugin.xml
-plugindir = /plugins/symprovider
-plugin_LTLIBRARIES = libruntime.la
-plugin_DATA = plugin.xml
-libruntime_la_SOURCES = symprovider.c
-libruntime_la_LDFLAGS = -module -avoid-version
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign test/plugins-source/symprovider/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign test/plugins-source/symprovider/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       list2=; for p in $$list; do \
-         if test -f $$p; then \
-           list2="$$list2 $$p"; \
-         else :; fi; \
-       done; \
-       test -z "$$list2" || { \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \
-       }
-
-uninstall-pluginLTLIBRARIES:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         $(am__strip_dir) \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \
-       done
-
-clean-pluginLTLIBRARIES:
-       -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES)
-       @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \
-         dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
-         test "$$dir" != "$$p" || dir=.; \
-         echo "rm -f \"$${dir}/so_locations\""; \
-         rm -f "$${dir}/so_locations"; \
-       done
-libruntime.la: $(libruntime_la_OBJECTS) $(libruntime_la_DEPENDENCIES) $(EXTRA_libruntime_la_DEPENDENCIES) 
-       $(libruntime_la_LINK) -rpath $(plugindir) $(libruntime_la_OBJECTS) $(libruntime_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/symprovider.Plo
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-pluginDATA: $(plugin_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES) $(DATA)
-installdirs:
-       for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \
-       mostlyclean-am
-
-distclean: distclean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-pluginDATA install-pluginLTLIBRARIES
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
-       clean-libtool clean-pluginLTLIBRARIES ctags distclean \
-       distclean-compile distclean-generic distclean-libtool \
-       distclean-tags distdir dvi dvi-am html html-am info info-am \
-       install install-am install-data install-data-am install-dvi \
-       install-dvi-am install-exec install-exec-am install-html \
-       install-html-am install-info install-info-am install-man \
-       install-pdf install-pdf-am install-pluginDATA \
-       install-pluginLTLIBRARIES install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-       pdf pdf-am ps ps-am tags uninstall uninstall-am \
-       uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/cpluff/test/plugins-source/symuser/Makefile b/service/protocol-plugin/lib/cpluff/test/plugins-source/symuser/Makefile
deleted file mode 100644 (file)
index 5e92e37..0000000
+++ /dev/null
@@ -1,582 +0,0 @@
-# Makefile.in generated by automake 1.11.3 from Makefile.am.
-# test/plugins-source/symuser/Makefile.  Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-# Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-# Copyright 2007 Johannes Lehtinen
-# This Makefile is free software; Johannes Lehtinen gives unlimited
-# permission to copy, distribute and modify it.
-
-
-
-pkgdatadir = $(datadir)/cpluff
-pkgincludedir = $(includedir)/cpluff
-pkglibdir = $(libdir)/cpluff
-pkglibexecdir = $(libexecdir)/cpluff
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = i686-pc-linux-gnu
-host_triplet = i686-pc-linux-gnu
-subdir = test/plugins-source/symuser
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-       $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"
-LTLIBRARIES = $(plugin_LTLIBRARIES)
-libruntime_la_LIBADD =
-am_libruntime_la_OBJECTS = symuser.lo
-libruntime_la_OBJECTS = $(am_libruntime_la_OBJECTS)
-libruntime_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
-       $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-       $(libruntime_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES = -I. -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-       $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-       $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
-       --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-       $(LDFLAGS) -o $@
-SOURCES = $(libruntime_la_SOURCES)
-DIST_SOURCES = $(libruntime_la_SOURCES)
-DATA = $(plugin_DATA)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11
-AMTAR = $${TAR-tar}
-AR = ar
-AS = as
-AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf
-AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader
-AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11
-AWK = mawk
-CC = gcc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2
-CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader
-CPP = gcc -E
-CPPFLAGS =  -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG
-CP_CXX_LIB_VERSION = 0:0:0
-CP_C_LIB_VERSION = 0:3:0
-CP_VERSION_MAJOR = 0
-CP_VERSION_MINOR = 1
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-DLLTOOL = dlltool
-DSYMUTIL = 
-DUMPBIN = 
-ECHO_C = 
-ECHO_N = -n
-ECHO_T = 
-EGREP = /bin/grep -E
-EXEEXT = 
-FGREP = /bin/grep -F
-GETTEXT_MACRO_VERSION = 0.18
-GMSGFMT = /usr/bin/msgfmt
-GMSGFMT_015 = /usr/bin/msgfmt
-GREP = /bin/grep
-INSTALL = /usr/bin/install -c
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
-INTLLIBS = 
-INTL_MACOSX_LIBS = 
-LD = /usr/bin/ld
-LDFLAGS = 
-LIBICONV = -liconv
-LIBINTL = 
-LIBOBJS = 
-LIBS = $(top_builddir)/libcpluff/libcpluff.la  
-LIBS_LIBCPLUFF = -lexpat -ldl 
-LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la 
-LIBTOOL = $(SHELL) $(top_builddir)/libtool
-LIB_READLINE = 
-LIPO = 
-LN_S = ln -s
-LTLIBICONV = -liconv
-LTLIBINTL = 
-LTLIBOBJS = 
-MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo
-MANIFEST_TOOL = :
-MKDIR_P = /bin/mkdir -p
-MSGFMT = /usr/bin/msgfmt
-MSGFMT_015 = /usr/bin/msgfmt
-MSGMERGE = /usr/bin/msgmerge
-NM = /usr/bin/nm -B
-NMEDIT = 
-OBJDUMP = objdump
-OBJEXT = o
-OTOOL = 
-OTOOL64 = 
-PACKAGE = cpluff
-PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi
-PACKAGE_NAME = C-Pluff
-PACKAGE_STRING = C-Pluff 0.1.3
-PACKAGE_TARNAME = cpluff
-PACKAGE_URL = 
-PACKAGE_VERSION = 0.1.3
-PATH_SEPARATOR = :
-POSUB = po
-RANLIB = ranlib
-SED = /bin/sed
-SET_MAKE = 
-SHELL = /bin/bash
-STRIP = strip
-USE_NLS = yes
-VERSION = 0.1.3
-XGETTEXT = /usr/bin/xgettext
-XGETTEXT_015 = /usr/bin/xgettext
-XGETTEXT_EXTRA_OPTIONS = 
-abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source/symuser
-abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/test/plugins-source/symuser
-abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff
-ac_ct_AR = ar
-ac_ct_CC = gcc
-ac_ct_DUMPBIN = 
-am__include = include
-am__leading_dot = .
-am__quote = 
-am__tar = $${TAR-tar} chof - "$$tardir"
-am__untar = $${TAR-tar} xf -
-bindir = ${exec_prefix}/bin
-build = i686-pc-linux-gnu
-build_alias = 
-build_cpu = i686
-build_os = linux-gnu
-build_vendor = pc
-builddir = .
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host = i686-pc-linux-gnu
-host_alias = 
-host_cpu = i686
-host_os = linux-gnu
-host_vendor = pc
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = /bin/mkdir -p
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-srcdir = .
-sysconfdir = ${prefix}/etc
-target_alias = 
-top_build_prefix = ../../../
-top_builddir = ../../..
-top_srcdir = ../../..
-EXTRA_DIST = plugin.xml
-plugindir = /plugins/symuser
-plugin_LTLIBRARIES = libruntime.la
-plugin_DATA = plugin.xml
-libruntime_la_SOURCES = symuser.c
-libruntime_la_LDFLAGS = -module -avoid-version
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-       @for dep in $?; do \
-         case '$(am__configure_deps)' in \
-           *$$dep*) \
-             ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-               && { if test -f $@; then exit 0; else break; fi; }; \
-             exit 1;; \
-         esac; \
-       done; \
-       echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign test/plugins-source/symuser/Makefile'; \
-       $(am__cd) $(top_srcdir) && \
-         $(AUTOMAKE) --foreign test/plugins-source/symuser/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-       @case '$?' in \
-         *config.status*) \
-           cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-         *) \
-           echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-           cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-       esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-       cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       list2=; for p in $$list; do \
-         if test -f $$p; then \
-           list2="$$list2 $$p"; \
-         else :; fi; \
-       done; \
-       test -z "$$list2" || { \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \
-       }
-
-uninstall-pluginLTLIBRARIES:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         $(am__strip_dir) \
-         echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \
-         $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \
-       done
-
-clean-pluginLTLIBRARIES:
-       -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES)
-       @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \
-         dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
-         test "$$dir" != "$$p" || dir=.; \
-         echo "rm -f \"$${dir}/so_locations\""; \
-         rm -f "$${dir}/so_locations"; \
-       done
-libruntime.la: $(libruntime_la_OBJECTS) $(libruntime_la_DEPENDENCIES) $(EXTRA_libruntime_la_DEPENDENCIES) 
-       $(libruntime_la_LINK) -rpath $(plugindir) $(libruntime_la_OBJECTS) $(libruntime_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-       -rm -f *.$(OBJEXT)
-
-distclean-compile:
-       -rm -f *.tab.c
-
-include ./$(DEPDIR)/symuser.Plo
-
-.c.o:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c $<
-
-.c.obj:
-       $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-#      source='$<' object='$@' libtool=no \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.c.lo:
-       $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-       $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
-#      source='$<' object='$@' libtool=yes \
-#      DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-#      $(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-       -rm -f *.lo
-
-clean-libtool:
-       -rm -rf .libs _libs
-install-pluginDATA: $(plugin_DATA)
-       @$(NORMAL_INSTALL)
-       test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)"
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       for p in $$list; do \
-         if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-         echo "$$d$$p"; \
-       done | $(am__base_list) | \
-       while read files; do \
-         echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \
-         $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \
-       done
-
-uninstall-pluginDATA:
-       @$(NORMAL_UNINSTALL)
-       @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \
-       files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-       dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir)
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
-       list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       mkid -fID $$unique
-tags: TAGS
-
-TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       set x; \
-       here=`pwd`; \
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       shift; \
-       if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-         test -n "$$unique" || unique=$$empty_fix; \
-         if test $$# -gt 0; then \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             "$$@" $$unique; \
-         else \
-           $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-             $$unique; \
-         fi; \
-       fi
-ctags: CTAGS
-CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
-               $(TAGS_FILES) $(LISP)
-       list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
-       unique=`for i in $$list; do \
-           if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-         done | \
-         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
-             END { if (nonempty) { for (i in files) print i; }; }'`; \
-       test -z "$(CTAGS_ARGS)$$unique" \
-         || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-            $$unique
-
-GTAGS:
-       here=`$(am__cd) $(top_builddir) && pwd` \
-         && $(am__cd) $(top_srcdir) \
-         && gtags -i $(GTAGS_ARGS) "$$here"
-
-distclean-tags:
-       -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-       list='$(DISTFILES)'; \
-         dist_files=`for file in $$list; do echo $$file; done | \
-         sed -e "s|^$$srcdirstrip/||;t" \
-             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-       case $$dist_files in \
-         */*) $(MKDIR_P) `echo "$$dist_files" | \
-                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-                          sort -u` ;; \
-       esac; \
-       for file in $$dist_files; do \
-         if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         if test -d $$d/$$file; then \
-           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-           if test -d "$(distdir)/$$file"; then \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-             cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-             find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-           fi; \
-           cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-         else \
-           test -f "$(distdir)/$$file" \
-           || cp -p $$d/$$file "$(distdir)/$$file" \
-           || exit 1; \
-         fi; \
-       done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES) $(DATA)
-installdirs:
-       for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \
-         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-       done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-       @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-       if test -z '$(STRIP)'; then \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-             install; \
-       else \
-         $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-           install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-           "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-       fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-       -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-       @echo "This command is intended for maintainers to use"
-       @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \
-       mostlyclean-am
-
-distclean: distclean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-       distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am: install-pluginDATA install-pluginLTLIBRARIES
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-       -rm -rf ./$(DEPDIR)
-       -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-       mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
-       clean-libtool clean-pluginLTLIBRARIES ctags distclean \
-       distclean-compile distclean-generic distclean-libtool \
-       distclean-tags distdir dvi dvi-am html html-am info info-am \
-       install install-am install-data install-data-am install-dvi \
-       install-dvi-am install-exec install-exec-am install-html \
-       install-html-am install-info install-info-am install-man \
-       install-pdf install-pdf-am install-pluginDATA \
-       install-pluginLTLIBRARIES install-ps install-ps-am \
-       install-strip installcheck installcheck-am installdirs \
-       maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-       pdf pdf-am ps ps-am tags uninstall uninstall-am \
-       uninstall-pluginDATA uninstall-pluginLTLIBRARIES
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/service/protocol-plugin/lib/rapidxml/rapidxml.hpp b/service/protocol-plugin/lib/rapidxml/rapidxml.hpp
deleted file mode 100644 (file)
index 9ddf195..0000000
+++ /dev/null
@@ -1,2601 +0,0 @@
-#ifndef RAPIDXML_HPP_INCLUDED
-#define RAPIDXML_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml.hpp This file contains rapidxml parser and DOM implementation
-
-// If standard library is disabled, user must provide implementations of required functions and typedefs
-#if !defined(RAPIDXML_NO_STDLIB)
-    #include <cstdlib>      // For std::size_t
-    #include <cassert>      // For assert
-    #include <new>          // For placement new
-#endif
-
-// On MSVC, disable "conditional expression is constant" warning (level 4). 
-// This warning is almost impossible to avoid with certain types of templated code
-#ifdef _MSC_VER
-    #pragma warning(push)
-    #pragma warning(disable:4127)   // Conditional expression is constant
-#endif
-
-///////////////////////////////////////////////////////////////////////////
-// RAPIDXML_PARSE_ERROR
-    
-#if defined(RAPIDXML_NO_EXCEPTIONS)
-
-#define RAPIDXML_PARSE_ERROR(what, where) { parse_error_handler(what, where); assert(0); }
-
-namespace rapidxml
-{
-    //! When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, 
-    //! this function is called to notify user about the error.
-    //! It must be defined by the user.
-    //! <br><br>
-    //! This function cannot return. If it does, the results are undefined.
-    //! <br><br>
-    //! A very simple definition might look like that:
-    //! <pre>
-    //! void %rapidxml::%parse_error_handler(const char *what, void *where)
-    //! {
-    //!     std::cout << "Parse error: " << what << "\n";
-    //!     std::abort();
-    //! }
-    //! </pre>
-    //! \param what Human readable description of the error.
-    //! \param where Pointer to character data where error was detected.
-    void parse_error_handler(const char *what, void *where);
-}
-
-#else
-    
-#include <exception>    // For std::exception
-
-#define RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where)
-
-namespace rapidxml
-{
-
-    //! Parse error exception. 
-    //! This exception is thrown by the parser when an error occurs. 
-    //! Use what() function to get human-readable error message. 
-    //! Use where() function to get a pointer to position within source text where error was detected.
-    //! <br><br>
-    //! If throwing exceptions by the parser is undesirable, 
-    //! it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included.
-    //! This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception.
-    //! This function must be defined by the user.
-    //! <br><br>
-    //! This class derives from <code>std::exception</code> class.
-    class parse_error: public std::exception
-    {
-    
-    public:
-    
-        //! Constructs parse error
-        parse_error(const char *what, void *where)
-            : m_what(what)
-            , m_where(where)
-        {
-        }
-
-        //! Gets human readable description of error.
-        //! \return Pointer to null terminated description of the error.
-        virtual const char *what() const throw()
-        {
-            return m_what;
-        }
-
-        //! Gets pointer to character data where error happened.
-        //! Ch should be the same as char type of xml_document that produced the error.
-        //! \return Pointer to location within the parsed string where error occured.
-        template<class Ch>
-        Ch *where() const
-        {
-            return reinterpret_cast<Ch *>(m_where);
-        }
-
-    private:  
-
-        const char *m_what;
-        void *m_where;
-
-    };
-}
-
-#endif
-
-///////////////////////////////////////////////////////////////////////////
-// Pool sizes
-
-#ifndef RAPIDXML_STATIC_POOL_SIZE
-    // Size of static memory block of memory_pool.
-    // Define RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value.
-    // No dynamic memory allocations are performed by memory_pool until static memory is exhausted.
-    #define RAPIDXML_STATIC_POOL_SIZE (64 * 1024)
-#endif
-
-#ifndef RAPIDXML_DYNAMIC_POOL_SIZE
-    // Size of dynamic memory block of memory_pool.
-    // Define RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value.
-    // After the static block is exhausted, dynamic blocks with approximately this size are allocated by memory_pool.
-    #define RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024)
-#endif
-
-#ifndef RAPIDXML_ALIGNMENT
-    // Memory allocation alignment.
-    // Define RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to override the default value, which is the size of pointer.
-    // All memory allocations for nodes, attributes and strings will be aligned to this value.
-    // This must be a power of 2 and at least 1, otherwise memory_pool will not work.
-    #define RAPIDXML_ALIGNMENT sizeof(void *)
-#endif
-
-namespace rapidxml
-{
-    // Forward declarations
-    template<class Ch> class xml_node;
-    template<class Ch> class xml_attribute;
-    template<class Ch> class xml_document;
-    
-    //! Enumeration listing all node types produced by the parser.
-    //! Use xml_node::type() function to query node type.
-    enum node_type
-    {
-        node_document,      //!< A document node. Name and value are empty.
-        node_element,       //!< An element node. Name contains element name. Value contains text of first data node.
-        node_data,          //!< A data node. Name is empty. Value contains data text.
-        node_cdata,         //!< A CDATA node. Name is empty. Value contains data text.
-        node_comment,       //!< A comment node. Name is empty. Value contains comment text.
-        node_declaration,   //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.
-        node_doctype,       //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text.
-        node_pi             //!< A PI node. Name contains target. Value contains instructions.
-    };
-
-    ///////////////////////////////////////////////////////////////////////
-    // Parsing flags
-
-    //! Parse flag instructing the parser to not create data nodes. 
-    //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_data_nodes = 0x1;            
-
-    //! Parse flag instructing the parser to not use text of first data node as a value of parent element.
-    //! Can be combined with other flags by use of | operator.
-    //! Note that child data nodes of element node take precendence over its value when printing. 
-    //! That is, if element has one or more child data nodes <em>and</em> a value, the value will be ignored.
-    //! Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_element_values = 0x2;
-    
-    //! Parse flag instructing the parser to not place zero terminators after strings in the source text.
-    //! By default zero terminators are placed, modifying source text.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_string_terminators = 0x4;
-    
-    //! Parse flag instructing the parser to not translate entities in the source text.
-    //! By default entities are translated, modifying source text.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_entity_translation = 0x8;
-    
-    //! Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters.
-    //! By default, UTF-8 handling is enabled.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_utf8 = 0x10;
-    
-    //! Parse flag instructing the parser to create XML declaration node.
-    //! By default, declaration node is not created.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_declaration_node = 0x20;
-    
-    //! Parse flag instructing the parser to create comments nodes.
-    //! By default, comment nodes are not created.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_comment_nodes = 0x40;
-    
-    //! Parse flag instructing the parser to create DOCTYPE node.
-    //! By default, doctype node is not created.
-    //! Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_doctype_node = 0x80;
-    
-    //! Parse flag instructing the parser to create PI nodes.
-    //! By default, PI nodes are not created.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_pi_nodes = 0x100;
-    
-    //! Parse flag instructing the parser to validate closing tag names. 
-    //! If not set, name inside closing tag is irrelevant to the parser.
-    //! By default, closing tags are not validated.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_validate_closing_tags = 0x200;
-    
-    //! Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes.
-    //! By default, whitespace is not trimmed. 
-    //! This flag does not cause the parser to modify source text.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_trim_whitespace = 0x400;
-
-    //! Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character.
-    //! Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag.
-    //! By default, whitespace is not normalized. 
-    //! If this flag is specified, source text will be modified.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_normalize_whitespace = 0x800;
-
-    // Compound flags
-    
-    //! Parse flags which represent default behaviour of the parser. 
-    //! This is always equal to 0, so that all other flags can be simply ored together.
-    //! Normally there is no need to inconveniently disable flags by anding with their negated (~) values.
-    //! This also means that meaning of each flag is a <i>negation</i> of the default setting. 
-    //! For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is <i>enabled</i> by default,
-    //! and using the flag will disable it.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_default = 0;
-    
-    //! A combination of parse flags that forbids any modifications of the source text. 
-    //! This also results in faster parsing. However, note that the following will occur:
-    //! <ul>
-    //! <li>names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends</li>
-    //! <li>entities will not be translated</li>
-    //! <li>whitespace will not be normalized</li>
-    //! </ul>
-    //! See xml_document::parse() function.
-    const int parse_non_destructive = parse_no_string_terminators | parse_no_entity_translation;
-    
-    //! A combination of parse flags resulting in fastest possible parsing, without sacrificing important data.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_fastest = parse_non_destructive | parse_no_data_nodes;
-    
-    //! A combination of parse flags resulting in largest amount of data being extracted. 
-    //! This usually results in slowest parsing.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_full = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags;
-
-    ///////////////////////////////////////////////////////////////////////
-    // Internals
-
-    //! \cond internal
-    namespace internal
-    {
-
-        // Struct that contains lookup tables for the parser
-        // It must be a template to allow correct linking (because it has static data members, which are defined in a header file).
-        template<int Dummy>
-        struct lookup_tables
-        {
-            static const unsigned char lookup_whitespace[256];              // Whitespace table
-            static const unsigned char lookup_node_name[256];               // Node name table
-            static const unsigned char lookup_text[256];                    // Text table
-            static const unsigned char lookup_text_pure_no_ws[256];         // Text table
-            static const unsigned char lookup_text_pure_with_ws[256];       // Text table
-            static const unsigned char lookup_attribute_name[256];          // Attribute name table
-            static const unsigned char lookup_attribute_data_1[256];        // Attribute data table with single quote
-            static const unsigned char lookup_attribute_data_1_pure[256];   // Attribute data table with single quote
-            static const unsigned char lookup_attribute_data_2[256];        // Attribute data table with double quotes
-            static const unsigned char lookup_attribute_data_2_pure[256];   // Attribute data table with double quotes
-            static const unsigned char lookup_digits[256];                  // Digits
-            static const unsigned char lookup_upcase[256];                  // To uppercase conversion table for ASCII characters
-        };
-
-        // Find length of the string
-        template<class Ch>
-        inline std::size_t measure(const Ch *p)
-        {
-            const Ch *tmp = p;
-            while (*tmp) 
-                ++tmp;
-            return tmp - p;
-        }
-
-        // Compare strings for equality
-        template<class Ch>
-        inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive)
-        {
-            if (size1 != size2)
-                return false;
-            if (case_sensitive)
-            {
-                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
-                    if (*p1 != *p2)
-                        return false;
-            }
-            else
-            {
-                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
-                    if (lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p1)] != lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p2)])
-                        return false;
-            }
-            return true;
-        }
-    }
-    //! \endcond
-
-    ///////////////////////////////////////////////////////////////////////
-    // Memory pool
-    
-    //! This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation.
-    //! In most cases, you will not need to use this class directly. 
-    //! However, if you need to create nodes manually or modify names/values of nodes, 
-    //! you are encouraged to use memory_pool of relevant xml_document to allocate the memory. 
-    //! Not only is this faster than allocating them by using <code>new</code> operator, 
-    //! but also their lifetime will be tied to the lifetime of document, 
-    //! possibly simplyfing memory management. 
-    //! <br><br>
-    //! Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. 
-    //! You can also call allocate_string() function to allocate strings.
-    //! Such strings can then be used as names or values of nodes without worrying about their lifetime.
-    //! Note that there is no <code>free()</code> function -- all allocations are freed at once when clear() function is called, 
-    //! or when the pool is destroyed.
-    //! <br><br>
-    //! It is also possible to create a standalone memory_pool, and use it 
-    //! to allocate nodes, whose lifetime will not be tied to any document.
-    //! <br><br>
-    //! Pool maintains <code>RAPIDXML_STATIC_POOL_SIZE</code> bytes of statically allocated memory. 
-    //! Until static memory is exhausted, no dynamic memory allocations are done.
-    //! When static memory is exhausted, pool allocates additional blocks of memory of size <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> each,
-    //! by using global <code>new[]</code> and <code>delete[]</code> operators. 
-    //! This behaviour can be changed by setting custom allocation routines. 
-    //! Use set_allocator() function to set them.
-    //! <br><br>
-    //! Allocations for nodes, attributes and strings are aligned at <code>RAPIDXML_ALIGNMENT</code> bytes.
-    //! This value defaults to the size of pointer on target architecture.
-    //! <br><br>
-    //! To obtain absolutely top performance from the parser,
-    //! it is important that all nodes are allocated from a single, contiguous block of memory.
-    //! Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably.
-    //! If required, you can tweak <code>RAPIDXML_STATIC_POOL_SIZE</code>, <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>RAPIDXML_ALIGNMENT</code> 
-    //! to obtain best wasted memory to performance compromise.
-    //! To do it, define their values before rapidxml.hpp file is included.
-    //! \param Ch Character type of created nodes. 
-    template<class Ch = char>
-    class memory_pool
-    {
-        
-    public:
-
-        //! \cond internal
-        typedef void *(alloc_func)(std::size_t);       // Type of user-defined function used to allocate memory
-        typedef void (free_func)(void *);              // Type of user-defined function used to free memory
-        //! \endcond
-        
-        //! Constructs empty pool with default allocator functions.
-        memory_pool()
-            : m_alloc_func(0)
-            , m_free_func(0)
-        {
-            init();
-        }
-
-        //! Destroys pool and frees all the memory. 
-        //! This causes memory occupied by nodes allocated by the pool to be freed.
-        //! Nodes allocated from the pool are no longer valid.
-        ~memory_pool()
-        {
-            clear();
-        }
-
-        //! Allocates a new node from the pool, and optionally assigns name and value to it. 
-        //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
-        //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
-        //! will call rapidxml::parse_error_handler() function.
-        //! \param type Type of node to create.
-        //! \param name Name to assign to the node, or 0 to assign no name.
-        //! \param value Value to assign to the node, or 0 to assign no value.
-        //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
-        //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
-        //! \return Pointer to allocated node. This pointer will never be NULL.
-        xml_node<Ch> *allocate_node(node_type type, 
-                                    const Ch *name = 0, const Ch *value = 0, 
-                                    std::size_t name_size = 0, std::size_t value_size = 0)
-        {
-            void *memory = allocate_aligned(sizeof(xml_node<Ch>));
-            xml_node<Ch> *node = new(memory) xml_node<Ch>(type);
-            if (name)
-            {
-                if (name_size > 0)
-                    node->name(name, name_size);
-                else
-                    node->name(name);
-            }
-            if (value)
-            {
-                if (value_size > 0)
-                    node->value(value, value_size);
-                else
-                    node->value(value);
-            }
-            return node;
-        }
-
-        //! Allocates a new attribute from the pool, and optionally assigns name and value to it.
-        //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
-        //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
-        //! will call rapidxml::parse_error_handler() function.
-        //! \param name Name to assign to the attribute, or 0 to assign no name.
-        //! \param value Value to assign to the attribute, or 0 to assign no value.
-        //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
-        //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
-        //! \return Pointer to allocated attribute. This pointer will never be NULL.
-        xml_attribute<Ch> *allocate_attribute(const Ch *name = 0, const Ch *value = 0, 
-                                              std::size_t name_size = 0, std::size_t value_size = 0)
-        {
-            void *memory = allocate_aligned(sizeof(xml_attribute<Ch>));
-            xml_attribute<Ch> *attribute = new(memory) xml_attribute<Ch>;
-            if (name)
-            {
-                if (name_size > 0)
-                    attribute->name(name, name_size);
-                else
-                    attribute->name(name);
-            }
-            if (value)
-            {
-                if (value_size > 0)
-                    attribute->value(value, value_size);
-                else
-                    attribute->value(value);
-            }
-            return attribute;
-        }
-
-        //! Allocates a char array of given size from the pool, and optionally copies a given string to it.
-        //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
-        //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
-        //! will call rapidxml::parse_error_handler() function.
-        //! \param source String to initialize the allocated memory with, or 0 to not initialize it.
-        //! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated.
-        //! \return Pointer to allocated char array. This pointer will never be NULL.
-        Ch *allocate_string(const Ch *source = 0, std::size_t size = 0)
-        {
-            assert(source || size);     // Either source or size (or both) must be specified
-            if (size == 0)
-                size = internal::measure(source) + 1;
-            Ch *result = static_cast<Ch *>(allocate_aligned(size * sizeof(Ch)));
-            if (source)
-                for (std::size_t i = 0; i < size; ++i)
-                    result[i] = source[i];
-            return result;
-        }
-
-        //! Clones an xml_node and its hierarchy of child nodes and attributes.
-        //! Nodes and attributes are allocated from this memory pool.
-        //! Names and values are not cloned, they are shared between the clone and the source.
-        //! Result node can be optionally specified as a second parameter, 
-        //! in which case its contents will be replaced with cloned source node.
-        //! This is useful when you want to clone entire document.
-        //! \param source Node to clone.
-        //! \param result Node to put results in, or 0 to automatically allocate result node
-        //! \return Pointer to cloned node. This pointer will never be NULL.
-        xml_node<Ch> *clone_node(const xml_node<Ch> *source, xml_node<Ch> *result = 0)
-        {
-            // Prepare result node
-            if (result)
-            {
-                result->remove_all_attributes();
-                result->remove_all_nodes();
-                result->type(source->type());
-            }
-            else
-                result = allocate_node(source->type());
-
-            // Clone name and value
-            result->name(source->name(), source->name_size());
-            result->value(source->value(), source->value_size());
-
-            // Clone child nodes and attributes
-            for (xml_node<Ch> *child = source->first_node(); child; child = child->next_sibling())
-                result->append_node(clone_node(child));
-            for (xml_attribute<Ch> *attr = source->first_attribute(); attr; attr = attr->next_attribute())
-                result->append_attribute(allocate_attribute(attr->name(), attr->value(), attr->name_size(), attr->value_size()));
-
-            return result;
-        }
-
-        //! Clears the pool. 
-        //! This causes memory occupied by nodes allocated by the pool to be freed.
-        //! Any nodes or strings allocated from the pool will no longer be valid.
-        void clear()
-        {
-            while (m_begin != m_static_memory)
-            {
-                char *previous_begin = reinterpret_cast<header *>(align(m_begin))->previous_begin;
-                if (m_free_func)
-                    m_free_func(m_begin);
-                else
-                    delete[] m_begin;
-                m_begin = previous_begin;
-            }
-            init();
-        }
-
-        //! Sets or resets the user-defined memory allocation functions for the pool.
-        //! This can only be called when no memory is allocated from the pool yet, otherwise results are undefined.
-        //! Allocation function must not return invalid pointer on failure. It should either throw,
-        //! stop the program, or use <code>longjmp()</code> function to pass control to other place of program. 
-        //! If it returns invalid pointer, results are undefined.
-        //! <br><br>
-        //! User defined allocation functions must have the following forms:
-        //! <br><code>
-        //! <br>void *allocate(std::size_t size);
-        //! <br>void free(void *pointer);
-        //! </code><br>
-        //! \param af Allocation function, or 0 to restore default function
-        //! \param ff Free function, or 0 to restore default function
-        void set_allocator(alloc_func *af, free_func *ff)
-        {
-            assert(m_begin == m_static_memory && m_ptr == align(m_begin));    // Verify that no memory is allocated yet
-            m_alloc_func = af;
-            m_free_func = ff;
-        }
-
-    private:
-
-        struct header
-        {
-            char *previous_begin;
-        };
-
-        void init()
-        {
-            m_begin = m_static_memory;
-            m_ptr = align(m_begin);
-            m_end = m_static_memory + sizeof(m_static_memory);
-        }
-        
-        char *align(char *ptr)
-        {
-            std::size_t alignment = ((RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (RAPIDXML_ALIGNMENT - 1))) & (RAPIDXML_ALIGNMENT - 1));
-            return ptr + alignment;
-        }
-        
-        char *allocate_raw(std::size_t size)
-        {
-            // Allocate
-            void *memory;   
-            if (m_alloc_func)   // Allocate memory using either user-specified allocation function or global operator new[]
-            {
-                memory = m_alloc_func(size);
-                assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp
-            }
-            else
-            {
-                memory = new char[size];
-#ifdef RAPIDXML_NO_EXCEPTIONS
-                if (!memory)            // If exceptions are disabled, verify memory allocation, because new will not be able to throw bad_alloc
-                    RAPIDXML_PARSE_ERROR("out of memory", 0);
-#endif
-            }
-            return static_cast<char *>(memory);
-        }
-        
-        void *allocate_aligned(std::size_t size)
-        {
-            // Calculate aligned pointer
-            char *result = align(m_ptr);
-
-            // If not enough memory left in current pool, allocate a new pool
-            if (result + size > m_end)
-            {
-                // Calculate required pool size (may be bigger than RAPIDXML_DYNAMIC_POOL_SIZE)
-                std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE;
-                if (pool_size < size)
-                    pool_size = size;
-                
-                // Allocate
-                std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + pool_size;     // 2 alignments required in worst case: one for header, one for actual allocation
-                char *raw_memory = allocate_raw(alloc_size);
-                    
-                // Setup new pool in allocated memory
-                char *pool = align(raw_memory);
-                header *new_header = reinterpret_cast<header *>(pool);
-                new_header->previous_begin = m_begin;
-                m_begin = raw_memory;
-                m_ptr = pool + sizeof(header);
-                m_end = raw_memory + alloc_size;
-
-                // Calculate aligned pointer again using new pool
-                result = align(m_ptr);
-            }
-
-            // Update pool and return aligned pointer
-            m_ptr = result + size;
-            return result;
-        }
-
-        char *m_begin;                                      // Start of raw memory making up current pool
-        char *m_ptr;                                        // First free byte in current pool
-        char *m_end;                                        // One past last available byte in current pool
-        char m_static_memory[RAPIDXML_STATIC_POOL_SIZE];    // Static raw memory
-        alloc_func *m_alloc_func;                           // Allocator function, or 0 if default is to be used
-        free_func *m_free_func;                             // Free function, or 0 if default is to be used
-    };
-
-    ///////////////////////////////////////////////////////////////////////////
-    // XML base
-
-    //! Base class for xml_node and xml_attribute implementing common functions: 
-    //! name(), name_size(), value(), value_size() and parent().
-    //! \param Ch Character type to use
-    template<class Ch = char>
-    class xml_base
-    {
-
-    public:
-        
-        ///////////////////////////////////////////////////////////////////////////
-        // Construction & destruction
-    
-        // Construct a base with empty name, value and parent
-        xml_base()
-            : m_name(0)
-            , m_value(0)
-            , m_parent(0)
-        {
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node data access
-    
-        //! Gets name of the node. 
-        //! Interpretation of name depends on type of node.
-        //! Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.
-        //! <br><br>
-        //! Use name_size() function to determine length of the name.
-        //! \return Name of node, or empty string if node has no name.
-        Ch *name() const
-        {
-            return m_name ? m_name : nullstr();
-        }
-
-        //! Gets size of node name, not including terminator character.
-        //! This function works correctly irrespective of whether name is or is not zero terminated.
-        //! \return Size of node name, in characters.
-        std::size_t name_size() const
-        {
-            return m_name ? m_name_size : 0;
-        }
-
-        //! Gets value of node. 
-        //! Interpretation of value depends on type of node.
-        //! Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.
-        //! <br><br>
-        //! Use value_size() function to determine length of the value.
-        //! \return Value of node, or empty string if node has no value.
-        Ch *value() const
-        {
-            return m_value ? m_value : nullstr();
-        }
-
-        //! Gets size of node value, not including terminator character.
-        //! This function works correctly irrespective of whether value is or is not zero terminated.
-        //! \return Size of node value, in characters.
-        std::size_t value_size() const
-        {
-            return m_value ? m_value_size : 0;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node modification
-    
-        //! Sets name of node to a non zero-terminated string.
-        //! See \ref ownership_of_strings.
-        //! <br><br>
-        //! Note that node does not own its name or value, it only stores a pointer to it. 
-        //! It will not delete or otherwise free the pointer on destruction.
-        //! It is reponsibility of the user to properly manage lifetime of the string.
-        //! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
-        //! on destruction of the document the string will be automatically freed.
-        //! <br><br>
-        //! Size of name must be specified separately, because name does not have to be zero terminated.
-        //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated).
-        //! \param name Name of node to set. Does not have to be zero terminated.
-        //! \param size Size of name, in characters. This does not include zero terminator, if one is present.
-        void name(const Ch *name, std::size_t size)
-        {
-            m_name = const_cast<Ch *>(name);
-            m_name_size = size;
-        }
-
-        //! Sets name of node to a zero-terminated string.
-        //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t).
-        //! \param name Name of node to set. Must be zero terminated.
-        void name(const Ch *name)
-        {
-            this->name(name, internal::measure(name));
-        }
-
-        //! Sets value of node to a non zero-terminated string.
-        //! See \ref ownership_of_strings.
-        //! <br><br>
-        //! Note that node does not own its name or value, it only stores a pointer to it. 
-        //! It will not delete or otherwise free the pointer on destruction.
-        //! It is reponsibility of the user to properly manage lifetime of the string.
-        //! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
-        //! on destruction of the document the string will be automatically freed.
-        //! <br><br>
-        //! Size of value must be specified separately, because it does not have to be zero terminated.
-        //! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated).
-        //! <br><br>
-        //! If an element has a child node of type node_data, it will take precedence over element value when printing.
-        //! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser.
-        //! \param value value of node to set. Does not have to be zero terminated.
-        //! \param size Size of value, in characters. This does not include zero terminator, if one is present.
-        void value(const Ch *value, std::size_t size)
-        {
-            m_value = const_cast<Ch *>(value);
-            m_value_size = size;
-        }
-
-        //! Sets value of node to a zero-terminated string.
-        //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t).
-        //! \param value Vame of node to set. Must be zero terminated.
-        void value(const Ch *value)
-        {
-            this->value(value, internal::measure(value));
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Related nodes access
-    
-        //! Gets node parent.
-        //! \return Pointer to parent node, or 0 if there is no parent.
-        xml_node<Ch> *parent() const
-        {
-            return m_parent;
-        }
-
-    protected:
-
-        // Return empty string
-        static Ch *nullstr()
-        {
-            static Ch zero = Ch('\0');
-            return &zero;
-        }
-
-        Ch *m_name;                         // Name of node, or 0 if no name
-        Ch *m_value;                        // Value of node, or 0 if no value
-        std::size_t m_name_size;            // Length of node name, or undefined of no name
-        std::size_t m_value_size;           // Length of node value, or undefined if no value
-        xml_node<Ch> *m_parent;             // Pointer to parent node, or 0 if none
-
-    };
-
-    //! Class representing attribute node of XML document. 
-    //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base).
-    //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing. 
-    //! Thus, this text must persist in memory for the lifetime of attribute.
-    //! \param Ch Character type to use.
-    template<class Ch = char>
-    class xml_attribute: public xml_base<Ch>
-    {
-
-        friend class xml_node<Ch>;
-    
-    public:
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Construction & destruction
-    
-        //! Constructs an empty attribute with the specified type. 
-        //! Consider using memory_pool of appropriate xml_document if allocating attributes manually.
-        xml_attribute()
-        {
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Related nodes access
-    
-        //! Gets document of which attribute is a child.
-        //! \return Pointer to document that contains this attribute, or 0 if there is no parent document.
-        xml_document<Ch> *document() const
-        {
-            if (xml_node<Ch> *node = this->parent())
-            {
-                while (node->parent())
-                    node = node->parent();
-                return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0;
-            }
-            else
-                return 0;
-        }
-
-        //! Gets previous attribute, optionally matching attribute name. 
-        //! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *previous_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return this->m_parent ? m_prev_attribute : 0;
-        }
-
-        //! Gets next attribute, optionally matching attribute name. 
-        //! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *next_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return this->m_parent ? m_next_attribute : 0;
-        }
-
-    private:
-
-        xml_attribute<Ch> *m_prev_attribute;        // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero
-        xml_attribute<Ch> *m_next_attribute;        // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero
-    
-    };
-
-    ///////////////////////////////////////////////////////////////////////////
-    // XML node
-
-    //! Class representing a node of XML document. 
-    //! Each node may have associated name and value strings, which are available through name() and value() functions. 
-    //! Interpretation of name and value depends on type of the node.
-    //! Type of node can be determined by using type() function.
-    //! <br><br>
-    //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. 
-    //! Thus, this text must persist in the memory for the lifetime of node.
-    //! \param Ch Character type to use.
-    template<class Ch = char>
-    class xml_node: public xml_base<Ch>
-    {
-
-    public:
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Construction & destruction
-    
-        //! Constructs an empty node with the specified type. 
-        //! Consider using memory_pool of appropriate document to allocate nodes manually.
-        //! \param type Type of node to construct.
-        xml_node(node_type type)
-            : m_type(type)
-            , m_first_node(0)
-            , m_first_attribute(0)
-        {
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node data access
-    
-        //! Gets type of node.
-        //! \return Type of node.
-        node_type type() const
-        {
-            return m_type;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Related nodes access
-    
-        //! Gets document of which node is a child.
-        //! \return Pointer to document that contains this node, or 0 if there is no parent document.
-        xml_document<Ch> *document() const
-        {
-            xml_node<Ch> *node = const_cast<xml_node<Ch> *>(this);
-            while (node->parent())
-                node = node->parent();
-            return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0;
-        }
-
-        //! Gets first child node, optionally matching node name.
-        //! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found child, or 0 if not found.
-        xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling())
-                    if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
-                        return child;
-                return 0;
-            }
-            else
-                return m_first_node;
-        }
-
-        //! Gets last child node, optionally matching node name. 
-        //! Behaviour is undefined if node has no children.
-        //! Use first_node() to test if node has children.
-        //! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found child, or 0 if not found.
-        xml_node<Ch> *last_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            assert(m_first_node);  // Cannot query for last child if node has no children
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *child = m_last_node; child; child = child->previous_sibling())
-                    if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
-                        return child;
-                return 0;
-            }
-            else
-                return m_last_node;
-        }
-
-        //! Gets previous sibling node, optionally matching node name. 
-        //! Behaviour is undefined if node has no parent.
-        //! Use parent() to test if node has a parent.
-        //! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found sibling, or 0 if not found.
-        xml_node<Ch> *previous_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            assert(this->m_parent);     // Cannot query for siblings if node has no parent
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling)
-                    if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive))
-                        return sibling;
-                return 0;
-            }
-            else
-                return m_prev_sibling;
-        }
-
-        //! Gets next sibling node, optionally matching node name. 
-        //! Behaviour is undefined if node has no parent.
-        //! Use parent() to test if node has a parent.
-        //! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found sibling, or 0 if not found.
-        xml_node<Ch> *next_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            assert(this->m_parent);     // Cannot query for siblings if node has no parent
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling)
-                    if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive))
-                        return sibling;
-                return 0;
-            }
-            else
-                return m_next_sibling;
-        }
-
-        //! Gets first attribute of node, optionally matching attribute name.
-        //! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *first_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return m_first_attribute;
-        }
-
-        //! Gets last attribute of node, optionally matching attribute name.
-        //! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *last_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return m_first_attribute ? m_last_attribute : 0;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node modification
-    
-        //! Sets type of node.
-        //! \param type Type of node to set.
-        void type(node_type type)
-        {
-            m_type = type;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node manipulation
-
-        //! Prepends a new child node.
-        //! The prepended child becomes the first child, and all existing children are moved one position back.
-        //! \param child Node to prepend.
-        void prepend_node(xml_node<Ch> *child)
-        {
-            assert(child && !child->parent() && child->type() != node_document);
-            if (first_node())
-            {
-                child->m_next_sibling = m_first_node;
-                m_first_node->m_prev_sibling = child;
-            }
-            else
-            {
-                child->m_next_sibling = 0;
-                m_last_node = child;
-            }
-            m_first_node = child;
-            child->m_parent = this;
-            child->m_prev_sibling = 0;
-        }
-
-        //! Appends a new child node. 
-        //! The appended child becomes the last child.
-        //! \param child Node to append.
-        void append_node(xml_node<Ch> *child)
-        {
-            assert(child && !child->parent() && child->type() != node_document);
-            if (first_node())
-            {
-                child->m_prev_sibling = m_last_node;
-                m_last_node->m_next_sibling = child;
-            }
-            else
-            {
-                child->m_prev_sibling = 0;
-                m_first_node = child;
-            }
-            m_last_node = child;
-            child->m_parent = this;
-            child->m_next_sibling = 0;
-        }
-
-        //! Inserts a new child node at specified place inside the node. 
-        //! All children after and including the specified node are moved one position back.
-        //! \param where Place where to insert the child, or 0 to insert at the back.
-        //! \param child Node to insert.
-        void insert_node(xml_node<Ch> *where, xml_node<Ch> *child)
-        {
-            assert(!where || where->parent() == this);
-            assert(child && !child->parent() && child->type() != node_document);
-            if (where == m_first_node)
-                prepend_node(child);
-            else if (where == 0)
-                append_node(child);
-            else
-            {
-                child->m_prev_sibling = where->m_prev_sibling;
-                child->m_next_sibling = where;
-                where->m_prev_sibling->m_next_sibling = child;
-                where->m_prev_sibling = child;
-                child->m_parent = this;
-            }
-        }
-
-        //! Removes first child node. 
-        //! If node has no children, behaviour is undefined.
-        //! Use first_node() to test if node has children.
-        void remove_first_node()
-        {
-            assert(first_node());
-            xml_node<Ch> *child = m_first_node;
-            m_first_node = child->m_next_sibling;
-            if (child->m_next_sibling)
-                child->m_next_sibling->m_prev_sibling = 0;
-            else
-                m_last_node = 0;
-            child->m_parent = 0;
-        }
-
-        //! Removes last child of the node. 
-        //! If node has no children, behaviour is undefined.
-        //! Use first_node() to test if node has children.
-        void remove_last_node()
-        {
-            assert(first_node());
-            xml_node<Ch> *child = m_last_node;
-            if (child->m_prev_sibling)
-            {
-                m_last_node = child->m_prev_sibling;
-                child->m_prev_sibling->m_next_sibling = 0;
-            }
-            else
-                m_first_node = 0;
-            child->m_parent = 0;
-        }
-
-        //! Removes specified child from the node
-        // \param where Pointer to child to be removed.
-        void remove_node(xml_node<Ch> *where)
-        {
-            assert(where && where->parent() == this);
-            assert(first_node());
-            if (where == m_first_node)
-                remove_first_node();
-            else if (where == m_last_node)
-                remove_last_node();
-            else
-            {
-                where->m_prev_sibling->m_next_sibling = where->m_next_sibling;
-                where->m_next_sibling->m_prev_sibling = where->m_prev_sibling;
-                where->m_parent = 0;
-            }
-        }
-
-        //! Removes all child nodes (but not attributes).
-        void remove_all_nodes()
-        {
-            for (xml_node<Ch> *node = first_node(); node; node = node->m_next_sibling)
-                node->m_parent = 0;
-            m_first_node = 0;
-        }
-
-        //! Prepends a new attribute to the node.
-        //! \param attribute Attribute to prepend.
-        void prepend_attribute(xml_attribute<Ch> *attribute)
-        {
-            assert(attribute && !attribute->parent());
-            if (first_attribute())
-            {
-                attribute->m_next_attribute = m_first_attribute;
-                m_first_attribute->m_prev_attribute = attribute;
-            }
-            else
-            {
-                attribute->m_next_attribute = 0;
-                m_last_attribute = attribute;
-            }
-            m_first_attribute = attribute;
-            attribute->m_parent = this;
-            attribute->m_prev_attribute = 0;
-        }
-
-        //! Appends a new attribute to the node.
-        //! \param attribute Attribute to append.
-        void append_attribute(xml_attribute<Ch> *attribute)
-        {
-            assert(attribute && !attribute->parent());
-            if (first_attribute())
-            {
-                attribute->m_prev_attribute = m_last_attribute;
-                m_last_attribute->m_next_attribute = attribute;
-            }
-            else
-            {
-                attribute->m_prev_attribute = 0;
-                m_first_attribute = attribute;
-            }
-            m_last_attribute = attribute;
-            attribute->m_parent = this;
-            attribute->m_next_attribute = 0;
-        }
-
-        //! Inserts a new attribute at specified place inside the node. 
-        //! All attributes after and including the specified attribute are moved one position back.
-        //! \param where Place where to insert the attribute, or 0 to insert at the back.
-        //! \param attribute Attribute to insert.
-        void insert_attribute(xml_attribute<Ch> *where, xml_attribute<Ch> *attribute)
-        {
-            assert(!where || where->parent() == this);
-            assert(attribute && !attribute->parent());
-            if (where == m_first_attribute)
-                prepend_attribute(attribute);
-            else if (where == 0)
-                append_attribute(attribute);
-            else
-            {
-                attribute->m_prev_attribute = where->m_prev_attribute;
-                attribute->m_next_attribute = where;
-                where->m_prev_attribute->m_next_attribute = attribute;
-                where->m_prev_attribute = attribute;
-                attribute->m_parent = this;
-            }
-        }
-
-        //! Removes first attribute of the node. 
-        //! If node has no attributes, behaviour is undefined.
-        //! Use first_attribute() to test if node has attributes.
-        void remove_first_attribute()
-        {
-            assert(first_attribute());
-            xml_attribute<Ch> *attribute = m_first_attribute;
-            if (attribute->m_next_attribute)
-            {
-                attribute->m_next_attribute->m_prev_attribute = 0;
-            }
-            else
-                m_last_attribute = 0;
-            attribute->m_parent = 0;
-            m_first_attribute = attribute->m_next_attribute;
-        }
-
-        //! Removes last attribute of the node. 
-        //! If node has no attributes, behaviour is undefined.
-        //! Use first_attribute() to test if node has attributes.
-        void remove_last_attribute()
-        {
-            assert(first_attribute());
-            xml_attribute<Ch> *attribute = m_last_attribute;
-            if (attribute->m_prev_attribute)
-            {
-                attribute->m_prev_attribute->m_next_attribute = 0;
-                m_last_attribute = attribute->m_prev_attribute;
-            }
-            else
-                m_first_attribute = 0;
-            attribute->m_parent = 0;
-        }
-
-        //! Removes specified attribute from node.
-        //! \param where Pointer to attribute to be removed.
-        void remove_attribute(xml_attribute<Ch> *where)
-        {
-            assert(first_attribute() && where->parent() == this);
-            if (where == m_first_attribute)
-                remove_first_attribute();
-            else if (where == m_last_attribute)
-                remove_last_attribute();
-            else
-            {
-                where->m_prev_attribute->m_next_attribute = where->m_next_attribute;
-                where->m_next_attribute->m_prev_attribute = where->m_prev_attribute;
-                where->m_parent = 0;
-            }
-        }
-
-        //! Removes all attributes of node.
-        void remove_all_attributes()
-        {
-            for (xml_attribute<Ch> *attribute = first_attribute(); attribute; attribute = attribute->m_next_attribute)
-                attribute->m_parent = 0;
-            m_first_attribute = 0;
-        }
-        
-    private:
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Restrictions
-
-        // No copying
-        xml_node(const xml_node &);
-        void operator =(const xml_node &);
-    
-        ///////////////////////////////////////////////////////////////////////////
-        // Data members
-    
-        // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0.
-        // This is required for maximum performance, as it allows the parser to omit initialization of 
-        // unneded/redundant values.
-        //
-        // The rules are as follows:
-        // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively
-        // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage
-        // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage
-
-        node_type m_type;                       // Type of node; always valid
-        xml_node<Ch> *m_first_node;             // Pointer to first child node, or 0 if none; always valid
-        xml_node<Ch> *m_last_node;              // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero
-        xml_attribute<Ch> *m_first_attribute;   // Pointer to first attribute of node, or 0 if none; always valid
-        xml_attribute<Ch> *m_last_attribute;    // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero
-        xml_node<Ch> *m_prev_sibling;           // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero
-        xml_node<Ch> *m_next_sibling;           // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero
-
-    };
-
-    ///////////////////////////////////////////////////////////////////////////
-    // XML document
-    
-    //! This class represents root of the DOM hierarchy. 
-    //! It is also an xml_node and a memory_pool through public inheritance.
-    //! Use parse() function to build a DOM tree from a zero-terminated XML text string.
-    //! parse() function allocates memory for nodes and attributes by using functions of xml_document, 
-    //! which are inherited from memory_pool.
-    //! To access root node of the document, use the document itself, as if it was an xml_node.
-    //! \param Ch Character type to use.
-    template<class Ch = char>
-    class xml_document: public xml_node<Ch>, public memory_pool<Ch>
-    {
-    
-    public:
-
-        //! Constructs empty XML document
-        xml_document()
-            : xml_node<Ch>(node_document)
-        {
-        }
-
-        //! Parses zero-terminated XML string according to given flags.
-        //! Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used.
-        //! The string must persist for the lifetime of the document.
-        //! In case of error, rapidxml::parse_error exception will be thrown.
-        //! <br><br>
-        //! If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning.
-        //! Make sure that data is zero-terminated.
-        //! <br><br>
-        //! Document can be parsed into multiple times. 
-        //! Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool.
-        //! \param text XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser.
-        template<int Flags>
-        void parse(Ch *text)
-        {
-            assert(text);
-            
-            // Remove current contents
-            this->remove_all_nodes();
-            this->remove_all_attributes();
-            
-            // Parse BOM, if any
-            parse_bom<Flags>(text);
-            
-            // Parse children
-            while (1)
-            {
-                // Skip whitespace before node
-                skip<whitespace_pred, Flags>(text);
-                if (*text == 0)
-                    break;
-
-                // Parse and append new child
-                if (*text == Ch('<'))
-                {
-                    ++text;     // Skip '<'
-                    if (xml_node<Ch> *node = parse_node<Flags>(text))
-                        this->append_node(node);
-                }
-                else
-                    RAPIDXML_PARSE_ERROR("expected <", text);
-            }
-
-        }
-
-        //! Clears the document by deleting all nodes and clearing the memory pool.
-        //! All nodes owned by document pool are destroyed.
-        void clear()
-        {
-            this->remove_all_nodes();
-            this->remove_all_attributes();
-            memory_pool<Ch>::clear();
-        }
-        
-    private:
-
-        ///////////////////////////////////////////////////////////////////////
-        // Internal character utility functions
-        
-        // Detect whitespace character
-        struct whitespace_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_whitespace[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect node name character
-        struct node_name_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_node_name[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect attribute name character
-        struct attribute_name_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_attribute_name[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect text character (PCDATA)
-        struct text_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_text[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect text character (PCDATA) that does not require processing
-        struct text_pure_no_ws_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_text_pure_no_ws[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect text character (PCDATA) that does not require processing
-        struct text_pure_with_ws_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_text_pure_with_ws[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect attribute value character
-        template<Ch Quote>
-        struct attribute_value_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                if (Quote == Ch('\''))
-                    return internal::lookup_tables<0>::lookup_attribute_data_1[static_cast<unsigned char>(ch)];
-                if (Quote == Ch('\"'))
-                    return internal::lookup_tables<0>::lookup_attribute_data_2[static_cast<unsigned char>(ch)];
-                return 0;       // Should never be executed, to avoid warnings on Comeau
-            }
-        };
-
-        // Detect attribute value character
-        template<Ch Quote>
-        struct attribute_value_pure_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                if (Quote == Ch('\''))
-                    return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast<unsigned char>(ch)];
-                if (Quote == Ch('\"'))
-                    return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast<unsigned char>(ch)];
-                return 0;       // Should never be executed, to avoid warnings on Comeau
-            }
-        };
-
-        // Insert coded character, using UTF8 or 8-bit ASCII
-        template<int Flags>
-        static void insert_coded_character(Ch *&text, unsigned long code)
-        {
-            if (Flags & parse_no_utf8)
-            {
-                // Insert 8-bit ASCII character
-                // Todo: possibly verify that code is less than 256 and use replacement char otherwise?
-                text[0] = static_cast<unsigned char>(code);
-                text += 1;
-            }
-            else
-            {
-                // Insert UTF8 sequence
-                if (code < 0x80)    // 1 byte sequence
-                {
-                       text[0] = static_cast<unsigned char>(code);
-                    text += 1;
-                }
-                else if (code < 0x800)  // 2 byte sequence
-                {
-                       text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[0] = static_cast<unsigned char>(code | 0xC0);
-                    text += 2;
-                }
-                   else if (code < 0x10000)    // 3 byte sequence
-                {
-                       text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[0] = static_cast<unsigned char>(code | 0xE0);
-                    text += 3;
-                }
-                   else if (code < 0x110000)   // 4 byte sequence
-                {
-                       text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[0] = static_cast<unsigned char>(code | 0xF0);
-                    text += 4;
-                }
-                else    // Invalid, only codes up to 0x10FFFF are allowed in Unicode
-                {
-                    RAPIDXML_PARSE_ERROR("invalid numeric character entity", text);
-                }
-            }
-        }
-
-        // Skip characters until predicate evaluates to true
-        template<class StopPred, int Flags>
-        static void skip(Ch *&text)
-        {
-            Ch *tmp = text;
-            while (StopPred::test(*tmp))
-                ++tmp;
-            text = tmp;
-        }
-
-        // Skip characters until predicate evaluates to true while doing the following:
-        // - replacing XML character entity references with proper characters (&apos; &amp; &quot; &lt; &gt; &#...;)
-        // - condensing whitespace sequences to single space character
-        template<class StopPred, class StopPredPure, int Flags>
-        static Ch *skip_and_expand_character_refs(Ch *&text)
-        {
-            // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip
-            if (Flags & parse_no_entity_translation && 
-                !(Flags & parse_normalize_whitespace) &&
-                !(Flags & parse_trim_whitespace))
-            {
-                skip<StopPred, Flags>(text);
-                return text;
-            }
-            
-            // Use simple skip until first modification is detected
-            skip<StopPredPure, Flags>(text);
-
-            // Use translation skip
-            Ch *src = text;
-            Ch *dest = src;
-            while (StopPred::test(*src))
-            {
-                // If entity translation is enabled    
-                if (!(Flags & parse_no_entity_translation))
-                {
-                    // Test if replacement is needed
-                    if (src[0] == Ch('&'))
-                    {
-                        switch (src[1])
-                        {
-
-                        // &amp; &apos;
-                        case Ch('a'): 
-                            if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';'))
-                            {
-                                *dest = Ch('&');
-                                ++dest;
-                                src += 5;
-                                continue;
-                            }
-                            if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';'))
-                            {
-                                *dest = Ch('\'');
-                                ++dest;
-                                src += 6;
-                                continue;
-                            }
-                            break;
-
-                        // &quot;
-                        case Ch('q'): 
-                            if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';'))
-                            {
-                                *dest = Ch('"');
-                                ++dest;
-                                src += 6;
-                                continue;
-                            }
-                            break;
-
-                        // &gt;
-                        case Ch('g'): 
-                            if (src[2] == Ch('t') && src[3] == Ch(';'))
-                            {
-                                *dest = Ch('>');
-                                ++dest;
-                                src += 4;
-                                continue;
-                            }
-                            break;
-
-                        // &lt;
-                        case Ch('l'): 
-                            if (src[2] == Ch('t') && src[3] == Ch(';'))
-                            {
-                                *dest = Ch('<');
-                                ++dest;
-                                src += 4;
-                                continue;
-                            }
-                            break;
-
-                        // &#...; - assumes ASCII
-                        case Ch('#'): 
-                            if (src[2] == Ch('x'))
-                            {
-                                unsigned long code = 0;
-                                src += 3;   // Skip &#x
-                                while (1)
-                                {
-                                    unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)];
-                                    if (digit == 0xFF)
-                                        break;
-                                    code = code * 16 + digit;
-                                    ++src;
-                                }
-                                insert_coded_character<Flags>(dest, code);    // Put character in output
-                            }
-                            else
-                            {
-                                unsigned long code = 0;
-                                src += 2;   // Skip &#
-                                while (1)
-                                {
-                                    unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)];
-                                    if (digit == 0xFF)
-                                        break;
-                                    code = code * 10 + digit;
-                                    ++src;
-                                }
-                                insert_coded_character<Flags>(dest, code);    // Put character in output
-                            }
-                            if (*src == Ch(';'))
-                                ++src;
-                            else
-                                RAPIDXML_PARSE_ERROR("expected ;", src);
-                            continue;
-
-                        // Something else
-                        default:
-                            // Ignore, just copy '&' verbatim
-                            break;
-
-                        }
-                    }
-                }
-                
-                // If whitespace condensing is enabled
-                if (Flags & parse_normalize_whitespace)
-                {
-                    // Test if condensing is needed                 
-                    if (whitespace_pred::test(*src))
-                    {
-                        *dest = Ch(' '); ++dest;    // Put single space in dest
-                        ++src;                      // Skip first whitespace char
-                        // Skip remaining whitespace chars
-                        while (whitespace_pred::test(*src))
-                            ++src;
-                        continue;
-                    }
-                }
-
-                // No replacement, only copy character
-                *dest++ = *src++;
-
-            }
-
-            // Return new end
-            text = src;
-            return dest;
-
-        }
-
-        ///////////////////////////////////////////////////////////////////////
-        // Internal parsing functions
-        
-        // Parse BOM, if any
-        template<int Flags>
-        void parse_bom(Ch *&text)
-        {
-            // UTF-8?
-            if (static_cast<unsigned char>(text[0]) == 0xEF && 
-                static_cast<unsigned char>(text[1]) == 0xBB && 
-                static_cast<unsigned char>(text[2]) == 0xBF)
-            {
-                text += 3;      // Skup utf-8 bom
-            }
-        }
-
-        // Parse XML declaration (<?xml...)
-        template<int Flags>
-        xml_node<Ch> *parse_xml_declaration(Ch *&text)
-        {
-            // If parsing of declaration is disabled
-            if (!(Flags & parse_declaration_node))
-            {
-                // Skip until end of declaration
-                while (text[0] != Ch('?') || text[1] != Ch('>'))
-                {
-                    if (!text[0])
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 2;    // Skip '?>'
-                return 0;
-            }
-
-            // Create declaration
-            xml_node<Ch> *declaration = this->allocate_node(node_declaration);
-
-            // Skip whitespace before attributes or ?>
-            skip<whitespace_pred, Flags>(text);
-
-            // Parse declaration attributes
-            parse_node_attributes<Flags>(text, declaration);
-            
-            // Skip ?>
-            if (text[0] != Ch('?') || text[1] != Ch('>'))
-                RAPIDXML_PARSE_ERROR("expected ?>", text);
-            text += 2;
-            
-            return declaration;
-        }
-
-        // Parse XML comment (<!--...)
-        template<int Flags>
-        xml_node<Ch> *parse_comment(Ch *&text)
-        {
-            // If parsing of comments is disabled
-            if (!(Flags & parse_comment_nodes))
-            {
-                // Skip until end of comment
-                while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
-                {
-                    if (!text[0])
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 3;     // Skip '-->'
-                return 0;      // Do not produce comment node
-            }
-
-            // Remember value start
-            Ch *value = text;
-
-            // Skip until end of comment
-            while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
-            {
-                if (!text[0])
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                ++text;
-            }
-
-            // Create comment node
-            xml_node<Ch> *comment = this->allocate_node(node_comment);
-            comment->value(value, text - value);
-            
-            // Place zero terminator after comment value
-            if (!(Flags & parse_no_string_terminators))
-                *text = Ch('\0');
-            
-            text += 3;     // Skip '-->'
-            return comment;
-        }
-
-        // Parse DOCTYPE
-        template<int Flags>
-        xml_node<Ch> *parse_doctype(Ch *&text)
-        {
-            // Remember value start
-            Ch *value = text;
-
-            // Skip to >
-            while (*text != Ch('>'))
-            {
-                // Determine character type
-                switch (*text)
-                {
-                
-                // If '[' encountered, scan for matching ending ']' using naive algorithm with depth
-                // This works for all W3C test files except for 2 most wicked
-                case Ch('['):
-                {
-                    ++text;     // Skip '['
-                    int depth = 1;
-                    while (depth > 0)
-                    {
-                        switch (*text)
-                        {
-                            case Ch('['): ++depth; break;
-                            case Ch(']'): --depth; break;
-                            case 0: RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                                                       default: break;
-                        }
-                        ++text;
-                    }
-                    break;
-                }
-                
-                // Error on end of text
-                case Ch('\0'):
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                
-                // Other character, skip it
-                default:
-                    ++text;
-
-                }
-            }
-            
-            // If DOCTYPE nodes enabled
-            if (Flags & parse_doctype_node)
-            {
-                // Create a new doctype node
-                xml_node<Ch> *doctype = this->allocate_node(node_doctype);
-                doctype->value(value, text - value);
-                
-                // Place zero terminator after value
-                if (!(Flags & parse_no_string_terminators))
-                    *text = Ch('\0');
-
-                text += 1;      // skip '>'
-                return doctype;
-            }
-            else
-            {
-                text += 1;      // skip '>'
-                return 0;
-            }
-
-        }
-
-        // Parse PI
-        template<int Flags>
-        xml_node<Ch> *parse_pi(Ch *&text)
-        {
-            // If creation of PI nodes is enabled
-            if (Flags & parse_pi_nodes)
-            {
-                // Create pi node
-                xml_node<Ch> *pi = this->allocate_node(node_pi);
-
-                // Extract PI target name
-                Ch *name = text;
-                skip<node_name_pred, Flags>(text);
-                if (text == name)
-                    RAPIDXML_PARSE_ERROR("expected PI target", text);
-                pi->name(name, text - name);
-                
-                // Skip whitespace between pi target and pi
-                skip<whitespace_pred, Flags>(text);
-
-                // Remember start of pi
-                Ch *value = text;
-                
-                // Skip to '?>'
-                while (text[0] != Ch('?') || text[1] != Ch('>'))
-                {
-                    if (*text == Ch('\0'))
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-
-                // Set pi value (verbatim, no entity expansion or whitespace normalization)
-                pi->value(value, text - value);     
-                
-                // Place zero terminator after name and value
-                if (!(Flags & parse_no_string_terminators))
-                {
-                    pi->name()[pi->name_size()] = Ch('\0');
-                    pi->value()[pi->value_size()] = Ch('\0');
-                }
-                
-                text += 2;                          // Skip '?>'
-                return pi;
-            }
-            else
-            {
-                // Skip to '?>'
-                while (text[0] != Ch('?') || text[1] != Ch('>'))
-                {
-                    if (*text == Ch('\0'))
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 2;    // Skip '?>'
-                return 0;
-            }
-        }
-
-        // Parse and append data
-        // Return character that ends data.
-        // This is necessary because this character might have been overwritten by a terminating 0
-        template<int Flags>
-        Ch parse_and_append_data(xml_node<Ch> *node, Ch *&text, Ch *contents_start)
-        {
-            // Backup to contents start if whitespace trimming is disabled
-            if (!(Flags & parse_trim_whitespace))
-                text = contents_start;     
-            
-            // Skip until end of data
-            Ch *value = text, *end;
-            if (Flags & parse_normalize_whitespace)
-                end = skip_and_expand_character_refs<text_pred, text_pure_with_ws_pred, Flags>(text);   
-            else
-                end = skip_and_expand_character_refs<text_pred, text_pure_no_ws_pred, Flags>(text);
-
-            // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after >
-            if (Flags & parse_trim_whitespace)
-            {
-                if (Flags & parse_normalize_whitespace)
-                {
-                    // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end
-                    if (*(end - 1) == Ch(' '))
-                        --end;
-                }
-                else
-                {
-                    // Backup until non-whitespace character is found
-                    while (whitespace_pred::test(*(end - 1)))
-                        --end;
-                }
-            }
-            
-            // If characters are still left between end and value (this test is only necessary if normalization is enabled)
-            // Create new data node
-            if (!(Flags & parse_no_data_nodes))
-            {
-                xml_node<Ch> *data = this->allocate_node(node_data);
-                data->value(value, end - value);
-                node->append_node(data);
-            }
-
-            // Add data to parent node if no data exists yet
-            if (!(Flags & parse_no_element_values)) 
-                if (*node->value() == Ch('\0'))
-                    node->value(value, end - value);
-
-            // Place zero terminator after value
-            if (!(Flags & parse_no_string_terminators))
-            {
-                Ch ch = *text;
-                *end = Ch('\0');
-                return ch;      // Return character that ends data; this is required because zero terminator overwritten it
-            }
-
-            // Return character that ends data
-            return *text;
-        }
-
-        // Parse CDATA
-        template<int Flags>
-        xml_node<Ch> *parse_cdata(Ch *&text)
-        {
-            // If CDATA is disabled
-            if (Flags & parse_no_data_nodes)
-            {
-                // Skip until end of cdata
-                while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
-                {
-                    if (!text[0])
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 3;      // Skip ]]>
-                return 0;       // Do not produce CDATA node
-            }
-
-            // Skip until end of cdata
-            Ch *value = text;
-            while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
-            {
-                if (!text[0])
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                ++text;
-            }
-
-            // Create new cdata node
-            xml_node<Ch> *cdata = this->allocate_node(node_cdata);
-            cdata->value(value, text - value);
-
-            // Place zero terminator after value
-            if (!(Flags & parse_no_string_terminators))
-                *text = Ch('\0');
-
-            text += 3;      // Skip ]]>
-            return cdata;
-        }
-        
-        // Parse element node
-        template<int Flags>
-        xml_node<Ch> *parse_element(Ch *&text)
-        {
-            // Create element node
-            xml_node<Ch> *element = this->allocate_node(node_element);
-
-            // Extract element name
-            Ch *name = text;
-            skip<node_name_pred, Flags>(text);
-            if (text == name)
-                RAPIDXML_PARSE_ERROR("expected element name", text);
-            element->name(name, text - name);
-            
-            // Skip whitespace between element name and attributes or >
-            skip<whitespace_pred, Flags>(text);
-
-            // Parse attributes, if any
-            parse_node_attributes<Flags>(text, element);
-
-            // Determine ending type
-            if (*text == Ch('>'))
-            {
-                ++text;
-                parse_node_contents<Flags>(text, element);
-            }
-            else if (*text == Ch('/'))
-            {
-                ++text;
-                if (*text != Ch('>'))
-                    RAPIDXML_PARSE_ERROR("expected >", text);
-                ++text;
-            }
-            else
-                RAPIDXML_PARSE_ERROR("expected >", text);
-
-            // Place zero terminator after name
-            if (!(Flags & parse_no_string_terminators))
-                element->name()[element->name_size()] = Ch('\0');
-
-            // Return parsed element
-            return element;
-        }
-
-        // Determine node type, and parse it
-        template<int Flags>
-        xml_node<Ch> *parse_node(Ch *&text)
-        {
-            // Parse proper node type
-            switch (text[0])
-            {
-
-            // <...
-            default: 
-                // Parse and append element node
-                return parse_element<Flags>(text);
-
-            // <?...
-            case Ch('?'): 
-                ++text;     // Skip ?
-                if ((text[0] == Ch('x') || text[0] == Ch('X')) &&
-                    (text[1] == Ch('m') || text[1] == Ch('M')) && 
-                    (text[2] == Ch('l') || text[2] == Ch('L')) &&
-                    whitespace_pred::test(text[3]))
-                {
-                    // '<?xml ' - xml declaration
-                    text += 4;      // Skip 'xml '
-                    return parse_xml_declaration<Flags>(text);
-                }
-                else
-                {
-                    // Parse PI
-                    return parse_pi<Flags>(text);
-                }
-            
-            // <!...
-            case Ch('!'): 
-
-                // Parse proper subset of <! node
-                switch (text[1])    
-                {
-                
-                // <!-
-                case Ch('-'):
-                    if (text[2] == Ch('-'))
-                    {
-                        // '<!--' - xml comment
-                        text += 3;     // Skip '!--'
-                        return parse_comment<Flags>(text);
-                    }
-                    break;
-
-                // <![
-                case Ch('['):
-                    if (text[2] == Ch('C') && text[3] == Ch('D') && text[4] == Ch('A') && 
-                        text[5] == Ch('T') && text[6] == Ch('A') && text[7] == Ch('['))
-                    {
-                        // '<![CDATA[' - cdata
-                        text += 8;     // Skip '![CDATA['
-                        return parse_cdata<Flags>(text);
-                    }
-                    break;
-
-                // <!D
-                case Ch('D'):
-                    if (text[2] == Ch('O') && text[3] == Ch('C') && text[4] == Ch('T') && 
-                        text[5] == Ch('Y') && text[6] == Ch('P') && text[7] == Ch('E') && 
-                        whitespace_pred::test(text[8]))
-                    {
-                        // '<!DOCTYPE ' - doctype
-                        text += 9;      // skip '!DOCTYPE '
-                        return parse_doctype<Flags>(text);
-                    }
-                                       break;
-                               
-                               default:
-                                       break;
-
-                }   // switch
-
-                // Attempt to skip other, unrecognized node types starting with <!
-                ++text;     // Skip !
-                while (*text != Ch('>'))
-                {
-                    if (*text == 0)
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                ++text;     // Skip '>'
-                return 0;   // No node recognized
-
-            }
-        }
-
-        // Parse contents of the node - children, data etc.
-        template<int Flags>
-        void parse_node_contents(Ch *&text, xml_node<Ch> *node)
-        {
-            // For all children and text
-            while (1)
-            {
-                // Skip whitespace between > and node contents
-                Ch *contents_start = text;      // Store start of node contents before whitespace is skipped
-                skip<whitespace_pred, Flags>(text);
-                Ch next_char = *text;
-
-            // After data nodes, instead of continuing the loop, control jumps here.
-            // This is because zero termination inside parse_and_append_data() function
-            // would wreak havoc with the above code.
-            // Also, skipping whitespace after data nodes is unnecessary.
-            after_data_node:    
-                
-                // Determine what comes next: node closing, child node, data node, or 0?
-                switch (next_char)
-                {
-                
-                // Node closing or child node
-                case Ch('<'):
-                    if (text[1] == Ch('/'))
-                    {
-                        // Node closing
-                        text += 2;      // Skip '</'
-                        if (Flags & parse_validate_closing_tags)
-                        {
-                            // Skip and validate closing tag name
-                            Ch *closing_name = text;
-                            skip<node_name_pred, Flags>(text);
-                            if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true))
-                                RAPIDXML_PARSE_ERROR("invalid closing tag name", text);
-                        }
-                        else
-                        {
-                            // No validation, just skip name
-                            skip<node_name_pred, Flags>(text);
-                        }
-                        // Skip remaining whitespace after node name
-                        skip<whitespace_pred, Flags>(text);
-                        if (*text != Ch('>'))
-                            RAPIDXML_PARSE_ERROR("expected >", text);
-                        ++text;     // Skip '>'
-                        return;     // Node closed, finished parsing contents
-                    }
-                    else
-                    {
-                        // Child node
-                        ++text;     // Skip '<'
-                        if (xml_node<Ch> *child = parse_node<Flags>(text))
-                            node->append_node(child);
-                    }
-                    break;
-
-                // End of data - error
-                case Ch('\0'):
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-
-                // Data node
-                default:
-                    next_char = parse_and_append_data<Flags>(node, text, contents_start);
-                    goto after_data_node;   // Bypass regular processing after data nodes
-
-                }
-            }
-        }
-        
-        // Parse XML attributes of the node
-        template<int Flags>
-        void parse_node_attributes(Ch *&text, xml_node<Ch> *node)
-        {
-            // For all attributes 
-            while (attribute_name_pred::test(*text))
-            {
-                // Extract attribute name
-                Ch *name = text;
-                ++text;     // Skip first character of attribute name
-                skip<attribute_name_pred, Flags>(text);
-                if (text == name)
-                    RAPIDXML_PARSE_ERROR("expected attribute name", name);
-
-                // Create new attribute
-                xml_attribute<Ch> *attribute = this->allocate_attribute();
-                attribute->name(name, text - name);
-                node->append_attribute(attribute);
-
-                // Skip whitespace after attribute name
-                skip<whitespace_pred, Flags>(text);
-
-                // Skip =
-                if (*text != Ch('='))
-                    RAPIDXML_PARSE_ERROR("expected =", text);
-                ++text;
-
-                // Add terminating zero after name
-                if (!(Flags & parse_no_string_terminators))
-                    attribute->name()[attribute->name_size()] = 0;
-
-                // Skip whitespace after =
-                skip<whitespace_pred, Flags>(text);
-
-                // Skip quote and remember if it was ' or "
-                Ch quote = *text;
-                if (quote != Ch('\'') && quote != Ch('"'))
-                    RAPIDXML_PARSE_ERROR("expected ' or \"", text);
-                ++text;
-
-                // Extract attribute value and expand char refs in it
-                Ch *value = text, *end;
-                const int AttFlags = Flags & ~parse_normalize_whitespace;   // No whitespace normalization in attributes
-                if (quote == Ch('\''))
-                    end = skip_and_expand_character_refs<attribute_value_pred<Ch('\'')>, attribute_value_pure_pred<Ch('\'')>, AttFlags>(text);
-                else
-                    end = skip_and_expand_character_refs<attribute_value_pred<Ch('"')>, attribute_value_pure_pred<Ch('"')>, AttFlags>(text);
-                
-                // Set attribute value
-                attribute->value(value, end - value);
-                
-                // Make sure that end quote is present
-                if (*text != quote)
-                    RAPIDXML_PARSE_ERROR("expected ' or \"", text);
-                ++text;     // Skip quote
-
-                // Add terminating zero after value
-                if (!(Flags & parse_no_string_terminators))
-                    attribute->value()[attribute->value_size()] = 0;
-
-                // Skip whitespace after attribute value
-                skip<whitespace_pred, Flags>(text);
-            }
-        }
-
-    };
-
-    //! \cond internal
-    namespace internal
-    {
-
-        // Whitespace (space \n \r \t)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_whitespace[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  0,  1,  0,  0,  // 0
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 1
-             1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 2
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 3
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 4
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 5
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 6
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 7
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 8
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 9
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // A
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // B
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // C
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // D
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // E
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0   // F
-        };
-
-        // Node name (anything but space \n \r \t / > ? \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_node_name[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Text (i.e. PCDATA) (anything but < \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_text[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled 
-        // (anything but < \0 &)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_text_pure_no_ws[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled
-        // (anything but < \0 & space \n \r \t)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_text_pure_with_ws[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             0,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute name (anything but space \n \r \t / < > = ? ! \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_name[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with single quote (anything but ' \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with single quote that does not require processing (anything but ' \0 &)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1_pure[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with double quote (anything but " \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with double quote that does not require processing (anything but " \0 &)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2_pure[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  0,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Digits (dec and hex, 255 denotes end of numeric character reference)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_digits[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 0
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 1
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 2
-             0,  1,  2,  3,  4,  5,  6,  7,  8,  9,255,255,255,255,255,255,  // 3
-           255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255,  // 4
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 5
-           255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255,  // 6
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 7
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 8
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 9
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // A
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // B
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // C
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // D
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // E
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255   // F
-        };
-    
-        // Upper case conversion
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_upcase[256] = 
-        {
-          // 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  A   B   C   D   E   F
-           0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15,   // 0
-           16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,   // 1
-           32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,   // 2
-           48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,   // 3
-           64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 4
-           80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,   // 5
-           96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 6
-           80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127,  // 7
-           128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,  // 8
-           144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,  // 9
-           160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,  // A
-           176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,  // B
-           192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,  // C
-           208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,  // D
-           224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,  // E
-           240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255   // F
-        };
-    }
-    //! \endcond
-
-}
-
-// Undefine internal macros
-#undef RAPIDXML_PARSE_ERROR
-
-// On MSVC, restore warnings state
-#ifdef _MSC_VER
-    #pragma warning(pop)
-#endif
-
-#endif
diff --git a/service/protocol-plugin/lib/rapidxml/rapidxml_iterators.hpp b/service/protocol-plugin/lib/rapidxml/rapidxml_iterators.hpp
deleted file mode 100644 (file)
index 52ebc29..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-#ifndef RAPIDXML_ITERATORS_HPP_INCLUDED
-#define RAPIDXML_ITERATORS_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml_iterators.hpp This file contains rapidxml iterators
-
-#include "rapidxml.hpp"
-
-namespace rapidxml
-{
-
-    //! Iterator of child nodes of xml_node
-    template<class Ch>
-    class node_iterator
-    {
-    
-    public:
-
-        typedef typename xml_node<Ch> value_type;
-        typedef typename xml_node<Ch> &reference;
-        typedef typename xml_node<Ch> *pointer;
-        typedef std::ptrdiff_t difference_type;
-        typedef std::bidirectional_iterator_tag iterator_category;
-        
-        node_iterator()
-            : m_node(0)
-        {
-        }
-
-        node_iterator(xml_node<Ch> *node)
-            : m_node(node->first_node())
-        {
-        }
-        
-        reference operator *() const
-        {
-            assert(m_node);
-            return *m_node;
-        }
-
-        pointer operator->() const
-        {
-            assert(m_node);
-            return m_node;
-        }
-
-        node_iterator& operator++()
-        {
-            assert(m_node);
-            m_node = m_node->next_sibling();
-            return *this;
-        }
-
-        node_iterator operator++(int)
-        {
-            node_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        node_iterator& operator--()
-        {
-            assert(m_node && m_node->previous_sibling());
-            m_node = m_node->previous_sibling();
-            return *this;
-        }
-
-        node_iterator operator--(int)
-        {
-            node_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        bool operator ==(const node_iterator<Ch> &rhs)
-        {
-            return m_node == rhs.m_node;
-        }
-
-        bool operator !=(const node_iterator<Ch> &rhs)
-        {
-            return m_node != rhs.m_node;
-        }
-
-    private:
-
-        xml_node<Ch> *m_node;
-
-    };
-
-    //! Iterator of child attributes of xml_node
-    template<class Ch>
-    class attribute_iterator
-    {
-    
-    public:
-
-        typedef typename xml_attribute<Ch> value_type;
-        typedef typename xml_attribute<Ch> &reference;
-        typedef typename xml_attribute<Ch> *pointer;
-        typedef std::ptrdiff_t difference_type;
-        typedef std::bidirectional_iterator_tag iterator_category;
-        
-        attribute_iterator()
-            : m_attribute(0)
-        {
-        }
-
-        attribute_iterator(xml_node<Ch> *node)
-            : m_attribute(node->first_attribute())
-        {
-        }
-        
-        reference operator *() const
-        {
-            assert(m_attribute);
-            return *m_attribute;
-        }
-
-        pointer operator->() const
-        {
-            assert(m_attribute);
-            return m_attribute;
-        }
-
-        attribute_iterator& operator++()
-        {
-            assert(m_attribute);
-            m_attribute = m_attribute->next_attribute();
-            return *this;
-        }
-
-        attribute_iterator operator++(int)
-        {
-            attribute_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        attribute_iterator& operator--()
-        {
-            assert(m_attribute && m_attribute->previous_attribute());
-            m_attribute = m_attribute->previous_attribute();
-            return *this;
-        }
-
-        attribute_iterator operator--(int)
-        {
-            attribute_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        bool operator ==(const attribute_iterator<Ch> &rhs)
-        {
-            return m_attribute == rhs.m_attribute;
-        }
-
-        bool operator !=(const attribute_iterator<Ch> &rhs)
-        {
-            return m_attribute != rhs.m_attribute;
-        }
-
-    private:
-
-        xml_attribute<Ch> *m_attribute;
-
-    };
-
-}
-
-#endif
diff --git a/service/protocol-plugin/lib/rapidxml/rapidxml_print.hpp b/service/protocol-plugin/lib/rapidxml/rapidxml_print.hpp
deleted file mode 100644 (file)
index f929b3c..0000000
+++ /dev/null
@@ -1,422 +0,0 @@
-#ifndef RAPIDXML_PRINT_HPP_INCLUDED
-#define RAPIDXML_PRINT_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml_print.hpp This file contains rapidxml printer implementation
-
-#include "rapidxml.hpp"
-
-// Only include streams if not disabled
-#ifndef RAPIDXML_NO_STREAMS
-    #include <ostream>
-    #include <iterator>
-#endif
-
-namespace rapidxml
-{
-
-    ///////////////////////////////////////////////////////////////////////
-    // Printing flags
-
-    const int print_no_indenting = 0x1;   //!< Printer flag instructing the printer to suppress indenting of XML. See print() function.
-
-    ///////////////////////////////////////////////////////////////////////
-    // Internal
-
-    //! \cond internal
-    namespace internal
-    {
-        
-        ///////////////////////////////////////////////////////////////////////////
-        // Internal character operations
-    
-        // Copy characters from given range to given output iterator
-        template<class OutIt, class Ch>
-        inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out)
-        {
-            while (begin != end)
-                *out++ = *begin++;
-            return out;
-        }
-        
-        // Copy characters from given range to given output iterator and expand
-        // characters into references (&lt; &gt; &apos; &quot; &amp;)
-        template<class OutIt, class Ch>
-        inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out)
-        {
-            while (begin != end)
-            {
-                if (*begin == noexpand)
-                {
-                    *out++ = *begin;    // No expansion, copy character
-                }
-                else
-                {
-                    switch (*begin)
-                    {
-                    case Ch('<'):
-                        *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';');
-                        break;
-                    case Ch('>'): 
-                        *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';');
-                        break;
-                    case Ch('\''): 
-                        *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';');
-                        break;
-                    case Ch('"'): 
-                        *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';');
-                        break;
-                    case Ch('&'): 
-                        *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); 
-                        break;
-                    default:
-                        *out++ = *begin;    // No expansion, copy character
-                    }
-                }
-                ++begin;    // Step to next character
-            }
-            return out;
-        }
-
-        // Fill given output iterator with repetitions of the same character
-        template<class OutIt, class Ch>
-        inline OutIt fill_chars(OutIt out, int n, Ch ch)
-        {
-            for (int i = 0; i < n; ++i)
-                *out++ = ch;
-            return out;
-        }
-
-        // Find character
-        template<class Ch, Ch ch>
-        inline bool find_char(const Ch *begin, const Ch *end)
-        {
-            while (begin != end)
-                if (*begin++ == ch)
-                    return true;
-            return false;
-        }
-
-        template<class OutIt, class Ch>
-        inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);
-
-        // Print children of the node                               
-        template<class OutIt, class Ch>
-        inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling())
-                out = print_node(out, child, flags, indent);
-            return out;
-        }
-
-        // Print attributes of the node
-        template<class OutIt, class Ch>
-        inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags)
-        {
-            for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute())
-            {
-                if (attribute->name() && attribute->value())
-                {
-                    // Print attribute name
-                    *out = Ch(' '), ++out;
-                    out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out);
-                    *out = Ch('='), ++out;
-                    // Print attribute value using appropriate quote type
-                    if (find_char<Ch, Ch('"')>(attribute->value(), attribute->value() + attribute->value_size()))
-                    {
-                        *out = Ch('\''), ++out;
-                        out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out);
-                        *out = Ch('\''), ++out;
-                    }
-                    else
-                    {
-                        *out = Ch('"'), ++out;
-                        out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out);
-                        *out = Ch('"'), ++out;
-                    }
-                }
-            }
-            return out;
-        }
-
-        // Print data node
-        template<class OutIt, class Ch>
-        inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_data);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
-            return out;
-        }
-
-        // Print data node
-        template<class OutIt, class Ch>
-        inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_cdata);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'); ++out;
-            *out = Ch('!'); ++out;
-            *out = Ch('['); ++out;
-            *out = Ch('C'); ++out;
-            *out = Ch('D'); ++out;
-            *out = Ch('A'); ++out;
-            *out = Ch('T'); ++out;
-            *out = Ch('A'); ++out;
-            *out = Ch('['); ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch(']'); ++out;
-            *out = Ch(']'); ++out;
-            *out = Ch('>'); ++out;
-            return out;
-        }
-
-        // Print element node
-        template<class OutIt, class Ch>
-        inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_element);
-
-            // Print element name and attributes, if any
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            out = copy_chars(node->name(), node->name() + node->name_size(), out);
-            out = print_attributes(out, node, flags);
-            
-            // If node is childless
-            if (node->value_size() == 0 && !node->first_node())
-            {
-                // Print childless node tag ending
-                *out = Ch('/'), ++out;
-                *out = Ch('>'), ++out;
-            }
-            else
-            {
-                // Print normal node tag ending
-                *out = Ch('>'), ++out;
-
-                // Test if node contains a single data node only (and no other nodes)
-                xml_node<Ch> *child = node->first_node();
-                if (!child)
-                {
-                    // If node has no children, only print its value without indenting
-                    out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
-                }
-                else if (child->next_sibling() == 0 && child->type() == node_data)
-                {
-                    // If node has a sole data child, only print its value without indenting
-                    out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out);
-                }
-                else
-                {
-                    // Print all children with full indenting
-                    if (!(flags & print_no_indenting))
-                        *out = Ch('\n'), ++out;
-                    out = print_children(out, node, flags, indent + 1);
-                    if (!(flags & print_no_indenting))
-                        out = fill_chars(out, indent, Ch('\t'));
-                }
-
-                // Print node end
-                *out = Ch('<'), ++out;
-                *out = Ch('/'), ++out;
-                out = copy_chars(node->name(), node->name() + node->name_size(), out);
-                *out = Ch('>'), ++out;
-            }
-            return out;
-        }
-
-        // Print declaration node
-        template<class OutIt, class Ch>
-        inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            // Print declaration start
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('?'), ++out;
-            *out = Ch('x'), ++out;
-            *out = Ch('m'), ++out;
-            *out = Ch('l'), ++out;
-
-            // Print attributes
-            out = print_attributes(out, node, flags);
-            
-            // Print declaration end
-            *out = Ch('?'), ++out;
-            *out = Ch('>'), ++out;
-            
-            return out;
-        }
-
-        // Print comment node
-        template<class OutIt, class Ch>
-        inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_comment);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('!'), ++out;
-            *out = Ch('-'), ++out;
-            *out = Ch('-'), ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch('-'), ++out;
-            *out = Ch('-'), ++out;
-            *out = Ch('>'), ++out;
-            return out;
-        }
-
-        // Print doctype node
-        template<class OutIt, class Ch>
-        inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_doctype);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('!'), ++out;
-            *out = Ch('D'), ++out;
-            *out = Ch('O'), ++out;
-            *out = Ch('C'), ++out;
-            *out = Ch('T'), ++out;
-            *out = Ch('Y'), ++out;
-            *out = Ch('P'), ++out;
-            *out = Ch('E'), ++out;
-            *out = Ch(' '), ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch('>'), ++out;
-            return out;
-        }
-
-        // Print pi node
-        template<class OutIt, class Ch>
-        inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_pi);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('?'), ++out;
-            out = copy_chars(node->name(), node->name() + node->name_size(), out);
-            *out = Ch(' '), ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch('?'), ++out;
-            *out = Ch('>'), ++out;
-            return out;
-        }
-        ///////////////////////////////////////////////////////////////////////////
-                // Internal printing operations
-
-                // Print node
-                template<class OutIt, class Ch>
-                inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-                {
-                    // Print proper node type
-                    switch (node->type())
-                    {
-
-                    // Document
-                    case node_document:
-                        out = print_children(out, node, flags, indent);
-                        break;
-
-                    // Element
-                    case node_element:
-                        out = print_element_node(out, node, flags, indent);
-                        break;
-
-                    // Data
-                    case node_data:
-                        out = print_data_node(out, node, flags, indent);
-                        break;
-
-                    // CDATA
-                    case node_cdata:
-                        out = print_cdata_node(out, node, flags, indent);
-                        break;
-
-                    // Declaration
-                    case node_declaration:
-                        out = print_declaration_node(out, node, flags, indent);
-                        break;
-
-                    // Comment
-                    case node_comment:
-                        out = print_comment_node(out, node, flags, indent);
-                        break;
-
-                    // Doctype
-                    case node_doctype:
-                        out = print_doctype_node(out, node, flags, indent);
-                        break;
-
-                    // Pi
-                    case node_pi:
-                        out = print_pi_node(out, node, flags, indent);
-                        break;
-
-                        // Unknown
-                    default:
-                        assert(0);
-                        break;
-                    }
-
-                    // If indenting not disabled, add line break after node
-                    if (!(flags & print_no_indenting))
-                        *out = Ch('\n'), ++out;
-
-                    // Return modified iterator
-                    return out;
-                }
-    }
-    //! \endcond
-
-    ///////////////////////////////////////////////////////////////////////////
-    // Printing
-
-    //! Prints XML to given output iterator.
-    //! \param out Output iterator to print to.
-    //! \param node Node to be printed. Pass xml_document to print entire document.
-    //! \param flags Flags controlling how XML is printed.
-    //! \return Output iterator pointing to position immediately after last character of printed text.
-    template<class OutIt, class Ch> 
-    inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0)
-    {
-        return internal::print_node(out, &node, flags, 0);
-    }
-
-#ifndef RAPIDXML_NO_STREAMS
-
-    //! Prints XML to given output stream.
-    //! \param out Output stream to print to.
-    //! \param node Node to be printed. Pass xml_document to print entire document.
-    //! \param flags Flags controlling how XML is printed.
-    //! \return Output stream.
-    template<class Ch> 
-    inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node, int flags = 0)
-    {
-        print(std::ostream_iterator<Ch>(out), node, flags);
-        return out;
-    }
-
-    //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.
-    //! \param out Output stream to print to.
-    //! \param node Node to be printed.
-    //! \return Output stream.
-    template<class Ch> 
-    inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node)
-    {
-        return print(out, node);
-    }
-
-#endif
-
-}
-
-#endif
diff --git a/service/protocol-plugin/lib/rapidxml/rapidxml_utils.hpp b/service/protocol-plugin/lib/rapidxml/rapidxml_utils.hpp
deleted file mode 100644 (file)
index 37c2953..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-#ifndef RAPIDXML_UTILS_HPP_INCLUDED
-#define RAPIDXML_UTILS_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml_utils.hpp This file contains high-level rapidxml utilities that can be useful
-//! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective.
-
-#include "rapidxml.hpp"
-#include <vector>
-#include <string>
-#include <fstream>
-#include <stdexcept>
-
-namespace rapidxml
-{
-
-    //! Represents data loaded from a file
-    template<class Ch = char>
-    class file
-    {
-        
-    public:
-        
-        //! Loads file into the memory. Data will be automatically destroyed by the destructor.
-        //! \param filename Filename to load.
-        file(const char *filename)
-        {
-            using namespace std;
-
-            // Open stream
-            basic_ifstream<Ch> stream(filename, ios::binary);
-            if (!stream)
-                throw runtime_error(string("cannot open file ") + filename);
-            stream.unsetf(ios::skipws);
-            
-            // Determine stream size
-            stream.seekg(0, ios::end);
-            size_t size = stream.tellg();
-            stream.seekg(0);   
-            
-            // Load data and add terminating 0
-            m_data.resize(size + 1);
-            stream.read(&m_data.front(), static_cast<streamsize>(size));
-            m_data[size] = 0;
-        }
-
-        //! Loads file into the memory. Data will be automatically destroyed by the destructor
-        //! \param stream Stream to load from
-        file(std::basic_istream<Ch> &stream)
-        {
-            using namespace std;
-
-            // Load data and add terminating 0
-            stream.unsetf(ios::skipws);
-            m_data.assign(istreambuf_iterator<Ch>(stream), istreambuf_iterator<Ch>());
-            if (stream.fail() || stream.bad())
-                throw runtime_error("error reading stream");
-            m_data.push_back(0);
-        }
-        
-        //! Gets file data.
-        //! \return Pointer to data of file.
-        Ch *data()
-        {
-            return &m_data.front();
-        }
-
-        //! Gets file data.
-        //! \return Pointer to data of file.
-        const Ch *data() const
-        {
-            return &m_data.front();
-        }
-
-        //! Gets file data size.
-        //! \return Size of file data, in characters.
-        std::size_t size() const
-        {
-            return m_data.size();
-        }
-
-    private:
-
-        std::vector<Ch> m_data;   // File data
-
-    };
-
-    //! Counts children of node. Time complexity is O(n).
-    //! \return Number of children of node
-    template<class Ch>
-    inline std::size_t count_children(xml_node<Ch> *node)
-    {
-        xml_node<Ch> *child = node->first_node();
-        std::size_t count = 0;
-        while (child)
-        {
-            ++count;
-            child = child->next_sibling();
-        }
-        return count;
-    }
-
-    //! Counts attributes of node. Time complexity is O(n).
-    //! \return Number of attributes of node
-    template<class Ch>
-    inline std::size_t count_attributes(xml_node<Ch> *node)
-    {
-        xml_attribute<Ch> *attr = node->first_attribute();
-        std::size_t count = 0;
-        while (attr)
-        {
-            ++count;
-            attr = attr->next_attribute();
-        }
-        return count;
-    }
-
-}
-
-#endif
index e15658f..681ab10 100644 (file)
@@ -1,7 +1,7 @@
 ##
 # plugin-manager project build script
 ##
-
+import os
 Import('env')
 
 # Add third party libraries
@@ -16,16 +16,16 @@ target_os = env.get('TARGET_OS')
 plugin_manager_env.AppendUnique(CPPPATH = [
                '../lib/cpluff/libcpluff',
                'src',
-               '../lib/rapidxml'
+               env.get('SRC_DIR')+'/extlibs/rapidxml'
                ])
 
 if target_os not in ['windows', 'winrt']:
-       plugin_manager_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall',
+       plugin_manager_env.AppendUnique(CXXFLAGS = ['-Wall','-std=c++0x',
                '-fpermissive', '-Wsign-compare'])
 
 if target_os == 'android':
-       plugin_manager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       plugin_manager_env.AppendUnique(LIBS = ['boost_thread-gcc-mt-1_49', 'gnustl_static'])
+       plugin_manager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions', '-DANDROID'])
+       plugin_manager_env.AppendUnique(LIBS = ['boost_thread', 'boost_system', 'gnustl_shared', 'log'])
 
 plugin_manager_env.AppendUnique(CPPDEFINES = ['CP_C_API=CP_EXPORT',
                                        'CP_HOST=\"\\"'+env.get('TARGET_OS')+'\\"\"',
@@ -48,14 +48,20 @@ ppm = plugin_manager_env.StaticLibrary('ppm', ppm_src)
 
 pmimpl_src = [
                'src/CpluffAdapter.cpp',
-               'src/FelixAdapter.cpp',
                'src/Plugin.cpp',
                'src/PluginManagerImpl.cpp',
                'src/Config.cpp']
 
+if target_os == 'android':
+       pmimpl_src += ['src/FelixAdapter.cpp']
+
 pmimpl_env = plugin_manager_env.Clone()
 pmimpl_env.PrependUnique(CCFLAGS = ['-fPIC'])
 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')
+
+# Build JNI library for android
+if env.get('TARGET_OS') == 'android':
+        SConscript('src/Android/jni/SConscript')
\ No newline at end of file
diff --git a/service/protocol-plugin/plugin-manager/build/linux/Makefile b/service/protocol-plugin/plugin-manager/build/linux/Makefile
deleted file mode 100644 (file)
index 453451f..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-CXX = g++
-
-CXX_FLAGS = -std=c++0x -Wall
-LIB = ../../../lib
-CPLUFF_DIR = $(LIB)/cpluff/libcpluff
-
-SRC = ../../src/
-
-CXX_INC    = -I. -I$(CPLUFF_DIR)
-CXX_INC += -I$(LIB)/rapidxml 
-
-LINK_LIB = -lboost_system -ldl -lexpat -lboost_thread 
-CXX_LIBS = $(CPLUFF_DIR)/.libs/libcpluff.a 
-
-PHONY :libppm.a libpmimpl.so
-
-all: .PHONY
-       
-libppm.a:PluginManager.o  Plugin.o 
-       ar -cvr libppm.a  PluginManager.o  Plugin.o 
-
-PluginManager.o : $(SRC)PluginManager.cpp
-       $(CXX) $(CXX_INC) -c $(CXX_FLAGS) -Wsign-compare $(SRC)PluginManager.cpp 
-
-
-libpmimpl.so:PluginManagerImpl.o Plugin.o CpluffAdapter.o FelixAdapter.o Config.o $(CPLUFF_DIR)/.libs/libcpluff.a 
-       $(CXX) -shared -o libpmimpl.so PluginManagerImpl.o Plugin.o CpluffAdapter.o FelixAdapter.o Config.o $(CXX_LIBS) $(LINK_LIB)  
-
-PluginManagerImpl.o : $(SRC)PluginManagerImpl.cpp
-       $(CXX) $(CXX_INC)  -fPIC  -c $(CXX_FLAGS) -Wsign-compare $(SRC)PluginManagerImpl.cpp
-
-Plugin.o : $(SRC)Plugin.cpp
-       $(CXX) $(CXX_INC)  -fPIC  -c $(SRC)Plugin.cpp
-
-Config.o : $(SRC)Config.cpp
-       $(CXX) $(CXX_INC)  -fPIC  -c $(SRC)Config.cpp
-
-CpluffAdapter.o  : $(SRC)CpluffAdapter.cpp
-       $(CXX) $(CXX_INC) -c $(CXX_FLAGS) -Wsign-compare $(SRC)CpluffAdapter.cpp
-
-FelixAdapter.o : $(SRC)FelixAdapter.cpp
-       $(CXX) $(CXX_INC) -c $(CXX_FLAGS) -Wsign-compare $(SRC)FelixAdapter.cpp
-
-clean: 
-       rm -rf *.o
-       rm -rf *.a
-       rm -rf *.so
diff --git a/service/protocol-plugin/plugin-manager/src/Android/.classpath b/service/protocol-plugin/plugin-manager/src/Android/.classpath
new file mode 100644 (file)
index 0000000..6eaa154
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="src" path="gen"/>
+       <classpathentry exported="true" kind="lib" path="/home/minji/JUDO/out/felix.jar"/>
+       <classpathentry exported="true" kind="lib" path="/home/minji/JUDO/150520/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
+       <classpathentry kind="output" path="bin/classes"/>
+</classpath>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/.project b/service/protocol-plugin/plugin-manager/src/Android/.project
new file mode 100644 (file)
index 0000000..3ba6a91
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>MainActivity</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+       </natures>
+</projectDescription>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/AndroidManifest.xml b/service/protocol-plugin/plugin-manager/src/Android/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..f642453
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.iotivity.service.ppm"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+       <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+    <uses-permission android:name="android.permission.GET_TASKS"/>
+    <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>
+    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
+    <uses-permission android:name="android.permission.CALL_PHONE" />
+    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
+    <uses-permission android:name="android.permission.READ_CONTACTS"/>
+    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
+    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
+    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
+    <uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY"/>
+    
+    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" />
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme"
+        android:largeHeap="true" >
+        <activity
+            android:name="org.iotivity.service.ppm.MainActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/assets/files/pluginmanager.xml b/service/protocol-plugin/plugin-manager/src/Android/assets/files/pluginmanager.xml
new file mode 100644 (file)
index 0000000..f833a47
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<pluginManager>
+    <pluginInfo        
+        pluginPath="/data/data/org.iotivity.service.ppm/files"
+        maxMEM="64M"
+        maxPlugin=""
+        version="1.0"
+        name="pluginmanager">
+    </pluginInfo>
+    <specailpluginInfo>
+    </specailpluginInfo>
+</pluginManager>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/ic_launcher-web.png b/service/protocol-plugin/plugin-manager/src/Android/ic_launcher-web.png
new file mode 100644 (file)
index 0000000..a18cbb4
Binary files /dev/null and b/service/protocol-plugin/plugin-manager/src/Android/ic_launcher-web.png differ
diff --git a/service/protocol-plugin/plugin-manager/src/Android/jni/Android.mk b/service/protocol-plugin/plugin-manager/src/Android/jni/Android.mk
new file mode 100644 (file)
index 0000000..9bf9102
--- /dev/null
@@ -0,0 +1,47 @@
+LOCAL_PATH:=$(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE   := libexpat
+LOCAL_SRC_FILES        := ../../../../../../dep/android/armeabi/usr/lib/libexpat.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE   := libboost_thread
+LOCAL_SRC_FILES        := ../../../../../../dep/android/armeabi/usr/lib/libboost_thread.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE   := libboost_system
+LOCAL_SRC_FILES        := ../../../../../../dep/android/armeabi/usr/lib/libboost_system.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE   := libcpluff
+LOCAL_SRC_FILES        := ../../../../../../out/android/armeabi/release/libcpluff.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE   := libpmimpl
+LOCAL_SRC_FILES        := ../../../../../../out/android/armeabi/release/libpmimpl.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+
+include $(CLEAR_VARS)
+LOCAL_DEFAULT_CPP_EXTENSION    := cpp
+LOCAL_MODULE                           := PluginManager
+LOCAL_SRC_FILES                                := PluginManager.cpp
+LOCAL_CPPFLAGS                                 := -std=c++0x -frtti -fexceptions
+LOCAL_LDLIBS                           := -llog -ldl -lz
+
+LOCAL_STATIC_LIBRARIES         := libcpluff
+LOCAL_STATIC_LIBRARIES         += libpmimpl
+LOCAL_STATIC_LIBRARIES         += libboost_thread
+LOCAL_STATIC_LIBRARIES         += libboost_system
+LOCAL_STATIC_LIBRARIES         += libexpat
+
+LOCAL_C_INCLUDES                       := ../../../../../../extlibs/boost/boost_1_58_0
+LOCAL_C_INCLUDES                       += ../../../../lib/cpluff/libcpluff
+LOCAL_C_INCLUDES                       += ../../../src
+LOCAL_C_INCLUDES                       += ../../../../../../extlibs/rapidxml
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/service/protocol-plugin/plugin-manager/src/Android/jni/Application.mk b/service/protocol-plugin/plugin-manager/src/Android/jni/Application.mk
new file mode 100644 (file)
index 0000000..17f3064
--- /dev/null
@@ -0,0 +1,2 @@
+NDK_TOOLCHAIN_VERSION := 4.9
+APP_STL := gnustl_shared
diff --git a/service/protocol-plugin/plugin-manager/src/Android/jni/PluginManager.cpp b/service/protocol-plugin/plugin-manager/src/Android/jni/PluginManager.cpp
new file mode 100644 (file)
index 0000000..0279730
--- /dev/null
@@ -0,0 +1,162 @@
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file PluginManager.cpp
+
+/// @brief
+
+#include <stdio.h>
+#include <string>
+
+#include "PluginManager.h"
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    startPlugins
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)I
+ */
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ppm_PluginManager_jniStartPlugins(JNIEnv *env, jobject jobj,
+        jstring jkey, jstring jvalue)
+{
+    LOGD("jniStartPlugins() Called.");
+
+    if((!jkey)||(!jvalue))
+        return 0;
+    std::string ckey = env->GetStringUTFChars(jkey, 0);
+    std::string cvalue = env->GetStringUTFChars(jvalue, 0);
+
+    return (jint)pluginManagerImpl->startPlugins(ckey, cvalue);
+}
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    stopPlugins
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)I
+ */
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ppm_PluginManager_jniStopPlugins(JNIEnv *env, jobject jobj,
+        jstring jkey, jstring jvalue)
+{
+    LOGD("jniStopPlugins() Called.");
+
+    if((!jkey)||(!jvalue))
+        return 0;
+    std::string ckey = env->GetStringUTFChars(jkey, 0);
+    std::string cvalue = env->GetStringUTFChars(jvalue, 0);
+
+    return (jint)pluginManagerImpl->stopPlugins(ckey, cvalue);
+}
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    jniRescanPlugin
+ * Signature: (V)I
+ */
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ppm_PluginManager_jniRescanPlugin(JNIEnv *env, jobject jobj)
+{
+    LOGD("jniRescanPlugin() Called.");
+
+    return (jint)pluginManagerImpl->rescanPlugin();
+}
+
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    getPlugins
+ * Signature: (V)[Lorg/iotivity/service/ppm/Plugin;
+ */
+JNIEXPORT jobjectArray JNICALL Java_org_iotivity_service_ppm_PluginManager_jniGetPlugins(JNIEnv *env,
+        jobject jobj)
+{
+    LOGD("jniGetPlugins() Called.");
+
+    std::vector<OIC::Plugin> result = pluginManagerImpl->getAllPlugins();
+
+    jclass cls = env->FindClass("org/iotivity/service/ppm/Plugin");
+    jmethodID mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
+    jobjectArray resultArray = (jobjectArray)env->NewObjectArray(result.size(), cls, NULL);
+
+    for (int i = 0; i < result.size(); i++)
+    {
+        jstring jname = env->NewStringUTF(result[i].getName().c_str());
+        LOGD("jniGetPlugins() [%d] Name: %s", i + 1, result[i].getName().c_str());
+        jstring jplugID = env->NewStringUTF(result[i].getID().c_str());
+        LOGD("jniGetPlugins() [%d] Version: %s", i + 1, result[i].getID().c_str());
+        env->SetObjectArrayElement(resultArray, i, env->NewObject(cls, mid, jname, jplugID));
+    }
+
+    return resultArray;
+}
+
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    getState
+ * Signature: (Ljava/lang/String;)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_org_iotivity_service_ppm_PluginManager_jniGetState(JNIEnv *env, jobject jobj,
+        jstring jplugID)
+{
+    LOGD("jniGetState() Called.");
+
+    if (!jplugID)
+        return env->NewStringUTF("NULL_INPUT");
+    std::string cplugID = env->GetStringUTFChars(jplugID, 0);
+    std::string result = pluginManagerImpl->getState(cplugID);
+
+    return env->NewStringUTF(result.c_str());
+}
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    JNI_OnLoad
+ */
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jjvm, void *reserved)
+{
+    LOGD("JNI_OnLoad() Called.");
+
+    JNIEnv *env;
+
+    if (jjvm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK)
+        return JNI_ERR;
+
+    jvm = jjvm;
+    pluginManagerImpl = new OIC::PluginManagerImpl((void *)jvm);
+
+    return JNI_VERSION_1_6;
+}
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    JNI_OnUnload
+ */
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jjvm, void *reserved)
+{
+    LOGD("JNI_OnUnload() Called.");
+
+    JNIEnv *env;
+
+    if (jjvm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK)
+        return ;
+
+    jvm = NULL;
+
+    if (pluginManagerImpl)
+        delete pluginManagerImpl;
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/jni/PluginManager.h b/service/protocol-plugin/plugin-manager/src/Android/jni/PluginManager.h
new file mode 100644 (file)
index 0000000..cc4df34
--- /dev/null
@@ -0,0 +1,94 @@
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file PluginManager.h
+
+/// @brief
+
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include <jni.h>
+#include <android/log.h>
+
+#include "../../PluginManagerImpl.h"
+
+/* Header for class com_example_iotivity_PluginManager */
+
+#define  LOG_TAG    "PluginManager.cpp"
+#define  LOGUNK(...)  __android_log_print(ANDROID_LOG_UNKNOWN,LOG_TAG,__VA_ARGS__)
+#define  LOGDEF(...)  __android_log_print(ANDROID_LOG_DEFAULT,LOG_TAG,__VA_ARGS__)
+#define  LOGV(...)  __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__)
+#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
+#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
+#define  LOGW(...)  __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
+#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
+#define  LOGF(...)  __android_log_print(ANDROID_FATAL_ERROR,LOG_TAG,__VA_ARGS__)
+#define  LOGS(...)  __android_log_print(ANDROID_SILENT_ERROR,LOG_TAG,__VA_ARGS__)
+
+#ifndef _Included_org_iotivity_service_ppm_PluginManager
+#define _Included_org_iotivity_service_ppm_PluginManager
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+OIC::PluginManagerImpl *pluginManagerImpl;
+JavaVM *jvm;
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    jniStartPlugins
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)I
+ */
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ppm_PluginManager_jniStartPlugins(JNIEnv *, jobject,
+        jstring, jstring);
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    jniStopPlugins
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)I
+ */
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ppm_PluginManager_jniStopPlugins(JNIEnv *, jobject, jstring,
+        jstring);
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    jniRescanPlugin
+ * Signature: (V)I
+ */
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ppm_PluginManager_jniRescanPlugin(JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    jniGetPlugins
+ * Signature: (V)[Lorg/iotivity/service/ppm/Plugin;
+ */
+JNIEXPORT jobjectArray JNICALL Java_org_iotivity_service_ppm_PluginManager_jniGetPlugins(JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_ppm_PluginManager
+ * Method:    jniGetState
+ * Signature: (Ljava/lang/String;)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_org_iotivity_service_ppm_PluginManager_jniGetState(JNIEnv *, jobject,
+        jstring);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/service/protocol-plugin/plugin-manager/src/Android/jni/SConscript b/service/protocol-plugin/plugin-manager/src/Android/jni/SConscript
new file mode 100644 (file)
index 0000000..55ec004
--- /dev/null
@@ -0,0 +1,52 @@
+##
+# Protocol plug-in manager service JNI build script
+##
+
+import os
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env')
+
+ppm_jni_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+ppm_sdk = env.get('SRC_DIR') + '/service/protocol-plugin/plugin-manager'
+
+######################################################################
+# Build flags
+######################################################################
+ppm_jni_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-DLINUX', '-DNDEBUG'])
+ppm_jni_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ppm_jni_env.PrependUnique(LIBS = ['pmimpl', 'ppm', 'expat', 'cpluff', 'boost_system', 'boost_thread', 'gnustl_shared', 'log'])
+
+ppm_jni_env.AppendUnique(CPPPATH = [ppm_sdk+'/src'])
+ppm_jni_env.AppendUnique(CPPPATH = [ppm_sdk+'/../lib/cpluff/libcpluff'])
+ppm_jni_env.AppendUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs/rapidxml'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+ppm_jni_src = ['PluginManager.cpp']
+ppm_jni = ppm_jni_env.SharedLibrary('PluginManager', ppm_jni_src)
+
+ppm_jni_env.InstallTarget(ppm_jni, 'libPluginManager')
+
+######################################################################
+# Install the libraries to /libs/<TARGET_ARCH> directory
+######################################################################
+ppm_jni_env.Install(ppm_sdk+'/src/Android/libs/'+env.get('TARGET_ARCH'),ppm_jni)
+ppm_jni_env.Install(ppm_sdk+'/src/Android/libs/'+env.get('TARGET_ARCH'),env.get('BUILD_DIR')+'/libpmimpl.so')
+ppm_jni_env.Install(ppm_sdk+'/src/Android/libs/'+env.get('TARGET_ARCH'),env.get('SRC_DIR')+'/dep/android/'+env.get('TARGET_ARCH')+'/usr/lib/libexpat.so')
+
+gnu_lib_paths = env.get('LIBPATH')
+for gnu_lib_path in gnu_lib_paths:
+    gnu_lib_path = gnu_lib_path + '/libgnustl_shared.so'
+    if os.path.exists(gnu_lib_path):
+        ppm_jni_env.Install(ppm_sdk+'/src/Android/libs/'+env.get('TARGET_ARCH'), gnu_lib_path)
+        break
+
+
+
+
+
diff --git a/service/protocol-plugin/plugin-manager/src/Android/lint.xml b/service/protocol-plugin/plugin-manager/src/Android/lint.xml
new file mode 100644 (file)
index 0000000..ee0eead
--- /dev/null
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<lint>
+</lint>
\ No newline at end of file
diff --git a/service/protocol-plugin/plugin-manager/src/Android/proguard-project.txt b/service/protocol-plugin/plugin-manager/src/Android/proguard-project.txt
new file mode 100644 (file)
index 0000000..f2fe155
--- /dev/null
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/project.properties b/service/protocol-plugin/plugin-manager/src/Android/project.properties
new file mode 100644 (file)
index 0000000..00cf62b
--- /dev/null
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-22
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/drawable-hdpi/ic_launcher.png b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-hdpi/ic_launcher.png differ
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/drawable-mdpi/ic_launcher.png b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..6ae570b
Binary files /dev/null and b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-mdpi/ic_launcher.png differ
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/drawable-xhdpi/ic_launcher.png b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-xhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..d4fb7cd
Binary files /dev/null and b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/drawable-xxhdpi/ic_launcher.png b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..85a6081
Binary files /dev/null and b/service/protocol-plugin/plugin-manager/src/Android/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/layout/activity_main.xml b/service/protocol-plugin/plugin-manager/src/Android/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..0371a56
--- /dev/null
@@ -0,0 +1,217 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    tools:context="org.iotivity.service.ppm.MainActivity$PlaceholderFragment" >
+
+    <ScrollView
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:layout_alignParentLeft="true"
+        android:layout_alignParentTop="true" >
+
+        <LinearLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="vertical" >
+
+            <LinearLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="horizontal" >
+
+                <TextView
+                    android:id="@+id/textView5"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="center"
+                    android:text="Belkin Plug : "
+                    android:textAppearance="?android:attr/textAppearanceMedium" />
+
+                <Button
+                    android:id="@+id/btn_belkin"
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="center"
+                    android:text="ON/OFF" />
+            </LinearLayout>
+
+            <LinearLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="horizontal" >
+
+                <Button
+                    android:id="@+id/Button01"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="START PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button02"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="STOP PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button03"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="GET PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button04"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="GET STATE"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button05"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="RESCAN PLUGIN"
+                    android:textSize="10dp" />
+
+            </LinearLayout>
+
+            <LinearLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="horizontal" >
+
+                <TextView
+                    android:id="@+id/textView4"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="center"
+                    android:text="Gear Plug : "
+                    android:textAppearance="?android:attr/textAppearanceMedium" />
+
+                <Button
+                    android:id="@+id/btn_gear"
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="center"
+                    android:text="ON/OFF" />
+            </LinearLayout>
+
+            <LinearLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="horizontal" >
+
+                <Button
+                    android:id="@+id/Button06"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="START PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button07"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="STOP PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button08"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="GET PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button09"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="GET STATE"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button10"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="RESCAN PLUGIN"
+                    android:textSize="10dp" />
+
+            </LinearLayout>
+
+        <LinearLayout
+                    android:layout_width="match_parent"
+                   android:layout_height="wrap_content"
+                   android:orientation="horizontal" >
+                   <TextView
+                       android:id="@+id/textView3"
+                       android:layout_width="120dp"
+                       android:layout_height="wrap_content"
+                       android:text="Hue Bulb : "
+                       android:textAppearance="?android:attr/textAppearanceMedium"
+                       android:layout_gravity="center"/>
+                   <ToggleButton
+                        android:id="@+id/tbtn_hue_power"
+                        android:layout_width="100dp"
+                        android:layout_height="wrap_content"
+                        android:layout_gravity="center"
+                        android:onClick="onToggleClicked"
+                        android:textOff="OFF"
+                        android:textOn="ON" />
+                   <NumberPicker
+                        android:id="@+id/np_hue_color"
+                        android:layout_width="100dp"
+                        android:layout_height="wrap_content"
+                        android:layout_gravity="center"/>
+               </LinearLayout>
+               <LinearLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="horizontal" >
+
+                <Button
+                    android:id="@+id/Button11"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="START PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button12"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="STOP PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button13"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="GET PLUGIN"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button14"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="GET STATE"
+                    android:textSize="10dp" />
+
+                <Button
+                    android:id="@+id/Button15"
+                    android:layout_width="65dp"
+                    android:layout_height="wrap_content"
+                    android:text="RESCAN PLUGIN"
+                    android:textSize="10dp" />
+
+            </LinearLayout>
+          </LinearLayout>
+    </ScrollView>
+
+</RelativeLayout>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/layout/fragment_main.xml b/service/protocol-plugin/plugin-manager/src/Android/res/layout/fragment_main.xml
new file mode 100644 (file)
index 0000000..d14d61d
--- /dev/null
@@ -0,0 +1,11 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    tools:context="org.iotivity.service.ppm.MainActivity$PlaceholderFragment" >
+
+</RelativeLayout>
\ No newline at end of file
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/menu/main.xml b/service/protocol-plugin/plugin-manager/src/Android/res/menu/main.xml
new file mode 100644 (file)
index 0000000..8177459
--- /dev/null
@@ -0,0 +1,11 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    tools:context="org.iotivity.service.ppm.MainActivity" >
+
+    <item
+        android:id="@+id/action_settings"
+        android:orderInCategory="100"
+        android:title="@string/action_settings"/>
+
+</menu>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/values-v11/styles.xml b/service/protocol-plugin/plugin-manager/src/Android/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..aeeae24
--- /dev/null
@@ -0,0 +1,11 @@
+<resources>
+
+    <!--
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!-- API 11 theme customizations can go here. -->
+    </style>
+
+</resources>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/values-v14/styles.xml b/service/protocol-plugin/plugin-manager/src/Android/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..afb7b31
--- /dev/null
@@ -0,0 +1,12 @@
+<resources>
+
+    <!--
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!-- API 14 theme customizations can go here. -->
+    </style>
+
+</resources>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/values-w820dp/dimens.xml b/service/protocol-plugin/plugin-manager/src/Android/res/values-w820dp/dimens.xml
new file mode 100644 (file)
index 0000000..f3e7020
--- /dev/null
@@ -0,0 +1,10 @@
+<resources>
+
+    <!--
+         Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
+    -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+
+</resources>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/values/dimens.xml b/service/protocol-plugin/plugin-manager/src/Android/res/values/dimens.xml
new file mode 100644 (file)
index 0000000..55c1e59
--- /dev/null
@@ -0,0 +1,7 @@
+<resources>
+
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/values/strings.xml b/service/protocol-plugin/plugin-manager/src/Android/res/values/strings.xml
new file mode 100644 (file)
index 0000000..39ed22c
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="app_name">Android</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="action_settings">Settings</string>
+
+</resources>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/res/values/styles.xml b/service/protocol-plugin/plugin-manager/src/Android/res/values/styles.xml
new file mode 100644 (file)
index 0000000..6ce89c7
--- /dev/null
@@ -0,0 +1,20 @@
+<resources>
+
+    <!--
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!--
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        -->
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+    </style>
+
+</resources>
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/FelixManager.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/FelixManager.java
new file mode 100644 (file)
index 0000000..b7d7c87
--- /dev/null
@@ -0,0 +1,578 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file FelixManager.java
+
+package org.iotivity.service.ppm;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.felix.framework.Felix;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleException;
+import org.osgi.framework.Constants;
+
+import android.content.Context;
+import android.content.res.AssetManager;
+import android.os.FileObserver;
+import android.util.Log;
+
+public class FelixManager {
+    private static Felix                   m_felix                    = null;
+    private static ArrayList<FileObserver> m_observer;
+    private static FelixManager            m_felixmgr;
+    private static Context                 m_context;
+    private static final int               TRUE                       = 1;
+    private static final int               FALSE                      = 0;
+
+    static final String                    ANDROID_FRAMEWORK_PACKAGES = ("android,"
+                                                                  + "android.app,"
+                                                                  + "android.content,"
+                                                                  + "android.content.pm,"
+                                                                  + "android.content.res,"
+                                                                  + "android.database,"
+                                                                  + "android.database.sqlite,"
+                                                                  + "android.graphics,"
+                                                                  + "android.graphics.drawable,"
+                                                                  + "android.graphics.glutils,"
+                                                                  + "android.hardware,"
+                                                                  + "android.location,"
+                                                                  + "android.media,"
+                                                                  + "android.net,"
+                                                                  + "android.net.wifi,"
+                                                                  + "android.net.http,"
+                                                                  + "android.opengl,"
+                                                                  + "android.os,"
+                                                                  + "android.provider,"
+                                                                  + "android.sax,"
+                                                                  + "android.speech.recognition,"
+                                                                  + "android.telephony,"
+                                                                  + "android.telephony.gsm,"
+                                                                  + "android.text,"
+                                                                  + "android.text.format,"
+                                                                  + "android.text.method,"
+                                                                  + "android.text.style,"
+                                                                  + "android.text.util,"
+                                                                  + "android.util,"
+                                                                  + "android.view,"
+                                                                  + "android.view.animation,"
+                                                                  + "android.webkit,"
+                                                                  + "android.widget,"
+                                                                  + "javax.xml.parsers,"
+                                                                  + "org.xml.sax,"
+                                                                  + "org.w3c.dom,"
+                                                                  + "com.example.felixmanager,"
+                                                                  + "org.iotivity.base");
+
+    // FelixManager singleton
+    public static FelixManager getInstance(Context ctx) {
+        if (m_felixmgr == null) {
+            m_felixmgr = new FelixManager(ctx);
+            copyFiles("files");
+        }
+
+        return m_felixmgr;
+    }
+
+    public static void LogEx(String info) {
+        Log.d("felix", info);
+    }
+
+    private FelixManager(Context ctx) {
+        m_context = ctx;
+        m_observer = new ArrayList<FileObserver>();
+
+        Map configMap = new HashMap();
+        String mCacheDir = ctx.getDir("org.osgi.framework.storage",
+                Context.MODE_WORLD_WRITEABLE).toString();
+        configMap.put("org.osgi.framework.storage", mCacheDir);
+        configMap.put("felix.embedded.execution", "true");
+        configMap.put("org.osgi.service.http.port", "9990");
+        configMap.put("org.osgi.framework.startlevel.beginning", "5");
+        configMap.put("felix.bootdelegation.implicit", "false");
+        configMap.put("felix.service.urlhandlers", "false");
+        configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA,
+                ANDROID_FRAMEWORK_PACKAGES);
+        try {
+            m_felix = new Felix(configMap);
+            m_felix.init();
+            m_felix.start();
+
+            for (org.osgi.framework.Bundle b : m_felix.getBundleContext()
+                    .getBundles()) {
+                LogEx("Bundle: " + b.getSymbolicName());
+            }
+        } catch (Throwable ex) {
+            Log.d("Felix", "could not create framework: " + ex.getMessage(), ex);
+        }
+    }
+
+    public static int registerPlugin(String path) {
+
+        int flag = FALSE;
+
+        flag = installPlugin(path);
+        if (flag == TRUE)
+            flag = loadPluginInfoToManager(path);
+
+        return flag;
+    }
+
+    public static int registerAllPlugin(String path) {
+
+        int flag = FALSE;
+
+        flag = findPluginRecursive(path);
+        if (flag == TRUE)
+            flag = loadPluginInfoToManager(path);
+
+        return flag;
+    }
+
+    public static int unregisterPlugin(String id) {
+        int flag = TRUE;
+        try {
+            BundleContext bContext = m_felix.getBundleContext();
+            org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+            for (org.osgi.framework.Bundle b : bundles) {
+                if (b.getSymbolicName().equals(id)) {
+                    Log.d("Felix", "bundle: " + b.getBundleId()
+                            + "   symbolicName : " + b.getSymbolicName());
+                    b.uninstall();
+                    Log.d("Felix", "uninstall end");
+                }
+            }
+        } catch (BundleException e) {
+            e.printStackTrace();
+            flag = FALSE;
+        }
+
+        return flag;
+    }
+
+    public static int unregisterAllPlugin() {
+        int flag = TRUE;
+        try {
+            BundleContext bContext = m_felix.getBundleContext();
+            org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+            for (org.osgi.framework.Bundle b : bundles) {
+                if (!b.getSymbolicName().equals("org.apache.felix.framework")) {
+                    Log.d("Felix", "bundle: " + b.getBundleId()
+                            + "   symbolicName : " + b.getSymbolicName());
+                    b.uninstall();
+                    Log.d("Felix", "uninstall end");
+                }
+            }
+        } catch (BundleException e) {
+            e.printStackTrace();
+            flag = FALSE;
+        }
+
+        return flag;
+    }
+
+    public static org.osgi.framework.Bundle[] getAllPlugins() {
+        try {
+            BundleContext bContext = m_felix.getBundleContext();
+            org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+            return bundles;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+    public static org.osgi.framework.Bundle[] findPulgins(String key,
+            String value) {
+        BundleContext bContext = m_felix.getBundleContext();
+        org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+
+        return bundles;
+    }
+
+    public static org.osgi.framework.Bundle getPlugin(int ID) {
+        BundleContext bContext = m_felix.getBundleContext();
+        org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+        for (int i = 0; i < bundles.length; i++) {
+            if (bundles[i].getBundleId() == ID) {
+                return bundles[i];
+            }
+        }
+        return null;
+    }
+
+    public static int start(String id) {
+        int flag = TRUE;
+        Log.d("Felix", "String id : " + id);
+        try {
+            BundleContext bContext = m_felix.getBundleContext();
+            bContext.registerService(Context.class.getName(), m_context, null);
+
+            org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+            for (org.osgi.framework.Bundle b : bundles) {
+                Log.d("Felix", "symbolicName : " + b.getSymbolicName());
+                if (b.getSymbolicName().equals(id)) {
+                    Log.d("Felix", "bundle: " + b.getBundleId()
+                            + "   symbolicName : " + b.getSymbolicName());
+                    b.start();
+                    Log.d("Felix", "start end");
+                }
+            }
+        } catch (BundleException e) {
+            e.printStackTrace();
+            flag = FALSE;
+        }
+        return flag;
+    }
+
+    public static int stop(String id) {
+        int flag = TRUE;
+        try {
+            BundleContext bContext = m_felix.getBundleContext();
+            org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+            for (org.osgi.framework.Bundle b : bundles) {
+                if (b.getSymbolicName().equals(id)) {
+                    Log.d("Felix", "bundle: " + b.getBundleId()
+                            + "   symbolicName : " + b.getSymbolicName());
+                    b.stop();
+                    b.uninstall();
+                    Log.d("Felix", "stop end");
+                }
+            }
+        } catch (BundleException e) {
+            e.printStackTrace();
+            flag = FALSE;
+        }
+        return flag;
+    }
+
+    public static boolean isStarted(String name) {
+        String state = getState(name);
+        if (state.equals("ACTIVE") || state.equals("STARTING"))
+            return true;
+        return false;
+    }
+
+    public static String getValue(String name, String key) {
+        Log.d("FELIX", "getValue");
+        BundleContext bContext = m_felix.getBundleContext();
+        org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+        for (org.osgi.framework.Bundle b : bundles) {
+            Dictionary<String, String> dic = b.getHeaders();
+            String bundlename = b.getSymbolicName();
+            Log.d("FELIX", "Bundlename: " + bundlename);
+
+            if (bundlename.equals(name)) {
+                if (dic.get("Bundle-" + key) == null) {
+                    Log.d("FELIX", name + " null");
+                    return "";
+                }
+                Log.d("FELIX", name + " " + dic.get("Bundle-" + key));
+                return dic.get("Bundle-" + key);
+            }
+        }
+        return "";
+    }
+
+    public static String getState(String name) {
+        Log.d("FELIX", "getState");
+        BundleContext bContext = m_felix.getBundleContext();
+        org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+        for (org.osgi.framework.Bundle b : bundles) {
+            Dictionary<String, String> dic = b.getHeaders();
+            String bundlename = b.getSymbolicName();
+
+            if (bundlename.equals(name)) {
+                Log.d("FELIX", state_to_string(b.getState()));
+                return state_to_string(b.getState());
+            }
+        }
+        Log.d("FELIX", "null");
+        return "";
+    }
+
+    public static String printPluginList() {
+        String str = "";
+        str += "id   |     state     |    symbolname | ";
+        BundleContext bContext = m_felix.getBundleContext();
+        org.osgi.framework.Bundle[] bundles = bContext.getBundles();
+        for (org.osgi.framework.Bundle b : bundles) {
+            str += "\n" + b.getBundleId() + "  "
+                    + state_to_string(b.getState()) + " " + b.getSymbolicName();
+        }
+        return str;
+    }
+
+    public static void stop_felix() {
+        try {
+            m_felix.stop();
+            m_felix.waitForStop(0);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static ArrayList<String> getFileList(String path, boolean recursive) {
+        File file = new File(path);
+        File[] files = file.listFiles();
+        ArrayList<String> array = new ArrayList<String>();
+        for (int i = 0; i < files.length; i++) {
+            if (files[i].isDirectory()) {
+                if (recursive == true) {
+                    ArrayList<String> directory_list = getFileList(files[i]
+                            + "/", true);
+                    array.addAll(directory_list);
+                }
+                Log.v("Directory : ", files[i].getName());
+            } else {
+                if (files[i].getName().endsWith("jar")) {
+                    Log.v("File :", files[i].getName());
+                    if (path.charAt(path.length() - 1) != '/') {
+                        path += "/";
+                    }
+                    array.add(path + files[i].getName());
+                }
+            }
+        }
+        return array;
+    }
+
+    private static String state_to_string(int state) {
+        String str = state + " [unknown state]";
+
+        if (state == org.osgi.framework.Bundle.ACTIVE) {
+            return "ACTIVE";
+        } else if (state == org.osgi.framework.Bundle.INSTALLED) {
+            return "INSTALLED";
+        } else if (state == org.osgi.framework.Bundle.RESOLVED) {
+            return "RESOLVED";
+        } else if (state == org.osgi.framework.Bundle.STARTING) {
+            return "STARTING";
+        } else if (state == org.osgi.framework.Bundle.STOPPING) {
+            return "STOPPING";
+        } else if (state == org.osgi.framework.Bundle.UNINSTALLED) {
+            return "UNINSTALLED";
+        }
+        return str;
+    }
+
+    public static int installPlugin(String path) {
+
+        int flag = TRUE;
+        if (path == "") {
+            System.out.println("PluginManager path is Null\n");
+        }
+
+        ArrayList<String> filearray;
+        BundleContext bContext = m_felix.getBundleContext();
+        String location = "";
+        FileInputStream fin;
+        if (path.charAt(0) != '/') {
+            path = "/" + path;
+        } else if (path.charAt(path.length() - 1) != '/') {
+            path = path + "/";
+        }
+
+        filearray = getFileList(path, false);
+
+        for (int i = 0; i < filearray.size(); i++) {
+            try {
+                location = "file:" + filearray.get(i);
+                fin = new FileInputStream(new File(filearray.get(i)));
+                bContext.installBundle(location, fin);
+            } catch (BundleException e) {
+                e.printStackTrace();
+                flag = FALSE;
+            } catch (FileNotFoundException e) {
+                e.printStackTrace();
+                flag = FALSE;
+            }
+        }
+
+        return flag;
+    }
+
+    private static String getEventString(int event) {
+        switch (event) {
+            case FileObserver.ACCESS:
+                return "ACCESS";
+            case FileObserver.MODIFY:
+                return "MODIFY";
+            case FileObserver.ATTRIB:
+                return "ATTRIB";
+            case FileObserver.CLOSE_WRITE:
+                return "CLOSE_WRITE";
+            case FileObserver.CLOSE_NOWRITE:
+                return "CLOSE_NOWRITE";
+            case FileObserver.OPEN:
+                return "OPEN";
+            case FileObserver.MOVED_FROM:
+                return "MOVED_FROM";
+            case FileObserver.MOVED_TO:
+                return "MOVED_TO";
+            case FileObserver.CREATE:
+                return "CREATE";
+            case FileObserver.DELETE:
+                return "DELETE";
+            case FileObserver.DELETE_SELF:
+                return "DELETE_SELF";
+            case FileObserver.MOVE_SELF:
+                return "MOVE_SELF";
+            default:
+                return "UNKNOWN";
+        }
+    }
+
+    public static int ObservePluginPath(String path) {
+        int flag = TRUE;
+        Log.d("FELIX", "ObservePluginPath" + path);
+
+        FileObserver observer = new FileObserver(path) {
+            @Override
+            public void onEvent(int event, String path) {
+                Log.d("FELIX", "Observing start : " + path);
+                Log.d("FELIX", "Observing event : " + getEventString(event));
+            }
+        };
+        observer.startWatching();
+        m_observer.add(observer);
+
+        return flag;
+    }
+
+    public static int findPluginRecursive(String path) {
+        int flag = TRUE;
+        if (path == "") {
+            System.out.println("PluginManager path is Null\n");
+            Log.d("FELIX", "PluginManager path is Null\n");
+            flag = FALSE;
+            return flag;
+        }
+
+        ArrayList<String> filearray;
+        BundleContext bContext = m_felix.getBundleContext();
+        String location = "";
+        FileInputStream fin;
+
+        if (path.charAt(0) != '/') {
+            path = "/" + path;
+        } else if (path.charAt(path.length() - 1) != '/') {
+            path = path + "/";
+        }
+
+        filearray = getFileList(path, true);
+
+        for (int i = 0; i < filearray.size(); i++) {
+            try {
+                location = "file:" + filearray.get(i);
+                fin = new FileInputStream(new File(filearray.get(i)));
+                bContext.installBundle(location, fin);
+            } catch (BundleException e) {
+                e.printStackTrace();
+                flag = FALSE;
+            } catch (FileNotFoundException e) {
+                e.printStackTrace();
+                flag = FALSE;
+            }
+        }
+
+        return flag;
+    }
+
+    public static int loadPluginInfoToManager(String path) {
+        int flag = FALSE;
+
+        flag = ObservePluginPath(path);
+        FelixManager.printPluginList();
+
+        return flag;
+    }
+
+    public static String getPackageName() {
+        String packagename;
+
+        packagename = m_context.getPackageName();
+
+        return packagename;
+    }
+
+    private static void copyFiles(String path) {
+        AssetManager assetManager = m_context.getAssets();
+        String assets[] = null;
+
+        try {
+            assets = assetManager.list(path);
+
+            if (assets.length == 0) {
+                copyFile(path);
+            } else {
+                String fullPath = "/data/data/"
+                        + m_context.getPackageName() + "/" + path;
+                Log.d("FELIX", fullPath);
+                File dir = new File(fullPath);
+
+                if (!dir.exists())
+                    dir.mkdir();
+                for (int i = 0; i < assets.length; ++i) {
+                    copyFiles(path + "/" + assets[i]);
+                }
+            }
+        } catch (IOException ex) {
+            Log.e("tag", "I/O Exception", ex);
+        }
+    }
+
+    private static void copyFile(String filename) {
+        AssetManager assetManager = m_context.getAssets();
+        InputStream in = null;
+        OutputStream out = null;
+
+        try {
+            in = assetManager.open(filename);
+            out = m_context.openFileOutput(filename.split("/")[1], Context.MODE_PRIVATE);
+
+            byte[] buffer = new byte[1024];
+            
+            int read;
+
+            while ((read = in.read(buffer)) != -1) {
+                out.write(buffer, 0, read);
+            }
+
+            in.close();
+            in = null;
+            out.flush();
+            out.close();
+            out = null;
+        } catch (Exception e) {
+            Log.e("tag", e.getMessage());
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/FoundResource.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/FoundResource.java
new file mode 100644 (file)
index 0000000..1fa7ef5
--- /dev/null
@@ -0,0 +1,82 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file FoundResource.java
+
+package org.iotivity.service.ppm;
+
+import java.util.HashMap;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+public class FoundResource implements OcPlatform.OnResourceFoundListener {
+    final private static String TAG = "FoundResource";
+
+    public void onResourceFound(OcResource resource) {
+
+        String resourceURI;
+        String hostAddress;
+
+        if (resource != null) {
+            Log.i(TAG, "DISCOVERED Resource");
+
+            resourceURI = resource.getUri();
+
+            Log.i(TAG, "URI of the resource: " + resourceURI);
+
+            hostAddress = resource.getHost();
+            Log.i(TAG, "Host address of the resource: " + hostAddress);
+
+            if (resourceURI.equals("/a/wemo")) {
+                MainActivity.belkinResource = resource;
+                OnGetBelkinplug onGet = new OnGetBelkinplug();
+                try {
+                    resource.get(new HashMap<String, String>(), onGet);
+                } catch (OcException e) {
+                    e.printStackTrace();
+                }
+            } else if (resourceURI.equals("/a/galaxy/gear")) {
+                MainActivity.gearResource = resource;
+                OnGetGear onGet = new OnGetGear();
+                try {
+                    resource.get(new HashMap<String, String>(), onGet);
+                } catch (OcException e) {
+                    e.printStackTrace();
+                }
+            } else if (resourceURI.equals("/a/huebulb")) {
+                MainActivity.hueResource = resource;
+                OnGetHuebulb onGet = new OnGetHuebulb();
+                try {
+                    resource.get(new HashMap<String, String>(), onGet);
+                } catch (OcException e) {
+                    e.printStackTrace();
+                }
+            } else {
+                Log.e(TAG, "ResourceURI is invalid");
+            }
+        } else {
+            Log.e(TAG, "Resource is invalid");
+        }
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/MainActivity.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/MainActivity.java
new file mode 100644 (file)
index 0000000..8a866d8
--- /dev/null
@@ -0,0 +1,692 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file MainActivity.java
+
+package org.iotivity.service.ppm;
+
+import java.util.HashMap;
+import java.util.Map;
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.service.ppm.R;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Handler;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+import android.widget.ToggleButton;
+
+public class MainActivity extends Activity implements
+        android.widget.NumberPicker.OnValueChangeListener {
+    class S_demo_device {
+        public String m_name;
+        public String m_power;
+        public int    m_bright;
+        public int    m_color;
+        public String m_uri;
+    }
+
+    static S_demo_device               belkinplug;
+    static S_demo_device               gearplug;
+    static S_demo_device               hueplug;
+    static OcResource                  belkinResource;
+    static OcResource                  gearResource;
+    static OcResource                  hueResource;
+    static TextView                    belkintv;
+    static TextView                    geartv;
+    static TextView                    huetv;
+    static ToggleButton                Hue;
+    static android.widget.NumberPicker hue_color;
+    static Activity                    mActivity;
+
+    PluginManager                      m_pm;
+
+    Button                             belkinstart;
+    Button                             belkingetPlugins;
+    Button                             belkingetstate;
+    Button                             belkinstop;
+    Button                             belkinrescan;
+    Button                             Belkin;
+
+    Button                             gearstart;
+    Button                             geargetPlugins;
+    Button                             geargetstate;
+    Button                             gearstop;
+    Button                             gearrescan;
+    Button                             Gear;
+
+    Button                             huestart;
+    Button                             huegetPlugins;
+    Button                             huegetstate;
+    Button                             huestop;
+    Button                             huerescan;
+
+    Context                            ctx;
+
+    String                             name;
+    String                             key;
+    String                             state;
+    String                             id;
+    Plugin[]                           user_plugin;
+    Map<Integer, Integer>              onValueChangefinalVal    = new HashMap<Integer, Integer>();
+    Map<Integer, Boolean>              onValueChangeThreadStart = new HashMap<Integer, Boolean>();
+    String[]                           np_h                     = new String[11];
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+
+        super.onCreate(savedInstanceState);
+        ctx = getApplicationContext();
+        m_pm = new PluginManager(ctx);
+
+        setContentView(R.layout.activity_main);
+        mActivity = this;
+        onValueChangeThreadStart.put(R.id.np_hue_color, false);
+        belkinplug = new S_demo_device();
+        gearplug = new S_demo_device();
+        hueplug = new S_demo_device();
+
+        for (int i = 0; i < np_h.length; i++) {
+            np_h[i] = Integer.toString(i);
+        }
+
+        hue_color = (android.widget.NumberPicker) findViewById(R.id.np_hue_color);
+        hue_color.setMaxValue(10);
+        hue_color.setMinValue(0);
+        hue_color.setDisplayedValues(np_h);
+        hue_color.setFocusable(true);
+        hue_color.setFocusableInTouchMode(true);
+        hue_color
+                .setDescendantFocusability(android.widget.NumberPicker.FOCUS_BLOCK_DESCENDANTS);
+        hue_color.setOnValueChangedListener(this);
+
+        PlatformConfig cfg = new PlatformConfig(this, ServiceType.IN_PROC,
+                ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+
+        OcPlatform.Configure(cfg);
+
+        try {
+            FoundResource foundResource = new FoundResource();
+            OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY,
+                    OcConnectivityType.ALL, foundResource);
+        } catch (Exception e) {
+            Log.e("Felix", "Exception : " + e);
+        }
+
+        Belkin = (Button) findViewById(R.id.btn_belkin);
+        Belkin.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "Belkin button click listener");
+                OcRepresentation rep = new OcRepresentation();
+                try {
+                    if (belkinplug.m_power == null) {
+                        Log.i("Felix", "m_power is null");
+                        belkinplug.m_power = "on";
+                        rep.setValue("power", "on");
+                    }
+                    if (belkinplug.m_power.equals("on")) {
+                        Toast.makeText(getApplicationContext(), "Off",
+                                Toast.LENGTH_SHORT).show();
+                        Log.i("Felix", "belkin wemo off");
+                        rep.setValue("power", "off");
+                    } else if (belkinplug.m_power.equals("off")) {
+                        Toast.makeText(getApplicationContext(), "On",
+                                Toast.LENGTH_SHORT).show();
+                        Log.i("Felix", "belkin wemo on");
+                        rep.setValue("power", "on");
+                    } else {
+                        rep.setValue("power", "on");
+                    }
+                    rep.setValue("name", "belkin");
+                    rep.setValue("uri", "/a/wemo");
+                    rep.setValue("brightness", 0);
+                    rep.setValue("color", 0);
+                } catch (OcException e) {
+                    Log.e("Felix", e.getMessage());
+                }
+                OnPutBelkinplug onPut = new OnPutBelkinplug();
+                if (belkinResource != null) {
+                    try {
+                        belkinResource.put(rep, new HashMap<String, String>(),
+                                onPut);
+                    } catch (OcException e) {
+                        e.printStackTrace();
+                    }
+                } else {
+                    Toast.makeText(getApplicationContext(), "Belkinplug null",
+                            Toast.LENGTH_SHORT).show();
+                }
+            }
+        });
+
+        belkinstart = (Button) findViewById(R.id.Button01);
+        belkinstart.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "start button click listener");
+                m_pm.startPlugins("ResourceType", "device.smartplug");
+
+                Handler handler = new Handler();
+                handler.postDelayed(new Runnable() {
+                    @Override
+                    public void run() {
+                        Log.i("Felix", "run called!!!");
+                        FoundResource foundResource = new FoundResource();
+                        try {
+                            OcPlatform
+                                    .findResource(
+                                            "", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "device.smartplug",
+                                            OcConnectivityType.ALL, foundResource);
+                        } catch (OcException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                }, 3000);
+            }
+        });
+
+        belkinstop = (Button) findViewById(R.id.Button02);
+        belkinstop.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "stop button click listener");
+                m_pm.stopPlugins("ResourceType", "device.smartplug");
+                belkinResource = null;
+                try {
+                    java.lang.Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        belkingetPlugins = (Button) findViewById(R.id.Button03);
+        belkingetPlugins.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "getPlugins button click listener");
+                user_plugin = m_pm.getPlugins();
+                // key = "name";
+                state = "";
+                id = "";
+
+                for (int i = 0; i < user_plugin.length; i++) {
+                    System.out.println("value name " + user_plugin[i].getName());
+                    System.out.println("value id " + user_plugin[i].getID());
+                    // name = user_plugin[i].getID();
+                }
+            }
+        });
+
+        belkingetPlugins = (Button) findViewById(R.id.Button04);
+        belkingetPlugins.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "getState click listener");
+                state = m_pm.getState("wemo");
+                if (state == "")
+                    state = "null";
+                System.out.println("state: " + state);
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        belkinrescan = (Button) findViewById(R.id.Button05);
+        belkinrescan.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "Rescan Plugin click listener");
+                m_pm.rescanPlugin();
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        Gear = (Button) findViewById(R.id.btn_gear);
+        Gear.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "Gear button click listener");
+                OcRepresentation rep = new OcRepresentation();
+                
+                try{   
+                    rep.setValue("power", "Happy New Year!");
+                    rep.setValue("name", "gear");
+                    rep.setValue("uri", "/a/galaxy/gear");
+                    rep.setValue("brightness", 0);
+                    rep.setValue("color", 0);
+                } catch (OcException e) {
+                    Log.e("Felix", e.getMessage());
+                }
+                
+                if (gearResource != null) {
+                    Toast.makeText(getApplicationContext(),
+                            "Send Noti. to Gear", Toast.LENGTH_SHORT).show();
+                    try {
+                        OnPutGear onPut = new OnPutGear();
+                        gearResource.put(rep, new HashMap<String, String>(),
+                                onPut);
+                    } catch (OcException e) {
+                        e.printStackTrace();
+                    }
+                } else {
+                    Toast.makeText(getApplicationContext(), "Gear is null",
+                            Toast.LENGTH_SHORT).show();
+                }
+            }
+        });
+
+        gearstart = (Button) findViewById(R.id.Button06);
+        gearstart.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "start button click listener");
+                m_pm.startPlugins("ResourceType", "device.notify");
+
+                Handler handler = new Handler();
+                handler.postDelayed(new Runnable() {
+                    @Override
+                    public void run() {
+                        Log.i("Felix", "run called!!!");
+                        FoundResource foundResource = new FoundResource();
+                        try {
+                            OcPlatform
+                            .findResource(
+                                    "", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "device.notify",
+                                    OcConnectivityType.ALL, foundResource);
+                        } catch (OcException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                }, 3000);
+            }
+        });
+
+        gearstop = (Button) findViewById(R.id.Button07);
+        gearstop.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "stop button click listener");
+                m_pm.stopPlugins("ResourceType", "device.notify");
+                gearResource = null;
+                try {
+                    java.lang.Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        geargetPlugins = (Button) findViewById(R.id.Button08);
+        geargetPlugins.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "getPlugins button click listener");
+                user_plugin = m_pm.getPlugins();
+                state = "";
+                id = "";
+
+                for (int i = 0; i < user_plugin.length; i++) {
+                    System.out.println("value name " + user_plugin[i].getName());
+                    System.out.println("value id " + user_plugin[i].getID());
+                    name = user_plugin[i].getID();
+                }
+            }
+        });
+
+        geargetPlugins = (Button) findViewById(R.id.Button09);
+        geargetPlugins.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "getState click listener");
+                state = m_pm.getState("gearnoti");
+                if (state == "")
+                    state = "null";
+                System.out.println("state: " + state);
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        gearrescan = (Button) findViewById(R.id.Button10);
+        gearrescan.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "Rescan Plugin click listener");
+                m_pm.rescanPlugin();
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        Hue = (ToggleButton) findViewById(R.id.tbtn_hue_power);
+        Hue.setOnClickListener(new ToggleButton.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "Hue button click listener");
+                OcRepresentation rep = new OcRepresentation();
+                ToggleButton t = (ToggleButton) v;
+                if (t.isChecked()) {
+                    Toast.makeText(getApplicationContext(), "Hue ON",
+                            Toast.LENGTH_SHORT).show();
+                    if (hueplug.m_bright == 0) {
+                        Log.e("Felix", "hueplug m_bright is 0");
+                        hueplug.m_bright = 128;
+                    }
+                    try {
+                        rep.setValue("power", "on");
+                        rep.setValue("name", "hue");
+                        rep.setValue("uri", "/a/huebulb");
+                        rep.setValue("brightness", hueplug.m_bright);
+                        rep.setValue("color", hueplug.m_color);
+                    } catch (OcException e) {
+                        Log.e("Felix", e.getMessage());
+                    }
+
+                    OnPutHuebulb onPut = new OnPutHuebulb();
+                    if (hueResource != null) {
+                        try {
+                            hueResource.put(rep, new HashMap<String, String>(),
+                                    onPut);
+                        } catch (OcException e) {
+                            e.printStackTrace();
+                        }
+                    } else {
+                        Toast.makeText(getApplicationContext(),
+                                "HueResource null", Toast.LENGTH_SHORT).show();
+                    }
+                } else {
+                    Toast.makeText(getApplicationContext(), "Hue OFF",
+                            Toast.LENGTH_SHORT).show();
+                    if (hueplug.m_bright == 0) {
+                        Log.e("Felix", "hueplug m_bright is 0");
+                        hueplug.m_bright = 128;
+                    }
+                    try {
+                        rep.setValue("power", "off");
+                        rep.setValue("name", "hue");
+                        rep.setValue("uri", "/a/huebulb");
+                        rep.setValue("brightness", hueplug.m_bright);
+                        rep.setValue("color", hueplug.m_color);
+                    } catch (OcException e) {
+                        Log.e("Felix", e.getMessage());
+                    }
+
+                    OnPutHuebulb onPut = new OnPutHuebulb();
+
+                    if (hueResource != null) {
+                        try {
+                            hueResource.put(rep, new HashMap<String, String>(),
+                                    onPut);
+                        } catch (OcException e) {
+                            e.printStackTrace();
+                        }
+                    } else {
+                        Toast.makeText(getApplicationContext(),
+                                "HueResource null", Toast.LENGTH_SHORT).show();
+                    }
+                }
+            }
+        });
+
+        huestart = (Button) findViewById(R.id.Button11);
+        huestart.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "start button click listener");
+                m_pm.startPlugins("ResourceType", "device.light");
+
+                Handler handler = new Handler();
+                handler.postDelayed(new Runnable() {
+                    @Override
+                    public void run() {
+                        Log.i("Felix", "run called!!!");
+                        FoundResource foundResource = new FoundResource();
+                        try {
+                            OcPlatform
+                            .findResource(
+                                    "", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "device.light",
+                                    OcConnectivityType.ALL, foundResource);
+                        } catch (OcException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                }, 3000);
+            }
+        });
+
+        huestop = (Button) findViewById(R.id.Button12);
+        huestop.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "stop button click listener");
+                m_pm.stopPlugins("ResourceType", "device.light");
+                hueResource = null;
+                try {
+                    java.lang.Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        huegetPlugins = (Button) findViewById(R.id.Button13);
+        huegetPlugins.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "getPlugins button click listener");
+                user_plugin = m_pm.getPlugins();
+                key = "name";
+                state = "";
+                id = "";
+
+                for (int i = 0; i < user_plugin.length; i++) {
+                    System.out.println("value name " + user_plugin[i].getName());
+                    System.out.println("value id " + user_plugin[i].getID());
+                    name = user_plugin[i].getID();
+                }
+            }
+        });
+
+        huegetPlugins = (Button) findViewById(R.id.Button14);
+        huegetPlugins.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "getState click listener");
+                state = m_pm.getState("hue");
+                if (state == "")
+                    state = "null";
+                System.out.println("state: " + state);
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        huerescan = (Button) findViewById(R.id.Button15);
+        huerescan.setOnClickListener(new Button.OnClickListener() {
+            public void onClick(View v) {
+                Log.i("Felix", "Rescan Plugin click listener");
+                m_pm.rescanPlugin();
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+    }
+
+    static public void updateConnectStatus(String device, boolean status) {
+        if (device.equals("belkinplug")) {
+            if (status) {
+                Log.i("Felix", "belkingplug status green");
+                Toast.makeText(mActivity.getApplicationContext(),
+                        "Belkin Connected", Toast.LENGTH_SHORT).show();
+            } else {
+                Log.i("Felix", "belkingplug status gray");
+                Toast.makeText(mActivity.getApplicationContext(),
+                        "Belkin Disonnected", Toast.LENGTH_SHORT).show();
+            }
+        } else if (device.equals("gear")) {
+            if (status) {
+                Log.i("Felix", "gear status green");
+                Toast.makeText(mActivity.getApplicationContext(),
+                        "Gear Connected", Toast.LENGTH_SHORT).show();
+            } else {
+                Log.i("Felix", "gear status gray");
+                Toast.makeText(mActivity.getApplicationContext(),
+                        "Gear Disconnected", Toast.LENGTH_SHORT).show();
+            }
+        } else if (device.equals("huebulb")) {
+            if (status) {
+                Log.i("Felix", "huebulb status green");
+                Toast.makeText(mActivity.getApplicationContext(),
+                        "Hue Connected", Toast.LENGTH_SHORT).show();
+            } else {
+                Log.i("Felix", "huebulb status gray");
+                Toast.makeText(mActivity.getApplicationContext(),
+                        "Hue Disconnected", Toast.LENGTH_SHORT).show();
+            }
+
+            if (hueplug.m_power.equals("on")) {
+                Hue.setChecked(true);
+            } else {
+                Hue.setChecked(false);
+            }
+        }
+    }
+
+    static public void updateBelkinStatus() {
+        updateConnectStatus("belkinplug", true);
+    }
+
+    static public void updateGearStatus() {
+        updateConnectStatus("gear", true);
+    }
+
+    static public void updateHuebulbStatus() {
+        updateConnectStatus("huebulb", true);
+    }
+
+    @Override
+    protected void onResume() {
+        Log.i("Felix", "onResume()");
+        super.onResume();
+    }
+
+    @Override
+    protected void onPause() {
+        Log.i("Felix", "onPause()");
+        super.onPause();
+        finish();
+    }
+
+    @Override
+    protected void onStop() {
+        Log.i("Felix", "onStop()");
+        super.onStop();
+    }
+
+    @Override
+    protected void onDestroy() {
+        Log.i("Felix", "onDestroy()");
+        System.exit(1);
+        super.onDestroy();
+    }
+
+    private class ValueChangeThread extends Thread {
+        int idx;
+
+        public ValueChangeThread(int idx) {
+            this.idx = idx;
+        }
+
+        public void run() {
+            onValueChangeThreadStart.put(idx, true);
+            try {
+                sleep(1000, 0);
+            } catch (Exception e) {
+                Log.i("Felix", "waitForFinal exception : " + e);
+            }
+            Log.i("Felix", "Final Value for NUMBERPICKER[" + idx + "] : "
+                    + onValueChangefinalVal.get(idx));
+
+            if (idx == R.id.np_hue_color) {
+                hueplug.m_color = 6300 * onValueChangefinalVal.get(idx);
+                Log.i("Felix", "m_color = " + hueplug.m_color);
+
+                OcRepresentation rep = new OcRepresentation();
+                if (hueplug.m_power == null) {
+                    hueplug.m_power = "on";
+                }
+                if (hueplug.m_bright == 0) {
+                    hueplug.m_bright = 128;
+                }
+                try{
+                    rep.setValue("power", hueplug.m_power);
+                    rep.setValue("name", "huebulb");
+                    rep.setValue("uri", "/a/huebulb");
+                    rep.setValue("brightness", hueplug.m_bright = 180);
+                    rep.setValue("color", hueplug.m_color);
+                } catch (OcException e) {
+                    Log.e("Felix", e.getMessage());
+                }
+
+                OnPutHuebulb onPut = new OnPutHuebulb();
+                if (hueResource != null) {
+                    Log.i("Felix", "huebulbResource is not null");
+                    try {
+                        hueResource.put(rep, new HashMap<String, String>(),
+                                onPut);
+                    } catch (OcException e) {
+                        e.printStackTrace();
+                    }
+                } else {
+                    Log.i("Felix", "huebulbResource is null");
+                }
+            }
+            onValueChangeThreadStart.put(idx, false);
+        }
+    }
+
+    public void onValueChange(android.widget.NumberPicker picker, int oldVal,
+            int newVal) {
+        final int pickerIdx = picker.getId();
+
+        Thread waitForFinal = new ValueChangeThread(pickerIdx);
+        if (onValueChangeThreadStart.get(pickerIdx) == false)
+            waitForFinal.start();
+
+        onValueChangefinalVal.put(pickerIdx, newVal);
+    }
+}
\ No newline at end of file
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetBelkinplug.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetBelkinplug.java
new file mode 100644 (file)
index 0000000..3e58264
--- /dev/null
@@ -0,0 +1,80 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file OnGetBelkinplug.java
+
+/// @brief This class is OnGetListener for Belkinplug.
+
+package org.iotivity.service.ppm;
+
+import java.util.List;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+public class OnGetBelkinplug implements OcResource.OnGetListener {
+    final private static String TAG = "OnGetBelkinplug";
+
+    @Override
+    public void onGetCompleted(List<OcHeaderOption> headerOptions,
+            OcRepresentation rep) {
+        Log.i(TAG, "GET request Belkin wemo plug was successful");
+        Log.i(TAG, "Resource URI : " + rep.getUri());
+        Log.i(TAG, "power : " + MainActivity.belkinplug.m_power);
+
+        try{
+            MainActivity.belkinplug.m_name = rep.getValue("name");
+            MainActivity.belkinplug.m_power = rep.getValue("power");
+            MainActivity.belkinplug.m_bright = rep.getValue("brightness");
+            MainActivity.belkinplug.m_color = rep.getValue("color");
+            MainActivity.belkinplug.m_uri = rep.getValue("uri");
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+        }
+
+        Log.i(TAG, "name : " + MainActivity.belkinplug.m_name);
+        Log.i(TAG, "power : " + MainActivity.belkinplug.m_power);
+        Log.i(TAG, "brightness : " + MainActivity.belkinplug.m_bright);
+        Log.i(TAG, "color : " + MainActivity.belkinplug.m_color);
+        Log.i(TAG, "uri : " + MainActivity.belkinplug.m_uri);
+
+        Log.e(TAG, "updating display from thread");
+        MainActivity.mActivity.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                MainActivity.updateBelkinStatus();
+            }
+        });
+    }
+
+    @Override
+    public void onGetFailed(Throwable ex) {
+        if (ex instanceof OcException) {
+            OcException ocEx = (OcException) ex;
+            ErrorCode errCode = ocEx.getErrorCode();
+        }
+        Log.e(TAG, ex.toString());
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetGear.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetGear.java
new file mode 100644 (file)
index 0000000..309f1d6
--- /dev/null
@@ -0,0 +1,79 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file OnGetGear.java
+
+/// @brief This class is OnGetListener for Gear.
+
+package org.iotivity.service.ppm;
+
+import java.util.List;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+public class OnGetGear implements OcResource.OnGetListener {
+    final private static String TAG = "OnGetGear";
+
+    @Override
+    public void onGetCompleted(List<OcHeaderOption> headerOptions,
+            OcRepresentation rep) {
+        Log.i(TAG, "GET request Gear was successful");
+
+        try{
+            MainActivity.gearplug.m_name = rep.getValue("name");
+            MainActivity.gearplug.m_power = rep.getValue("power");
+            MainActivity.gearplug.m_bright = rep.getValue("brightness");
+            MainActivity.gearplug.m_color = rep.getValue("color");
+            MainActivity.gearplug.m_uri = rep.getValue("uri");
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+        }
+
+        Log.i(TAG, "name : " + MainActivity.gearplug.m_name);
+        Log.i(TAG, "power : " + MainActivity.gearplug.m_power);
+        Log.i(TAG, "brightness : " + MainActivity.gearplug.m_bright);
+        Log.i(TAG, "color : " + MainActivity.gearplug.m_color);
+        Log.i(TAG, "uri : " + MainActivity.gearplug.m_uri);
+
+        Log.e(TAG, "updating display from thread");
+
+        MainActivity.mActivity.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                MainActivity.updateGearStatus();
+            }
+        });
+    }
+
+    @Override
+    public void onGetFailed(Throwable ex) {
+        if (ex instanceof OcException) {
+            OcException ocEx = (OcException) ex;
+            ErrorCode errCode = ocEx.getErrorCode();
+        }
+        Log.e(TAG, ex.toString());
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetHuebulb.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnGetHuebulb.java
new file mode 100644 (file)
index 0000000..dfb89f0
--- /dev/null
@@ -0,0 +1,79 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file OnGetHueblub.java
+
+/// @brief This class is OnGetListener for Huebulb.
+
+package org.iotivity.service.ppm;
+
+import java.util.List;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+public class OnGetHuebulb implements OcResource.OnGetListener {
+    final private static String TAG = "OnGetHuebulb";
+
+    @Override
+    public void onGetCompleted(List<OcHeaderOption> headerOptions,
+            OcRepresentation rep) {
+        Log.i(TAG, "GET request Hue was successful");
+        Log.i(TAG, "Resource URI : " + rep.getUri());
+
+        try{
+            MainActivity.hueplug.m_name = rep.getValue("name");
+            MainActivity.hueplug.m_power = rep.getValue("power");
+            MainActivity.hueplug.m_bright = rep.getValue("brightness");
+            MainActivity.hueplug.m_color = rep.getValue("color");
+            MainActivity.hueplug.m_uri = rep.getValue("uri");
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+        }
+
+        Log.i(TAG, "name : " + MainActivity.hueplug.m_name);
+        Log.i(TAG, "power : " + MainActivity.hueplug.m_power);
+        Log.i(TAG, "brightness : " + MainActivity.hueplug.m_bright);
+        Log.i(TAG, "color : " + MainActivity.hueplug.m_color);
+        Log.i(TAG, "uri : " + MainActivity.hueplug.m_uri);
+
+        Log.e(TAG, "updating display from thread");
+        MainActivity.mActivity.runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                MainActivity.updateHuebulbStatus();
+            }
+        });
+    }
+
+    @Override
+    public void onGetFailed(Throwable ex) {
+        if (ex instanceof OcException) {
+            OcException ocEx = (OcException) ex;
+            ErrorCode errCode = ocEx.getErrorCode();
+        }
+        Log.e(TAG, ex.toString());
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutBelkinplug.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutBelkinplug.java
new file mode 100644 (file)
index 0000000..c949ca9
--- /dev/null
@@ -0,0 +1,70 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file OnPutBelkinplug.java
+
+/// @brief This class is OnPutListener for Belkinplug.
+
+package org.iotivity.service.ppm;
+
+import java.util.List;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+public class OnPutBelkinplug implements OcResource.OnPutListener {
+    final private static String TAG = "OnPutBelkinplug";
+
+    @Override
+    public void onPutCompleted(List<OcHeaderOption> options,
+            OcRepresentation rep) {
+        Log.i(TAG, "PUT request was successful");
+
+        try{
+            MainActivity.belkinplug.m_name = rep.getValue("name");
+            MainActivity.belkinplug.m_power = rep.getValue("power");
+            MainActivity.belkinplug.m_bright = rep.getValue("brightness");
+            MainActivity.belkinplug.m_color = rep.getValue("color");
+            MainActivity.belkinplug.m_uri = rep.getValue("uri");
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+        }
+
+        Log.i(TAG, "name : " + MainActivity.belkinplug.m_name);
+        Log.i(TAG, "power : " + MainActivity.belkinplug.m_power);
+        Log.i(TAG, "brightness : " + MainActivity.belkinplug.m_bright);
+        Log.i(TAG, "color : " + MainActivity.belkinplug.m_color);
+        Log.i(TAG, "uri : " + MainActivity.belkinplug.m_uri);
+    }
+
+    @Override
+    public void onPutFailed(Throwable ex) {
+        if (ex instanceof OcException) {
+            OcException ocEx = (OcException) ex;
+            ErrorCode errCode = ocEx.getErrorCode();
+        }
+        Log.e(TAG, ex.toString());
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutGear.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutGear.java
new file mode 100644 (file)
index 0000000..081247f
--- /dev/null
@@ -0,0 +1,70 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file OnPutGear.java
+
+/// @brief This class is OnPutListener for Gear.
+
+package org.iotivity.service.ppm;
+
+import java.util.List;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+public class OnPutGear implements OcResource.OnPutListener {
+    final private static String TAG = "OnPutGear";
+
+    @Override
+    public void onPutCompleted(List<OcHeaderOption> options,
+            OcRepresentation rep) {
+        Log.i(TAG, "PUT request was successful");
+
+        try{
+            MainActivity.gearplug.m_name = rep.getValue("name");
+            MainActivity.gearplug.m_power = rep.getValue("power");
+            MainActivity.gearplug.m_bright = rep.getValue("brightness");
+            MainActivity.gearplug.m_color = rep.getValue("color");
+            MainActivity.gearplug.m_uri = rep.getValue("uri");
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+        }
+
+        Log.i(TAG, "name : " + MainActivity.gearplug.m_name);
+        Log.i(TAG, "power : " + MainActivity.gearplug.m_power);
+        Log.i(TAG, "brightness : " + MainActivity.gearplug.m_bright);
+        Log.i(TAG, "color : " + MainActivity.gearplug.m_color);
+        Log.i(TAG, "uri : " + MainActivity.gearplug.m_uri);
+    }
+
+    @Override
+    public void onPutFailed(Throwable ex) {
+        if (ex instanceof OcException) {
+            OcException ocEx = (OcException) ex;
+            ErrorCode errCode = ocEx.getErrorCode();
+        }
+        Log.e(TAG, ex.toString());
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutHuebulb.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/OnPutHuebulb.java
new file mode 100644 (file)
index 0000000..defd511
--- /dev/null
@@ -0,0 +1,70 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file OnPutHuebulb.java
+
+/// @brief This class is OnPutListener for Huebulb.
+
+package org.iotivity.service.ppm;
+
+import java.util.List;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+public class OnPutHuebulb implements OcResource.OnPutListener {
+    final private static String TAG = "OnPutHuebulb";
+
+    @Override
+    public void onPutCompleted(List<OcHeaderOption> options,
+            OcRepresentation rep) {
+        Log.i(TAG, "PUT request was successful");
+
+        try{
+            MainActivity.hueplug.m_name = rep.getValue("name");
+            MainActivity.hueplug.m_power = rep.getValue("power");
+            MainActivity.hueplug.m_bright = rep.getValue("brightness");
+            MainActivity.hueplug.m_color = rep.getValue("color");
+            MainActivity.hueplug.m_uri = rep.getValue("uri");
+        } catch (OcException e) {
+            Log.e(TAG, e.getMessage());
+        }
+
+        Log.i(TAG, "name : " + MainActivity.hueplug.m_name);
+        Log.i(TAG, "power : " + MainActivity.hueplug.m_power);
+        Log.i(TAG, "brightness : " + MainActivity.hueplug.m_bright);
+        Log.i(TAG, "color : " + MainActivity.hueplug.m_color);
+        Log.i(TAG, "uri : " + MainActivity.hueplug.m_uri);
+    }
+
+    @Override
+    public void onPutFailed(Throwable ex) {
+        if (ex instanceof OcException) {
+            OcException ocEx = (OcException) ex;
+            ErrorCode errCode = ocEx.getErrorCode();
+        }
+        Log.e(TAG, ex.toString());
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/Plugin.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/Plugin.java
new file mode 100644 (file)
index 0000000..ae179e2
--- /dev/null
@@ -0,0 +1,160 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file Plugin.java
+
+/// @brief This class provides information of each plugin installed for JAVA.
+
+package org.iotivity.service.ppm;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Vector;
+
+public class Plugin {
+
+    private Map<String, String> m_attributeMap;
+    private Vector<String>      m_supportedType;
+
+    /**
+     * Constructor for Plugin.
+     *
+     */
+    public Plugin() {
+        m_attributeMap = new HashMap<String, String>();
+        m_supportedType = new Vector<String>();
+    }
+
+    /**
+     * Constructor for Plugin(Overlading).
+     *
+     * @param Plugin's name and id Strings.
+     */
+    public Plugin(String name, String id) {
+        this();
+        setValue("Name", name);
+        setValue("Id", id);
+    }
+
+    /**
+     * Get unique ID of the plugin.
+     *
+     * @return unique id String of the plugin. if ID is not exist, it return "".
+     */
+    public String getID() {
+        Iterator<Entry<String, String>> m_iterator = m_attributeMap.entrySet()
+                .iterator();
+
+        while (m_iterator.hasNext()) {
+            Entry<String, String> entryMap = m_iterator.next();
+            if (entryMap.getKey().equals("Id"))
+                return entryMap.getValue();
+        }
+        return "";
+    }
+
+    /**
+     * Get version of the plugin.
+     *
+     * @return version information String of the plugin. if Version is not
+     *         exist, it return "".
+     */
+    public String getVersion() {
+        Iterator<Entry<String, String>> m_iterator = m_attributeMap.entrySet()
+                .iterator();
+
+        while (m_iterator.hasNext()) {
+            Entry<String, String> entryMap = m_iterator.next();
+            if (entryMap.getKey().equals("Version"))
+                return entryMap.getValue();
+        }
+        return "";
+    }
+
+    /**
+     * Get name of the plugin.
+     *
+     * @return name String of the plugin. if Name is not exist, it return "".
+     */
+    public String getName() {
+        Iterator<Entry<String, String>> m_iterator = m_attributeMap.entrySet()
+                .iterator();
+
+        while (m_iterator.hasNext()) {
+            Entry<String, String> entryMap = m_iterator.next();
+            if (entryMap.getKey().equals("Name"))
+                return entryMap.getValue();
+        }
+        return "";
+    }
+
+    /**
+     * Get provider name of the plugin.
+     *
+     * @return provider name of the plugin. if ProviderName is not exist, it
+     *         return "".
+     */
+    public String getProviderName() {
+        Iterator<Entry<String, String>> m_iterator = m_attributeMap.entrySet()
+                .iterator();
+
+        while (m_iterator.hasNext()) {
+            Entry<String, String> entryMap = m_iterator.next();
+            if (entryMap.getKey().equals("Provider"))
+                return entryMap.getValue();
+        }
+        return "";
+    }
+
+    /**
+     * Get value for the attributes.
+     *
+     * @param attriubute
+     *            String to get value.
+     * @return value String of the attribute. if "attribute" is not exist, it
+     *         return "".
+     */
+    public String getValueByAttribute(String attribute) {
+        Iterator<Entry<String, String>> m_iterator = m_attributeMap.entrySet()
+                .iterator();
+
+        while (m_iterator.hasNext()) {
+            Entry<String, String> entryMap = m_iterator.next();
+            if (entryMap.getKey().equals(attribute))
+                return entryMap.getValue();
+        }
+        return "";
+    }
+
+    /**
+     * Set key, value. key is attribute name.
+     *
+     * @param key
+     *            is atrribute name.
+     * @param value
+     *            for the attribute.
+     * @return void.
+     */
+    public void setValue(String key, String value) {
+        m_attributeMap.put(key, value);
+    }
+}
diff --git a/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/PluginManager.java b/service/protocol-plugin/plugin-manager/src/Android/src/org/iotivity/service/ppm/PluginManager.java
new file mode 100644 (file)
index 0000000..ad875d9
--- /dev/null
@@ -0,0 +1,108 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file PluginManager.java
+
+/// @brief After installing a plug-in in a directory, each plug-in can be managed by this class.
+
+package org.iotivity.service.ppm;
+
+import android.content.Context;
+import android.util.Log;
+
+public class PluginManager {
+
+    /**
+    * Start plug-ins by key-value pair.
+    *
+    * @param key    - key information of the plug-in to be started.
+    * @param value   - value information of the plug-in to be started.
+    * @return int   - 1 on success or 0 on failure.
+    */
+    public int startPlugins(String key, String value) {
+        LogEx("startPlugins() Called.");
+        return jniStartPlugins(key, value);
+    }
+
+    /**
+    * Stop plug-ins by key-value pair.
+    *
+    * @param key    - key information of the plug-in to be stopped.
+    * @param value   - value information of the plug-in to be stopped.
+    * @return int   - 1 on success or 0 on failure.
+    */
+    public int stopPlugins(String key, String value) {
+        LogEx("stopPlugins() Called.");
+        return jniStopPlugins(key, value);
+    }
+
+    /**
+    * Rescan for plug-ins in the registered directory and install plug-ins.
+    *
+    * @param void
+    * @return int   - 1 on success or 0 on failure.
+    */
+    public int rescanPlugin() {
+        LogEx("rescanPlugin() Called.");
+        return jniRescanPlugin();
+    }
+
+    /**
+    * Get list of plug-ins.
+    *
+    * @param void
+    * @return Plugin[]   - Plug-in array.
+    */
+    public Plugin[] getPlugins() {
+        LogEx("getPlugins() Called.");
+        return jniGetPlugins();
+    }
+
+    /**
+    * Get state of the plug-in.
+    *
+    * @param pluginID       - ID of the plug-in to get state.
+    * @return String   - state of the plug-in.
+    */
+    public String getState(String plugID) {
+        LogEx("getState() Called.");
+        return jniGetState(plugID);
+    }
+
+    public PluginManager(Context ctx) {
+        LogEx("PluginManager() Called.");
+        FelixManager.getInstance(ctx);
+        System.loadLibrary("PluginManager");
+    }
+
+    private native int jniStartPlugins(String key, String value);
+
+    private native int jniStopPlugins(String key, String value);
+
+    private native int jniRescanPlugin();
+
+    private native Plugin[] jniGetPlugins();
+
+    private native String jniGetState(String plugID);
+
+    private static void LogEx(String info) {
+        Log.d("PluginManager.java", info);
+    }
+}
index d473421..963c89e 100644 (file)
@@ -20,7 +20,7 @@
 
 /// @file Config.cpp
 
-/// @brief
+/// @brief Config class reads pluginmanager.xml file and configures PPM
 
 
 #include "Config.h"
@@ -32,9 +32,33 @@ using namespace std;
 
 Config *Config::s_configinstance = NULL;
 
-Config::Config()
+Config::Config(void *args)
 {
-    if (loadConfigFile("./pluginmanager.xml") != PM_S_OK)
+    std::string path = ".";
+/**
+ * For Tizen Platform, specifiy the absolute location of config file. It is required for
+ * Tizen 2.3 EFL App to work.
+ */
+#ifdef __TIZEN__
+    if (loadConfigFile("/opt/usr/apps/org.iotivity.service.ppm.ppmsampleapp/lib/pluginmanager.xml")
+                                                                                        != PM_S_OK)
+#else
+#ifdef ANDROID
+    JavaVM *jvm = (JavaVM *)args;
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "getPackageName", "()Ljava/lang/String;");
+    jstring jpath = (jstring)env->CallStaticObjectMethod(cls, mid);
+    path = env->GetStringUTFChars(jpath, 0);
+
+    if(path != ".")
+        path = "/data/data/" + path + "/files";
+#endif
+
+    if (loadConfigFile(path + "/pluginmanager.xml") != PM_S_OK)
+#endif //#ifdef __TIZEN__
     {
         fprintf(stderr, "PM Configuration file is not exist current Folder.\n" );
         exit(EXIT_FAILURE);
@@ -43,44 +67,56 @@ Config::Config()
 
 Config::~Config(void)
 {
-    s_configinstance->deleteinstance();
-    s_configinstance = NULL;
+    if (s_configinstance) 
+    {
+        s_configinstance->deleteinstance();
+        s_configinstance = NULL;
+    }
 }
 
 PMRESULT Config::loadConfigFile(const std::string configfilepath)
 {
     // Read the xml file
-    std::ifstream xmlFile(configfilepath.c_str());
-    if(!xmlFile.good())
+   xml_document< char > doc;
+    std::basic_ifstream< char > xmlFile(configfilepath.c_str());
+    if (!xmlFile.good())
     {
         return PM_S_FALSE;
     }
-    xml_document<> doc;
-    //into a vector
-    std::vector<char> buffer((istreambuf_iterator<char>(xmlFile)), istreambuf_iterator<char>());
-    buffer.push_back('\0');
 
-    // Parse the buffer using the xml file parsing library into doc
-    parsing(buffer, &doc);
+    xmlFile.seekg(0, std::ios::end);
+    unsigned int size = (unsigned int)xmlFile.tellg();
+    xmlFile.seekg(0);
+
+    std::vector< char > xmlData(size + 1);
+    xmlData[size] = 0;
+
+    xmlFile.read(&xmlData.front(), (std::streamsize)size);
+    xmlFile.close();
+
+    // Parse the xmlData using the xml file parsing library into doc
+    parsing(&xmlData.front(), &doc);
 
     // Find our root node
-    xml_node<> *root_node = doc.first_node("pluginManager");
-    xml_node<> *pluginInfo = root_node->first_node("pluginInfo");
+    xml_node< char > *root_node = doc.first_node("pluginManager");
+    if(!root_node)
+    {
+        throw parse_error("No Root Element", 0);
+    }
+
+    xml_node< char > *pluginInfo = root_node->first_node("pluginInfo");
 
     getXmlData(pluginInfo, "pluginPath");
-    getXmlData(pluginInfo, "maxMEM");
-    getXmlData(pluginInfo, "version");
-    getXmlData(pluginInfo, "name");
 
     return PM_S_OK;
 }
 
-PMRESULT Config::parsing(std::vector<char> buffer, xml_document<> *doc)
+PMRESULT Config::parsing(char *xmlData, xml_document<> *doc)
 {
-    // Parse the buffer using the xml file parsing library into doc
+    // Parse the xmlData using the xml file parsing library into doc
     try
     {
-        doc->parse<0>(&buffer[0]);
+        doc->parse< 0 >(xmlData);
     }
     catch (rapidxml::parse_error err)
     {
@@ -112,10 +148,11 @@ void Config::setValue(const std::string key, const std::string value)
     m_configurationMap.insert( std::pair<std::string, std::string>(key, value));
 }
 
-std::string  Config::getValue(const std::string key)
+std::string Config::getValue(const std::string key)
 {
     std::map<std::string, std::string>::iterator m_iterator;
 
+    // Find the value for key
     m_iterator = m_configurationMap.find(key.c_str());
 
     if (m_iterator != m_configurationMap.end())
@@ -128,10 +165,11 @@ std::string  Config::getValue(const std::string key)
     }
 }
 
-std::string  Config::getVersion()
+std::string Config::getVersion()
 {
     std::map<std::string, std::string>::iterator m_iterator;
 
+    // Find the value for key - version
     m_iterator = m_configurationMap.find("version");
 
     if (m_iterator != m_configurationMap.end())
@@ -144,10 +182,11 @@ std::string  Config::getVersion()
     }
 }
 
-std::string  Config::getPluginPath()
+std::string Config::getPluginPath()
 {
     std::map<std::string, std::string>::iterator m_iterator;
 
+    // Find the value for key - pluginPath
     m_iterator = m_configurationMap.find("pluginPath");
 
     if (m_iterator != m_configurationMap.end())
index 33f7f39..553f0d1 100644 (file)
@@ -32,6 +32,9 @@
 #include "rapidxml.hpp"
 #include <fstream>
 #include <vector>
+#ifdef ANDROID
+#include <jni.h>
+#endif
 
 using namespace rapidxml;
 
@@ -72,11 +75,11 @@ namespace OIC
             *
             * @return config pointer Address.
             */
-            static Config *Getinstance()
+            static Config *Getinstance(void *args = NULL)
             {
                 if (NULL == s_configinstance)
                 {
-                    s_configinstance = new Config();
+                    s_configinstance = new Config(args);
                 }
 
                 return s_configinstance;
@@ -89,12 +92,13 @@ namespace OIC
             static Config *s_configinstance;
             typedef std::map<std::string, std::string> configmap;
             configmap m_configurationMap;
+
             /**
             * Constructor for Config.
             * During construction time, configuration file  will be loaded.
             *
             */
-            Config();
+            Config(void *args = NULL);
 
             /**
             * Virtual destructor
@@ -114,9 +118,9 @@ namespace OIC
             }
             void setValue(const std::string key, const std::string value);
             PMRESULT loadConfigFile(const std::string configfilepath);
-            PMRESULT parsing(std::vector<char> buffer, xml_document<> *doc);
+            PMRESULT parsing(char *xmlData, xml_document<> *doc);
             PMRESULT getXmlData(  xml_node<> *pluginInfo, std::string key);
     };
 }
 
-#endif
\ No newline at end of file
+#endif
index 3acd2f5..8db6d6e 100644 (file)
@@ -28,14 +28,14 @@ using namespace OIC;
 
 CpluffAdapter *CpluffAdapter::s_pinstance;
 
-CpluffAdapter::CpluffAdapter()
+CpluffAdapter::CpluffAdapter(void *args)
 {
     m_status = cp_init();
     m_context = cp_create_context(&m_status);
     m_cp_plugins = nullptr;
     m_plugin = nullptr;
 
-    config = Config::Getinstance();
+    config = Config::Getinstance(args);
     std::string pluginpath = config->getPluginPath();
     if (pluginpath != "")
     {
@@ -211,7 +211,6 @@ int CpluffAdapter::loadPluginInfoToManager(const std::string path)
             m_plugins.push_back(*plugin);
             delete(plugin);
         }
-        //printf("plugin size = %d\n",m_plugins.size());
     }
 
     return TRUE;
@@ -219,7 +218,6 @@ int CpluffAdapter::loadPluginInfoToManager(const std::string path)
 
 int CpluffAdapter::registerPlugin(const std::string path)
 {
-    //printf("CpluffAdapter register\n");
     int flag = FALSE;
 
     if (path == "")
@@ -238,7 +236,6 @@ int CpluffAdapter::registerPlugin(const std::string path)
 
 int CpluffAdapter::registerAllPlugin(const std::string path)
 {
-    //printf("CpluffAdapter register\n");
     int flag = FALSE;
     if (path == "")
     {
@@ -324,6 +321,7 @@ std::vector<Plugin> *CpluffAdapter::findPlugins(const std::string key, const std
 
     return re_plugins;
 }
+
 /*
 Plugin *CpluffAdapter::getPlugin(const std::string plugID)
 {
@@ -338,6 +336,7 @@ Plugin *CpluffAdapter::getPlugin(const std::string plugID)
     return nullptr;
 }
 */
+
 bool CpluffAdapter::getFileList(File_list &list, const std::string strDir)
 {
     struct stat statinfo;
@@ -445,21 +444,14 @@ void CpluffAdapter::printPluginList()
 
 int CpluffAdapter::start(Plugin *const plugin, void *const arg)
 {
-    //printf("start\n");
     std::string id;
     cp_status_t status;
-    cp_context_t *ctx;
 
     id = plugin->getID();
     for (unsigned int i = 0 ; i < m_plugins.size(); i++)
     {
         if (*plugin == m_plugins[i])
         {
-            ctx = cpi_new_context((cp_plugin_t *)hnode_get(hash_lookup(m_context->env->plugins, id.c_str())),
-                                  m_context->env, &status);
-            //cp_define_symbol(ctx, "START_ARGUMENT", arg);
-            //printf("start ocplatform address : %x\n", arg);
-
             if ((status = cp_start_plugin(m_context, (char *)id.c_str()) ) != CP_OK)
             {
                 printf("API function CpluffAdapter::start() faild with error code.\n");
@@ -510,18 +502,17 @@ bool CpluffAdapter::isStarted(Plugin *plugin)
     }
     return FALSE;
 }
-//Auto plugin detection is disabled
+
+// Auto plugin detection is disabled
 /*
 void CpluffAdapter::observePluginPath(void *str)
 {
-    //printf("start observePluginPath\n");
     int length;
     int i = 0;
     int fd;
     int wd;
     char *str1 = (char *)str;
     std::string original_path(str1);
-    //printf("Directory is %s\n",(char*)str1));
     char buffer[BUF_LEN];
 
     fd = inotify_init();
@@ -546,7 +537,6 @@ void CpluffAdapter::observePluginPath(void *str)
             printf("observePluginPath read\n");
         }
         std::string filepath = original_path;
-        //printf("filepath = %s\n",filepath.c_str());
         while ( i < length )
         {
             if (i < (signed)(BUF_LEN  - ( sizeof( struct inotify_event) + 16)) && i > -1)
@@ -559,12 +549,8 @@ void CpluffAdapter::observePluginPath(void *str)
                 }
                 else
                 {
-                    //filepath += "/";
-                    //filepath += std::string(event->name);
                     std::vector<Plugin> *resource_plugin = findPlugins("Path", filepath.c_str()); //add foldername
 
-                    //printf("plugin size is %d\n",resource_plugin->size());
-                    //printf("plugin file path is %s\n",resource_plugin->());
                     if (resource_plugin->size() == 1)
                     {
                         unregisterPlugin(&(resource_plugin->at(0)));
@@ -576,8 +562,6 @@ void CpluffAdapter::observePluginPath(void *str)
                     delete(resource_plugin);
                     resource_plugin = nullptr;
                 }
-                //printf("observePluginPath path = %s \n",str1);
-                //printf("observePluginPath directory name = %s \n",event->name);
                 i += EVENT_SIZE + event->len;
             }
         }
@@ -586,9 +570,9 @@ void CpluffAdapter::observePluginPath(void *str)
     }
     ( void ) inotify_rm_watch( fd, wd );
     ( void ) close( fd );
-    //printf("observePluginPath end\n");
 }
 */
+
 const std::string CpluffAdapter::getState(const std::string plugID)
 {
     return state_to_string(cp_get_plugin_state(m_context, plugID.c_str()));
index 6c108d0..2248665 100644 (file)
@@ -24,7 +24,9 @@
 
 #ifndef __CPLUFFADAPTER_H
 #define __CPLUFFADAPTER_H
+#ifndef DLOPEN_POSIX
 #define DLOPEN_POSIX
+#endif
 
 #include <vector>
 #include <dirent.h>
@@ -173,11 +175,11 @@ namespace OIC
             *
             * @return OICPluginManager pointer Address.
             */
-            static CpluffAdapter *Getinstance()
+            static CpluffAdapter *Getinstance(void *args = NULL)
             {
                 if (NULL == s_pinstance)
                 {
-                    s_pinstance = new CpluffAdapter();
+                    s_pinstance = new CpluffAdapter(args);
                 }
 
                 return s_pinstance;
@@ -202,7 +204,7 @@ namespace OIC
             * During construction time, all plugins under the root plugin path will be loaded.
             *
             */
-            CpluffAdapter();
+            CpluffAdapter(void *args = NULL);
 
             /**
             * Virtual destructor
index 50a92e2..44df0bf 100644 (file)
 /// @brief
 
 #include "FelixAdapter.h"
+#include <sstream>
 
 using namespace OIC;
 
 FelixAdapter *FelixAdapter::s_pinstance;
 
-FelixAdapter::FelixAdapter()
+FelixAdapter::FelixAdapter(JavaVM *args)
 {
-    config = Config::Getinstance();
+    jvm = args;
+
+    config = Config::Getinstance(args);
     std::string pluginpath = config->getPluginPath();
     if (pluginpath != "")
     {
@@ -38,7 +41,7 @@ FelixAdapter::FelixAdapter()
     }
     else
     {
-        fprintf(stderr, "Pluing path is not exist\n");
+        fprintf(stderr, "Pluin path does not exist\n");
         pluginpath = "";
     }
     registerAllPlugin(pluginpath);
@@ -46,7 +49,9 @@ FelixAdapter::FelixAdapter()
 
 FelixAdapter::~FelixAdapter(void)
 {
+
     s_pinstance->deleteinstance();
+    s_pinstance = NULL;
 }
 
 int FelixAdapter::installPlugin(const std::string path)
@@ -66,32 +71,187 @@ int FelixAdapter::loadPluginInfoToManager(const std::string path)
 
 int FelixAdapter::registerPlugin(const std::string path)
 {
-    return 1;
+    if (path == "")
+    {
+        printf("FelixAdapter path == null\n");
+        return 0;
+    }
+
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    jstring jpath = env->NewStringUTF(path.c_str());
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "registerPlugin", "(Ljava/lang/String;)I");
+
+    // call registerPlugin() function
+    return  (int)env->CallStaticIntMethod(cls, mid, jpath);
 }
 
 int FelixAdapter::registerAllPlugin(const std::string path)
 {
-    return 1;
+    if (path == "")
+    {
+        printf("FelixAdapter path == null\n");
+        return 0;
+    }
+
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    jstring jpath = env->NewStringUTF(path.c_str());
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "registerAllPlugin", "(Ljava/lang/String;)I");
+
+    // call registerAllPlugin() function
+    return (int)env->CallStaticIntMethod(cls, mid, jpath);
 }
 
 int FelixAdapter::unregisterPlugin(Plugin *const plugin)
 {
-    return 1;
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    const char *cpath = plugin->getID().c_str();
+    jstring jpath = env->NewStringUTF(cpath);
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "unregisterPlugin", "(Ljava/lang/String;)I");
+
+    // call unregisterPlugin() function
+    return (int)env->CallStaticIntMethod(cls, mid, jpath);
 }
 
 int FelixAdapter::unregisterAllPlugin(void)
 {
-    return 1;
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "unregisterAllPlugin", "()I");
+
+    // call registerAllPlugin() function
+    return (int)env->CallStaticIntMethod(cls, mid);
 }
 
 std::vector<Plugin> &FelixAdapter::getAllPlugins(void)
 {
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "getAllPlugins", "()[Lorg/osgi/framework/Bundle;");
+
+    // call getAllPlugins() function
+    jobjectArray jresultArray = (jobjectArray)env->CallStaticObjectMethod(cls, mid);
+    jint size = env->GetArrayLength(jresultArray);
+    m_plugins.clear();
+
+    for (int i = 0; i < (int)size; i++)
+    {
+        Plugin *plugin = new Plugin;
+
+        jobject result = env->GetObjectArrayElement(jresultArray, i);
+        cls = env->GetObjectClass(result);
+        // set Language value
+        plugin->setValue("Language", "JAVA");
+        // set Id value
+        mid = env->GetMethodID(cls, "getSymbolicName", "()Ljava/lang/String;");
+        jstring jid = (jstring)env->CallObjectMethod(result, mid);
+        std::string id = env->GetStringUTFChars(jid, 0);
+        plugin->setValue("Id", id);
+        // set Version value
+        mid = env->GetMethodID(cls, "getVersion", "()Lorg/osgi/framework/Version;");
+        jobject jversion_object = env->CallObjectMethod(result, mid);
+        jclass vcls = env->GetObjectClass(jversion_object);
+        mid = env->GetMethodID(vcls, "toString", "()Ljava/lang/String;");
+        jstring jversion = (jstring)env->CallObjectMethod(jversion_object, mid);
+        std::string version = env->GetStringUTFChars(jversion, 0);
+        plugin->setValue("Version", version);
+        // set Name value
+        cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+        mid = env->GetStaticMethodID(cls, "getValue",
+                                     "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
+        std::string key = "Name";
+        jstring jname = (jstring)env->CallStaticObjectMethod(cls, mid, jid, 
+                        env->NewStringUTF(key.c_str()));
+        std::string name = env->GetStringUTFChars(jname, 0);
+        plugin->setValue("Name", name);
+        // set ResourceType value
+        key = "ResourceType";
+        jstring jresourcetype = (jstring)env->CallStaticObjectMethod(cls, mid, jid,
+                                env->NewStringUTF(key.c_str()));
+        std::string resourcetype = env->GetStringUTFChars(jresourcetype, 0);
+        plugin->setValue("ResourceType", resourcetype);
+        // push the plugin into the vector
+        m_plugins.push_back(*plugin);
+    }
+
     return m_plugins;
 }
 
 std::vector<Plugin> *FelixAdapter::findPlugins(const std::string key, const std::string value)
 {
-    return nullptr;
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    jstring jkey = env->NewStringUTF(key.c_str());
+    jstring jvalue = env->NewStringUTF(value.c_str());
+
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "findPlugins",
+                        "(Ljava/lang/String;Ljava/lang/String;)[Lorg/osgi/framework/Bundle;");
+
+    // call findPlugins() function
+    jobjectArray jresultArray = (jobjectArray)env->CallStaticObjectMethod(cls, mid, (jstring)jkey,
+                                (jstring)jvalue);
+
+    jint size = env->GetArrayLength(jresultArray);
+
+    std::vector<Plugin> *re_plugins;
+    re_plugins = new std::vector<Plugin>;
+
+    for (int i = 0; i < (int)size; i++)
+    {
+        Plugin *plugin = new Plugin;
+
+        jobject result = env->GetObjectArrayElement(jresultArray, i);
+        cls = env->GetObjectClass(result);
+        // set Language value
+        plugin->setValue("Language", "JAVA");
+        // set Id value
+        mid = env->GetMethodID(cls, "getSymbolicName", "()Ljava/lang/String;");
+        jstring jid = (jstring)env->CallObjectMethod(result, mid);
+        std::string id = env->GetStringUTFChars(jid, 0);
+        plugin->setValue("Id", id);
+        // set Version value
+        mid = env->GetMethodID(cls, "getVersion", "()Lorg/osgi/framework/Version;");
+        jobject jversion_object = env->CallObjectMethod(result, mid);
+        jclass vcls = env->GetObjectClass(jversion_object);
+        mid = env->GetMethodID(vcls, "toString", "()Ljava/lang/String;");
+        jstring jversion = (jstring)env->CallObjectMethod(jversion_object, mid);
+        std::string version = env->GetStringUTFChars(jversion, 0);
+        plugin->setValue("Version", version);
+        // set Name value
+        cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+        mid = env->GetStaticMethodID(cls, "getValue",
+                    "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
+        std::string key = "Name";
+        jstring jname = (jstring)env->CallStaticObjectMethod(cls, mid, jid, 
+                        env->NewStringUTF(key.c_str()));
+        std::string name = env->GetStringUTFChars(jname, 0);
+        plugin->setValue("Name", name);
+        // set ResourceType value
+        key = "ResourceType";
+        jstring jresourcetype = (jstring)env->CallStaticObjectMethod(cls, mid, jid,
+                                env->NewStringUTF(key.c_str()));
+        std::string resourcetype = env->GetStringUTFChars(jresourcetype, 0);
+        plugin->setValue("ResourceType", resourcetype);
+        // push the plugin into the vector
+        m_plugins.push_back(*plugin);
+    }
+
+    return re_plugins;
 }
 /*
 Plugin *FelixAdapter::getPlugin(const std::string plugID)
@@ -112,25 +272,64 @@ void FelixAdapter::printPluginList(cp_plugin_info_t **plugins)
 
 int FelixAdapter::start(Plugin *const plugin, void *const arg)
 {
-    return TRUE;
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    const char *cid = plugin->getID().c_str();
+    jstring jid = env->NewStringUTF(cid);
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "start", "(Ljava/lang/String;)I");
+
+    // call start() function
+    return (int)env->CallStaticIntMethod(cls, mid, jid);
 }
 
 int FelixAdapter::stop(Plugin *const plugin)
 {
-    return TRUE;
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    const char *cid = plugin->getID().c_str();
+    jstring jid = env->NewStringUTF(cid);
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "stop", "(Ljava/lang/String;)I");
+
+    // call stop() function
+    return (int)env->CallStaticIntMethod(cls, mid, jid);
 }
 
 bool FelixAdapter::isStarted(Plugin *plugin)
 {
-    return FALSE;
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    const char *cid = plugin->getID().c_str();
+    jstring jid = env->NewStringUTF(cid);
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "isStarted", "(Ljava/lang/String;)Z");
+
+    // call isStarted() function
+    return (bool)env->CallStaticBooleanMethod(cls, mid, jid);
 }
+
 /*
 void FelixAdapter::observePluginPath(void *str)
 {
 
 }
 */
+
 const std::string FelixAdapter::getState(const std::string plugID)
 {
-    return "";
+    JNIEnv *env;
+    jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+
+    jstring jplugID = env->NewStringUTF(plugID.c_str());
+    jclass cls = env->FindClass("org/iotivity/service/ppm/FelixManager");
+    jmethodID mid = env->GetStaticMethodID(cls, "getState", 
+                    "(Ljava/lang/String;)Ljava/lang/String;");
+
+    // call getState() function
+    jstring jresult = (jstring)env->CallStaticObjectMethod(cls, mid, jplugID);
+    return env->GetStringUTFChars(jresult, 0);
 }
\ No newline at end of file
index 7f03f7f..f4d655d 100644 (file)
@@ -24,7 +24,9 @@
 
 #ifndef __FELIXADAPTER_H__
 #define __FELIXADAPTER_H__
+#ifndef DLOPEN_POSIX
 #define DLOPEN_POSIX
+#endif
 
 #include <vector>
 #include <dirent.h>
@@ -35,6 +37,7 @@
 #include <boost/thread.hpp>
 #include <boost/bind.hpp>
 #include <internal.h>
+#include <jni.h>
 
 #include "Plugin.h"
 #include "Config.h"
@@ -166,11 +169,11 @@ namespace OIC
             *
             * @return OICPluginManager pointer Address.
             */
-            static FelixAdapter *Getinstance()
+            static FelixAdapter *Getinstance(void *args = NULL)
             {
                 if (NULL == s_pinstance)
                 {
-                    s_pinstance = new FelixAdapter();
+                    s_pinstance = new FelixAdapter((JavaVM *)args);
                 }
 
                 return s_pinstance;
@@ -179,18 +182,12 @@ namespace OIC
 
 
         private:
+            JavaVM *jvm;
             Config *config;
             typedef std::map<std::string, bool> File_list;
             std::vector<Plugin> m_plugins;
             boost::thread m_file_detect_thread;
-            /*
-            cp_context_t *m_context;
-            cp_status_t m_status;
-            cp_plugin_info_t **m_cp_plugins;
-            cp_plugin_info_t *m_plugin;
-            boost::thread_group m_thread_g;
-            std::string m_path;
-            */
+
             static FelixAdapter *s_pinstance;
 
             /**
@@ -198,7 +195,7 @@ namespace OIC
             * During construction time, all plugins under the root plugin path will be loaded.
             *
             */
-            FelixAdapter();
+            FelixAdapter(JavaVM *);
 
             /**
             * Virtual destructor
index d360cf0..6b4b1c7 100644 (file)
@@ -73,68 +73,67 @@ namespace OIC
             */
             virtual ~Plugin(void);
 
+
             /**
-            * Get unique ID of the plug-in
+            * Get unique ID of the plugin.
             *
-            * @return unique id string of the pluin. if ID is not exist, it return ""
+            * @return unique id string of the pluin. if ID is not exist, it return "".
             */
             std::string getID(void);
 
 
             /**
-            * Get version of the plug-in
-            *
-            * @return version information string of the plugin. if Version is not exist, it return ""
+            * Get version of the plugin.
             *
+            * @return version information string of the plugin. if Version is not exist, it return "".
             */
             std::string getVersion(void);
 
 
             /**
-            * Get name of the plug-in
+            * Get name of the plugin.
             *
-            * @return name string of the plugin. if Name is not exist, it return ""
+            * @return name string of the plugin. if Name is not exist, it return "".
             */
             std::string getName(void);
 
 
             /**
-            * Get provider name of the plug-in
-            *
-            * @return provider name of the plugin. if ProviderName is not exist, it return ""
+            * Get provider name of the plugin.
             *
+            * @return provider name of the plugin. if ProviderName is not exist, it return "".
             */
             std::string getProviderName(void);
 
 
             /**
-            * Get value for the attributes
-            *
-            * @param attribute attriubute string to get value
-            * @return value of the attribute. if "attribute" is not exist, it return ""
+            * Get value for the attributes.
             *
+            * @param attriubute string to get value.
+            * @return value of the attribute. if "attribute" is not exist, it return "".
             */
             std::string getValueByAttribute(const std::string attribute);
 
+
             /**
             * Check whether the plugin same or not.
             *
-            * @param plugin
-            * @return true if same, else return false
-            *
+            * @param plugin.
+            * @return true if same, else return false.
             */
             bool operator==(Plugin &plugin);
 
         private:
             friend class CpluffAdapter;
             friend class FelixAdapter;
-              /**
+
+
+            /**
             * Set key, value. key is attribute name.
             *
             * @param key is atrribute name.
             * @param value for the attribute.
-            * @return void
-            *
+            * @return void.
             */
             void setValue(const std::string key, const std::string value);
 
index 7e0f0ed..43b41a8 100644 (file)
@@ -29,22 +29,32 @@ using namespace OIC;
 
 PluginManager::PluginManager()
 {
+/**
+ * For Tizen Platform, specifiy the absolute location of dynamic library. It is required for
+ * Tizen 2.3 EFL App to work.
+ */
+#ifdef __TIZEN__
+    handle = dlopen("/opt/usr/apps/org.iotivity.service.ppm.ppmsampleapp/lib/libpmimpl.so",
+                                                                                        RTLD_LAZY);
+#else
     handle = dlopen("./libpmimpl.so", RTLD_LAZY);
+#endif //#ifdef __TIZEN__
+
     if (!handle)
     {
         fprintf(stderr, "%s\n", dlerror());
         exit(EXIT_FAILURE);
     }
-    PluginManagerImpl* (*create)();
-    create = (PluginManagerImpl * (*)())dlsym(handle, "create_object");
+    PluginManagerImpl* (*create)(void *);
+    create = (PluginManagerImpl * (*)(void *))dlsym(handle, "create_object");
     destroy = (void (*)(PluginManagerImpl *))dlsym(handle, "destroy_object");
-    pluginManagerImpl = (PluginManagerImpl *)create();
+    pluginManagerImpl = (PluginManagerImpl *)create(NULL);
 }
 
 PluginManager::~PluginManager(void)
 {
     destroy(pluginManagerImpl);
-    free(handle);
+    dlclose(handle);
 }
 
 int PluginManager::startPlugins(const std::string key, const std::string value)
index 12c11ab..f1fe50f 100644 (file)
@@ -24,7 +24,9 @@
 
 #ifndef __PLUGINMANAGER_H
 #define __PLUGINMANAGER_H
+#ifndef DLOPEN_POSIX
 #define DLOPEN_POSIX
+#endif
 
 #include <vector>
 #include <dirent.h>
@@ -51,19 +53,20 @@ namespace OIC
             * Virtual destructor
             */
             ~PluginManager(void);
+
             /**
-            * Start  plugins by resource type
-            *
-            * @param type resouce type string to be started.
+            * Start plugins by key-value pair.
             *
+            * @param key-value pair string to be started.
+            * @return int, 1 is success, 0 is fail.
             */
             int startPlugins(const std::string key, const std::string value);
 
             /**
-            * Stop  plugins by resource type
-            *
-            * @param type resouce type string to be started.
+            * Stop plugins by key-value pair.
             *
+            * @param key-value pair string to be stopped.
+            * @return int, 1 is success, 0 is fail.
             */
             int stopPlugins(const std::string key, const std::string value);
 
@@ -71,25 +74,24 @@ namespace OIC
             * Rescan Plugin.
             * This function will call rescan function of plugins in the configuration folder
             *
-            * @param Plugin
+            * @param void.
             * @return int, 1 is success, 0 is fail.
             */
-            int rescanPlugin();
+            int rescanPlugin(void);
 
             /**
             * Get Plugin list.
             *
-            *
-            *
-            * @return
+            * @param void.
+            * @return Plugin vector
             */
             std::vector<Plugin> getPlugins(void);
 
             /**
             * Get Plugin state.
             *
-            * @param Plugin ID
-            * @return Plugin state.
+            * @param Plugin ID string.
+            * @return Plugin state string.
             */
             std::string getState(const std::string plugID);
 
@@ -99,4 +101,4 @@ namespace OIC
             void *handle;
     };
 }
-#endif //__PLUGINMANAGER_H
+#endif //__PLUGINMANAGER_H
\ No newline at end of file
index 1f527fb..19bfc42 100644 (file)
 
 /// @file PluginManagerImpl.cpp
 
-/// @brief
+/// @brief PluginManagerImple provides abstraction of the plugin manager interface
 
 #include "PluginManagerImpl.h"
 
 using namespace OIC;
 
-PluginManagerImpl *PluginManagerImpl::s_pinstance = nullptr;
+PluginManagerImpl *PluginManagerImpl::s_pinstance = NULL;
 
-extern "C" PluginManagerImpl *create_object()
+extern "C" PluginManagerImpl *create_object(void *args)
 {
     PluginManagerImpl *newobj;
-    newobj =  new PluginManagerImpl;
+    newobj =  new PluginManagerImpl(args);
     return newobj;
 }
 
@@ -40,10 +40,21 @@ extern "C" void destroy_object( PluginManagerImpl *object )
     delete object;
 }
 
-PluginManagerImpl::PluginManagerImpl()
+PluginManagerImpl::PluginManagerImpl(void *args)
 {
-    cppm = CpluffAdapter::Getinstance();
-    javappm = FelixAdapter::Getinstance();
+#ifndef ANDROID
+        m_args = args;
+        cppm = CpluffAdapter::Getinstance();
+#endif
+#ifdef ANDROID
+    m_args = args;
+    cppm = CpluffAdapter::Getinstance(args);
+    if (args)
+        javappm = FelixAdapter::Getinstance(args);
+    else
+        javappm = NULL;
+#endif
+
     refreshPluginInfo();
 }
 
@@ -55,8 +66,12 @@ PluginManagerImpl::~PluginManagerImpl()
 int PluginManagerImpl::registerPlugin(std::string path)
 {
     int flag = 0;
+
     flag = cppm->registerPlugin(path);
-    flag = javappm->registerPlugin(path);
+#ifdef ANDROID
+    if (javappm)
+        flag = javappm->registerPlugin(path);
+#endif
     refreshPluginInfo();
     return flag;
 }
@@ -65,7 +80,12 @@ int PluginManagerImpl::registerAllPlugin(std::string path)
 {
     int flag = 0;
     flag = cppm->registerAllPlugin(path);
-    flag = javappm->registerAllPlugin(path);
+
+#ifdef ANDROID
+    if (javappm)
+        flag = javappm->registerAllPlugin(path);
+#endif
+
     refreshPluginInfo();
     return flag;
 }
@@ -87,10 +107,12 @@ int PluginManagerImpl::unregisterPlugin(std::string id)
             }
             else if (!m_plugins[i].getValueByAttribute("Language").compare("JAVA"))
             {
+#ifdef ANDROID
                 if ((flag = javappm->unregisterPlugin(&m_plugins[i])))
                 {
                     m_plugins.erase(m_plugins.begin() + i);
                 }
+#endif
             }
         }
     }
@@ -102,14 +124,17 @@ int PluginManagerImpl::unregisterAllPlugin()
 {
     int flag = 0;
     flag = cppm->unregisterAllPlugin();
-    flag = javappm->unregisterAllPlugin();
+#ifdef ANDROID
+    if (javappm)
+        flag = javappm->unregisterAllPlugin();
+#endif
     m_plugins.clear();
     return flag;
 }
 
 int PluginManagerImpl::rescanPlugin()
 {
-    Config *config = Config::Getinstance();
+    Config *config = Config::Getinstance(m_args);
     std::string pluginpath = config->getPluginPath();
     if (pluginpath != "")
     {
@@ -124,7 +149,6 @@ int PluginManagerImpl::rescanPlugin()
     return result;
 }
 
-
 std::vector<Plugin> &PluginManagerImpl::getAllPlugins(void)
 {
     return m_plugins;
@@ -156,7 +180,7 @@ Plugin *PluginManagerImpl::getPlugin(const std::string pluginID)
         }
     }
 
-    return nullptr;
+    return NULL;
 }
 int PluginManagerImpl::startPlugins(const std::string key, const std::string value)
 {
@@ -190,14 +214,14 @@ int PluginManagerImpl::startPlugins(const std::string key, const std::string val
         }
     }
     delete(resource_plugin);
-    resource_plugin = nullptr;
+    resource_plugin = NULL;
     return flag;
 }
 
 int PluginManagerImpl::startPlugins(Plugin *const plugin)
 {
     int flag = FALSE;
-    void *arg  = nullptr;
+    void *arg  = NULL;
 
     flag = startbyPlatform(plugin, arg);
 
@@ -239,7 +263,7 @@ int PluginManagerImpl::stopPlugins(const std::string key, const std::string valu
         }
     }
     delete(resource_plugin);
-    resource_plugin = nullptr;
+    resource_plugin = NULL;
     return flag;
 }
 
@@ -266,7 +290,10 @@ int PluginManagerImpl::startbyPlatform(Plugin *const plugin, void *const arg)
             }
             else if (!m_plugins[i].getValueByAttribute("Language").compare("JAVA"))
             {
-                flag = javappm->start(plugin, arg);
+#ifdef ANDROID
+                if (javappm)
+                    flag = javappm->start(plugin, arg);
+#endif
             }
         }
     }
@@ -292,7 +319,10 @@ int PluginManagerImpl::stopbyPlatform(Plugin *const plugin)
             }
             else if (!m_plugins[i].getValueByAttribute("Language").compare("JAVA"))
             {
-                flag = javappm->stop(plugin);
+#ifdef ANDROID
+                if (javappm)
+                    flag = javappm->stop(plugin);
+#endif
             }
         }
     }
@@ -312,12 +342,16 @@ bool PluginManagerImpl::isStarted(Plugin *plugin)
         flag = TRUE;
         return flag;
     }
-
-    if (javappm->isStarted(plugin))
+#ifdef ANDROID
+    if (javappm)
     {
-        flag = TRUE;
-        return flag;
+        if (javappm->isStarted(plugin))
+        {
+            flag = TRUE;
+            return flag;
+        }
     }
+#endif
     return flag;
 }
 
@@ -335,7 +369,10 @@ std::string PluginManagerImpl::getState(std::string plugID)
             }
             else if (!m_plugins[i].getValueByAttribute("Language").compare("JAVA"))
             {
-                str = javappm->getState(plugID);
+#ifdef ANDROID
+                if (javappm)
+                    str = javappm->getState(plugID);
+#endif
             }
         }
     }
@@ -348,13 +385,18 @@ std::vector<Plugin> PluginManagerImpl::refreshPluginInfo()
     m_plugins.clear();
     m_plugins = cppm->getAllPlugins();
 
-    std::vector<Plugin> java_plugins = javappm->getAllPlugins();
-    int size = java_plugins.size();
-
-    for (int i = 0 ; i < size ; i++)
+#ifdef ANDROID
+    if (javappm)
     {
-        m_plugins.push_back(java_plugins[i]);
+        std::vector<Plugin> java_plugins = javappm->getAllPlugins();
+        int size = java_plugins.size();
+
+        for (int i = 0 ; i < size ; i++)
+        {
+            m_plugins.push_back(java_plugins[i]);
+        }
     }
+#endif
 
     return m_plugins;
 }
\ No newline at end of file
index 3beb8e8..c49768b 100644 (file)
 
 /// @file PluginManagerImpl.h
 
-/// @brief
+/// @brief PluginManagerImple provides abstraction of the plugin manager interface
 
 #ifndef __PLUGINMANAGERIMPL_H__
 #define __PLUGINMANAGERIMPL_H__
 
 #include "Plugin.h"
 #include "CpluffAdapter.h"
+
+#ifdef ANDROID
 #include "FelixAdapter.h"
+#endif
 
 namespace OIC
 {
@@ -40,7 +43,7 @@ namespace OIC
             * During construction time, all plugins under the root plugin path will be loaded.
             *
             */
-            PluginManagerImpl();
+            PluginManagerImpl(void *args);
 
             /**
             * Virtual destructor
@@ -61,7 +64,6 @@ namespace OIC
             int registerPlugin(std::string path);
 
 
-
             /**
             * A function to register pluins in the path.
             * This function will load plugins in plugin manager table.
@@ -174,11 +176,11 @@ namespace OIC
             */
             virtual std::vector<Plugin> &getAllPlugins(void);
 
-            static PluginManagerImpl *Getinstance()
+            static PluginManagerImpl *Getinstance(void *args)
             {
                 if (NULL == s_pinstance)
                 {
-                    s_pinstance = new PluginManagerImpl();
+                    s_pinstance = new PluginManagerImpl(args);
                 }
 
                 return s_pinstance;
@@ -187,7 +189,10 @@ namespace OIC
         private:
 
             CpluffAdapter *cppm;
+            void *m_args;
+#ifdef ANDROID
             FelixAdapter *javappm;
+#endif
 
             std::vector<Plugin> m_plugins;
             static PluginManagerImpl *s_pinstance;
diff --git a/service/protocol-plugin/plugin-manager/src/pluginmanager.xml b/service/protocol-plugin/plugin-manager/src/pluginmanager.xml
new file mode 100644 (file)
index 0000000..e8845cf
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<pluginManager>
+    <pluginInfo
+        pluginPath="../../../plugins"
+        name="pluginmanager">
+    </pluginInfo>
+    <specialpluginInfo>
+    </specialpluginInfo>
+</pluginManager>
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/.classpath b/service/protocol-plugin/plugins/Android/plugin.gear.noti/.classpath
new file mode 100644 (file)
index 0000000..74d7dc7
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry exported="true" kind="lib" path="libs/"/>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/android.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/felix.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/base.jar"/>
+       <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/META-INF/MANIFEST.MF b/service/protocol-plugin/plugins/Android/plugin.gear.noti/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..a027915
--- /dev/null
@@ -0,0 +1,36 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Samsung GearS Rich Notification Plugin
+Bundle-SymbolicName: gearnoti
+Bundle-ResourceType: device.notify
+Bundle-Version: 1.0.0
+Bundle-ClassPath: .,
+ libs/
+Export-Package: oic.plugin.gear.noti,
+ com.google.gson,
+ com.google.gson.annotations,
+ com.google.gson.internal,
+ com.google.gson.internal.bind,
+ com.google.gson.reflect,
+ com.google.gson.stream,
+ com.samsung.android.sdk,
+ com.samsung.android.sdk.richnotification,
+ com.samsung.android.sdk.richnotification.actions,
+ com.samsung.android.sdk.richnotification.templates
+Import-Package: org.osgi.framework,
+ android.app,
+ android.dalvik;resolution:=optional,
+ android.content,
+ android.content.pm,
+ android.content.res,
+ android.graphics,
+ android.graphics.drawable,
+ android.net,
+ android.os,
+ android.provider,
+ android.text.format,
+ android.util,
+ android.view,
+ android.widget,
+ org.iotivity.base
+Bundle-Activator: oic.plugin.gear.noti.Activator
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/build.properties b/service/protocol-plugin/plugins/Android/plugin.gear.noti/build.properties
new file mode 100644 (file)
index 0000000..f1a3ffe
--- /dev/null
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               libs/
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/gson.jar b/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/gson.jar
new file mode 100644 (file)
index 0000000..9478253
Binary files /dev/null and b/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/gson.jar differ
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/richnotification.jar b/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/richnotification.jar
new file mode 100644 (file)
index 0000000..d9ca96e
Binary files /dev/null and b/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/richnotification.jar differ
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/sdk.jar b/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/sdk.jar
new file mode 100644 (file)
index 0000000..070d65d
Binary files /dev/null and b/service/protocol-plugin/plugins/Android/plugin.gear.noti/lib/sdk.jar differ
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/Activator.java b/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/Activator.java
new file mode 100644 (file)
index 0000000..1d95080
--- /dev/null
@@ -0,0 +1,170 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file Activator.java
+
+package oic.plugin.gear.noti;
+
+import java.util.EnumSet;
+import java.util.UUID;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ResourceProperty;
+import org.iotivity.base.ServiceType;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+
+import android.app.Activity;
+import android.content.Context;
+import android.util.Log;
+
+import com.samsung.android.sdk.SsdkUnsupportedException;
+import com.samsung.android.sdk.richnotification.Srn;
+import com.samsung.android.sdk.richnotification.SrnRichNotification;
+import com.samsung.android.sdk.richnotification.SrnRichNotificationManager;
+import com.samsung.android.sdk.richnotification.SrnRichNotificationManager.ErrorType;
+import com.samsung.android.sdk.richnotification.SrnRichNotificationManager.EventListener;
+
+public class Activator extends Activity implements BundleActivator,
+        EventListener {
+
+    final private static String TAG = "GearNoti";
+
+    public enum TemplateTypes {
+        SMALL_HEADER;
+    }
+
+    private static BundleContext             context;
+    public static Context                    AppContext;
+    public static SrnRichNotificationManager mRichNotificationManager;
+
+    class Notify {
+        public String m_power;
+        public String m_name;
+
+        public Notify() {
+            m_power = "";
+            m_name = "device.notify";
+        }
+    }
+
+    static int                     OBSERVE_TYPE_TO_USE = ObserveType.OBSERVE
+                                                               .getValue();
+
+    public static Notify           myNotify;
+    public static OcResource       curResource;
+    public static OcResourceHandle resourceHandle;
+    static int                     oc                  = 0;
+    static Activity                mActivity;
+
+    static BundleContext getContext() {
+        return context;
+    }
+
+    public void start(BundleContext bundleContext) throws Exception {
+        Activator.context = bundleContext;
+
+        ServiceReference<Context> ref = Activator.context
+                .getServiceReference(Context.class);
+        AppContext = Activator.context.getService(ref);
+
+        myNotify = new Notify();
+
+        Srn srn = new Srn();
+        try {
+            // Initializes an instance of Srn.
+            srn.initialize(AppContext);
+            Log.w(TAG, "SRN initialized");
+        } catch (SsdkUnsupportedException e) {
+            Log.w(TAG, "SsdkUnsupportedException");
+        }
+
+        mRichNotificationManager = new SrnRichNotificationManager(AppContext);
+
+        if (mRichNotificationManager.isConnected()) {
+            // Starts the manager.
+            mRichNotificationManager.start();
+            Log.w(TAG, "RichNoti Manager Started");
+
+            SrnRichNotification myRichNotification = new SrnRichNotification(
+                    AppContext);
+            Log.w(TAG, "RichNoti instance created");
+
+            PlatformConfig cfg = new PlatformConfig(this, ServiceType.IN_PROC,
+                    ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+
+            OcPlatform.Configure(cfg);
+
+            EntityHandlerNoti entitycb = new EntityHandlerNoti();
+
+            resourceHandle = OcPlatform.registerResource("/a/galaxy/gear",
+                    "device.notify", "oc.mi.def", entitycb,
+                    EnumSet.of(ResourceProperty.DISCOVERABLE));
+        }
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        mRichNotificationManager.registerRichNotificationListener(this);
+    }
+
+    @Override
+    protected void onPause() {
+        super.onPause();
+        mRichNotificationManager.unregisterRichNotificationListener(this);
+    }
+
+    @Override
+    public void onError(UUID arg0, ErrorType arg1) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void onRead(UUID arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void onRemoved(UUID arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void stop(BundleContext arg0) throws Exception {
+        // TODO Auto-generated method stub
+        OcPlatform.unregisterResource(resourceHandle);
+        context = null;
+        mRichNotificationManager = null;
+        myNotify = null;
+
+    }
+
+}
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/EntityHandlerNoti.java b/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/EntityHandlerNoti.java
new file mode 100644 (file)
index 0000000..a9b5d74
--- /dev/null
@@ -0,0 +1,175 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file EntityHandlerNoti.java
+
+package oic.plugin.gear.noti;
+
+import java.util.UUID;
+
+import oic.plugin.gear.noti.Activator.TemplateTypes;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.osgi.framework.BundleContext;
+
+import android.util.Log;
+
+public class EntityHandlerNoti implements OcPlatform.EntityHandler {
+
+    final private static String TAG = "EntityHandler";
+
+    public static String        textNoti;
+
+    public EntityHandlerResult handleEntity(OcResourceRequest resourcerequest) {
+        Log.e(TAG, "Entity Handler callback. LJH");
+
+        System.out.println("IN Server CPP entity Handler");
+        System.out.println("gear");
+        // OcResourceResponse response = new OcResourceResponse();
+        // int result = 1; // EH_ERROR
+        if (resourcerequest != null
+                && resourcerequest.getResourceUri().equals("/a/galaxy/gear")) {
+            RequestType requestType = resourcerequest.getRequestType();
+            EnumSet<RequestHandlerFlag> handlerFlagSet = resourcerequest
+                    .getRequestHandlerFlagSet();
+
+            if(handlerFlagSet.contains(RequestHandlerFlag.INIT))
+            {
+                Log.e(TAG, "requestFlag : Init");
+            }
+            if(handlerFlagSet.contains(RequestHandlerFlag.REQUEST))
+            {
+                OcResourceResponse response = new OcResourceResponse();
+                OcRepresentation representation = new OcRepresentation();
+                response.setRequestHandle(resourcerequest
+                        .getRequestHandle());
+                response.setResourceHandle(resourcerequest
+                        .getResourceHandle());
+                Log.d("JUDO",
+                        "/******************************************************************************/");
+                Log.d("JUDO", "Name: "
+                        + resourcerequest.getResourceRepresentation()
+                                .getValueString("name"));
+                Log.d("JUDO", "Name: "
+                        + resourcerequest.getResourceRepresentation()
+                                .getValueString("power"));
+                Log.d("JUDO", "Name: "
+                        + resourcerequest.getResourceRepresentation()
+                                .getValueInt("brigthness"));
+                Log.d("JUDO", "Name: "
+                        + resourcerequest.getResourceRepresentation()
+                                .getValueInt("color"));
+                Log.d("JUDO",
+                        "/******************************************************************************/");
+                switch (requestType) {
+                    case GET:
+                        break;
+                    case PUT:
+                        textNoti = resourcerequest
+                                .getResourceRepresentation()
+                                .getValueString("power");
+                        perform(0);
+                        break;
+                    case POST:
+                        break;
+                }
+                response.setErrorCode(200);
+                // representation.setUri("/a/galaxy/gear");
+                representation.setValueString("name",
+                        Activator.myNotify.m_name);
+                representation.setValueString("power",
+                        Activator.myNotify.m_power);
+                representation.setValueInt("brightness", 0);
+                representation.setValueInt("color", 0);
+                response.setResourceRepresentation(representation);
+                try {
+                    OcPlatform.sendResponse(response);
+                } catch (OcException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                    return EntityHandlerResult.ERROR;
+                }
+                }
+            if(handlerFlagSet.contains(RequestHandlerFlag.OBSERVER))
+            {
+                Log.e(TAG, "requestFlag : Observer");
+            }
+            return EntityHandlerResult.OK;
+        }
+        return EntityHandlerResult.ERROR;
+        /*
+         * if((requestFlag & 1 << 0) != 0 ) // init flag { Log.e(TAG,
+         * "requestFlag : Init"); } if((requestFlag & 1 << 1) != 0)
+         * //RequestFlag { if(requestType.equals("GET")) {
+         * 
+         * } else if(requestType.equals("PUT")) { textNoti =
+         * resourcerequest.getResourceRepresentation().getValueString("power");
+         * perform(0); } else if(requestType.equals("POST")) { }
+         * OcRepresentation representation = new OcRepresentation();
+         * OcResourceResponse response = new OcResourceResponse();
+         * response.setRequestHandle(resourcerequest.getRequestHandle());
+         * response.setResourceHandle(resourcerequest.getResourceHandle());
+         * representation.setUri("/a/galaxy/gear");
+         * representation.setValueString("name", Activator.myNotify.m_name);
+         * representation.setValueString("power", Activator.myNotify.m_power);
+         * representation.setValueInt("brightness", 0);
+         * representation.setValueInt("color", 0); response.setErrorCode(200);
+         * response.setResourceRepresentation(representation); try {
+         * OcPlatform.sendResponse(response); } catch (OcException e) { // TODO
+         * Auto-generated catch block e.printStackTrace(); return
+         * EntityHandlerResult.ERROR; } } if((requestFlag & 1 << 2) != 0)
+         * //ObserverFlag { Log.e(TAG, "requestFlag : Observer"); } } return
+         * EntityHandlerResult.OK;
+         */
+
+    }
+
+    public void stop(BundleContext bundleContext) throws Exception {
+        Activator.AppContext = null;
+        Activator.mRichNotificationManager.stop();
+    }
+
+    public void perform(int primary) {
+        if (primary < 0 || primary >= TemplateTypes.values().length) {
+            return;
+        }
+
+        Log.w(TAG, "Sending Notification");
+
+        switch (TemplateTypes.values()[primary]) {
+            case SMALL_HEADER:
+                performExample(new SmallHeaderExample(Activator.AppContext));
+                break;
+        }
+    }
+
+    private void performExample(IExample example) {
+        UUID uuid = Activator.mRichNotificationManager.notify(example
+                .createRichNoti());
+        Log.w(TAG, "Notification ID: " + uuid);
+    }
+}
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/IExample.java b/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/IExample.java
new file mode 100644 (file)
index 0000000..7ce8985
--- /dev/null
@@ -0,0 +1,29 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file IExample.java
+
+package oic.plugin.gear.noti;
+
+import com.samsung.android.sdk.richnotification.SrnRichNotification;
+
+public interface IExample {
+    SrnRichNotification createRichNoti();
+}
diff --git a/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/SmallHeaderExample.java b/service/protocol-plugin/plugins/Android/plugin.gear.noti/src/oic/plugin/gear/noti/SmallHeaderExample.java
new file mode 100644 (file)
index 0000000..d5298a7
--- /dev/null
@@ -0,0 +1,60 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file SmallHeaderExample.java
+
+package oic.plugin.gear.noti;
+
+import android.content.Context;
+
+import com.samsung.android.sdk.richnotification.SrnRichNotification;
+import com.samsung.android.sdk.richnotification.SrnRichNotification.AlertType;
+import com.samsung.android.sdk.richnotification.templates.SrnPrimaryTemplate;
+import com.samsung.android.sdk.richnotification.templates.SrnStandardTemplate;
+import com.samsung.android.sdk.richnotification.templates.SrnStandardTemplate.HeaderSizeType;
+
+public class SmallHeaderExample implements IExample {
+
+    private final Context mContext;
+
+    public SmallHeaderExample(Context ctx) {
+        mContext = ctx;
+    }
+
+    @Override
+    public SrnRichNotification createRichNoti() {
+        SrnRichNotification noti = new SrnRichNotification(mContext);
+        noti.setReadout(EntityHandlerNoti.textNoti, "");
+        noti.setPrimaryTemplate(getSmallHeaderTemplate());
+
+        noti.setAlertType(AlertType.VIBRATION);
+
+        return noti;
+    }
+
+    public SrnPrimaryTemplate getSmallHeaderTemplate() {
+        SrnStandardTemplate smallHeaderTemplate = new SrnStandardTemplate(
+                HeaderSizeType.SMALL);
+
+        smallHeaderTemplate.setSubHeader(EntityHandlerNoti.textNoti);
+
+        return smallHeaderTemplate;
+    }
+}
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/.classpath b/service/protocol-plugin/plugins/Android/plugin.hue/.classpath
new file mode 100644 (file)
index 0000000..b6c0713
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry exported="true" kind="lib" path="libs/"/>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/android.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/felix.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/huelocalsdk.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/huesdkresources.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/base.jar"/>
+       <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/META-INF/MANIFEST.MF b/service/protocol-plugin/plugins/Android/plugin.hue/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..9d49405
--- /dev/null
@@ -0,0 +1,41 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Philips Hue Plugin
+Bundle-SymbolicName: hue
+Bundle-ResourceType: device.light
+Bundle-Version: 1.0.0
+Bundle-ClassPath: .,
+ libs/
+Export-Package: com.philips.lighting.annotations,
+ com.philips.lighting.hue.listener,
+ com.philips.lighting.hue.sdk,
+ com.philips.lighting.hue.sdk.bridge.impl,
+ com.philips.lighting.hue.sdk.clip,
+ com.philips.lighting.hue.sdk.clip.serialisation,
+ com.philips.lighting.hue.sdk.clip.serialisation.sensors,
+ com.philips.lighting.hue.sdk.connection.impl,
+ com.philips.lighting.hue.sdk.data,
+ com.philips.lighting.hue.sdk.exception,
+ com.philips.lighting.hue.sdk.fbp,
+ com.philips.lighting.hue.sdk.heartbeat,
+ com.philips.lighting.hue.sdk.notification.impl,
+ com.philips.lighting.hue.sdk.upnp,
+ com.philips.lighting.hue.sdk.util,
+ com.philips.lighting.hue.sdk.utilities,
+ com.philips.lighting.hue.sdk.utilities.impl,
+ com.philips.lighting.model,
+ com.philips.lighting.model.rule,
+ com.philips.lighting.model.sensor,
+ com.philips.lighting.model.sensor.metadata,
+ org.json.hue
+Import-Package: org.osgi.framework,
+ android.app,
+ android.dalvik;resolution:=optional,
+ android.util,
+ android.content,
+ android.os,
+ android.graphics,
+ android.view,
+ android.widget,
+ org.iotivity.base
+Bundle-Activator: oic.plugin.hue.Activator
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/build.properties b/service/protocol-plugin/plugins/Android/plugin.hue/build.properties
new file mode 100644 (file)
index 0000000..f1a3ffe
--- /dev/null
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               libs/
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/lib/huelocalsdk.jar b/service/protocol-plugin/plugins/Android/plugin.hue/lib/huelocalsdk.jar
new file mode 100644 (file)
index 0000000..ecc7555
Binary files /dev/null and b/service/protocol-plugin/plugins/Android/plugin.hue/lib/huelocalsdk.jar differ
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/lib/huesdkresources.jar b/service/protocol-plugin/plugins/Android/plugin.hue/lib/huesdkresources.jar
new file mode 100644 (file)
index 0000000..24ab76e
Binary files /dev/null and b/service/protocol-plugin/plugins/Android/plugin.hue/lib/huesdkresources.jar differ
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/AccessPointListAdapter.java b/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/AccessPointListAdapter.java
new file mode 100644 (file)
index 0000000..f2c134e
--- /dev/null
@@ -0,0 +1,95 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file AccessPointListAdapter.java
+
+package oic.plugin.hue;
+
+import java.util.List;
+
+import android.content.Context;
+import android.graphics.Color;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseAdapter;
+import android.widget.TextView;
+
+import com.philips.lighting.hue.sdk.PHAccessPoint;
+
+public class AccessPointListAdapter extends BaseAdapter {
+    private LayoutInflater      mInflater;
+    private List<PHAccessPoint> accessPoints;
+
+    class BridgeListItem {
+        private TextView bridgeIp;
+        private TextView bridgeMac;
+    }
+
+    public AccessPointListAdapter(Context context,
+            List<PHAccessPoint> accessPoints) {
+        // Cache the LayoutInflate to avoid asking for a new one each time.
+        mInflater = LayoutInflater.from(context);
+        this.accessPoints = accessPoints;
+    }
+
+    public View getView(final int position, View convertView, ViewGroup parent) {
+
+        BridgeListItem item;
+
+        if (convertView == null) {
+            convertView = mInflater.inflate(0x7f030004, null);
+
+            item = new BridgeListItem();
+            item.bridgeMac = (TextView) convertView.findViewById(0x7f080009);
+            item.bridgeIp = (TextView) convertView.findViewById(0x7f08000a);
+            convertView.setTag(item);
+        } else {
+            item = (BridgeListItem) convertView.getTag();
+        }
+        PHAccessPoint accessPoint = accessPoints.get(0);
+        item.bridgeIp.setTextColor(Color.BLACK);
+        item.bridgeIp.setText(accessPoint.getIpAddress());
+        item.bridgeMac.setTextColor(Color.DKGRAY);
+        item.bridgeMac.setText(accessPoint.getMacAddress());
+        return convertView;
+    }
+
+    @Override
+    public long getItemId(int position) {
+        return 0;
+    }
+
+    @Override
+    public int getCount() {
+        return accessPoints.size();
+    }
+
+    @Override
+    public Object getItem(int position) {
+        return accessPoints.get(position);
+    }
+
+    public void updateData(List<PHAccessPoint> accessPoints) {
+        this.accessPoints = accessPoints;
+        notifyDataSetChanged();
+    }
+
+}
\ No newline at end of file
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/Activator.java b/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/Activator.java
new file mode 100644 (file)
index 0000000..64f831c
--- /dev/null
@@ -0,0 +1,341 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file Activator.java
+
+package oic.plugin.hue;
+
+import java.util.EnumSet;
+import java.util.List;
+
+import oic.plugin.hue.AccessPointListAdapter;
+import oic.plugin.hue.HueSharedPreferences;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ResourceProperty;
+import org.iotivity.base.ServiceType;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+
+import com.philips.lighting.hue.sdk.PHAccessPoint;
+import com.philips.lighting.hue.sdk.PHBridgeSearchManager;
+import com.philips.lighting.hue.sdk.PHHueSDK;
+import com.philips.lighting.hue.sdk.PHSDKListener;
+import com.philips.lighting.model.PHBridge;
+import com.philips.lighting.model.PHHueError;
+import com.philips.lighting.model.PHHueParsingError;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.util.Log;
+
+public class Activator extends Activity implements BundleActivator {
+
+    private static BundleContext   context;
+    private static Context         AppContext;
+    private PHHueSDK               phHueSDK;
+    public static final String     TAG = "Hue Plugin";
+    private HueSharedPreferences   prefs;
+    private AccessPointListAdapter adapter;
+
+    class Light {
+        public String m_power;
+        public int    m_brightness;
+        public int    m_color;
+        public String m_name;
+
+        public Light() {
+            m_power = "off";
+            m_brightness = 0;
+            m_color = 0;
+            m_name = "device.light";
+        }
+    }
+
+    static int                     OBSERVE_TYPE_TO_USE = ObserveType.OBSERVE
+                                                               .getValue();
+
+    public static Light            myLight;
+    public static OcResource       curResource;
+    public static OcResourceHandle resourceHandle;
+    static int                     oc                  = 0;
+    static Activity                mActivity;
+
+    static BundleContext getContext() {
+        return context;
+    }
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mActivity = this;
+    }
+
+    public void start(BundleContext bundleContext) throws Exception {
+        Activator.context = bundleContext;
+
+        ServiceReference<Context> ref = Activator.context
+                .getServiceReference(Context.class);
+        AppContext = Activator.context.getService(ref);
+
+        // Gets an instance of the Hue SDK.
+        phHueSDK = PHHueSDK.getInstance();
+
+        // Set the Device Name (name of your app). This will be stored in your
+        // bridge whitelist entry.
+        phHueSDK.setAppName("QuickStartApp");
+        phHueSDK.setDeviceName(android.os.Build.MODEL);
+
+        // Register the PHSDKListener to receive callbacks from the bridge.
+        phHueSDK.getNotificationManager().registerSDKListener(listener);
+
+        adapter = new AccessPointListAdapter(AppContext,
+                phHueSDK.getAccessPointsFound());
+
+        // Try to automatically connect to the last known bridge. For first time
+        // use this will be empty so a bridge search is automatically started.
+        prefs = HueSharedPreferences.getInstance(AppContext);
+        String lastIpAddress = prefs.getLastConnectedIPAddress();
+        String lastUsername = prefs.getUsername();
+
+        // Automatically try to connect to the last connected IP Address. For
+        // multiple bridge support a different implementation is required.
+        if (lastIpAddress != null && !lastIpAddress.equals("")) {
+            PHAccessPoint lastAccessPoint = new PHAccessPoint();
+            lastAccessPoint.setIpAddress(lastIpAddress);
+            lastAccessPoint.setUsername(lastUsername);
+
+            if (!phHueSDK.isAccessPointConnected(lastAccessPoint)) {
+                phHueSDK.connect(lastAccessPoint);
+            }
+        } else { // First time use, so perform a bridge search.
+            doBridgeSearch();
+            Log.w(TAG, "Searching for Bridges.");
+        }
+
+        myLight = new Light();
+    }
+
+    public void stop(BundleContext bundleContext) throws Exception {
+        OcPlatform.unregisterResource(resourceHandle);
+        context = null;
+        myLight = null;
+        // phHueSDK = null;
+    }
+
+    public void doBridgeSearch() {
+        PHBridgeSearchManager sm = (PHBridgeSearchManager) phHueSDK
+                .getSDKService(PHHueSDK.SEARCH_BRIDGE);
+        // Start the UPNP Searching of local bridges.
+        sm.search(true, true);
+    }
+
+    private PHSDKListener listener = new PHSDKListener() {
+
+                                       @Override
+                                       public void onAccessPointsFound(
+                                               List<PHAccessPoint> accessPoint) {
+                                           Log.w(TAG, "Access Points Found. "
+                                                   + accessPoint.size());
+                                           if (accessPoint != null
+                                                   && accessPoint.size() > 0) {
+                                               phHueSDK.getAccessPointsFound()
+                                                       .clear();
+                                               phHueSDK.getAccessPointsFound()
+                                                       .addAll(accessPoint);
+                                               runOnUiThread(new Runnable() {
+                                                   @Override
+                                                   public void run() {
+                                                       adapter.updateData(phHueSDK
+                                                               .getAccessPointsFound());
+                                                   }
+                                               });
+
+                                               HueSharedPreferences prefs2 = HueSharedPreferences
+                                                       .getInstance(AppContext);
+                                               PHAccessPoint accessPoint2 = (PHAccessPoint) adapter
+                                                       .getItem(0);
+                                               accessPoint2.setUsername(prefs2
+                                                       .getUsername());
+
+                                               PHBridge connectedBridge = phHueSDK
+                                                       .getSelectedBridge();
+
+                                               if (connectedBridge != null) {
+                                                   String connectedIP = connectedBridge
+                                                           .getResourceCache()
+                                                           .getBridgeConfiguration()
+                                                           .getIpAddress();
+                                                   Log.w(TAG, "Connected IP: "
+                                                           + connectedIP);
+                                                   if (connectedIP != null) { // We
+                                                                              // are
+                                                                              // already
+                                                                              // connected
+                                                                              // here:-
+                                                       Log.w(TAG,
+                                                               "Connected IP != null");
+                                                       phHueSDK.disableHeartbeat(connectedBridge);
+                                                       phHueSDK.disconnect(connectedBridge);
+                                                   }
+                                               }
+                                               phHueSDK.connect(accessPoint2);
+                                           }
+                                       }
+
+                                       @Override
+                                       public void onCacheUpdated(
+                                               List<Integer> arg0,
+                                               PHBridge bridge) {
+                                           Log.w(TAG, "On CacheUpdated.");
+                                       }
+
+                                       @Override
+                                       public void onBridgeConnected(PHBridge b) {
+                                           Log.w(TAG,
+                                                   "Connected to the Bridge.");
+                                           phHueSDK.setSelectedBridge(b);
+                                           phHueSDK.enableHeartbeat(b,
+                                                   PHHueSDK.HB_INTERVAL);
+                                           phHueSDK.getLastHeartbeat()
+                                                   .put(b.getResourceCache()
+                                                           .getBridgeConfiguration()
+                                                           .getIpAddress(),
+                                                           System.currentTimeMillis());
+
+                                           PlatformConfig cfg = new PlatformConfig(
+                                                   this,
+                                                   ServiceType.IN_PROC,
+                                                   ModeType.CLIENT_SERVER,
+                                                   "0.0.0.0", 0,
+                                                   QualityOfService.LOW);
+
+                                           OcPlatform.Configure(cfg);
+
+                                           EntityHandlerHue entitycb = new EntityHandlerHue();
+                                           try {
+                                               resourceHandle = OcPlatform
+                                                       .registerResource(
+                                                               "/a/huebulb",
+                                                               "device.light",
+                                                               "oc.mi.def",
+                                                               entitycb,
+                                                               EnumSet.of(ResourceProperty.DISCOVERABLE));
+                                           } catch (OcException e) {
+                                               e.printStackTrace();
+                                           }
+                                       }
+
+                                       @Override
+                                       public void onAuthenticationRequired(
+                                               PHAccessPoint accessPoint) {
+                                           Log.w(TAG,
+                                                   "Authentication Required.");
+                                           phHueSDK.startPushlinkAuthentication(accessPoint);
+                                           Log.w(TAG, "Access Point IP addr: "
+                                                   + accessPoint.getIpAddress());
+                                           Log.w(TAG,
+                                                   "Access Point MAC addr: "
+                                                           + accessPoint
+                                                                   .getMacAddress());
+                                           Log.w(TAG, "Access Point key: "
+                                                   + accessPoint.getUsername());
+                                       }
+
+                                       @Override
+                                       public void onConnectionResumed(
+                                               PHBridge bridge) {
+                                           // Log.v(TAG, "onConnectionResumed "
+                                           // +
+                                           // bridge.getResourceCache().getBridgeConfiguration().getIpAddress());
+                                           phHueSDK.getLastHeartbeat()
+                                                   .put(bridge
+                                                           .getResourceCache()
+                                                           .getBridgeConfiguration()
+                                                           .getIpAddress(),
+                                                           System.currentTimeMillis());
+                                           for (int i = 0; i < phHueSDK
+                                                   .getDisconnectedAccessPoint()
+                                                   .size(); i++) {
+                                               if (phHueSDK
+                                                       .getDisconnectedAccessPoint()
+                                                       .get(i)
+                                                       .getIpAddress()
+                                                       .equals(bridge
+                                                               .getResourceCache()
+                                                               .getBridgeConfiguration()
+                                                               .getIpAddress())) {
+                                                   phHueSDK.getDisconnectedAccessPoint()
+                                                           .remove(i);
+                                               }
+                                           }
+                                       }
+
+                                       @Override
+                                       public void onConnectionLost(
+                                               PHAccessPoint accessPoint) {
+                                           Log.v(TAG, "onConnectionLost : "
+                                                   + accessPoint.getIpAddress());
+                                           if (!phHueSDK
+                                                   .getDisconnectedAccessPoint()
+                                                   .contains(accessPoint)) {
+                                               phHueSDK.getDisconnectedAccessPoint()
+                                                       .add(accessPoint);
+                                           }
+                                       }
+
+                                       @Override
+                                       public void onError(int code,
+                                               final String message) {
+                                           Log.e(TAG, "on Error Called : "
+                                                   + code + ":" + message);
+
+                                           if (code == PHHueError.NO_CONNECTION) {
+                                               Log.w(TAG, "On No Connection");
+                                           } else if (code == PHHueError.AUTHENTICATION_FAILED
+                                                   || code == 1158) {
+
+                                           } else if (code == PHHueError.BRIDGE_NOT_RESPONDING) {
+                                               Log.w(TAG,
+                                                       "Bridge Not Responding . . . ");
+                                           }
+                                       }
+
+                                       @Override
+                                       public void onParsingErrors(
+                                               List<PHHueParsingError> parsingErrorsList) {
+                                           for (PHHueParsingError parsingError : parsingErrorsList) {
+                                               Log.e(TAG,
+                                                       "ParsingError : "
+                                                               + parsingError
+                                                                       .getMessage());
+                                           }
+                                       }
+                                   };
+}
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/EntityHandlerHue.java b/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/EntityHandlerHue.java
new file mode 100644 (file)
index 0000000..278d3de
--- /dev/null
@@ -0,0 +1,147 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file EntityHandlerHue.java
+
+package oic.plugin.hue;
+
+import java.util.List;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+
+import android.util.Log;
+
+import com.philips.lighting.hue.sdk.PHHueSDK;
+import com.philips.lighting.model.PHBridge;
+import com.philips.lighting.model.PHLight;
+import com.philips.lighting.model.PHLightState;
+
+public class EntityHandlerHue implements OcPlatform.EntityHandler {
+
+    final private static String TAG = "EntityHandler";
+
+    public EntityHandlerResult handleEntity(OcResourceRequest resourcerequest) {
+        Log.e(TAG, "Entity Handler callback.");
+
+        System.out.println("IN Server CPP entity Handler");
+        System.out.println("Hue bulb");
+        // OcResourceResponse response = new OcResourceResponse();
+        // int result = 1; // EH_ERROR
+        if (resourcerequest != null
+                && resourcerequest.getResourceUri().equals("/a/huebulb")) {
+            RequestType requestType = resourcerequest.getRequestType();
+            EnumSet<RequestHandlerFlag> handlerFlagSet = resourcerequest
+                    .getRequestHandlerFlagSet();
+
+            if(handlerFlagSet.contains(RequestHandlerFlag.INIT))
+            {
+                Log.e(TAG, "requestFlag : Init");
+            }
+            if(handlerFlagSet.contains(RequestHandlerFlag.REQUEST))
+            {
+                OcResourceResponse response = new OcResourceResponse();
+                OcRepresentation representation = new OcRepresentation();
+                response.setRequestHandle(resourcerequest
+                        .getRequestHandle());
+                response.setResourceHandle(resourcerequest
+                        .getResourceHandle());
+                switch (requestType) {
+                    case GET:
+                        PHBridge bridge = PHHueSDK.getInstance()
+                                .getSelectedBridge();
+                        List<PHLight> myLights = bridge.getResourceCache()
+                                .getAllLights();
+                        for (PHLight light : myLights) {
+                            PHLightState lightState = new PHLightState();
+                            lightState = light.getLastKnownLightState();
+                            if (lightState.isOn()) {
+                                Activator.myLight.m_power = "on";
+                            } else if (!lightState.isOn()) {
+                                Activator.myLight.m_power = "off";
+                            }
+                            Activator.myLight.m_color = lightState.getHue();
+                            Activator.myLight.m_brightness = lightState
+                                    .getBrightness();
+                        }
+                        break;
+                    case PUT:
+                        PHBridge mbridge = PHHueSDK.getInstance()
+                                .getSelectedBridge();
+                        List<PHLight> mmyLights = mbridge
+                                .getResourceCache().getAllLights();
+                        for (PHLight light : mmyLights) {
+                            PHLightState lightState = new PHLightState();
+                            String str = resourcerequest
+                                    .getResourceRepresentation()
+                                    .getValueString("power");
+                            if (str.equals("on")) {
+                                lightState.setOn(true);
+                                Activator.myLight.m_power = "on";
+                            } else if (str.equals("off")) {
+                                lightState.setOn(false);
+                                Activator.myLight.m_power = "off";
+                            }
+                            lightState.setHue(resourcerequest
+                                    .getResourceRepresentation()
+                                    .getValueInt("color"));
+                            Activator.myLight.m_color = resourcerequest
+                                    .getResourceRepresentation()
+                                    .getValueInt("color");
+                            mbridge.updateLightState(light, lightState);
+                        }
+                        break;
+                    case POST:
+                        break;
+                }
+                response.setErrorCode(200);
+                // representation.setUri("/a/huebulb");
+                representation.setValueString("name",
+                        Activator.myLight.m_name);
+                representation.setValueString("power",
+                        Activator.myLight.m_power);
+                representation.setValueInt("brightness",
+                        Activator.myLight.m_brightness);
+                representation.setValueInt("color",
+                        Activator.myLight.m_color);
+                response.setResourceRepresentation(representation);
+                try {
+                    OcPlatform.sendResponse(response);
+                } catch (OcException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                    return EntityHandlerResult.ERROR;
+                }
+            }
+            if(handlerFlagSet.contains(RequestHandlerFlag.OBSERVER))
+            {
+                Log.e(TAG, "requestFlag : Observer");
+            }
+            return EntityHandlerResult.OK;
+        }
+        return EntityHandlerResult.ERROR;
+    }
+}
diff --git a/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/HueSharedPreferences.java b/service/protocol-plugin/plugins/Android/plugin.hue/src/oic/plugin/hue/HueSharedPreferences.java
new file mode 100644 (file)
index 0000000..84f8441
--- /dev/null
@@ -0,0 +1,80 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file HueSharedPreferences.java
+
+package oic.plugin.hue;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.Editor;
+
+import com.philips.lighting.hue.sdk.connection.impl.PHBridgeInternal;
+
+public class HueSharedPreferences {
+    private static final String         HUE_SHARED_PREFERENCES_STORE = "HueSharedPrefs";
+    private static final String         LAST_CONNECTED_USERNAME      = "LastConnectedUsername";
+    private static final String         LAST_CONNECTED_IP            = "LastConnectedIP";
+    private static HueSharedPreferences instance                     = null;
+    private SharedPreferences           mSharedPreferences           = null;
+
+    private Editor                      mSharedPreferencesEditor     = null;
+
+    public void create() {
+
+    }
+
+    public static HueSharedPreferences getInstance(Context ctx) {
+        if (instance == null) {
+            instance = new HueSharedPreferences(ctx);
+        }
+        return instance;
+    }
+
+    private HueSharedPreferences(Context appContext) {
+        mSharedPreferences = appContext.getSharedPreferences(
+                HUE_SHARED_PREFERENCES_STORE, 0); // 0 - for private mode
+        mSharedPreferencesEditor = mSharedPreferences.edit();
+    }
+
+    public String getUsername() {
+        String username = mSharedPreferences.getString(LAST_CONNECTED_USERNAME,
+                "");
+        if (username == null || username.equals("")) {
+            username = PHBridgeInternal.generateUniqueKey();
+            setUsername(username); // Persist the username in the shared prefs
+        }
+        return username;
+    }
+
+    public boolean setUsername(String username) {
+        mSharedPreferencesEditor.putString(LAST_CONNECTED_USERNAME, username);
+        return (mSharedPreferencesEditor.commit());
+    }
+
+    public String getLastConnectedIPAddress() {
+        return mSharedPreferences.getString(LAST_CONNECTED_IP, "");
+    }
+
+    public boolean setLastConnectedIPAddress(String ipAddress) {
+        mSharedPreferencesEditor.putString(LAST_CONNECTED_IP, ipAddress);
+        return (mSharedPreferencesEditor.commit());
+    }
+}
\ No newline at end of file
diff --git a/service/protocol-plugin/plugins/Android/plugin.wemo/.classpath b/service/protocol-plugin/plugins/Android/plugin.wemo/.classpath
new file mode 100644 (file)
index 0000000..74d7dc7
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry exported="true" kind="lib" path="libs/"/>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/android.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/felix.jar"/>
+       <classpathentry exported="true" kind="lib" path="C:/Users/yh_.joo/Desktop/Workspace3 (2)/base.jar"/>
+       <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/service/protocol-plugin/plugins/Android/plugin.wemo/META-INF/MANIFEST.MF b/service/protocol-plugin/plugins/Android/plugin.wemo/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..30e0c41
--- /dev/null
@@ -0,0 +1,40 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Belkin WeMo Plugin
+Bundle-SymbolicName: wemo
+Bundle-ResourceType: device.smartplug
+Bundle-Version: 1.0.0
+Bundle-ClassPath: .,
+ libs/
+Export-Package: oic.plugin.wemo,
+ com.belkin.wemo.localsdk,
+ com.belkin.wemo.storage,
+ org.cybergarage.http,
+ org.cybergarage.net,
+ org.cybergarage.soap,
+ org.cybergarage.upnp,
+ org.cybergarage.upnp.control,
+ org.cybergarage.upnp.device,
+ org.cybergarage.upnp.event,
+ org.cybergarage.upnp.ssdp,
+ org.cybergarage.upnp.xml,
+ org.cybergarage.util,
+ org.cybergarage.xml,
+ org.cybergarage.xml.parser
+Import-Package: org.osgi.framework,
+ android.dalvik;resolution:=optional,
+ android.app,
+ android.content,
+ android.database,
+ android.database.sqlite,
+ android.net,
+ android.net.wifi,
+ android.net.http,
+ android.os,
+ android.util,
+ javax.xml.parsers,
+ org.xml.sax,
+ org.w3c.dom,
+ org.iotivity.base
+Bundle-Activator: oic.plugin.wemo.Activator
+Bundle-ActivationPolicy: lazy
diff --git a/service/protocol-plugin/plugins/Android/plugin.wemo/build.properties b/service/protocol-plugin/plugins/Android/plugin.wemo/build.properties
new file mode 100644 (file)
index 0000000..f1a3ffe
--- /dev/null
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               libs/
diff --git a/service/protocol-plugin/plugins/Android/plugin.wemo/lib/wemosdk.jar b/service/protocol-plugin/plugins/Android/plugin.wemo/lib/wemosdk.jar
new file mode 100644 (file)
index 0000000..8ce64d7
Binary files /dev/null and b/service/protocol-plugin/plugins/Android/plugin.wemo/lib/wemosdk.jar differ
diff --git a/service/protocol-plugin/plugins/Android/plugin.wemo/src/oic/plugin/wemo/Activator.java b/service/protocol-plugin/plugins/Android/plugin.wemo/src/oic/plugin/wemo/Activator.java
new file mode 100644 (file)
index 0000000..42aa81e
--- /dev/null
@@ -0,0 +1,182 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file Activator.java
+
+package oic.plugin.wemo;
+
+import java.util.ArrayList;
+import java.util.EnumSet;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ResourceProperty;
+import org.iotivity.base.ServiceType;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.belkin.wemo.localsdk.WeMoDevice;
+import com.belkin.wemo.localsdk.WeMoSDKContext;
+
+public class Activator extends Activity implements BundleActivator,
+        WeMoSDKContext.NotificationListener {
+    final private static String  TAG             = "SimpleClient";
+
+    private static BundleContext context;
+    private Context              AppContext;
+    public static WeMoSDKContext mWeMoSDKContext = null;
+    WeMoDevice                   wemoDevice;
+
+    static class SmartPlug {
+        public String m_power;
+        public String m_name;
+
+        public SmartPlug() {
+            m_power = "";
+            m_name = "";
+        }
+    }
+
+    static int                     OBSERVE_TYPE_TO_USE = ObserveType.OBSERVE
+                                                               .getValue();
+
+    public static SmartPlug        mySmartPlug;
+    public static OcResource       curResource;
+    public static OcResourceHandle resourceHandle;
+    static int                     oc                  = 0;
+    static Activity                mActivity;
+
+    static BundleContext getContext() {
+
+        return context;
+    }
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mActivity = this;
+    }
+
+    public void start(BundleContext bundleContext) throws Exception {
+        /*
+         * OSGi bundle context
+         */
+        context = bundleContext;
+
+        /*
+         * Android Application Context
+         */
+        ServiceReference<Context> ref = context
+                .getServiceReference(Context.class);
+        this.AppContext = ((Context) context.getService(ref));
+
+        /*
+         * WeMo Context
+         */
+        this.mWeMoSDKContext = new WeMoSDKContext(this.AppContext);
+        this.mWeMoSDKContext.addNotificationListener(this);
+        refresh();
+
+        mySmartPlug = new SmartPlug();
+    }
+
+    public void stop(BundleContext bundleContext) throws Exception {
+        OcPlatform.unregisterResource(resourceHandle);
+        context = null;
+        mWeMoSDKContext = null;
+        mySmartPlug = null;
+
+    }
+
+    public void onNotify(final String event, final String udn) {
+        runOnUiThread(new Runnable() {
+            public void run() {
+                Activator.this.wemoDevice = Activator.this.mWeMoSDKContext
+                        .getWeMoDeviceByUDN(udn);
+                if (event.equals("refresh")) {
+                    ArrayList<String> udns = Activator.this.mWeMoSDKContext
+                            .getListOfWeMoDevicesOnLAN();
+                    ArrayList<WeMoDevice> wemoDevices = new ArrayList();
+                    for (String udn : udns) {
+                        WeMoDevice listDevice = Activator.this.mWeMoSDKContext
+                                .getWeMoDeviceByUDN(udn);
+                        if ((listDevice != null) && (listDevice.isAvailable())) {
+                            wemoDevices.add(listDevice);
+                            Log.i("WeMoPlugin", "WeMo Decive Name: "
+                                    + listDevice.getFriendlyName());
+                            Log.i("WeMoPlugin", "WeMo Decive UDN: "
+                                    + listDevice.getUDN());
+                            Log.i("WeMoPlugin", "WeMo Decive Type: "
+                                    + listDevice.getType());
+                            Log.i("WeMoPlugin", "WeMo Decive Serial #: "
+                                    + listDevice.getSerialNumber());
+                        }
+                    }
+                } else if (event.equals(WeMoSDKContext.ADD_DEVICE)) {
+                    ArrayList<String> udns = Activator.this.mWeMoSDKContext
+                            .getListOfWeMoDevicesOnLAN();
+                    ArrayList<WeMoDevice> wemoDevices = new ArrayList();
+                    for (String udn : udns) {
+                        WeMoDevice listDevice = Activator.this.mWeMoSDKContext
+                                .getWeMoDeviceByUDN(udn);
+                        if ((listDevice != null) && (listDevice.isAvailable())) {
+                            PlatformConfig cfg = new PlatformConfig(
+                                    this,
+                                    ServiceType.IN_PROC,
+                                    ModeType.CLIENT_SERVER, "0.0.0.0", 0,
+                                    QualityOfService.LOW);
+
+                            OcPlatform.Configure(cfg);
+
+                            EntityHandlerWemo entitycb = new EntityHandlerWemo();
+                            try {
+                                resourceHandle = OcPlatform
+                                        .registerResource(
+                                                "/a/wemo",
+                                                "device.smartplug",
+                                                "oc.mi.def",
+                                                entitycb,
+                                                EnumSet.of(ResourceProperty.DISCOVERABLE));
+                            } catch (OcException e) {
+                                e.printStackTrace();
+                            }
+                        }
+                    }
+                }
+            }
+        });
+    }
+
+    private void refresh() {
+        this.mWeMoSDKContext.refreshListOfWeMoDevicesOnLAN();
+    }
+}
diff --git a/service/protocol-plugin/plugins/Android/plugin.wemo/src/oic/plugin/wemo/EntityHandlerWemo.java b/service/protocol-plugin/plugins/Android/plugin.wemo/src/oic/plugin/wemo/EntityHandlerWemo.java
new file mode 100644 (file)
index 0000000..559cc21
--- /dev/null
@@ -0,0 +1,136 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file EntityHandlerWemo.java
+
+package oic.plugin.wemo;
+
+import java.util.ArrayList;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+
+import android.util.Log;
+
+import com.belkin.wemo.localsdk.WeMoDevice;
+
+public class EntityHandlerWemo implements OcPlatform.EntityHandler {
+
+    final private static String TAG = "EntityHandlerWeMo";
+
+    public EntityHandlerResult handleEntity(OcResourceRequest resourcerequest) {
+        Log.e(TAG, "Entity Handler callback");
+
+        // OcResourceResponse response = new OcResourceResponse();
+
+        if (resourcerequest != null
+                && resourcerequest.getResourceUri().equals("/a/wemo")) {
+            RequestType requestType = resourcerequest.getRequestType();
+            EnumSet<RequestHandlerFlag> handlerFlagSet = resourcerequest
+                    .getRequestHandlerFlagSet();
+
+            if(handlerFlagSet.contains(RequestHandlerFlag.INIT))
+            {
+                Log.e(TAG, "requestFlag : Init");
+            }
+            if(handlerFlagSet.contains(RequestHandlerFlag.REQUEST))
+            {
+                OcResourceResponse response = new OcResourceResponse();
+                OcRepresentation representation = new OcRepresentation();
+                response.setRequestHandle(resourcerequest
+                        .getRequestHandle());
+                response.setResourceHandle(resourcerequest
+                        .getResourceHandle());
+                switch (requestType) {
+                    case GET:
+                        ArrayList<String> udns = Activator.mWeMoSDKContext
+                                .getListOfWeMoDevicesOnLAN();
+                        for (String udn : udns) {
+                            WeMoDevice wemoDevice = Activator.mWeMoSDKContext
+                                    .getWeMoDeviceByUDN(udn);
+                            if (wemoDevice.getState() == "0") {
+                                Activator.mySmartPlug.m_power = "off";
+                            } else if (wemoDevice.getState() == "1") {
+                                Activator.mySmartPlug.m_power = "on";
+                            }
+                        }
+                        break;
+                    case PUT:
+                        ArrayList<String> uudns = Activator.mWeMoSDKContext
+                                .getListOfWeMoDevicesOnLAN();
+                        for (String udn : uudns) {
+                            WeMoDevice wemoDevice = Activator.mWeMoSDKContext
+                                    .getWeMoDeviceByUDN(udn);
+                            String type = wemoDevice.getType();
+                            if (type.equals(WeMoDevice.SWITCH)) {
+                                String newState = "";
+                                if (resourcerequest
+                                        .getResourceRepresentation()
+                                        .getValueString("power")
+                                        .equals("on")) {
+                                    Activator.mySmartPlug.m_power = "on";
+                                    newState = WeMoDevice.WEMO_DEVICE_ON;
+                                } else if (resourcerequest
+                                        .getResourceRepresentation()
+                                        .getValueString("power")
+                                        .equals("off")) {
+                                    Activator.mySmartPlug.m_power = "off";
+                                    newState = WeMoDevice.WEMO_DEVICE_OFF;
+                                }
+                                Activator.mWeMoSDKContext.setDeviceState(
+                                        newState, wemoDevice.getUDN());
+                            }
+                        }
+                        break;
+                    case POST:
+                        break;
+                }
+                response.setErrorCode(200);
+                // representation.setUri("/a/wemo");
+                representation.setValueString("name",
+                        Activator.mySmartPlug.m_name);
+                representation.setValueString("power",
+                        Activator.mySmartPlug.m_power);
+                representation.setValueInt("brightness", 0);
+                representation.setValueInt("color", 0);
+                response.setResourceRepresentation(representation);
+                try {
+                    OcPlatform.sendResponse(response);
+                } catch (OcException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                    return EntityHandlerResult.ERROR;
+                }
+            }
+            if(handlerFlagSet.contains(RequestHandlerFlag.OBSERVER))
+            {
+                Log.e(TAG, "requestFlag : Observer");
+            }
+            return EntityHandlerResult.OK;
+        }
+        return EntityHandlerResult.ERROR;
+    }
+}
index 5e5d919..376fe96 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
 ##
@@ -17,19 +36,21 @@ target_os = env.get('TARGET_OS')
 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.AppendUnique(LINKFLAGS = ['-fPIC'])
+    plugins_env.AppendUnique(CXXFLAGS = ['-g3', '-Wall', '-pthread', '-std=c++0x'])
+    plugins_env.PrependUnique(CCFLAGS = ['-fPIC'])
+    plugins_env.AppendUnique(LINKFLAGS = ['-fPIC'])
 
-       if target_os not in ['arduino', 'android']:
-               plugins_env.AppendUnique(LIBS = ['pthread'])
+#plugins_env.AppendUnique(LIBS=['libconnectivity-abstraction'])
+
+    if target_os not in ['arduino', 'android']:
+        plugins_env.AppendUnique(LIBS = ['pthread'])
 
 if target_os == 'android':
-       plugins_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       plugins_env.AppendUnique(LIBS = ['gnustl_static'])
+    plugins_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+    plugins_env.AppendUnique(LIBS = ['gnustl_shared'])
 
 plugins_env.AppendUnique(LIBS = [File(env.get('BUILD_DIR') + '/libmosquitto.a'),
-               'mosquitto', 'ssl', 'rt'])
+        'mosquitto', 'ssl', 'rt'])
 
 
 ######################################################################
diff --git a/service/protocol-plugin/plugins/mqtt-fan/build/linux/Makefile b/service/protocol-plugin/plugins/mqtt-fan/build/linux/Makefile
deleted file mode 100644 (file)
index 248e35c..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-CXX = g++
-
-CXX_FLAGS = -std=c++0x -Wall -pthread
-
-TOP_DIR = ../../../../../..
-LIB_DIR = ../../../../../../resource
-
-SRC_DIR = ../../src
-
-DEPEND_DIR:= $(LIB_DIR)/dependencies
-CEREAL_DIR:= $(DEPEND_DIR)/cereal
-
-CXX_INC := -I$(LIB_DIR)/include/ 
-CXX_INC += -I$(LIB_DIR)/oc_logger/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/stack/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/ocsocket/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/ocrandom/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/logger/include/
-CXX_INC += -I$(BOOST_DIR) 
-CXX_INC += -I../../lib 
-CXX_INC += -I../../../../lib/cpluff/libcpluff
-CXX_INC          += -I../csdk/libcoap
-CXX_INC   += -I$(CEREAL_DIR)/include
-
-LIB_OC_LOGGER := $(LIB_DIR)/oc_logger/lib/oc_logger.a
-CXX_LIBS  := ../../../../lib/cpluff/libcpluff/.libs/libcpluff.a
-
-.PHONY: lib release_build ./release/fanserver_mqtt_plugin.so 
-
-all: .PHONY
-
-lib:
-       cd ../../lib && $(MAKE)
-
-release_build:
-       -mkdir release
-       -mkdir release/obj
-       cp plugin.xml release
-
-./release/fanserver_mqtt_plugin.so: ./release/obj/fanserver_mqtt_plugin.o ./release/obj/fanserver.o
-       $(CXX) -shared -o ./release/fanserver_mqtt_plugin.so ./release/obj/fanserver_mqtt_plugin.o ./release/obj/fanserver.o $(CXX_LIBS)  -L../../lib -L$(TOP_DIR)/out/linux/x86/release -lmosquitto -lssl -lrt -loc -loctbstack -loc_logger -lcoap
-
-./release/obj/fanserver_mqtt_plugin.o: $(SRC_DIR)/fanserver_mqtt_plugin.cpp
-       $(CXX) $(CXX_INC) -fPIC -o ./release/obj/fanserver_mqtt_plugin.o -c $(SRC_DIR)/fanserver_mqtt_plugin.cpp 
-
-./release/obj/fanserver.o: $(SRC_DIR)/fanserver.cpp
-       $(CXX) $(CXX_FLAGS) -fPIC -o ./release/obj/fanserver.o -c $(SRC_DIR)/fanserver.cpp $(CXX_INC)
-       
-clean:
-       cd ../../lib && $(MAKE) clean
-       rm -rf ./release/obj
-       cd ./release && rm -f *.so
diff --git a/service/protocol-plugin/plugins/mqtt-fan/lib/Makefile b/service/protocol-plugin/plugins/mqtt-fan/lib/Makefile
deleted file mode 100644 (file)
index 7c10ecb..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-include  config.mk
-
-.PHONY : really clean install
-
-MOSQ_OBJS=mosquitto.o \
-                 logging_mosq.o \
-                 memory_mosq.o \
-                 messages_mosq.o \
-                 net_mosq.o \
-                 read_handle.o \
-                 read_handle_client.o \
-                 read_handle_shared.o \
-                 send_mosq.o \
-                 send_client_mosq.o \
-                 srv_mosq.o \
-                 thread_mosq.o \
-                 time_mosq.o \
-                 tls_mosq.o \
-                 util_mosq.o \
-                 will_mosq.o
-
-all : libmosquitto.so.${SOVERSION} libmosquitto.a
-       $(MAKE) -C cpp
-       $(MAKE) -C python
-
-install : all
-       $(INSTALL) -d ${DESTDIR}$(prefix)/lib${LIB_SUFFIX}/
-       $(INSTALL) -s libmosquitto.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so.${SOVERSION}
-       ln -sf libmosquitto.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so
-       $(INSTALL) -d ${DESTDIR}${prefix}/include/
-       $(INSTALL) mosquitto.h ${DESTDIR}${prefix}/include/mosquitto.h
-       $(MAKE) -C cpp install
-       $(MAKE) -C python install
-
-uninstall :
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so.${SOVERSION}
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so
-       -rm -f ${DESTDIR}${prefix}/include/mosquitto.h
-
-reallyclean : clean
-
-clean :
-       -rm -f *.o libmosquitto.so.${SOVERSION} libmosquitto.so libmosquitto.a
-       $(MAKE) -C cpp clean
-       $(MAKE) -C python clean
-
-libmosquitto.so.${SOVERSION} : ${MOSQ_OBJS}
-       $(CC) -shared $(LIB_LDFLAGS) $^ -o $@ ${LIB_LIBS}
-
-libmosquitto.a : ${MOSQ_OBJS}
-       $(AR) cr $@ $^
-mosquitto.o : mosquitto.c mosquitto.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-logging_mosq.o : logging_mosq.c logging_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-messages_mosq.o : messages_mosq.c messages_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-memory_mosq.o : memory_mosq.c memory_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-net_mosq.o : net_mosq.c net_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-read_handle.o : read_handle.c read_handle.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-read_handle_client.o : read_handle_client.c read_handle.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-read_handle_shared.o : read_handle_shared.c read_handle.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-send_mosq.o : send_mosq.c send_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-send_client_mosq.o : send_client_mosq.c send_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-srv_mosq.o : srv_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-thread_mosq.o : thread_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-time_mosq.o : time_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-tls_mosq.o : tls_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-util_mosq.o : util_mosq.c util_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-will_mosq.o : will_mosq.c will_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
index a5695c2..fc2add8 100644 (file)
@@ -14,6 +14,8 @@ target_os = env.get('TARGET_OS')
 ######################################################################
 mosquitto_env.AppendUnique(CPPPATH = ['./'])
 if target_os not in ['windows', 'winrt']:
+       # strdup() and pselect() require specific extensions to be enabled.
+       mosquitto_env.AppendUnique(CPPDEFINES = [('_XOPEN_SOURCE', 600)])
        mosquitto_env.AppendUnique(CFLAGS = ['-Wall', '-ggdb', '-fPIC',
                        '-DWITH_TLS', '-DWITH_TLS_PSK', '-DWITH_THREADING'])
 ######################################################################
diff --git a/service/protocol-plugin/plugins/mqtt-fan/lib/cpp/Makefile b/service/protocol-plugin/plugins/mqtt-fan/lib/cpp/Makefile
deleted file mode 100644 (file)
index 8e04b6c..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-include ../config.mk
-
-ifneq ($(UNAME),SunOS)
-       LIB_LDFLAGS:=$(LDFLAGS) -Wl,-soname,libmosquittopp.so.${SOVERSION}
-endif
-
-.PHONY : clean install
-
-all : libmosquittopp.so.${SOVERSION}
-
-install : all
-       $(INSTALL) -d ${DESTDIR}$(prefix)/lib${LIB_SUFFIX}/
-       $(INSTALL) -s libmosquittopp.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so.${SOVERSION}
-       ln -sf libmosquittopp.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so
-       $(INSTALL) -d ${DESTDIR}${prefix}/include/
-       $(INSTALL) mosquittopp.h ${DESTDIR}${prefix}/include/mosquittopp.h
-       
-uninstall :
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so.${SOVERSION}
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so
-       -rm -f ${DESTDIR}${prefix}/include/mosquittopp.h
-
-clean :
-       -rm -f *.o libmosquittopp.so.${SOVERSION}
-
-libmosquittopp.so.${SOVERSION} : mosquittopp.o
-       $(CXX) -shared $(LIB_LDFLAGS) $< -o $@ ../libmosquitto.so.${SOVERSION}
-
-mosquittopp.o : mosquittopp.cpp mosquittopp.h
-       $(CXX) $(LIB_CXXFLAGS) -c $< -o $@
-
index fa4e436..dafb375 100644 (file)
@@ -31,275 +31,284 @@ POSSIBILITY OF SUCH DAMAGE.
 #include <mosquitto.h>
 #include <mosquittopp.h>
 
-namespace mosqpp {
-
-static void on_connect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_connect(rc);
-}
-
-static void on_disconnect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_disconnect(rc);
-}
-
-static void on_publish_wrapper(struct mosquitto *mosq, void *userdata, int mid)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_publish(mid);
-}
-
-static void on_message_wrapper(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_message(message);
-}
-
-static void on_subscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_subscribe(mid, qos_count, granted_qos);
-}
-
-static void on_unsubscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_unsubscribe(mid);
-}
-
-
-static void on_log_wrapper(struct mosquitto *mosq, void *userdata, int level, const char *str)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_log(level, str);
-}
-
-int lib_version(int *major, int *minor, int *revision)
-{
-       if(major) *major = LIBMOSQUITTO_MAJOR;
-       if(minor) *minor = LIBMOSQUITTO_MINOR;
-       if(revision) *revision = LIBMOSQUITTO_REVISION;
-       return LIBMOSQUITTO_VERSION_NUMBER;
-}
-
-int lib_init()
-{
-       return mosquitto_lib_init();
-}
-
-int lib_cleanup()
-{
-       return mosquitto_lib_cleanup();
-}
-
-const char* strerror(int mosq_errno)
-{
-       return mosquitto_strerror(mosq_errno);
-}
-
-const char* connack_string(int connack_code)
-{
-       return mosquitto_connack_string(connack_code);
-}
-
-int sub_topic_tokenise(const char *subtopic, char ***topics, int *count)
-{
-       return mosquitto_sub_topic_tokenise(subtopic, topics, count);
-}
-
-int sub_topic_tokens_free(char ***topics, int count)
-{
-       return mosquitto_sub_topic_tokens_free(topics, count);
-}
-
-int topic_matches_sub(const char *sub, const char *topic, bool *result)
-{
-       return mosquitto_topic_matches_sub(sub, topic, result);
-}
-
-mosquittopp::mosquittopp(const char *id, bool clean_session)
-{
-       m_mosq = mosquitto_new(id, clean_session, this);
-       mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
-       mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
-       mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
-       mosquitto_message_callback_set(m_mosq, on_message_wrapper);
-       mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
-       mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
-       mosquitto_log_callback_set(m_mosq, on_log_wrapper);
-}
-
-mosquittopp::~mosquittopp()
-{
-       mosquitto_destroy(m_mosq);
-}
-
-int mosquittopp::reinitialise(const char *id, bool clean_session)
-{
-       int rc;
-       rc = mosquitto_reinitialise(m_mosq, id, clean_session, this);
-       if(rc == MOSQ_ERR_SUCCESS){
-               mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
-               mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
-               mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
-               mosquitto_message_callback_set(m_mosq, on_message_wrapper);
-               mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
-               mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
-               mosquitto_log_callback_set(m_mosq, on_log_wrapper);
-       }
-       return rc;
-}
-
-int mosquittopp::connect(const char *host, int port, int keepalive)
-{
-       return mosquitto_connect(m_mosq, host, port, keepalive);
-}
-
-int mosquittopp::connect(const char *host, int port, int keepalive, const char *bind_address)
-{
-       return mosquitto_connect_bind(m_mosq, host, port, keepalive, bind_address);
-}
-
-int mosquittopp::connect_async(const char *host, int port, int keepalive)
-{
-       return mosquitto_connect_async(m_mosq, host, port, keepalive);
-}
-
-int mosquittopp::connect_async(const char *host, int port, int keepalive, const char *bind_address)
-{
-       return mosquitto_connect_bind_async(m_mosq, host, port, keepalive, bind_address);
-}
-
-int mosquittopp::reconnect()
-{
-       return mosquitto_reconnect(m_mosq);
-}
-
-int mosquittopp::reconnect_async()
-{
-       return mosquitto_reconnect_async(m_mosq);
-}
-
-int mosquittopp::disconnect()
-{
-       return mosquitto_disconnect(m_mosq);
-}
-
-int mosquittopp::socket()
-{
-       return mosquitto_socket(m_mosq);
-}
-
-int mosquittopp::will_set(const char *topic, int payloadlen, const void *payload, int qos, bool retain)
-{
-       return mosquitto_will_set(m_mosq, topic, payloadlen, payload, qos, retain);
-}
-
-int mosquittopp::will_clear()
-{
-       return mosquitto_will_clear(m_mosq);
-}
-
-int mosquittopp::username_pw_set(const char *username, const char *password)
-{
-       return mosquitto_username_pw_set(m_mosq, username, password);
-}
-
-int mosquittopp::publish(int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain)
-{
-       return mosquitto_publish(m_mosq, mid, topic, payloadlen, payload, qos, retain);
-}
-
-void mosquittopp::reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff)
-{
-       mosquitto_reconnect_delay_set(m_mosq, reconnect_delay, reconnect_delay_max, reconnect_exponential_backoff);
-}
-
-int mosquittopp::max_inflight_messages_set(unsigned int max_inflight_messages)
-{
-       return mosquitto_max_inflight_messages_set(m_mosq, max_inflight_messages);
-}
-
-void mosquittopp::message_retry_set(unsigned int message_retry)
-{
-       mosquitto_message_retry_set(m_mosq, message_retry);
-}
-
-int mosquittopp::subscribe(int *mid, const char *sub, int qos)
-{
-       return mosquitto_subscribe(m_mosq, mid, sub, qos);
-}
-
-int mosquittopp::unsubscribe(int *mid, const char *sub)
-{
-       return mosquitto_unsubscribe(m_mosq, mid, sub);
-}
-
-int mosquittopp::loop(int timeout, int max_packets)
-{
-       return mosquitto_loop(m_mosq, timeout, max_packets);
-}
-
-int mosquittopp::loop_misc()
-{
-       return mosquitto_loop_misc(m_mosq);
-}
-
-int mosquittopp::loop_read(int max_packets)
-{
-       return mosquitto_loop_read(m_mosq, max_packets);
-}
-
-int mosquittopp::loop_write(int max_packets)
-{
-       return mosquitto_loop_write(m_mosq, max_packets);
-}
-
-int mosquittopp::loop_forever(int timeout, int max_packets)
-{
-       return mosquitto_loop_forever(m_mosq, timeout, max_packets);
-}
-
-int mosquittopp::loop_start()
-{
-       return mosquitto_loop_start(m_mosq);
-}
-
-int mosquittopp::loop_stop(bool force)
-{
-       return mosquitto_loop_stop(m_mosq, force);
-}
-
-bool mosquittopp::want_write()
-{
-       return mosquitto_want_write(m_mosq);
-}
-
-void mosquittopp::user_data_set(void *userdata)
-{
-       mosquitto_user_data_set(m_mosq, userdata);
-}
-
-int mosquittopp::tls_set(const char *cafile, const char *capath, const char *certfile, const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata))
-{
-       return mosquitto_tls_set(m_mosq, cafile, capath, certfile, keyfile, pw_callback);
-}
-
-int mosquittopp::tls_opts_set(int cert_reqs, const char *tls_version, const char *ciphers)
-{
-       return mosquitto_tls_opts_set(m_mosq, cert_reqs, tls_version, ciphers);
-}
-
-int mosquittopp::tls_insecure_set(bool value)
-{
-       return mosquitto_tls_insecure_set(m_mosq, value);
-}
-
-int mosquittopp::tls_psk_set(const char *psk, const char *identity, const char *ciphers)
-{
-       return mosquitto_tls_psk_set(m_mosq, psk, identity, ciphers);
-}
+namespace mosqpp
+{
+
+    static void on_connect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_connect(rc);
+    }
+
+    static void on_disconnect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_disconnect(rc);
+    }
+
+    static void on_publish_wrapper(struct mosquitto *mosq, void *userdata, int mid)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_publish(mid);
+    }
+
+    static void on_message_wrapper(struct mosquitto *mosq, void *userdata,
+                                   const struct mosquitto_message *message)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_message(message);
+    }
+
+    static void on_subscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid, int qos_count,
+                                     const int *granted_qos)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_subscribe(mid, qos_count, granted_qos);
+    }
+
+    static void on_unsubscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_unsubscribe(mid);
+    }
+
+
+    static void on_log_wrapper(struct mosquitto *mosq, void *userdata, int level, const char *str)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_log(level, str);
+    }
+
+    int lib_version(int *major, int *minor, int *revision)
+    {
+        if (major) *major = LIBMOSQUITTO_MAJOR;
+        if (minor) *minor = LIBMOSQUITTO_MINOR;
+        if (revision) *revision = LIBMOSQUITTO_REVISION;
+        return LIBMOSQUITTO_VERSION_NUMBER;
+    }
+
+    int lib_init()
+    {
+        return mosquitto_lib_init();
+    }
+
+    int lib_cleanup()
+    {
+        return mosquitto_lib_cleanup();
+    }
+
+    const char *strerror(int mosq_errno)
+    {
+        return mosquitto_strerror(mosq_errno);
+    }
+
+    const char *connack_string(int connack_code)
+    {
+        return mosquitto_connack_string(connack_code);
+    }
+
+    int sub_topic_tokenise(const char *subtopic, char ***topics, int *count)
+    {
+        return mosquitto_sub_topic_tokenise(subtopic, topics, count);
+    }
+
+    int sub_topic_tokens_free(char ***topics, int count)
+    {
+        return mosquitto_sub_topic_tokens_free(topics, count);
+    }
+
+    int topic_matches_sub(const char *sub, const char *topic, bool *result)
+    {
+        return mosquitto_topic_matches_sub(sub, topic, result);
+    }
+
+    mosquittopp::mosquittopp(const char *id, bool clean_session)
+    {
+        m_mosq = mosquitto_new(id, clean_session, this);
+        mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
+        mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
+        mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
+        mosquitto_message_callback_set(m_mosq, on_message_wrapper);
+        mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
+        mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
+        mosquitto_log_callback_set(m_mosq, on_log_wrapper);
+    }
+
+    mosquittopp::~mosquittopp()
+    {
+        mosquitto_destroy(m_mosq);
+    }
+
+    int mosquittopp::reinitialise(const char *id, bool clean_session)
+    {
+        int rc;
+        rc = mosquitto_reinitialise(m_mosq, id, clean_session, this);
+        if (rc == MOSQ_ERR_SUCCESS)
+        {
+            mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
+            mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
+            mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
+            mosquitto_message_callback_set(m_mosq, on_message_wrapper);
+            mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
+            mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
+            mosquitto_log_callback_set(m_mosq, on_log_wrapper);
+        }
+        return rc;
+    }
+
+    int mosquittopp::connect(const char *host, int port, int keepalive)
+    {
+        return mosquitto_connect(m_mosq, host, port, keepalive);
+    }
+
+    int mosquittopp::connect(const char *host, int port, int keepalive, const char *bind_address)
+    {
+        return mosquitto_connect_bind(m_mosq, host, port, keepalive, bind_address);
+    }
+
+    int mosquittopp::connect_async(const char *host, int port, int keepalive)
+    {
+        return mosquitto_connect_async(m_mosq, host, port, keepalive);
+    }
+
+    int mosquittopp::connect_async(const char *host, int port, int keepalive, const char *bind_address)
+    {
+        return mosquitto_connect_bind_async(m_mosq, host, port, keepalive, bind_address);
+    }
+
+    int mosquittopp::reconnect()
+    {
+        return mosquitto_reconnect(m_mosq);
+    }
+
+    int mosquittopp::reconnect_async()
+    {
+        return mosquitto_reconnect_async(m_mosq);
+    }
+
+    int mosquittopp::disconnect()
+    {
+        return mosquitto_disconnect(m_mosq);
+    }
+
+    int mosquittopp::socket()
+    {
+        return mosquitto_socket(m_mosq);
+    }
+
+    int mosquittopp::will_set(const char *topic, int payloadlen, const void *payload, int qos,
+                              bool retain)
+    {
+        return mosquitto_will_set(m_mosq, topic, payloadlen, payload, qos, retain);
+    }
+
+    int mosquittopp::will_clear()
+    {
+        return mosquitto_will_clear(m_mosq);
+    }
+
+    int mosquittopp::username_pw_set(const char *username, const char *password)
+    {
+        return mosquitto_username_pw_set(m_mosq, username, password);
+    }
+
+    int mosquittopp::publish(int *mid, const char *topic, int payloadlen, const void *payload, int qos,
+                             bool retain)
+    {
+        return mosquitto_publish(m_mosq, mid, topic, payloadlen, payload, qos, retain);
+    }
+
+    void mosquittopp::reconnect_delay_set(unsigned int reconnect_delay,
+                                          unsigned int reconnect_delay_max, bool reconnect_exponential_backoff)
+    {
+        mosquitto_reconnect_delay_set(m_mosq, reconnect_delay, reconnect_delay_max,
+                                      reconnect_exponential_backoff);
+    }
+
+    int mosquittopp::max_inflight_messages_set(unsigned int max_inflight_messages)
+    {
+        return mosquitto_max_inflight_messages_set(m_mosq, max_inflight_messages);
+    }
+
+    void mosquittopp::message_retry_set(unsigned int message_retry)
+    {
+        mosquitto_message_retry_set(m_mosq, message_retry);
+    }
+
+    int mosquittopp::subscribe(int *mid, const char *sub, int qos)
+    {
+        return mosquitto_subscribe(m_mosq, mid, sub, qos);
+    }
+
+    int mosquittopp::unsubscribe(int *mid, const char *sub)
+    {
+        return mosquitto_unsubscribe(m_mosq, mid, sub);
+    }
+
+    int mosquittopp::loop(int timeout, int max_packets)
+    {
+        return mosquitto_loop(m_mosq, timeout, max_packets);
+    }
+
+    int mosquittopp::loop_misc()
+    {
+        return mosquitto_loop_misc(m_mosq);
+    }
+
+    int mosquittopp::loop_read(int max_packets)
+    {
+        return mosquitto_loop_read(m_mosq, max_packets);
+    }
+
+    int mosquittopp::loop_write(int max_packets)
+    {
+        return mosquitto_loop_write(m_mosq, max_packets);
+    }
+
+    int mosquittopp::loop_forever(int timeout, int max_packets)
+    {
+        return mosquitto_loop_forever(m_mosq, timeout, max_packets);
+    }
+
+    int mosquittopp::loop_start()
+    {
+        return mosquitto_loop_start(m_mosq);
+    }
+
+    int mosquittopp::loop_stop(bool force)
+    {
+        return mosquitto_loop_stop(m_mosq, force);
+    }
+
+    bool mosquittopp::want_write()
+    {
+        return mosquitto_want_write(m_mosq);
+    }
+
+    void mosquittopp::user_data_set(void *userdata)
+    {
+        mosquitto_user_data_set(m_mosq, userdata);
+    }
+
+    int mosquittopp::tls_set(const char *cafile, const char *capath, const char *certfile,
+                             const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata))
+    {
+        return mosquitto_tls_set(m_mosq, cafile, capath, certfile, keyfile, pw_callback);
+    }
+
+    int mosquittopp::tls_opts_set(int cert_reqs, const char *tls_version, const char *ciphers)
+    {
+        return mosquitto_tls_opts_set(m_mosq, cert_reqs, tls_version, ciphers);
+    }
+
+    int mosquittopp::tls_insecure_set(bool value)
+    {
+        return mosquitto_tls_insecure_set(m_mosq, value);
+    }
+
+    int mosquittopp::tls_psk_set(const char *psk, const char *identity, const char *ciphers)
+    {
+        return mosquitto_tls_psk_set(m_mosq, psk, identity, ciphers);
+    }
 
 }
index 41537b6..8e3cabf 100644 (file)
@@ -38,85 +38,92 @@ This product includes software written by Tim Hudson (tjh@cryptsoft.com)
 #define _MOSQUITTOPP_H_
 
 #ifdef _WIN32
-#      ifdef mosquittopp_EXPORTS
-#              define mosqpp_EXPORT  __declspec(dllexport)
-#      else
-#              define mosqpp_EXPORT  __declspec(dllimport)
-#      endif
+#   ifdef mosquittopp_EXPORTS
+#       define mosqpp_EXPORT  __declspec(dllexport)
+#   else
+#       define mosqpp_EXPORT  __declspec(dllimport)
+#   endif
 #else
-#      define mosqpp_EXPORT
+#   define mosqpp_EXPORT
 #endif
 
 #include <cstdlib>
 #include <time.h>
 #include "../mosquitto.h"
 
-namespace mosqpp {
+namespace mosqpp
+{
 
-mosqpp_EXPORT const char *strerror(int mosq_errno);
-mosqpp_EXPORT const char *connack_string(int connack_code);
-mosqpp_EXPORT int sub_topic_tokenise(const char *subtopic, char ***topics, int *count);
-mosqpp_EXPORT int sub_topic_tokens_free(char ***topics, int count);
-mosqpp_EXPORT int lib_version(int *major, int *minor, int *revision);
-mosqpp_EXPORT int lib_init();
-mosqpp_EXPORT int lib_cleanup();
-mosqpp_EXPORT int topic_matches_sub(const char *sub, const char *topic, bool *result);
+    mosqpp_EXPORT const char *strerror(int mosq_errno);
+    mosqpp_EXPORT const char *connack_string(int connack_code);
+    mosqpp_EXPORT int sub_topic_tokenise(const char *subtopic, char ***topics, int *count);
+    mosqpp_EXPORT int sub_topic_tokens_free(char ***topics, int count);
+    mosqpp_EXPORT int lib_version(int *major, int *minor, int *revision);
+    mosqpp_EXPORT int lib_init();
+    mosqpp_EXPORT int lib_cleanup();
+    mosqpp_EXPORT int topic_matches_sub(const char *sub, const char *topic, bool *result);
 
-/*
- * Class: mosquittopp
- *
- * A mosquitto client class. This is a C++ wrapper class for the mosquitto C
- * library. Please see mosquitto.h for details of the functions.
- */
-class mosqpp_EXPORT mosquittopp {
-       private:
-               struct mosquitto *m_mosq;
-       public:
-               mosquittopp(const char *id=NULL, bool clean_session=true);
-               ~mosquittopp();
+    /*
+     * Class: mosquittopp
+     *
+     * A mosquitto client class. This is a C++ wrapper class for the mosquitto C
+     * library. Please see mosquitto.h for details of the functions.
+     */
+    class mosqpp_EXPORT mosquittopp
+    {
+        private:
+            struct mosquitto *m_mosq;
+        public:
+            mosquittopp(const char *id = NULL, bool clean_session = true);
+            ~mosquittopp();
+
+            int reinitialise(const char *id, bool clean_session);
+            int socket();
+            int will_set(const char *topic, int payloadlen = 0, const void *payload = NULL, int qos = 0,
+                         bool retain = false);
+            int will_clear();
+            int username_pw_set(const char *username, const char *password = NULL);
+            int connect(const char *host, int port = 1883, int keepalive = 60);
+            int connect_async(const char *host, int port = 1883, int keepalive = 60);
+            int connect(const char *host, int port, int keepalive, const char *bind_address);
+            int connect_async(const char *host, int port, int keepalive, const char *bind_address);
+            int reconnect();
+            int reconnect_async();
+            int disconnect();
+            int publish(int *mid, const char *topic, int payloadlen = 0, const void *payload = NULL,
+                        int qos = 0, bool retain = false);
+            int subscribe(int *mid, const char *sub, int qos = 0);
+            int unsubscribe(int *mid, const char *sub);
+            void reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max,
+                                     bool reconnect_exponential_backoff);
+            int max_inflight_messages_set(unsigned int max_inflight_messages);
+            void message_retry_set(unsigned int message_retry);
+            void user_data_set(void *userdata);
+            int tls_set(const char *cafile, const char *capath = NULL, const char *certfile = NULL,
+                        const char *keyfile = NULL, int (*pw_callback)(char *buf, int size, int rwflag,
+                                void *userdata) = NULL);
+            int tls_opts_set(int cert_reqs, const char *tls_version = NULL, const char *ciphers = NULL);
+            int tls_insecure_set(bool value);
+            int tls_psk_set(const char *psk, const char *identity, const char *ciphers = NULL);
 
-               int reinitialise(const char *id, bool clean_session);
-               int socket();
-               int will_set(const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false);
-               int will_clear();
-               int username_pw_set(const char *username, const char *password=NULL);
-               int connect(const char *host, int port=1883, int keepalive=60);
-               int connect_async(const char *host, int port=1883, int keepalive=60);
-               int connect(const char *host, int port, int keepalive, const char *bind_address);
-               int connect_async(const char *host, int port, int keepalive, const char *bind_address);
-               int reconnect();
-               int reconnect_async();
-               int disconnect();
-               int publish(int *mid, const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false);
-               int subscribe(int *mid, const char *sub, int qos=0);
-               int unsubscribe(int *mid, const char *sub);
-               void reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff);
-               int max_inflight_messages_set(unsigned int max_inflight_messages);
-               void message_retry_set(unsigned int message_retry);
-               void user_data_set(void *userdata);
-               int tls_set(const char *cafile, const char *capath=NULL, const char *certfile=NULL, const char *keyfile=NULL, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)=NULL);
-               int tls_opts_set(int cert_reqs, const char *tls_version=NULL, const char *ciphers=NULL);
-               int tls_insecure_set(bool value);
-               int tls_psk_set(const char *psk, const char *identity, const char *ciphers=NULL);
+            int loop(int timeout = -1, int max_packets = 1);
+            int loop_misc();
+            int loop_read(int max_packets = 1);
+            int loop_write(int max_packets = 1);
+            int loop_forever(int timeout = -1, int max_packets = 1);
+            int loop_start();
+            int loop_stop(bool force = false);
+            bool want_write();
 
-               int loop(int timeout=-1, int max_packets=1);
-               int loop_misc();
-               int loop_read(int max_packets=1);
-               int loop_write(int max_packets=1);
-               int loop_forever(int timeout=-1, int max_packets=1);
-               int loop_start();
-               int loop_stop(bool force=false);
-               bool want_write();
-               
-               virtual void on_connect(int rc) {return;};
-               virtual void on_disconnect(int rc) {return;};
-               virtual void on_publish(int mid) {return;};
-               virtual void on_message(const struct mosquitto_message *message) {return;};
-               virtual void on_subscribe(int mid, int qos_count, const int *granted_qos) {return;};
-               virtual void on_unsubscribe(int mid) {return;};
-               virtual void on_log(int level, const char *str) {return;};
-               virtual void on_error() {return;};
-};
+            virtual void on_connect(int rc) {return;};
+            virtual void on_disconnect(int rc) {return;};
+            virtual void on_publish(int mid) {return;};
+            virtual void on_message(const struct mosquitto_message *message) {return;};
+            virtual void on_subscribe(int mid, int qos_count, const int *granted_qos) {return;};
+            virtual void on_unsubscribe(int mid) {return;};
+            virtual void on_log(int level, const char *str) {return;};
+            virtual void on_error() {return;};
+    };
 
 }
 #endif
index 31f3251..e71f525 100644 (file)
@@ -7,7 +7,7 @@
 
 #define pthread_mutex_init(A, B)
 #define pthread_mutex_destroy(A)
-#define pthread_mutex_lock(A) 
-#define pthread_mutex_unlock(A) 
+#define pthread_mutex_lock(A)
+#define pthread_mutex_unlock(A)
 
 #endif
index 199455e..3e3de97 100644 (file)
@@ -27,6 +27,19 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */
 
+#ifndef _POSIX_C_SOURCE
+// Defining _POSIX_C_SOURCE macro with 200809L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2008 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2008 base specification,
+// Refer http://pubs.opengroup.org/stage7tc1/
+//
+// For this specific file, see use of strndup,
+// Refer http://man7.org/linux/man-pages/man3/strdup.3.html
+#define _POSIX_C_SOURCE 200809L
+#endif
+
 #include "config.h"
 
 #include <stdlib.h>
index b9d0c8e..eebea23 100644 (file)
@@ -34,11 +34,15 @@ POSSIBILITY OF SUCH DAMAGE.
 
 void _mosquitto_message_cleanup_all(struct mosquitto *mosq);
 void _mosquitto_message_cleanup(struct mosquitto_message_all **message);
-int _mosquitto_message_delete(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir);
-void _mosquitto_message_queue(struct mosquitto *mosq, struct mosquitto_message_all *message, enum mosquitto_msg_direction dir);
+int _mosquitto_message_delete(struct mosquitto *mosq, uint16_t mid,
+                              enum mosquitto_msg_direction dir);
+void _mosquitto_message_queue(struct mosquitto *mosq, struct mosquitto_message_all *message,
+                              enum mosquitto_msg_direction dir);
 void _mosquitto_messages_reconnect_reset(struct mosquitto *mosq);
-int _mosquitto_message_remove(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir, struct mosquitto_message_all **message);
+int _mosquitto_message_remove(struct mosquitto *mosq, uint16_t mid,
+                              enum mosquitto_msg_direction dir, struct mosquitto_message_all **message);
 void _mosquitto_message_retry_check(struct mosquitto *mosq);
-int _mosquitto_message_out_update(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_state state);
+int _mosquitto_message_out_update(struct mosquitto *mosq, uint16_t mid,
+                                  enum mosquitto_msg_state state);
 
 #endif
index 7f94dea..070904a 100644 (file)
@@ -27,12 +27,27 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */
 
+#ifndef _POSIX_C_SOURCE
+// Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2001 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2001 base specification,
+// Refer http://pubs.opengroup.org/onlinepubs/009695399/
+//
+// For this specific file, see use of pselect,
+// Refer http://man7.org/linux/man-pages/man2/select.2.html
+#define _POSIX_C_SOURCE 200112L // Needed for pselect
+#endif
+
 #include <assert.h>
 #include <errno.h>
 #include <signal.h>
 #include <stdio.h>
 #include <string.h>
+#include <strings.h>
 #ifndef WIN32
+#include <strings.h>  /* for strcasecmp() */
 #include <sys/select.h>
 #include <sys/time.h>
 #include <unistd.h>
index 27506eb..ca3bf12 100644 (file)
@@ -42,25 +42,25 @@ extern "C" {
 #endif
 
 #if defined(WIN32) && !defined(WITH_BROKER)
-#      ifdef libmosquitto_EXPORTS
-#              define libmosq_EXPORT  __declspec(dllexport)
-#      else
-#              define libmosq_EXPORT  __declspec(dllimport)
-#      endif
+#   ifdef libmosquitto_EXPORTS
+#       define libmosq_EXPORT  __declspec(dllexport)
+#   else
+#       define libmosq_EXPORT  __declspec(dllimport)
+#   endif
 #else
-#      define libmosq_EXPORT
+#   define libmosq_EXPORT
 #endif
 
 #ifdef WIN32
-#      ifndef __cplusplus
-#              define bool char
-#              define true 1
-#              define false 0
-#      endif
+#   ifndef __cplusplus
+#       define bool char
+#       define true 1
+#       define false 0
+#   endif
 #else
-#      ifndef __cplusplus
-#              include <stdbool.h>
-#      endif
+#   ifndef __cplusplus
+#       include <stdbool.h>
+#   endif
 #endif
 
 #define LIBMOSQUITTO_MAJOR 1
@@ -81,48 +81,50 @@ extern "C" {
 #define MOSQ_LOG_ALL 0xFFFF
 
 /* Error values */
-enum mosq_err_t {
-       MOSQ_ERR_CONN_PENDING = -1,
-       MOSQ_ERR_SUCCESS = 0,
-       MOSQ_ERR_NOMEM = 1,
-       MOSQ_ERR_PROTOCOL = 2,
-       MOSQ_ERR_INVAL = 3,
-       MOSQ_ERR_NO_CONN = 4,
-       MOSQ_ERR_CONN_REFUSED = 5,
-       MOSQ_ERR_NOT_FOUND = 6,
-       MOSQ_ERR_CONN_LOST = 7,
-       MOSQ_ERR_TLS = 8,
-       MOSQ_ERR_PAYLOAD_SIZE = 9,
-       MOSQ_ERR_NOT_SUPPORTED = 10,
-       MOSQ_ERR_AUTH = 11,
-       MOSQ_ERR_ACL_DENIED = 12,
-       MOSQ_ERR_UNKNOWN = 13,
-       MOSQ_ERR_ERRNO = 14,
-       MOSQ_ERR_EAI = 15
+enum mosq_err_t
+{
+    MOSQ_ERR_CONN_PENDING = -1,
+    MOSQ_ERR_SUCCESS = 0,
+    MOSQ_ERR_NOMEM = 1,
+    MOSQ_ERR_PROTOCOL = 2,
+    MOSQ_ERR_INVAL = 3,
+    MOSQ_ERR_NO_CONN = 4,
+    MOSQ_ERR_CONN_REFUSED = 5,
+    MOSQ_ERR_NOT_FOUND = 6,
+    MOSQ_ERR_CONN_LOST = 7,
+    MOSQ_ERR_TLS = 8,
+    MOSQ_ERR_PAYLOAD_SIZE = 9,
+    MOSQ_ERR_NOT_SUPPORTED = 10,
+    MOSQ_ERR_AUTH = 11,
+    MOSQ_ERR_ACL_DENIED = 12,
+    MOSQ_ERR_UNKNOWN = 13,
+    MOSQ_ERR_ERRNO = 14,
+    MOSQ_ERR_EAI = 15
 };
 
 /* MQTT specification restricts client ids to a maximum of 23 characters */
 #define MOSQ_MQTT_ID_MAX_LENGTH 23
 
-struct mosquitto_message{
-       int mid;
-       char *topic;
-       void *payload;
-       int payloadlen;
-       int qos;
-       bool retain;
+struct mosquitto_message
+{
+    int mid;
+    char *topic;
+    void *payload;
+    int payloadlen;
+    int qos;
+    bool retain;
 };
 
 struct mosquitto;
 
 /*
  * Topic: Threads
- *     libmosquitto provides thread safe operation, with the exception of
- *     <mosquitto_lib_init> which is not thread safe.
+ *  libmosquitto provides thread safe operation, with the exception of
+ *  <mosquitto_lib_init> which is not thread safe.
  */
 /***************************************************
  * Important note
- * 
+ *
  * The following functions that deal with network operations will return
  * MOSQ_ERR_SUCCESS on success, but this does not mean that the operation has
  * taken place. An attempt will be made to write the network data, but if the
@@ -157,10 +159,10 @@ struct mosquitto;
  *             be returned in this variable.
  *
  * Returns:
- *     LIBMOSQUITTO_VERSION_NUMBER, which is a unique number based on the major,
- *             minor and revision values.
+ *  LIBMOSQUITTO_VERSION_NUMBER, which is a unique number based on the major,
+ *      minor and revision values.
  * See Also:
- *     <mosquitto_lib_cleanup>, <mosquitto_lib_init>
+ *  <mosquitto_lib_cleanup>, <mosquitto_lib_init>
  */
 libmosq_EXPORT int mosquitto_lib_version(int *major, int *minor, int *revision);
 
@@ -172,10 +174,10 @@ libmosq_EXPORT int mosquitto_lib_version(int *major, int *minor, int *revision);
  * This function is *not* thread safe.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - always
+ *  MOSQ_ERR_SUCCESS - always
  *
  * See Also:
- *     <mosquitto_lib_cleanup>, <mosquitto_lib_version>
+ *  <mosquitto_lib_cleanup>, <mosquitto_lib_version>
  */
 libmosq_EXPORT int mosquitto_lib_init(void);
 
@@ -185,10 +187,10 @@ libmosq_EXPORT int mosquitto_lib_init(void);
  * Call to free resources associated with the library.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - always
+ *  MOSQ_ERR_SUCCESS - always
  *
  * See Also:
- *     <mosquitto_lib_init>, <mosquitto_lib_version>
+ *  <mosquitto_lib_init>, <mosquitto_lib_version>
  */
 libmosq_EXPORT int mosquitto_lib_cleanup(void);
 
@@ -198,9 +200,9 @@ libmosq_EXPORT int mosquitto_lib_cleanup(void);
  * Create a new mosquitto client instance.
  *
  * Parameters:
- *     id -            String to use as the client id. If NULL, a random client id
- *                     will be generated. If id is NULL, clean_session must be true.
- *     clean_session - set to true to instruct the broker to clean all messages
+ *  id -            String to use as the client id. If NULL, a random client id
+ *                  will be generated. If id is NULL, clean_session must be true.
+ *  clean_session - set to true to instruct the broker to clean all messages
  *                  and subscriptions on disconnect, false to instruct it to
  *                  keep them. See the man page mqtt(7) for more details.
  *                  Note that a client will never discard its own outgoing
@@ -209,30 +211,30 @@ libmosq_EXPORT int mosquitto_lib_cleanup(void);
  *                  Use <mosquitto_reinitialise> to reset a client to its
  *                  original state.
  *                  Must be set to true if the id parameter is NULL.
- *     obj -           A user pointer that will be passed as an argument to any
+ *  obj -           A user pointer that will be passed as an argument to any
  *                  callbacks that are specified.
  *
  * Returns:
- *     Pointer to a struct mosquitto on success.
- *     NULL on failure. Interrogate errno to determine the cause for the failure:
+ *  Pointer to a struct mosquitto on success.
+ *  NULL on failure. Interrogate errno to determine the cause for the failure:
  *      - ENOMEM on out of memory.
  *      - EINVAL on invalid input parameters.
  *
  * See Also:
- *     <mosquitto_reinitialise>, <mosquitto_destroy>, <mosquitto_user_data_set>
+ *  <mosquitto_reinitialise>, <mosquitto_destroy>, <mosquitto_user_data_set>
  */
 libmosq_EXPORT struct mosquitto *mosquitto_new(const char *id, bool clean_session, void *obj);
 
-/* 
+/*
  * Function: mosquitto_destroy
  *
  * Use to free memory associated with a mosquitto client instance.
  *
  * Parameters:
- *     mosq - a struct mosquitto pointer to free.
+ *  mosq - a struct mosquitto pointer to free.
  *
  * See Also:
- *     <mosquitto_new>, <mosquitto_reinitialise>
+ *  <mosquitto_new>, <mosquitto_reinitialise>
  */
 libmosq_EXPORT void mosquitto_destroy(struct mosquitto *mosq);
 
@@ -245,63 +247,65 @@ libmosq_EXPORT void mosquitto_destroy(struct mosquitto *mosq);
  * same as the output of <mosquitto_new>.
  *
  * Parameters:
- *     mosq -          a valid mosquitto instance.
- *     id -            string to use as the client id. If NULL, a random client id
- *                     will be generated. If id is NULL, clean_session must be true.
- *     clean_session - set to true to instruct the broker to clean all messages
+ *  mosq -          a valid mosquitto instance.
+ *  id -            string to use as the client id. If NULL, a random client id
+ *                  will be generated. If id is NULL, clean_session must be true.
+ *  clean_session - set to true to instruct the broker to clean all messages
  *                  and subscriptions on disconnect, false to instruct it to
  *                  keep them. See the man page mqtt(7) for more details.
  *                  Must be set to true if the id parameter is NULL.
- *     obj -           A user pointer that will be passed as an argument to any
+ *  obj -           A user pointer that will be passed as an argument to any
  *                  callbacks that are specified.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_new>, <mosquitto_destroy>
+ *  <mosquitto_new>, <mosquitto_destroy>
  */
-libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_session, void *obj);
+libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id,
+        bool clean_session, void *obj);
 
-/* 
+/*
  * Function: mosquitto_will_set
  *
  * Configure will information for a mosquitto instance. By default, clients do
  * not have a will.  This must be called before calling <mosquitto_connect>.
  *
  * Parameters:
- *     mosq -       a valid mosquitto instance.
- *     topic -      the topic on which to publish the will.
- *     payloadlen - the size of the payload (bytes). Valid values are between 0 and
+ *  mosq -       a valid mosquitto instance.
+ *  topic -      the topic on which to publish the will.
+ *  payloadlen - the size of the payload (bytes). Valid values are between 0 and
  *               268,435,455.
- *     payload -    pointer to the data to send. If payloadlen > 0 this must be a
+ *  payload -    pointer to the data to send. If payloadlen > 0 this must be a
  *               valid memory location.
- *     qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
+ *  qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
  *               used for the will.
- *     retain -     set to true to make the will a retained message.
+ *  retain -     set to true to make the will a retained message.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -      on success.
- *     MOSQ_ERR_INVAL -        if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
- *     MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
+ *  MOSQ_ERR_SUCCESS -      on success.
+ *  MOSQ_ERR_INVAL -        if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
+ *  MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
  */
-libmosq_EXPORT int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain);
+libmosq_EXPORT int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen,
+                                      const void *payload, int qos, bool retain);
 
-/* 
+/*
  * Function: mosquitto_will_clear
  *
  * Remove a previously configured will. This must be called before calling
  * <mosquitto_connect>.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  */
 libmosq_EXPORT int mosquitto_will_clear(struct mosquitto *mosq);
 
@@ -317,18 +321,19 @@ libmosq_EXPORT int mosquitto_will_clear(struct mosquitto *mosq);
  * This is must be called before calling <mosquitto_connect>.
  *
  * Parameters:
- *     mosq -     a valid mosquitto instance.
- *     username - the username to send as a string, or NULL to disable
+ *  mosq -     a valid mosquitto instance.
+ *  username - the username to send as a string, or NULL to disable
  *             authentication.
- *     password - the password to send as a string. Set to NULL when username is
- *                valid in order to send just a username.
+ *  password - the password to send as a string. Set to NULL when username is
+ *             valid in order to send just a username.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  */
-libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username, const char *password);
+libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username,
+        const char *password);
 
 /*
  * Function: mosquitto_connect
@@ -336,55 +341,57 @@ libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char
  * Connect to an MQTT broker.
  *
  * Parameters:
- *     mosq -      a valid mosquitto instance.
- *     host -      the hostname or ip address of the broker to connect to.
- *     port -      the network port to connect to. Usually 1883.
- *     keepalive - the number of seconds after which the broker should send a PING
+ *  mosq -      a valid mosquitto instance.
+ *  host -      the hostname or ip address of the broker to connect to.
+ *  port -      the network port to connect to. Usually 1883.
+ *  keepalive - the number of seconds after which the broker should send a PING
  *              message to the client if no other messages have been exchanged
  *              in that time.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_bind>, <mosquitto_connect_async>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
+ *  <mosquitto_connect_bind>, <mosquitto_connect_async>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_connect(struct mosquitto *mosq, const char *host, int port, int keepalive);
+libmosq_EXPORT int mosquitto_connect(struct mosquitto *mosq, const char *host, int port,
+                                     int keepalive);
 
 /*
  * Function: mosquitto_connect_bind
  *
  * Connect to an MQTT broker. This extends the functionality of
  * <mosquitto_connect> by adding the bind_address parameter. Use this function
- * if you need to restrict network communication over a particular interface. 
+ * if you need to restrict network communication over a particular interface.
  *
  * Parameters:
- *     mosq -         a valid mosquitto instance.
- *     host -         the hostname or ip address of the broker to connect to.
- *     port -         the network port to connect to. Usually 1883.
- *     keepalive -    the number of seconds after which the broker should send a PING
+ *  mosq -         a valid mosquitto instance.
+ *  host -         the hostname or ip address of the broker to connect to.
+ *  port -         the network port to connect to. Usually 1883.
+ *  keepalive -    the number of seconds after which the broker should send a PING
  *                 message to the client if no other messages have been exchanged
  *                 in that time.
  *  bind_address - the hostname or ip address of the local network interface to
  *                 bind to.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect>, <mosquitto_connect_async>, <mosquitto_connect_bind_async>
+ *  <mosquitto_connect>, <mosquitto_connect_async>, <mosquitto_connect_bind_async>
  */
-libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address);
+libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port,
+        int keepalive, const char *bind_address);
 
 /*
  * Function: mosquitto_connect_async
@@ -397,25 +404,26 @@ libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *ho
  * May be called before or after <mosquitto_loop_start>.
  *
  * Parameters:
- *     mosq -      a valid mosquitto instance.
- *     host -      the hostname or ip address of the broker to connect to.
- *     port -      the network port to connect to. Usually 1883.
- *     keepalive - the number of seconds after which the broker should send a PING
+ *  mosq -      a valid mosquitto instance.
+ *  host -      the hostname or ip address of the broker to connect to.
+ *  port -      the network port to connect to. Usually 1883.
+ *  keepalive - the number of seconds after which the broker should send a PING
  *              message to the client if no other messages have been exchanged
  *              in that time.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_bind_async>, <mosquitto_connect>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
+ *  <mosquitto_connect_bind_async>, <mosquitto_connect>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port, int keepalive);
+libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port,
+        int keepalive);
 
 /*
  * Function: mosquitto_connect_async
@@ -427,32 +435,33 @@ libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *h
  *
  * This extends the functionality of <mosquitto_connect_async> by adding the
  * bind_address parameter. Use this function if you need to restrict network
- * communication over a particular interface. 
+ * communication over a particular interface.
  *
  * May be called before or after <mosquitto_loop_start>.
  *
  * Parameters:
- *     mosq -         a valid mosquitto instance.
- *     host -         the hostname or ip address of the broker to connect to.
- *     port -         the network port to connect to. Usually 1883.
- *     keepalive -    the number of seconds after which the broker should send a PING
+ *  mosq -         a valid mosquitto instance.
+ *  host -         the hostname or ip address of the broker to connect to.
+ *  port -         the network port to connect to. Usually 1883.
+ *  keepalive -    the number of seconds after which the broker should send a PING
  *                 message to the client if no other messages have been exchanged
  *                 in that time.
  *  bind_address - the hostname or ip address of the local network interface to
  *                 bind to.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
+ *  <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
  */
-libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address);
+libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port,
+        int keepalive, const char *bind_address);
 
 /*
  * Function: mosquitto_connect_srv
@@ -464,31 +473,32 @@ libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const ch
  *
  * This extends the functionality of <mosquitto_connect_async> by adding the
  * bind_address parameter. Use this function if you need to restrict network
- * communication over a particular interface. 
+ * communication over a particular interface.
  *
  * May be called before or after <mosquitto_loop_start>.
  *
  * Parameters:
- *     mosq -         a valid mosquitto instance.
- *     host -         the hostname or ip address of the broker to connect to.
- *     keepalive -    the number of seconds after which the broker should send a PING
+ *  mosq -         a valid mosquitto instance.
+ *  host -         the hostname or ip address of the broker to connect to.
+ *  keepalive -    the number of seconds after which the broker should send a PING
  *                 message to the client if no other messages have been exchanged
  *                 in that time.
  *  bind_address - the hostname or ip address of the local network interface to
  *                 bind to.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
+ *  <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
  */
-libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address);
+libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive,
+        const char *bind_address);
 
 /*
  * Function: mosquitto_reconnect
@@ -499,25 +509,25 @@ libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *hos
  * connection has been lost. It uses the values that were provided in the
  * <mosquitto_connect> call. It must not be called before
  * <mosquitto_connect>.
- * 
+ *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect>, <mosquitto_disconnect>, <mosquitto_reconnect_async>
+ *  <mosquitto_connect>, <mosquitto_disconnect>, <mosquitto_reconnect_async>
  */
 libmosq_EXPORT int mosquitto_reconnect(struct mosquitto *mosq);
 
@@ -530,25 +540,25 @@ libmosq_EXPORT int mosquitto_reconnect(struct mosquitto *mosq);
  * connection has been lost. It uses the values that were provided in the
  * <mosquitto_connect> or <mosquitto_connect_async> calls. It must not be
  * called before <mosquitto_connect>.
- * 
+ *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect>, <mosquitto_disconnect>
+ *  <mosquitto_connect>, <mosquitto_disconnect>
  */
 libmosq_EXPORT int mosquitto_reconnect_async(struct mosquitto *mosq);
 
@@ -558,50 +568,51 @@ libmosq_EXPORT int mosquitto_reconnect_async(struct mosquitto *mosq);
  * Disconnect from the broker.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NO_CONN -  if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NO_CONN -  if the client isn't connected to a broker.
  */
 libmosq_EXPORT int mosquitto_disconnect(struct mosquitto *mosq);
 
-/* 
+/*
  * Function: mosquitto_publish
  *
  * Publish a message on a given topic.
- * 
+ *
  * Parameters:
- *     mosq -       a valid mosquitto instance.
- *     mid -        pointer to an int. If not NULL, the function will set this
+ *  mosq -       a valid mosquitto instance.
+ *  mid -        pointer to an int. If not NULL, the function will set this
  *               to the message id of this particular message. This can be then
  *               used with the publish callback to determine when the message
  *               has been sent.
  *               Note that although the MQTT protocol doesn't use message ids
  *               for messages with QoS=0, libmosquitto assigns them message ids
  *               so they can be tracked with this parameter.
- *     payloadlen - the size of the payload (bytes). Valid values are between 0 and
+ *  payloadlen - the size of the payload (bytes). Valid values are between 0 and
  *               268,435,455.
- *     payload -    pointer to the data to send. If payloadlen > 0 this must be a
+ *  payload -    pointer to the data to send. If payloadlen > 0 this must be a
  *               valid memory location.
- *     qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
+ *  qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
  *               used for the message.
- *     retain -     set to true to make the message retained.
+ *  retain -     set to true to make the message retained.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -      on success.
- *     MOSQ_ERR_INVAL -        if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -      if the client isn't connected to a broker.
- *     MOSQ_ERR_PROTOCOL -     if there is a protocol error communicating with the
+ *  MOSQ_ERR_SUCCESS -      on success.
+ *  MOSQ_ERR_INVAL -        if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -      if the client isn't connected to a broker.
+ *  MOSQ_ERR_PROTOCOL -     if there is a protocol error communicating with the
  *                          broker.
- *     MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
+ *  MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
  *
- * See Also: 
- *     <mosquitto_max_inflight_messages_set>
+ * See Also:
+ *  <mosquitto_max_inflight_messages_set>
  */
-libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain);
+libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic,
+                                     int payloadlen, const void *payload, int qos, bool retain);
 
 /*
  * Function: mosquitto_subscribe
@@ -609,19 +620,19 @@ libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const cha
  * Subscribe to a topic.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
- *     mid -  a pointer to an int. If not NULL, the function will set this to
- *            the message id of this particular message. This can be then used
- *            with the subscribe callback to determine when the message has been
- *            sent.
- *     sub -  the subscription pattern.
- *     qos -  the requested Quality of Service for this subscription.
+ *  mosq - a valid mosquitto instance.
+ *  mid -  a pointer to an int. If not NULL, the function will set this to
+ *         the message id of this particular message. This can be then used
+ *         with the subscribe callback to determine when the message has been
+ *         sent.
+ *  sub -  the subscription pattern.
+ *  qos -  the requested Quality of Service for this subscription.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
  */
 libmosq_EXPORT int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const char *sub, int qos);
 
@@ -631,18 +642,18 @@ libmosq_EXPORT int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const c
  * Unsubscribe from a topic.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
- *     mid -  a pointer to an int. If not NULL, the function will set this to
- *            the message id of this particular message. This can be then used
- *            with the unsubscribe callback to determine when the message has been
- *            sent.
- *     sub -  the unsubscription pattern.
+ *  mosq - a valid mosquitto instance.
+ *  mid -  a pointer to an int. If not NULL, the function will set this to
+ *         the message id of this particular message. This can be then used
+ *         with the unsubscribe callback to determine when the message has been
+ *         sent.
+ *  sub -  the unsubscription pattern.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
  */
 libmosq_EXPORT int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const char *sub);
 
@@ -653,29 +664,30 @@ libmosq_EXPORT int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const
  * Useful for preserving a message received in the on_message() callback.
  *
  * Parameters:
- *     dst - a pointer to a valid mosquitto_message struct to copy to.
- *     src - a pointer to a valid mosquitto_message struct to copy from.
+ *  dst - a pointer to a valid mosquitto_message struct to copy to.
+ *  src - a pointer to a valid mosquitto_message struct to copy from.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_message_free>
+ *  <mosquitto_message_free>
  */
-libmosq_EXPORT int mosquitto_message_copy(struct mosquitto_message *dst, const struct mosquitto_message *src);
+libmosq_EXPORT int mosquitto_message_copy(struct mosquitto_message *dst,
+        const struct mosquitto_message *src);
 
 /*
  * Function: mosquitto_message_free
- * 
+ *
  * Completely free a mosquitto_message struct.
  *
  * Parameters:
- *     message - pointer to a mosquitto_message pointer to free.
+ *  message - pointer to a mosquitto_message pointer to free.
  *
  * See Also:
- *     <mosquitto_message_copy>
+ *  <mosquitto_message_copy>
  */
 libmosq_EXPORT void mosquitto_message_free(struct mosquitto_message **message);
 
@@ -699,29 +711,29 @@ libmosq_EXPORT void mosquitto_message_free(struct mosquitto_message **message);
  * <mosquitto_loop_misc>.
  *
  * Threads:
- *     
+ *
  * Parameters:
- *     mosq -        a valid mosquitto instance.
- *     timeout -     Maximum number of milliseconds to wait for network activity
- *                   in the select() call before timing out. Set to 0 for instant
- *                   return.  Set negative to use the default of 1000ms.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
- * 
+ *  mosq -        a valid mosquitto instance.
+ *  timeout -     Maximum number of milliseconds to wait for network activity
+ *                in the select() call before timing out. Set to 0 for instant
+ *                return.  Set negative to use the default of 1000ms.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
+ *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  * See Also:
- *     <mosquitto_loop_forever>, <mosquitto_loop_start>, <mosquitto_loop_stop>
+ *  <mosquitto_loop_forever>, <mosquitto_loop_start>, <mosquitto_loop_stop>
  */
 libmosq_EXPORT int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_packets);
 
@@ -737,27 +749,27 @@ libmosq_EXPORT int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_p
  *
  * Parameters:
  *  mosq - a valid mosquitto instance.
- *     timeout -     Maximum number of milliseconds to wait for network activity
- *                   in the select() call before timing out. Set to 0 for instant
- *                   return.  Set negative to use the default of 1000ms.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
+ *  timeout -     Maximum number of milliseconds to wait for network activity
+ *                in the select() call before timing out. Set to 0 for instant
+ *                return.  Set negative to use the default of 1000ms.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  *
  * See Also:
- *     <mosquitto_loop>, <mosquitto_loop_start>
+ *  <mosquitto_loop>, <mosquitto_loop_start>
  */
 libmosq_EXPORT int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets);
 
@@ -772,12 +784,12 @@ libmosq_EXPORT int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, i
  *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -       on success.
- *     MOSQ_ERR_INVAL -         if the input parameters were invalid.
- *     MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
+ *  MOSQ_ERR_SUCCESS -       on success.
+ *  MOSQ_ERR_INVAL -         if the input parameters were invalid.
+ *  MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
  *
  * See Also:
- *     <mosquitto_connect_async>, <mosquitto_loop>, <mosquitto_loop_forever>, <mosquitto_loop_stop>
+ *  <mosquitto_connect_async>, <mosquitto_loop>, <mosquitto_loop_forever>, <mosquitto_loop_stop>
  */
 libmosq_EXPORT int mosquitto_loop_start(struct mosquitto *mosq);
 
@@ -792,16 +804,16 @@ libmosq_EXPORT int mosquitto_loop_start(struct mosquitto *mosq);
  *
  * Parameters:
  *  mosq - a valid mosquitto instance.
- *     force - set to true to force thread cancellation. If false,
- *             <mosquitto_disconnect> must have already been called.
+ *  force - set to true to force thread cancellation. If false,
+ *          <mosquitto_disconnect> must have already been called.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -       on success.
- *     MOSQ_ERR_INVAL -         if the input parameters were invalid.
- *     MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
+ *  MOSQ_ERR_SUCCESS -       on success.
+ *  MOSQ_ERR_INVAL -         if the input parameters were invalid.
+ *  MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
  *
  * See Also:
- *     <mosquitto_loop>, <mosquitto_loop_start>
+ *  <mosquitto_loop>, <mosquitto_loop_start>
  */
 libmosq_EXPORT int mosquitto_loop_stop(struct mosquitto *mosq, bool force);
 
@@ -812,10 +824,10 @@ libmosq_EXPORT int mosquitto_loop_stop(struct mosquitto *mosq, bool force);
  * include a mosquitto client in your own select() calls.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     The socket for the mosquitto client or -1 on failure.
+ *  The socket for the mosquitto client or -1 on failure.
  */
 libmosq_EXPORT int mosquitto_socket(struct mosquitto *mosq);
 
@@ -827,25 +839,25 @@ libmosq_EXPORT int mosquitto_socket(struct mosquitto *mosq);
  * monitoring the client network socket for activity yourself.
  *
  * Parameters:
- *     mosq -        a valid mosquitto instance.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
+ *  mosq -        a valid mosquitto instance.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_write>, <mosquitto_loop_misc>
+ *  <mosquitto_socket>, <mosquitto_loop_write>, <mosquitto_loop_misc>
  */
 libmosq_EXPORT int mosquitto_loop_read(struct mosquitto *mosq, int max_packets);
 
@@ -857,25 +869,25 @@ libmosq_EXPORT int mosquitto_loop_read(struct mosquitto *mosq, int max_packets);
  * monitoring the client network socket for activity yourself.
  *
  * Parameters:
- *     mosq -        a valid mosquitto instance.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
+ *  mosq -        a valid mosquitto instance.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_misc>, <mosquitto_want_write>
+ *  <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_misc>, <mosquitto_want_write>
  */
 libmosq_EXPORT int mosquitto_loop_write(struct mosquitto *mosq, int max_packets);
 
@@ -890,15 +902,15 @@ libmosq_EXPORT int mosquitto_loop_write(struct mosquitto *mosq, int max_packets)
  * to be retried, so should be called fairly frequently.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
+ *  <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
  */
 libmosq_EXPORT int mosquitto_loop_misc(struct mosquitto *mosq);
 
@@ -908,10 +920,10 @@ libmosq_EXPORT int mosquitto_loop_misc(struct mosquitto *mosq);
  * Returns true if there is data ready to be written on the socket.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
+ *  <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
  */
 libmosq_EXPORT bool mosquitto_want_write(struct mosquitto *mosq);
 
@@ -954,17 +966,17 @@ libmosq_EXPORT bool mosquitto_want_write(struct mosquitto *mosq);
  *                instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_tls_opts_set>, <mosquitto_tls_psk_set>, <mosquitto_tls_insecure_set>
+ *  <mosquitto_tls_opts_set>, <mosquitto_tls_psk_set>, <mosquitto_tls_insecure_set>
  */
 libmosq_EXPORT int mosquitto_tls_set(struct mosquitto *mosq,
-               const char *cafile, const char *capath,
-               const char *certfile, const char *keyfile,
-               int (*pw_callback)(char *buf, int size, int rwflag, void *userdata));
+                                     const char *cafile, const char *capath,
+                                     const char *certfile, const char *keyfile,
+                                     int (*pw_callback)(char *buf, int size, int rwflag, void *userdata));
 
 /*
  * Function: mosquitto_tls_insecure_set
@@ -985,11 +997,11 @@ libmosq_EXPORT int mosquitto_tls_set(struct mosquitto *mosq,
  *          the connection is insecure.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  *
  * See Also:
- *     <mosquitto_tls_set>
+ *  <mosquitto_tls_set>
  */
 libmosq_EXPORT int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value);
 
@@ -1000,32 +1012,33 @@ libmosq_EXPORT int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value
  *
  * Parameters:
  *  mosq -        a valid mosquitto instance.
- *     cert_reqs -   an integer defining the verification requirements the client
- *                   will impose on the server. This can be one of:
- *                   * SSL_VERIFY_NONE (0): the server will not be verified in any way.
- *                   * SSL_VERIFY_PEER (1): the server certificate will be verified
- *                     and the connection aborted if the verification fails.
- *                   The default and recommended value is SSL_VERIFY_PEER. Using
- *                   SSL_VERIFY_NONE provides no security.
- *     tls_version - the version of the SSL/TLS protocol to use as a string. If NULL,
- *                   the default value is used. The default value and the
- *                   available values depend on the version of openssl that the
- *                   library was compiled against. For openssl >= 1.0.1, the
- *                   available options are tlsv1.2, tlsv1.1 and tlsv1, with tlv1.2
- *                   as the default. For openssl < 1.0.1, only tlsv1 is available.
- *     ciphers -     a string describing the ciphers available for use. See the
- *                   "openssl ciphers" tool for more information. If NULL, the
- *                   default ciphers will be used.
+ *  cert_reqs -   an integer defining the verification requirements the client
+ *                will impose on the server. This can be one of:
+ *                * SSL_VERIFY_NONE (0): the server will not be verified in any way.
+ *                * SSL_VERIFY_PEER (1): the server certificate will be verified
+ *                  and the connection aborted if the verification fails.
+ *                The default and recommended value is SSL_VERIFY_PEER. Using
+ *                SSL_VERIFY_NONE provides no security.
+ *  tls_version - the version of the SSL/TLS protocol to use as a string. If NULL,
+ *                the default value is used. The default value and the
+ *                available values depend on the version of openssl that the
+ *                library was compiled against. For openssl >= 1.0.1, the
+ *                available options are tlsv1.2, tlsv1.1 and tlsv1, with tlv1.2
+ *                as the default. For openssl < 1.0.1, only tlsv1 is available.
+ *  ciphers -     a string describing the ciphers available for use. See the
+ *                "openssl ciphers" tool for more information. If NULL, the
+ *                default ciphers will be used.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_tls_set>
+ *  <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs, const char *tls_version, const char *ciphers);
+libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs,
+        const char *tls_version, const char *ciphers);
 
 /*
  * Function: mosquitto_tls_psk_set
@@ -1040,21 +1053,22 @@ libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs,
  *  psk -      the pre-shared-key in hex format with no leading "0x".
  *  identity - the identity of this client. May be used as the username
  *             depending on the server settings.
- *     ciphers -  a string describing the PSK ciphers available for use. See the
- *                "openssl ciphers" tool for more information. If NULL, the
- *                default ciphers will be used.
+ *  ciphers -  a string describing the PSK ciphers available for use. See the
+ *             "openssl ciphers" tool for more information. If NULL, the
+ *             default ciphers will be used.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_tls_set>
+ *  <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk, const char *identity, const char *ciphers);
+libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk,
+        const char *identity, const char *ciphers);
 
-/* 
+/*
  * Function: mosquitto_connect_callback_set
  *
  * Set the connect callback. This is called when the broker sends a CONNACK
@@ -1076,14 +1090,15 @@ libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk
  * * 3 - connection refused (broker unavailable)
  * * 4-255 - reserved for future use
  */
-libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq,
+        void (*on_connect)(struct mosquitto *, void *, int));
+
 /*
  * Function: mosquitto_disconnect_callback_set
  *
  * Set the disconnect callback. This is called when the broker has received the
  * DISCONNECT command and has disconnected the client.
- * 
+ *
  * Parameters:
  *  mosq -          a valid mosquitto instance.
  *  on_disconnect - a callback function in the following form:
@@ -1096,14 +1111,15 @@ libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, void
  *         means the client has called <mosquitto_disconnect>. Any other value
  *         indicates that the disconnect is unexpected.
  */
-libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq,
+        void (*on_disconnect)(struct mosquitto *, void *, int));
+
 /*
  * Function: mosquitto_publish_callback_set
  *
  * Set the publish callback. This is called when a message initiated with
  * <mosquitto_publish> has been sent to the broker successfully.
- * 
+ *
  * Parameters:
  *  mosq -       a valid mosquitto instance.
  *  on_publish - a callback function in the following form:
@@ -1114,14 +1130,15 @@ libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq, vo
  *  obj -  the user data provided in <mosquitto_new>
  *  mid -  the message id of the sent message.
  */
-libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq,
+        void (*on_publish)(struct mosquitto *, void *, int));
 
 /*
  * Function: mosquitto_message_callback_set
  *
  * Set the message callback. This is called when a message is received from the
  * broker.
- * 
+ *
  * Parameters:
  *  mosq -       a valid mosquitto instance.
  *  on_message - a callback function in the following form:
@@ -1135,16 +1152,17 @@ libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq, void
  *            should make copies of any of the data it requires.
  *
  * See Also:
- *     <mosquitto_message_copy>
+ *  <mosquitto_message_copy>
  */
-libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *));
+libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq,
+        void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *));
 
 /*
  * Function: mosquitto_subscribe_callback_set
  *
  * Set the subscribe callback. This is called when the broker responds to a
  * subscription request.
- * 
+ *
  * Parameters:
  *  mosq -         a valid mosquitto instance.
  *  on_subscribe - a callback function in the following form:
@@ -1158,14 +1176,15 @@ libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq, void
  *  granted_qos - an array of integers indicating the granted QoS for each of
  *                the subscriptions.
  */
-libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *));
+libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq,
+        void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *));
 
 /*
  * Function: mosquitto_unsubscribe_callback_set
  *
  * Set the unsubscribe callback. This is called when the broker responds to a
  * unsubscription request.
- * 
+ *
  * Parameters:
  *  mosq -           a valid mosquitto instance.
  *  on_unsubscribe - a callback function in the following form:
@@ -1176,7 +1195,8 @@ libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq, voi
  *  obj -  the user data provided in <mosquitto_new>
  *  mid -  the message id of the unsubscribe message.
  */
-libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq,
+        void (*on_unsubscribe)(struct mosquitto *, void *, int));
 
 /*
  * Function: mosquitto_log_callback_set
@@ -1192,14 +1212,15 @@ libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, v
  *  mosq -  the mosquitto instance making the callback.
  *  obj -   the user data provided in <mosquitto_new>
  *  level - the log message level from the values:
- *             MOSQ_LOG_INFO
- *             MOSQ_LOG_NOTICE
- *             MOSQ_LOG_WARNING
- *             MOSQ_LOG_ERR
- *             MOSQ_LOG_DEBUG
- *     str -   the message string.
+ *          MOSQ_LOG_INFO
+ *          MOSQ_LOG_NOTICE
+ *          MOSQ_LOG_WARNING
+ *          MOSQ_LOG_ERR
+ *          MOSQ_LOG_DEBUG
+ *  str -   the message string.
  */
-libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on_log)(struct mosquitto *, void *, int, const char *));
+libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq,
+        void (*on_log)(struct mosquitto *, void *, int, const char *));
 
 /*
  * Function: mosquitto_reconnect_delay_set
@@ -1215,12 +1236,12 @@ libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on
  * set an upper bound on the delay with reconnect_delay_max.
  *
  * Example 1:
- *     delay=2, delay_max=10, exponential_backoff=False
- *     Delays would be: 2, 4, 6, 8, 10, 10, ...
+ *  delay=2, delay_max=10, exponential_backoff=False
+ *  Delays would be: 2, 4, 6, 8, 10, 10, ...
  *
  * Example 2:
- *     delay=3, delay_max=30, exponential_backoff=True
- *     Delays would be: 3, 6, 12, 24, 30, 30, ...
+ *  delay=3, delay_max=30, exponential_backoff=True
+ *  Delays would be: 3, 6, 12, 24, 30, 30, ...
  *
  * Parameters:
  *  mosq -                          a valid mosquitto instance.
@@ -1233,10 +1254,11 @@ libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on
  *                                  exponential backoff.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  */
-libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff);
+libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq,
+        unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff);
 
 /*
  * Function: mosquitto_max_inflight_messages_set
@@ -1258,17 +1280,18 @@ libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigne
  *                          to 20.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  */
-libmosq_EXPORT int mosquitto_max_inflight_messages_set(struct mosquitto *mosq, unsigned int max_inflight_messages);
+libmosq_EXPORT int mosquitto_max_inflight_messages_set(struct mosquitto *mosq,
+        unsigned int max_inflight_messages);
 
 /*
  * Function: mosquitto_message_retry_set
  *
  * Set the number of seconds to wait before retrying messages. This applies to
  * publish messages with QoS>0. May be called at any time.
- * 
+ *
  * Parameters:
  *  mosq -          a valid mosquitto instance.
  *  message_retry - the number of seconds to wait for a response before
@@ -1287,8 +1310,8 @@ libmosq_EXPORT void mosquitto_message_retry_set(struct mosquitto *mosq, unsigned
  *
  * Parameters:
  *  mosq - a valid mosquitto instance.
- *     obj -  A user pointer that will be passed as an argument to any callbacks
- *            that are specified.
+ *  obj -  A user pointer that will be passed as an argument to any callbacks
+ *         that are specified.
  */
 libmosq_EXPORT void mosquitto_user_data_set(struct mosquitto *mosq, void *obj);
 
@@ -1306,10 +1329,10 @@ libmosq_EXPORT void mosquitto_user_data_set(struct mosquitto *mosq, void *obj);
  * Call to obtain a const string description of a mosquitto error number.
  *
  * Parameters:
- *     mosq_errno - a mosquitto error number.
+ *  mosq_errno - a mosquitto error number.
  *
  * Returns:
- *     A constant string describing the error.
+ *  A constant string describing the error.
  */
 libmosq_EXPORT const char *mosquitto_strerror(int mosq_errno);
 
@@ -1319,10 +1342,10 @@ libmosq_EXPORT const char *mosquitto_strerror(int mosq_errno);
  * Call to obtain a const string description of an MQTT connection result.
  *
  * Parameters:
- *     connack_code - an MQTT connection result.
+ *  connack_code - an MQTT connection result.
  *
  * Returns:
- *     A constant string describing the result.
+ *  A constant string describing the result.
  */
 libmosq_EXPORT const char *mosquitto_connack_string(int connack_code);
 
@@ -1356,20 +1379,20 @@ libmosq_EXPORT const char *mosquitto_connack_string(int connack_code);
  * topics[4] = "hierarchy"
  *
  * Parameters:
- *     subtopic - the subscription/topic to tokenise
- *     topics -   a pointer to store the array of strings
- *     count -    an int pointer to store the number of items in the topics array.
+ *  subtopic - the subscription/topic to tokenise
+ *  topics -   a pointer to store the array of strings
+ *  count -    an int pointer to store the number of items in the topics array.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * Example:
  *
  * > char **topics;
  * > int topic_count;
  * > int i;
- * > 
+ * >
  * > mosquitto_sub_topic_tokenise("$SYS/broker/uptime", &topics, &topic_count);
  * >
  * > for(i=0; i<token_count; i++){
@@ -1377,7 +1400,7 @@ libmosq_EXPORT const char *mosquitto_connack_string(int connack_code);
  * > }
  *
  * See Also:
- *     <mosquitto_sub_topic_tokens_free>
+ *  <mosquitto_sub_topic_tokens_free>
  */
 libmosq_EXPORT int mosquitto_sub_topic_tokenise(const char *subtopic, char ***topics, int *count);
 
@@ -1387,15 +1410,15 @@ libmosq_EXPORT int mosquitto_sub_topic_tokenise(const char *subtopic, char ***to
  * Free memory that was allocated in <mosquitto_sub_topic_tokenise>.
  *
  * Parameters:
- *     topics - pointer to string array.
- *     count - count of items in string array.
+ *  topics - pointer to string array.
+ *  count - count of items in string array.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  *
  * See Also:
- *     <mosquitto_sub_topic_tokenise>
+ *  <mosquitto_sub_topic_tokenise>
  */
 libmosq_EXPORT int mosquitto_sub_topic_tokens_free(char ***topics, int count);
 
@@ -1410,15 +1433,15 @@ libmosq_EXPORT int mosquitto_sub_topic_tokens_free(char ***topics, int count);
  * non/matching would not match the subscription non/+/+
  *
  * Parameters:
- *     sub - subscription string to check topic against.
- *     topic - topic to check.
- *     result - bool pointer to hold result. Will be set to true if the topic
- *              matches the subscription.
+ *  sub - subscription string to check topic against.
+ *  topic - topic to check.
+ *  result - bool pointer to hold result. Will be set to true if the topic
+ *           matches the subscription.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  */
 libmosq_EXPORT int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result);
 
index f3d5fde..523b1d9 100644 (file)
@@ -52,16 +52,16 @@ POSSIBILITY OF SUCH DAMAGE.
 #endif
 
 #ifdef WIN32
-#      if _MSC_VER < 1600
-               typedef unsigned char uint8_t;
-               typedef unsigned short uint16_t;
-               typedef unsigned int uint32_t;
-               typedef unsigned long long uint64_t;
-#      else
-#              include <stdint.h>
-#      endif
+#   if _MSC_VER < 1600
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long uint64_t;
+#   else
+#       include <stdint.h>
+#   endif
 #else
-#      include <stdint.h>
+#   include <stdint.h>
 #endif
 
 #include "mosquitto.h"
@@ -70,172 +70,181 @@ POSSIBILITY OF SUCH DAMAGE.
 struct mosquitto_client_msg;
 #endif
 
-enum mosquitto_msg_direction {
-       mosq_md_in = 0,
-       mosq_md_out = 1
+enum mosquitto_msg_direction
+{
+    mosq_md_in = 0,
+    mosq_md_out = 1
 };
 
-enum mosquitto_msg_state {
-       mosq_ms_invalid = 0,
-       mosq_ms_publish_qos0 = 1,
-       mosq_ms_publish_qos1 = 2,
-       mosq_ms_wait_for_puback = 3,
-       mosq_ms_publish_qos2 = 4,
-       mosq_ms_wait_for_pubrec = 5,
-       mosq_ms_resend_pubrel = 6,
-       mosq_ms_wait_for_pubrel = 7,
-       mosq_ms_resend_pubcomp = 8,
-       mosq_ms_wait_for_pubcomp = 9,
-       mosq_ms_send_pubrec = 10,
-       mosq_ms_queued = 11
+enum mosquitto_msg_state
+{
+    mosq_ms_invalid = 0,
+    mosq_ms_publish_qos0 = 1,
+    mosq_ms_publish_qos1 = 2,
+    mosq_ms_wait_for_puback = 3,
+    mosq_ms_publish_qos2 = 4,
+    mosq_ms_wait_for_pubrec = 5,
+    mosq_ms_resend_pubrel = 6,
+    mosq_ms_wait_for_pubrel = 7,
+    mosq_ms_resend_pubcomp = 8,
+    mosq_ms_wait_for_pubcomp = 9,
+    mosq_ms_send_pubrec = 10,
+    mosq_ms_queued = 11
 };
 
-enum mosquitto_client_state {
-       mosq_cs_new = 0,
-       mosq_cs_connected = 1,
-       mosq_cs_disconnecting = 2,
-       mosq_cs_connect_async = 3,
-       mosq_cs_connect_pending = 4,
-       mosq_cs_connect_srv = 5
+enum mosquitto_client_state
+{
+    mosq_cs_new = 0,
+    mosq_cs_connected = 1,
+    mosq_cs_disconnecting = 2,
+    mosq_cs_connect_async = 3,
+    mosq_cs_connect_pending = 4,
+    mosq_cs_connect_srv = 5
 };
 
-enum _mosquitto_protocol {
-       mosq_p_invalid = 0,
-       mosq_p_mqtt31 = 1,
-       mosq_p_mqtt311 = 2,
-       mosq_p_mqtts = 3
+enum _mosquitto_protocol
+{
+    mosq_p_invalid = 0,
+    mosq_p_mqtt31 = 1,
+    mosq_p_mqtt311 = 2,
+    mosq_p_mqtts = 3
 };
 
-enum _mosquitto_transport {
-       mosq_t_invalid = 0,
-       mosq_t_tcp = 1,
-       mosq_t_ws = 2,
-       mosq_t_sctp = 3
+enum _mosquitto_transport
+{
+    mosq_t_invalid = 0,
+    mosq_t_tcp = 1,
+    mosq_t_ws = 2,
+    mosq_t_sctp = 3
 };
 
-struct _mosquitto_packet{
-       uint8_t command;
-       uint8_t have_remaining;
-       uint8_t remaining_count;
-       uint16_t mid;
-       uint32_t remaining_mult;
-       uint32_t remaining_length;
-       uint32_t packet_length;
-       uint32_t to_process;
-       uint32_t pos;
-       uint8_t *payload;
-       struct _mosquitto_packet *next;
+struct _mosquitto_packet
+{
+    uint8_t command;
+    uint8_t have_remaining;
+    uint8_t remaining_count;
+    uint16_t mid;
+    uint32_t remaining_mult;
+    uint32_t remaining_length;
+    uint32_t packet_length;
+    uint32_t to_process;
+    uint32_t pos;
+    uint8_t *payload;
+    struct _mosquitto_packet *next;
 };
 
-struct mosquitto_message_all{
-       struct mosquitto_message_all *next;
-       time_t timestamp;
-       //enum mosquitto_msg_direction direction;
-       enum mosquitto_msg_state state;
-       bool dup;
-       struct mosquitto_message msg;
+struct mosquitto_message_all
+{
+    struct mosquitto_message_all *next;
+    time_t timestamp;
+    //enum mosquitto_msg_direction direction;
+    enum mosquitto_msg_state state;
+    bool dup;
+    struct mosquitto_message msg;
 };
 
-struct mosquitto {
+struct mosquitto
+{
 #ifndef WIN32
-       int sock;
+    int sock;
 #  ifndef WITH_BROKER
-       int sockpairR, sockpairW;
+    int sockpairR, sockpairW;
 #  endif
 #else
-       SOCKET sock;
+    SOCKET sock;
 #  ifndef WITH_BROKER
-       SOCKET sockpairR, sockpairW;
+    SOCKET sockpairR, sockpairW;
 #  endif
 #endif
-       enum _mosquitto_protocol protocol;
-       char *address;
-       char *id;
-       char *username;
-       char *password;
-       uint16_t keepalive;
-       bool clean_session;
-       enum mosquitto_client_state state;
-       time_t last_msg_in;
-       time_t last_msg_out;
-       time_t ping_t;
-       uint16_t last_mid;
-       struct _mosquitto_packet in_packet;
-       struct _mosquitto_packet *current_out_packet;
-       struct _mosquitto_packet *out_packet;
-       struct mosquitto_message *will;
+    enum _mosquitto_protocol protocol;
+    char *address;
+    char *id;
+    char *username;
+    char *password;
+    uint16_t keepalive;
+    bool clean_session;
+    enum mosquitto_client_state state;
+    time_t last_msg_in;
+    time_t last_msg_out;
+    time_t ping_t;
+    uint16_t last_mid;
+    struct _mosquitto_packet in_packet;
+    struct _mosquitto_packet *current_out_packet;
+    struct _mosquitto_packet *out_packet;
+    struct mosquitto_message *will;
 #ifdef WITH_TLS
-       SSL *ssl;
-       SSL_CTX *ssl_ctx;
-       char *tls_cafile;
-       char *tls_capath;
-       char *tls_certfile;
-       char *tls_keyfile;
-       int (*tls_pw_callback)(char *buf, int size, int rwflag, void *userdata);
-       int tls_cert_reqs;
-       char *tls_version;
-       char *tls_ciphers;
-       char *tls_psk;
-       char *tls_psk_identity;
-       bool tls_insecure;
+    SSL *ssl;
+    SSL_CTX *ssl_ctx;
+    char *tls_cafile;
+    char *tls_capath;
+    char *tls_certfile;
+    char *tls_keyfile;
+    int (*tls_pw_callback)(char *buf, int size, int rwflag, void *userdata);
+    int tls_cert_reqs;
+    char *tls_version;
+    char *tls_ciphers;
+    char *tls_psk;
+    char *tls_psk_identity;
+    bool tls_insecure;
 #endif
-       bool want_write;
+    bool want_write;
 #if defined(WITH_THREADING) && !defined(WITH_BROKER)
-       pthread_mutex_t callback_mutex;
-       pthread_mutex_t log_callback_mutex;
-       pthread_mutex_t msgtime_mutex;
-       pthread_mutex_t out_packet_mutex;
-       pthread_mutex_t current_out_packet_mutex;
-       pthread_mutex_t state_mutex;
-       pthread_mutex_t in_message_mutex;
-       pthread_mutex_t out_message_mutex;
-       pthread_t thread_id;
+    pthread_mutex_t callback_mutex;
+    pthread_mutex_t log_callback_mutex;
+    pthread_mutex_t msgtime_mutex;
+    pthread_mutex_t out_packet_mutex;
+    pthread_mutex_t current_out_packet_mutex;
+    pthread_mutex_t state_mutex;
+    pthread_mutex_t in_message_mutex;
+    pthread_mutex_t out_message_mutex;
+    pthread_t thread_id;
 #endif
 #ifdef WITH_BROKER
-       bool is_bridge;
-       struct _mqtt3_bridge *bridge;
-       struct mosquitto_client_msg *msgs;
-       struct mosquitto_client_msg *last_msg;
-       int msg_count;
-       int msg_count12;
-       struct _mosquitto_acl_user *acl_list;
-       struct _mqtt3_listener *listener;
-       time_t disconnect_t;
-       int pollfd_index;
-       int db_index;
-       struct _mosquitto_packet *out_packet_last;
-       bool is_dropping;
+    bool is_bridge;
+    struct _mqtt3_bridge *bridge;
+    struct mosquitto_client_msg *msgs;
+    struct mosquitto_client_msg *last_msg;
+    int msg_count;
+    int msg_count12;
+    struct _mosquitto_acl_user *acl_list;
+    struct _mqtt3_listener *listener;
+    time_t disconnect_t;
+    int pollfd_index;
+    int db_index;
+    struct _mosquitto_packet *out_packet_last;
+    bool is_dropping;
 #else
-       void *userdata;
-       bool in_callback;
-       unsigned int message_retry;
-       time_t last_retry_check;
-       struct mosquitto_message_all *in_messages;
-       struct mosquitto_message_all *in_messages_last;
-       struct mosquitto_message_all *out_messages;
-       struct mosquitto_message_all *out_messages_last;
-       void (*on_connect)(struct mosquitto *, void *userdata, int rc);
-       void (*on_disconnect)(struct mosquitto *, void *userdata, int rc);
-       void (*on_publish)(struct mosquitto *, void *userdata, int mid);
-       void (*on_message)(struct mosquitto *, void *userdata, const struct mosquitto_message *message);
-       void (*on_subscribe)(struct mosquitto *, void *userdata, int mid, int qos_count, const int *granted_qos);
-       void (*on_unsubscribe)(struct mosquitto *, void *userdata, int mid);
-       void (*on_log)(struct mosquitto *, void *userdata, int level, const char *str);
-       //void (*on_error)();
-       char *host;
-       int port;
-       int in_queue_len;
-       int out_queue_len;
-       char *bind_address;
-       unsigned int reconnect_delay;
-       unsigned int reconnect_delay_max;
-       bool reconnect_exponential_backoff;
-       bool threaded;
-       struct _mosquitto_packet *out_packet_last;
-       int inflight_messages;
-       int max_inflight_messages;
+    void *userdata;
+    bool in_callback;
+    unsigned int message_retry;
+    time_t last_retry_check;
+    struct mosquitto_message_all *in_messages;
+    struct mosquitto_message_all *in_messages_last;
+    struct mosquitto_message_all *out_messages;
+    struct mosquitto_message_all *out_messages_last;
+    void (*on_connect)(struct mosquitto *, void *userdata, int rc);
+    void (*on_disconnect)(struct mosquitto *, void *userdata, int rc);
+    void (*on_publish)(struct mosquitto *, void *userdata, int mid);
+    void (*on_message)(struct mosquitto *, void *userdata, const struct mosquitto_message *message);
+    void (*on_subscribe)(struct mosquitto *, void *userdata, int mid, int qos_count,
+                         const int *granted_qos);
+    void (*on_unsubscribe)(struct mosquitto *, void *userdata, int mid);
+    void (*on_log)(struct mosquitto *, void *userdata, int level, const char *str);
+    //void (*on_error)();
+    char *host;
+    int port;
+    int in_queue_len;
+    int out_queue_len;
+    char *bind_address;
+    unsigned int reconnect_delay;
+    unsigned int reconnect_delay_max;
+    bool reconnect_exponential_backoff;
+    bool threaded;
+    struct _mosquitto_packet *out_packet_last;
+    int inflight_messages;
+    int max_inflight_messages;
 #  ifdef WITH_SRV
-       ares_channel achan;
+    ares_channel achan;
 #  endif
 #endif
 };
index 517a485..4329e3c 100644 (file)
@@ -27,6 +27,19 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */
 
+#ifndef _POSIX_C_SOURCE
+// Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1-2001 base
+// specification (excluding the XSI extension).
+// For POSIX.1-2001 base specification,
+// Refer http://pubs.opengroup.org/onlinepubs/009695399/
+//
+// For this specific file, see use of getaddrinfo & structs,
+// Refer http://man7.org/linux/man-pages/man3/getaddrinfo.3.html
+#define _POSIX_C_SOURCE 200112L // needed for getaddrinfo & structs
+#endif
+
 #include <assert.h>
 #include <errno.h>
 #include <fcntl.h>
index 96f89a1..f8bd07f 100644 (file)
@@ -71,9 +71,11 @@ void _mosquitto_net_cleanup(void);
 
 void _mosquitto_packet_cleanup(struct _mosquitto_packet *packet);
 int _mosquitto_packet_queue(struct mosquitto *mosq, struct _mosquitto_packet *packet);
-int _mosquitto_socket_connect(struct mosquitto *mosq, const char *host, uint16_t port, const char *bind_address, bool blocking);
+int _mosquitto_socket_connect(struct mosquitto *mosq, const char *host, uint16_t port,
+                              const char *bind_address, bool blocking);
 int _mosquitto_socket_close(struct mosquitto *mosq);
-int _mosquitto_try_connect(const char *host, uint16_t port, int *sock, const char *bind_address, bool blocking);
+int _mosquitto_try_connect(const char *host, uint16_t port, int *sock, const char *bind_address,
+                           bool blocking);
 int _mosquitto_socket_nonblock(int sock);
 int _mosquitto_socketpair(int *sp1, int *sp2);
 
diff --git a/service/protocol-plugin/plugins/mqtt-fan/lib/python/Makefile b/service/protocol-plugin/plugins/mqtt-fan/lib/python/Makefile
deleted file mode 100644 (file)
index 2a54111..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-# Set DESTDIR if it isn't given
-DESTDIR?=/
-
-.PHONY : all clean install
-
-ifeq ($(WITH_PYTHON),yes)
-all : mosquitto.pyc
-else
-all :
-endif
-
-ifeq ($(WITH_PYTHON),yes)
-install : all
-       python ./setup.py install --prefix=${prefix} --root=${DESTDIR}
-else
-install :
-endif
-
-mosquitto.pyc : mosquitto.py
-       python ./setup.py build
-
-clean :
-       -rm -rf build mosquitto.pyc __pycache__
index 35e8544..c49a5c7 100644 (file)
@@ -32,8 +32,10 @@ POSSIBILITY OF SUCH DAMAGE.
 #include "mosquitto.h"
 
 int _mosquitto_send_simple_command(struct mosquitto *mosq, uint8_t command);
-int _mosquitto_send_command_with_mid(struct mosquitto *mosq, uint8_t command, uint16_t mid, bool dup);
-int _mosquitto_send_real_publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
+int _mosquitto_send_command_with_mid(struct mosquitto *mosq, uint8_t command, uint16_t mid,
+                                     bool dup);
+int _mosquitto_send_real_publish(struct mosquitto *mosq, uint16_t mid, const char *topic,
+                                 uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
 
 int _mosquitto_send_connect(struct mosquitto *mosq, uint16_t keepalive, bool clean_session);
 int _mosquitto_send_disconnect(struct mosquitto *mosq);
@@ -41,10 +43,12 @@ int _mosquitto_send_pingreq(struct mosquitto *mosq);
 int _mosquitto_send_pingresp(struct mosquitto *mosq);
 int _mosquitto_send_puback(struct mosquitto *mosq, uint16_t mid);
 int _mosquitto_send_pubcomp(struct mosquitto *mosq, uint16_t mid);
-int _mosquitto_send_publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
+int _mosquitto_send_publish(struct mosquitto *mosq, uint16_t mid, const char *topic,
+                            uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
 int _mosquitto_send_pubrec(struct mosquitto *mosq, uint16_t mid);
 int _mosquitto_send_pubrel(struct mosquitto *mosq, uint16_t mid, bool dup);
-int _mosquitto_send_subscribe(struct mosquitto *mosq, int *mid, bool dup, const char *topic, uint8_t topic_qos);
+int _mosquitto_send_subscribe(struct mosquitto *mosq, int *mid, bool dup, const char *topic,
+                              uint8_t topic_qos);
 int _mosquitto_send_unsubscribe(struct mosquitto *mosq, int *mid, bool dup, const char *topic);
 
 #endif
index 9d2e499..91c9602 100644 (file)
@@ -27,6 +27,17 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */
 
+#ifndef _POSIX_C_SOURCE
+// Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
+// causes header files to expose definitions
+// corresponding to the POSIX.1b, Real-time extensions
+// (IEEE Std 1003.1b-1993) specification
+//
+// For this specific file, see use of clock_gettime,
+// Refer http://man7.org/linux/man-pages/man2/clock_gettime.2.html
+#define _POSIX_C_SOURCE 199309L // needed for clock_gettime
+#endif
+
 #ifdef __APPLE__
 #include <mach/mach.h>
 #include <mach/mach_time.h>
index 362c015..2959e4c 100644 (file)
@@ -37,6 +37,7 @@ POSSIBILITY OF SUCH DAMAGE.
 #endif
 
 #include <string.h>
+#include <strings.h>
 #include <openssl/conf.h>
 #include <openssl/x509v3.h>
 #include <openssl/ssl.h>
index 61d0a79..8891c2e 100644 (file)
@@ -33,7 +33,8 @@ POSSIBILITY OF SUCH DAMAGE.
 #include "mosquitto.h"
 #include "mosquitto_internal.h"
 
-int _mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain);
+int _mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen,
+                        const void *payload, int qos, bool retain);
 int _mosquitto_will_clear(struct mosquitto *mosq);
 
 #endif
index 12111e0..bfbc399 100644 (file)
@@ -73,7 +73,7 @@ struct plugin_data_t
     bool flag;
 };
 
-
+struct mosquitto *myMosquitto;
 class FanResource
 {
     public:
@@ -176,6 +176,14 @@ class FanResource
                 if (rep.getValue("power", m_power))
                 {
                     cout << "\t\t\t\t" << "power: " << m_power << endl;
+                    if (m_power == 1)
+                    {
+                        mosquitto_publish(myMosquitto, NULL, "actuators/fan", 32, "onfan", 0, true);
+                    }
+                    else
+                    {
+                        mosquitto_publish(myMosquitto, NULL, "actuators/fan", 32, "offfan", 0, true);
+                    }
                 }
                 else
                 {
@@ -260,12 +268,6 @@ class FanResource
                 std::string requestType = request->getRequestType();
                 int requestFlag = request->getRequestHandlerFlag();
 
-                if (requestFlag & RequestHandlerFlag::InitFlag)
-                {
-                    cout << "\t\trequestFlag : Init\n";
-
-                    // entity handler to perform resource initialization operations
-                }
                 if (requestFlag & RequestHandlerFlag::RequestFlag)
                 {
                     cout << "\t\trequestFlag : Request   ===  Handle by FanServer\n";
@@ -384,7 +386,6 @@ class FanResource
 };
 
 // Create the instance of the resource class (in this case instance of class 'FanResource').
-struct mosquitto *myMosquitto;
 
 // ChangeFanRepresentaion is an observation function,
 // which notifies any changes to the resource to stack
@@ -491,8 +492,12 @@ void *start_fanserver(void *d)      // 2
             printf("Mosquitto is working\n");
         }
 
-        mosquitto_connect(myMosquitto, "127.0.0.1", 1883, 60);
-        printf("Mosquitto Connection is done\n");
+        if (mosquitto_connect(myMosquitto, "127.0.0.1", 1883, 60) != MOSQ_ERR_SUCCESS)
+        {
+            printf("Mosquitto Connection is failed.\n");
+            pthread_exit((void *)0);
+        }
+        printf("Mosquitto Connection is done.\n");
         myFanResource.createResource();
         // Get time of day
         timer = time(NULL);
diff --git a/service/protocol-plugin/plugins/mqtt-light/build/linux/Makefile b/service/protocol-plugin/plugins/mqtt-light/build/linux/Makefile
deleted file mode 100644 (file)
index 788b7cf..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-CXX = g++
-
-CXX_FLAGS = -std=c++0x -Wall -pthread
-
-TOP_DIR = ../../../../../..
-LIB_DIR = ../../../../../../resource
-
-SRC_DIR = ../../src
-
-DEPEND_DIR:= $(LIB_DIR)/dependencies
-CEREAL_DIR:= $(DEPEND_DIR)/cereal
-
-CXX_INC := -I$(LIB_DIR)/include/ 
-CXX_INC += -I$(LIB_DIR)/oc_logger/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/stack/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/ocsocket/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/ocrandom/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/logger/include/
-CXX_INC += -I$(BOOST_DIR) 
-CXX_INC += -I../../lib 
-CXX_INC += -I../../../../lib/cpluff/libcpluff
-CXX_INC          += -I../csdk/libcoap
-CXX_INC   += -I$(CEREAL_DIR)/include
-
-LIB_OC_LOGGER := $(LIB_DIR)/oc_logger/lib/oc_logger.a
-CXX_LIBS  := ../../../../lib/cpluff/libcpluff/.libs/libcpluff.a
-
-.PHONY: lib release_build ./release/lightserver_mqtt_plugin.so 
-
-all: .PHONY
-
-lib:
-       cd ../../lib && $(MAKE)
-
-release_build:
-       -mkdir release
-       -mkdir release/obj
-       cp plugin.xml release
-
-./release/lightserver_mqtt_plugin.so: ./release/obj/lightserver_mqtt_plugin.o ./release/obj/lightserver.o
-       $(CXX) -shared -o ./release/lightserver_mqtt_plugin.so ./release/obj/lightserver_mqtt_plugin.o ./release/obj/lightserver.o $(CXX_LIBS)  -L../../lib  -L$(TOP_DIR)/out/linux/x86/release -lmosquitto -lssl -lrt -loc -loctbstack -loc_logger -lcoap
-
-./release/obj/lightserver_mqtt_plugin.o: $(SRC_DIR)/lightserver_mqtt_plugin.cpp
-       $(CXX) $(CXX_INC) -fPIC -o ./release/obj/lightserver_mqtt_plugin.o -c $(SRC_DIR)/lightserver_mqtt_plugin.cpp 
-
-./release/obj/lightserver.o: $(SRC_DIR)/lightserver.cpp
-       $(CXX) $(CXX_FLAGS) -fPIC -o ./release/obj/lightserver.o -c $(SRC_DIR)/lightserver.cpp $(CXX_INC)
-       
-clean:
-       cd ../../lib && $(MAKE) clean
-       rm -rf ./release/obj
-       cd ./release && rm -f *.so
diff --git a/service/protocol-plugin/plugins/mqtt-light/lib/Makefile b/service/protocol-plugin/plugins/mqtt-light/lib/Makefile
deleted file mode 100644 (file)
index 7c10ecb..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-include  config.mk
-
-.PHONY : really clean install
-
-MOSQ_OBJS=mosquitto.o \
-                 logging_mosq.o \
-                 memory_mosq.o \
-                 messages_mosq.o \
-                 net_mosq.o \
-                 read_handle.o \
-                 read_handle_client.o \
-                 read_handle_shared.o \
-                 send_mosq.o \
-                 send_client_mosq.o \
-                 srv_mosq.o \
-                 thread_mosq.o \
-                 time_mosq.o \
-                 tls_mosq.o \
-                 util_mosq.o \
-                 will_mosq.o
-
-all : libmosquitto.so.${SOVERSION} libmosquitto.a
-       $(MAKE) -C cpp
-       $(MAKE) -C python
-
-install : all
-       $(INSTALL) -d ${DESTDIR}$(prefix)/lib${LIB_SUFFIX}/
-       $(INSTALL) -s libmosquitto.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so.${SOVERSION}
-       ln -sf libmosquitto.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so
-       $(INSTALL) -d ${DESTDIR}${prefix}/include/
-       $(INSTALL) mosquitto.h ${DESTDIR}${prefix}/include/mosquitto.h
-       $(MAKE) -C cpp install
-       $(MAKE) -C python install
-
-uninstall :
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so.${SOVERSION}
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquitto.so
-       -rm -f ${DESTDIR}${prefix}/include/mosquitto.h
-
-reallyclean : clean
-
-clean :
-       -rm -f *.o libmosquitto.so.${SOVERSION} libmosquitto.so libmosquitto.a
-       $(MAKE) -C cpp clean
-       $(MAKE) -C python clean
-
-libmosquitto.so.${SOVERSION} : ${MOSQ_OBJS}
-       $(CC) -shared $(LIB_LDFLAGS) $^ -o $@ ${LIB_LIBS}
-
-libmosquitto.a : ${MOSQ_OBJS}
-       $(AR) cr $@ $^
-mosquitto.o : mosquitto.c mosquitto.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-logging_mosq.o : logging_mosq.c logging_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-messages_mosq.o : messages_mosq.c messages_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-memory_mosq.o : memory_mosq.c memory_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-net_mosq.o : net_mosq.c net_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-read_handle.o : read_handle.c read_handle.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-read_handle_client.o : read_handle_client.c read_handle.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-read_handle_shared.o : read_handle_shared.c read_handle.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-send_mosq.o : send_mosq.c send_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-send_client_mosq.o : send_client_mosq.c send_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-srv_mosq.o : srv_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-thread_mosq.o : thread_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-time_mosq.o : time_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-tls_mosq.o : tls_mosq.c
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-util_mosq.o : util_mosq.c util_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
-will_mosq.o : will_mosq.c will_mosq.h
-       $(CC) $(LIB_CFLAGS) -c $< -o $@
-
diff --git a/service/protocol-plugin/plugins/mqtt-light/lib/cpp/Makefile b/service/protocol-plugin/plugins/mqtt-light/lib/cpp/Makefile
deleted file mode 100644 (file)
index 8e04b6c..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-include ../config.mk
-
-ifneq ($(UNAME),SunOS)
-       LIB_LDFLAGS:=$(LDFLAGS) -Wl,-soname,libmosquittopp.so.${SOVERSION}
-endif
-
-.PHONY : clean install
-
-all : libmosquittopp.so.${SOVERSION}
-
-install : all
-       $(INSTALL) -d ${DESTDIR}$(prefix)/lib${LIB_SUFFIX}/
-       $(INSTALL) -s libmosquittopp.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so.${SOVERSION}
-       ln -sf libmosquittopp.so.${SOVERSION} ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so
-       $(INSTALL) -d ${DESTDIR}${prefix}/include/
-       $(INSTALL) mosquittopp.h ${DESTDIR}${prefix}/include/mosquittopp.h
-       
-uninstall :
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so.${SOVERSION}
-       -rm -f ${DESTDIR}${prefix}/lib${LIB_SUFFIX}/libmosquittopp.so
-       -rm -f ${DESTDIR}${prefix}/include/mosquittopp.h
-
-clean :
-       -rm -f *.o libmosquittopp.so.${SOVERSION}
-
-libmosquittopp.so.${SOVERSION} : mosquittopp.o
-       $(CXX) -shared $(LIB_LDFLAGS) $< -o $@ ../libmosquitto.so.${SOVERSION}
-
-mosquittopp.o : mosquittopp.cpp mosquittopp.h
-       $(CXX) $(LIB_CXXFLAGS) -c $< -o $@
-
index fa4e436..dafb375 100644 (file)
@@ -31,275 +31,284 @@ POSSIBILITY OF SUCH DAMAGE.
 #include <mosquitto.h>
 #include <mosquittopp.h>
 
-namespace mosqpp {
-
-static void on_connect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_connect(rc);
-}
-
-static void on_disconnect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_disconnect(rc);
-}
-
-static void on_publish_wrapper(struct mosquitto *mosq, void *userdata, int mid)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_publish(mid);
-}
-
-static void on_message_wrapper(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_message(message);
-}
-
-static void on_subscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_subscribe(mid, qos_count, granted_qos);
-}
-
-static void on_unsubscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_unsubscribe(mid);
-}
-
-
-static void on_log_wrapper(struct mosquitto *mosq, void *userdata, int level, const char *str)
-{
-       class mosquittopp *m = (class mosquittopp *)userdata;
-       m->on_log(level, str);
-}
-
-int lib_version(int *major, int *minor, int *revision)
-{
-       if(major) *major = LIBMOSQUITTO_MAJOR;
-       if(minor) *minor = LIBMOSQUITTO_MINOR;
-       if(revision) *revision = LIBMOSQUITTO_REVISION;
-       return LIBMOSQUITTO_VERSION_NUMBER;
-}
-
-int lib_init()
-{
-       return mosquitto_lib_init();
-}
-
-int lib_cleanup()
-{
-       return mosquitto_lib_cleanup();
-}
-
-const char* strerror(int mosq_errno)
-{
-       return mosquitto_strerror(mosq_errno);
-}
-
-const char* connack_string(int connack_code)
-{
-       return mosquitto_connack_string(connack_code);
-}
-
-int sub_topic_tokenise(const char *subtopic, char ***topics, int *count)
-{
-       return mosquitto_sub_topic_tokenise(subtopic, topics, count);
-}
-
-int sub_topic_tokens_free(char ***topics, int count)
-{
-       return mosquitto_sub_topic_tokens_free(topics, count);
-}
-
-int topic_matches_sub(const char *sub, const char *topic, bool *result)
-{
-       return mosquitto_topic_matches_sub(sub, topic, result);
-}
-
-mosquittopp::mosquittopp(const char *id, bool clean_session)
-{
-       m_mosq = mosquitto_new(id, clean_session, this);
-       mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
-       mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
-       mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
-       mosquitto_message_callback_set(m_mosq, on_message_wrapper);
-       mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
-       mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
-       mosquitto_log_callback_set(m_mosq, on_log_wrapper);
-}
-
-mosquittopp::~mosquittopp()
-{
-       mosquitto_destroy(m_mosq);
-}
-
-int mosquittopp::reinitialise(const char *id, bool clean_session)
-{
-       int rc;
-       rc = mosquitto_reinitialise(m_mosq, id, clean_session, this);
-       if(rc == MOSQ_ERR_SUCCESS){
-               mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
-               mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
-               mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
-               mosquitto_message_callback_set(m_mosq, on_message_wrapper);
-               mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
-               mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
-               mosquitto_log_callback_set(m_mosq, on_log_wrapper);
-       }
-       return rc;
-}
-
-int mosquittopp::connect(const char *host, int port, int keepalive)
-{
-       return mosquitto_connect(m_mosq, host, port, keepalive);
-}
-
-int mosquittopp::connect(const char *host, int port, int keepalive, const char *bind_address)
-{
-       return mosquitto_connect_bind(m_mosq, host, port, keepalive, bind_address);
-}
-
-int mosquittopp::connect_async(const char *host, int port, int keepalive)
-{
-       return mosquitto_connect_async(m_mosq, host, port, keepalive);
-}
-
-int mosquittopp::connect_async(const char *host, int port, int keepalive, const char *bind_address)
-{
-       return mosquitto_connect_bind_async(m_mosq, host, port, keepalive, bind_address);
-}
-
-int mosquittopp::reconnect()
-{
-       return mosquitto_reconnect(m_mosq);
-}
-
-int mosquittopp::reconnect_async()
-{
-       return mosquitto_reconnect_async(m_mosq);
-}
-
-int mosquittopp::disconnect()
-{
-       return mosquitto_disconnect(m_mosq);
-}
-
-int mosquittopp::socket()
-{
-       return mosquitto_socket(m_mosq);
-}
-
-int mosquittopp::will_set(const char *topic, int payloadlen, const void *payload, int qos, bool retain)
-{
-       return mosquitto_will_set(m_mosq, topic, payloadlen, payload, qos, retain);
-}
-
-int mosquittopp::will_clear()
-{
-       return mosquitto_will_clear(m_mosq);
-}
-
-int mosquittopp::username_pw_set(const char *username, const char *password)
-{
-       return mosquitto_username_pw_set(m_mosq, username, password);
-}
-
-int mosquittopp::publish(int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain)
-{
-       return mosquitto_publish(m_mosq, mid, topic, payloadlen, payload, qos, retain);
-}
-
-void mosquittopp::reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff)
-{
-       mosquitto_reconnect_delay_set(m_mosq, reconnect_delay, reconnect_delay_max, reconnect_exponential_backoff);
-}
-
-int mosquittopp::max_inflight_messages_set(unsigned int max_inflight_messages)
-{
-       return mosquitto_max_inflight_messages_set(m_mosq, max_inflight_messages);
-}
-
-void mosquittopp::message_retry_set(unsigned int message_retry)
-{
-       mosquitto_message_retry_set(m_mosq, message_retry);
-}
-
-int mosquittopp::subscribe(int *mid, const char *sub, int qos)
-{
-       return mosquitto_subscribe(m_mosq, mid, sub, qos);
-}
-
-int mosquittopp::unsubscribe(int *mid, const char *sub)
-{
-       return mosquitto_unsubscribe(m_mosq, mid, sub);
-}
-
-int mosquittopp::loop(int timeout, int max_packets)
-{
-       return mosquitto_loop(m_mosq, timeout, max_packets);
-}
-
-int mosquittopp::loop_misc()
-{
-       return mosquitto_loop_misc(m_mosq);
-}
-
-int mosquittopp::loop_read(int max_packets)
-{
-       return mosquitto_loop_read(m_mosq, max_packets);
-}
-
-int mosquittopp::loop_write(int max_packets)
-{
-       return mosquitto_loop_write(m_mosq, max_packets);
-}
-
-int mosquittopp::loop_forever(int timeout, int max_packets)
-{
-       return mosquitto_loop_forever(m_mosq, timeout, max_packets);
-}
-
-int mosquittopp::loop_start()
-{
-       return mosquitto_loop_start(m_mosq);
-}
-
-int mosquittopp::loop_stop(bool force)
-{
-       return mosquitto_loop_stop(m_mosq, force);
-}
-
-bool mosquittopp::want_write()
-{
-       return mosquitto_want_write(m_mosq);
-}
-
-void mosquittopp::user_data_set(void *userdata)
-{
-       mosquitto_user_data_set(m_mosq, userdata);
-}
-
-int mosquittopp::tls_set(const char *cafile, const char *capath, const char *certfile, const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata))
-{
-       return mosquitto_tls_set(m_mosq, cafile, capath, certfile, keyfile, pw_callback);
-}
-
-int mosquittopp::tls_opts_set(int cert_reqs, const char *tls_version, const char *ciphers)
-{
-       return mosquitto_tls_opts_set(m_mosq, cert_reqs, tls_version, ciphers);
-}
-
-int mosquittopp::tls_insecure_set(bool value)
-{
-       return mosquitto_tls_insecure_set(m_mosq, value);
-}
-
-int mosquittopp::tls_psk_set(const char *psk, const char *identity, const char *ciphers)
-{
-       return mosquitto_tls_psk_set(m_mosq, psk, identity, ciphers);
-}
+namespace mosqpp
+{
+
+    static void on_connect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_connect(rc);
+    }
+
+    static void on_disconnect_wrapper(struct mosquitto *mosq, void *userdata, int rc)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_disconnect(rc);
+    }
+
+    static void on_publish_wrapper(struct mosquitto *mosq, void *userdata, int mid)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_publish(mid);
+    }
+
+    static void on_message_wrapper(struct mosquitto *mosq, void *userdata,
+                                   const struct mosquitto_message *message)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_message(message);
+    }
+
+    static void on_subscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid, int qos_count,
+                                     const int *granted_qos)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_subscribe(mid, qos_count, granted_qos);
+    }
+
+    static void on_unsubscribe_wrapper(struct mosquitto *mosq, void *userdata, int mid)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_unsubscribe(mid);
+    }
+
+
+    static void on_log_wrapper(struct mosquitto *mosq, void *userdata, int level, const char *str)
+    {
+        class mosquittopp *m = (class mosquittopp *)userdata;
+        m->on_log(level, str);
+    }
+
+    int lib_version(int *major, int *minor, int *revision)
+    {
+        if (major) *major = LIBMOSQUITTO_MAJOR;
+        if (minor) *minor = LIBMOSQUITTO_MINOR;
+        if (revision) *revision = LIBMOSQUITTO_REVISION;
+        return LIBMOSQUITTO_VERSION_NUMBER;
+    }
+
+    int lib_init()
+    {
+        return mosquitto_lib_init();
+    }
+
+    int lib_cleanup()
+    {
+        return mosquitto_lib_cleanup();
+    }
+
+    const char *strerror(int mosq_errno)
+    {
+        return mosquitto_strerror(mosq_errno);
+    }
+
+    const char *connack_string(int connack_code)
+    {
+        return mosquitto_connack_string(connack_code);
+    }
+
+    int sub_topic_tokenise(const char *subtopic, char ***topics, int *count)
+    {
+        return mosquitto_sub_topic_tokenise(subtopic, topics, count);
+    }
+
+    int sub_topic_tokens_free(char ***topics, int count)
+    {
+        return mosquitto_sub_topic_tokens_free(topics, count);
+    }
+
+    int topic_matches_sub(const char *sub, const char *topic, bool *result)
+    {
+        return mosquitto_topic_matches_sub(sub, topic, result);
+    }
+
+    mosquittopp::mosquittopp(const char *id, bool clean_session)
+    {
+        m_mosq = mosquitto_new(id, clean_session, this);
+        mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
+        mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
+        mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
+        mosquitto_message_callback_set(m_mosq, on_message_wrapper);
+        mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
+        mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
+        mosquitto_log_callback_set(m_mosq, on_log_wrapper);
+    }
+
+    mosquittopp::~mosquittopp()
+    {
+        mosquitto_destroy(m_mosq);
+    }
+
+    int mosquittopp::reinitialise(const char *id, bool clean_session)
+    {
+        int rc;
+        rc = mosquitto_reinitialise(m_mosq, id, clean_session, this);
+        if (rc == MOSQ_ERR_SUCCESS)
+        {
+            mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
+            mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
+            mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
+            mosquitto_message_callback_set(m_mosq, on_message_wrapper);
+            mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
+            mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
+            mosquitto_log_callback_set(m_mosq, on_log_wrapper);
+        }
+        return rc;
+    }
+
+    int mosquittopp::connect(const char *host, int port, int keepalive)
+    {
+        return mosquitto_connect(m_mosq, host, port, keepalive);
+    }
+
+    int mosquittopp::connect(const char *host, int port, int keepalive, const char *bind_address)
+    {
+        return mosquitto_connect_bind(m_mosq, host, port, keepalive, bind_address);
+    }
+
+    int mosquittopp::connect_async(const char *host, int port, int keepalive)
+    {
+        return mosquitto_connect_async(m_mosq, host, port, keepalive);
+    }
+
+    int mosquittopp::connect_async(const char *host, int port, int keepalive, const char *bind_address)
+    {
+        return mosquitto_connect_bind_async(m_mosq, host, port, keepalive, bind_address);
+    }
+
+    int mosquittopp::reconnect()
+    {
+        return mosquitto_reconnect(m_mosq);
+    }
+
+    int mosquittopp::reconnect_async()
+    {
+        return mosquitto_reconnect_async(m_mosq);
+    }
+
+    int mosquittopp::disconnect()
+    {
+        return mosquitto_disconnect(m_mosq);
+    }
+
+    int mosquittopp::socket()
+    {
+        return mosquitto_socket(m_mosq);
+    }
+
+    int mosquittopp::will_set(const char *topic, int payloadlen, const void *payload, int qos,
+                              bool retain)
+    {
+        return mosquitto_will_set(m_mosq, topic, payloadlen, payload, qos, retain);
+    }
+
+    int mosquittopp::will_clear()
+    {
+        return mosquitto_will_clear(m_mosq);
+    }
+
+    int mosquittopp::username_pw_set(const char *username, const char *password)
+    {
+        return mosquitto_username_pw_set(m_mosq, username, password);
+    }
+
+    int mosquittopp::publish(int *mid, const char *topic, int payloadlen, const void *payload, int qos,
+                             bool retain)
+    {
+        return mosquitto_publish(m_mosq, mid, topic, payloadlen, payload, qos, retain);
+    }
+
+    void mosquittopp::reconnect_delay_set(unsigned int reconnect_delay,
+                                          unsigned int reconnect_delay_max, bool reconnect_exponential_backoff)
+    {
+        mosquitto_reconnect_delay_set(m_mosq, reconnect_delay, reconnect_delay_max,
+                                      reconnect_exponential_backoff);
+    }
+
+    int mosquittopp::max_inflight_messages_set(unsigned int max_inflight_messages)
+    {
+        return mosquitto_max_inflight_messages_set(m_mosq, max_inflight_messages);
+    }
+
+    void mosquittopp::message_retry_set(unsigned int message_retry)
+    {
+        mosquitto_message_retry_set(m_mosq, message_retry);
+    }
+
+    int mosquittopp::subscribe(int *mid, const char *sub, int qos)
+    {
+        return mosquitto_subscribe(m_mosq, mid, sub, qos);
+    }
+
+    int mosquittopp::unsubscribe(int *mid, const char *sub)
+    {
+        return mosquitto_unsubscribe(m_mosq, mid, sub);
+    }
+
+    int mosquittopp::loop(int timeout, int max_packets)
+    {
+        return mosquitto_loop(m_mosq, timeout, max_packets);
+    }
+
+    int mosquittopp::loop_misc()
+    {
+        return mosquitto_loop_misc(m_mosq);
+    }
+
+    int mosquittopp::loop_read(int max_packets)
+    {
+        return mosquitto_loop_read(m_mosq, max_packets);
+    }
+
+    int mosquittopp::loop_write(int max_packets)
+    {
+        return mosquitto_loop_write(m_mosq, max_packets);
+    }
+
+    int mosquittopp::loop_forever(int timeout, int max_packets)
+    {
+        return mosquitto_loop_forever(m_mosq, timeout, max_packets);
+    }
+
+    int mosquittopp::loop_start()
+    {
+        return mosquitto_loop_start(m_mosq);
+    }
+
+    int mosquittopp::loop_stop(bool force)
+    {
+        return mosquitto_loop_stop(m_mosq, force);
+    }
+
+    bool mosquittopp::want_write()
+    {
+        return mosquitto_want_write(m_mosq);
+    }
+
+    void mosquittopp::user_data_set(void *userdata)
+    {
+        mosquitto_user_data_set(m_mosq, userdata);
+    }
+
+    int mosquittopp::tls_set(const char *cafile, const char *capath, const char *certfile,
+                             const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata))
+    {
+        return mosquitto_tls_set(m_mosq, cafile, capath, certfile, keyfile, pw_callback);
+    }
+
+    int mosquittopp::tls_opts_set(int cert_reqs, const char *tls_version, const char *ciphers)
+    {
+        return mosquitto_tls_opts_set(m_mosq, cert_reqs, tls_version, ciphers);
+    }
+
+    int mosquittopp::tls_insecure_set(bool value)
+    {
+        return mosquitto_tls_insecure_set(m_mosq, value);
+    }
+
+    int mosquittopp::tls_psk_set(const char *psk, const char *identity, const char *ciphers)
+    {
+        return mosquitto_tls_psk_set(m_mosq, psk, identity, ciphers);
+    }
 
 }
index 41537b6..8e3cabf 100644 (file)
@@ -38,85 +38,92 @@ This product includes software written by Tim Hudson (tjh@cryptsoft.com)
 #define _MOSQUITTOPP_H_
 
 #ifdef _WIN32
-#      ifdef mosquittopp_EXPORTS
-#              define mosqpp_EXPORT  __declspec(dllexport)
-#      else
-#              define mosqpp_EXPORT  __declspec(dllimport)
-#      endif
+#   ifdef mosquittopp_EXPORTS
+#       define mosqpp_EXPORT  __declspec(dllexport)
+#   else
+#       define mosqpp_EXPORT  __declspec(dllimport)
+#   endif
 #else
-#      define mosqpp_EXPORT
+#   define mosqpp_EXPORT
 #endif
 
 #include <cstdlib>
 #include <time.h>
 #include "../mosquitto.h"
 
-namespace mosqpp {
+namespace mosqpp
+{
 
-mosqpp_EXPORT const char *strerror(int mosq_errno);
-mosqpp_EXPORT const char *connack_string(int connack_code);
-mosqpp_EXPORT int sub_topic_tokenise(const char *subtopic, char ***topics, int *count);
-mosqpp_EXPORT int sub_topic_tokens_free(char ***topics, int count);
-mosqpp_EXPORT int lib_version(int *major, int *minor, int *revision);
-mosqpp_EXPORT int lib_init();
-mosqpp_EXPORT int lib_cleanup();
-mosqpp_EXPORT int topic_matches_sub(const char *sub, const char *topic, bool *result);
+    mosqpp_EXPORT const char *strerror(int mosq_errno);
+    mosqpp_EXPORT const char *connack_string(int connack_code);
+    mosqpp_EXPORT int sub_topic_tokenise(const char *subtopic, char ***topics, int *count);
+    mosqpp_EXPORT int sub_topic_tokens_free(char ***topics, int count);
+    mosqpp_EXPORT int lib_version(int *major, int *minor, int *revision);
+    mosqpp_EXPORT int lib_init();
+    mosqpp_EXPORT int lib_cleanup();
+    mosqpp_EXPORT int topic_matches_sub(const char *sub, const char *topic, bool *result);
 
-/*
- * Class: mosquittopp
- *
- * A mosquitto client class. This is a C++ wrapper class for the mosquitto C
- * library. Please see mosquitto.h for details of the functions.
- */
-class mosqpp_EXPORT mosquittopp {
-       private:
-               struct mosquitto *m_mosq;
-       public:
-               mosquittopp(const char *id=NULL, bool clean_session=true);
-               ~mosquittopp();
+    /*
+     * Class: mosquittopp
+     *
+     * A mosquitto client class. This is a C++ wrapper class for the mosquitto C
+     * library. Please see mosquitto.h for details of the functions.
+     */
+    class mosqpp_EXPORT mosquittopp
+    {
+        private:
+            struct mosquitto *m_mosq;
+        public:
+            mosquittopp(const char *id = NULL, bool clean_session = true);
+            ~mosquittopp();
+
+            int reinitialise(const char *id, bool clean_session);
+            int socket();
+            int will_set(const char *topic, int payloadlen = 0, const void *payload = NULL, int qos = 0,
+                         bool retain = false);
+            int will_clear();
+            int username_pw_set(const char *username, const char *password = NULL);
+            int connect(const char *host, int port = 1883, int keepalive = 60);
+            int connect_async(const char *host, int port = 1883, int keepalive = 60);
+            int connect(const char *host, int port, int keepalive, const char *bind_address);
+            int connect_async(const char *host, int port, int keepalive, const char *bind_address);
+            int reconnect();
+            int reconnect_async();
+            int disconnect();
+            int publish(int *mid, const char *topic, int payloadlen = 0, const void *payload = NULL,
+                        int qos = 0, bool retain = false);
+            int subscribe(int *mid, const char *sub, int qos = 0);
+            int unsubscribe(int *mid, const char *sub);
+            void reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max,
+                                     bool reconnect_exponential_backoff);
+            int max_inflight_messages_set(unsigned int max_inflight_messages);
+            void message_retry_set(unsigned int message_retry);
+            void user_data_set(void *userdata);
+            int tls_set(const char *cafile, const char *capath = NULL, const char *certfile = NULL,
+                        const char *keyfile = NULL, int (*pw_callback)(char *buf, int size, int rwflag,
+                                void *userdata) = NULL);
+            int tls_opts_set(int cert_reqs, const char *tls_version = NULL, const char *ciphers = NULL);
+            int tls_insecure_set(bool value);
+            int tls_psk_set(const char *psk, const char *identity, const char *ciphers = NULL);
 
-               int reinitialise(const char *id, bool clean_session);
-               int socket();
-               int will_set(const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false);
-               int will_clear();
-               int username_pw_set(const char *username, const char *password=NULL);
-               int connect(const char *host, int port=1883, int keepalive=60);
-               int connect_async(const char *host, int port=1883, int keepalive=60);
-               int connect(const char *host, int port, int keepalive, const char *bind_address);
-               int connect_async(const char *host, int port, int keepalive, const char *bind_address);
-               int reconnect();
-               int reconnect_async();
-               int disconnect();
-               int publish(int *mid, const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false);
-               int subscribe(int *mid, const char *sub, int qos=0);
-               int unsubscribe(int *mid, const char *sub);
-               void reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff);
-               int max_inflight_messages_set(unsigned int max_inflight_messages);
-               void message_retry_set(unsigned int message_retry);
-               void user_data_set(void *userdata);
-               int tls_set(const char *cafile, const char *capath=NULL, const char *certfile=NULL, const char *keyfile=NULL, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)=NULL);
-               int tls_opts_set(int cert_reqs, const char *tls_version=NULL, const char *ciphers=NULL);
-               int tls_insecure_set(bool value);
-               int tls_psk_set(const char *psk, const char *identity, const char *ciphers=NULL);
+            int loop(int timeout = -1, int max_packets = 1);
+            int loop_misc();
+            int loop_read(int max_packets = 1);
+            int loop_write(int max_packets = 1);
+            int loop_forever(int timeout = -1, int max_packets = 1);
+            int loop_start();
+            int loop_stop(bool force = false);
+            bool want_write();
 
-               int loop(int timeout=-1, int max_packets=1);
-               int loop_misc();
-               int loop_read(int max_packets=1);
-               int loop_write(int max_packets=1);
-               int loop_forever(int timeout=-1, int max_packets=1);
-               int loop_start();
-               int loop_stop(bool force=false);
-               bool want_write();
-               
-               virtual void on_connect(int rc) {return;};
-               virtual void on_disconnect(int rc) {return;};
-               virtual void on_publish(int mid) {return;};
-               virtual void on_message(const struct mosquitto_message *message) {return;};
-               virtual void on_subscribe(int mid, int qos_count, const int *granted_qos) {return;};
-               virtual void on_unsubscribe(int mid) {return;};
-               virtual void on_log(int level, const char *str) {return;};
-               virtual void on_error() {return;};
-};
+            virtual void on_connect(int rc) {return;};
+            virtual void on_disconnect(int rc) {return;};
+            virtual void on_publish(int mid) {return;};
+            virtual void on_message(const struct mosquitto_message *message) {return;};
+            virtual void on_subscribe(int mid, int qos_count, const int *granted_qos) {return;};
+            virtual void on_unsubscribe(int mid) {return;};
+            virtual void on_log(int level, const char *str) {return;};
+            virtual void on_error() {return;};
+    };
 
 }
 #endif
index 31f3251..e71f525 100644 (file)
@@ -7,7 +7,7 @@
 
 #define pthread_mutex_init(A, B)
 #define pthread_mutex_destroy(A)
-#define pthread_mutex_lock(A) 
-#define pthread_mutex_unlock(A) 
+#define pthread_mutex_lock(A)
+#define pthread_mutex_unlock(A)
 
 #endif
index b9d0c8e..eebea23 100644 (file)
@@ -34,11 +34,15 @@ POSSIBILITY OF SUCH DAMAGE.
 
 void _mosquitto_message_cleanup_all(struct mosquitto *mosq);
 void _mosquitto_message_cleanup(struct mosquitto_message_all **message);
-int _mosquitto_message_delete(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir);
-void _mosquitto_message_queue(struct mosquitto *mosq, struct mosquitto_message_all *message, enum mosquitto_msg_direction dir);
+int _mosquitto_message_delete(struct mosquitto *mosq, uint16_t mid,
+                              enum mosquitto_msg_direction dir);
+void _mosquitto_message_queue(struct mosquitto *mosq, struct mosquitto_message_all *message,
+                              enum mosquitto_msg_direction dir);
 void _mosquitto_messages_reconnect_reset(struct mosquitto *mosq);
-int _mosquitto_message_remove(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_direction dir, struct mosquitto_message_all **message);
+int _mosquitto_message_remove(struct mosquitto *mosq, uint16_t mid,
+                              enum mosquitto_msg_direction dir, struct mosquitto_message_all **message);
 void _mosquitto_message_retry_check(struct mosquitto *mosq);
-int _mosquitto_message_out_update(struct mosquitto *mosq, uint16_t mid, enum mosquitto_msg_state state);
+int _mosquitto_message_out_update(struct mosquitto *mosq, uint16_t mid,
+                                  enum mosquitto_msg_state state);
 
 #endif
index 27506eb..ca3bf12 100644 (file)
@@ -42,25 +42,25 @@ extern "C" {
 #endif
 
 #if defined(WIN32) && !defined(WITH_BROKER)
-#      ifdef libmosquitto_EXPORTS
-#              define libmosq_EXPORT  __declspec(dllexport)
-#      else
-#              define libmosq_EXPORT  __declspec(dllimport)
-#      endif
+#   ifdef libmosquitto_EXPORTS
+#       define libmosq_EXPORT  __declspec(dllexport)
+#   else
+#       define libmosq_EXPORT  __declspec(dllimport)
+#   endif
 #else
-#      define libmosq_EXPORT
+#   define libmosq_EXPORT
 #endif
 
 #ifdef WIN32
-#      ifndef __cplusplus
-#              define bool char
-#              define true 1
-#              define false 0
-#      endif
+#   ifndef __cplusplus
+#       define bool char
+#       define true 1
+#       define false 0
+#   endif
 #else
-#      ifndef __cplusplus
-#              include <stdbool.h>
-#      endif
+#   ifndef __cplusplus
+#       include <stdbool.h>
+#   endif
 #endif
 
 #define LIBMOSQUITTO_MAJOR 1
@@ -81,48 +81,50 @@ extern "C" {
 #define MOSQ_LOG_ALL 0xFFFF
 
 /* Error values */
-enum mosq_err_t {
-       MOSQ_ERR_CONN_PENDING = -1,
-       MOSQ_ERR_SUCCESS = 0,
-       MOSQ_ERR_NOMEM = 1,
-       MOSQ_ERR_PROTOCOL = 2,
-       MOSQ_ERR_INVAL = 3,
-       MOSQ_ERR_NO_CONN = 4,
-       MOSQ_ERR_CONN_REFUSED = 5,
-       MOSQ_ERR_NOT_FOUND = 6,
-       MOSQ_ERR_CONN_LOST = 7,
-       MOSQ_ERR_TLS = 8,
-       MOSQ_ERR_PAYLOAD_SIZE = 9,
-       MOSQ_ERR_NOT_SUPPORTED = 10,
-       MOSQ_ERR_AUTH = 11,
-       MOSQ_ERR_ACL_DENIED = 12,
-       MOSQ_ERR_UNKNOWN = 13,
-       MOSQ_ERR_ERRNO = 14,
-       MOSQ_ERR_EAI = 15
+enum mosq_err_t
+{
+    MOSQ_ERR_CONN_PENDING = -1,
+    MOSQ_ERR_SUCCESS = 0,
+    MOSQ_ERR_NOMEM = 1,
+    MOSQ_ERR_PROTOCOL = 2,
+    MOSQ_ERR_INVAL = 3,
+    MOSQ_ERR_NO_CONN = 4,
+    MOSQ_ERR_CONN_REFUSED = 5,
+    MOSQ_ERR_NOT_FOUND = 6,
+    MOSQ_ERR_CONN_LOST = 7,
+    MOSQ_ERR_TLS = 8,
+    MOSQ_ERR_PAYLOAD_SIZE = 9,
+    MOSQ_ERR_NOT_SUPPORTED = 10,
+    MOSQ_ERR_AUTH = 11,
+    MOSQ_ERR_ACL_DENIED = 12,
+    MOSQ_ERR_UNKNOWN = 13,
+    MOSQ_ERR_ERRNO = 14,
+    MOSQ_ERR_EAI = 15
 };
 
 /* MQTT specification restricts client ids to a maximum of 23 characters */
 #define MOSQ_MQTT_ID_MAX_LENGTH 23
 
-struct mosquitto_message{
-       int mid;
-       char *topic;
-       void *payload;
-       int payloadlen;
-       int qos;
-       bool retain;
+struct mosquitto_message
+{
+    int mid;
+    char *topic;
+    void *payload;
+    int payloadlen;
+    int qos;
+    bool retain;
 };
 
 struct mosquitto;
 
 /*
  * Topic: Threads
- *     libmosquitto provides thread safe operation, with the exception of
- *     <mosquitto_lib_init> which is not thread safe.
+ *  libmosquitto provides thread safe operation, with the exception of
+ *  <mosquitto_lib_init> which is not thread safe.
  */
 /***************************************************
  * Important note
- * 
+ *
  * The following functions that deal with network operations will return
  * MOSQ_ERR_SUCCESS on success, but this does not mean that the operation has
  * taken place. An attempt will be made to write the network data, but if the
@@ -157,10 +159,10 @@ struct mosquitto;
  *             be returned in this variable.
  *
  * Returns:
- *     LIBMOSQUITTO_VERSION_NUMBER, which is a unique number based on the major,
- *             minor and revision values.
+ *  LIBMOSQUITTO_VERSION_NUMBER, which is a unique number based on the major,
+ *      minor and revision values.
  * See Also:
- *     <mosquitto_lib_cleanup>, <mosquitto_lib_init>
+ *  <mosquitto_lib_cleanup>, <mosquitto_lib_init>
  */
 libmosq_EXPORT int mosquitto_lib_version(int *major, int *minor, int *revision);
 
@@ -172,10 +174,10 @@ libmosq_EXPORT int mosquitto_lib_version(int *major, int *minor, int *revision);
  * This function is *not* thread safe.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - always
+ *  MOSQ_ERR_SUCCESS - always
  *
  * See Also:
- *     <mosquitto_lib_cleanup>, <mosquitto_lib_version>
+ *  <mosquitto_lib_cleanup>, <mosquitto_lib_version>
  */
 libmosq_EXPORT int mosquitto_lib_init(void);
 
@@ -185,10 +187,10 @@ libmosq_EXPORT int mosquitto_lib_init(void);
  * Call to free resources associated with the library.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - always
+ *  MOSQ_ERR_SUCCESS - always
  *
  * See Also:
- *     <mosquitto_lib_init>, <mosquitto_lib_version>
+ *  <mosquitto_lib_init>, <mosquitto_lib_version>
  */
 libmosq_EXPORT int mosquitto_lib_cleanup(void);
 
@@ -198,9 +200,9 @@ libmosq_EXPORT int mosquitto_lib_cleanup(void);
  * Create a new mosquitto client instance.
  *
  * Parameters:
- *     id -            String to use as the client id. If NULL, a random client id
- *                     will be generated. If id is NULL, clean_session must be true.
- *     clean_session - set to true to instruct the broker to clean all messages
+ *  id -            String to use as the client id. If NULL, a random client id
+ *                  will be generated. If id is NULL, clean_session must be true.
+ *  clean_session - set to true to instruct the broker to clean all messages
  *                  and subscriptions on disconnect, false to instruct it to
  *                  keep them. See the man page mqtt(7) for more details.
  *                  Note that a client will never discard its own outgoing
@@ -209,30 +211,30 @@ libmosq_EXPORT int mosquitto_lib_cleanup(void);
  *                  Use <mosquitto_reinitialise> to reset a client to its
  *                  original state.
  *                  Must be set to true if the id parameter is NULL.
- *     obj -           A user pointer that will be passed as an argument to any
+ *  obj -           A user pointer that will be passed as an argument to any
  *                  callbacks that are specified.
  *
  * Returns:
- *     Pointer to a struct mosquitto on success.
- *     NULL on failure. Interrogate errno to determine the cause for the failure:
+ *  Pointer to a struct mosquitto on success.
+ *  NULL on failure. Interrogate errno to determine the cause for the failure:
  *      - ENOMEM on out of memory.
  *      - EINVAL on invalid input parameters.
  *
  * See Also:
- *     <mosquitto_reinitialise>, <mosquitto_destroy>, <mosquitto_user_data_set>
+ *  <mosquitto_reinitialise>, <mosquitto_destroy>, <mosquitto_user_data_set>
  */
 libmosq_EXPORT struct mosquitto *mosquitto_new(const char *id, bool clean_session, void *obj);
 
-/* 
+/*
  * Function: mosquitto_destroy
  *
  * Use to free memory associated with a mosquitto client instance.
  *
  * Parameters:
- *     mosq - a struct mosquitto pointer to free.
+ *  mosq - a struct mosquitto pointer to free.
  *
  * See Also:
- *     <mosquitto_new>, <mosquitto_reinitialise>
+ *  <mosquitto_new>, <mosquitto_reinitialise>
  */
 libmosq_EXPORT void mosquitto_destroy(struct mosquitto *mosq);
 
@@ -245,63 +247,65 @@ libmosq_EXPORT void mosquitto_destroy(struct mosquitto *mosq);
  * same as the output of <mosquitto_new>.
  *
  * Parameters:
- *     mosq -          a valid mosquitto instance.
- *     id -            string to use as the client id. If NULL, a random client id
- *                     will be generated. If id is NULL, clean_session must be true.
- *     clean_session - set to true to instruct the broker to clean all messages
+ *  mosq -          a valid mosquitto instance.
+ *  id -            string to use as the client id. If NULL, a random client id
+ *                  will be generated. If id is NULL, clean_session must be true.
+ *  clean_session - set to true to instruct the broker to clean all messages
  *                  and subscriptions on disconnect, false to instruct it to
  *                  keep them. See the man page mqtt(7) for more details.
  *                  Must be set to true if the id parameter is NULL.
- *     obj -           A user pointer that will be passed as an argument to any
+ *  obj -           A user pointer that will be passed as an argument to any
  *                  callbacks that are specified.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_new>, <mosquitto_destroy>
+ *  <mosquitto_new>, <mosquitto_destroy>
  */
-libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_session, void *obj);
+libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id,
+        bool clean_session, void *obj);
 
-/* 
+/*
  * Function: mosquitto_will_set
  *
  * Configure will information for a mosquitto instance. By default, clients do
  * not have a will.  This must be called before calling <mosquitto_connect>.
  *
  * Parameters:
- *     mosq -       a valid mosquitto instance.
- *     topic -      the topic on which to publish the will.
- *     payloadlen - the size of the payload (bytes). Valid values are between 0 and
+ *  mosq -       a valid mosquitto instance.
+ *  topic -      the topic on which to publish the will.
+ *  payloadlen - the size of the payload (bytes). Valid values are between 0 and
  *               268,435,455.
- *     payload -    pointer to the data to send. If payloadlen > 0 this must be a
+ *  payload -    pointer to the data to send. If payloadlen > 0 this must be a
  *               valid memory location.
- *     qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
+ *  qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
  *               used for the will.
- *     retain -     set to true to make the will a retained message.
+ *  retain -     set to true to make the will a retained message.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -      on success.
- *     MOSQ_ERR_INVAL -        if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
- *     MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
+ *  MOSQ_ERR_SUCCESS -      on success.
+ *  MOSQ_ERR_INVAL -        if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
+ *  MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
  */
-libmosq_EXPORT int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain);
+libmosq_EXPORT int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen,
+                                      const void *payload, int qos, bool retain);
 
-/* 
+/*
  * Function: mosquitto_will_clear
  *
  * Remove a previously configured will. This must be called before calling
  * <mosquitto_connect>.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  */
 libmosq_EXPORT int mosquitto_will_clear(struct mosquitto *mosq);
 
@@ -317,18 +321,19 @@ libmosq_EXPORT int mosquitto_will_clear(struct mosquitto *mosq);
  * This is must be called before calling <mosquitto_connect>.
  *
  * Parameters:
- *     mosq -     a valid mosquitto instance.
- *     username - the username to send as a string, or NULL to disable
+ *  mosq -     a valid mosquitto instance.
+ *  username - the username to send as a string, or NULL to disable
  *             authentication.
- *     password - the password to send as a string. Set to NULL when username is
- *                valid in order to send just a username.
+ *  password - the password to send as a string. Set to NULL when username is
+ *             valid in order to send just a username.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  */
-libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username, const char *password);
+libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username,
+        const char *password);
 
 /*
  * Function: mosquitto_connect
@@ -336,55 +341,57 @@ libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char
  * Connect to an MQTT broker.
  *
  * Parameters:
- *     mosq -      a valid mosquitto instance.
- *     host -      the hostname or ip address of the broker to connect to.
- *     port -      the network port to connect to. Usually 1883.
- *     keepalive - the number of seconds after which the broker should send a PING
+ *  mosq -      a valid mosquitto instance.
+ *  host -      the hostname or ip address of the broker to connect to.
+ *  port -      the network port to connect to. Usually 1883.
+ *  keepalive - the number of seconds after which the broker should send a PING
  *              message to the client if no other messages have been exchanged
  *              in that time.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_bind>, <mosquitto_connect_async>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
+ *  <mosquitto_connect_bind>, <mosquitto_connect_async>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_connect(struct mosquitto *mosq, const char *host, int port, int keepalive);
+libmosq_EXPORT int mosquitto_connect(struct mosquitto *mosq, const char *host, int port,
+                                     int keepalive);
 
 /*
  * Function: mosquitto_connect_bind
  *
  * Connect to an MQTT broker. This extends the functionality of
  * <mosquitto_connect> by adding the bind_address parameter. Use this function
- * if you need to restrict network communication over a particular interface. 
+ * if you need to restrict network communication over a particular interface.
  *
  * Parameters:
- *     mosq -         a valid mosquitto instance.
- *     host -         the hostname or ip address of the broker to connect to.
- *     port -         the network port to connect to. Usually 1883.
- *     keepalive -    the number of seconds after which the broker should send a PING
+ *  mosq -         a valid mosquitto instance.
+ *  host -         the hostname or ip address of the broker to connect to.
+ *  port -         the network port to connect to. Usually 1883.
+ *  keepalive -    the number of seconds after which the broker should send a PING
  *                 message to the client if no other messages have been exchanged
  *                 in that time.
  *  bind_address - the hostname or ip address of the local network interface to
  *                 bind to.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect>, <mosquitto_connect_async>, <mosquitto_connect_bind_async>
+ *  <mosquitto_connect>, <mosquitto_connect_async>, <mosquitto_connect_bind_async>
  */
-libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address);
+libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port,
+        int keepalive, const char *bind_address);
 
 /*
  * Function: mosquitto_connect_async
@@ -397,25 +404,26 @@ libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *ho
  * May be called before or after <mosquitto_loop_start>.
  *
  * Parameters:
- *     mosq -      a valid mosquitto instance.
- *     host -      the hostname or ip address of the broker to connect to.
- *     port -      the network port to connect to. Usually 1883.
- *     keepalive - the number of seconds after which the broker should send a PING
+ *  mosq -      a valid mosquitto instance.
+ *  host -      the hostname or ip address of the broker to connect to.
+ *  port -      the network port to connect to. Usually 1883.
+ *  keepalive - the number of seconds after which the broker should send a PING
  *              message to the client if no other messages have been exchanged
  *              in that time.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_bind_async>, <mosquitto_connect>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
+ *  <mosquitto_connect_bind_async>, <mosquitto_connect>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port, int keepalive);
+libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port,
+        int keepalive);
 
 /*
  * Function: mosquitto_connect_async
@@ -427,32 +435,33 @@ libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *h
  *
  * This extends the functionality of <mosquitto_connect_async> by adding the
  * bind_address parameter. Use this function if you need to restrict network
- * communication over a particular interface. 
+ * communication over a particular interface.
  *
  * May be called before or after <mosquitto_loop_start>.
  *
  * Parameters:
- *     mosq -         a valid mosquitto instance.
- *     host -         the hostname or ip address of the broker to connect to.
- *     port -         the network port to connect to. Usually 1883.
- *     keepalive -    the number of seconds after which the broker should send a PING
+ *  mosq -         a valid mosquitto instance.
+ *  host -         the hostname or ip address of the broker to connect to.
+ *  port -         the network port to connect to. Usually 1883.
+ *  keepalive -    the number of seconds after which the broker should send a PING
  *                 message to the client if no other messages have been exchanged
  *                 in that time.
  *  bind_address - the hostname or ip address of the local network interface to
  *                 bind to.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
+ *  <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
  */
-libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address);
+libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port,
+        int keepalive, const char *bind_address);
 
 /*
  * Function: mosquitto_connect_srv
@@ -464,31 +473,32 @@ libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const ch
  *
  * This extends the functionality of <mosquitto_connect_async> by adding the
  * bind_address parameter. Use this function if you need to restrict network
- * communication over a particular interface. 
+ * communication over a particular interface.
  *
  * May be called before or after <mosquitto_loop_start>.
  *
  * Parameters:
- *     mosq -         a valid mosquitto instance.
- *     host -         the hostname or ip address of the broker to connect to.
- *     keepalive -    the number of seconds after which the broker should send a PING
+ *  mosq -         a valid mosquitto instance.
+ *  host -         the hostname or ip address of the broker to connect to.
+ *  keepalive -    the number of seconds after which the broker should send a PING
  *                 message to the client if no other messages have been exchanged
  *                 in that time.
  *  bind_address - the hostname or ip address of the local network interface to
  *                 bind to.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
+ *  <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
  */
-libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address);
+libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive,
+        const char *bind_address);
 
 /*
  * Function: mosquitto_reconnect
@@ -499,25 +509,25 @@ libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *hos
  * connection has been lost. It uses the values that were provided in the
  * <mosquitto_connect> call. It must not be called before
  * <mosquitto_connect>.
- * 
+ *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect>, <mosquitto_disconnect>, <mosquitto_reconnect_async>
+ *  <mosquitto_connect>, <mosquitto_disconnect>, <mosquitto_reconnect_async>
  */
 libmosq_EXPORT int mosquitto_reconnect(struct mosquitto *mosq);
 
@@ -530,25 +540,25 @@ libmosq_EXPORT int mosquitto_reconnect(struct mosquitto *mosq);
  * connection has been lost. It uses the values that were provided in the
  * <mosquitto_connect> or <mosquitto_connect_async> calls. It must not be
  * called before <mosquitto_connect>.
- * 
+ *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_ERRNO -   if a system call returned an error. The variable errno
  *                     contains the error code, even on Windows.
  *                     Use strerror_r() where available or FormatMessage() on
  *                     Windows.
  *
  * See Also:
- *     <mosquitto_connect>, <mosquitto_disconnect>
+ *  <mosquitto_connect>, <mosquitto_disconnect>
  */
 libmosq_EXPORT int mosquitto_reconnect_async(struct mosquitto *mosq);
 
@@ -558,50 +568,51 @@ libmosq_EXPORT int mosquitto_reconnect_async(struct mosquitto *mosq);
  * Disconnect from the broker.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NO_CONN -  if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NO_CONN -  if the client isn't connected to a broker.
  */
 libmosq_EXPORT int mosquitto_disconnect(struct mosquitto *mosq);
 
-/* 
+/*
  * Function: mosquitto_publish
  *
  * Publish a message on a given topic.
- * 
+ *
  * Parameters:
- *     mosq -       a valid mosquitto instance.
- *     mid -        pointer to an int. If not NULL, the function will set this
+ *  mosq -       a valid mosquitto instance.
+ *  mid -        pointer to an int. If not NULL, the function will set this
  *               to the message id of this particular message. This can be then
  *               used with the publish callback to determine when the message
  *               has been sent.
  *               Note that although the MQTT protocol doesn't use message ids
  *               for messages with QoS=0, libmosquitto assigns them message ids
  *               so they can be tracked with this parameter.
- *     payloadlen - the size of the payload (bytes). Valid values are between 0 and
+ *  payloadlen - the size of the payload (bytes). Valid values are between 0 and
  *               268,435,455.
- *     payload -    pointer to the data to send. If payloadlen > 0 this must be a
+ *  payload -    pointer to the data to send. If payloadlen > 0 this must be a
  *               valid memory location.
- *     qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
+ *  qos -        integer value 0, 1 or 2 indicating the Quality of Service to be
  *               used for the message.
- *     retain -     set to true to make the message retained.
+ *  retain -     set to true to make the message retained.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -      on success.
- *     MOSQ_ERR_INVAL -        if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -      if the client isn't connected to a broker.
- *     MOSQ_ERR_PROTOCOL -     if there is a protocol error communicating with the
+ *  MOSQ_ERR_SUCCESS -      on success.
+ *  MOSQ_ERR_INVAL -        if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -        if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -      if the client isn't connected to a broker.
+ *  MOSQ_ERR_PROTOCOL -     if there is a protocol error communicating with the
  *                          broker.
- *     MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
+ *  MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
  *
- * See Also: 
- *     <mosquitto_max_inflight_messages_set>
+ * See Also:
+ *  <mosquitto_max_inflight_messages_set>
  */
-libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain);
+libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic,
+                                     int payloadlen, const void *payload, int qos, bool retain);
 
 /*
  * Function: mosquitto_subscribe
@@ -609,19 +620,19 @@ libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const cha
  * Subscribe to a topic.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
- *     mid -  a pointer to an int. If not NULL, the function will set this to
- *            the message id of this particular message. This can be then used
- *            with the subscribe callback to determine when the message has been
- *            sent.
- *     sub -  the subscription pattern.
- *     qos -  the requested Quality of Service for this subscription.
+ *  mosq - a valid mosquitto instance.
+ *  mid -  a pointer to an int. If not NULL, the function will set this to
+ *         the message id of this particular message. This can be then used
+ *         with the subscribe callback to determine when the message has been
+ *         sent.
+ *  sub -  the subscription pattern.
+ *  qos -  the requested Quality of Service for this subscription.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
  */
 libmosq_EXPORT int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const char *sub, int qos);
 
@@ -631,18 +642,18 @@ libmosq_EXPORT int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const c
  * Unsubscribe from a topic.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
- *     mid -  a pointer to an int. If not NULL, the function will set this to
- *            the message id of this particular message. This can be then used
- *            with the unsubscribe callback to determine when the message has been
- *            sent.
- *     sub -  the unsubscription pattern.
+ *  mosq - a valid mosquitto instance.
+ *  mid -  a pointer to an int. If not NULL, the function will set this to
+ *         the message id of this particular message. This can be then used
+ *         with the unsubscribe callback to determine when the message has been
+ *         sent.
+ *  sub -  the unsubscription pattern.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
  */
 libmosq_EXPORT int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const char *sub);
 
@@ -653,29 +664,30 @@ libmosq_EXPORT int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const
  * Useful for preserving a message received in the on_message() callback.
  *
  * Parameters:
- *     dst - a pointer to a valid mosquitto_message struct to copy to.
- *     src - a pointer to a valid mosquitto_message struct to copy from.
+ *  dst - a pointer to a valid mosquitto_message struct to copy to.
+ *  src - a pointer to a valid mosquitto_message struct to copy from.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_message_free>
+ *  <mosquitto_message_free>
  */
-libmosq_EXPORT int mosquitto_message_copy(struct mosquitto_message *dst, const struct mosquitto_message *src);
+libmosq_EXPORT int mosquitto_message_copy(struct mosquitto_message *dst,
+        const struct mosquitto_message *src);
 
 /*
  * Function: mosquitto_message_free
- * 
+ *
  * Completely free a mosquitto_message struct.
  *
  * Parameters:
- *     message - pointer to a mosquitto_message pointer to free.
+ *  message - pointer to a mosquitto_message pointer to free.
  *
  * See Also:
- *     <mosquitto_message_copy>
+ *  <mosquitto_message_copy>
  */
 libmosq_EXPORT void mosquitto_message_free(struct mosquitto_message **message);
 
@@ -699,29 +711,29 @@ libmosq_EXPORT void mosquitto_message_free(struct mosquitto_message **message);
  * <mosquitto_loop_misc>.
  *
  * Threads:
- *     
+ *
  * Parameters:
- *     mosq -        a valid mosquitto instance.
- *     timeout -     Maximum number of milliseconds to wait for network activity
- *                   in the select() call before timing out. Set to 0 for instant
- *                   return.  Set negative to use the default of 1000ms.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
- * 
+ *  mosq -        a valid mosquitto instance.
+ *  timeout -     Maximum number of milliseconds to wait for network activity
+ *                in the select() call before timing out. Set to 0 for instant
+ *                return.  Set negative to use the default of 1000ms.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
+ *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  * See Also:
- *     <mosquitto_loop_forever>, <mosquitto_loop_start>, <mosquitto_loop_stop>
+ *  <mosquitto_loop_forever>, <mosquitto_loop_start>, <mosquitto_loop_stop>
  */
 libmosq_EXPORT int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_packets);
 
@@ -737,27 +749,27 @@ libmosq_EXPORT int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_p
  *
  * Parameters:
  *  mosq - a valid mosquitto instance.
- *     timeout -     Maximum number of milliseconds to wait for network activity
- *                   in the select() call before timing out. Set to 0 for instant
- *                   return.  Set negative to use the default of 1000ms.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
+ *  timeout -     Maximum number of milliseconds to wait for network activity
+ *                in the select() call before timing out. Set to 0 for instant
+ *                return.  Set negative to use the default of 1000ms.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  *
  * See Also:
- *     <mosquitto_loop>, <mosquitto_loop_start>
+ *  <mosquitto_loop>, <mosquitto_loop_start>
  */
 libmosq_EXPORT int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets);
 
@@ -772,12 +784,12 @@ libmosq_EXPORT int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, i
  *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -       on success.
- *     MOSQ_ERR_INVAL -         if the input parameters were invalid.
- *     MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
+ *  MOSQ_ERR_SUCCESS -       on success.
+ *  MOSQ_ERR_INVAL -         if the input parameters were invalid.
+ *  MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
  *
  * See Also:
- *     <mosquitto_connect_async>, <mosquitto_loop>, <mosquitto_loop_forever>, <mosquitto_loop_stop>
+ *  <mosquitto_connect_async>, <mosquitto_loop>, <mosquitto_loop_forever>, <mosquitto_loop_stop>
  */
 libmosq_EXPORT int mosquitto_loop_start(struct mosquitto *mosq);
 
@@ -792,16 +804,16 @@ libmosq_EXPORT int mosquitto_loop_start(struct mosquitto *mosq);
  *
  * Parameters:
  *  mosq - a valid mosquitto instance.
- *     force - set to true to force thread cancellation. If false,
- *             <mosquitto_disconnect> must have already been called.
+ *  force - set to true to force thread cancellation. If false,
+ *          <mosquitto_disconnect> must have already been called.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -       on success.
- *     MOSQ_ERR_INVAL -         if the input parameters were invalid.
- *     MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
+ *  MOSQ_ERR_SUCCESS -       on success.
+ *  MOSQ_ERR_INVAL -         if the input parameters were invalid.
+ *  MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
  *
  * See Also:
- *     <mosquitto_loop>, <mosquitto_loop_start>
+ *  <mosquitto_loop>, <mosquitto_loop_start>
  */
 libmosq_EXPORT int mosquitto_loop_stop(struct mosquitto *mosq, bool force);
 
@@ -812,10 +824,10 @@ libmosq_EXPORT int mosquitto_loop_stop(struct mosquitto *mosq, bool force);
  * include a mosquitto client in your own select() calls.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     The socket for the mosquitto client or -1 on failure.
+ *  The socket for the mosquitto client or -1 on failure.
  */
 libmosq_EXPORT int mosquitto_socket(struct mosquitto *mosq);
 
@@ -827,25 +839,25 @@ libmosq_EXPORT int mosquitto_socket(struct mosquitto *mosq);
  * monitoring the client network socket for activity yourself.
  *
  * Parameters:
- *     mosq -        a valid mosquitto instance.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
+ *  mosq -        a valid mosquitto instance.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_write>, <mosquitto_loop_misc>
+ *  <mosquitto_socket>, <mosquitto_loop_write>, <mosquitto_loop_misc>
  */
 libmosq_EXPORT int mosquitto_loop_read(struct mosquitto *mosq, int max_packets);
 
@@ -857,25 +869,25 @@ libmosq_EXPORT int mosquitto_loop_read(struct mosquitto *mosq, int max_packets);
  * monitoring the client network socket for activity yourself.
  *
  * Parameters:
- *     mosq -        a valid mosquitto instance.
- *     max_packets - this parameter is currently unused and should be set to 1 for
- *                   future compatibility.
+ *  mosq -        a valid mosquitto instance.
+ *  max_packets - this parameter is currently unused and should be set to 1 for
+ *                future compatibility.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -     if an out of memory condition occurred.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *  MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
- *     MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
+ *  MOSQ_ERR_PROTOCOL -  if there is a protocol error communicating with the
  *                       broker.
- *     MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
+ *  MOSQ_ERR_ERRNO -     if a system call returned an error. The variable errno
  *                       contains the error code, even on Windows.
  *                       Use strerror_r() where available or FormatMessage() on
  *                       Windows.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_misc>, <mosquitto_want_write>
+ *  <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_misc>, <mosquitto_want_write>
  */
 libmosq_EXPORT int mosquitto_loop_write(struct mosquitto *mosq, int max_packets);
 
@@ -890,15 +902,15 @@ libmosq_EXPORT int mosquitto_loop_write(struct mosquitto *mosq, int max_packets)
  * to be retried, so should be called fairly frequently.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS -   on success.
- *     MOSQ_ERR_INVAL -     if the input parameters were invalid.
- *     MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
+ *  MOSQ_ERR_SUCCESS -   on success.
+ *  MOSQ_ERR_INVAL -     if the input parameters were invalid.
+ *  MOSQ_ERR_NO_CONN -   if the client isn't connected to a broker.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
+ *  <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
  */
 libmosq_EXPORT int mosquitto_loop_misc(struct mosquitto *mosq);
 
@@ -908,10 +920,10 @@ libmosq_EXPORT int mosquitto_loop_misc(struct mosquitto *mosq);
  * Returns true if there is data ready to be written on the socket.
  *
  * Parameters:
- *     mosq - a valid mosquitto instance.
+ *  mosq - a valid mosquitto instance.
  *
  * See Also:
- *     <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
+ *  <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
  */
 libmosq_EXPORT bool mosquitto_want_write(struct mosquitto *mosq);
 
@@ -954,17 +966,17 @@ libmosq_EXPORT bool mosquitto_want_write(struct mosquitto *mosq);
  *                instance.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_tls_opts_set>, <mosquitto_tls_psk_set>, <mosquitto_tls_insecure_set>
+ *  <mosquitto_tls_opts_set>, <mosquitto_tls_psk_set>, <mosquitto_tls_insecure_set>
  */
 libmosq_EXPORT int mosquitto_tls_set(struct mosquitto *mosq,
-               const char *cafile, const char *capath,
-               const char *certfile, const char *keyfile,
-               int (*pw_callback)(char *buf, int size, int rwflag, void *userdata));
+                                     const char *cafile, const char *capath,
+                                     const char *certfile, const char *keyfile,
+                                     int (*pw_callback)(char *buf, int size, int rwflag, void *userdata));
 
 /*
  * Function: mosquitto_tls_insecure_set
@@ -985,11 +997,11 @@ libmosq_EXPORT int mosquitto_tls_set(struct mosquitto *mosq,
  *          the connection is insecure.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  *
  * See Also:
- *     <mosquitto_tls_set>
+ *  <mosquitto_tls_set>
  */
 libmosq_EXPORT int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value);
 
@@ -1000,32 +1012,33 @@ libmosq_EXPORT int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value
  *
  * Parameters:
  *  mosq -        a valid mosquitto instance.
- *     cert_reqs -   an integer defining the verification requirements the client
- *                   will impose on the server. This can be one of:
- *                   * SSL_VERIFY_NONE (0): the server will not be verified in any way.
- *                   * SSL_VERIFY_PEER (1): the server certificate will be verified
- *                     and the connection aborted if the verification fails.
- *                   The default and recommended value is SSL_VERIFY_PEER. Using
- *                   SSL_VERIFY_NONE provides no security.
- *     tls_version - the version of the SSL/TLS protocol to use as a string. If NULL,
- *                   the default value is used. The default value and the
- *                   available values depend on the version of openssl that the
- *                   library was compiled against. For openssl >= 1.0.1, the
- *                   available options are tlsv1.2, tlsv1.1 and tlsv1, with tlv1.2
- *                   as the default. For openssl < 1.0.1, only tlsv1 is available.
- *     ciphers -     a string describing the ciphers available for use. See the
- *                   "openssl ciphers" tool for more information. If NULL, the
- *                   default ciphers will be used.
+ *  cert_reqs -   an integer defining the verification requirements the client
+ *                will impose on the server. This can be one of:
+ *                * SSL_VERIFY_NONE (0): the server will not be verified in any way.
+ *                * SSL_VERIFY_PEER (1): the server certificate will be verified
+ *                  and the connection aborted if the verification fails.
+ *                The default and recommended value is SSL_VERIFY_PEER. Using
+ *                SSL_VERIFY_NONE provides no security.
+ *  tls_version - the version of the SSL/TLS protocol to use as a string. If NULL,
+ *                the default value is used. The default value and the
+ *                available values depend on the version of openssl that the
+ *                library was compiled against. For openssl >= 1.0.1, the
+ *                available options are tlsv1.2, tlsv1.1 and tlsv1, with tlv1.2
+ *                as the default. For openssl < 1.0.1, only tlsv1 is available.
+ *  ciphers -     a string describing the ciphers available for use. See the
+ *                "openssl ciphers" tool for more information. If NULL, the
+ *                default ciphers will be used.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_tls_set>
+ *  <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs, const char *tls_version, const char *ciphers);
+libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs,
+        const char *tls_version, const char *ciphers);
 
 /*
  * Function: mosquitto_tls_psk_set
@@ -1040,21 +1053,22 @@ libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs,
  *  psk -      the pre-shared-key in hex format with no leading "0x".
  *  identity - the identity of this client. May be used as the username
  *             depending on the server settings.
- *     ciphers -  a string describing the PSK ciphers available for use. See the
- *                "openssl ciphers" tool for more information. If NULL, the
- *                default ciphers will be used.
+ *  ciphers -  a string describing the PSK ciphers available for use. See the
+ *             "openssl ciphers" tool for more information. If NULL, the
+ *             default ciphers will be used.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * See Also:
- *     <mosquitto_tls_set>
+ *  <mosquitto_tls_set>
  */
-libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk, const char *identity, const char *ciphers);
+libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk,
+        const char *identity, const char *ciphers);
 
-/* 
+/*
  * Function: mosquitto_connect_callback_set
  *
  * Set the connect callback. This is called when the broker sends a CONNACK
@@ -1076,14 +1090,15 @@ libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk
  * * 3 - connection refused (broker unavailable)
  * * 4-255 - reserved for future use
  */
-libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq,
+        void (*on_connect)(struct mosquitto *, void *, int));
+
 /*
  * Function: mosquitto_disconnect_callback_set
  *
  * Set the disconnect callback. This is called when the broker has received the
  * DISCONNECT command and has disconnected the client.
- * 
+ *
  * Parameters:
  *  mosq -          a valid mosquitto instance.
  *  on_disconnect - a callback function in the following form:
@@ -1096,14 +1111,15 @@ libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, void
  *         means the client has called <mosquitto_disconnect>. Any other value
  *         indicates that the disconnect is unexpected.
  */
-libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq,
+        void (*on_disconnect)(struct mosquitto *, void *, int));
+
 /*
  * Function: mosquitto_publish_callback_set
  *
  * Set the publish callback. This is called when a message initiated with
  * <mosquitto_publish> has been sent to the broker successfully.
- * 
+ *
  * Parameters:
  *  mosq -       a valid mosquitto instance.
  *  on_publish - a callback function in the following form:
@@ -1114,14 +1130,15 @@ libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq, vo
  *  obj -  the user data provided in <mosquitto_new>
  *  mid -  the message id of the sent message.
  */
-libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq,
+        void (*on_publish)(struct mosquitto *, void *, int));
 
 /*
  * Function: mosquitto_message_callback_set
  *
  * Set the message callback. This is called when a message is received from the
  * broker.
- * 
+ *
  * Parameters:
  *  mosq -       a valid mosquitto instance.
  *  on_message - a callback function in the following form:
@@ -1135,16 +1152,17 @@ libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq, void
  *            should make copies of any of the data it requires.
  *
  * See Also:
- *     <mosquitto_message_copy>
+ *  <mosquitto_message_copy>
  */
-libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *));
+libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq,
+        void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *));
 
 /*
  * Function: mosquitto_subscribe_callback_set
  *
  * Set the subscribe callback. This is called when the broker responds to a
  * subscription request.
- * 
+ *
  * Parameters:
  *  mosq -         a valid mosquitto instance.
  *  on_subscribe - a callback function in the following form:
@@ -1158,14 +1176,15 @@ libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq, void
  *  granted_qos - an array of integers indicating the granted QoS for each of
  *                the subscriptions.
  */
-libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *));
+libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq,
+        void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *));
 
 /*
  * Function: mosquitto_unsubscribe_callback_set
  *
  * Set the unsubscribe callback. This is called when the broker responds to a
  * unsubscription request.
- * 
+ *
  * Parameters:
  *  mosq -           a valid mosquitto instance.
  *  on_unsubscribe - a callback function in the following form:
@@ -1176,7 +1195,8 @@ libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq, voi
  *  obj -  the user data provided in <mosquitto_new>
  *  mid -  the message id of the unsubscribe message.
  */
-libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int));
+libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq,
+        void (*on_unsubscribe)(struct mosquitto *, void *, int));
 
 /*
  * Function: mosquitto_log_callback_set
@@ -1192,14 +1212,15 @@ libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, v
  *  mosq -  the mosquitto instance making the callback.
  *  obj -   the user data provided in <mosquitto_new>
  *  level - the log message level from the values:
- *             MOSQ_LOG_INFO
- *             MOSQ_LOG_NOTICE
- *             MOSQ_LOG_WARNING
- *             MOSQ_LOG_ERR
- *             MOSQ_LOG_DEBUG
- *     str -   the message string.
+ *          MOSQ_LOG_INFO
+ *          MOSQ_LOG_NOTICE
+ *          MOSQ_LOG_WARNING
+ *          MOSQ_LOG_ERR
+ *          MOSQ_LOG_DEBUG
+ *  str -   the message string.
  */
-libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on_log)(struct mosquitto *, void *, int, const char *));
+libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq,
+        void (*on_log)(struct mosquitto *, void *, int, const char *));
 
 /*
  * Function: mosquitto_reconnect_delay_set
@@ -1215,12 +1236,12 @@ libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on
  * set an upper bound on the delay with reconnect_delay_max.
  *
  * Example 1:
- *     delay=2, delay_max=10, exponential_backoff=False
- *     Delays would be: 2, 4, 6, 8, 10, 10, ...
+ *  delay=2, delay_max=10, exponential_backoff=False
+ *  Delays would be: 2, 4, 6, 8, 10, 10, ...
  *
  * Example 2:
- *     delay=3, delay_max=30, exponential_backoff=True
- *     Delays would be: 3, 6, 12, 24, 30, 30, ...
+ *  delay=3, delay_max=30, exponential_backoff=True
+ *  Delays would be: 3, 6, 12, 24, 30, 30, ...
  *
  * Parameters:
  *  mosq -                          a valid mosquitto instance.
@@ -1233,10 +1254,11 @@ libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on
  *                                  exponential backoff.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  */
-libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff);
+libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq,
+        unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff);
 
 /*
  * Function: mosquitto_max_inflight_messages_set
@@ -1258,17 +1280,18 @@ libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigne
  *                          to 20.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success.
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success.
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  */
-libmosq_EXPORT int mosquitto_max_inflight_messages_set(struct mosquitto *mosq, unsigned int max_inflight_messages);
+libmosq_EXPORT int mosquitto_max_inflight_messages_set(struct mosquitto *mosq,
+        unsigned int max_inflight_messages);
 
 /*
  * Function: mosquitto_message_retry_set
  *
  * Set the number of seconds to wait before retrying messages. This applies to
  * publish messages with QoS>0. May be called at any time.
- * 
+ *
  * Parameters:
  *  mosq -          a valid mosquitto instance.
  *  message_retry - the number of seconds to wait for a response before
@@ -1287,8 +1310,8 @@ libmosq_EXPORT void mosquitto_message_retry_set(struct mosquitto *mosq, unsigned
  *
  * Parameters:
  *  mosq - a valid mosquitto instance.
- *     obj -  A user pointer that will be passed as an argument to any callbacks
- *            that are specified.
+ *  obj -  A user pointer that will be passed as an argument to any callbacks
+ *         that are specified.
  */
 libmosq_EXPORT void mosquitto_user_data_set(struct mosquitto *mosq, void *obj);
 
@@ -1306,10 +1329,10 @@ libmosq_EXPORT void mosquitto_user_data_set(struct mosquitto *mosq, void *obj);
  * Call to obtain a const string description of a mosquitto error number.
  *
  * Parameters:
- *     mosq_errno - a mosquitto error number.
+ *  mosq_errno - a mosquitto error number.
  *
  * Returns:
- *     A constant string describing the error.
+ *  A constant string describing the error.
  */
 libmosq_EXPORT const char *mosquitto_strerror(int mosq_errno);
 
@@ -1319,10 +1342,10 @@ libmosq_EXPORT const char *mosquitto_strerror(int mosq_errno);
  * Call to obtain a const string description of an MQTT connection result.
  *
  * Parameters:
- *     connack_code - an MQTT connection result.
+ *  connack_code - an MQTT connection result.
  *
  * Returns:
- *     A constant string describing the result.
+ *  A constant string describing the result.
  */
 libmosq_EXPORT const char *mosquitto_connack_string(int connack_code);
 
@@ -1356,20 +1379,20 @@ libmosq_EXPORT const char *mosquitto_connack_string(int connack_code);
  * topics[4] = "hierarchy"
  *
  * Parameters:
- *     subtopic - the subscription/topic to tokenise
- *     topics -   a pointer to store the array of strings
- *     count -    an int pointer to store the number of items in the topics array.
+ *  subtopic - the subscription/topic to tokenise
+ *  topics -   a pointer to store the array of strings
+ *  count -    an int pointer to store the number of items in the topics array.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  *
  * Example:
  *
  * > char **topics;
  * > int topic_count;
  * > int i;
- * > 
+ * >
  * > mosquitto_sub_topic_tokenise("$SYS/broker/uptime", &topics, &topic_count);
  * >
  * > for(i=0; i<token_count; i++){
@@ -1377,7 +1400,7 @@ libmosq_EXPORT const char *mosquitto_connack_string(int connack_code);
  * > }
  *
  * See Also:
- *     <mosquitto_sub_topic_tokens_free>
+ *  <mosquitto_sub_topic_tokens_free>
  */
 libmosq_EXPORT int mosquitto_sub_topic_tokenise(const char *subtopic, char ***topics, int *count);
 
@@ -1387,15 +1410,15 @@ libmosq_EXPORT int mosquitto_sub_topic_tokenise(const char *subtopic, char ***to
  * Free memory that was allocated in <mosquitto_sub_topic_tokenise>.
  *
  * Parameters:
- *     topics - pointer to string array.
- *     count - count of items in string array.
+ *  topics - pointer to string array.
+ *  count - count of items in string array.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_SUCCESS - on success
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
  *
  * See Also:
- *     <mosquitto_sub_topic_tokenise>
+ *  <mosquitto_sub_topic_tokenise>
  */
 libmosq_EXPORT int mosquitto_sub_topic_tokens_free(char ***topics, int count);
 
@@ -1410,15 +1433,15 @@ libmosq_EXPORT int mosquitto_sub_topic_tokens_free(char ***topics, int count);
  * non/matching would not match the subscription non/+/+
  *
  * Parameters:
- *     sub - subscription string to check topic against.
- *     topic - topic to check.
- *     result - bool pointer to hold result. Will be set to true if the topic
- *              matches the subscription.
+ *  sub - subscription string to check topic against.
+ *  topic - topic to check.
+ *  result - bool pointer to hold result. Will be set to true if the topic
+ *           matches the subscription.
  *
  * Returns:
- *     MOSQ_ERR_SUCCESS - on success
- *     MOSQ_ERR_INVAL -   if the input parameters were invalid.
- *     MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
+ *  MOSQ_ERR_SUCCESS - on success
+ *  MOSQ_ERR_INVAL -   if the input parameters were invalid.
+ *  MOSQ_ERR_NOMEM -   if an out of memory condition occurred.
  */
 libmosq_EXPORT int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result);
 
index f3d5fde..523b1d9 100644 (file)
@@ -52,16 +52,16 @@ POSSIBILITY OF SUCH DAMAGE.
 #endif
 
 #ifdef WIN32
-#      if _MSC_VER < 1600
-               typedef unsigned char uint8_t;
-               typedef unsigned short uint16_t;
-               typedef unsigned int uint32_t;
-               typedef unsigned long long uint64_t;
-#      else
-#              include <stdint.h>
-#      endif
+#   if _MSC_VER < 1600
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long uint64_t;
+#   else
+#       include <stdint.h>
+#   endif
 #else
-#      include <stdint.h>
+#   include <stdint.h>
 #endif
 
 #include "mosquitto.h"
@@ -70,172 +70,181 @@ POSSIBILITY OF SUCH DAMAGE.
 struct mosquitto_client_msg;
 #endif
 
-enum mosquitto_msg_direction {
-       mosq_md_in = 0,
-       mosq_md_out = 1
+enum mosquitto_msg_direction
+{
+    mosq_md_in = 0,
+    mosq_md_out = 1
 };
 
-enum mosquitto_msg_state {
-       mosq_ms_invalid = 0,
-       mosq_ms_publish_qos0 = 1,
-       mosq_ms_publish_qos1 = 2,
-       mosq_ms_wait_for_puback = 3,
-       mosq_ms_publish_qos2 = 4,
-       mosq_ms_wait_for_pubrec = 5,
-       mosq_ms_resend_pubrel = 6,
-       mosq_ms_wait_for_pubrel = 7,
-       mosq_ms_resend_pubcomp = 8,
-       mosq_ms_wait_for_pubcomp = 9,
-       mosq_ms_send_pubrec = 10,
-       mosq_ms_queued = 11
+enum mosquitto_msg_state
+{
+    mosq_ms_invalid = 0,
+    mosq_ms_publish_qos0 = 1,
+    mosq_ms_publish_qos1 = 2,
+    mosq_ms_wait_for_puback = 3,
+    mosq_ms_publish_qos2 = 4,
+    mosq_ms_wait_for_pubrec = 5,
+    mosq_ms_resend_pubrel = 6,
+    mosq_ms_wait_for_pubrel = 7,
+    mosq_ms_resend_pubcomp = 8,
+    mosq_ms_wait_for_pubcomp = 9,
+    mosq_ms_send_pubrec = 10,
+    mosq_ms_queued = 11
 };
 
-enum mosquitto_client_state {
-       mosq_cs_new = 0,
-       mosq_cs_connected = 1,
-       mosq_cs_disconnecting = 2,
-       mosq_cs_connect_async = 3,
-       mosq_cs_connect_pending = 4,
-       mosq_cs_connect_srv = 5
+enum mosquitto_client_state
+{
+    mosq_cs_new = 0,
+    mosq_cs_connected = 1,
+    mosq_cs_disconnecting = 2,
+    mosq_cs_connect_async = 3,
+    mosq_cs_connect_pending = 4,
+    mosq_cs_connect_srv = 5
 };
 
-enum _mosquitto_protocol {
-       mosq_p_invalid = 0,
-       mosq_p_mqtt31 = 1,
-       mosq_p_mqtt311 = 2,
-       mosq_p_mqtts = 3
+enum _mosquitto_protocol
+{
+    mosq_p_invalid = 0,
+    mosq_p_mqtt31 = 1,
+    mosq_p_mqtt311 = 2,
+    mosq_p_mqtts = 3
 };
 
-enum _mosquitto_transport {
-       mosq_t_invalid = 0,
-       mosq_t_tcp = 1,
-       mosq_t_ws = 2,
-       mosq_t_sctp = 3
+enum _mosquitto_transport
+{
+    mosq_t_invalid = 0,
+    mosq_t_tcp = 1,
+    mosq_t_ws = 2,
+    mosq_t_sctp = 3
 };
 
-struct _mosquitto_packet{
-       uint8_t command;
-       uint8_t have_remaining;
-       uint8_t remaining_count;
-       uint16_t mid;
-       uint32_t remaining_mult;
-       uint32_t remaining_length;
-       uint32_t packet_length;
-       uint32_t to_process;
-       uint32_t pos;
-       uint8_t *payload;
-       struct _mosquitto_packet *next;
+struct _mosquitto_packet
+{
+    uint8_t command;
+    uint8_t have_remaining;
+    uint8_t remaining_count;
+    uint16_t mid;
+    uint32_t remaining_mult;
+    uint32_t remaining_length;
+    uint32_t packet_length;
+    uint32_t to_process;
+    uint32_t pos;
+    uint8_t *payload;
+    struct _mosquitto_packet *next;
 };
 
-struct mosquitto_message_all{
-       struct mosquitto_message_all *next;
-       time_t timestamp;
-       //enum mosquitto_msg_direction direction;
-       enum mosquitto_msg_state state;
-       bool dup;
-       struct mosquitto_message msg;
+struct mosquitto_message_all
+{
+    struct mosquitto_message_all *next;
+    time_t timestamp;
+    //enum mosquitto_msg_direction direction;
+    enum mosquitto_msg_state state;
+    bool dup;
+    struct mosquitto_message msg;
 };
 
-struct mosquitto {
+struct mosquitto
+{
 #ifndef WIN32
-       int sock;
+    int sock;
 #  ifndef WITH_BROKER
-       int sockpairR, sockpairW;
+    int sockpairR, sockpairW;
 #  endif
 #else
-       SOCKET sock;
+    SOCKET sock;
 #  ifndef WITH_BROKER
-       SOCKET sockpairR, sockpairW;
+    SOCKET sockpairR, sockpairW;
 #  endif
 #endif
-       enum _mosquitto_protocol protocol;
-       char *address;
-       char *id;
-       char *username;
-       char *password;
-       uint16_t keepalive;
-       bool clean_session;
-       enum mosquitto_client_state state;
-       time_t last_msg_in;
-       time_t last_msg_out;
-       time_t ping_t;
-       uint16_t last_mid;
-       struct _mosquitto_packet in_packet;
-       struct _mosquitto_packet *current_out_packet;
-       struct _mosquitto_packet *out_packet;
-       struct mosquitto_message *will;
+    enum _mosquitto_protocol protocol;
+    char *address;
+    char *id;
+    char *username;
+    char *password;
+    uint16_t keepalive;
+    bool clean_session;
+    enum mosquitto_client_state state;
+    time_t last_msg_in;
+    time_t last_msg_out;
+    time_t ping_t;
+    uint16_t last_mid;
+    struct _mosquitto_packet in_packet;
+    struct _mosquitto_packet *current_out_packet;
+    struct _mosquitto_packet *out_packet;
+    struct mosquitto_message *will;
 #ifdef WITH_TLS
-       SSL *ssl;
-       SSL_CTX *ssl_ctx;
-       char *tls_cafile;
-       char *tls_capath;
-       char *tls_certfile;
-       char *tls_keyfile;
-       int (*tls_pw_callback)(char *buf, int size, int rwflag, void *userdata);
-       int tls_cert_reqs;
-       char *tls_version;
-       char *tls_ciphers;
-       char *tls_psk;
-       char *tls_psk_identity;
-       bool tls_insecure;
+    SSL *ssl;
+    SSL_CTX *ssl_ctx;
+    char *tls_cafile;
+    char *tls_capath;
+    char *tls_certfile;
+    char *tls_keyfile;
+    int (*tls_pw_callback)(char *buf, int size, int rwflag, void *userdata);
+    int tls_cert_reqs;
+    char *tls_version;
+    char *tls_ciphers;
+    char *tls_psk;
+    char *tls_psk_identity;
+    bool tls_insecure;
 #endif
-       bool want_write;
+    bool want_write;
 #if defined(WITH_THREADING) && !defined(WITH_BROKER)
-       pthread_mutex_t callback_mutex;
-       pthread_mutex_t log_callback_mutex;
-       pthread_mutex_t msgtime_mutex;
-       pthread_mutex_t out_packet_mutex;
-       pthread_mutex_t current_out_packet_mutex;
-       pthread_mutex_t state_mutex;
-       pthread_mutex_t in_message_mutex;
-       pthread_mutex_t out_message_mutex;
-       pthread_t thread_id;
+    pthread_mutex_t callback_mutex;
+    pthread_mutex_t log_callback_mutex;
+    pthread_mutex_t msgtime_mutex;
+    pthread_mutex_t out_packet_mutex;
+    pthread_mutex_t current_out_packet_mutex;
+    pthread_mutex_t state_mutex;
+    pthread_mutex_t in_message_mutex;
+    pthread_mutex_t out_message_mutex;
+    pthread_t thread_id;
 #endif
 #ifdef WITH_BROKER
-       bool is_bridge;
-       struct _mqtt3_bridge *bridge;
-       struct mosquitto_client_msg *msgs;
-       struct mosquitto_client_msg *last_msg;
-       int msg_count;
-       int msg_count12;
-       struct _mosquitto_acl_user *acl_list;
-       struct _mqtt3_listener *listener;
-       time_t disconnect_t;
-       int pollfd_index;
-       int db_index;
-       struct _mosquitto_packet *out_packet_last;
-       bool is_dropping;
+    bool is_bridge;
+    struct _mqtt3_bridge *bridge;
+    struct mosquitto_client_msg *msgs;
+    struct mosquitto_client_msg *last_msg;
+    int msg_count;
+    int msg_count12;
+    struct _mosquitto_acl_user *acl_list;
+    struct _mqtt3_listener *listener;
+    time_t disconnect_t;
+    int pollfd_index;
+    int db_index;
+    struct _mosquitto_packet *out_packet_last;
+    bool is_dropping;
 #else
-       void *userdata;
-       bool in_callback;
-       unsigned int message_retry;
-       time_t last_retry_check;
-       struct mosquitto_message_all *in_messages;
-       struct mosquitto_message_all *in_messages_last;
-       struct mosquitto_message_all *out_messages;
-       struct mosquitto_message_all *out_messages_last;
-       void (*on_connect)(struct mosquitto *, void *userdata, int rc);
-       void (*on_disconnect)(struct mosquitto *, void *userdata, int rc);
-       void (*on_publish)(struct mosquitto *, void *userdata, int mid);
-       void (*on_message)(struct mosquitto *, void *userdata, const struct mosquitto_message *message);
-       void (*on_subscribe)(struct mosquitto *, void *userdata, int mid, int qos_count, const int *granted_qos);
-       void (*on_unsubscribe)(struct mosquitto *, void *userdata, int mid);
-       void (*on_log)(struct mosquitto *, void *userdata, int level, const char *str);
-       //void (*on_error)();
-       char *host;
-       int port;
-       int in_queue_len;
-       int out_queue_len;
-       char *bind_address;
-       unsigned int reconnect_delay;
-       unsigned int reconnect_delay_max;
-       bool reconnect_exponential_backoff;
-       bool threaded;
-       struct _mosquitto_packet *out_packet_last;
-       int inflight_messages;
-       int max_inflight_messages;
+    void *userdata;
+    bool in_callback;
+    unsigned int message_retry;
+    time_t last_retry_check;
+    struct mosquitto_message_all *in_messages;
+    struct mosquitto_message_all *in_messages_last;
+    struct mosquitto_message_all *out_messages;
+    struct mosquitto_message_all *out_messages_last;
+    void (*on_connect)(struct mosquitto *, void *userdata, int rc);
+    void (*on_disconnect)(struct mosquitto *, void *userdata, int rc);
+    void (*on_publish)(struct mosquitto *, void *userdata, int mid);
+    void (*on_message)(struct mosquitto *, void *userdata, const struct mosquitto_message *message);
+    void (*on_subscribe)(struct mosquitto *, void *userdata, int mid, int qos_count,
+                         const int *granted_qos);
+    void (*on_unsubscribe)(struct mosquitto *, void *userdata, int mid);
+    void (*on_log)(struct mosquitto *, void *userdata, int level, const char *str);
+    //void (*on_error)();
+    char *host;
+    int port;
+    int in_queue_len;
+    int out_queue_len;
+    char *bind_address;
+    unsigned int reconnect_delay;
+    unsigned int reconnect_delay_max;
+    bool reconnect_exponential_backoff;
+    bool threaded;
+    struct _mosquitto_packet *out_packet_last;
+    int inflight_messages;
+    int max_inflight_messages;
 #  ifdef WITH_SRV
-       ares_channel achan;
+    ares_channel achan;
 #  endif
 #endif
 };
index 96f89a1..f8bd07f 100644 (file)
@@ -71,9 +71,11 @@ void _mosquitto_net_cleanup(void);
 
 void _mosquitto_packet_cleanup(struct _mosquitto_packet *packet);
 int _mosquitto_packet_queue(struct mosquitto *mosq, struct _mosquitto_packet *packet);
-int _mosquitto_socket_connect(struct mosquitto *mosq, const char *host, uint16_t port, const char *bind_address, bool blocking);
+int _mosquitto_socket_connect(struct mosquitto *mosq, const char *host, uint16_t port,
+                              const char *bind_address, bool blocking);
 int _mosquitto_socket_close(struct mosquitto *mosq);
-int _mosquitto_try_connect(const char *host, uint16_t port, int *sock, const char *bind_address, bool blocking);
+int _mosquitto_try_connect(const char *host, uint16_t port, int *sock, const char *bind_address,
+                           bool blocking);
 int _mosquitto_socket_nonblock(int sock);
 int _mosquitto_socketpair(int *sp1, int *sp2);
 
diff --git a/service/protocol-plugin/plugins/mqtt-light/lib/python/Makefile b/service/protocol-plugin/plugins/mqtt-light/lib/python/Makefile
deleted file mode 100644 (file)
index 2a54111..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-# Set DESTDIR if it isn't given
-DESTDIR?=/
-
-.PHONY : all clean install
-
-ifeq ($(WITH_PYTHON),yes)
-all : mosquitto.pyc
-else
-all :
-endif
-
-ifeq ($(WITH_PYTHON),yes)
-install : all
-       python ./setup.py install --prefix=${prefix} --root=${DESTDIR}
-else
-install :
-endif
-
-mosquitto.pyc : mosquitto.py
-       python ./setup.py build
-
-clean :
-       -rm -rf build mosquitto.pyc __pycache__
index 35e8544..c49a5c7 100644 (file)
@@ -32,8 +32,10 @@ POSSIBILITY OF SUCH DAMAGE.
 #include "mosquitto.h"
 
 int _mosquitto_send_simple_command(struct mosquitto *mosq, uint8_t command);
-int _mosquitto_send_command_with_mid(struct mosquitto *mosq, uint8_t command, uint16_t mid, bool dup);
-int _mosquitto_send_real_publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
+int _mosquitto_send_command_with_mid(struct mosquitto *mosq, uint8_t command, uint16_t mid,
+                                     bool dup);
+int _mosquitto_send_real_publish(struct mosquitto *mosq, uint16_t mid, const char *topic,
+                                 uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
 
 int _mosquitto_send_connect(struct mosquitto *mosq, uint16_t keepalive, bool clean_session);
 int _mosquitto_send_disconnect(struct mosquitto *mosq);
@@ -41,10 +43,12 @@ int _mosquitto_send_pingreq(struct mosquitto *mosq);
 int _mosquitto_send_pingresp(struct mosquitto *mosq);
 int _mosquitto_send_puback(struct mosquitto *mosq, uint16_t mid);
 int _mosquitto_send_pubcomp(struct mosquitto *mosq, uint16_t mid);
-int _mosquitto_send_publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
+int _mosquitto_send_publish(struct mosquitto *mosq, uint16_t mid, const char *topic,
+                            uint32_t payloadlen, const void *payload, int qos, bool retain, bool dup);
 int _mosquitto_send_pubrec(struct mosquitto *mosq, uint16_t mid);
 int _mosquitto_send_pubrel(struct mosquitto *mosq, uint16_t mid, bool dup);
-int _mosquitto_send_subscribe(struct mosquitto *mosq, int *mid, bool dup, const char *topic, uint8_t topic_qos);
+int _mosquitto_send_subscribe(struct mosquitto *mosq, int *mid, bool dup, const char *topic,
+                              uint8_t topic_qos);
 int _mosquitto_send_unsubscribe(struct mosquitto *mosq, int *mid, bool dup, const char *topic);
 
 #endif
index 61d0a79..8891c2e 100644 (file)
@@ -33,7 +33,8 @@ POSSIBILITY OF SUCH DAMAGE.
 #include "mosquitto.h"
 #include "mosquitto_internal.h"
 
-int _mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain);
+int _mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen,
+                        const void *payload, int qos, bool retain);
 int _mosquitto_will_clear(struct mosquitto *mosq);
 
 #endif
index 9f30718..bc77110 100644 (file)
@@ -73,7 +73,7 @@ struct plugin_data_t
     bool flag;
 };
 
-
+struct mosquitto *myMosquitto;
 class LightResource
 {
     public:
@@ -176,6 +176,14 @@ class LightResource
                 if (rep.getValue("power", m_power))
                 {
                     cout << "\t\t\t\t" << "power: " << m_power << endl;
+                    if (m_power == 1)
+                    {
+                        mosquitto_publish(myMosquitto, NULL, "actuators/fan", 32, "onfan", 0, true);
+                    }
+                    else
+                    {
+                        mosquitto_publish(myMosquitto, NULL, "actuators/fan", 32, "offfan", 0, true);
+                    }
                 }
                 else
                 {
@@ -260,12 +268,6 @@ class LightResource
                 std::string requestType = request->getRequestType();
                 int requestFlag = request->getRequestHandlerFlag();
 
-                if (requestFlag & RequestHandlerFlag::InitFlag)
-                {
-                    cout << "\t\trequestFlag : Init\n";
-
-                    // entity handler to perform resource initialization operations
-                }
                 if (requestFlag & RequestHandlerFlag::RequestFlag)
                 {
                     cout << "\t\trequestFlag : Request ===  Handle by FanServer\n";
@@ -384,7 +386,6 @@ class LightResource
 };
 
 // Create the instance of the resource class (in this case instance of class 'LightResource').
-struct mosquitto *myMosquitto;
 
 // ChangeLightRepresentaion is an observation function,
 // which notifies any changes to the resource to stack
index 413dd94..cd8deaa 100644 (file)
@@ -1,10 +1,11 @@
 ##
 #sample-app build script
 ##
+import platform
 
 Import('env')
 
 target_os = env.get('TARGET_OS')
 
 if target_os == 'linux':
-       SConscript('linux/SConscript')
+    SConscript('linux/SConscript')
index 2e6b311..5c35aa1 100644 (file)
@@ -1,7 +1,25 @@
+#******************************************************************
+#
+# 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
 ##
-
 Import('env')
 
 # Add third party libraries
@@ -16,16 +34,28 @@ target_os = env.get('TARGET_OS')
 sample_env.AppendUnique(CPPPATH = [
                                '../../plugin-manager/src/',
                                '../../lib/cpluff/libcpluff/',
-                               '../../lib/rapidxml'])
+                               env.get('SRC_DIR') + '/extlibs/rapidxml/'])
+
 if target_os not in ['windows', 'winrt']:
        sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-pthread', '-std=c++0x'])
 
+sample_env.AppendUnique(LIBS = ['oc', 'oc_logger', 'octbstack',
+                                'connectivity_abstraction', 'coap',
+                                'ppm', 'pmimpl', 'dl'])
+
+if env.get('SECURED') == '1':
+    sample_env.AppendUnique(LIBS = ['tinydtls'])
+
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in sample_env.get('LIBS'):
+    sample_env.Append(LIBS = ['rt'])
+
 sample_env.AppendUnique(LIBS = ['pthread'])
-sample_env.AppendUnique(LIBS = ['oc', 'oc_logger', 'octbstack', 'coap', 'ppm', 'pmimpl', 'dl'])
 ######################################################################
 # Source files and Targets
 ######################################################################
 mqttclient = sample_env.Program('mqtt/mqttclient', 'mqtt/mqttclient.cpp')
 
 Alias('mqttclient', mqttclient)
-env.AppendTarget('mqttclient')
\ No newline at end of file
+env.AppendTarget('mqttclient')
diff --git a/service/protocol-plugin/sample-app/linux/mqtt/Makefile b/service/protocol-plugin/sample-app/linux/mqtt/Makefile
deleted file mode 100644 (file)
index 131e83a..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-CXX = g++
-
-CXX_FLAGS = -std=c++0x -Wall -pthread
-
-TOP_DIR = ../../../../..
-LIB_DIR = ../../../../../resource
-
-DEPEND_DIR:= $(LIB_DIR)/dependencies
-CEREAL_DIR:= $(DEPEND_DIR)/cereal
-
-CXX_INC := -I$(LIB_DIR)/include/ 
-CXX_INC += -I$(LIB_DIR)/oc_logger/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/stack/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/ocsocket/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/ocrandom/include/ 
-CXX_INC += -I$(LIB_DIR)/csdk/logger/include/
-CXX_INC += -I$(BOOST_DIR) 
-CXX_INC += -I../../lib
-CXX_INC += -I../../../lib/cpluff/libcpluff
-CXX_INC += -I../../../plugin-manager/src
-CXX_INC   += -I$(CEREAL_DIR)/include
-CXX_INC += -I../../../lib/rapidxml 
-
-LIB_OC_LOGGER := $(LIB_DIR)/oc_logger/lib/oc_logger.a
-CXX_LIBS  := ../../../build/linux/release/libppm.a ../../../lib/cpluff/libcpluff/.libs/libcpluff.a
-LINK_LIB = -lboost_system -ldl -lexpat -lboost_thread -L$(TOP_DIR)/out/linux/x86/release -loc -loctbstack -loc_logger -lcoap
-
-.PHONY: mqttclient
-
-all: .PHONY
-
-mqttclient: mqttclient.o
-       $(CXX) $(CXX_FLAGS) -o mqttclient mqttclient.o $(CXX_LIBS) $(LINK_LIB)
-
-mqttclient.o: mqttclient.cpp
-       $(CXX) $(CXX_FLAGS) -c mqttclient.cpp $(CXX_INC)
-
-       
-clean:
-       rm -f *.o
-       rm -f *.so
-       rm -f mqttclient
index 59ec85d..065b2d4 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+/// @file mqttclient.cpp
+
+/// @brief Samplecode which controls MQTT-fan plugin using Protocol Plugin Manager. 
 
-// OCClient.cpp : Defines the entry point for the console application.
-//
 #include <string>
 #include <cstdlib>
 #include <pthread.h>
 #include "OCPlatform.h"
 #include "PluginManager.h"
 #include "OCApi.h"
-#include <time.h>
 
 using namespace OC;
 using namespace OIC;
 
+const int SUCCESS_RESPONSE = 0;
 std::shared_ptr<OCResource> curFanResource;
-std::shared_ptr<OCResource> curLightResource;
 static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-
-time_t timer;                // Define the timer
-struct tm *tblock;           // Define a structure for time block
+int count = 0;
+void putFanRepresentation(std::shared_ptr<OCResource> resource);
 
 class Fan
 {
@@ -54,21 +53,6 @@ class Fan
 
 Fan myfan;
 
-class Light
-{
-    public:
-
-        bool m_state;
-        int m_power;
-        std::string m_name;
-
-        Light() : m_state(false), m_power(0), m_name("")
-        {
-        }
-};
-
-Light mylight;
-
 int observe_count()
 {
     static int oc = 0;
@@ -81,7 +65,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 +116,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);
 
@@ -222,7 +206,7 @@ void onPut(const HeaderOptions &headerOptions, const OCRepresentation &rep, cons
         std::cout << "\tpower: " << myfan.m_power << std::endl;
         std::cout << "\tname: " << myfan.m_name << std::endl;
 
-        postFanRepresentation(curFanResource);
+        putFanRepresentation(curFanResource);
     }
     else
     {
@@ -241,8 +225,11 @@ void putFanRepresentation(std::shared_ptr<OCResource> resource)
         std::cout << "Putting fan representation..." << std::endl;
 
         myfan.m_state = true;
-        myfan.m_power = 15;
-
+        if (myfan.m_power == 1)
+            myfan.m_power = 0;
+        else
+            myfan.m_power = 1;
+        sleep(5);
         rep.setValue("state", myfan.m_state);
         rep.setValue("power", myfan.m_power);
 
@@ -276,28 +263,6 @@ void onFanGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, c
     }
 }
 
-void onLightGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
-{
-    if (eCode == OC_STACK_OK)
-    {
-        std::cout << "GET Light request was successful" << std::endl;
-        std::cout << "Resource URI: " << rep.getUri() << std::endl;
-
-        rep.getValue("state", mylight.m_state);
-        rep.getValue("power", mylight.m_power);
-        rep.getValue("name", mylight.m_name);
-
-        std::cout << "\tstate: " << mylight.m_state << std::endl;
-        std::cout << "\tpower: " << mylight.m_power << std::endl;
-        std::cout << "\tname: " << mylight.m_name << std::endl; 
-    }
-    else
-    {
-        std::cout << "onGET Response error: " << eCode << std::endl;
-        std::exit(-1);
-    }
-}
-
 
 // Local function to get representation of fan resource
 void getFanRepresentation(std::shared_ptr<OCResource> resource)
@@ -312,18 +277,6 @@ void getFanRepresentation(std::shared_ptr<OCResource> resource)
     }
 }
 
-void getLightRepresentation(std::shared_ptr<OCResource> resource)
-{
-    if (resource)
-    {
-        std::cout << "Getting Light Representation..." << std::endl;
-        // Invoke resource's get API with the callback parameter
-
-        QueryParamsMap test;
-        resource->get(test, &onLightGet);
-    }
-}
-
 // Callback to found resources
 void foundResourceFan(std::shared_ptr<OCResource> resource)
 {
@@ -366,7 +319,7 @@ void foundResourceFan(std::shared_ptr<OCResource> resource)
             {
                 curFanResource = resource;
                 // Call a local function which will internally invoke get API on the resource pointer
-                getFanRepresentation(resource);
+                putFanRepresentation(curFanResource);
             }
         }
         else
@@ -378,65 +331,7 @@ void foundResourceFan(std::shared_ptr<OCResource> resource)
     }
     catch (std::exception &e)
     {
-        //log(e.what());
-    }
-}
-
-// Callback to found resources
-void foundResourceLight(std::shared_ptr<OCResource> resource)
-{
-    if (curLightResource)
-    {
-        std::cout << "Found another resource, ignoring" << std::endl;
-    }
-
-    std::string resourceURI;
-    std::string hostAddress;
-    try
-    {
-        // Do some operations with resource object.
-        if (resource)
-        {
-            std::cout << "DISCOVERED Resource:" << std::endl;
-            // Get the resource URI
-            resourceURI = resource->uri();
-            std::cout << "\tURI of the resource: " << resourceURI << std::endl;
-
-            // Get the resource host address
-            hostAddress = resource->host();
-            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
-
-            // Get the resource types
-            std::cout << "\tList of resource types: " << std::endl;
-            for (auto &resourceTypes : resource->getResourceTypes())
-            {
-                std::cout << "\t\t" << resourceTypes << std::endl;
-            }
-
-            // Get the resource interfaces
-            std::cout << "\tList of resource interfaces: " << std::endl;
-            for (auto &resourceInterfaces : resource->getResourceInterfaces())
-            {
-                std::cout << "\t\t" << resourceInterfaces << std::endl;
-            }
-
-            if (resourceURI == "/a/light")
-            {
-                curLightResource = resource;
-                // Call a local function which will internally invoke get API on the resource pointer
-                getLightRepresentation(resource);
-            }
-        }
-        else
-        {
-            // Resource is invalid
-            std::cout << "Resource is invalid" << std::endl;
-        }
-
-    }
-    catch (std::exception &e)
-    {
-        //log(e.what());
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 }
 
@@ -448,54 +343,6 @@ void PrintUsage()
     std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
 }
 
-void client1()
-{
-    std::cout << "in client1\n";
-
-    // OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.foo",
-    //                                 foundResource1);
-    std::cout << "starting findResource = core.fan" << std::endl;
-    // Find all resources
-    OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.fan", &foundResourceFan);
-    // Get time of day
-    timer = time(NULL);
-    // Converts date/time to a structure
-    tblock = localtime(&timer);
-    std::cout << "Finding Fan Resource... time : " << asctime(tblock) << std::endl;
-    while (1)
-    {
-        std::cout << "Get Fan Resource....." << std::endl;
-        sleep(5);
-        getFanRepresentation(curFanResource);
-    }
-}
-
-void client2()
-{
-    std::cout << "in client2\n";
-
-    // OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.foo",
-    //             foundResource2);
-
-    std::cout << "starting findResource = core.light" << std::endl;
-    // Find all resources
-    OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResourceLight);
-    // Get time of day
-    timer = time(NULL);
-    // Converts date/time to a structure
-    tblock = localtime(&timer);
-    std::cout << "Finding Light Resource... time : " << asctime(tblock) << std::endl;
-
-
-
-    while (1)
-    {
-        std::cout << "Get Light Resource....." << std::endl;
-        sleep(5);
-        getLightRepresentation(curLightResource);
-    }
-}
-
 
 
 int main(int argc, char *argv[])
@@ -504,6 +351,7 @@ int main(int argc, char *argv[])
     std::string key = "Name";
     std::string  state = "";
     std::string  id = "";
+    std::ostringstream requestURI;
 
     if (argc == 1)
     {
@@ -539,86 +387,16 @@ int main(int argc, char *argv[])
 
     try
     {
-
-        std::cout << "Created Platform..." << std::endl;
-
         PluginManager *m_pm = new PluginManager();
-
-        std::cout << "==== 1st TEST CASE ===" << std::endl;
-        std::cout << "======================" << std::endl;
         std::cout << "start light Plugin by Resource Type"  << std::endl;
-
-        m_pm->startPlugins("ResourceType", "oic.light");
-
+        m_pm->startPlugins("ResourceType", "oic.fan");
         sleep(2);
-
-        std::cout << "\n==== 2nd TEST CASE =====" << std::endl;
-        std::cout << "======================" << std::endl;
-        std::cout << "Get Plugin List\n" << std::endl;
-        std::vector<Plugin> user_plugin;
-
-        user_plugin = m_pm->getPlugins();
-
-        for (unsigned int i = 0; i < user_plugin.size(); i++)
-        {
-            std::cout << "value Name = " << user_plugin[i].getName() << std::endl;
-            std::cout << "value ID = " << user_plugin[i].getID() << std::endl;
-            id =  user_plugin[i].getID();
-        }
-        std::cout << "\n===== 3rd TEST CASE =====" << std::endl;
-        std::cout << "======================" << std::endl;
-        std::cout << "Start Fan Plugin by Name\n" << std::endl;
-
-        name = user_plugin[0].getName();
-        m_pm->startPlugins(key, name);
-
-        sleep(5);
-
-        std::cout << "\n====== 4th TEST CASE ======" << std::endl;
-        std::cout << "========================" << std::endl;
-        std::cout << "Get Plugin Status\n" << std::endl;
-
-        state = m_pm->getState(id);
-
-        std::cout << "last plugin status :  " << state << std::endl;
-        std::cout << "sleep 15 seconds please add new plugin in the plugin folder  " << std::endl;
-
-        sleep(15);
-
-        std::cout << "\n====  5th TEST CASE  ====" << std::endl;
-        std::cout << "========================" << std::endl;
-        std::cout << "Rescan Plugins.........\n" << std::endl;
-
-        m_pm->rescanPlugin();
-
-        std::cout << "\n====  6th TEST CASE  ====" << std::endl;
-        std::cout << "========================" << std::endl;
-        std::cout << "Try to start new resource type.........\n" << std::endl;
-        std::cout << "start oic.test resource" <<  std::endl;
-
-        sleep(5);
-
-        int flag = m_pm->startPlugins("ResourceType", "oic.test");
-
-        if (!flag)
-            std::cout << "There are no resouce type. Start plugin failed" << std::endl;
-        // Start each client in a seperate thread
-
-        sleep(10);
-
-        std::cout << "\n====== 7th TEST CASE =======" << std::endl;
-        std::cout << "========================" << std::endl;
-        std::cout << " start client to find resource" << std::endl;
-
-        std::thread t1(client1);
-        t1.detach();
-
-        sleep(5);
-
-        // Start each client in a seperate thread
-        std::thread t2(client2);
-        t2.detach();
-
+        // makes it so that all boolean values are printed as 'true/false' in this stream
+        std::cout.setf(std::ios::boolalpha);
+        // Find all resources
+        requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.fan";
+        OCPlatform::findResource("", requestURI.str(), OC_ALL, &foundResourceFan);
+        std::cout << "Finding Resource... " << std::endl;
         while (true)
         {
             // some operations
@@ -627,9 +405,8 @@ int main(int argc, char *argv[])
     }
     catch (OCException &e)
     {
-        //log(e.what());
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 
     return 0;
 }
-
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/.cproject b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/.cproject
new file mode 100644 (file)
index 0000000..9f8ba20
--- /dev/null
@@ -0,0 +1,526 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+    <storageModule moduleId="org.eclipse.cdt.core.settings">
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="ppmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.1732789683" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.784108973" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder arguments="--eval=&quot;SHELL=cmd&quot; -r" autoBuildTarget="all" buildPath="${workspace_loc:/ConServerApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.991141288" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.498617409" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.847181660" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.1877648524" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.30268440" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.39285929" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1365166625" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.195721954" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.2031608880" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                    <listOptionValue builtIn="false" value="../../../../plugin-manager/src/"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/csdk/stack/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/csdk/ocstack/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/csdk/ocsocket/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/oc_logger/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../lib/cpluff/libcpluff/"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../extlibs/rapidxml"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.2019722103" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.preprocessor.def.1628062174" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.1552197767" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+                                <option id="gnu.cpp.compiler.option.other.other.1077700307" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=gnu++0x" valueType="string"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.546425854" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.1904769633" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1301963388" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.1501054876" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.5248569" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.916623032" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1523138456" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.295281858" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.1144492600" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.preprocessor.def.symbols.1496533463" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.misc.other.1752913740" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=gnu++0x" valueType="string"/>
+                                <option id="gnu.c.compiler.option.dialect.std.1829487212" name="Language standard" superClass="gnu.c.compiler.option.dialect.std" value="gnu.c.compiler.dialect.default" valueType="enumerated"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.183281612" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1326307127" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1156278367" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.387163191" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.1160023692" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.libs.1981950125" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+                                    <listOptionValue builtIn="false" value="ppm"/>
+                                    <listOptionValue builtIn="false" value="oc"/>
+                                    <listOptionValue builtIn="false" value="octbstack"/>
+                                    <listOptionValue builtIn="false" value="oc_logger"/>
+                                    <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+                                    <listOptionValue builtIn="false" value="coap"/>
+                                    <listOptionValue builtIn="false" value="boost_system"/>
+                                    <listOptionValue builtIn="false" value="boost_thread"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.linker.option.shared_flag.core.1600357455" name="Linker.Shared" superClass="sbi.gnu.cpp.linker.option.shared_flag.core" value="true" valueType="boolean"/>
+                                <option id="gnu.cpp.link.option.other.1278390791" name="Other options (-Xlinker [option])" superClass="gnu.cpp.link.option.other"/>
+                                <option id="gnu.cpp.link.option.userobjs.337011879" name="Other objects" superClass="gnu.cpp.link.option.userobjs"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1548223100" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                                <outputType id="cdt.managedbuild.tool.gnu.cpp.linker.output.so.1567998933" outputPrefix="" superClass="cdt.managedbuild.tool.gnu.cpp.linker.output.so"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1801679035" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1012512773" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.719506497" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.1591459501" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.483946980" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.539557992" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1541244945" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1328146458" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227" moduleId="org.eclipse.cdt.core.settings" name="Release">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="ppmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.1806554459" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1882260991" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder buildPath="${workspace_loc:/ConServerApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.1480786483" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.101665077" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.906486264" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.325943992" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.819826799" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.cpp.compiler.option.1888932227" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.911460631" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.740263234" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.1207714584" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                    <listOptionValue builtIn="false" value="../../../../plugin-manager/src/"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/csdk/stack/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/csdk/ocstack/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/csdk/ocsocket/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../../../resource/oc_logger/include"/>
+                                    <listOptionValue builtIn="false" value="../../../../lib/cpluff/libcpluff/"/>
+                                    <listOptionValue builtIn="false" value="../../../../lib/rapidxml"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1142433860" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.other.other.1926478158" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=gnu++0x" valueType="string"/>
+                                <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.1349150475" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1397777277" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.1731044300" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.225459286" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.291907753" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.c.compiler.option.1322971988" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1895593459" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.2053809161" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.2104973765" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.1764818276" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.dialect.std.962515331" name="Language standard" superClass="gnu.c.compiler.option.dialect.std" value="gnu.c.compiler.dialect.default" valueType="enumerated"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1553289120" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1602883613" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1501052901" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.561516003" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.973160572" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.libs.904205149" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+                                    <listOptionValue builtIn="false" value="ppm"/>
+                                    <listOptionValue builtIn="false" value="oc"/>
+                                    <listOptionValue builtIn="false" value="octbstack"/>
+                                    <listOptionValue builtIn="false" value="coap"/>
+                                    <listOptionValue builtIn="false" value="oc_logger"/>
+                                    <listOptionValue builtIn="false" value="oc_logger_core"/>
+                                    <listOptionValue builtIn="false" value="boost_system"/>
+                                    <listOptionValue builtIn="false" value="boost_thread"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.linker.option.shared_flag.core.870017078" name="Linker.Shared" superClass="sbi.gnu.cpp.linker.option.shared_flag.core" value="true" valueType="boolean"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.204670616" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1928734833" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.326189069" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.1298411328" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.891775659" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.706788156" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.2024368653" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.188711953" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.601836947" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+    </storageModule>
+    <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+        <project id="ConServerApp.org.tizen.nativecore.target.sbi.gcc45.app.2088063880" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+    </storageModule>
+    <storageModule moduleId="scannerConfiguration">
+        <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+    </storageModule>
+    <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+    <storageModule moduleId="refreshScope"/>
+    <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+</cproject>
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/.exportMap b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/.exportMap
new file mode 100644 (file)
index 0000000..43e310e
--- /dev/null
@@ -0,0 +1,4 @@
+{
+       global: main;
+       local: *;
+};
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/.project b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/.project
new file mode 100644 (file)
index 0000000..f0417e1
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>PPMSampleApp</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+            <triggers>full,incremental,</triggers>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.tizen.nativecore.apichecker.core.builder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.cdt.core.cnature</nature>
+        <nature>org.eclipse.cdt.core.ccnature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+        <nature>org.tizen.nativecore.apichecker.core.tizenCppNature</nature>
+    </natures>
+    <filteredResources>
+        <filter>
+            <id>0</id>
+            <name></name>
+            <type>26</type>
+            <matcher>
+                <id>org.eclipse.ui.ide.multiFilter</id>
+                <arguments>1.0-projectRelativePath-matches-false-false-*/.tpk</arguments>
+            </matcher>
+        </filter>
+    </filteredResources>
+</projectDescription>
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/inc/ppmsampleapp.h b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/inc/ppmsampleapp.h
new file mode 100644 (file)
index 0000000..5e862af
--- /dev/null
@@ -0,0 +1,39 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef __PPMTESTERAPP_H__
+#define __PPMTESTERAPP_H__
+
+#include <app.h>
+#include <dlog.h>
+#include <efl-extension/efl_extension.h>
+#include <Elementary.h>
+#include <system_settings.h>
+
+#ifdef  LOG_TAG
+#undef  LOG_TAG
+#endif
+#define LOG_TAG "ppmtesterapp"
+
+#if !defined(PACKAGE)
+#define PACKAGE "org.iotivity.service.ppm.ppmtesterapp"
+#endif
+
+#endif // __PPMTESTERAPP_H__
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/pluginmanager.xml b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/pluginmanager.xml
new file mode 100644 (file)
index 0000000..b69e7f4
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<pluginManager>
+    <pluginInfo        
+        pluginPath="/opt/usr/apps/org.iotivity.service.ppm.ppmsampleapp/lib/plugins"        
+        maxMEM="64M"
+        maxPlugin=""
+        version="1.0"
+        name="pluginmanager">
+    </pluginInfo>
+    <specailpluginInfo>
+    </specailpluginInfo>
+</pluginManager>
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/plugins/mqtt-fan/plugin.xml b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/plugins/mqtt-fan/plugin.xml
new file mode 100644 (file)
index 0000000..2ce900e
--- /dev/null
@@ -0,0 +1,7 @@
+<plugin id="oic.plugin.mqtt-fan" 
+  version="0.1"
+  name="mqtt-fan"
+  url="fan"
+  resourcetype="oic.fan">
+       <runtime library="fanserver_mqtt_plugin" funcs="mqtt_plugin_fanserver_funcs"/>
+</plugin>
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/plugins/mqtt-light/plugin.xml b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/lib/plugins/mqtt-light/plugin.xml
new file mode 100644 (file)
index 0000000..15ea179
--- /dev/null
@@ -0,0 +1,7 @@
+<plugin id="oic.plugin.mqtt-light" 
+  version="0.1"
+  name="mqtt-light"
+  url="light"
+  resourcetype="oic.light">
+       <runtime library="lightserver_mqtt_plugin" funcs="mqtt_plugin_lightserver_funcs"/>
+</plugin>
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/shared/res/sampleapp.png b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/shared/res/sampleapp.png
new file mode 100644 (file)
index 0000000..9765b1b
Binary files /dev/null and b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/shared/res/sampleapp.png differ
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/src/ppmsampleapp.cpp b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/src/ppmsampleapp.cpp
new file mode 100644 (file)
index 0000000..54f9b03
--- /dev/null
@@ -0,0 +1,768 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "ppmsampleapp.h"
+
+#include <tizen.h>
+#include <wifi.h>
+#include <algorithm>
+#include "string.h"
+#include <time.h>
+#include <pthread.h>
+
+#include "PluginManager.h"
+#include "OCPlatform.h"
+#include "PluginManager.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace OIC;
+
+class Fan
+{
+    public:
+
+        bool m_state;
+        int m_power;
+        std::string m_name;
+
+        Fan() : m_state(false), m_power(0), m_name("")
+        {
+        }
+};
+
+typedef struct appdata
+{
+    Evas_Object *win;
+    Evas_Object *conform;
+    Evas_Object *naviframe;
+    Evas_Object *box;
+
+    Evas_Object *log;
+
+    Evas_Object *send_msg_button;
+    Evas_Object *clear_log_button;
+} appdata_s;
+
+typedef struct threadContext
+{
+    appdata_s *ad;
+    const char *log;
+} threadContext_s;
+
+threadContext_s m_ThreadContext;
+bool isSendMessage = true;
+const int SUCCESS_RESPONSE = 0;
+std::shared_ptr<OCResource> curFanResource;
+static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+int count = 0;
+Fan myfan;
+char log_buffer[10000];
+PluginManager *m_pm = NULL;
+char temp_string[2000];
+char buf[100];
+
+void putFanRepresentation(std::shared_ptr<OCResource> resource);
+
+void updateLog(appdata_s *ad, const char *newlog)
+{
+    const char *log_text = NULL;
+
+    log_text = elm_entry_entry_get(ad->log);
+    strcpy(log_buffer, log_text);
+    strcat(log_buffer, newlog);
+    elm_entry_entry_set(ad->log, log_buffer);
+    elm_entry_cursor_end_set(ad->log);
+}
+
+void *updateCallbackLog(void *data)
+{
+    threadContext_s  *pThreadContext = (threadContext_s *)data;
+    updateLog(pThreadContext->ad, pThreadContext->log);
+    return NULL;
+}
+
+
+int observe_count()
+{
+    static int oc = 0;
+    return ++oc;
+}
+
+void onObserve(const HeaderOptions headerOptions, const OCRepresentation &rep,
+               const int &eCode, const int &sequenceNumber)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        std::cout << "OBSERVE RESULT:" << std::endl;
+        std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
+
+        rep.getValue("state", myfan.m_state);
+        rep.getValue("power", myfan.m_power);
+        rep.getValue("name", myfan.m_name);
+
+        sprintf(buf, "OBSERVE RESULT: sequence number = %d<br>", sequenceNumber);
+        strcpy(temp_string, buf);
+        sprintf(buf, "state: = %d<br>", myfan.m_state);
+        strcat(temp_string, buf);
+        sprintf(buf, "power: = %d<br>", myfan.m_power);
+        strcat(temp_string, buf);
+        sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
+        strcat(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+
+        if (observe_count() > 30)
+        {
+            std::cout << "Cancelling Observe..." << std::endl;
+            OCStackResult result = curFanResource->cancelObserve();
+
+            std::cout << "Cancel result: " << result << std::endl;
+            sleep(10);
+            std::cout << "DONE" << std::endl;
+            std::exit(0);
+        }
+    }
+    else
+    {
+        std::cout << "onObserve Response error: " << eCode << std::endl;
+        sprintf(buf, "onObserve Response error:  = %d<br>", eCode);
+        strcpy(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+        std::exit(-1);
+    }
+}
+
+void onPost2(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
+    {
+        std::cout << "POST request was successful" << std::endl;
+
+        if (rep.hasAttribute("createduri"))
+        {
+            std::cout << "\tUri of the created resource: "
+                      << rep.getValue<std::string>("createduri") << std::endl;
+        }
+        else
+        {
+            rep.getValue("state", myfan.m_state);
+            rep.getValue("power", myfan.m_power);
+            rep.getValue("name", myfan.m_name);
+
+            std::cout << "\tstate: " << myfan.m_state << std::endl;
+            std::cout << "\tpower: " << myfan.m_power << std::endl;
+            std::cout << "\tname: " << myfan.m_name << std::endl;
+
+            strcpy(temp_string, "POST2 request was successful<br>");
+            sprintf(buf, "state: = %d<br>", myfan.m_state);
+            strcat(temp_string, buf);
+            sprintf(buf, "power: = %d<br>", myfan.m_power);
+            strcat(temp_string, buf);
+            sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
+            strcat(temp_string, buf);
+            m_ThreadContext.log = temp_string;
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                                  &m_ThreadContext);
+        }
+
+        if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
+            std::cout << std::endl << "Observe is used." << std::endl;
+        else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
+            std::cout << std::endl << "ObserveAll is used." << std::endl;
+
+        // curFanResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
+
+    }
+    else
+    {
+        std::cout << "onPost Response error: " << eCode << std::endl;
+        sprintf(buf, "onPost Response error:  = %d<br>", eCode);
+        strcpy(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+        std::exit(-1);
+    }
+}
+
+void onPost(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)
+    {
+        std::cout << "POST request was successful" << std::endl;
+
+        if (rep.hasAttribute("createduri"))
+        {
+            std::cout << "\tUri of the created resource: "
+                      << rep.getValue<std::string>("createduri") << std::endl;
+        }
+        else
+        {
+            rep.getValue("state", myfan.m_state);
+            rep.getValue("power", myfan.m_power);
+            rep.getValue("name", myfan.m_name);
+
+            std::cout << "\tstate: " << myfan.m_state << std::endl;
+            std::cout << "\tpower: " << myfan.m_power << std::endl;
+            std::cout << "\tname: " << myfan.m_name << std::endl;
+
+            strcpy(temp_string, "POST request was successful<br>");
+            sprintf(buf, "state: = %d<br>", myfan.m_state);
+            strcat(temp_string, buf);
+            sprintf(buf, "power: = %d<br>", myfan.m_power);
+            strcat(temp_string, buf);
+            sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
+            strcat(temp_string, buf);
+            m_ThreadContext.log = temp_string;
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                                  &m_ThreadContext);
+        }
+
+        OCRepresentation rep2;
+
+        std::cout << "Posting fan representation..." << std::endl;
+
+        myfan.m_state = true;
+        myfan.m_power = 55;
+
+        rep2.setValue("state", myfan.m_state);
+        rep2.setValue("power", myfan.m_power);
+
+        curFanResource->post(rep2, QueryParamsMap(), &onPost2);
+    }
+    else
+    {
+        std::cout << "onPost Response error: " << eCode << std::endl;
+        sprintf(buf, "onPost Response error:  = %d<br>", eCode);
+        strcpy(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+        std::exit(-1);
+    }
+}
+
+// Local function to put a different state for this resource
+void postFanRepresentation(std::shared_ptr<OCResource> resource)
+{
+    if (resource)
+    {
+        OCRepresentation rep;
+
+        std::cout << "Posting fan representation..." << std::endl;
+
+        myfan.m_state = false;
+        myfan.m_power = 105;
+
+        rep.setValue("state", myfan.m_state);
+        rep.setValue("power", myfan.m_power);
+
+        // Invoke resource's post API with rep, query map and the callback parameter
+        resource->post(rep, QueryParamsMap(), &onPost);
+    }
+}
+
+// Callback handler on PUT request
+void onPut(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        std::cout << "PUT request was successful" << std::endl;
+
+        rep.getValue("state", myfan.m_state);
+        rep.getValue("power", myfan.m_power);
+        rep.getValue("name", myfan.m_name);
+
+        std::cout << "\tstate: " << myfan.m_state << std::endl;
+        std::cout << "\tpower: " << myfan.m_power << std::endl;
+        std::cout << "\tname: " << myfan.m_name << std::endl;
+
+        strcpy(temp_string, "PUT request was successful<br>");
+        sprintf(buf, "state: = %d<br>", myfan.m_state);
+        strcat(temp_string, buf);
+        sprintf(buf, "power: = %d<br>", myfan.m_power);
+        strcat(temp_string, buf);
+        sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
+        strcat(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+
+        putFanRepresentation(curFanResource);
+    }
+    else
+    {
+        std::cout << "onPut Response error: " << eCode << std::endl;
+        sprintf(buf, "onPut Response error:  = %d<br>", eCode);
+        strcpy(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+        std::exit(-1);
+    }
+}
+
+// Local function to put a different state for this resource
+void putFanRepresentation(std::shared_ptr<OCResource> resource)
+{
+    if (resource)
+    {
+        OCRepresentation rep;
+
+        std::cout << "Putting fan representation..." << std::endl;
+
+        myfan.m_state = true;
+        if (myfan.m_power == 1)
+            myfan.m_power = 0;
+        else
+            myfan.m_power = 1;
+        sleep(5);
+        rep.setValue("state", myfan.m_state);
+        rep.setValue("power", myfan.m_power);
+
+        // Invoke resource's put API with rep, query map and the callback parameter
+        resource->put(rep, QueryParamsMap(), &onPut);
+    }
+}
+
+// Callback handler on GET request
+void onFanGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        std::cout << "GET Fan request was successful" << std::endl;
+        std::cout << "Resource URI: " << rep.getUri() << std::endl;
+
+        rep.getValue("state", myfan.m_state);
+        rep.getValue("power", myfan.m_power);
+        rep.getValue("name", myfan.m_name);
+
+        std::cout << "\tstate: " << myfan.m_state << std::endl;
+        std::cout << "\tpower: " << myfan.m_power << std::endl;
+        std::cout << "\tname: " << myfan.m_name << std::endl;
+
+        strcpy(temp_string, "GET Fan request was successful<br>");
+        sprintf(buf, "state: = %d<br>", myfan.m_state);
+        strcat(temp_string, buf);
+        sprintf(buf, "power: = %d<br>", myfan.m_power);
+        strcat(temp_string, buf);
+        sprintf(buf, "name: = %s<br>", myfan.m_name.c_str());
+        strcat(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+
+        putFanRepresentation(curFanResource);
+    }
+    else
+    {
+        std::cout << "onGET Response error: " << eCode << std::endl;
+        sprintf(buf, "onGET Response error:  = %d<br>", eCode);
+        strcpy(temp_string, buf);
+        m_ThreadContext.log = temp_string;
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                              &m_ThreadContext);
+        std::exit(-1);
+    }
+}
+
+
+// Local function to get representation of fan resource
+void getFanRepresentation(std::shared_ptr<OCResource> resource)
+{
+    if (resource)
+    {
+        std::cout << "Getting Fan Representation..." << std::endl;
+
+        // Invoke resource's get API with the callback parameter
+        QueryParamsMap test;
+        resource->get(test, &onFanGet);
+    }
+}
+
+// Callback to found resources
+void foundResourceFan(std::shared_ptr<OCResource> resource)
+{
+    if (curFanResource)
+    {
+        std::cout << "Found another resource, ignoring" << std::endl;
+    }
+
+    std::string resourceURI;
+    std::string hostAddress;
+    try
+    {
+        // Do some operations with resource object.
+        if (resource)
+        {
+            std::cout << "DISCOVERED Resource:" << std::endl;
+            strcpy(temp_string, "DISCOVERED Resource:");
+
+            // Get the resource URI
+            resourceURI = resource->uri();
+            std::cout << "\tURI of the resource: " << resourceURI << std::endl;
+            sprintf(buf, "URI of the resource: = %s<br>", resourceURI.c_str());
+            strcat(temp_string, buf);
+
+            // Get the resource host address
+            hostAddress = resource->host();
+            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
+            sprintf(buf, "Host address of the resource: = %s<br>", hostAddress.c_str());
+            strcat(temp_string, buf);
+
+            // Get the resource types
+            std::cout << "\tList of resource types: " << std::endl;
+            strcat(temp_string, "List of resource types: <br>");
+            for (auto & resourceTypes : resource->getResourceTypes())
+            {
+                std::cout << "\t\t" << resourceTypes << std::endl;
+                sprintf(buf, "%s<br>", resourceTypes.c_str());
+                strcat(temp_string, buf);
+            }
+
+            // Get the resource interfaces
+            std::cout << "\tList of resource interfaces: " << std::endl;
+            for (auto & resourceInterfaces : resource->getResourceInterfaces())
+            {
+                std::cout << "\t\t" << resourceInterfaces << std::endl;
+                sprintf(buf, "%s<br>", resourceInterfaces.c_str());
+                strcat(temp_string, buf);
+            }
+
+            if (resourceURI == "/a/fan")
+            {
+                curFanResource = resource;
+                /* Call a local function which will internally invoke get API
+                   on the resource pointer */
+                putFanRepresentation(curFanResource);
+            }
+            m_ThreadContext.log = temp_string;
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                                  &m_ThreadContext);
+        }
+        else
+        {
+            // Resource is invalid
+            std::cout << "Resource is invalid" << std::endl;
+            strcpy(temp_string, "Resource is invalid");
+            m_ThreadContext.log = temp_string;
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                                  &m_ThreadContext);
+        }
+
+    }
+    catch (std::exception &e)
+    {
+        // log(e.what());
+    }
+}
+
+void PrintUsage()
+{
+    std::cout << std::endl;
+    std::cout << "Usage : simpleclient <ObserveType>" << std::endl;
+    std::cout << "   ObserveType : 1 - Observe" << std::endl;
+    std::cout << "   ObserveType : 2 - ObserveAll" << std::endl;
+}
+
+static void
+win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    ui_app_exit();
+}
+
+static void
+win_back_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    ui_app_exit();
+}
+
+static void
+send_msg_clicked_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    appdata_s *ad = (appdata_s *)data;
+    if (isSendMessage == true)
+    {
+        try
+        {
+            m_pm = new PluginManager();
+
+            // Get Plugins
+            std::vector<Plugin> user_plugin;
+
+            user_plugin = m_pm->getPlugins();
+
+            for (unsigned int i = 0; i < user_plugin.size(); i++)
+            {
+                strcpy(temp_string, "Calling Get Plugin<br>");
+                sprintf(buf, "value Name = %s<br>", user_plugin[i].getName().c_str());
+                strcat(temp_string, buf);
+                sprintf(buf, "value ID = %s<br>", user_plugin[i].getID().c_str());
+                strcat(temp_string, buf);
+                m_ThreadContext.log = temp_string;
+                ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                                      &m_ThreadContext);
+                std::cout << "value Name = " << user_plugin[i].getName() << std::endl;
+                std::cout << "value ID = " << user_plugin[i].getID() << std::endl;
+            }
+
+
+            std::cout << "start fan Plugin by Resource Type"  << std::endl;
+            strcpy(temp_string, "start fan Plugin<br>");
+            strcat(temp_string, "fan Plugin is getting started. Please wait...<br>");
+            m_ThreadContext.log = temp_string;
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateCallbackLog,
+                                                  &m_ThreadContext);
+            m_pm->startPlugins("ResourceType", "oic.fan");
+            sleep(2);
+            // Makes it so that all boolean values are printed as 'true/false' in this stream
+            std::cout.setf(std::ios::boolalpha);
+            std::cout << "Before find Resource... " << std::endl;
+
+            // Find fan resources
+            std::ostringstream requestURI;
+            requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.fan";
+            OCPlatform::findResource("", requestURI.str(), OC_ALL, &foundResourceFan);
+            std::cout << "Finding Resource... " << std::endl;
+        }
+        catch (OCException &e)
+        {
+            // log(e.what());
+        }
+
+        elm_object_text_set(ad->send_msg_button, "Press here to close the App");
+        isSendMessage = false;
+    }
+    else
+    {
+        isSendMessage = true;
+        ui_app_exit();
+    }
+}
+
+static void
+clear_log_clicked_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    appdata_s *ad = (appdata_s *)data;
+    elm_entry_entry_set(ad->log, "");
+}
+
+static void
+create_base_gui(appdata_s *ad)
+{
+    // Window
+    ad->win = elm_win_util_standard_add(PACKAGE, PACKAGE);
+    elm_win_autodel_set(ad->win, EINA_TRUE);
+
+    if (elm_win_wm_rotation_supported_get(ad->win))
+    {
+        int rots[4] = { 0, 90, 180, 270 };
+        elm_win_wm_rotation_available_rotations_set(ad->win, (const int *)(&rots), 4);
+    }
+
+    evas_object_smart_callback_add(ad->win, "delete,request", win_delete_request_cb, NULL);
+    eext_object_event_callback_add(ad->win, EEXT_CALLBACK_BACK, win_back_cb, ad);
+
+    // Conformant
+    ad->conform = elm_conformant_add(ad->win);
+    elm_win_indicator_mode_set(ad->win, ELM_WIN_INDICATOR_SHOW);
+    elm_win_indicator_opacity_set(ad->win, ELM_WIN_INDICATOR_OPAQUE);
+    evas_object_size_hint_weight_set(ad->conform, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_win_resize_object_add(ad->win, ad->conform);
+    evas_object_show(ad->conform);
+
+    // naviframe
+    ad->naviframe = elm_naviframe_add(ad->conform);
+    elm_object_content_set(ad->conform, ad->naviframe);
+    evas_object_show(ad->naviframe);
+
+    // Box container
+    ad->box = elm_box_add(ad->naviframe);
+    elm_box_horizontal_set(ad->box, EINA_FALSE);
+    evas_object_size_hint_weight_set(ad->box, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(ad->box, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    elm_box_padding_set(ad->box, 0, 15 * elm_config_scale_get());
+    elm_naviframe_item_push(ad->naviframe, "ProtocolPlugin App", NULL, NULL, ad->box, NULL);
+    evas_object_show(ad->box);
+
+    ad->send_msg_button = elm_button_add(ad->box);
+    evas_object_size_hint_align_set(ad->send_msg_button, EVAS_HINT_FILL, 0.0);
+    elm_object_text_set(ad->send_msg_button, "Invoke Fan Plugin");
+    evas_object_smart_callback_add(ad->send_msg_button, "clicked", send_msg_clicked_cb, ad);
+    elm_box_pack_end(ad->box, ad->send_msg_button);
+    evas_object_show(ad->send_msg_button);
+
+    ad->clear_log_button = elm_button_add(ad->box);
+    evas_object_size_hint_align_set(ad->clear_log_button, EVAS_HINT_FILL, 0.0);
+    elm_object_text_set(ad->clear_log_button, "Clear Log");
+    evas_object_smart_callback_add(ad->clear_log_button, "clicked", clear_log_clicked_cb, ad);
+    elm_box_pack_end(ad->box, ad->clear_log_button);
+    evas_object_show(ad->clear_log_button);
+
+    ad->log = elm_entry_add(ad->box);
+    elm_object_part_text_set(ad->log, "elm.guide", "Log messages will be update here!!!");
+    elm_entry_scrollable_set(ad->log, EINA_TRUE);
+    evas_object_size_hint_weight_set(ad->log, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(ad->log, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    elm_box_pack_end(ad->box, ad->log);
+    evas_object_show(ad->log);
+
+    // Show window after base gui is set up
+    evas_object_show(ad->win);
+
+    std::string name;
+    std::string key = "Name";
+    std::string  state = "";
+    std::string  id = "";
+
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    {
+        OC::ServiceType::InProc,
+        OC::ModeType::Both,
+        "0.0.0.0",
+        0,
+        OC::QualityOfService::LowQos
+    };
+
+    OCPlatform::Configure(cfg);
+}
+
+static bool
+app_create(void *data)
+{
+    /* Hook to take necessary actions before main event loop starts
+        Initialize UI resources and application's data
+        If this function returns true, the main loop of application starts
+        If this function returns false, the application is terminated */
+    appdata_s *ad = (appdata_s *)data;
+    m_ThreadContext.ad = ad;
+    m_ThreadContext.log = NULL;
+    create_base_gui(ad);
+
+    return true;
+}
+
+static void
+app_control(app_control_h app_control, void *data)
+{
+    // Handle the launch request.
+    dlog_print(DLOG_INFO, LOG_TAG, "#### in app_control");
+}
+
+static void
+app_pause(void *data)
+{
+    // Take necessary actions when application becomes invisible.
+    dlog_print(DLOG_INFO, LOG_TAG, "#### in app_pause");
+}
+
+static void
+app_resume(void *data)
+{
+    // Take necessary actions when application becomes visible.
+    dlog_print(DLOG_INFO, LOG_TAG, "#### in app_resume");
+}
+
+static void
+app_terminate(void *data)
+{
+    // Release all resources.
+    dlog_print(DLOG_INFO, LOG_TAG, "#### in app_terminate");
+
+}
+
+static void
+ui_app_lang_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LANGUAGE_CHANGED
+    char *locale = NULL;
+    system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale);
+    elm_language_set(locale);
+    free(locale);
+    return;
+}
+
+static void
+ui_app_orient_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_DEVICE_ORIENTATION_CHANGED
+    dlog_print(DLOG_INFO, LOG_TAG, "#### app orient changed");
+    return;
+}
+
+static void
+ui_app_region_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_REGION_FORMAT_CHANGED
+}
+
+static void
+ui_app_low_battery(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_BATTERY
+}
+
+static void
+ui_app_low_memory(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_MEMORY
+}
+
+int
+main(int argc, char *argv[])
+{
+    appdata_s ad = {0,};
+    int ret = 0;
+
+    ui_app_lifecycle_callback_s event_callback = {0,};
+    app_event_handler_h handlers[5] = {NULL, };
+
+    event_callback.create = app_create;
+    event_callback.terminate = app_terminate;
+    event_callback.pause = app_pause;
+    event_callback.resume = app_resume;
+    event_callback.app_control = app_control;
+
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY,
+                             ui_app_low_battery, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY,
+                             ui_app_low_memory, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED],
+                             APP_EVENT_DEVICE_ORIENTATION_CHANGED, ui_app_orient_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED], APP_EVENT_LANGUAGE_CHANGED,
+                             ui_app_lang_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED],
+                             APP_EVENT_REGION_FORMAT_CHANGED, ui_app_region_changed, &ad);
+    ui_app_remove_event_handler(handlers[APP_EVENT_LOW_MEMORY]);
+
+    ret = ui_app_main(argc, argv, &event_callback, &ad);
+
+    if (ret != APP_ERROR_NONE)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "app_main() is failed. err = %d", ret);
+    }
+
+    return ret;
+}
diff --git a/service/protocol-plugin/sample-app/tizen/PPMSampleApp/tizen-manifest.xml b/service/protocol-plugin/sample-app/tizen/PPMSampleApp/tizen-manifest.xml
new file mode 100644 (file)
index 0000000..676e388
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="2.3" package="org.iotivity.service.ppm.ppmsampleapp" version="1.0.0">
+    <profile name="mobile"/>
+    <ui-application appid="org.iotivity.service.ppm.ppmsampleapp" exec="ppmsampleapp" multiple="false" nodisplay="false" taskmanage="true" type="capp">
+        <label>ppmsampleapp</label>
+        <icon>sampleapp.png</icon>
+    </ui-application>
+    <privileges>
+        <privilege>http://tizen.org/privilege/network.get</privilege>
+        <privilege>http://tizen.org/privilege/internet</privilege>
+    </privileges>
+    <feature name="http://tizen.org/feature/network.wifi">true</feature>
+</manifest>
index 8dceeeb..1a645ef 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
 ##
@@ -20,13 +40,14 @@ if target_os == 'arduino':
 # Build flags
 ######################################################################
 if target_os not in ['windows', 'winrt']:
-       soft_sensor_manager_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-DLINUX'])
+       soft_sensor_manager_env.AppendUnique(CXXFLAGS = ['-Wall', '-DLINUX','-std=c++0x'])
        if target_os != 'android':
+               soft_sensor_manager_env.AppendUnique(LIBS = ['pthread'])
                soft_sensor_manager_env.AppendUnique(CXXFLAGS = ['-pthread'])
 
 if target_os == 'android':
        soft_sensor_manager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       soft_sensor_manager_env.AppendUnique(LIBS = ['gnustl_static', 'compatibility'])
+       soft_sensor_manager_env.AppendUnique(LIBS = ['gnustl_shared'])
 
        if not env.get('RELEASE'):
                soft_sensor_manager_env.AppendUnique(LIBS = ['log'])
@@ -47,7 +68,7 @@ env.AppendTarget('libSSMSDK')
 libssmsdk = sdk_env.StaticLibrary(
                target = 'libSSMSDK',
                source = [ssm_sdk_cpp_src]
-               )               
+               )
 sdk_env.InstallTarget(libssmsdk, 'libSSMCORE')
 
 ######################################################################
@@ -67,12 +88,35 @@ DiscomfortIndexSensor_src = [ Glob(DISCOMFORTINDEXSENSOR_DIR + 'src/*.cpp')]
 DiscomfortIndexSensor = DiscomfortIndexSensor_env.SharedLibrary('DiscomfortIndexSensor', DiscomfortIndexSensor_src)
 DiscomfortIndexSensor_env.InstallTarget(DiscomfortIndexSensor, 'libDiscomfortIndexSensor')
 
+
+
+
+######################################################################
+# build BMISensor plugin
+######################################################################
+BMISensor_env = soft_sensor_manager_env.Clone()
+
+BMISensor_env.AppendUnique(CCFLAGS = ['-fPIC'])
+BMISENSOR_DIR = 'SoftSensorPlugin/BMISensor/'
+BMISensor_env.AppendUnique(CPPPATH = [
+               BMISENSOR_DIR + 'include',
+               'SSMCore/src/SSMInterface/'
+               ])
+
+BMISensor_src = [ Glob(BMISENSOR_DIR + 'src/*.cpp')]
+
+BMISensor = BMISensor_env.SharedLibrary('BMISensor', BMISensor_src)
+BMISensor_env.InstallTarget(BMISensor, 'libBMISensor')
+
+
+
 ######################################################################
 # build SSM CORE
 ######################################################################
 ssmcore_env = soft_sensor_manager_env.Clone()
 
 ssmcore_env.AppendUnique(CPPPATH = [
+               env.get('SRC_DIR')+'/extlibs',
                'SSMCore/include/',
                'SSMCore/src/',
                'SSMCore/src/Common/'
@@ -102,12 +146,22 @@ ssm_core_c_src = [
                'SSMCore/src/Common/sqlite3.c'
 ]
 
-libssmcore = ssmcore_env.StaticLibrary(
+
+static_libssmcore = ssmcore_env.StaticLibrary(
+               target = 'SSMCore',
+               source = [ssm_core_cpp_src, ssm_core_c_src]
+               )
+
+ssmcore_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+ssmcore_env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger',
+            'connectivity_abstraction', 'coap'])
+
+shared_libssmcore = ssmcore_env.SharedLibrary(
                target = 'SSMCore',
                source = [ssm_core_cpp_src, ssm_core_c_src]
                )
 
-ssmcore_env.InstallTarget(libssmcore, 'libSSMCORE')
+ssmcore_env.InstallTarget([shared_libssmcore, static_libssmcore], 'libSSMCORE')
 
 #######################################################################
 ## build SampleApp
@@ -123,3 +177,5 @@ if target_os == 'linux':
        Command("SoftSensorDescription.xml", "SoftSensorPlugin/SoftSensorDescription.xml", Copy("$TARGET", "$SOURCE"))
        Command("THSensorApp","SampleApp/linux/THSensorApp/THSensorApp", Copy("$TARGET", "$SOURCE"))
        Command("THSensorApp1","SampleApp/linux/THSensorApp1/THSensorApp1", Copy("$TARGET", "$SOURCE"))
+       Command("HeightSensorApp","SampleApp/linux/HeightSensorApp/HeightSensorApp", Copy("$TARGET", "$SOURCE"))
+       Command("WeightSensorApp","SampleApp/linux/WeightSensorApp/WeightSensorApp", Copy("$TARGET", "$SOURCE"))
diff --git a/service/soft-sensor-manager/SDK/cpp/build/linux/Makefile b/service/soft-sensor-manager/SDK/cpp/build/linux/Makefile
deleted file mode 100644 (file)
index 918471b..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
--include ../../../../build/linux/root_path.inc
--include ../../../../build/linux/environment.mk
-
-BOOST=${BOOST_BASE}
-SRC_PATH=../../src
-INC_PATH=../../include
-RST_NAME=release
-
-GAR=ar
-
-# Insert your project name.
-TARGET=${SSM_LIB}
-
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX
-CXX_INC=-I../../ -I${INC_PATH}/ -I${FD_SSMCORE}/include -I${FD_SSMCORE}/src -I${BOOST}
-CXX_LIB= 
-
-SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
-OBJPATH=${SRCLIST:.cpp=.o}
-OBJLIST=${notdir ${OBJPATH}}
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job ${TARGET} post_job
-
-pre_job:
-       @echo " " 
-       @echo "--------- SDK Build Begin. ----------" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-
-${TARGET}: ${OBJLIST}
-       ${GAR} -r ./${RST_NAME}/$@  ./*.o
-       @cp -Rdp ${INC_PATH}/*.h ./${RST_NAME}/
-       @echo " " 
-
-%.o : ${SRC_PATH}/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o $@
-       @echo " " 
-
-post_job:
-       @echo " " 
-       @cp -Rdp ./${RST_NAME}/* ${OUTPUTS_DIR}/
-       @echo "--------- SDK Build Successful. ---------"
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " " 
-       
-       
-clean:
-       rm -f -v *.o ${TARGET}
-       rm -rf ./${RST_NAME}
-       
index 0085b3b..866d578 100644 (file)
@@ -1,3 +1,29 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+* @file
+*
+* This file defines basic interface of Soft Sensor Manager.
+*/
+
 #ifndef _SSMInterface_H_
 #define _SSMInterface_H_
 
@@ -13,6 +39,9 @@ namespace OIC
         , SSM_E_POINTER
         , SSM_E_OUTOFMEMORY
         , SSM_E_FAIL
+        , SSM_E_NOTINIT
+        , SSM_E_INITIALIZED
+        , SSM_E_INVALIDXML
         , SSM_E_NOINTERFACE
         , SSM_E_NOTIMPL
     };
@@ -21,75 +50,50 @@ namespace OIC
     * @class    IModelData
     * @brief    This class represents context model data package
     *
-    * @see
     */
     class IModelData
     {
         public:
             /**
-            * @fn     getDataId
-            * @brief Get affected DataId. ContextModel has plenty of data so \n
+            * Get affected DataId. ContextModel has plenty of data so \n
             *         returned data is matched from given condition
             *
-            * @param None
-            *
-            * @return int
-            * @warning
-            * @exception
-            * @see
+            * @return int - the affected DataId
             */
             virtual int getDataId() = 0;
 
             /**
-            * @fn     GetPropertyCount
-            * @brief ContextModel has at least one property that contains data \n
+            * ContextModel has at least one property that contains data \n
             *         property is described from its specification.
             *
-            * @param None
-            *
-            * @return int
-            * @warning
-            * @exception
-            * @see
+            * @return int - number of properties
             */
             virtual int getPropertyCount() = 0;
 
             /**
-            * @fn     getPropertyName
-            * @brief Retrieve propertyName
+            * Retrieve propertyName
             *
-            * @param [in] int propertyIndex - index of property to read
+            * @param propertyIndex - index of property to read
             *
-            * @return std::string
-            * @warning
-            * @exception
-            * @see
+            * @return std::string - property name
             */
             virtual std::string getPropertyName(int propertyIndex) = 0;
 
             /**
-            * @fn     getPropertyValue
-            * @brief Retrieve propertyValue
+            * Retrieve propertyValue
             *
-            * @param [in] int propertyIndex - index of property to read
+            * @param propertyIndex index of property to read
             *
-            * @return std::string
-            * @warning
-            * @exception
-            * @see
+            * @return std::string - property value
             */
             virtual std::string getPropertyValue(int propertyIndex) = 0;
 
             /**
-            * @fn     getPropertyValueByName
-            * @brief Retrieve propertyValue using given name
+            * Retrieve propertyValue using given name
             *
-            * @param [in] std::string propertyName - property name looking for
+            * @param propertyName - property name looking for
             *
-            * @return std::string
-            * @warning
-            * @exception
-            * @see
+            * @return std::string - property name
             */
             virtual std::string getPropertyValueByName(std::string propertyName) = 0;
         protected:
@@ -106,49 +110,35 @@ namespace OIC
     {
         public:
             /**
-            * @fn     getAffectedModels
-            * @brief Get affected ContextModels. The CQL can specify multiple ContextModels for retrieving data.
+            * Get affected ContextModels. The query can specify multiple ContextModels for retrieving data.
             *
-            * @param [in, out] std::vector<std::string> *pAffectedModels - affected ContextModel list
+            * @param pAffectedModels - affected ContextModel list
             *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT getAffectedModels(std::vector<std::string> *pAffectedModels) = 0;
 
             /**
-            * @fn     getModelDataCount
-            * @brief Get affected data count. There are multiple data can exist from given condition.
+            * Get affected data count. There are multiple data can exist from given condition.
             *
-            * @param [in] std::string modelName - affected ContextModel name
+            * @param modelName - affected ContextModel name
             *
-            * @param [in, out] int *pDataCount - affected dataId count
+            * @param pDataCount - affected dataId count
             *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT getModelDataCount(std::string modelName, int *pDataCount) = 0;
 
             /**
-            * @fn     getModelData
-            * @brief Get actual Context Model data
+            * Get actual Context Model data
             *
-            * @param [in] std::string modelName - affected ContextModel name
+            * @param modelName - affected ContextModel name
             *
+            * @param dataIndex - affected dataId index
             *
-            * @param [in] int dataIndex - affected dataId index
+            * @param ppModelData - affected ContextModel data reader
             *
-            *
-            * @param [out] IModelData **ppModelData - affected ContextModel data reader
-            *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT getModelData(std::string modelName, int dataIndex, IModelData **ppModelData) = 0;
         protected:
@@ -165,17 +155,13 @@ namespace OIC
     {
         public:
             /**
-            * @fn     onQueryEngineEvent
-            * @brief Transmit result of SSMCore to Application layer
+            * Transmit result of SSMCore to Application layer
             *
-            * @param [in] int cqid - entered ContextQuery ID
+            * @param cqid - entered ContextQuery ID
             *
-            * @param [in] IDataReader *pResult - result of SSMCore
+            * @param pResult - result of SSMCore
             *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult) = 0;
         protected:
@@ -183,47 +169,41 @@ namespace OIC
     };
 
     /**
-    * @class    SSMInterface
-    * @brief    This class represents main class for querying Soft Sensors
+    * Initialize Soft sensor manager using given configuration information.
     *
-    * @see
+    * @param xmlDescription - specification described in XML
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
     */
-    class SSMInterface
-    {
-        public:
-            SSMInterface();
-            ~SSMInterface();
+    SSMRESULT InitializeSSM(std::string xmlDescription);
 
-            /**
-            * @fn     registerQuery
-            * @brief Execute ContextQuery and return ContextQuery ID
-            *
-            * @param [in] std::string queryString - query for requesting data
-            *
-            * @param [in] IQueryEngineEvent listener - listener for receiving data related to query
-            *
-            * @param [in, out] int &cqid - ID of ContextQuery
-            *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
-            */
-            SSMRESULT registerQuery(std::string queryString, IQueryEngineEvent *listener, int &cqid);
+    /**
+    * Terminates Soft sensor manager
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
+    */
+    SSMRESULT TerminateSSM();
 
-            /**
-            * @fn    unregisterQuery
-            * @brief unregister registered ContextQuery according to cqid
-            *
-            * @param [in] int cqid - Context query corresponding to the cqid will be terminated
-            *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
-            */
-            SSMRESULT unregisterQuery(int cqid);
-    };
+    /**
+    * Execute query and return ContextQuery ID
+    *
+    * @param queryString - query for requesting data
+    *
+    * @param listener - listener for receiving data related to query
+    *
+    * @param cqid - ID of ContextQuery
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
+    */
+    SSMRESULT RegisterQuery(std::string queryString, IQueryEngineEvent *listener, int &cqid);
 
+    /**
+    * Unregister registered query according to cqid
+    *
+    * @param cqid - Query corresponding to the cqid will be terminated
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
+    */
+    SSMRESULT UnregisterQuery(int cqid);
 }
 #endif
\ No newline at end of file
index 358f807..01451e9 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.
+ *
+ ******************************************************************/
 #include "SSMInterface.h"
 #include "SSMInterface/SSMCore.h"
 #include "Common/PlatformLayer.h"
@@ -9,7 +28,7 @@ class SSMCoreEventReceiver : public IQueryEngineEvent
         {
         }
 
-        SSMRESULT onQueryEngineEvent(IN int cqid, IN IDataReader *pResult)
+        SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult)
         {
             SSMRESULT res = SSM_E_FAIL;
 
@@ -39,12 +58,12 @@ CLEANUP:
             m_mtxListener.unlock();
         }
 
-        void addListener(IN int cqid, IN IQueryEngineEvent *pEngineEvent)
+        void addListener(int cqid, IQueryEngineEvent *pEngineEvent)
         {
             m_mapListener[cqid] = pEngineEvent;
         }
 
-        void removeListener(IN int cqid)
+        void removeListener(int cqid)
         {
             m_mapListener.erase(cqid);
         }
@@ -57,32 +76,37 @@ CLEANUP:
 IQueryEngine                        *g_pQueryEngineInstance = NULL;
 SSMCoreEventReceiver                *g_pEventReceiver = NULL;
 
-SSMInterface::SSMInterface()
+SSMRESULT OIC::InitializeSSM(std::string xmlDescription)
 {
-    std::string xmlDescription = "<SSMCore>"
-                                 "<Device>"
-                                 "<UDN>abcde123-31f8-11b4-a222-08002b34c003</UDN>"
-                                 "<Name>MyPC</Name>"
-                                 "<Type>PC</Type>"
-                                 "</Device>"
-                                 "</SSMCore>";
-
     SSMRESULT res = SSM_E_FAIL;
 
+    if (g_pQueryEngineInstance != NULL)
+        SSM_CLEANUP_ASSERT(SSM_E_INITIALIZED);
+
     g_pEventReceiver = new SSMCoreEventReceiver();
     SSM_CLEANUP_NULL_ASSERT(g_pEventReceiver);
     SSM_CLEANUP_ASSERT(InitializeSSMCore(xmlDescription));
     SSM_CLEANUP_ASSERT(StartSSMCore());
     SSM_CLEANUP_ASSERT(CreateQueryEngine(&g_pQueryEngineInstance));
     SSM_CLEANUP_ASSERT(g_pQueryEngineInstance->registerQueryEvent(g_pEventReceiver));
+
 CLEANUP:
-    ;
+    if (res != SSM_S_OK &&
+        res != SSM_E_INITIALIZED)
+    {
+        SAFE_DELETE(g_pEventReceiver);
+    }
+
+    return res;
 }
 
-SSMInterface::~SSMInterface()
+SSMRESULT OIC::TerminateSSM()
 {
     SSMRESULT res = SSM_E_FAIL;
 
+    if (g_pQueryEngineInstance == NULL)
+        SSM_CLEANUP_ASSERT(SSM_E_NOTINIT);
+
     SSM_CLEANUP_ASSERT(g_pQueryEngineInstance->unregisterQueryEvent(g_pEventReceiver));
     ReleaseQueryEngine(g_pQueryEngineInstance);
     g_pQueryEngineInstance = NULL;
@@ -91,31 +115,40 @@ SSMInterface::~SSMInterface()
 
 CLEANUP:
     SAFE_DELETE(g_pEventReceiver);
+    return res;
 }
 
-SSMRESULT SSMInterface::registerQuery(IN std::string queryString, IN IQueryEngineEvent *listener,
-                                      IN int &cqid)
+SSMRESULT OIC::RegisterQuery(std::string queryString, IQueryEngineEvent *listener,
+                             int &cqid)
 {
     SSMRESULT res = SSM_E_FAIL;
 
+    if (g_pQueryEngineInstance == NULL)
+        SSM_CLEANUP_ASSERT(SSM_E_NOTINIT);
+
     g_pEventReceiver->lockListener();
     SSM_CLEANUP_ASSERT(g_pQueryEngineInstance->executeContextQuery(queryString, &cqid));
     g_pEventReceiver->addListener(cqid, listener);
 
 CLEANUP:
-    g_pEventReceiver->unlockListener();
+    if (g_pEventReceiver != NULL)
+        g_pEventReceiver->unlockListener();
     return res;
 }
 
-SSMRESULT SSMInterface::unregisterQuery(IN int cqid)
+SSMRESULT OIC::UnregisterQuery(int cqid)
 {
     SSMRESULT res = SSM_E_FAIL;
 
+    if (g_pQueryEngineInstance == NULL)
+        SSM_CLEANUP_ASSERT(SSM_E_NOTINIT);
+
     g_pEventReceiver->lockListener();
     SSM_CLEANUP_ASSERT(g_pQueryEngineInstance->killContextQuery(cqid));
     g_pEventReceiver->removeListener(cqid);
 
 CLEANUP:
-    g_pEventReceiver->unlockListener();
+    if (g_pEventReceiver != NULL)
+        g_pEventReceiver->unlockListener();
     return res;
 }
\ No newline at end of file
index 38ff87c..5958659 100644 (file)
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    CoreController.java
+ *
+ * @brief    This file provides a class containing a set of APIs for soft sensor manager
+ *          application.
+ *
+ */
+
 package org.iotivity.service.ssm;
 
 import java.util.List;
 
-import android.util.Log;
-
-public class CoreController 
-{
-       static
-       {
-               try
-               {
-                       String workingPath = System.getProperty( "user.dir" );
-                       
-                       Log.i("SSMTester", "loading ssm lib");
-                       
-                       // for android: not complete method
-                       if(System.getProperty("os.name").toLowerCase().equals("linux"))
-                       {
-                               //System.out.println("System load Android library");
-                               System.loadLibrary("SSMCore_Android");
-                       }
-                       else
-                       {
-                               //System.out.println("System load 32bit library");
-                               workingPath += "/../Outputs/";
-                               System.load( workingPath + "SSMCore_Windows.dll");
-                       }
-                       
-                       Log.i("SSMTester", "loading done");
-               }
-               catch(UnsatisfiedLinkError e)
-               {
-                       System.out.println(e.getMessage());
-               }
-       }
-       
-       static private CoreController coreController;
-       
-       public static CoreController getInstance()
-       {
-               if(coreController == null)
-                       coreController = new CoreController();
-               
-               return coreController;
-       }
-       
-       public native void InitializeSSMCore(String xmlDescription);
-       public native void StartSSMCore();
-       public native void StopSSMCore();
-       public native void TerminateSSMCore();
-       public native QueryEngine CreateQueryEngine();
-       public native int ReleaseQueryEngine(QueryEngine queryEngine);
-       
-       // QueryEngine
-       public native int ExecuteContextQuery(int pQueryEngineInstance, String contextQuery);
-       public native void RegisterQueryEvent(int pQueryEngineInstance, IQueryEngineEvent queryEngineEvent);
-       public native void KillContextQuery(int pQueryEngineInstance, int cqid);        
-               
-       //public native void UnregiterQueryEvent(int pQueryEngineInstance, IQueryEngineEvent queryEngineEvent);
-
-       //IModelData
-       public native int GetDataId(int pIModelDataInstance);   
-       public native int GetPropertyCount(int pIModelDataInstance);
-       public native String GetPropertyName(int pIModelDataInstance, int propertyIndex);
-       public native String GetPropertyValue(int pIModelDataInstance, int propertyIndex);
-               
-       //IDataReader
-       public native List<String> GetAffectedModels(int pDataReaderInstance);
-       public native int GetModelDataCount(int pDataReaderInstance, String modelName);
-       public native ModelData GetModelData(int pDataReaderInstance, String modelName, int dataIndex);
-       
-       public native void RegisterReportReceiver(IReportReceiver reportReceiver);
+/**
+ * @class CoreController
+ * @brief This class provides a set of APIs relating to soft sensor manager It
+ *        contains utility API's for DataReader, QueryEngine and SSMInterface
+ *        classes.
+ */
+public class CoreController {
+    static {
+        try {
+            String workingPath = System.getProperty("user.dir");
+
+            // for android: not complete method
+            if (System.getProperty("os.name").toLowerCase().equals("linux")) {
+                System.loadLibrary("gnustl_shared");
+                System.loadLibrary("oc_logger");
+                System.loadLibrary("connectivity_abstraction");
+                System.loadLibrary("octbstack");
+                System.loadLibrary("oc");
+                System.loadLibrary("SSMCore");
+            } else {
+                System.load(workingPath + "SSMCore_Windows.dll");
+            }
+        } catch (UnsatisfiedLinkError e) {
+            System.out.println(e.getMessage());
+        }
+    }
+
+    static private CoreController coreController;
+
+    /**
+     * Return instance of CoreController.
+     * 
+     * @return CoreController - instance of this class
+     */
+    public static CoreController getInstance() {
+        if (coreController == null)
+            coreController = new CoreController();
+
+        return coreController;
+    }
+
+    /**
+     * Initialize a framework using the given configuration
+     * 
+     * @param xmlDescription
+     *            - Framework specifications described in XML format
+     * 
+     * @return void
+     */
+    public native void initializeSSMCore(String xmlDescription)
+            throws Exception;
+
+    /**
+     * Starts the framework that allows other devices to discover and
+     * communicate with the SSMCore and underlying query engine.
+     * 
+     * @return void
+     */
+    public native void startSSMCore() throws Exception;
+
+    /**
+     * Stops the framework and terminate all communications.
+     * 
+     * @return void
+     */
+    public native void stopSSMCore() throws Exception;
+
+    /**
+     * Terminate the framework, return all allocated resources
+     * 
+     * @return void
+     */
+    public native void terminateSSMCore() throws Exception;
+
+    /**
+     * Creates an instance of the Query Engine
+     * 
+     * @return QueryEngine - QueryEngine object created
+     */
+    public native QueryEngine createQueryEngine() throws Exception;
+
+    /**
+     * Release the QueryEngine object.
+     * 
+     * @param queryEngine
+     *            - QueryEngine instance to be released
+     * 
+     * @return int - success or failure result
+     */
+    public native int releaseQueryEngine(QueryEngine queryEngine);
+
+    /**
+     * Execute the query with the QueryEngine and return ContextQuery ID for the
+     * query
+     * 
+     * @param pQueryEngineInstance
+     *            - instance(created on creation of the QueryEngine) of the
+     *            query engine with which the query is to be executed
+     * 
+     * @param contextQuery
+     *            - query string to be executed
+     * 
+     * @return int - ID of context query executed
+     */
+    public native int executeContextQuery(int pQueryEngineInstance,
+            String contextQuery) throws Exception;
+
+    /**
+     * Register QueryEngineEvent to QueryEngine.
+     * 
+     * @param pQueryEngineInstance
+     *            - instance(created on creation of the QueryEngine) of the
+     *            query engine with which the query is to be registered
+     * 
+     * @param queryEngineEvent
+     *            - the event class to receive QueryEngine events
+     * 
+     * @return void
+     */
+    public native void registerQueryEvent(int pQueryEngineInstance,
+            IQueryEngineEvent queryEngineEvent);
+
+    /**
+     * Kill the registered ContextQuery corresponding to the cqid
+     * 
+     * @param pQueryEngineInstance
+     *            - instance(created on creation of the QueryEngine) of the
+     *            query engine with which the query is to be terminated
+     * 
+     * @param cqid
+     *            - ContextQuery ID of the query to be terminated
+     * 
+     * @return void
+     */
+    public native void killContextQuery(int pQueryEngineInstance, int cqid)
+            throws Exception;
+
+    /**
+     * Get the affected DataId. ContextModel has plenty of data so returned data
+     * is matched from given condition which in this case is the model data
+     * object instance
+     * 
+     * @param pIModelDataInstance
+     *            - instance(created on creation of the ModelData) of the model
+     *            data for which Data ID is to be returned
+     * 
+     * @return int - the affected DataId
+     */
+    public native int getDataId(int pIModelDataInstance);
+
+    /**
+     * ContextModel has at least one property that contains data \n property is
+     * described from its specification.
+     * 
+     * @param pIModelDataInstance
+     *            - instance(created on creation of the ModelData) of the model
+     *            data for which property count is to be returned
+     * 
+     * @return @return int - number of properties
+     */
+    public native int getPropertyCount(int pIModelDataInstance);
+
+    /**
+     * Retrieve the name of the property using the given index
+     * 
+     * @param pIModelDataInstance
+     *            - instance(created on creation of the ModelData) of the model
+     *            data for which property name is to be returned
+     * 
+     * @param propertyIndex
+     *            - index of property to read
+     * 
+     * @return String - property name
+     */
+    public native String getPropertyName(int pIModelDataInstance,
+            int propertyIndex);
+
+    /**
+     * Retrieve the value of the property using the given index
+     * 
+     * @param pIModelDataInstance
+     *            - instance(created on creation of the ModelData) of the model
+     *            data for which property value is to be returned
+     * 
+     * @param propertyIndex
+     *            - index of property to read
+     * 
+     * @return String - property value
+     */
+    public native String getPropertyValue(int pIModelDataInstance,
+            int propertyIndex);
+
+    /**
+     * Get affected context models. The CQL(context query language) can specify
+     * multiple ContextModels for retrieving data so a list of string of
+     * affected context models is returned
+     * 
+     * @param pDataReaderInstance
+     *            - instance(created on creation of the DataReader) of the data
+     *            reader class object
+     * 
+     * @return List<String> - affected ContextModel list
+     */
+    public native List<String> getAffectedModels(int pDataReaderInstance);
+
+    /**
+     * Get affected model data count. There can be multiple data models existing
+     * from the given condition, return the count.
+     * 
+     * @param pDataReaderInstance
+     *            - instance(created on creation of the DataReader) of the data
+     *            reader class object
+     * 
+     * @param modelName
+     *            - affected ContextModel name
+     * 
+     * @return int - affected dataId count
+     */
+    public native int getModelDataCount(int pDataReaderInstance,
+            String modelName) throws Exception;
+
+    /**
+     * Get actual Context Model data
+     * 
+     * @param pDataReaderInstance
+     *            - instance(created on creation of the DataReader) of the data
+     *            reader class object
+     * 
+     * @param modelName
+     *            - affected ContextModel name
+     * 
+     * @param dataIndex
+     *            - affected dataId index
+     * 
+     * @return ModelData - affected ContextModel data reader
+     */
+    public native ModelData getModelData(int pDataReaderInstance,
+            String modelName, int dataIndex) throws Exception;
+
+    /**
+     * To register the report receiver to receive messages
+     * 
+     * @param reportReceiver
+     *            - report receiver instance
+     * 
+     * @return void
+     */
+    public native void registerReportReceiver(IReportReceiver reportReceiver);
 }
\ No newline at end of file
index c963a25..2679850 100644 (file)
@@ -1,28 +1,95 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    DataReader.java
+ *
+ * @brief    This file provides a class that represents context model data package's reader
+ *
+ */
+
 package org.iotivity.service.ssm;
 
 import java.util.List;
 
-public class DataReader {
-
-       private int pDataReaderInstance;
-       
-       public DataReader(int dataReaderInstance)
-       {
-               pDataReaderInstance = dataReaderInstance;
-       }
-       
-       public List<String> GetAffectedModels()
-       {
-               return CoreController.getInstance().GetAffectedModels(pDataReaderInstance);
-       }
-       
-       public int GetModelDataCount(String modelName)
-       {
-               return CoreController.getInstance().GetModelDataCount(pDataReaderInstance, modelName);
-       }
-       
-       public ModelData GetModelData(String modelName, int dataIndex)
-       {
-               return CoreController.getInstance().GetModelData(pDataReaderInstance, modelName, dataIndex);
-       }
+/**
+* @class    DataReader
+* @brief     This class represents context model data package's reader and contains
+*           API's to be used by IQueryEngineEvent listeners to handle the model data.
+*
+*/
+public class DataReader
+{
+
+        private int pDataReaderInstance;
+
+        public DataReader(int dataReaderInstance)
+        {
+            pDataReaderInstance = dataReaderInstance;
+        }
+
+        /**
+         * Get affected context models. The CQL(context query language) can specify
+         *       multiple ContextModels for retrieving data so a list of string of affected
+         *       context models is returned
+         *
+         * @return List<String> - affected ContextModel list
+         * 
+         */
+        public List<String> getAffectedModels()
+        {
+            return CoreController.getInstance().getAffectedModels(
+                       pDataReaderInstance);
+        }
+
+        /**
+         * Get affected model data count. There can be multiple data models existing
+         *       from the given condition, return the count.
+         *
+         * @param modelName 
+         *              - affected ContextModel name
+         *
+         * @return int  - affected dataId count
+         * 
+         */
+        public int getModelDataCount(String modelName) throws Exception
+        {
+            return CoreController.getInstance().getModelDataCount(
+                pDataReaderInstance, modelName);
+        }
+
+        /**
+         * Get actual Context Model data
+         *
+         * @param modelName 
+         *              - affected ContextModel name
+         *
+         * @param dataIndex 
+         *              - affected dataId index
+         *
+         * @return ModelData  - affected ContextModel data reader
+         * 
+         */
+        public ModelData getModelData(String modelName, int dataIndex)
+        throws Exception
+        {
+            return CoreController.getInstance().getModelData(pDataReaderInstance,
+            modelName, dataIndex);
+        }
 }
index 3dd46bf..30e7e1b 100644 (file)
@@ -1,5 +1,83 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    IQueryEngineEvent.java
+ *
+ * @brief    This file provides a class that represents Query Engine's event that contains results
+ *
+ */
+
 package org.iotivity.service.ssm;
 
-public interface IQueryEngineEvent {
-       public void OnQueryEngineEvent(int cqid, DataReader result);
+    /**
+    * @class    IQueryEngineEvent
+    * @brief    This is an interface class for sample applications.It handles the response from
+    *            SSMCore received asynchronously on making a query with the SSMCore.
+    *            Application should implement the pure virtual function OnQueryEngineEvent.
+    *            The Application should call registerQuery() and add a listener.
+    *
+    *<pre>
+    Sample code :
+
+        int cqid = SoftSensorManager.registerQuery(edtQuery.getText().toString(), mQueryEngineEventListener);
+        mRunningQueries.add(cqid);
+
+        private IQueryEngineEvent mQueryEngineEventListener = new IQueryEngineEvent()
+        {
+        @Override
+        public void onQueryEngineEvent(int cqid, DataReader result)
+        {
+                List<String> models = result.GetAffectedModels();
+
+                for(String modelName : models)
+                {
+                    int dataCount = result.GetModelDataCount(modelName);
+                    for(int i=0; i < dataCount; i++)
+                    {
+                        ModelData modelData = result.GetModelData(modelName, i);
+                        for(int j=0; j < modelData.GetPropertyCount(); j++)
+                        {
+                            PrintLog("Name: " + modelData.GetPropertyName(j) +
+                                " Value: " + modelData.GetPropertyValue(j));
+                        }
+                    }
+                }
+        }
+        };</pre>
+    */
+public abstract class IQueryEngineEvent
+{
+
+        /**
+         * Transmits result of SSMCore to Application layer
+         *     This abstract method needs to be implemeted by application
+         *     as a precondition for query engine implementation.
+         *
+         * @param cqid 
+         *              - ContextQuery ID of the registered query
+         *
+         * @param result 
+         *              - data received from SSMCore
+         *
+         * @return void
+         *
+         */
+        public abstract void onQueryEngineEvent(int cqid, DataReader result);
 }
\ No newline at end of file
index 9a8aec1..090f823 100644 (file)
@@ -1,5 +1,51 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    IReportReceiver.java
+ *
+ * @brief    This file provides a class for a set of APIs to handle response on receiving
+ * message
+ *
+ */
+
 package org.iotivity.service.ssm;
 
-public interface IReportReceiver {
-       public void OnMessageReceived(String tag, String msg);
-}
+/**
+ * @class IReportReceiver
+ * @brief This class provides an API to handle the report Message.
+ *      The application should implement the pure virtual function OnMessageReceived.
+ *
+ */
+public abstract class IReportReceiver
+{
+        /**
+         * Handle response on receiving message
+         *       This abstract method needs to be implemeted by application
+         *        as a precondition for query engine implementation.
+         *
+         * @param tag - tag from SSMCore
+         *
+         * @param msg - received message
+         *
+         * @return void
+         * 
+         */
+        public abstract void onMessageReceived(String tag, String msg);
+}
\ No newline at end of file
index c43e1df..c276f83 100644 (file)
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    ModelData.java
+ *
+ * @brief    This file provides a class for Model data operations
+ * message
+ *
+ */
+
 package org.iotivity.service.ssm;
 
-public class ModelData {
-       
-       private int pIModelDataInstance;
-       
-       public ModelData(int iModelDataInstance)
-       {
-               pIModelDataInstance = iModelDataInstance;
-       }
-       
-       public int GetDataId()
-       {
-               return CoreController.getInstance().GetDataId(pIModelDataInstance);
-       }
-       
-       public int GetPropertyCount()
-       {
-               return CoreController.getInstance().GetPropertyCount(pIModelDataInstance);
-       }
-       
-       public String GetPropertyName(int propertyIndex)
-       {
-               return CoreController.getInstance().GetPropertyName(pIModelDataInstance, propertyIndex);
-       }
-       
-       public String GetPropertyValue(int propertyIndex)
-       {
-               return CoreController.getInstance().GetPropertyValue(pIModelDataInstance, propertyIndex);
-       }
+/**
+ * @class    ModelData
+ * @brief    This class provides a set of API for DataReader class to handle the data
+ *         received by IQueryEngineEvent listeners from SSMCore
+ *
+ */
+public class ModelData
+{
+
+        private int pIModelDataInstance;
+
+        public ModelData(int iModelDataInstance)
+        {
+            pIModelDataInstance = iModelDataInstance;
+        }
+
+        /**
+         * Get the affected DataId. ContextModel has plenty of data so returned data is matched 
+         *               from given condition which in this case is the model data object instance
+         *
+         * @return int - the affected DataId
+         * 
+         */
+        public int getDataId()
+        {
+            return CoreController.getInstance().getDataId(pIModelDataInstance);
+        }
+
+        /**
+         * ContextModel has at least one property that contains data \n
+         *           property is described from its specification.
+         *
+         * @return int - number of properties
+         * 
+         */
+        public int getPropertyCount()
+        {
+            return CoreController.getInstance().getPropertyCount(
+                       pIModelDataInstance);
+        }
+
+        /**
+         * Retrieve the name of the property using the given index
+         *
+         * @param propertyIndex 
+         *               - index of property to read
+         *
+         * @return String - property name
+         * 
+         */
+        public String getPropertyName(int propertyIndex)
+        {
+            return CoreController.getInstance().getPropertyName(
+                       pIModelDataInstance, propertyIndex);
+        }
+
+        /**
+         * Retrieve the value of the property using the given index
+         *
+         * @param propertyIndex 
+         *               - index of property to read
+         *
+         * @return String - property value
+         * 
+         */
+        public String getPropertyValue(int propertyIndex)
+        {
+            return CoreController.getInstance().getPropertyValue(
+                       pIModelDataInstance, propertyIndex);
+        }
 }
\ No newline at end of file
index a14e640..348e51d 100644 (file)
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    QueryEngine.java
+ *
+ * @brief    This file provides a class that represents main interface of Query Engine
+ *
+ */
+
 package org.iotivity.service.ssm;
 
+/**
+* @class    QueryEngine
+* @brief     This class represents main interface of Query Engine to interact with
+*           SSMCore with in turn interacts with the application.
+*           QueryEninge class forms the database from the base to respond to
+*           queries from SSMCore.
+*
+*/
 public class QueryEngine
 {
-       private int pQueryEngineInstance;
-       
-       public QueryEngine(int queryEngineInstance)
-       {
-               pQueryEngineInstance = queryEngineInstance;
-       }
-       
-       public int GetQueryEngineInstance()
-       {
-               return pQueryEngineInstance;
-       }
-       
-       public int ExecuteContextQuery(String contextQuery)
-       {
-               return CoreController.getInstance().ExecuteContextQuery(pQueryEngineInstance, contextQuery);
-       }
-       
-       public void RegisterQueryEvent(IQueryEngineEvent queryEngineEvent)
-       {
-               CoreController.getInstance().RegisterQueryEvent(pQueryEngineInstance, queryEngineEvent);
-       }
-       
-       public void KillContextQuery(int cqid)
-       {
-               CoreController.getInstance().KillContextQuery(pQueryEngineInstance, cqid);
-       }
+        private int pQueryEngineInstance;
+
+        public QueryEngine(int queryEngineInstance)
+        {
+            pQueryEngineInstance = queryEngineInstance;
+        }
+
+        /**
+         * Obtain the instance value of the called query engine object,
+         *          this value is set on creation of the QueryEngine object
+         *
+         * @return int - Instance of the query engine object, set on object's creation
+         * 
+         */
+        public int getQueryEngineInstance()
+        {
+            return pQueryEngineInstance;
+        }
+
+        /**
+         * Execute the query with the QueryEngine and return ContextQuery ID
+         *            for the query
+         *
+         * @param contextQuery 
+         *               - query string to be executed
+         *
+         * @return int - ID of context query executed
+         * 
+         */
+        public int executeContextQuery(String contextQuery) throws Exception
+        {
+            return CoreController.getInstance().executeContextQuery(
+                pQueryEngineInstance, contextQuery);
+        }
+
+        /**
+         * Register QueryEngineEvent to QueryEngine
+         *
+         * @param queryEngineEvent 
+         *               - the event class to receive QueryEngine events
+         *
+         * @return void
+         * 
+         */
+        public void registerQueryEvent(IQueryEngineEvent queryEngineEvent)
+        {
+            CoreController.getInstance().registerQueryEvent(pQueryEngineInstance,
+                    queryEngineEvent);
+        }
+
+        /**
+         * Kill the registered ContextQuery corresponding to the  to cqid
+         *
+         * @param cqid 
+         *              - ContextQuery ID of the query to be terminated
+         *
+         * @return void
+         * 
+         */
+        public void killContextQuery(int cqid) throws Exception
+        {
+            CoreController.getInstance().killContextQuery(pQueryEngineInstance,
+            cqid);
+        }
 }
\ No newline at end of file
index 8169548..93f1d45 100644 (file)
@@ -1,3 +1,32 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    SSMInterface.java
+ *
+ * @brief    This file gives description of SSMInterface class and its utility functions.
+ *         This is the interface between an application and the query engine.
+ *         SSMinterface makes desired queries in form of CQL(Context Query Language)
+ *         to the query engine and passes the returned result obtained in form of callback
+ *         back to the application.
+ */
+
 package org.iotivity.service.ssm;
 
 import java.util.ArrayList;
@@ -7,93 +36,214 @@ import java.util.Map;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
-public class SSMInterface {
-       private class QueryEngineEventReceiver implements IQueryEngineEvent
-       {
-        private Lock                                                           mMtxListener = new ReentrantLock();
-               private Map<Integer, IQueryEngineEvent>         mMapListener = new HashMap<Integer, IQueryEngineEvent>();
-               
-               public void OnQueryEngineEvent(int cqid, DataReader result)
-               {
-                       mMtxListener.lock();
-
-                       mMapListener.get(cqid).OnQueryEngineEvent(cqid, result);
-            
-                       mMtxListener.unlock();
-               }
-               void lockListener()
+/**
+ * @class SSMInterface
+ * @brief This class provides a set of APIs to manage the SSM framework
+ *      This class sits in between the application and query engine and acts
+ *      as an interface between them. SSMinterface makes desired queries in form of CQL(Context Query Language)
+ *      to the query engine and passes the returned result obtained in form of callback
+ *      back to the application
+ */
+public class SSMInterface
+{
+
+        /**
+         * @class QueryEngineEventReceiver
+         * @brief This class provides a set of APIs to handle query engine events
+         *          related to soft sensor Interface framework.
+         *
+         *
+         */
+        private class QueryEngineEventReceiver extends IQueryEngineEvent
+        {
+                private Lock mMtxListener = new ReentrantLock();
+                private Map<Integer, IQueryEngineEvent> mMapListener = new HashMap<Integer, IQueryEngineEvent>();
+
+                /**
+                 * Transmits result of SSMCore to Application layer
+                 *     This abstract method needs to be implemeted by application
+                 *     as a precondition for query engine implementation.
+                 *
+                 * @param cqid 
+                 *              - ContextQuery ID of the registered query
+                 *
+                 * @param result 
+                 *              - data received from SSMCore
+                 *
+                 * @return void
+                 *
+                 */
+                public void onQueryEngineEvent(int cqid, DataReader result)
+                {
+                    mMtxListener.lock();
+
+                    mMapListener.get(cqid).onQueryEngineEvent(cqid, result);
+
+                    mMtxListener.unlock();
+                }
+
+                /**
+                 * To lock QueryEngineEventReceiver object to execute a query atomically,
+                 *         this is done to provide synchronization in case of multiple queries.
+                 *
+                 * @return void
+                 * 
+                 */
+                void lockListener()
+                {
+                    mMtxListener.lock();
+                }
+
+                /**
+                 * release the QueryEngineEventReceiver object
+                 *
+                 * @return void
+                 * 
+                 */
+                void unlockListener()
+                {
+                    mMtxListener.unlock();
+                }
+
+                /**
+                 * add listener to receive response for the registered query with SSMCore.
+                 *     Listen for callbacks from SSMCore.
+                 *     This is also a precondition for implementing query engine object.
+                 *
+                 * @param cqid 
+                 *              - ContextQuery ID of the registered query
+                 *
+                 * @param engineEvent 
+                 *              - query engine's event that contains the results
+                 *
+                 * @return void
+                 */
+                void addListener(int cqid, IQueryEngineEvent engineEvent)
+                {
+                    mMapListener.put(cqid, engineEvent);
+                }
+
+                /**
+                 * Remove listener for a query on unregistering it
+                 *
+                 * @param cqid 
+                 *              - ContextQuery ID of the registered query
+                 *
+                 * @return void
+                 * 
+                 */
+                void removeListener(int cqid)
+                {
+                    mMapListener.remove(cqid);
+                }
+        };
+
+        private CoreController mSSMCore = null;
+        private QueryEngine mQueryEngine = null;
+        private QueryEngineEventReceiver mQueryEngineEventListenerReceiver = new QueryEngineEventReceiver();
+        private List<Integer> mRunningCQLs = new ArrayList<Integer>();
+
+        public SSMInterface()
         {
-                       mMtxListener.lock();
         }
 
-        void unlockListener()
+        /**
+         * Starts the framework that allows other devices to discover and communicate
+         *     with the SSMCore and underlying query engine.
+         *
+         * @param initConfig 
+         *              - initial framework specifications
+         *
+         * @return void
+         * 
+         */
+        public void startSSMCore(String initConfig) throws Exception
         {
-               mMtxListener.unlock();
+            mSSMCore = CoreController.getInstance();
+            mSSMCore.initializeSSMCore(initConfig);
+            mSSMCore.startSSMCore();
+
+            mQueryEngine = mSSMCore.createQueryEngine();
+
+            mQueryEngine.registerQueryEvent(mQueryEngineEventListenerReceiver);
         }
 
-        void addListener(int cqid, IQueryEngineEvent engineEvent)
+        /**
+         * Stops the framework and terminate all communications.
+         *
+         * @return void
+         * 
+         */
+        public void stopSSMCore() throws Exception
         {
-               mMapListener.put(cqid, engineEvent);
+            mQueryEngine.registerQueryEvent(null);
+            mSSMCore.releaseQueryEngine(mQueryEngine);
+            mQueryEngineEventListenerReceiver = null;
+            mQueryEngine = null;
+            mSSMCore.stopSSMCore();
+            mSSMCore.terminateSSMCore();
+        }
+
+        /**
+         * Register the query and execute statement with the query engine
+         *     and add listener for the registered query so as to get response data.
+         *     After success response message for registration, SSMCore sends an
+         *     event to the client, if the specified condtions in the query is satisfied.
+         *
+         * @param contextQuery 
+         *             - query for requesting data
+         *
+         * @param listener 
+         *             - listener for receiving response data of the query
+         *
+         * @return int - ContextQuery ID
+         * 
+         */
+        public int registerQuery(String contextQuery, IQueryEngineEvent listener)
+        throws Exception
+        {
+            int cqid = 0;
+
+            try {
+                mQueryEngineEventListenerReceiver.lockListener();
+                cqid = mQueryEngine.executeContextQuery(contextQuery);
+                mQueryEngineEventListenerReceiver.addListener(cqid, listener);
+                mRunningCQLs.add(cqid);
+            }
+            catch (Exception e)
+            {
+                throw e;
+            } finally {
+                mQueryEngineEventListenerReceiver.unlockListener();
+            }
+
+            return cqid;
         }
 
-        void removeListener(int cqid)
+        /**
+         * unregister a registered query using its query ID. The query corresponding
+         *      to the cqid will be terminated and removes listener for the given query
+         *      The SSMCore will not send any callbacks after successful unregistration.
+         *
+         *
+         * @param cqid - ContextQuery ID of the query to be unregistered
+         *
+         * @return void
+         * 
+         */
+        public void unregisterQuery(int cqid) throws Exception
         {
-               mMapListener.remove(cqid);
+            try {
+                mQueryEngineEventListenerReceiver.lockListener();
+                mQueryEngine.killContextQuery(cqid);
+                mQueryEngineEventListenerReceiver.removeListener(cqid);
+                mRunningCQLs.remove((Object) cqid);
+            }
+            catch (Exception e)
+            {
+                throw e;
+            } finally {
+                mQueryEngineEventListenerReceiver.unlockListener();
+            }
         }
-       };
-       
-       private CoreController                          mSSMCore = null;
-       private QueryEngine                                     mQueryEngine = null;
-       private QueryEngineEventReceiver        mQueryEngineEventListenerReceiver = new QueryEngineEventReceiver();
-       private List<Integer>                           mRunningCQLs = new ArrayList<Integer>();
-       
-       public SSMInterface()
-       {               
-       }
-       
-       public void startSSMCore(String initConfig) throws Exception
-       {
-               mSSMCore = CoreController.getInstance();
-        mSSMCore.InitializeSSMCore(initConfig);
-        mSSMCore.StartSSMCore();
-        
-        mQueryEngine = mSSMCore.CreateQueryEngine();
-        
-        if(mQueryEngine == null)
-               throw new Exception("Create Query Engine failed");
-        
-        mQueryEngine.RegisterQueryEvent(mQueryEngineEventListenerReceiver);
-       }
-       
-       public void stopSSMCore()
-       {
-               mQueryEngine.RegisterQueryEvent(null);
-               mSSMCore.ReleaseQueryEngine(mQueryEngine);
-               mQueryEngineEventListenerReceiver = null;
-               mQueryEngine = null;
-               mSSMCore.StopSSMCore();
-               mSSMCore.TerminateSSMCore();
-       }
-       
-       public int registerQuery(String contextQuery, IQueryEngineEvent listener)
-       {
-               int cqid;
-               
-               mQueryEngineEventListenerReceiver.lockListener();
-               cqid = mQueryEngine.ExecuteContextQuery(contextQuery);
-               mQueryEngineEventListenerReceiver.addListener(cqid, listener);
-               mRunningCQLs.add(cqid);
-               mQueryEngineEventListenerReceiver.unlockListener();
-               
-               return cqid;
-       }
-       
-       public void unregisterQuery(int cqid)
-       {
-               mQueryEngineEventListenerReceiver.lockListener();
-               mQueryEngine.KillContextQuery(cqid);
-               mQueryEngineEventListenerReceiver.removeListener(cqid);
-               mRunningCQLs.remove(cqid);
-               mQueryEngineEventListenerReceiver.unlockListener();
-       }
 }
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SSMCore/build/linux/Makefile b/service/soft-sensor-manager/SSMCore/build/linux/Makefile
deleted file mode 100644 (file)
index 01d6453..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
--include ../../../build/linux/root_path.inc
--include ../../../build/linux/environment.mk
-
-BOOST=${BOOST_BASE}
-SRC_PATH=../../src
-INC_PATH=../../include
-RST_NAME=release
-
-# Insert your project name.
-TARGET=${SSMCORE_LIB}
-EXCLUDE_LIST=SSMCore_JNI.cpp
-
-# C++ type Compile Flag define.
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
-CXX_INC=-I${INC_PATH}/ -I${SRC_PATH}/ -I${IOT_BASE}/include/ -I${IOT_LOG_DIR}/include/ -I${IOT_BASE}/csdk/stack/include -I${IOT_BASE}/csdk/ocsocket/include -I${IOT_BASE}/csdk/ocrandom/include -I${IOT_BASE}/csdk/logger/include -I${BOOST}
-CXX_LIB=-L""
-
-CXX_SRCPATH=${wildcard ${SRC_PATH}/**/*.cpp}
-CXX_SRCPATH+=${wildcard ${SRC_PATH}/*.cpp}
-CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
-CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
-CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
-
-# C type Compile Flag define.
-GCC=gcc
-GCC_FLAGS=-Wall -pthread -DLINUX -ldl
-GCC_INC=-I../../ -I${INC_PATH}/ -I${IOT_BASE}/include/ -I${IOT_BASE}/csdk/stack/include -I${IOT_BASE}/csdk/ocsocket/include -I${IOT_BASE}/csdk/ocrandom/include -I${IOT_BASE}/csdk/logger/include -I${BOOST} -I${SRC_PATH} -I${SRC_PATH}/Common -I${SRC_PATH}/QueryProcessor -I${SRC_PATH}/SensorProcessor -I${SRC_PATH}/SSMInterface
-
-GCC_SRCPATH=${wildcard ${SRC_PATH}/**/*.c}
-GCC_SRCLIST=${notdir ${GCC_SRCPATH}}
-GCC_USESRCS=${filter-out ${EXCLUDE_LIST}, ${GCC_SRCLIST}}
-GCC_OBJLIST=${GCC_USESRCS:.c=.o}
-
-# Linker FLAGS define.
-LD_FLAGS=-std=c++0x -Wall -DLINUX
-GAR=ar
-# LD_LIB=${IOT_RELEASE}/${IOT_LIB} ${IOT_CSDK_RELEASE}/${IOT_CSDK_LIB} ${IOT_LOG_DIR}/lib/${IOT_LOG_LIB} -lpthread -ldl 
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job ${TARGET} post_job
-
-pre_job:
-       @echo " " 
-       @echo "---------- SSMCore Build Begin. -------------" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-       @echo "${MODEL_DIR}"
-       
-${TARGET}: ${GCC_OBJLIST} ${CXX_OBJLIST}
-       # $(CXX) $(LD_FLAGS) -o ./${RST_NAME}/$@ $^ ${LD_LIB}           
-       ${GAR} -r ./${RST_NAME}/$@  ./*.o
-       @echo " "
-
-%.o : ${SRC_PATH}/**/%.c 
-       ${GCC} ${GCC_FLAGS} -c $< ${GCC_INC} -o $@
-       @echo " " 
-               
-%.o : ${SRC_PATH}/**/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o $@
-       @echo " " 
-       
-%.o : ${SRC_PATH}/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o $@
-       @echo " "
-
-post_job:
-       @echo " " 
-       cp -Rdp ${INC_PATH}/SSMInterface.h ${FD_SDK}/include/
-       cp -Rdp ./${RST_NAME}/${TARGET} ${OUTPUTS_DIR}/
-       cp -Rdp ${INC_PATH}/SSMInterface.h ${OUTPUTS_DIR}/
-       cp -Rdp ${SRC_PATH}/SSMInterface/SSMModelDefinition.h ${OUTPUTS_DIR}/
-       @echo "---------------- SSMCore Build Successful. ---------------"
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " " 
-
-
-clean:
-       rm -f -v *.o ${TARGET}
-       rm -rf ./${RST_NAME}
-       
index 0085b3b..866d578 100644 (file)
@@ -1,3 +1,29 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+/**
+* @file
+*
+* This file defines basic interface of Soft Sensor Manager.
+*/
+
 #ifndef _SSMInterface_H_
 #define _SSMInterface_H_
 
@@ -13,6 +39,9 @@ namespace OIC
         , SSM_E_POINTER
         , SSM_E_OUTOFMEMORY
         , SSM_E_FAIL
+        , SSM_E_NOTINIT
+        , SSM_E_INITIALIZED
+        , SSM_E_INVALIDXML
         , SSM_E_NOINTERFACE
         , SSM_E_NOTIMPL
     };
@@ -21,75 +50,50 @@ namespace OIC
     * @class    IModelData
     * @brief    This class represents context model data package
     *
-    * @see
     */
     class IModelData
     {
         public:
             /**
-            * @fn     getDataId
-            * @brief Get affected DataId. ContextModel has plenty of data so \n
+            * Get affected DataId. ContextModel has plenty of data so \n
             *         returned data is matched from given condition
             *
-            * @param None
-            *
-            * @return int
-            * @warning
-            * @exception
-            * @see
+            * @return int - the affected DataId
             */
             virtual int getDataId() = 0;
 
             /**
-            * @fn     GetPropertyCount
-            * @brief ContextModel has at least one property that contains data \n
+            * ContextModel has at least one property that contains data \n
             *         property is described from its specification.
             *
-            * @param None
-            *
-            * @return int
-            * @warning
-            * @exception
-            * @see
+            * @return int - number of properties
             */
             virtual int getPropertyCount() = 0;
 
             /**
-            * @fn     getPropertyName
-            * @brief Retrieve propertyName
+            * Retrieve propertyName
             *
-            * @param [in] int propertyIndex - index of property to read
+            * @param propertyIndex - index of property to read
             *
-            * @return std::string
-            * @warning
-            * @exception
-            * @see
+            * @return std::string - property name
             */
             virtual std::string getPropertyName(int propertyIndex) = 0;
 
             /**
-            * @fn     getPropertyValue
-            * @brief Retrieve propertyValue
+            * Retrieve propertyValue
             *
-            * @param [in] int propertyIndex - index of property to read
+            * @param propertyIndex index of property to read
             *
-            * @return std::string
-            * @warning
-            * @exception
-            * @see
+            * @return std::string - property value
             */
             virtual std::string getPropertyValue(int propertyIndex) = 0;
 
             /**
-            * @fn     getPropertyValueByName
-            * @brief Retrieve propertyValue using given name
+            * Retrieve propertyValue using given name
             *
-            * @param [in] std::string propertyName - property name looking for
+            * @param propertyName - property name looking for
             *
-            * @return std::string
-            * @warning
-            * @exception
-            * @see
+            * @return std::string - property name
             */
             virtual std::string getPropertyValueByName(std::string propertyName) = 0;
         protected:
@@ -106,49 +110,35 @@ namespace OIC
     {
         public:
             /**
-            * @fn     getAffectedModels
-            * @brief Get affected ContextModels. The CQL can specify multiple ContextModels for retrieving data.
+            * Get affected ContextModels. The query can specify multiple ContextModels for retrieving data.
             *
-            * @param [in, out] std::vector<std::string> *pAffectedModels - affected ContextModel list
+            * @param pAffectedModels - affected ContextModel list
             *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT getAffectedModels(std::vector<std::string> *pAffectedModels) = 0;
 
             /**
-            * @fn     getModelDataCount
-            * @brief Get affected data count. There are multiple data can exist from given condition.
+            * Get affected data count. There are multiple data can exist from given condition.
             *
-            * @param [in] std::string modelName - affected ContextModel name
+            * @param modelName - affected ContextModel name
             *
-            * @param [in, out] int *pDataCount - affected dataId count
+            * @param pDataCount - affected dataId count
             *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT getModelDataCount(std::string modelName, int *pDataCount) = 0;
 
             /**
-            * @fn     getModelData
-            * @brief Get actual Context Model data
+            * Get actual Context Model data
             *
-            * @param [in] std::string modelName - affected ContextModel name
+            * @param modelName - affected ContextModel name
             *
+            * @param dataIndex - affected dataId index
             *
-            * @param [in] int dataIndex - affected dataId index
+            * @param ppModelData - affected ContextModel data reader
             *
-            *
-            * @param [out] IModelData **ppModelData - affected ContextModel data reader
-            *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT getModelData(std::string modelName, int dataIndex, IModelData **ppModelData) = 0;
         protected:
@@ -165,17 +155,13 @@ namespace OIC
     {
         public:
             /**
-            * @fn     onQueryEngineEvent
-            * @brief Transmit result of SSMCore to Application layer
+            * Transmit result of SSMCore to Application layer
             *
-            * @param [in] int cqid - entered ContextQuery ID
+            * @param cqid - entered ContextQuery ID
             *
-            * @param [in] IDataReader *pResult - result of SSMCore
+            * @param pResult - result of SSMCore
             *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
+            * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
             */
             virtual SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult) = 0;
         protected:
@@ -183,47 +169,41 @@ namespace OIC
     };
 
     /**
-    * @class    SSMInterface
-    * @brief    This class represents main class for querying Soft Sensors
+    * Initialize Soft sensor manager using given configuration information.
     *
-    * @see
+    * @param xmlDescription - specification described in XML
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
     */
-    class SSMInterface
-    {
-        public:
-            SSMInterface();
-            ~SSMInterface();
+    SSMRESULT InitializeSSM(std::string xmlDescription);
 
-            /**
-            * @fn     registerQuery
-            * @brief Execute ContextQuery and return ContextQuery ID
-            *
-            * @param [in] std::string queryString - query for requesting data
-            *
-            * @param [in] IQueryEngineEvent listener - listener for receiving data related to query
-            *
-            * @param [in, out] int &cqid - ID of ContextQuery
-            *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
-            */
-            SSMRESULT registerQuery(std::string queryString, IQueryEngineEvent *listener, int &cqid);
+    /**
+    * Terminates Soft sensor manager
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
+    */
+    SSMRESULT TerminateSSM();
 
-            /**
-            * @fn    unregisterQuery
-            * @brief unregister registered ContextQuery according to cqid
-            *
-            * @param [in] int cqid - Context query corresponding to the cqid will be terminated
-            *
-            * @return SSMRESULT
-            * @warning
-            * @exception
-            * @see
-            */
-            SSMRESULT unregisterQuery(int cqid);
-    };
+    /**
+    * Execute query and return ContextQuery ID
+    *
+    * @param queryString - query for requesting data
+    *
+    * @param listener - listener for receiving data related to query
+    *
+    * @param cqid - ID of ContextQuery
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
+    */
+    SSMRESULT RegisterQuery(std::string queryString, IQueryEngineEvent *listener, int &cqid);
 
+    /**
+    * Unregister registered query according to cqid
+    *
+    * @param cqid - Query corresponding to the cqid will be terminated
+    *
+    * @return SSMRESULT - return value of the API. Returns SSM_S_OK if success
+    */
+    SSMRESULT UnregisterQuery(int cqid);
 }
 #endif
\ No newline at end of file
index e0db5b2..250ace7 100644 (file)
@@ -89,7 +89,7 @@ class IContextRepository : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getSoftSensorList(OUT std::vector<ISSMResource *> *pSoftSensorList) = 0 ;
+        virtual SSMRESULT getSoftSensorList(std::vector<ISSMResource *> *pSoftSensorList) = 0 ;
 
         /**
         * @fn           getPrimitiveSensorList
@@ -109,7 +109,7 @@ class IContextRepository : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getPrimitiveSensorList(OUT std::vector<ISSMResource *> *pPrimitiveSensorList) = 0
+        virtual SSMRESULT getPrimitiveSensorList(std::vector<ISSMResource *> *pPrimitiveSensorList) = 0
                 ;
 
         /**
@@ -126,20 +126,21 @@ class IContextRepository : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT initRepository(IN std::string name, IN std::string type,
-                                         IN std::string pathSoftSensors, IN std::string pathDescription) = 0;
+        virtual SSMRESULT initRepository(std::string name, std::string type,
+                                         std::string pathSoftSensors, std::string pathDescription) = 0;
 
-        virtual SSMRESULT registerResourceFinderEvent(IN IResourceEvent *pResourceEvent) = 0;
+        virtual SSMRESULT registerResourceFinderEvent(IResourceEvent *pResourceEvent) = 0;
         virtual SSMRESULT startResourceFinder() = 0;
-        virtual SSMRESULT onResourceFound(IN ISSMResource *pSensor) = 0;
-        virtual SSMRESULT onResourceLost(IN ISSMResource *pSensor) = 0;
+        virtual SSMRESULT stopResourceFinder() = 0;
+        virtual SSMRESULT onResourceFound(ISSMResource *pSensor) = 0;
+        virtual SSMRESULT onResourceLost(ISSMResource *pSensor) = 0;
 
-        virtual SSMRESULT startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent) = 0;
-        virtual SSMRESULT stopObserveResource(IN ISSMResource *pSensor) = 0;
+        virtual SSMRESULT startObserveResource(ISSMResource *pSensor, IEvent *pEvent) = 0;
+        virtual SSMRESULT stopObserveResource(ISSMResource *pSensor) = 0;
 
-        virtual SSMRESULT loadSoftSensor(IN std::string softSensorName, IN ICtxDelegate *pDelegate,
-                                         OUT void **hSoftSensor) = 0;
-        virtual SSMRESULT unloadSoftSensor(IN void *hSoftSensor) = 0;
+        virtual SSMRESULT loadSoftSensor(std::string softSensorName, ICtxDelegate *pDelegate,
+                                         void **hSoftSensor) = 0;
+        virtual SSMRESULT unloadSoftSensor(void *hSoftSensor) = 0;
 };
 
 struct ModelProperty
@@ -183,7 +184,7 @@ class IEvaluationEngineEvent : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT onWatchModelData(IN int triggerId, IN int dataId) = 0;
+        virtual SSMRESULT onWatchModelData(int triggerId, int dataId) = 0;
 };
 
 static const OID OID_IEvaluationEngine = { 0x5a59a9f3, 0x7506, 0x4a3a, { 0xb9, 0x34, 0xcb, 0x51, 0xd, 0xb4, 0xed, 0x53 } };
@@ -237,9 +238,9 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT createModel(IN int parentModelId, IN const char *newModelName,
-                                      IN ModelPropertyVec *pModelDescs, OUT int *pModelId) = 0;
-        //virtual SSMRESULT GetModelSchema(IN int modelId, OUT ModelPropertyVec *pModelProperties) = 0;
+        virtual SSMRESULT createModel(int parentModelId, const char *newModelName,
+                                      ModelPropertyVec *pModelDescs, int *pModelId) = 0;
+        //virtual SSMRESULT GetModelSchema(int modelId, ModelPropertyVec *pModelProperties) = 0;
 
         /**
         * @fn     addModelData
@@ -256,8 +257,8 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT addModelData(IN int modelId, IN int parentModelId, IN int parentDataId,
-                                       IN ModelPropertyVec *pModelValues, OUT int *pDataId) = 0;
+        virtual SSMRESULT addModelData(int modelId, int parentModelId, int parentDataId,
+                                       ModelPropertyVec *pModelValues, int *pDataId) = 0;
 
         /**
         * @fn     updateModelData
@@ -272,10 +273,10 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT updateModelData(IN int modelId, IN int dataId,
-                                          IN ModelPropertyVec *pModelValues) = 0;
+        virtual SSMRESULT updateModelData(int modelId, int dataId,
+                                          ModelPropertyVec *pModelValues) = 0;
 
-        //virtual SSMRESULT DeleteModel(IN int modelId) = 0;
+        //virtual SSMRESULT DeleteModel(int modelId) = 0;
 
         /**
         * @fn     deleteModelData
@@ -289,9 +290,9 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT deleteModelData(IN int modelId, IN int dataId) = 0;
+        virtual SSMRESULT deleteModelData(int modelId, int dataId) = 0;
 
-        //virtual SSMRESULT GetModelId(IN const char *modelName, OUT int *pModelId) = 0;
+        //virtual SSMRESULT GetModelId(const char *modelName, int *pModelId) = 0;
 
         /**
         * @fn     getModelData
@@ -306,8 +307,8 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getModelData(IN int modelId, IN int dataId,
-                                       OUT ModelPropertyVec *pModelProperties) = 0;
+        virtual SSMRESULT getModelData(int modelId, int dataId,
+                                       ModelPropertyVec *pModelProperties) = 0;
 
         /**
         * @fn     getModelDataSet
@@ -324,8 +325,8 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getModelDataSet(IN int modelId, IN int startIndex, IN int count,
-                                          OUT std::vector<ModelPropertyVec> *pDataSet, OUT int *pLastIndex) = 0;
+        virtual SSMRESULT getModelDataSet(int modelId, int startIndex, int count,
+                                          std::vector<ModelPropertyVec> *pDataSet, int *pLastIndex) = 0;
 
         /**
         * @fn     getConditionedModelData
@@ -340,8 +341,8 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getConditionedModelData(IN int modelId, IN ModelConditionVec *pModelConditions,
-                OUT IntVec *pDataIds) = 0;
+        virtual SSMRESULT getConditionedModelData(int modelId, ModelConditionVec *pModelConditions,
+                IntVec *pDataIds) = 0;
 
         /**
         * @fn     watchModelData
@@ -357,8 +358,8 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT watchModelData(IN int modelId, IN ModelConditionVec *pModelConditions,
-                                         IN IEvaluationEngineEvent *pEvaluationEngineEvent, OUT int *pTriggerId) = 0;
+        virtual SSMRESULT watchModelData(int modelId, ModelConditionVec *pModelConditions,
+                                         IEvaluationEngineEvent *pEvaluationEngineEvent, int *pTriggerId) = 0;
 
         /**
         * @fn     dropWatchModelData
@@ -371,7 +372,7 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT dropWatchModelData(IN int triggerId) = 0;
+        virtual SSMRESULT dropWatchModelData(int triggerId) = 0;
 
         /**
         * @fn     getParentDataId
@@ -387,8 +388,8 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getParentDataId(IN int modelId, IN int dataId, IN int parentModelId,
-                                          OUT int *pParentDataId) = 0;
+        virtual SSMRESULT getParentDataId(int modelId, int dataId, int parentModelId,
+                                          int *pParentDataId) = 0;
 
         /**
         * @fn     getChildDataId
@@ -404,13 +405,13 @@ class IEvaluationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getChildDataId(IN int modelId, IN int dataId, IN int childModelId,
-                                         OUT IntVec *pChildDataIds) = 0;
+        virtual SSMRESULT getChildDataId(int modelId, int dataId, int childModelId,
+                                         IntVec *pChildDataIds) = 0;
 
         //For decision tree
-        //virtual SSMRESULT GetPathToRoot(IN int currentModelId, OUT IntVec *pPath) = 0;
-        //virtual SSMRESULT GetModelHierarchy(IN int rootModelId, OUT StringVec *pPath) = 0;
-        //virtual SSMRESULT GetDataHierarchy(IN int rootModelId, IN int dataId, OUT StringVec *pPath) = 0;
+        //virtual SSMRESULT GetPathToRoot(int currentModelId, IntVec *pPath) = 0;
+        //virtual SSMRESULT GetModelHierarchy(int rootModelId, StringVec *pPath) = 0;
+        //virtual SSMRESULT GetDataHierarchy(int rootModelId, int dataId, StringVec *pPath) = 0;
 };
 
 /**
@@ -434,7 +435,7 @@ class IConditionedModelEvent
         * @exception
         * @see
         */
-        virtual SSMRESULT onConditionedModelTriggered(IN int triggerId) = 0;
+        virtual SSMRESULT onConditionedModelTriggered(int triggerId) = 0;
         virtual ~IConditionedModelEvent() {};
 };
 
@@ -462,7 +463,7 @@ class IConditionedModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getBaseContextModel(OUT IContextModel **ppBaseContextModel) = 0;
+        virtual SSMRESULT getBaseContextModel(IContextModel **ppBaseContextModel) = 0;
 
         /**
         * @fn     registerConditionedModelEvent
@@ -475,7 +476,7 @@ class IConditionedModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT registerConditionedModelEvent(IN IConditionedModelEvent *pConditionedModelEvent) =
+        virtual SSMRESULT registerConditionedModelEvent(IConditionedModelEvent *pConditionedModelEvent) =
             0;
 
         /**
@@ -489,7 +490,7 @@ class IConditionedModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT activateTrigger(OUT int *pTriggerId) = 0;
+        virtual SSMRESULT activateTrigger(int *pTriggerId) = 0;
 
         /**
         * @fn     deactivateTrigger
@@ -528,7 +529,7 @@ class IConditionedModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getAffectedData(OUT IntVec *pDataIds) = 0;
+        virtual SSMRESULT getAffectedData(IntVec *pDataIds) = 0;
 
         /**
         * @fn     getWatchCondition
@@ -541,7 +542,7 @@ class IConditionedModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getWatchCondition(OUT ModelConditionVec *pModelConditions) = 0;
+        virtual SSMRESULT getWatchCondition(ModelConditionVec *pModelConditions) = 0;
 };
 
 static const OID OID_IConditionedQueryResult = { 0x4a24e85b, 0x8903, 0x4cf5, { 0x88, 0x7b, 0x65, 0xc2, 0xc3, 0x9e, 0x42, 0xfd } };
@@ -580,8 +581,8 @@ class IConditionedQueryResult : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getConditionedContextModel(IN unsigned int conditionedModelIndex,
-                OUT IConditionedModel **ppConditionedModel) = 0;
+        virtual SSMRESULT getConditionedContextModel(unsigned int conditionedModelIndex,
+                IConditionedModel **ppConditionedModel) = 0;
 };
 
 /**
@@ -605,8 +606,8 @@ class IConditionedQueryEvent
         * @exception
         * @see
         */
-        virtual SSMRESULT onConditionedQueryEvent(IN int userTriggerId,
-                IN IConditionedQueryResult *pConditionedQueryResult) = 0;
+        virtual SSMRESULT onConditionedQueryEvent(int userTriggerId,
+                IConditionedQueryResult *pConditionedQueryResult) = 0;
         virtual ~IConditionedQueryEvent() {};
 };
 
@@ -632,7 +633,7 @@ class IConditionedQuery : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT registerConditionedModel(IN IConditionedModel *pConditionedModel) = 0;
+        virtual SSMRESULT registerConditionedModel(IConditionedModel *pConditionedModel) = 0;
 
         /**
         * @fn     activateTriggers
@@ -645,7 +646,7 @@ class IConditionedQuery : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT activateTriggers(IN int userTriggerId) = 0;
+        virtual SSMRESULT activateTriggers(int userTriggerId) = 0;
 
         /**
         * @fn     deactivateTriggers
@@ -671,7 +672,7 @@ class IConditionedQuery : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getConditionedQueryResult(OUT IConditionedQueryResult **ppConditionedQueryResult)
+        virtual SSMRESULT getConditionedQueryResult(IConditionedQueryResult **ppConditionedQueryResult)
             = 0;
 
         /**
@@ -755,8 +756,8 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getParentDataId(IN int dataId, IN IContextModel *pParentModel,
-                                          OUT int *pParentDataId) = 0;
+        virtual SSMRESULT getParentDataId(int dataId, IContextModel *pParentModel,
+                                          int *pParentDataId) = 0;
 
         /**
         * @fn     getChildDataId
@@ -771,8 +772,8 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getChildDataId(IN int dataId, IN IContextModel *pChildModel,
-                                         OUT IntVec *pPath) = 0;
+        virtual SSMRESULT getChildDataId(int dataId, IContextModel *pChildModel,
+                                         IntVec *pPath) = 0;
 
         /**
         * @fn     activate
@@ -786,7 +787,7 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT activate(IN ActivationType activationType, IN int targetDeviceDataId) = 0;
+        virtual SSMRESULT activate(ActivationType activationType, int targetDeviceDataId) = 0;
 
         /**
         * @fn     deactivate
@@ -801,8 +802,8 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT deactivate(IN ActivationType activationType, IN int targetDeviceDataId) = 0;
-        //virtual SSMRESULT GetModelSchema(OUT ModelPropertyVec *pModelProperties) = 0;
+        virtual SSMRESULT deactivate(ActivationType activationType, int targetDeviceDataId) = 0;
+        //virtual SSMRESULT GetModelSchema(ModelPropertyVec *pModelProperties) = 0;
 
         /**
         * @fn     addModelData
@@ -817,8 +818,8 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT addModelData(IN int parentDataId, IN ModelPropertyVec *pData,
-                                       OUT int *pDataId) = 0;
+        virtual SSMRESULT addModelData(int parentDataId, ModelPropertyVec *pData,
+                                       int *pDataId) = 0;
 
         /**
         * @fn     updateModelData
@@ -832,7 +833,7 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT updateModelData(IN int dataId, IN ModelPropertyVec *pData) = 0;
+        virtual SSMRESULT updateModelData(int dataId, ModelPropertyVec *pData) = 0;
 
         /**
         * @fn     deleteModelData
@@ -845,7 +846,7 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT deleteModelData(IN int dataId) = 0;
+        virtual SSMRESULT deleteModelData(int dataId) = 0;
 
         /**
         * @fn     getModelData
@@ -859,7 +860,7 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getModelData(IN int dataId, OUT ModelPropertyVec *pData) = 0;
+        virtual SSMRESULT getModelData(int dataId, ModelPropertyVec *pData) = 0;
 
         /**
         * @fn     getModelDataSet
@@ -875,8 +876,8 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getModelDataSet(IN int startIndex, IN int count,
-                                          OUT std::vector<ModelPropertyVec> *pDataSet, OUT int *pLastIndex) = 0;
+        virtual SSMRESULT getModelDataSet(int startIndex, int count,
+                                          std::vector<ModelPropertyVec> *pDataSet, int *pLastIndex) = 0;
 
         /**
         * @fn     createConditionedModel
@@ -890,8 +891,8 @@ class IContextModel : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT createConditionedModel(IN ModelConditionVec *pModelConditionVec,
-                OUT IConditionedModel **ppConditionedModel) = 0;
+        virtual SSMRESULT createConditionedModel(ModelConditionVec *pModelConditionVec,
+                IConditionedModel **ppConditionedModel) = 0;
         //virtual SSMRESULT CleanUpModelData() = 0;
 
         /**
@@ -939,8 +940,8 @@ class IContextModelEvent
         * @exception
         * @see
         */
-        virtual SSMRESULT onModelStatusChange(IN IContextModel::Status newStatus,
-                                              IN ISSMResource *pSSMResource, IN IContextModel *pModel) = 0;
+        virtual SSMRESULT onModelStatusChange(IContextModel::Status newStatus,
+                                              ISSMResource *pSSMResource, IContextModel *pModel) = 0;
         virtual ~IContextModelEvent() {}
 };
 
@@ -966,8 +967,8 @@ class IContextModelAccessor
         * @exception
         * @see
         */
-        virtual SSMRESULT onQueryContextModel(IN std::string modelName,
-                                              OUT IContextModel **ppContextModel) = 0;
+        virtual SSMRESULT onQueryContextModel(std::string modelName,
+                                              IContextModel **ppContextModel) = 0;
         virtual ~IContextModelAccessor() {}
 };
 
@@ -993,7 +994,7 @@ class IContextDataReader : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT registerContextModelAccessor(IN IContextModelAccessor *pContextModelAccessor) = 0;
+        virtual SSMRESULT registerContextModelAccessor(IContextModelAccessor *pContextModelAccessor) = 0;
 
         /**
         * @fn     getContextData
@@ -1010,8 +1011,8 @@ class IContextDataReader : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getContextData(IN std::string modelName, IN int startIndex, IN int count,
-                                         OUT std::vector<ContextData> *data, OUT int *pLastIndex) = 0;
+        virtual SSMRESULT getContextData(std::string modelName, int startIndex, int count,
+                                         std::vector<ContextData> *data, int *pLastIndex) = 0;
 };
 
 typedef std::vector<std::pair<std::string, ModelConditionVec> > QueryCondition;
@@ -1039,8 +1040,8 @@ class IPropagationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getContextModel(IN std:: string modelName,
-                                          OUT IContextModel **ppContextModel) = 0;
+        virtual SSMRESULT getContextModel(std:: string modelName,
+                                          IContextModel **ppContextModel) = 0;
 
         /**
         * @fn     createConditionedQuery
@@ -1056,9 +1057,9 @@ class IPropagationEngine : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT createConditionedQuery(IN IContextModel::ActivationType activationType,
-                IN QueryCondition *pQueryCondition,
-                IN IConditionedQueryEvent *pEvent, OUT IConditionedQuery **ppConditionedQuery) = 0;
+        virtual SSMRESULT createConditionedQuery(IContextModel::ActivationType activationType,
+                QueryCondition *pQueryCondition,
+                IConditionedQueryEvent *pEvent, IConditionedQuery **ppConditionedQuery) = 0;
 };
 
 static const OID OID_IQueryEngineInternal = { 0x6eabf1a9, 0xe884, 0x4562, { 0x8b, 0x90, 0x1e, 0xe8, 0xba, 0xbf, 0xbe, 0x1a } };
@@ -1184,8 +1185,8 @@ class ISensingEngine : public IBase
 class IResourceFinderEvent
 {
     public:
-        virtual SSMRESULT onResourceFound(IN ISSMResource *pSensor) = 0;
-        virtual SSMRESULT onResourceLost(IN ISSMResource *pSensor) = 0;
+        virtual SSMRESULT onResourceFound(ISSMResource *pSensor) = 0;
+        virtual SSMRESULT onResourceLost(ISSMResource *pSensor) = 0;
         virtual ~IResourceFinderEvent() {}
 };
 
@@ -1193,10 +1194,11 @@ static const OID OID_IResourceFinder = { 0x8f52a31f, 0x51d5, 0x462b, { 0xa9, 0x8
 class IResourceFinder : public IBase
 {
     public:
-        virtual SSMRESULT registerResourceFinderEvent(IN IResourceFinderEvent *pEvent) = 0;
+        virtual SSMRESULT registerResourceFinderEvent(IResourceFinderEvent *pEvent) = 0;
         virtual SSMRESULT startResourceFinder() = 0;
-        virtual SSMRESULT startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent) = 0;
-        virtual SSMRESULT stopObserveResource(IN ISSMResource *pSensor) = 0;
+        virtual SSMRESULT stopResourceFinder() = 0;
+        virtual SSMRESULT startObserveResource(ISSMResource *pSensor, IEvent *pEvent) = 0;
+        virtual SSMRESULT stopObserveResource(ISSMResource *pSensor) = 0;
 };
 
 /**
@@ -1232,7 +1234,7 @@ class ISoftSensorManager : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT initializeCore(IN std::string xmlDescription) = 0;
+        virtual SSMRESULT initializeCore(std::string xmlDescription) = 0;
 
         /**
         * @fn startCore
@@ -1271,7 +1273,7 @@ class ISoftSensorManager : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT terminateCore(IN bool factoryResetFlag) = 0;
+        virtual SSMRESULT terminateCore(bool factoryResetFlag) = 0;
 
         /**
         * @fn createQueryEngine
@@ -1285,7 +1287,7 @@ class ISoftSensorManager : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT createQueryEngine(OUT IQueryEngine **ppQueryEngine) = 0;
+        virtual SSMRESULT createQueryEngine(IQueryEngine **ppQueryEngine) = 0;
 
         /**
         * @fn releaseQueryEngine
@@ -1297,7 +1299,7 @@ class ISoftSensorManager : public IBase
         * @exception
         * @see
         */
-        virtual unsigned long releaseQueryEngine(IN IQueryEngine *pQueryEngine) = 0;
+        virtual unsigned long releaseQueryEngine(IQueryEngine *pQueryEngine) = 0;
 
         /**
         * @fn getInstalledModelList
@@ -1310,6 +1312,6 @@ class ISoftSensorManager : public IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT getInstalledModelList(OUT std::vector<ISSMResource *> *pList) = 0;
+        virtual SSMRESULT getInstalledModelList(std::vector<ISSMResource *> *pList) = 0;
 };
 #endif
index 373734e..73cff04 100644 (file)
@@ -17,7 +17,6 @@
 * limitations under the License.
 *
 ******************************************************************/
-
 #ifndef _ObjectManager_H_
 #define _ObjectManager_H_
 
@@ -92,7 +91,7 @@ class IBase
         * @exception
         * @see
         */
-        virtual SSMRESULT queryInterface(IN const OID &interfaceID, OUT IBase **ppObject) = 0;
+        virtual SSMRESULT queryInterface(const OID &interfaceID, IBase **ppObject) = 0;
 
         /**
         * @fn     addRef
@@ -394,7 +393,7 @@ class CObjectPtr
 * @see
 */
 template <class T>
-SSMRESULT CreateNewObject(IN const OID &objectID, OUT IBase **ppObject)
+SSMRESULT CreateNewObject(const OID &objectID, IBase **ppObject)
 {
     SSMRESULT res = SSM_E_OUTOFMEMORY;
 
index 5e458e0..ded07bd 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.
+*
+******************************************************************/
 #ifndef _PlatformLayer_H_
 #define _PlatformLayer_H_
 
@@ -37,6 +56,8 @@
 
 #elif defined(TIZEN)
 
+#include <dlog.h>
+
 #endif
 
 #endif
@@ -64,13 +85,14 @@ void ReportMessage(const char *tag, const char *msg);
 
 #elif defined(TIZEN)
 
-#define REPORT_MESSAGE(tag, msg) printf("[%s] %s\n", tag, msg)
-#define PRINT_LOG(strError) printf("[SSM] %s:%d %s\n", __FUNCTION__, __LINE__, strError)
+void ReportMessage(const char *tag, const char *msg);
+#define REPORT_MESSAGE(tag, msg) ReportMessage(tag, msg)
+#define PRINT_LOG(strError) dlog_print(DLOG_DEBUG, "SSM", "%s:%d %s", __PRETTY_FUNCTION__, __LINE__, strError)
 
 #else //Default linux
 
 #define REPORT_MESSAGE(tag, msg) printf("[%s] %s\n", tag, msg)
-#define PRINT_LOG(strError) printf("[SSM] %s:%d %s\n", __FUNCTION__, __LINE__, strError)
+#define PRINT_LOG(strError) printf("[SSM] %s:%d %s\n", __PRETTY_FUNCTION__, __LINE__, strError)
 
 #endif
 
@@ -152,7 +174,7 @@ typedef std::vector<int> IntVec;
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC SSMRESULT CreateInstance(IN const OID &objectID, OUT IBase **ppObject);
+INTERFACE_DECLSPEC SSMRESULT CreateInstance(const OID &objectID, IBase **ppObject);
 
 /**
 * @fn createGlobalInstance
@@ -167,7 +189,7 @@ INTERFACE_DECLSPEC SSMRESULT CreateInstance(IN const OID &objectID, OUT IBase **
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC SSMRESULT CreateGlobalInstance(IN const OID &objectID, OUT IBase **ppObject);
+INTERFACE_DECLSPEC SSMRESULT CreateGlobalInstance(const OID &objectID, IBase **ppObject);
 
 INTERFACE_DECLSPEC SSMRESULT CreateGlobalInstanceRepo();
 
index 4a8e050..85ef306 100644 (file)
@@ -346,7 +346,7 @@ void CThreadPool::finalRelease()
     }
 }
 
-SSMRESULT CThreadPool::createWorkerThread(OUT IWorkerThread **ppWorkerThread)
+SSMRESULT CThreadPool::createWorkerThread(IWorkerThread **ppWorkerThread)
 {
     SSMRESULT res = SSM_E_FAIL;
 
index ca6b9b5..9eeed97 100644 (file)
@@ -431,7 +431,7 @@ static const OID OID_IThreadPool = { 0x53855605, 0xb2a0, 0x4a31, { 0xa2, 0x60, 0
 class IThreadPool : public IBase
 {
     public:
-        virtual SSMRESULT createWorkerThread(OUT IWorkerThread **ppWorkerThread) = 0;
+        virtual SSMRESULT createWorkerThread(IWorkerThread **ppWorkerThread) = 0;
         virtual SSMRESULT destroyThreadPool() = 0;
 };
 
@@ -469,7 +469,7 @@ class CThreadPool :
             return SSM_E_NOINTERFACE;
         }
 
-        SSMRESULT createWorkerThread(OUT IWorkerThread **ppWorkerThread);
+        SSMRESULT createWorkerThread(IWorkerThread **ppWorkerThread);
 
         SSMRESULT destroyThreadPool();
 };
diff --git a/service/soft-sensor-manager/SSMCore/src/Common/rapidxml.hpp b/service/soft-sensor-manager/SSMCore/src/Common/rapidxml.hpp
deleted file mode 100644 (file)
index 9ddf195..0000000
+++ /dev/null
@@ -1,2601 +0,0 @@
-#ifndef RAPIDXML_HPP_INCLUDED
-#define RAPIDXML_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml.hpp This file contains rapidxml parser and DOM implementation
-
-// If standard library is disabled, user must provide implementations of required functions and typedefs
-#if !defined(RAPIDXML_NO_STDLIB)
-    #include <cstdlib>      // For std::size_t
-    #include <cassert>      // For assert
-    #include <new>          // For placement new
-#endif
-
-// On MSVC, disable "conditional expression is constant" warning (level 4). 
-// This warning is almost impossible to avoid with certain types of templated code
-#ifdef _MSC_VER
-    #pragma warning(push)
-    #pragma warning(disable:4127)   // Conditional expression is constant
-#endif
-
-///////////////////////////////////////////////////////////////////////////
-// RAPIDXML_PARSE_ERROR
-    
-#if defined(RAPIDXML_NO_EXCEPTIONS)
-
-#define RAPIDXML_PARSE_ERROR(what, where) { parse_error_handler(what, where); assert(0); }
-
-namespace rapidxml
-{
-    //! When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, 
-    //! this function is called to notify user about the error.
-    //! It must be defined by the user.
-    //! <br><br>
-    //! This function cannot return. If it does, the results are undefined.
-    //! <br><br>
-    //! A very simple definition might look like that:
-    //! <pre>
-    //! void %rapidxml::%parse_error_handler(const char *what, void *where)
-    //! {
-    //!     std::cout << "Parse error: " << what << "\n";
-    //!     std::abort();
-    //! }
-    //! </pre>
-    //! \param what Human readable description of the error.
-    //! \param where Pointer to character data where error was detected.
-    void parse_error_handler(const char *what, void *where);
-}
-
-#else
-    
-#include <exception>    // For std::exception
-
-#define RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where)
-
-namespace rapidxml
-{
-
-    //! Parse error exception. 
-    //! This exception is thrown by the parser when an error occurs. 
-    //! Use what() function to get human-readable error message. 
-    //! Use where() function to get a pointer to position within source text where error was detected.
-    //! <br><br>
-    //! If throwing exceptions by the parser is undesirable, 
-    //! it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included.
-    //! This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception.
-    //! This function must be defined by the user.
-    //! <br><br>
-    //! This class derives from <code>std::exception</code> class.
-    class parse_error: public std::exception
-    {
-    
-    public:
-    
-        //! Constructs parse error
-        parse_error(const char *what, void *where)
-            : m_what(what)
-            , m_where(where)
-        {
-        }
-
-        //! Gets human readable description of error.
-        //! \return Pointer to null terminated description of the error.
-        virtual const char *what() const throw()
-        {
-            return m_what;
-        }
-
-        //! Gets pointer to character data where error happened.
-        //! Ch should be the same as char type of xml_document that produced the error.
-        //! \return Pointer to location within the parsed string where error occured.
-        template<class Ch>
-        Ch *where() const
-        {
-            return reinterpret_cast<Ch *>(m_where);
-        }
-
-    private:  
-
-        const char *m_what;
-        void *m_where;
-
-    };
-}
-
-#endif
-
-///////////////////////////////////////////////////////////////////////////
-// Pool sizes
-
-#ifndef RAPIDXML_STATIC_POOL_SIZE
-    // Size of static memory block of memory_pool.
-    // Define RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value.
-    // No dynamic memory allocations are performed by memory_pool until static memory is exhausted.
-    #define RAPIDXML_STATIC_POOL_SIZE (64 * 1024)
-#endif
-
-#ifndef RAPIDXML_DYNAMIC_POOL_SIZE
-    // Size of dynamic memory block of memory_pool.
-    // Define RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value.
-    // After the static block is exhausted, dynamic blocks with approximately this size are allocated by memory_pool.
-    #define RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024)
-#endif
-
-#ifndef RAPIDXML_ALIGNMENT
-    // Memory allocation alignment.
-    // Define RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to override the default value, which is the size of pointer.
-    // All memory allocations for nodes, attributes and strings will be aligned to this value.
-    // This must be a power of 2 and at least 1, otherwise memory_pool will not work.
-    #define RAPIDXML_ALIGNMENT sizeof(void *)
-#endif
-
-namespace rapidxml
-{
-    // Forward declarations
-    template<class Ch> class xml_node;
-    template<class Ch> class xml_attribute;
-    template<class Ch> class xml_document;
-    
-    //! Enumeration listing all node types produced by the parser.
-    //! Use xml_node::type() function to query node type.
-    enum node_type
-    {
-        node_document,      //!< A document node. Name and value are empty.
-        node_element,       //!< An element node. Name contains element name. Value contains text of first data node.
-        node_data,          //!< A data node. Name is empty. Value contains data text.
-        node_cdata,         //!< A CDATA node. Name is empty. Value contains data text.
-        node_comment,       //!< A comment node. Name is empty. Value contains comment text.
-        node_declaration,   //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.
-        node_doctype,       //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text.
-        node_pi             //!< A PI node. Name contains target. Value contains instructions.
-    };
-
-    ///////////////////////////////////////////////////////////////////////
-    // Parsing flags
-
-    //! Parse flag instructing the parser to not create data nodes. 
-    //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_data_nodes = 0x1;            
-
-    //! Parse flag instructing the parser to not use text of first data node as a value of parent element.
-    //! Can be combined with other flags by use of | operator.
-    //! Note that child data nodes of element node take precendence over its value when printing. 
-    //! That is, if element has one or more child data nodes <em>and</em> a value, the value will be ignored.
-    //! Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_element_values = 0x2;
-    
-    //! Parse flag instructing the parser to not place zero terminators after strings in the source text.
-    //! By default zero terminators are placed, modifying source text.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_string_terminators = 0x4;
-    
-    //! Parse flag instructing the parser to not translate entities in the source text.
-    //! By default entities are translated, modifying source text.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_entity_translation = 0x8;
-    
-    //! Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters.
-    //! By default, UTF-8 handling is enabled.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_no_utf8 = 0x10;
-    
-    //! Parse flag instructing the parser to create XML declaration node.
-    //! By default, declaration node is not created.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_declaration_node = 0x20;
-    
-    //! Parse flag instructing the parser to create comments nodes.
-    //! By default, comment nodes are not created.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_comment_nodes = 0x40;
-    
-    //! Parse flag instructing the parser to create DOCTYPE node.
-    //! By default, doctype node is not created.
-    //! Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_doctype_node = 0x80;
-    
-    //! Parse flag instructing the parser to create PI nodes.
-    //! By default, PI nodes are not created.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_pi_nodes = 0x100;
-    
-    //! Parse flag instructing the parser to validate closing tag names. 
-    //! If not set, name inside closing tag is irrelevant to the parser.
-    //! By default, closing tags are not validated.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_validate_closing_tags = 0x200;
-    
-    //! Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes.
-    //! By default, whitespace is not trimmed. 
-    //! This flag does not cause the parser to modify source text.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_trim_whitespace = 0x400;
-
-    //! Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character.
-    //! Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag.
-    //! By default, whitespace is not normalized. 
-    //! If this flag is specified, source text will be modified.
-    //! Can be combined with other flags by use of | operator.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_normalize_whitespace = 0x800;
-
-    // Compound flags
-    
-    //! Parse flags which represent default behaviour of the parser. 
-    //! This is always equal to 0, so that all other flags can be simply ored together.
-    //! Normally there is no need to inconveniently disable flags by anding with their negated (~) values.
-    //! This also means that meaning of each flag is a <i>negation</i> of the default setting. 
-    //! For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is <i>enabled</i> by default,
-    //! and using the flag will disable it.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_default = 0;
-    
-    //! A combination of parse flags that forbids any modifications of the source text. 
-    //! This also results in faster parsing. However, note that the following will occur:
-    //! <ul>
-    //! <li>names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends</li>
-    //! <li>entities will not be translated</li>
-    //! <li>whitespace will not be normalized</li>
-    //! </ul>
-    //! See xml_document::parse() function.
-    const int parse_non_destructive = parse_no_string_terminators | parse_no_entity_translation;
-    
-    //! A combination of parse flags resulting in fastest possible parsing, without sacrificing important data.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_fastest = parse_non_destructive | parse_no_data_nodes;
-    
-    //! A combination of parse flags resulting in largest amount of data being extracted. 
-    //! This usually results in slowest parsing.
-    //! <br><br>
-    //! See xml_document::parse() function.
-    const int parse_full = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags;
-
-    ///////////////////////////////////////////////////////////////////////
-    // Internals
-
-    //! \cond internal
-    namespace internal
-    {
-
-        // Struct that contains lookup tables for the parser
-        // It must be a template to allow correct linking (because it has static data members, which are defined in a header file).
-        template<int Dummy>
-        struct lookup_tables
-        {
-            static const unsigned char lookup_whitespace[256];              // Whitespace table
-            static const unsigned char lookup_node_name[256];               // Node name table
-            static const unsigned char lookup_text[256];                    // Text table
-            static const unsigned char lookup_text_pure_no_ws[256];         // Text table
-            static const unsigned char lookup_text_pure_with_ws[256];       // Text table
-            static const unsigned char lookup_attribute_name[256];          // Attribute name table
-            static const unsigned char lookup_attribute_data_1[256];        // Attribute data table with single quote
-            static const unsigned char lookup_attribute_data_1_pure[256];   // Attribute data table with single quote
-            static const unsigned char lookup_attribute_data_2[256];        // Attribute data table with double quotes
-            static const unsigned char lookup_attribute_data_2_pure[256];   // Attribute data table with double quotes
-            static const unsigned char lookup_digits[256];                  // Digits
-            static const unsigned char lookup_upcase[256];                  // To uppercase conversion table for ASCII characters
-        };
-
-        // Find length of the string
-        template<class Ch>
-        inline std::size_t measure(const Ch *p)
-        {
-            const Ch *tmp = p;
-            while (*tmp) 
-                ++tmp;
-            return tmp - p;
-        }
-
-        // Compare strings for equality
-        template<class Ch>
-        inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive)
-        {
-            if (size1 != size2)
-                return false;
-            if (case_sensitive)
-            {
-                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
-                    if (*p1 != *p2)
-                        return false;
-            }
-            else
-            {
-                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
-                    if (lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p1)] != lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p2)])
-                        return false;
-            }
-            return true;
-        }
-    }
-    //! \endcond
-
-    ///////////////////////////////////////////////////////////////////////
-    // Memory pool
-    
-    //! This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation.
-    //! In most cases, you will not need to use this class directly. 
-    //! However, if you need to create nodes manually or modify names/values of nodes, 
-    //! you are encouraged to use memory_pool of relevant xml_document to allocate the memory. 
-    //! Not only is this faster than allocating them by using <code>new</code> operator, 
-    //! but also their lifetime will be tied to the lifetime of document, 
-    //! possibly simplyfing memory management. 
-    //! <br><br>
-    //! Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. 
-    //! You can also call allocate_string() function to allocate strings.
-    //! Such strings can then be used as names or values of nodes without worrying about their lifetime.
-    //! Note that there is no <code>free()</code> function -- all allocations are freed at once when clear() function is called, 
-    //! or when the pool is destroyed.
-    //! <br><br>
-    //! It is also possible to create a standalone memory_pool, and use it 
-    //! to allocate nodes, whose lifetime will not be tied to any document.
-    //! <br><br>
-    //! Pool maintains <code>RAPIDXML_STATIC_POOL_SIZE</code> bytes of statically allocated memory. 
-    //! Until static memory is exhausted, no dynamic memory allocations are done.
-    //! When static memory is exhausted, pool allocates additional blocks of memory of size <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> each,
-    //! by using global <code>new[]</code> and <code>delete[]</code> operators. 
-    //! This behaviour can be changed by setting custom allocation routines. 
-    //! Use set_allocator() function to set them.
-    //! <br><br>
-    //! Allocations for nodes, attributes and strings are aligned at <code>RAPIDXML_ALIGNMENT</code> bytes.
-    //! This value defaults to the size of pointer on target architecture.
-    //! <br><br>
-    //! To obtain absolutely top performance from the parser,
-    //! it is important that all nodes are allocated from a single, contiguous block of memory.
-    //! Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably.
-    //! If required, you can tweak <code>RAPIDXML_STATIC_POOL_SIZE</code>, <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>RAPIDXML_ALIGNMENT</code> 
-    //! to obtain best wasted memory to performance compromise.
-    //! To do it, define their values before rapidxml.hpp file is included.
-    //! \param Ch Character type of created nodes. 
-    template<class Ch = char>
-    class memory_pool
-    {
-        
-    public:
-
-        //! \cond internal
-        typedef void *(alloc_func)(std::size_t);       // Type of user-defined function used to allocate memory
-        typedef void (free_func)(void *);              // Type of user-defined function used to free memory
-        //! \endcond
-        
-        //! Constructs empty pool with default allocator functions.
-        memory_pool()
-            : m_alloc_func(0)
-            , m_free_func(0)
-        {
-            init();
-        }
-
-        //! Destroys pool and frees all the memory. 
-        //! This causes memory occupied by nodes allocated by the pool to be freed.
-        //! Nodes allocated from the pool are no longer valid.
-        ~memory_pool()
-        {
-            clear();
-        }
-
-        //! Allocates a new node from the pool, and optionally assigns name and value to it. 
-        //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
-        //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
-        //! will call rapidxml::parse_error_handler() function.
-        //! \param type Type of node to create.
-        //! \param name Name to assign to the node, or 0 to assign no name.
-        //! \param value Value to assign to the node, or 0 to assign no value.
-        //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
-        //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
-        //! \return Pointer to allocated node. This pointer will never be NULL.
-        xml_node<Ch> *allocate_node(node_type type, 
-                                    const Ch *name = 0, const Ch *value = 0, 
-                                    std::size_t name_size = 0, std::size_t value_size = 0)
-        {
-            void *memory = allocate_aligned(sizeof(xml_node<Ch>));
-            xml_node<Ch> *node = new(memory) xml_node<Ch>(type);
-            if (name)
-            {
-                if (name_size > 0)
-                    node->name(name, name_size);
-                else
-                    node->name(name);
-            }
-            if (value)
-            {
-                if (value_size > 0)
-                    node->value(value, value_size);
-                else
-                    node->value(value);
-            }
-            return node;
-        }
-
-        //! Allocates a new attribute from the pool, and optionally assigns name and value to it.
-        //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
-        //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
-        //! will call rapidxml::parse_error_handler() function.
-        //! \param name Name to assign to the attribute, or 0 to assign no name.
-        //! \param value Value to assign to the attribute, or 0 to assign no value.
-        //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string.
-        //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string.
-        //! \return Pointer to allocated attribute. This pointer will never be NULL.
-        xml_attribute<Ch> *allocate_attribute(const Ch *name = 0, const Ch *value = 0, 
-                                              std::size_t name_size = 0, std::size_t value_size = 0)
-        {
-            void *memory = allocate_aligned(sizeof(xml_attribute<Ch>));
-            xml_attribute<Ch> *attribute = new(memory) xml_attribute<Ch>;
-            if (name)
-            {
-                if (name_size > 0)
-                    attribute->name(name, name_size);
-                else
-                    attribute->name(name);
-            }
-            if (value)
-            {
-                if (value_size > 0)
-                    attribute->value(value, value_size);
-                else
-                    attribute->value(value);
-            }
-            return attribute;
-        }
-
-        //! Allocates a char array of given size from the pool, and optionally copies a given string to it.
-        //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>.
-        //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function
-        //! will call rapidxml::parse_error_handler() function.
-        //! \param source String to initialize the allocated memory with, or 0 to not initialize it.
-        //! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated.
-        //! \return Pointer to allocated char array. This pointer will never be NULL.
-        Ch *allocate_string(const Ch *source = 0, std::size_t size = 0)
-        {
-            assert(source || size);     // Either source or size (or both) must be specified
-            if (size == 0)
-                size = internal::measure(source) + 1;
-            Ch *result = static_cast<Ch *>(allocate_aligned(size * sizeof(Ch)));
-            if (source)
-                for (std::size_t i = 0; i < size; ++i)
-                    result[i] = source[i];
-            return result;
-        }
-
-        //! Clones an xml_node and its hierarchy of child nodes and attributes.
-        //! Nodes and attributes are allocated from this memory pool.
-        //! Names and values are not cloned, they are shared between the clone and the source.
-        //! Result node can be optionally specified as a second parameter, 
-        //! in which case its contents will be replaced with cloned source node.
-        //! This is useful when you want to clone entire document.
-        //! \param source Node to clone.
-        //! \param result Node to put results in, or 0 to automatically allocate result node
-        //! \return Pointer to cloned node. This pointer will never be NULL.
-        xml_node<Ch> *clone_node(const xml_node<Ch> *source, xml_node<Ch> *result = 0)
-        {
-            // Prepare result node
-            if (result)
-            {
-                result->remove_all_attributes();
-                result->remove_all_nodes();
-                result->type(source->type());
-            }
-            else
-                result = allocate_node(source->type());
-
-            // Clone name and value
-            result->name(source->name(), source->name_size());
-            result->value(source->value(), source->value_size());
-
-            // Clone child nodes and attributes
-            for (xml_node<Ch> *child = source->first_node(); child; child = child->next_sibling())
-                result->append_node(clone_node(child));
-            for (xml_attribute<Ch> *attr = source->first_attribute(); attr; attr = attr->next_attribute())
-                result->append_attribute(allocate_attribute(attr->name(), attr->value(), attr->name_size(), attr->value_size()));
-
-            return result;
-        }
-
-        //! Clears the pool. 
-        //! This causes memory occupied by nodes allocated by the pool to be freed.
-        //! Any nodes or strings allocated from the pool will no longer be valid.
-        void clear()
-        {
-            while (m_begin != m_static_memory)
-            {
-                char *previous_begin = reinterpret_cast<header *>(align(m_begin))->previous_begin;
-                if (m_free_func)
-                    m_free_func(m_begin);
-                else
-                    delete[] m_begin;
-                m_begin = previous_begin;
-            }
-            init();
-        }
-
-        //! Sets or resets the user-defined memory allocation functions for the pool.
-        //! This can only be called when no memory is allocated from the pool yet, otherwise results are undefined.
-        //! Allocation function must not return invalid pointer on failure. It should either throw,
-        //! stop the program, or use <code>longjmp()</code> function to pass control to other place of program. 
-        //! If it returns invalid pointer, results are undefined.
-        //! <br><br>
-        //! User defined allocation functions must have the following forms:
-        //! <br><code>
-        //! <br>void *allocate(std::size_t size);
-        //! <br>void free(void *pointer);
-        //! </code><br>
-        //! \param af Allocation function, or 0 to restore default function
-        //! \param ff Free function, or 0 to restore default function
-        void set_allocator(alloc_func *af, free_func *ff)
-        {
-            assert(m_begin == m_static_memory && m_ptr == align(m_begin));    // Verify that no memory is allocated yet
-            m_alloc_func = af;
-            m_free_func = ff;
-        }
-
-    private:
-
-        struct header
-        {
-            char *previous_begin;
-        };
-
-        void init()
-        {
-            m_begin = m_static_memory;
-            m_ptr = align(m_begin);
-            m_end = m_static_memory + sizeof(m_static_memory);
-        }
-        
-        char *align(char *ptr)
-        {
-            std::size_t alignment = ((RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (RAPIDXML_ALIGNMENT - 1))) & (RAPIDXML_ALIGNMENT - 1));
-            return ptr + alignment;
-        }
-        
-        char *allocate_raw(std::size_t size)
-        {
-            // Allocate
-            void *memory;   
-            if (m_alloc_func)   // Allocate memory using either user-specified allocation function or global operator new[]
-            {
-                memory = m_alloc_func(size);
-                assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp
-            }
-            else
-            {
-                memory = new char[size];
-#ifdef RAPIDXML_NO_EXCEPTIONS
-                if (!memory)            // If exceptions are disabled, verify memory allocation, because new will not be able to throw bad_alloc
-                    RAPIDXML_PARSE_ERROR("out of memory", 0);
-#endif
-            }
-            return static_cast<char *>(memory);
-        }
-        
-        void *allocate_aligned(std::size_t size)
-        {
-            // Calculate aligned pointer
-            char *result = align(m_ptr);
-
-            // If not enough memory left in current pool, allocate a new pool
-            if (result + size > m_end)
-            {
-                // Calculate required pool size (may be bigger than RAPIDXML_DYNAMIC_POOL_SIZE)
-                std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE;
-                if (pool_size < size)
-                    pool_size = size;
-                
-                // Allocate
-                std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + pool_size;     // 2 alignments required in worst case: one for header, one for actual allocation
-                char *raw_memory = allocate_raw(alloc_size);
-                    
-                // Setup new pool in allocated memory
-                char *pool = align(raw_memory);
-                header *new_header = reinterpret_cast<header *>(pool);
-                new_header->previous_begin = m_begin;
-                m_begin = raw_memory;
-                m_ptr = pool + sizeof(header);
-                m_end = raw_memory + alloc_size;
-
-                // Calculate aligned pointer again using new pool
-                result = align(m_ptr);
-            }
-
-            // Update pool and return aligned pointer
-            m_ptr = result + size;
-            return result;
-        }
-
-        char *m_begin;                                      // Start of raw memory making up current pool
-        char *m_ptr;                                        // First free byte in current pool
-        char *m_end;                                        // One past last available byte in current pool
-        char m_static_memory[RAPIDXML_STATIC_POOL_SIZE];    // Static raw memory
-        alloc_func *m_alloc_func;                           // Allocator function, or 0 if default is to be used
-        free_func *m_free_func;                             // Free function, or 0 if default is to be used
-    };
-
-    ///////////////////////////////////////////////////////////////////////////
-    // XML base
-
-    //! Base class for xml_node and xml_attribute implementing common functions: 
-    //! name(), name_size(), value(), value_size() and parent().
-    //! \param Ch Character type to use
-    template<class Ch = char>
-    class xml_base
-    {
-
-    public:
-        
-        ///////////////////////////////////////////////////////////////////////////
-        // Construction & destruction
-    
-        // Construct a base with empty name, value and parent
-        xml_base()
-            : m_name(0)
-            , m_value(0)
-            , m_parent(0)
-        {
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node data access
-    
-        //! Gets name of the node. 
-        //! Interpretation of name depends on type of node.
-        //! Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.
-        //! <br><br>
-        //! Use name_size() function to determine length of the name.
-        //! \return Name of node, or empty string if node has no name.
-        Ch *name() const
-        {
-            return m_name ? m_name : nullstr();
-        }
-
-        //! Gets size of node name, not including terminator character.
-        //! This function works correctly irrespective of whether name is or is not zero terminated.
-        //! \return Size of node name, in characters.
-        std::size_t name_size() const
-        {
-            return m_name ? m_name_size : 0;
-        }
-
-        //! Gets value of node. 
-        //! Interpretation of value depends on type of node.
-        //! Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.
-        //! <br><br>
-        //! Use value_size() function to determine length of the value.
-        //! \return Value of node, or empty string if node has no value.
-        Ch *value() const
-        {
-            return m_value ? m_value : nullstr();
-        }
-
-        //! Gets size of node value, not including terminator character.
-        //! This function works correctly irrespective of whether value is or is not zero terminated.
-        //! \return Size of node value, in characters.
-        std::size_t value_size() const
-        {
-            return m_value ? m_value_size : 0;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node modification
-    
-        //! Sets name of node to a non zero-terminated string.
-        //! See \ref ownership_of_strings.
-        //! <br><br>
-        //! Note that node does not own its name or value, it only stores a pointer to it. 
-        //! It will not delete or otherwise free the pointer on destruction.
-        //! It is reponsibility of the user to properly manage lifetime of the string.
-        //! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
-        //! on destruction of the document the string will be automatically freed.
-        //! <br><br>
-        //! Size of name must be specified separately, because name does not have to be zero terminated.
-        //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated).
-        //! \param name Name of node to set. Does not have to be zero terminated.
-        //! \param size Size of name, in characters. This does not include zero terminator, if one is present.
-        void name(const Ch *name, std::size_t size)
-        {
-            m_name = const_cast<Ch *>(name);
-            m_name_size = size;
-        }
-
-        //! Sets name of node to a zero-terminated string.
-        //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t).
-        //! \param name Name of node to set. Must be zero terminated.
-        void name(const Ch *name)
-        {
-            this->name(name, internal::measure(name));
-        }
-
-        //! Sets value of node to a non zero-terminated string.
-        //! See \ref ownership_of_strings.
-        //! <br><br>
-        //! Note that node does not own its name or value, it only stores a pointer to it. 
-        //! It will not delete or otherwise free the pointer on destruction.
-        //! It is reponsibility of the user to properly manage lifetime of the string.
-        //! The easiest way to achieve it is to use memory_pool of the document to allocate the string -
-        //! on destruction of the document the string will be automatically freed.
-        //! <br><br>
-        //! Size of value must be specified separately, because it does not have to be zero terminated.
-        //! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated).
-        //! <br><br>
-        //! If an element has a child node of type node_data, it will take precedence over element value when printing.
-        //! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser.
-        //! \param value value of node to set. Does not have to be zero terminated.
-        //! \param size Size of value, in characters. This does not include zero terminator, if one is present.
-        void value(const Ch *value, std::size_t size)
-        {
-            m_value = const_cast<Ch *>(value);
-            m_value_size = size;
-        }
-
-        //! Sets value of node to a zero-terminated string.
-        //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t).
-        //! \param value Vame of node to set. Must be zero terminated.
-        void value(const Ch *value)
-        {
-            this->value(value, internal::measure(value));
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Related nodes access
-    
-        //! Gets node parent.
-        //! \return Pointer to parent node, or 0 if there is no parent.
-        xml_node<Ch> *parent() const
-        {
-            return m_parent;
-        }
-
-    protected:
-
-        // Return empty string
-        static Ch *nullstr()
-        {
-            static Ch zero = Ch('\0');
-            return &zero;
-        }
-
-        Ch *m_name;                         // Name of node, or 0 if no name
-        Ch *m_value;                        // Value of node, or 0 if no value
-        std::size_t m_name_size;            // Length of node name, or undefined of no name
-        std::size_t m_value_size;           // Length of node value, or undefined if no value
-        xml_node<Ch> *m_parent;             // Pointer to parent node, or 0 if none
-
-    };
-
-    //! Class representing attribute node of XML document. 
-    //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base).
-    //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing. 
-    //! Thus, this text must persist in memory for the lifetime of attribute.
-    //! \param Ch Character type to use.
-    template<class Ch = char>
-    class xml_attribute: public xml_base<Ch>
-    {
-
-        friend class xml_node<Ch>;
-    
-    public:
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Construction & destruction
-    
-        //! Constructs an empty attribute with the specified type. 
-        //! Consider using memory_pool of appropriate xml_document if allocating attributes manually.
-        xml_attribute()
-        {
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Related nodes access
-    
-        //! Gets document of which attribute is a child.
-        //! \return Pointer to document that contains this attribute, or 0 if there is no parent document.
-        xml_document<Ch> *document() const
-        {
-            if (xml_node<Ch> *node = this->parent())
-            {
-                while (node->parent())
-                    node = node->parent();
-                return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0;
-            }
-            else
-                return 0;
-        }
-
-        //! Gets previous attribute, optionally matching attribute name. 
-        //! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *previous_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return this->m_parent ? m_prev_attribute : 0;
-        }
-
-        //! Gets next attribute, optionally matching attribute name. 
-        //! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *next_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return this->m_parent ? m_next_attribute : 0;
-        }
-
-    private:
-
-        xml_attribute<Ch> *m_prev_attribute;        // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero
-        xml_attribute<Ch> *m_next_attribute;        // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero
-    
-    };
-
-    ///////////////////////////////////////////////////////////////////////////
-    // XML node
-
-    //! Class representing a node of XML document. 
-    //! Each node may have associated name and value strings, which are available through name() and value() functions. 
-    //! Interpretation of name and value depends on type of the node.
-    //! Type of node can be determined by using type() function.
-    //! <br><br>
-    //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. 
-    //! Thus, this text must persist in the memory for the lifetime of node.
-    //! \param Ch Character type to use.
-    template<class Ch = char>
-    class xml_node: public xml_base<Ch>
-    {
-
-    public:
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Construction & destruction
-    
-        //! Constructs an empty node with the specified type. 
-        //! Consider using memory_pool of appropriate document to allocate nodes manually.
-        //! \param type Type of node to construct.
-        xml_node(node_type type)
-            : m_type(type)
-            , m_first_node(0)
-            , m_first_attribute(0)
-        {
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node data access
-    
-        //! Gets type of node.
-        //! \return Type of node.
-        node_type type() const
-        {
-            return m_type;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Related nodes access
-    
-        //! Gets document of which node is a child.
-        //! \return Pointer to document that contains this node, or 0 if there is no parent document.
-        xml_document<Ch> *document() const
-        {
-            xml_node<Ch> *node = const_cast<xml_node<Ch> *>(this);
-            while (node->parent())
-                node = node->parent();
-            return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0;
-        }
-
-        //! Gets first child node, optionally matching node name.
-        //! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found child, or 0 if not found.
-        xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling())
-                    if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
-                        return child;
-                return 0;
-            }
-            else
-                return m_first_node;
-        }
-
-        //! Gets last child node, optionally matching node name. 
-        //! Behaviour is undefined if node has no children.
-        //! Use first_node() to test if node has children.
-        //! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found child, or 0 if not found.
-        xml_node<Ch> *last_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            assert(m_first_node);  // Cannot query for last child if node has no children
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *child = m_last_node; child; child = child->previous_sibling())
-                    if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive))
-                        return child;
-                return 0;
-            }
-            else
-                return m_last_node;
-        }
-
-        //! Gets previous sibling node, optionally matching node name. 
-        //! Behaviour is undefined if node has no parent.
-        //! Use parent() to test if node has a parent.
-        //! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found sibling, or 0 if not found.
-        xml_node<Ch> *previous_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            assert(this->m_parent);     // Cannot query for siblings if node has no parent
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling)
-                    if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive))
-                        return sibling;
-                return 0;
-            }
-            else
-                return m_prev_sibling;
-        }
-
-        //! Gets next sibling node, optionally matching node name. 
-        //! Behaviour is undefined if node has no parent.
-        //! Use parent() to test if node has a parent.
-        //! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found sibling, or 0 if not found.
-        xml_node<Ch> *next_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            assert(this->m_parent);     // Cannot query for siblings if node has no parent
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_node<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling)
-                    if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive))
-                        return sibling;
-                return 0;
-            }
-            else
-                return m_next_sibling;
-        }
-
-        //! Gets first attribute of node, optionally matching attribute name.
-        //! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *first_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return m_first_attribute;
-        }
-
-        //! Gets last attribute of node, optionally matching attribute name.
-        //! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
-        //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string
-        //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters
-        //! \return Pointer to found attribute, or 0 if not found.
-        xml_attribute<Ch> *last_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
-        {
-            if (name)
-            {
-                if (name_size == 0)
-                    name_size = internal::measure(name);
-                for (xml_attribute<Ch> *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute)
-                    if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive))
-                        return attribute;
-                return 0;
-            }
-            else
-                return m_first_attribute ? m_last_attribute : 0;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node modification
-    
-        //! Sets type of node.
-        //! \param type Type of node to set.
-        void type(node_type type)
-        {
-            m_type = type;
-        }
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Node manipulation
-
-        //! Prepends a new child node.
-        //! The prepended child becomes the first child, and all existing children are moved one position back.
-        //! \param child Node to prepend.
-        void prepend_node(xml_node<Ch> *child)
-        {
-            assert(child && !child->parent() && child->type() != node_document);
-            if (first_node())
-            {
-                child->m_next_sibling = m_first_node;
-                m_first_node->m_prev_sibling = child;
-            }
-            else
-            {
-                child->m_next_sibling = 0;
-                m_last_node = child;
-            }
-            m_first_node = child;
-            child->m_parent = this;
-            child->m_prev_sibling = 0;
-        }
-
-        //! Appends a new child node. 
-        //! The appended child becomes the last child.
-        //! \param child Node to append.
-        void append_node(xml_node<Ch> *child)
-        {
-            assert(child && !child->parent() && child->type() != node_document);
-            if (first_node())
-            {
-                child->m_prev_sibling = m_last_node;
-                m_last_node->m_next_sibling = child;
-            }
-            else
-            {
-                child->m_prev_sibling = 0;
-                m_first_node = child;
-            }
-            m_last_node = child;
-            child->m_parent = this;
-            child->m_next_sibling = 0;
-        }
-
-        //! Inserts a new child node at specified place inside the node. 
-        //! All children after and including the specified node are moved one position back.
-        //! \param where Place where to insert the child, or 0 to insert at the back.
-        //! \param child Node to insert.
-        void insert_node(xml_node<Ch> *where, xml_node<Ch> *child)
-        {
-            assert(!where || where->parent() == this);
-            assert(child && !child->parent() && child->type() != node_document);
-            if (where == m_first_node)
-                prepend_node(child);
-            else if (where == 0)
-                append_node(child);
-            else
-            {
-                child->m_prev_sibling = where->m_prev_sibling;
-                child->m_next_sibling = where;
-                where->m_prev_sibling->m_next_sibling = child;
-                where->m_prev_sibling = child;
-                child->m_parent = this;
-            }
-        }
-
-        //! Removes first child node. 
-        //! If node has no children, behaviour is undefined.
-        //! Use first_node() to test if node has children.
-        void remove_first_node()
-        {
-            assert(first_node());
-            xml_node<Ch> *child = m_first_node;
-            m_first_node = child->m_next_sibling;
-            if (child->m_next_sibling)
-                child->m_next_sibling->m_prev_sibling = 0;
-            else
-                m_last_node = 0;
-            child->m_parent = 0;
-        }
-
-        //! Removes last child of the node. 
-        //! If node has no children, behaviour is undefined.
-        //! Use first_node() to test if node has children.
-        void remove_last_node()
-        {
-            assert(first_node());
-            xml_node<Ch> *child = m_last_node;
-            if (child->m_prev_sibling)
-            {
-                m_last_node = child->m_prev_sibling;
-                child->m_prev_sibling->m_next_sibling = 0;
-            }
-            else
-                m_first_node = 0;
-            child->m_parent = 0;
-        }
-
-        //! Removes specified child from the node
-        // \param where Pointer to child to be removed.
-        void remove_node(xml_node<Ch> *where)
-        {
-            assert(where && where->parent() == this);
-            assert(first_node());
-            if (where == m_first_node)
-                remove_first_node();
-            else if (where == m_last_node)
-                remove_last_node();
-            else
-            {
-                where->m_prev_sibling->m_next_sibling = where->m_next_sibling;
-                where->m_next_sibling->m_prev_sibling = where->m_prev_sibling;
-                where->m_parent = 0;
-            }
-        }
-
-        //! Removes all child nodes (but not attributes).
-        void remove_all_nodes()
-        {
-            for (xml_node<Ch> *node = first_node(); node; node = node->m_next_sibling)
-                node->m_parent = 0;
-            m_first_node = 0;
-        }
-
-        //! Prepends a new attribute to the node.
-        //! \param attribute Attribute to prepend.
-        void prepend_attribute(xml_attribute<Ch> *attribute)
-        {
-            assert(attribute && !attribute->parent());
-            if (first_attribute())
-            {
-                attribute->m_next_attribute = m_first_attribute;
-                m_first_attribute->m_prev_attribute = attribute;
-            }
-            else
-            {
-                attribute->m_next_attribute = 0;
-                m_last_attribute = attribute;
-            }
-            m_first_attribute = attribute;
-            attribute->m_parent = this;
-            attribute->m_prev_attribute = 0;
-        }
-
-        //! Appends a new attribute to the node.
-        //! \param attribute Attribute to append.
-        void append_attribute(xml_attribute<Ch> *attribute)
-        {
-            assert(attribute && !attribute->parent());
-            if (first_attribute())
-            {
-                attribute->m_prev_attribute = m_last_attribute;
-                m_last_attribute->m_next_attribute = attribute;
-            }
-            else
-            {
-                attribute->m_prev_attribute = 0;
-                m_first_attribute = attribute;
-            }
-            m_last_attribute = attribute;
-            attribute->m_parent = this;
-            attribute->m_next_attribute = 0;
-        }
-
-        //! Inserts a new attribute at specified place inside the node. 
-        //! All attributes after and including the specified attribute are moved one position back.
-        //! \param where Place where to insert the attribute, or 0 to insert at the back.
-        //! \param attribute Attribute to insert.
-        void insert_attribute(xml_attribute<Ch> *where, xml_attribute<Ch> *attribute)
-        {
-            assert(!where || where->parent() == this);
-            assert(attribute && !attribute->parent());
-            if (where == m_first_attribute)
-                prepend_attribute(attribute);
-            else if (where == 0)
-                append_attribute(attribute);
-            else
-            {
-                attribute->m_prev_attribute = where->m_prev_attribute;
-                attribute->m_next_attribute = where;
-                where->m_prev_attribute->m_next_attribute = attribute;
-                where->m_prev_attribute = attribute;
-                attribute->m_parent = this;
-            }
-        }
-
-        //! Removes first attribute of the node. 
-        //! If node has no attributes, behaviour is undefined.
-        //! Use first_attribute() to test if node has attributes.
-        void remove_first_attribute()
-        {
-            assert(first_attribute());
-            xml_attribute<Ch> *attribute = m_first_attribute;
-            if (attribute->m_next_attribute)
-            {
-                attribute->m_next_attribute->m_prev_attribute = 0;
-            }
-            else
-                m_last_attribute = 0;
-            attribute->m_parent = 0;
-            m_first_attribute = attribute->m_next_attribute;
-        }
-
-        //! Removes last attribute of the node. 
-        //! If node has no attributes, behaviour is undefined.
-        //! Use first_attribute() to test if node has attributes.
-        void remove_last_attribute()
-        {
-            assert(first_attribute());
-            xml_attribute<Ch> *attribute = m_last_attribute;
-            if (attribute->m_prev_attribute)
-            {
-                attribute->m_prev_attribute->m_next_attribute = 0;
-                m_last_attribute = attribute->m_prev_attribute;
-            }
-            else
-                m_first_attribute = 0;
-            attribute->m_parent = 0;
-        }
-
-        //! Removes specified attribute from node.
-        //! \param where Pointer to attribute to be removed.
-        void remove_attribute(xml_attribute<Ch> *where)
-        {
-            assert(first_attribute() && where->parent() == this);
-            if (where == m_first_attribute)
-                remove_first_attribute();
-            else if (where == m_last_attribute)
-                remove_last_attribute();
-            else
-            {
-                where->m_prev_attribute->m_next_attribute = where->m_next_attribute;
-                where->m_next_attribute->m_prev_attribute = where->m_prev_attribute;
-                where->m_parent = 0;
-            }
-        }
-
-        //! Removes all attributes of node.
-        void remove_all_attributes()
-        {
-            for (xml_attribute<Ch> *attribute = first_attribute(); attribute; attribute = attribute->m_next_attribute)
-                attribute->m_parent = 0;
-            m_first_attribute = 0;
-        }
-        
-    private:
-
-        ///////////////////////////////////////////////////////////////////////////
-        // Restrictions
-
-        // No copying
-        xml_node(const xml_node &);
-        void operator =(const xml_node &);
-    
-        ///////////////////////////////////////////////////////////////////////////
-        // Data members
-    
-        // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0.
-        // This is required for maximum performance, as it allows the parser to omit initialization of 
-        // unneded/redundant values.
-        //
-        // The rules are as follows:
-        // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively
-        // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage
-        // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage
-
-        node_type m_type;                       // Type of node; always valid
-        xml_node<Ch> *m_first_node;             // Pointer to first child node, or 0 if none; always valid
-        xml_node<Ch> *m_last_node;              // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero
-        xml_attribute<Ch> *m_first_attribute;   // Pointer to first attribute of node, or 0 if none; always valid
-        xml_attribute<Ch> *m_last_attribute;    // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero
-        xml_node<Ch> *m_prev_sibling;           // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero
-        xml_node<Ch> *m_next_sibling;           // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero
-
-    };
-
-    ///////////////////////////////////////////////////////////////////////////
-    // XML document
-    
-    //! This class represents root of the DOM hierarchy. 
-    //! It is also an xml_node and a memory_pool through public inheritance.
-    //! Use parse() function to build a DOM tree from a zero-terminated XML text string.
-    //! parse() function allocates memory for nodes and attributes by using functions of xml_document, 
-    //! which are inherited from memory_pool.
-    //! To access root node of the document, use the document itself, as if it was an xml_node.
-    //! \param Ch Character type to use.
-    template<class Ch = char>
-    class xml_document: public xml_node<Ch>, public memory_pool<Ch>
-    {
-    
-    public:
-
-        //! Constructs empty XML document
-        xml_document()
-            : xml_node<Ch>(node_document)
-        {
-        }
-
-        //! Parses zero-terminated XML string according to given flags.
-        //! Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used.
-        //! The string must persist for the lifetime of the document.
-        //! In case of error, rapidxml::parse_error exception will be thrown.
-        //! <br><br>
-        //! If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning.
-        //! Make sure that data is zero-terminated.
-        //! <br><br>
-        //! Document can be parsed into multiple times. 
-        //! Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool.
-        //! \param text XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser.
-        template<int Flags>
-        void parse(Ch *text)
-        {
-            assert(text);
-            
-            // Remove current contents
-            this->remove_all_nodes();
-            this->remove_all_attributes();
-            
-            // Parse BOM, if any
-            parse_bom<Flags>(text);
-            
-            // Parse children
-            while (1)
-            {
-                // Skip whitespace before node
-                skip<whitespace_pred, Flags>(text);
-                if (*text == 0)
-                    break;
-
-                // Parse and append new child
-                if (*text == Ch('<'))
-                {
-                    ++text;     // Skip '<'
-                    if (xml_node<Ch> *node = parse_node<Flags>(text))
-                        this->append_node(node);
-                }
-                else
-                    RAPIDXML_PARSE_ERROR("expected <", text);
-            }
-
-        }
-
-        //! Clears the document by deleting all nodes and clearing the memory pool.
-        //! All nodes owned by document pool are destroyed.
-        void clear()
-        {
-            this->remove_all_nodes();
-            this->remove_all_attributes();
-            memory_pool<Ch>::clear();
-        }
-        
-    private:
-
-        ///////////////////////////////////////////////////////////////////////
-        // Internal character utility functions
-        
-        // Detect whitespace character
-        struct whitespace_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_whitespace[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect node name character
-        struct node_name_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_node_name[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect attribute name character
-        struct attribute_name_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_attribute_name[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect text character (PCDATA)
-        struct text_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_text[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect text character (PCDATA) that does not require processing
-        struct text_pure_no_ws_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_text_pure_no_ws[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect text character (PCDATA) that does not require processing
-        struct text_pure_with_ws_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                return internal::lookup_tables<0>::lookup_text_pure_with_ws[static_cast<unsigned char>(ch)];
-            }
-        };
-
-        // Detect attribute value character
-        template<Ch Quote>
-        struct attribute_value_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                if (Quote == Ch('\''))
-                    return internal::lookup_tables<0>::lookup_attribute_data_1[static_cast<unsigned char>(ch)];
-                if (Quote == Ch('\"'))
-                    return internal::lookup_tables<0>::lookup_attribute_data_2[static_cast<unsigned char>(ch)];
-                return 0;       // Should never be executed, to avoid warnings on Comeau
-            }
-        };
-
-        // Detect attribute value character
-        template<Ch Quote>
-        struct attribute_value_pure_pred
-        {
-            static unsigned char test(Ch ch)
-            {
-                if (Quote == Ch('\''))
-                    return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast<unsigned char>(ch)];
-                if (Quote == Ch('\"'))
-                    return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast<unsigned char>(ch)];
-                return 0;       // Should never be executed, to avoid warnings on Comeau
-            }
-        };
-
-        // Insert coded character, using UTF8 or 8-bit ASCII
-        template<int Flags>
-        static void insert_coded_character(Ch *&text, unsigned long code)
-        {
-            if (Flags & parse_no_utf8)
-            {
-                // Insert 8-bit ASCII character
-                // Todo: possibly verify that code is less than 256 and use replacement char otherwise?
-                text[0] = static_cast<unsigned char>(code);
-                text += 1;
-            }
-            else
-            {
-                // Insert UTF8 sequence
-                if (code < 0x80)    // 1 byte sequence
-                {
-                       text[0] = static_cast<unsigned char>(code);
-                    text += 1;
-                }
-                else if (code < 0x800)  // 2 byte sequence
-                {
-                       text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[0] = static_cast<unsigned char>(code | 0xC0);
-                    text += 2;
-                }
-                   else if (code < 0x10000)    // 3 byte sequence
-                {
-                       text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[0] = static_cast<unsigned char>(code | 0xE0);
-                    text += 3;
-                }
-                   else if (code < 0x110000)   // 4 byte sequence
-                {
-                       text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
-                       text[0] = static_cast<unsigned char>(code | 0xF0);
-                    text += 4;
-                }
-                else    // Invalid, only codes up to 0x10FFFF are allowed in Unicode
-                {
-                    RAPIDXML_PARSE_ERROR("invalid numeric character entity", text);
-                }
-            }
-        }
-
-        // Skip characters until predicate evaluates to true
-        template<class StopPred, int Flags>
-        static void skip(Ch *&text)
-        {
-            Ch *tmp = text;
-            while (StopPred::test(*tmp))
-                ++tmp;
-            text = tmp;
-        }
-
-        // Skip characters until predicate evaluates to true while doing the following:
-        // - replacing XML character entity references with proper characters (&apos; &amp; &quot; &lt; &gt; &#...;)
-        // - condensing whitespace sequences to single space character
-        template<class StopPred, class StopPredPure, int Flags>
-        static Ch *skip_and_expand_character_refs(Ch *&text)
-        {
-            // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip
-            if (Flags & parse_no_entity_translation && 
-                !(Flags & parse_normalize_whitespace) &&
-                !(Flags & parse_trim_whitespace))
-            {
-                skip<StopPred, Flags>(text);
-                return text;
-            }
-            
-            // Use simple skip until first modification is detected
-            skip<StopPredPure, Flags>(text);
-
-            // Use translation skip
-            Ch *src = text;
-            Ch *dest = src;
-            while (StopPred::test(*src))
-            {
-                // If entity translation is enabled    
-                if (!(Flags & parse_no_entity_translation))
-                {
-                    // Test if replacement is needed
-                    if (src[0] == Ch('&'))
-                    {
-                        switch (src[1])
-                        {
-
-                        // &amp; &apos;
-                        case Ch('a'): 
-                            if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';'))
-                            {
-                                *dest = Ch('&');
-                                ++dest;
-                                src += 5;
-                                continue;
-                            }
-                            if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';'))
-                            {
-                                *dest = Ch('\'');
-                                ++dest;
-                                src += 6;
-                                continue;
-                            }
-                            break;
-
-                        // &quot;
-                        case Ch('q'): 
-                            if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';'))
-                            {
-                                *dest = Ch('"');
-                                ++dest;
-                                src += 6;
-                                continue;
-                            }
-                            break;
-
-                        // &gt;
-                        case Ch('g'): 
-                            if (src[2] == Ch('t') && src[3] == Ch(';'))
-                            {
-                                *dest = Ch('>');
-                                ++dest;
-                                src += 4;
-                                continue;
-                            }
-                            break;
-
-                        // &lt;
-                        case Ch('l'): 
-                            if (src[2] == Ch('t') && src[3] == Ch(';'))
-                            {
-                                *dest = Ch('<');
-                                ++dest;
-                                src += 4;
-                                continue;
-                            }
-                            break;
-
-                        // &#...; - assumes ASCII
-                        case Ch('#'): 
-                            if (src[2] == Ch('x'))
-                            {
-                                unsigned long code = 0;
-                                src += 3;   // Skip &#x
-                                while (1)
-                                {
-                                    unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)];
-                                    if (digit == 0xFF)
-                                        break;
-                                    code = code * 16 + digit;
-                                    ++src;
-                                }
-                                insert_coded_character<Flags>(dest, code);    // Put character in output
-                            }
-                            else
-                            {
-                                unsigned long code = 0;
-                                src += 2;   // Skip &#
-                                while (1)
-                                {
-                                    unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)];
-                                    if (digit == 0xFF)
-                                        break;
-                                    code = code * 10 + digit;
-                                    ++src;
-                                }
-                                insert_coded_character<Flags>(dest, code);    // Put character in output
-                            }
-                            if (*src == Ch(';'))
-                                ++src;
-                            else
-                                RAPIDXML_PARSE_ERROR("expected ;", src);
-                            continue;
-
-                        // Something else
-                        default:
-                            // Ignore, just copy '&' verbatim
-                            break;
-
-                        }
-                    }
-                }
-                
-                // If whitespace condensing is enabled
-                if (Flags & parse_normalize_whitespace)
-                {
-                    // Test if condensing is needed                 
-                    if (whitespace_pred::test(*src))
-                    {
-                        *dest = Ch(' '); ++dest;    // Put single space in dest
-                        ++src;                      // Skip first whitespace char
-                        // Skip remaining whitespace chars
-                        while (whitespace_pred::test(*src))
-                            ++src;
-                        continue;
-                    }
-                }
-
-                // No replacement, only copy character
-                *dest++ = *src++;
-
-            }
-
-            // Return new end
-            text = src;
-            return dest;
-
-        }
-
-        ///////////////////////////////////////////////////////////////////////
-        // Internal parsing functions
-        
-        // Parse BOM, if any
-        template<int Flags>
-        void parse_bom(Ch *&text)
-        {
-            // UTF-8?
-            if (static_cast<unsigned char>(text[0]) == 0xEF && 
-                static_cast<unsigned char>(text[1]) == 0xBB && 
-                static_cast<unsigned char>(text[2]) == 0xBF)
-            {
-                text += 3;      // Skup utf-8 bom
-            }
-        }
-
-        // Parse XML declaration (<?xml...)
-        template<int Flags>
-        xml_node<Ch> *parse_xml_declaration(Ch *&text)
-        {
-            // If parsing of declaration is disabled
-            if (!(Flags & parse_declaration_node))
-            {
-                // Skip until end of declaration
-                while (text[0] != Ch('?') || text[1] != Ch('>'))
-                {
-                    if (!text[0])
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 2;    // Skip '?>'
-                return 0;
-            }
-
-            // Create declaration
-            xml_node<Ch> *declaration = this->allocate_node(node_declaration);
-
-            // Skip whitespace before attributes or ?>
-            skip<whitespace_pred, Flags>(text);
-
-            // Parse declaration attributes
-            parse_node_attributes<Flags>(text, declaration);
-            
-            // Skip ?>
-            if (text[0] != Ch('?') || text[1] != Ch('>'))
-                RAPIDXML_PARSE_ERROR("expected ?>", text);
-            text += 2;
-            
-            return declaration;
-        }
-
-        // Parse XML comment (<!--...)
-        template<int Flags>
-        xml_node<Ch> *parse_comment(Ch *&text)
-        {
-            // If parsing of comments is disabled
-            if (!(Flags & parse_comment_nodes))
-            {
-                // Skip until end of comment
-                while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
-                {
-                    if (!text[0])
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 3;     // Skip '-->'
-                return 0;      // Do not produce comment node
-            }
-
-            // Remember value start
-            Ch *value = text;
-
-            // Skip until end of comment
-            while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
-            {
-                if (!text[0])
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                ++text;
-            }
-
-            // Create comment node
-            xml_node<Ch> *comment = this->allocate_node(node_comment);
-            comment->value(value, text - value);
-            
-            // Place zero terminator after comment value
-            if (!(Flags & parse_no_string_terminators))
-                *text = Ch('\0');
-            
-            text += 3;     // Skip '-->'
-            return comment;
-        }
-
-        // Parse DOCTYPE
-        template<int Flags>
-        xml_node<Ch> *parse_doctype(Ch *&text)
-        {
-            // Remember value start
-            Ch *value = text;
-
-            // Skip to >
-            while (*text != Ch('>'))
-            {
-                // Determine character type
-                switch (*text)
-                {
-                
-                // If '[' encountered, scan for matching ending ']' using naive algorithm with depth
-                // This works for all W3C test files except for 2 most wicked
-                case Ch('['):
-                {
-                    ++text;     // Skip '['
-                    int depth = 1;
-                    while (depth > 0)
-                    {
-                        switch (*text)
-                        {
-                            case Ch('['): ++depth; break;
-                            case Ch(']'): --depth; break;
-                            case 0: RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                                                       default: break;
-                        }
-                        ++text;
-                    }
-                    break;
-                }
-                
-                // Error on end of text
-                case Ch('\0'):
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                
-                // Other character, skip it
-                default:
-                    ++text;
-
-                }
-            }
-            
-            // If DOCTYPE nodes enabled
-            if (Flags & parse_doctype_node)
-            {
-                // Create a new doctype node
-                xml_node<Ch> *doctype = this->allocate_node(node_doctype);
-                doctype->value(value, text - value);
-                
-                // Place zero terminator after value
-                if (!(Flags & parse_no_string_terminators))
-                    *text = Ch('\0');
-
-                text += 1;      // skip '>'
-                return doctype;
-            }
-            else
-            {
-                text += 1;      // skip '>'
-                return 0;
-            }
-
-        }
-
-        // Parse PI
-        template<int Flags>
-        xml_node<Ch> *parse_pi(Ch *&text)
-        {
-            // If creation of PI nodes is enabled
-            if (Flags & parse_pi_nodes)
-            {
-                // Create pi node
-                xml_node<Ch> *pi = this->allocate_node(node_pi);
-
-                // Extract PI target name
-                Ch *name = text;
-                skip<node_name_pred, Flags>(text);
-                if (text == name)
-                    RAPIDXML_PARSE_ERROR("expected PI target", text);
-                pi->name(name, text - name);
-                
-                // Skip whitespace between pi target and pi
-                skip<whitespace_pred, Flags>(text);
-
-                // Remember start of pi
-                Ch *value = text;
-                
-                // Skip to '?>'
-                while (text[0] != Ch('?') || text[1] != Ch('>'))
-                {
-                    if (*text == Ch('\0'))
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-
-                // Set pi value (verbatim, no entity expansion or whitespace normalization)
-                pi->value(value, text - value);     
-                
-                // Place zero terminator after name and value
-                if (!(Flags & parse_no_string_terminators))
-                {
-                    pi->name()[pi->name_size()] = Ch('\0');
-                    pi->value()[pi->value_size()] = Ch('\0');
-                }
-                
-                text += 2;                          // Skip '?>'
-                return pi;
-            }
-            else
-            {
-                // Skip to '?>'
-                while (text[0] != Ch('?') || text[1] != Ch('>'))
-                {
-                    if (*text == Ch('\0'))
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 2;    // Skip '?>'
-                return 0;
-            }
-        }
-
-        // Parse and append data
-        // Return character that ends data.
-        // This is necessary because this character might have been overwritten by a terminating 0
-        template<int Flags>
-        Ch parse_and_append_data(xml_node<Ch> *node, Ch *&text, Ch *contents_start)
-        {
-            // Backup to contents start if whitespace trimming is disabled
-            if (!(Flags & parse_trim_whitespace))
-                text = contents_start;     
-            
-            // Skip until end of data
-            Ch *value = text, *end;
-            if (Flags & parse_normalize_whitespace)
-                end = skip_and_expand_character_refs<text_pred, text_pure_with_ws_pred, Flags>(text);   
-            else
-                end = skip_and_expand_character_refs<text_pred, text_pure_no_ws_pred, Flags>(text);
-
-            // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after >
-            if (Flags & parse_trim_whitespace)
-            {
-                if (Flags & parse_normalize_whitespace)
-                {
-                    // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end
-                    if (*(end - 1) == Ch(' '))
-                        --end;
-                }
-                else
-                {
-                    // Backup until non-whitespace character is found
-                    while (whitespace_pred::test(*(end - 1)))
-                        --end;
-                }
-            }
-            
-            // If characters are still left between end and value (this test is only necessary if normalization is enabled)
-            // Create new data node
-            if (!(Flags & parse_no_data_nodes))
-            {
-                xml_node<Ch> *data = this->allocate_node(node_data);
-                data->value(value, end - value);
-                node->append_node(data);
-            }
-
-            // Add data to parent node if no data exists yet
-            if (!(Flags & parse_no_element_values)) 
-                if (*node->value() == Ch('\0'))
-                    node->value(value, end - value);
-
-            // Place zero terminator after value
-            if (!(Flags & parse_no_string_terminators))
-            {
-                Ch ch = *text;
-                *end = Ch('\0');
-                return ch;      // Return character that ends data; this is required because zero terminator overwritten it
-            }
-
-            // Return character that ends data
-            return *text;
-        }
-
-        // Parse CDATA
-        template<int Flags>
-        xml_node<Ch> *parse_cdata(Ch *&text)
-        {
-            // If CDATA is disabled
-            if (Flags & parse_no_data_nodes)
-            {
-                // Skip until end of cdata
-                while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
-                {
-                    if (!text[0])
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                text += 3;      // Skip ]]>
-                return 0;       // Do not produce CDATA node
-            }
-
-            // Skip until end of cdata
-            Ch *value = text;
-            while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
-            {
-                if (!text[0])
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                ++text;
-            }
-
-            // Create new cdata node
-            xml_node<Ch> *cdata = this->allocate_node(node_cdata);
-            cdata->value(value, text - value);
-
-            // Place zero terminator after value
-            if (!(Flags & parse_no_string_terminators))
-                *text = Ch('\0');
-
-            text += 3;      // Skip ]]>
-            return cdata;
-        }
-        
-        // Parse element node
-        template<int Flags>
-        xml_node<Ch> *parse_element(Ch *&text)
-        {
-            // Create element node
-            xml_node<Ch> *element = this->allocate_node(node_element);
-
-            // Extract element name
-            Ch *name = text;
-            skip<node_name_pred, Flags>(text);
-            if (text == name)
-                RAPIDXML_PARSE_ERROR("expected element name", text);
-            element->name(name, text - name);
-            
-            // Skip whitespace between element name and attributes or >
-            skip<whitespace_pred, Flags>(text);
-
-            // Parse attributes, if any
-            parse_node_attributes<Flags>(text, element);
-
-            // Determine ending type
-            if (*text == Ch('>'))
-            {
-                ++text;
-                parse_node_contents<Flags>(text, element);
-            }
-            else if (*text == Ch('/'))
-            {
-                ++text;
-                if (*text != Ch('>'))
-                    RAPIDXML_PARSE_ERROR("expected >", text);
-                ++text;
-            }
-            else
-                RAPIDXML_PARSE_ERROR("expected >", text);
-
-            // Place zero terminator after name
-            if (!(Flags & parse_no_string_terminators))
-                element->name()[element->name_size()] = Ch('\0');
-
-            // Return parsed element
-            return element;
-        }
-
-        // Determine node type, and parse it
-        template<int Flags>
-        xml_node<Ch> *parse_node(Ch *&text)
-        {
-            // Parse proper node type
-            switch (text[0])
-            {
-
-            // <...
-            default: 
-                // Parse and append element node
-                return parse_element<Flags>(text);
-
-            // <?...
-            case Ch('?'): 
-                ++text;     // Skip ?
-                if ((text[0] == Ch('x') || text[0] == Ch('X')) &&
-                    (text[1] == Ch('m') || text[1] == Ch('M')) && 
-                    (text[2] == Ch('l') || text[2] == Ch('L')) &&
-                    whitespace_pred::test(text[3]))
-                {
-                    // '<?xml ' - xml declaration
-                    text += 4;      // Skip 'xml '
-                    return parse_xml_declaration<Flags>(text);
-                }
-                else
-                {
-                    // Parse PI
-                    return parse_pi<Flags>(text);
-                }
-            
-            // <!...
-            case Ch('!'): 
-
-                // Parse proper subset of <! node
-                switch (text[1])    
-                {
-                
-                // <!-
-                case Ch('-'):
-                    if (text[2] == Ch('-'))
-                    {
-                        // '<!--' - xml comment
-                        text += 3;     // Skip '!--'
-                        return parse_comment<Flags>(text);
-                    }
-                    break;
-
-                // <![
-                case Ch('['):
-                    if (text[2] == Ch('C') && text[3] == Ch('D') && text[4] == Ch('A') && 
-                        text[5] == Ch('T') && text[6] == Ch('A') && text[7] == Ch('['))
-                    {
-                        // '<![CDATA[' - cdata
-                        text += 8;     // Skip '![CDATA['
-                        return parse_cdata<Flags>(text);
-                    }
-                    break;
-
-                // <!D
-                case Ch('D'):
-                    if (text[2] == Ch('O') && text[3] == Ch('C') && text[4] == Ch('T') && 
-                        text[5] == Ch('Y') && text[6] == Ch('P') && text[7] == Ch('E') && 
-                        whitespace_pred::test(text[8]))
-                    {
-                        // '<!DOCTYPE ' - doctype
-                        text += 9;      // skip '!DOCTYPE '
-                        return parse_doctype<Flags>(text);
-                    }
-                                       break;
-                               
-                               default:
-                                       break;
-
-                }   // switch
-
-                // Attempt to skip other, unrecognized node types starting with <!
-                ++text;     // Skip !
-                while (*text != Ch('>'))
-                {
-                    if (*text == 0)
-                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-                    ++text;
-                }
-                ++text;     // Skip '>'
-                return 0;   // No node recognized
-
-            }
-        }
-
-        // Parse contents of the node - children, data etc.
-        template<int Flags>
-        void parse_node_contents(Ch *&text, xml_node<Ch> *node)
-        {
-            // For all children and text
-            while (1)
-            {
-                // Skip whitespace between > and node contents
-                Ch *contents_start = text;      // Store start of node contents before whitespace is skipped
-                skip<whitespace_pred, Flags>(text);
-                Ch next_char = *text;
-
-            // After data nodes, instead of continuing the loop, control jumps here.
-            // This is because zero termination inside parse_and_append_data() function
-            // would wreak havoc with the above code.
-            // Also, skipping whitespace after data nodes is unnecessary.
-            after_data_node:    
-                
-                // Determine what comes next: node closing, child node, data node, or 0?
-                switch (next_char)
-                {
-                
-                // Node closing or child node
-                case Ch('<'):
-                    if (text[1] == Ch('/'))
-                    {
-                        // Node closing
-                        text += 2;      // Skip '</'
-                        if (Flags & parse_validate_closing_tags)
-                        {
-                            // Skip and validate closing tag name
-                            Ch *closing_name = text;
-                            skip<node_name_pred, Flags>(text);
-                            if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true))
-                                RAPIDXML_PARSE_ERROR("invalid closing tag name", text);
-                        }
-                        else
-                        {
-                            // No validation, just skip name
-                            skip<node_name_pred, Flags>(text);
-                        }
-                        // Skip remaining whitespace after node name
-                        skip<whitespace_pred, Flags>(text);
-                        if (*text != Ch('>'))
-                            RAPIDXML_PARSE_ERROR("expected >", text);
-                        ++text;     // Skip '>'
-                        return;     // Node closed, finished parsing contents
-                    }
-                    else
-                    {
-                        // Child node
-                        ++text;     // Skip '<'
-                        if (xml_node<Ch> *child = parse_node<Flags>(text))
-                            node->append_node(child);
-                    }
-                    break;
-
-                // End of data - error
-                case Ch('\0'):
-                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
-
-                // Data node
-                default:
-                    next_char = parse_and_append_data<Flags>(node, text, contents_start);
-                    goto after_data_node;   // Bypass regular processing after data nodes
-
-                }
-            }
-        }
-        
-        // Parse XML attributes of the node
-        template<int Flags>
-        void parse_node_attributes(Ch *&text, xml_node<Ch> *node)
-        {
-            // For all attributes 
-            while (attribute_name_pred::test(*text))
-            {
-                // Extract attribute name
-                Ch *name = text;
-                ++text;     // Skip first character of attribute name
-                skip<attribute_name_pred, Flags>(text);
-                if (text == name)
-                    RAPIDXML_PARSE_ERROR("expected attribute name", name);
-
-                // Create new attribute
-                xml_attribute<Ch> *attribute = this->allocate_attribute();
-                attribute->name(name, text - name);
-                node->append_attribute(attribute);
-
-                // Skip whitespace after attribute name
-                skip<whitespace_pred, Flags>(text);
-
-                // Skip =
-                if (*text != Ch('='))
-                    RAPIDXML_PARSE_ERROR("expected =", text);
-                ++text;
-
-                // Add terminating zero after name
-                if (!(Flags & parse_no_string_terminators))
-                    attribute->name()[attribute->name_size()] = 0;
-
-                // Skip whitespace after =
-                skip<whitespace_pred, Flags>(text);
-
-                // Skip quote and remember if it was ' or "
-                Ch quote = *text;
-                if (quote != Ch('\'') && quote != Ch('"'))
-                    RAPIDXML_PARSE_ERROR("expected ' or \"", text);
-                ++text;
-
-                // Extract attribute value and expand char refs in it
-                Ch *value = text, *end;
-                const int AttFlags = Flags & ~parse_normalize_whitespace;   // No whitespace normalization in attributes
-                if (quote == Ch('\''))
-                    end = skip_and_expand_character_refs<attribute_value_pred<Ch('\'')>, attribute_value_pure_pred<Ch('\'')>, AttFlags>(text);
-                else
-                    end = skip_and_expand_character_refs<attribute_value_pred<Ch('"')>, attribute_value_pure_pred<Ch('"')>, AttFlags>(text);
-                
-                // Set attribute value
-                attribute->value(value, end - value);
-                
-                // Make sure that end quote is present
-                if (*text != quote)
-                    RAPIDXML_PARSE_ERROR("expected ' or \"", text);
-                ++text;     // Skip quote
-
-                // Add terminating zero after value
-                if (!(Flags & parse_no_string_terminators))
-                    attribute->value()[attribute->value_size()] = 0;
-
-                // Skip whitespace after attribute value
-                skip<whitespace_pred, Flags>(text);
-            }
-        }
-
-    };
-
-    //! \cond internal
-    namespace internal
-    {
-
-        // Whitespace (space \n \r \t)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_whitespace[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  0,  1,  0,  0,  // 0
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 1
-             1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 2
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 3
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 4
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 5
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 6
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 7
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 8
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 9
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // A
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // B
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // C
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // D
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // E
-             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0   // F
-        };
-
-        // Node name (anything but space \n \r \t / > ? \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_node_name[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Text (i.e. PCDATA) (anything but < \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_text[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled 
-        // (anything but < \0 &)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_text_pure_no_ws[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled
-        // (anything but < \0 & space \n \r \t)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_text_pure_with_ws[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             0,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute name (anything but space \n \r \t / < > = ? ! \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_name[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with single quote (anything but ' \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with single quote that does not require processing (anything but ' \0 &)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1_pure[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with double quote (anything but " \0)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Attribute data with double quote that does not require processing (anything but " \0 &)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2_pure[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
-             1,  1,  0,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
-             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
-        };
-
-        // Digits (dec and hex, 255 denotes end of numeric character reference)
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_digits[256] = 
-        {
-          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 0
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 1
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 2
-             0,  1,  2,  3,  4,  5,  6,  7,  8,  9,255,255,255,255,255,255,  // 3
-           255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255,  // 4
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 5
-           255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255,  // 6
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 7
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 8
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 9
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // A
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // B
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // C
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // D
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // E
-           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255   // F
-        };
-    
-        // Upper case conversion
-        template<int Dummy>
-        const unsigned char lookup_tables<Dummy>::lookup_upcase[256] = 
-        {
-          // 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  A   B   C   D   E   F
-           0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15,   // 0
-           16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,   // 1
-           32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,   // 2
-           48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,   // 3
-           64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 4
-           80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,   // 5
-           96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 6
-           80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127,  // 7
-           128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,  // 8
-           144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,  // 9
-           160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,  // A
-           176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,  // B
-           192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,  // C
-           208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,  // D
-           224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,  // E
-           240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255   // F
-        };
-    }
-    //! \endcond
-
-}
-
-// Undefine internal macros
-#undef RAPIDXML_PARSE_ERROR
-
-// On MSVC, restore warnings state
-#ifdef _MSC_VER
-    #pragma warning(pop)
-#endif
-
-#endif
diff --git a/service/soft-sensor-manager/SSMCore/src/Common/rapidxml_iterators.hpp b/service/soft-sensor-manager/SSMCore/src/Common/rapidxml_iterators.hpp
deleted file mode 100644 (file)
index 52ebc29..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-#ifndef RAPIDXML_ITERATORS_HPP_INCLUDED
-#define RAPIDXML_ITERATORS_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml_iterators.hpp This file contains rapidxml iterators
-
-#include "rapidxml.hpp"
-
-namespace rapidxml
-{
-
-    //! Iterator of child nodes of xml_node
-    template<class Ch>
-    class node_iterator
-    {
-    
-    public:
-
-        typedef typename xml_node<Ch> value_type;
-        typedef typename xml_node<Ch> &reference;
-        typedef typename xml_node<Ch> *pointer;
-        typedef std::ptrdiff_t difference_type;
-        typedef std::bidirectional_iterator_tag iterator_category;
-        
-        node_iterator()
-            : m_node(0)
-        {
-        }
-
-        node_iterator(xml_node<Ch> *node)
-            : m_node(node->first_node())
-        {
-        }
-        
-        reference operator *() const
-        {
-            assert(m_node);
-            return *m_node;
-        }
-
-        pointer operator->() const
-        {
-            assert(m_node);
-            return m_node;
-        }
-
-        node_iterator& operator++()
-        {
-            assert(m_node);
-            m_node = m_node->next_sibling();
-            return *this;
-        }
-
-        node_iterator operator++(int)
-        {
-            node_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        node_iterator& operator--()
-        {
-            assert(m_node && m_node->previous_sibling());
-            m_node = m_node->previous_sibling();
-            return *this;
-        }
-
-        node_iterator operator--(int)
-        {
-            node_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        bool operator ==(const node_iterator<Ch> &rhs)
-        {
-            return m_node == rhs.m_node;
-        }
-
-        bool operator !=(const node_iterator<Ch> &rhs)
-        {
-            return m_node != rhs.m_node;
-        }
-
-    private:
-
-        xml_node<Ch> *m_node;
-
-    };
-
-    //! Iterator of child attributes of xml_node
-    template<class Ch>
-    class attribute_iterator
-    {
-    
-    public:
-
-        typedef typename xml_attribute<Ch> value_type;
-        typedef typename xml_attribute<Ch> &reference;
-        typedef typename xml_attribute<Ch> *pointer;
-        typedef std::ptrdiff_t difference_type;
-        typedef std::bidirectional_iterator_tag iterator_category;
-        
-        attribute_iterator()
-            : m_attribute(0)
-        {
-        }
-
-        attribute_iterator(xml_node<Ch> *node)
-            : m_attribute(node->first_attribute())
-        {
-        }
-        
-        reference operator *() const
-        {
-            assert(m_attribute);
-            return *m_attribute;
-        }
-
-        pointer operator->() const
-        {
-            assert(m_attribute);
-            return m_attribute;
-        }
-
-        attribute_iterator& operator++()
-        {
-            assert(m_attribute);
-            m_attribute = m_attribute->next_attribute();
-            return *this;
-        }
-
-        attribute_iterator operator++(int)
-        {
-            attribute_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        attribute_iterator& operator--()
-        {
-            assert(m_attribute && m_attribute->previous_attribute());
-            m_attribute = m_attribute->previous_attribute();
-            return *this;
-        }
-
-        attribute_iterator operator--(int)
-        {
-            attribute_iterator tmp = *this;
-            ++this;
-            return tmp;
-        }
-
-        bool operator ==(const attribute_iterator<Ch> &rhs)
-        {
-            return m_attribute == rhs.m_attribute;
-        }
-
-        bool operator !=(const attribute_iterator<Ch> &rhs)
-        {
-            return m_attribute != rhs.m_attribute;
-        }
-
-    private:
-
-        xml_attribute<Ch> *m_attribute;
-
-    };
-
-}
-
-#endif
diff --git a/service/soft-sensor-manager/SSMCore/src/Common/rapidxml_print.hpp b/service/soft-sensor-manager/SSMCore/src/Common/rapidxml_print.hpp
deleted file mode 100644 (file)
index f929b3c..0000000
+++ /dev/null
@@ -1,422 +0,0 @@
-#ifndef RAPIDXML_PRINT_HPP_INCLUDED
-#define RAPIDXML_PRINT_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml_print.hpp This file contains rapidxml printer implementation
-
-#include "rapidxml.hpp"
-
-// Only include streams if not disabled
-#ifndef RAPIDXML_NO_STREAMS
-    #include <ostream>
-    #include <iterator>
-#endif
-
-namespace rapidxml
-{
-
-    ///////////////////////////////////////////////////////////////////////
-    // Printing flags
-
-    const int print_no_indenting = 0x1;   //!< Printer flag instructing the printer to suppress indenting of XML. See print() function.
-
-    ///////////////////////////////////////////////////////////////////////
-    // Internal
-
-    //! \cond internal
-    namespace internal
-    {
-        
-        ///////////////////////////////////////////////////////////////////////////
-        // Internal character operations
-    
-        // Copy characters from given range to given output iterator
-        template<class OutIt, class Ch>
-        inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out)
-        {
-            while (begin != end)
-                *out++ = *begin++;
-            return out;
-        }
-        
-        // Copy characters from given range to given output iterator and expand
-        // characters into references (&lt; &gt; &apos; &quot; &amp;)
-        template<class OutIt, class Ch>
-        inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out)
-        {
-            while (begin != end)
-            {
-                if (*begin == noexpand)
-                {
-                    *out++ = *begin;    // No expansion, copy character
-                }
-                else
-                {
-                    switch (*begin)
-                    {
-                    case Ch('<'):
-                        *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';');
-                        break;
-                    case Ch('>'): 
-                        *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';');
-                        break;
-                    case Ch('\''): 
-                        *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';');
-                        break;
-                    case Ch('"'): 
-                        *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';');
-                        break;
-                    case Ch('&'): 
-                        *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); 
-                        break;
-                    default:
-                        *out++ = *begin;    // No expansion, copy character
-                    }
-                }
-                ++begin;    // Step to next character
-            }
-            return out;
-        }
-
-        // Fill given output iterator with repetitions of the same character
-        template<class OutIt, class Ch>
-        inline OutIt fill_chars(OutIt out, int n, Ch ch)
-        {
-            for (int i = 0; i < n; ++i)
-                *out++ = ch;
-            return out;
-        }
-
-        // Find character
-        template<class Ch, Ch ch>
-        inline bool find_char(const Ch *begin, const Ch *end)
-        {
-            while (begin != end)
-                if (*begin++ == ch)
-                    return true;
-            return false;
-        }
-
-        template<class OutIt, class Ch>
-        inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);
-
-        // Print children of the node                               
-        template<class OutIt, class Ch>
-        inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling())
-                out = print_node(out, child, flags, indent);
-            return out;
-        }
-
-        // Print attributes of the node
-        template<class OutIt, class Ch>
-        inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags)
-        {
-            for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute())
-            {
-                if (attribute->name() && attribute->value())
-                {
-                    // Print attribute name
-                    *out = Ch(' '), ++out;
-                    out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out);
-                    *out = Ch('='), ++out;
-                    // Print attribute value using appropriate quote type
-                    if (find_char<Ch, Ch('"')>(attribute->value(), attribute->value() + attribute->value_size()))
-                    {
-                        *out = Ch('\''), ++out;
-                        out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out);
-                        *out = Ch('\''), ++out;
-                    }
-                    else
-                    {
-                        *out = Ch('"'), ++out;
-                        out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out);
-                        *out = Ch('"'), ++out;
-                    }
-                }
-            }
-            return out;
-        }
-
-        // Print data node
-        template<class OutIt, class Ch>
-        inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_data);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
-            return out;
-        }
-
-        // Print data node
-        template<class OutIt, class Ch>
-        inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_cdata);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'); ++out;
-            *out = Ch('!'); ++out;
-            *out = Ch('['); ++out;
-            *out = Ch('C'); ++out;
-            *out = Ch('D'); ++out;
-            *out = Ch('A'); ++out;
-            *out = Ch('T'); ++out;
-            *out = Ch('A'); ++out;
-            *out = Ch('['); ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch(']'); ++out;
-            *out = Ch(']'); ++out;
-            *out = Ch('>'); ++out;
-            return out;
-        }
-
-        // Print element node
-        template<class OutIt, class Ch>
-        inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_element);
-
-            // Print element name and attributes, if any
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            out = copy_chars(node->name(), node->name() + node->name_size(), out);
-            out = print_attributes(out, node, flags);
-            
-            // If node is childless
-            if (node->value_size() == 0 && !node->first_node())
-            {
-                // Print childless node tag ending
-                *out = Ch('/'), ++out;
-                *out = Ch('>'), ++out;
-            }
-            else
-            {
-                // Print normal node tag ending
-                *out = Ch('>'), ++out;
-
-                // Test if node contains a single data node only (and no other nodes)
-                xml_node<Ch> *child = node->first_node();
-                if (!child)
-                {
-                    // If node has no children, only print its value without indenting
-                    out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
-                }
-                else if (child->next_sibling() == 0 && child->type() == node_data)
-                {
-                    // If node has a sole data child, only print its value without indenting
-                    out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out);
-                }
-                else
-                {
-                    // Print all children with full indenting
-                    if (!(flags & print_no_indenting))
-                        *out = Ch('\n'), ++out;
-                    out = print_children(out, node, flags, indent + 1);
-                    if (!(flags & print_no_indenting))
-                        out = fill_chars(out, indent, Ch('\t'));
-                }
-
-                // Print node end
-                *out = Ch('<'), ++out;
-                *out = Ch('/'), ++out;
-                out = copy_chars(node->name(), node->name() + node->name_size(), out);
-                *out = Ch('>'), ++out;
-            }
-            return out;
-        }
-
-        // Print declaration node
-        template<class OutIt, class Ch>
-        inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            // Print declaration start
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('?'), ++out;
-            *out = Ch('x'), ++out;
-            *out = Ch('m'), ++out;
-            *out = Ch('l'), ++out;
-
-            // Print attributes
-            out = print_attributes(out, node, flags);
-            
-            // Print declaration end
-            *out = Ch('?'), ++out;
-            *out = Ch('>'), ++out;
-            
-            return out;
-        }
-
-        // Print comment node
-        template<class OutIt, class Ch>
-        inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_comment);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('!'), ++out;
-            *out = Ch('-'), ++out;
-            *out = Ch('-'), ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch('-'), ++out;
-            *out = Ch('-'), ++out;
-            *out = Ch('>'), ++out;
-            return out;
-        }
-
-        // Print doctype node
-        template<class OutIt, class Ch>
-        inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_doctype);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('!'), ++out;
-            *out = Ch('D'), ++out;
-            *out = Ch('O'), ++out;
-            *out = Ch('C'), ++out;
-            *out = Ch('T'), ++out;
-            *out = Ch('Y'), ++out;
-            *out = Ch('P'), ++out;
-            *out = Ch('E'), ++out;
-            *out = Ch(' '), ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch('>'), ++out;
-            return out;
-        }
-
-        // Print pi node
-        template<class OutIt, class Ch>
-        inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            assert(node->type() == node_pi);
-            if (!(flags & print_no_indenting))
-                out = fill_chars(out, indent, Ch('\t'));
-            *out = Ch('<'), ++out;
-            *out = Ch('?'), ++out;
-            out = copy_chars(node->name(), node->name() + node->name_size(), out);
-            *out = Ch(' '), ++out;
-            out = copy_chars(node->value(), node->value() + node->value_size(), out);
-            *out = Ch('?'), ++out;
-            *out = Ch('>'), ++out;
-            return out;
-        }
-        ///////////////////////////////////////////////////////////////////////////
-                // Internal printing operations
-
-                // Print node
-                template<class OutIt, class Ch>
-                inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-                {
-                    // Print proper node type
-                    switch (node->type())
-                    {
-
-                    // Document
-                    case node_document:
-                        out = print_children(out, node, flags, indent);
-                        break;
-
-                    // Element
-                    case node_element:
-                        out = print_element_node(out, node, flags, indent);
-                        break;
-
-                    // Data
-                    case node_data:
-                        out = print_data_node(out, node, flags, indent);
-                        break;
-
-                    // CDATA
-                    case node_cdata:
-                        out = print_cdata_node(out, node, flags, indent);
-                        break;
-
-                    // Declaration
-                    case node_declaration:
-                        out = print_declaration_node(out, node, flags, indent);
-                        break;
-
-                    // Comment
-                    case node_comment:
-                        out = print_comment_node(out, node, flags, indent);
-                        break;
-
-                    // Doctype
-                    case node_doctype:
-                        out = print_doctype_node(out, node, flags, indent);
-                        break;
-
-                    // Pi
-                    case node_pi:
-                        out = print_pi_node(out, node, flags, indent);
-                        break;
-
-                        // Unknown
-                    default:
-                        assert(0);
-                        break;
-                    }
-
-                    // If indenting not disabled, add line break after node
-                    if (!(flags & print_no_indenting))
-                        *out = Ch('\n'), ++out;
-
-                    // Return modified iterator
-                    return out;
-                }
-    }
-    //! \endcond
-
-    ///////////////////////////////////////////////////////////////////////////
-    // Printing
-
-    //! Prints XML to given output iterator.
-    //! \param out Output iterator to print to.
-    //! \param node Node to be printed. Pass xml_document to print entire document.
-    //! \param flags Flags controlling how XML is printed.
-    //! \return Output iterator pointing to position immediately after last character of printed text.
-    template<class OutIt, class Ch> 
-    inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0)
-    {
-        return internal::print_node(out, &node, flags, 0);
-    }
-
-#ifndef RAPIDXML_NO_STREAMS
-
-    //! Prints XML to given output stream.
-    //! \param out Output stream to print to.
-    //! \param node Node to be printed. Pass xml_document to print entire document.
-    //! \param flags Flags controlling how XML is printed.
-    //! \return Output stream.
-    template<class Ch> 
-    inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node, int flags = 0)
-    {
-        print(std::ostream_iterator<Ch>(out), node, flags);
-        return out;
-    }
-
-    //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.
-    //! \param out Output stream to print to.
-    //! \param node Node to be printed.
-    //! \return Output stream.
-    template<class Ch> 
-    inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node)
-    {
-        return print(out, node);
-    }
-
-#endif
-
-}
-
-#endif
diff --git a/service/soft-sensor-manager/SSMCore/src/Common/rapidxml_utils.hpp b/service/soft-sensor-manager/SSMCore/src/Common/rapidxml_utils.hpp
deleted file mode 100644 (file)
index 37c2953..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-#ifndef RAPIDXML_UTILS_HPP_INCLUDED
-#define RAPIDXML_UTILS_HPP_INCLUDED
-
-// Copyright (C) 2006, 2009 Marcin Kalicinski
-// Version 1.13
-// Revision $DateTime: 2009/05/13 01:46:17 $
-//! \file rapidxml_utils.hpp This file contains high-level rapidxml utilities that can be useful
-//! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective.
-
-#include "rapidxml.hpp"
-#include <vector>
-#include <string>
-#include <fstream>
-#include <stdexcept>
-
-namespace rapidxml
-{
-
-    //! Represents data loaded from a file
-    template<class Ch = char>
-    class file
-    {
-        
-    public:
-        
-        //! Loads file into the memory. Data will be automatically destroyed by the destructor.
-        //! \param filename Filename to load.
-        file(const char *filename)
-        {
-            using namespace std;
-
-            // Open stream
-            basic_ifstream<Ch> stream(filename, ios::binary);
-            if (!stream)
-                throw runtime_error(string("cannot open file ") + filename);
-            stream.unsetf(ios::skipws);
-            
-            // Determine stream size
-            stream.seekg(0, ios::end);
-            size_t size = stream.tellg();
-            stream.seekg(0);   
-            
-            // Load data and add terminating 0
-            m_data.resize(size + 1);
-            stream.read(&m_data.front(), static_cast<streamsize>(size));
-            m_data[size] = 0;
-        }
-
-        //! Loads file into the memory. Data will be automatically destroyed by the destructor
-        //! \param stream Stream to load from
-        file(std::basic_istream<Ch> &stream)
-        {
-            using namespace std;
-
-            // Load data and add terminating 0
-            stream.unsetf(ios::skipws);
-            m_data.assign(istreambuf_iterator<Ch>(stream), istreambuf_iterator<Ch>());
-            if (stream.fail() || stream.bad())
-                throw runtime_error("error reading stream");
-            m_data.push_back(0);
-        }
-        
-        //! Gets file data.
-        //! \return Pointer to data of file.
-        Ch *data()
-        {
-            return &m_data.front();
-        }
-
-        //! Gets file data.
-        //! \return Pointer to data of file.
-        const Ch *data() const
-        {
-            return &m_data.front();
-        }
-
-        //! Gets file data size.
-        //! \return Size of file data, in characters.
-        std::size_t size() const
-        {
-            return m_data.size();
-        }
-
-    private:
-
-        std::vector<Ch> m_data;   // File data
-
-    };
-
-    //! Counts children of node. Time complexity is O(n).
-    //! \return Number of children of node
-    template<class Ch>
-    inline std::size_t count_children(xml_node<Ch> *node)
-    {
-        xml_node<Ch> *child = node->first_node();
-        std::size_t count = 0;
-        while (child)
-        {
-            ++count;
-            child = child->next_sibling();
-        }
-        return count;
-    }
-
-    //! Counts attributes of node. Time complexity is O(n).
-    //! \return Number of attributes of node
-    template<class Ch>
-    inline std::size_t count_attributes(xml_node<Ch> *node)
-    {
-        xml_attribute<Ch> *attr = node->first_attribute();
-        std::size_t count = 0;
-        while (attr)
-        {
-            ++count;
-            attr = attr->next_attribute();
-        }
-        return count;
-    }
-
-}
-
-#endif
index 7ba46e7..58d1ece 100644 (file)
@@ -27,7 +27,7 @@ Token::Token()
     condition = ModelCondition::PREDICATE_EQ;
 }
 
-std::vector<std::string> CCQLParser::tokenize(IN const std::string &input)
+std::vector<std::string> CCQLParser::tokenize(const std::string &input)
 {
     std::vector<std::string> temp;
     temp.push_back(",");
@@ -51,11 +51,12 @@ std::vector<std::string> CCQLParser::tokenize(IN const std::string &input)
     return tokens_temp;
 }
 
-void CCQLParser::parse(IN std::string input, OUT Token *root)
+bool CCQLParser::parse(std::string input, Token *root)
 {
     std::vector<std::string> tokens = tokenize(input);
     bool flag;//get,sub,if
     bool value_flag = false;
+    bool isCondition = false;
 
     for (unsigned int i = 0 ; i < tokens.size() ; i++)
     {
@@ -82,6 +83,7 @@ void CCQLParser::parse(IN std::string input, OUT Token *root)
                 i++;
                 //temp1 = temp;
                 flag = false;
+                isCondition = true;
             }
             else
             {
@@ -95,6 +97,7 @@ void CCQLParser::parse(IN std::string input, OUT Token *root)
                 if (tokens.at(i) == "if")
                 {
                     flag = false;
+                    isCondition = true;
                 }
                 else
                 {
@@ -102,6 +105,7 @@ void CCQLParser::parse(IN std::string input, OUT Token *root)
                 }
             }
 
+            SORT lastType = Command;
             while (1)
             {
                 //int count = 0;
@@ -110,6 +114,7 @@ void CCQLParser::parse(IN std::string input, OUT Token *root)
                 if (value_flag == true)
                 {
                     value_flag = false;
+                    lastType = Context;
                     i++;
                 }
 
@@ -164,8 +169,13 @@ void CCQLParser::parse(IN std::string input, OUT Token *root)
                 else
                 {
                     temp1.type = Context;
-                }
 
+                    //if current context token is reserved keyword, that return error
+                    if (tolower(tokens.at(i)) == "get" || tolower(tokens.at(i)) == "subscribe")
+                    {
+                        return false;
+                    }
+                }
 
                 if (flag == true)
                 {
@@ -175,23 +185,45 @@ void CCQLParser::parse(IN std::string input, OUT Token *root)
                         temp1.type = And_or;
                         flag = false;
                     }
-                    split(tokens.at(i), &temp1, flag );//false -> Property
-                    temp.child_token.push_back(temp1);
+
+                    if (split(tokens.at(i), &temp1, flag ) != true) //false -> Property
+                    {
+                        return false;
+                    }
                 }
                 else
                 {
-                    split(tokens.at(i), &temp1, flag , tokens.at(i + 1), tokens.at(i + 2)); //false -> Property
+                    //token count not matched, return and let grammer checker detects
+                    if (tokens.size() < i + 3)
+                    {
+                        return false;
+                    }
+
+                    if (split(tokens.at(i), &temp1, flag , tokens.at(i + 1),
+                              tokens.at(i + 2)) != true) //false -> Property
+                    {
+                        return false;
+                    }
                     flag = true;
-                    temp.child_token.push_back(temp1);
                 }
 
+                if (isCondition && lastType == temp1.type)
+                {
+                    return false;
+                }
+
+                lastType = temp1.type;
+
+                temp.child_token.push_back(temp1);
             }
             root->child_token.push_back(temp);
         }
     }
+
+    return true;
 }
 
-std::string CCQLParser::tolower(IN std::string str)
+std::string CCQLParser::tolower(std::string str)
 {
     for (unsigned int i = 0 ; i < str.size() ; i++)
     {
@@ -204,8 +236,8 @@ std::string CCQLParser::tolower(IN std::string str)
     return str;
 }
 
-std::vector<std::string> CCQLParser::getTokens(IN const std::string &str,
-        IN const std::string &delimiters)
+std::vector<std::string> CCQLParser::getTokens(const std::string &str,
+        const std::string &delimiters)
 {
     std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
     std::string::size_type pos     = str.find_first_of(delimiters, lastPos);
@@ -218,10 +250,13 @@ std::vector<std::string> CCQLParser::getTokens(IN const std::string &str,
         pos = str.find_first_of(delimiters, lastPos);
     }
 
+    if (tokens.size() == 0)
+        tokens.push_back("\"\"");
+
     return tokens;
 }
 
-void CCQLParser::check_index(IN std::string input, OUT Token *token)
+void CCQLParser::check_index(std::string input, Token *token)
 {
     std::vector<std::string> tokens = getTokens(input, "[");
 
@@ -248,8 +283,8 @@ void CCQLParser::check_index(IN std::string input, OUT Token *token)
     }
 }
 
-void CCQLParser::split(IN std::string input, IN Token *root, bool flag, IN std::string arg1,
-                       IN std::string arg2)
+bool CCQLParser::split(std::string input, Token *root, bool flag, std::string arg1,
+                       std::string arg2)
 {
     std::vector<std::string> tokens = getTokens(input, ".");
     Token *temp_token = root;
@@ -280,7 +315,7 @@ void CCQLParser::split(IN std::string input, IN Token *root, bool flag, IN std::
                     //root->child_token.push_back(temp1);
                 }
 
-                else if (check_number(arg2))
+                else
                 {
                     //temp1->number = atof(arg2.c_str());
 
@@ -293,6 +328,11 @@ void CCQLParser::split(IN std::string input, IN Token *root, bool flag, IN std::
                     {
                         property.propertyType = ModelProperty::TYPE_REAL;
                     }
+                    else
+                    {
+                        //unknown type raise error
+                        return false;
+                    }
                     property.propertyValue = arg2;
 
                     temp_token->model_property = property;
@@ -307,47 +347,47 @@ void CCQLParser::split(IN std::string input, IN Token *root, bool flag, IN std::
                 temp_token->child_token.push_back(temp1);
                 temp_token = &(temp_token->child_token.back());
             }
-
         }
     }
+
+    return true;
 }
 
-int CCQLParser::check_number(IN std::string &str)
+int CCQLParser::check_number(std::string &str)
 {
-    //int flag = 0; // 0 text /1 integer /2 real
+    int flag = 0; // 0 text /1 integer /2 real
+    int dotCount = 0;
 
-    int flag = 0;
-    for (unsigned int i = 0 ; i < str.size(); i++)
+    std::string::const_iterator it = str.begin();
+    while (it != str.end())
     {
-        if (str[i] == '.')
-        {
-            flag++;
-        }
-        else if (isdigit(str[i]))
+        if (*it == '.')
         {
-
+            dotCount++;
         }
-        else
+        else if (isdigit(*it) == false)
         {
-            return TYPETEXT;
+            //this is text
+            dotCount = 2;
+            break;
         }
-    }
 
-    if (flag == 1)
-    {
-        return TYPEREAL;
+        ++it;
     }
-    else if (flag > 1)
+
+    if (dotCount == 0)
     {
-        return TYPETEXT;
+        flag = 1;
     }
-    else
+    else if (dotCount == 1)
     {
-        return TYPEINTEGER;
+        flag = 2;
     }
+
+    return flag;
 }
 
-std::string CCQLParser::check_Predicate(IN std::string input)
+std::string CCQLParser::check_Predicate(std::string input)
 {
     std::string temp = "";
     for (unsigned int i = 0 ; i < input.size() ; i++)
@@ -393,7 +433,7 @@ std::string CCQLParser::check_Predicate(IN std::string input)
     return temp;
 }
 
-bool CCQLParser::check_grammer(IN Token *token)
+bool CCQLParser::check_grammer(Token *token)
 {
     if (token->child_token.size() == 1 && tolower(token->child_token.at(0).name) == "get")
     {
index 609cec7..1b658ae 100644 (file)
@@ -73,12 +73,12 @@ class CCQLParser
         *
         * @param [in] std::string input - Entered ContetxQuery
         * @param [out] Token* root - parsed result
-        * @return none
+        * @return bool
         * @warning
         * @exception
         * @see
         */
-        void parse(IN std::string input, OUT Token *root);
+        bool parse(std::string input, Token *root);
 
         /**
         * @fn tolower
@@ -90,7 +90,7 @@ class CCQLParser
         * @exception
         * @see
         */
-        static std::string tolower(IN std::string str);
+        static std::string tolower(std::string str);
 
         /**
         * @fn check_Query_grammer
@@ -102,7 +102,7 @@ class CCQLParser
         * @exception
         * @see
         */
-        bool check_grammer(IN Token *token);
+        bool check_grammer(Token *token);
 
     private:
         /**
@@ -115,7 +115,7 @@ class CCQLParser
         * @exception
         * @see
         */
-        std::vector<std::string> tokenize(IN const std::string &input);
+        std::vector<std::string> tokenize(const std::string &input);
 
         /**
         * @fn getTokens
@@ -128,8 +128,8 @@ class CCQLParser
         * @exception
         * @see
         */
-        static std::vector<std::string> getTokens(IN const std::string &str,
-                IN const std::string &delimiters = " ");
+        static std::vector<std::string> getTokens(const std::string &str,
+                const std::string &delimiters = " ");
 
         /**
         * @fn check_index
@@ -142,7 +142,7 @@ class CCQLParser
         * @exception
         * @see
         */
-        void check_index(IN std::string input, OUT Token *token);
+        void check_index(std::string input, Token *token);
 
         /**
         * @fn split
@@ -153,13 +153,13 @@ class CCQLParser
         * @param [in] bool flag - flag to distinguish token
         * @param [in] std::string arg1 - next token, default = ""
         * @param [in] std::string arg2 - next two token, default = ""
-        * @return none
+        * @return bool
         * @warning
         * @exception
         * @see
         */
-        void split(IN std::string input, IN Token *root, IN bool flag, IN std::string arg1 = "",
-                   IN std::string arg2 = "");
+        bool split(std::string input, Token *root, bool flag, std::string arg1 = "",
+                   std::string arg2 = "");
 
         /**
         * @fn check_number
@@ -171,7 +171,7 @@ class CCQLParser
         * @exception
         * @see
         */
-        int check_number(IN std::string &str);
+        int check_number(std::string &str);
 
         /**
         * @fn check_Predicate
@@ -183,7 +183,7 @@ class CCQLParser
         * @exception
         * @see
         */
-        std::string check_Predicate(IN std::string input);
+        std::string check_Predicate(std::string input);
 };
 
 #endif /*_CQLParser_H_*/
index 33e8ebc..f13e6e6 100644 (file)
@@ -45,14 +45,14 @@ void CConditionedModel::finalRelease()
     m_triggerId = -1;
 }
 
-SSMRESULT CConditionedModel::create(IN IContextModel *pBaseModel,
-                                    IN ModelConditionVec *pModelConditions)
+SSMRESULT CConditionedModel::create(IContextModel *pBaseModel,
+                                    ModelConditionVec *pModelConditions)
 {
     m_watchCondition = *pModelConditions;
     return pBaseModel->queryInterface(OID_IContextModel, (IBase **)&m_pBaseModel);
 }
 
-SSMRESULT CConditionedModel::getBaseContextModel(OUT IContextModel **ppBaseContextModel)
+SSMRESULT CConditionedModel::getBaseContextModel(IContextModel **ppBaseContextModel)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -62,14 +62,14 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CConditionedModel::registerConditionedModelEvent(IN IConditionedModelEvent
+SSMRESULT CConditionedModel::registerConditionedModelEvent(IConditionedModelEvent
         *pConditionedModelEvent)
 {
     m_pConditionedModelEvent = pConditionedModelEvent;
     return SSM_S_OK;
 }
 
-SSMRESULT CConditionedModel::onWatchModelData(IN int triggerId, IN int dataId)
+SSMRESULT CConditionedModel::onWatchModelData(int triggerId, int dataId)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -85,7 +85,7 @@ SSMRESULT CConditionedModel::onWatchModelData(IN int triggerId, IN int dataId)
     return res;
 }
 
-SSMRESULT CConditionedModel::activateTrigger(OUT int *pTriggerId)
+SSMRESULT CConditionedModel::activateTrigger(int *pTriggerId)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -143,7 +143,7 @@ CLEANUP:
     return ret;
 }
 
-SSMRESULT CConditionedModel::getAffectedData(OUT IntVec *pDataIds)
+SSMRESULT CConditionedModel::getAffectedData(IntVec *pDataIds)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -168,7 +168,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CConditionedModel::getWatchCondition(OUT ModelConditionVec *pModelConditions)
+SSMRESULT CConditionedModel::getWatchCondition(ModelConditionVec *pModelConditions)
 {
     *pModelConditions = m_watchCondition;
     return SSM_S_OK;
index 1d63c00..eb21eff 100644 (file)
@@ -63,7 +63,7 @@ class CConditionedModel :
         * @exception
         * @see
         */
-        SSMRESULT create(IN IContextModel *pBaseModel, IN ModelConditionVec *pModelConditions);
+        SSMRESULT create(IContextModel *pBaseModel, ModelConditionVec *pModelConditions);
 
         /**
         * @fn     onWatchModelData
@@ -77,7 +77,7 @@ class CConditionedModel :
         * @exception
         * @see
         */
-        SSMRESULT onWatchModelData(IN int triggerId, IN int dataId);
+        SSMRESULT onWatchModelData(int triggerId, int dataId);
 
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
         {
@@ -106,7 +106,7 @@ class CConditionedModel :
         * @exception
         * @see
         */
-        SSMRESULT getBaseContextModel(OUT IContextModel **ppBaseContextModel);
+        SSMRESULT getBaseContextModel(IContextModel **ppBaseContextModel);
 
         /**
         * @fn     registerConditionedModelEvent
@@ -119,7 +119,7 @@ class CConditionedModel :
         * @exception
         * @see
         */
-        SSMRESULT registerConditionedModelEvent(IN IConditionedModelEvent *pConditionedModelEvent);
+        SSMRESULT registerConditionedModelEvent(IConditionedModelEvent *pConditionedModelEvent);
 
         /**
         * @fn     activateTrigger
@@ -132,7 +132,7 @@ class CConditionedModel :
         * @exception
         * @see
         */
-        SSMRESULT activateTrigger(OUT int *pTriggerId);
+        SSMRESULT activateTrigger(int *pTriggerId);
 
         /**
         * @fn     deactivateTrigger
@@ -171,7 +171,7 @@ class CConditionedModel :
         * @exception
         * @see
         */
-        SSMRESULT getAffectedData(OUT IntVec *pDataIds);
+        SSMRESULT getAffectedData(IntVec *pDataIds);
 
         /**
         * @fn     getWatchCondition
@@ -184,7 +184,7 @@ class CConditionedModel :
         * @exception
         * @see
         */
-        SSMRESULT getWatchCondition(OUT ModelConditionVec *pModelConditions);
+        SSMRESULT getWatchCondition(ModelConditionVec *pModelConditions);
 };
 
 #endif
index f7de567..df3d026 100644 (file)
@@ -55,22 +55,22 @@ void CConditionedQuery::finalRelease()
     }
 }
 
-SSMRESULT CConditionedQuery::create(IN IContextModel::ActivationType activationType,
-                                    IN int totalConditionsCount)
+SSMRESULT CConditionedQuery::create(IContextModel::ActivationType activationType,
+                                    int totalConditionsCount)
 {
     m_activationType = activationType;
     m_untrackedConditionsCount = totalConditionsCount;
     return SSM_S_OK;
 }
 
-SSMRESULT CConditionedQuery::registerQueryConditionEvent(IN IConditionedQueryEvent
+SSMRESULT CConditionedQuery::registerQueryConditionEvent(IConditionedQueryEvent
         *pConditionedQueryEvent)
 {
     m_conditionedQueryEvent = pConditionedQueryEvent;
     return SSM_S_OK;
 }
 
-SSMRESULT CConditionedQuery::onConditionedModelTriggered(IN int triggerId)
+SSMRESULT CConditionedQuery::onConditionedModelTriggered(int triggerId)
 {
     SSMRESULT res = SSM_E_FAIL;
     int         evaluatedConditions = m_conditionedModels.size();
@@ -95,7 +95,7 @@ CLEANUP:
     return res;
 }
 
-void CConditionedQuery::onExecute(IN void *pArg)
+void CConditionedQuery::onExecute(void *pArg)
 {
     if (m_conditionedQueryEvent)
     {
@@ -103,13 +103,13 @@ void CConditionedQuery::onExecute(IN void *pArg)
     }
 }
 
-void CConditionedQuery::onTerminate(IN void *pArg)
+void CConditionedQuery::onTerminate(void *pArg)
 {
     IConditionedQueryResult *pResult = (IConditionedQueryResult *)pArg;
     SAFE_RELEASE(pResult);
 }
 
-SSMRESULT CConditionedQuery::registerConditionedModel(IN IConditionedModel *pConditionedModel)
+SSMRESULT CConditionedQuery::registerConditionedModel(IConditionedModel *pConditionedModel)
 {
     SSMRESULT           res = SSM_E_FAIL;
     IContextModel       *pContextModel = NULL;
@@ -142,6 +142,7 @@ SSMRESULT CConditionedQuery::registerConditionedModel(IN IConditionedModel *pCon
 
     if (hasAllConditionedModels() == true && m_reservedForActivate)
     {
+        m_reservedForActivate = false;
         SSM_CLEANUP_ASSERT(activateTriggers(m_userTriggerId));
     }
 
@@ -150,7 +151,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CConditionedQuery::activateTriggers(IN int userTriggerId)
+SSMRESULT CConditionedQuery::activateTriggers(int userTriggerId)
 {
     SSMRESULT           res = SSM_E_FAIL;
     int                 triggerId = 0;
@@ -212,12 +213,17 @@ SSMRESULT CConditionedQuery::deactivateTriggers()
         SAFE_RELEASE(pBaseContextModel);
     }
 
+    if (m_reservedForActivate == true)
+    {
+        res = SSM_S_OK;
+    }
+
 CLEANUP:
     SAFE_RELEASE(pBaseContextModel);
     return res;
 }
 
-SSMRESULT CConditionedQuery::getConditionedQueryResult(OUT IConditionedQueryResult
+SSMRESULT CConditionedQuery::getConditionedQueryResult(IConditionedQueryResult
         **ppConditionedQueryResult)
 {
     SSMRESULT res = SSM_E_FAIL;
index ef53d0c..714b28a 100644 (file)
@@ -67,7 +67,7 @@ class CConditionedQuery :
         * @exception
         * @see
         */
-        SSMRESULT create(IN IContextModel::ActivationType activationType, IN int totalConditionsCount);
+        SSMRESULT create(IContextModel::ActivationType activationType, int totalConditionsCount);
 
         /**
         * @fn     registerQueryConditionEvent
@@ -80,7 +80,7 @@ class CConditionedQuery :
         * @exception
         * @see
         */
-        SSMRESULT registerQueryConditionEvent(IN IConditionedQueryEvent *pConditionedQueryEvent);
+        SSMRESULT registerQueryConditionEvent(IConditionedQueryEvent *pConditionedQueryEvent);
 
         /**
         * @fn     onConditionedModelTriggered
@@ -93,11 +93,11 @@ class CConditionedQuery :
         * @exception
         * @see
         */
-        SSMRESULT onConditionedModelTriggered(IN int triggerId);
+        SSMRESULT onConditionedModelTriggered(int triggerId);
 
-        void onExecute(IN void *pArg);
+        void onExecute(void *pArg);
 
-        void onTerminate(IN void *pArg);
+        void onTerminate(void *pArg);
 
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
         {
@@ -126,7 +126,7 @@ class CConditionedQuery :
         * @exception
         * @see
         */
-        SSMRESULT registerConditionedModel(IN IConditionedModel *pConditionedModel);
+        SSMRESULT registerConditionedModel(IConditionedModel *pConditionedModel);
 
         /**
         * @fn     activateTriggers
@@ -139,7 +139,7 @@ class CConditionedQuery :
         * @exception
         * @see
         */
-        SSMRESULT activateTriggers(IN int userTriggerId);
+        SSMRESULT activateTriggers(int userTriggerId);
 
         /**
         * @fn     deactivateTriggers
@@ -165,7 +165,7 @@ class CConditionedQuery :
         * @exception
         * @see
         */
-        SSMRESULT getConditionedQueryResult(OUT IConditionedQueryResult **ppConditionedQueryResult);
+        SSMRESULT getConditionedQueryResult(IConditionedQueryResult **ppConditionedQueryResult);
 
         /**
         * @fn     hasAllConditionedModels
index 1396dec..67ab72d 100644 (file)
@@ -37,7 +37,7 @@ void CConditionedQueryResult::finalRelease()
     }
 }
 
-SSMRESULT CConditionedQueryResult::addConditionedModel(IN IConditionedModel *pConditionedModel)
+SSMRESULT CConditionedQueryResult::addConditionedModel(IConditionedModel *pConditionedModel)
 {
     pConditionedModel->addRef();
     m_conditionedModels.push_back(pConditionedModel);
@@ -50,8 +50,8 @@ unsigned int CConditionedQueryResult::getConditionedModelCount()
     return m_conditionedModels.size();
 }
 
-SSMRESULT CConditionedQueryResult::getConditionedContextModel(IN unsigned int conditionedModelIndex,
-        OUT IConditionedModel **ppConditionedModel)
+SSMRESULT CConditionedQueryResult::getConditionedContextModel(unsigned int conditionedModelIndex,
+        IConditionedModel **ppConditionedModel)
 {
     if (conditionedModelIndex > m_conditionedModels.size() - 1)
     {
index 92b649d..ff4c990 100644 (file)
@@ -54,7 +54,7 @@ class CConditionedQueryResult :
         * @exception
         * @see
         */
-        SSMRESULT addConditionedModel(IN IConditionedModel *pConditionedModel);
+        SSMRESULT addConditionedModel(IConditionedModel *pConditionedModel);
 
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
         {
@@ -97,8 +97,8 @@ class CConditionedQueryResult :
         * @exception
         * @see
         */
-        SSMRESULT getConditionedContextModel(IN unsigned int conditionedModelIndex,
-                                             OUT IConditionedModel **ppConditionedModel);
+        SSMRESULT getConditionedContextModel(unsigned int conditionedModelIndex,
+                                             IConditionedModel **ppConditionedModel);
 };
 
 #endif
index 20029b1..72a5b07 100644 (file)
@@ -89,8 +89,8 @@ CLEANUP:
     return;
 }
 
-void CContextModel::registerSSMResource(IN ActivationType activationType, IN int targetDeviceDataId,
-                                        IN ISSMResource *pSSMResource)
+void CContextModel::registerSSMResource(ActivationType activationType, int targetDeviceDataId,
+                                        ISSMResource *pSSMResource)
 {
     intptr_t     *pData = NULL;
 
@@ -136,8 +136,8 @@ void CContextModel::registerSSMResource(IN ActivationType activationType, IN int
     m_mtxActivationCount.unlock();
 }
 
-void CContextModel::unregisterSSMResource(IN ActivationType activationType,
-        IN int targetDeviceDataId, IN ISSMResource *pSSMResource)
+void CContextModel::unregisterSSMResource(ActivationType activationType,
+        int targetDeviceDataId, ISSMResource *pSSMResource)
 {
     intptr_t     *pData = NULL;
 
@@ -177,8 +177,8 @@ void CContextModel::unregisterSSMResource(IN ActivationType activationType,
     m_mtxActivationCount.unlock();
 }
 
-SSMRESULT CContextModel::create(IN ConstructionType constructionType,
-                                IN IContextModel *pParentModel, IN std::string modelName, IN ModelPropertyVec *pModelProperties)
+SSMRESULT CContextModel::create(ConstructionType constructionType,
+                                IContextModel *pParentModel, std::string modelName, ModelPropertyVec *pModelProperties)
 {
     SSMRESULT res = SSM_E_FAIL;
     int         modelId = 1;
@@ -205,13 +205,13 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CContextModel::registerContextModelEvent(IN IContextModelEvent *pContextModelEvent)
+SSMRESULT CContextModel::registerContextModelEvent(IContextModelEvent *pContextModelEvent)
 {
     m_pContextModelEvent = pContextModelEvent;
     return SSM_S_OK;
 }
 
-void CContextModel::onExecute(IN void *pArg)
+void CContextModel::onExecute(void *pArg)
 {
     intptr_t *pData = (intptr_t *)pArg;
 
@@ -221,15 +221,15 @@ void CContextModel::onExecute(IN void *pArg)
     }
 }
 
-void CContextModel::onTerminate(IN void *pArg)
+void CContextModel::onTerminate(void *pArg)
 {
     intptr_t *pData = (intptr_t *)pArg;
     SAFE_ARRAY_DELETE(pData);
 }
 
 //TODO: called when new data arrived
-int CContextModel::onEvent(IN std::string deviceID, IN TypeofEvent callType,
-                           IN std::vector<ContextData> ctxData)
+int CContextModel::onEvent(std::string deviceID, TypeofEvent callType,
+                           std::vector<ContextData> ctxData)
 {
     SSMRESULT           res = SSM_E_FAIL;
     int                 dataId = 0;
@@ -337,21 +337,21 @@ IContextModel::ConstructionType CContextModel::getConstructionType()
     return m_constructionType;
 }
 
-SSMRESULT CContextModel::getParentDataId(IN int dataId, IN IContextModel *pParentModel,
-        OUT int *pParentDataId)
+SSMRESULT CContextModel::getParentDataId(int dataId, IContextModel *pParentModel,
+        int *pParentDataId)
 {
     return m_pEvaluationEngine->getParentDataId(m_modelId, dataId, pParentModel->getModelId(),
             pParentDataId);
 }
 
-SSMRESULT CContextModel::getChildDataId(IN int dataId, IN IContextModel *pChildModel,
-                                        OUT IntVec *pChildDataIds)
+SSMRESULT CContextModel::getChildDataId(int dataId, IContextModel *pChildModel,
+                                        IntVec *pChildDataIds)
 {
     return m_pEvaluationEngine->getChildDataId(m_modelId, dataId, pChildModel->getModelId(),
             pChildDataIds);
 }
 
-SSMRESULT CContextModel::activate(IN ActivationType activationType, IN int targetDeviceDataId)
+SSMRESULT CContextModel::activate(ActivationType activationType, int targetDeviceDataId)
 {
     if (targetDeviceDataId < 0 && activationType == ACTIVATION_TYPE_SUBSCRIBE)
     {
@@ -377,7 +377,7 @@ SSMRESULT CContextModel::activate(IN ActivationType activationType, IN int targe
     return SSM_S_OK;
 }
 
-SSMRESULT CContextModel::deactivate(IN ActivationType activationType, IN int targetDeviceDataId)
+SSMRESULT CContextModel::deactivate(ActivationType activationType, int targetDeviceDataId)
 {
     if (targetDeviceDataId < 0 && activationType == ACTIVATION_TYPE_SUBSCRIBE)
     {
@@ -403,29 +403,29 @@ SSMRESULT CContextModel::deactivate(IN ActivationType activationType, IN int tar
     return SSM_S_OK;
 }
 /*
-SSMRESULT CContextModel::GetModelSchema(OUT ModelPropertyVec *pModelProperties)
+SSMRESULT CContextModel::GetModelSchema(ModelPropertyVec *pModelProperties)
 {
     return m_pEvaluationEngine->GetModelSchema(m_ModelId, pModelProperties);
 }
 */
-SSMRESULT CContextModel::addModelData(IN int parentDataId, IN ModelPropertyVec *pData,
-                                      OUT int *pDataId)
+SSMRESULT CContextModel::addModelData(int parentDataId, ModelPropertyVec *pData,
+                                      int *pDataId)
 {
     return m_pEvaluationEngine->addModelData(m_modelId, m_pParentModel->getModelId(), parentDataId,
             pData, pDataId);
 }
 
-SSMRESULT CContextModel::updateModelData(IN int dataId, IN ModelPropertyVec *pData)
+SSMRESULT CContextModel::updateModelData(int dataId, ModelPropertyVec *pData)
 {
     return m_pEvaluationEngine->updateModelData(m_modelId, dataId, pData);
 }
 
-SSMRESULT CContextModel::deleteModelData(IN int dataId)
+SSMRESULT CContextModel::deleteModelData(int dataId)
 {
     return m_pEvaluationEngine->deleteModelData(m_modelId, dataId);
 }
 
-SSMRESULT CContextModel::getModelData(IN int dataId, OUT ModelPropertyVec *pData)
+SSMRESULT CContextModel::getModelData(int dataId, ModelPropertyVec *pData)
 {
     SSMRESULT res = SSM_E_FAIL;
     int     i = 0;
@@ -440,8 +440,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CContextModel::getModelDataSet(IN int startIndex, IN int count,
-        OUT std::vector<ModelPropertyVec> *pDataSet, OUT int *pLastIndex)
+SSMRESULT CContextModel::getModelDataSet(int startIndex, int count,
+        std::vector<ModelPropertyVec> *pDataSet, int *pLastIndex)
 {
     SSMRESULT res = SSM_E_FAIL;
     int     i;
@@ -464,8 +464,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CContextModel::createConditionedModel(IN ModelConditionVec *pModelConditionVec,
-        OUT IConditionedModel **ppConditionedModel)
+SSMRESULT CContextModel::createConditionedModel(ModelConditionVec *pModelConditionVec,
+        IConditionedModel **ppConditionedModel)
 {
     SSMRESULT res = SSM_E_FAIL;
     CObject<CConditionedModel>                  *pConditionedModel;
@@ -501,8 +501,8 @@ CLEANUP:
 */
 
 //Called new install or re install
-void CContextModel::addSSMResourceAndDeviceDataId(IN std::string deviceId, IN int deviceDataId,
-        IN ISSMResource *pSSMResource)
+void CContextModel::addSSMResourceAndDeviceDataId(std::string deviceId, int deviceDataId,
+        ISSMResource *pSSMResource)
 {
     if (deviceDataId == 1)
     {
index 0fa0b8d..9cb018d 100644 (file)
@@ -60,11 +60,11 @@ class CContextModel :
 
         std::string                             m_secLifeTime;
 
-        void registerSSMResource(IN ActivationType activationType, IN int targetDeviceDataId,
-                                 IN ISSMResource *pSSMResource);
+        void registerSSMResource(ActivationType activationType, int targetDeviceDataId,
+                                 ISSMResource *pSSMResource);
 
-        void unregisterSSMResource(IN ActivationType activationType, IN int targetDeviceDataId,
-                                   IN ISSMResource *pSSMResource);
+        void unregisterSSMResource(ActivationType activationType, int targetDeviceDataId,
+                                   ISSMResource *pSSMResource);
 
     public:
         SSMRESULT finalConstruct();
@@ -85,8 +85,8 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT create(IN ConstructionType constructionType, IN IContextModel *pParentModel,
-                         IN std::string modelName, IN ModelPropertyVec *pModelProperties);
+        SSMRESULT create(ConstructionType constructionType, IContextModel *pParentModel,
+                         std::string modelName, ModelPropertyVec *pModelProperties);
 
         /**
         * @fn     registerContextModelEvent
@@ -99,11 +99,11 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT registerContextModelEvent(IN IContextModelEvent *pContextModelEvent);
+        SSMRESULT registerContextModelEvent(IContextModelEvent *pContextModelEvent);
 
-        void onExecute(IN void *pArg);
+        void onExecute(void *pArg);
 
-        void onTerminate(IN void *pArg);
+        void onTerminate(void *pArg);
 
         /**
         * @fn     onEvent
@@ -118,7 +118,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        int onEvent(IN std::string deviceID, IN TypeofEvent callType, IN std::vector<ContextData> ctxData);
+        int onEvent(std::string deviceID, TypeofEvent callType, std::vector<ContextData> ctxData);
 
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
         {
@@ -188,7 +188,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT getParentDataId(IN int dataId, IN IContextModel *pParentModel, OUT int *pParentDataId);
+        SSMRESULT getParentDataId(int dataId, IContextModel *pParentModel, int *pParentDataId);
 
         /**
         * @fn     getChildDataId
@@ -203,7 +203,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT getChildDataId(IN int dataId, IN IContextModel *pChildModel, OUT IntVec *pChildDataIds);
+        SSMRESULT getChildDataId(int dataId, IContextModel *pChildModel, IntVec *pChildDataIds);
 
         /**
         * @fn     activate
@@ -217,7 +217,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT activate(IN ActivationType activationType, IN int targetDeviceDataId);
+        SSMRESULT activate(ActivationType activationType, int targetDeviceDataId);
 
         /**
         * @fn     deactivate
@@ -232,9 +232,9 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT deactivate(IN ActivationType activationType, IN int targetDeviceDataId);
+        SSMRESULT deactivate(ActivationType activationType, int targetDeviceDataId);
 
-        //SSMRESULT GetModelSchema(OUT ModelPropertyVec *pModelProperties);
+        //SSMRESULT GetModelSchema(ModelPropertyVec *pModelProperties);
 
         /**
         * @fn     addModelData
@@ -249,7 +249,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT addModelData(IN int parentDataId, IN ModelPropertyVec *pData, OUT int *pDataId);
+        SSMRESULT addModelData(int parentDataId, ModelPropertyVec *pData, int *pDataId);
 
         /**
         * @fn     updateModelData
@@ -263,7 +263,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT updateModelData(IN int dataId, IN ModelPropertyVec *pData);
+        SSMRESULT updateModelData(int dataId, ModelPropertyVec *pData);
 
         /**
         * @fn     deleteModelData
@@ -276,7 +276,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT deleteModelData(IN int dataId);
+        SSMRESULT deleteModelData(int dataId);
 
         /**
         * @fn     getModelData
@@ -290,7 +290,7 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT getModelData(IN int dataId, OUT ModelPropertyVec *pData);
+        SSMRESULT getModelData(int dataId, ModelPropertyVec *pData);
 
         /**
         * @fn     getModelDataSet
@@ -306,8 +306,8 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT getModelDataSet(IN int startIndex, IN int count,
-                                  OUT std::vector<ModelPropertyVec> *pDataSet, OUT int *pLastIndex);
+        SSMRESULT getModelDataSet(int startIndex, int count,
+                                  std::vector<ModelPropertyVec> *pDataSet, int *pLastIndex);
 
         /**
         * @fn     createConditionedModel
@@ -321,8 +321,8 @@ class CContextModel :
         * @exception
         * @see
         */
-        SSMRESULT createConditionedModel(IN ModelConditionVec *pModelConditionVec,
-                                         OUT IConditionedModel **ppConditionedModel);
+        SSMRESULT createConditionedModel(ModelConditionVec *pModelConditionVec,
+                                         IConditionedModel **ppConditionedModel);
 
         //SSMRESULT CleanUpModelData();
 
@@ -339,8 +339,8 @@ class CContextModel :
         * @exception
         * @see
         */
-        void addSSMResourceAndDeviceDataId(IN std::string deviceId, IN int deviceDataId,
-                                           IN ISSMResource *pSSMResource);
+        void addSSMResourceAndDeviceDataId(std::string deviceId, int deviceDataId,
+                                           ISSMResource *pSSMResource);
 
         /**
         * @fn     SetLifeTime
index dbf42c8..92fa629 100644 (file)
@@ -28,13 +28,13 @@ CContextQuery::CContextQuery()
 {
 }
 
-SSMRESULT CContextQuery::initialize(IN Token &input_root)
+SSMRESULT CContextQuery::initialize(Token &input_root)
 {
     m_root = input_root;
     return CreateGlobalInstance(OID_IPropagationEngine, (IBase **)&m_pPropagationEngine);
 }
 
-std::string CContextQuery::search_last_modelName(IN Token *temp)
+std::string CContextQuery::search_last_modelName(Token *temp)
 {
     while (true)
     {
@@ -49,8 +49,8 @@ std::string CContextQuery::search_last_modelName(IN Token *temp)
     }
 }
 
-void CContextQuery::integrate_result(OUT std::vector<result_model> *result, IN int modelId,
-                                     IN std::vector<int> *dataid, IN std::string modelName)
+void CContextQuery::integrate_result(std::vector<result_model> *result, int modelId,
+                                     std::vector<int> *dataid, std::string modelName)
 {
     bool flag = false;
 
@@ -91,7 +91,7 @@ void CContextQuery::integrate_result(OUT std::vector<result_model> *result, IN i
 
 
 
-void CContextQuery::return_contextName(OUT std::vector<std::string> *contextName)
+void CContextQuery::return_contextName(std::vector<std::string> *contextName)
 {
     int k = m_root.child_token.at(0).child_token.size();
 
@@ -143,9 +143,10 @@ void CContextQuery::check_result_model()
 
         }
 
+        unsigned int cnt = 0;
+
         while (true)
         {
-            unsigned int cnt = 0;
             if ((unsigned int)cnt > min_cnt - 1)
             {
                 break;
@@ -202,26 +203,27 @@ void CContextQuery::check_result_model()
     }
 }
 
-void CContextQuery::return_modelID(OUT std::vector<int> *vector_int)
+void CContextQuery::return_modelID(std::vector<int> *vector_int)
 {
     int k = m_root.child_token.at(0).child_token.size();
 
+    IContextModel *pContextModel = NULL;
+    int pModel = 0;
+
     for (int i = 0; i < k; i++)
     {
-
         Token *temp = &(m_root.child_token.at(0).child_token.at(i));
-
-        int pModel = 0;
-        IContextModel *contextmodel;
-
-        m_pPropagationEngine->getContextModel(search_last_modelName(temp), &contextmodel);
-        pModel = contextmodel->getModelId();
-        vector_int->push_back(pModel);
-        SAFE_RELEASE(contextmodel);
+        if (m_pPropagationEngine->getContextModel(search_last_modelName(temp),
+                &pContextModel) == SSM_S_OK)
+        {
+            pModel = pContextModel->getModelId();
+            vector_int->push_back(pModel);
+        }
+        SAFE_RELEASE(pContextModel);
     }
 }
 
-void CContextQuery::make_QueryCondition(OUT QueryCondition *result)
+void CContextQuery::make_QueryCondition(QueryCondition *result)
 {
 
     if (m_root.child_token.size() < 2)
@@ -286,15 +288,13 @@ void CContextQuery::make_QueryCondition(OUT QueryCondition *result)
     {
         int k = m_root.child_token.at(1).child_token.size();
         std::string model_name = "";
-        ModelConditionVec modelcondition;
-        ModelCondition model_data;
 
-        for (int i = 0 ; i < k ; i++)
+        std::map<std::string, ModelConditionVec> modelConditionList;
+
+        for (int i = 0; i < k; i++)
         {
-            modelcondition.clear();
             Token *temp = &(m_root.child_token.at(1).child_token.at(i));
 
-
             if (temp->type == Context)
             {
                 while (1)
@@ -311,16 +311,20 @@ void CContextQuery::make_QueryCondition(OUT QueryCondition *result)
                     }
                 }
 
-
-
+                ModelCondition model_data;
                 model_data.predicate = m_root.child_token.at(1).child_token.at(i + 1).condition;
                 model_data.modelProperty.propertyName = temp->model_property.propertyName;
                 model_data.modelProperty.propertyType = temp->model_property.propertyType;
                 model_data.modelProperty.propertyValue = temp->model_property.propertyValue;
-                modelcondition.push_back(model_data);
-                result->push_back(std::pair<std::string, ModelConditionVec>(model_name, modelcondition));
-                ///result->push_back(model_name[i],modelcondition);
+                modelConditionList[model_name].push_back(model_data);
             }
         }
+
+        for (std::map<std::string, ModelConditionVec>::iterator itor = modelConditionList.begin();
+             itor != modelConditionList.end(); ++itor)
+        {
+            result->push_back(std::pair<std::string, ModelConditionVec>(itor->first,
+                              itor->second));
+        }
     }
 }
index 8b42ce5..7fb5e33 100644 (file)
@@ -80,7 +80,7 @@ class CContextQuery
         * @exception
         * @see
         */
-        SSMRESULT initialize(IN Token &input_root);
+        SSMRESULT initialize(Token &input_root);
 
         /**
         * @fn integrate_result
@@ -95,8 +95,8 @@ class CContextQuery
         * @exception
         * @see
         */
-        void integrate_result(OUT std::vector<result_model> *result, IN int modelId,
-                              IN std::vector<int> *dataid, IN std::string modelName);
+        void integrate_result(std::vector<result_model> *result, int modelId,
+                              std::vector<int> *dataid, std::string modelName);
 
         /**
         * @fn return_contextName
@@ -108,7 +108,7 @@ class CContextQuery
         * @exception
         * @see
         */
-        void return_contextName(OUT std::vector<std::string> *contextName);
+        void return_contextName(std::vector<std::string> *contextName);
 
         /**
         * @fn check_result_model
@@ -132,7 +132,7 @@ class CContextQuery
         * @exception
         * @see
         */
-        void return_modelID(OUT std::vector<int> *vector_int);
+        void return_modelID(std::vector<int> *vector_int);
 
         /**
         * @fn make_QueryCondition
@@ -144,7 +144,7 @@ class CContextQuery
         * @exception
         * @see
         */
-        void make_QueryCondition(OUT QueryCondition *result);
+        void make_QueryCondition(QueryCondition *result);
 
     private:
         /**
@@ -157,7 +157,7 @@ class CContextQuery
         * @exception
         * @see
         */
-        std::string search_last_modelName(IN Token *temp);
+        std::string search_last_modelName(Token *temp);
 
         Token m_root;
         CObjectPtr<IPropagationEngine>      m_pPropagationEngine;
index 0779c14..f064dc4 100644 (file)
@@ -37,15 +37,15 @@ CDataReader::~CDataReader()
     }
 }
 
-SSMRESULT CDataReader::addModelData(IN std::string modelName,
-                                    IN std::vector<CModelData *> *pModelData)
+SSMRESULT CDataReader::addModelData(std::string modelName,
+                                    std::vector<CModelData *> *pModelData)
 {
     m_modelDataList[modelName] = *pModelData;
 
     return SSM_S_OK;
 }
 
-SSMRESULT CDataReader::getAffectedModels(OUT std::vector<std::string> *pAffectedModels)
+SSMRESULT CDataReader::getAffectedModels(std::vector<std::string> *pAffectedModels)
 {
     for (std::map<std::string, std::vector<CModelData *> >::iterator itorModel =
              m_modelDataList.begin();
@@ -57,7 +57,7 @@ SSMRESULT CDataReader::getAffectedModels(OUT std::vector<std::string> *pAffected
     return SSM_S_OK;
 }
 
-SSMRESULT CDataReader::getModelDataCount(IN std::string modelName, OUT int *pDataCount)
+SSMRESULT CDataReader::getModelDataCount(std::string modelName, int *pDataCount)
 {
     std::map<std::string, std::vector<CModelData *> >::iterator itor;
 
@@ -73,8 +73,8 @@ SSMRESULT CDataReader::getModelDataCount(IN std::string modelName, OUT int *pDat
     return SSM_S_OK;
 }
 
-SSMRESULT CDataReader::getModelData(IN std::string modelName, IN int dataIndex,
-                                    OUT IModelData **ppModelData)
+SSMRESULT CDataReader::getModelData(std::string modelName, int dataIndex,
+                                    IModelData **ppModelData)
 {
     std::map<std::string, std::vector<CModelData *> >::iterator itor;
 
index 79e7828..cafbede 100644 (file)
@@ -53,7 +53,7 @@ class CDataReader : public IDataReader
         * @exception
         * @see
         */
-        SSMRESULT addModelData(IN std::string modelName, IN std::vector<CModelData *> *pModelData);
+        SSMRESULT addModelData(std::string modelName, std::vector<CModelData *> *pModelData);
 
         /**
         * @fn     getAffectedModels
@@ -66,7 +66,7 @@ class CDataReader : public IDataReader
         * @exception
         * @see
         */
-        SSMRESULT getAffectedModels(OUT std::vector<std::string> *pAffectedModels);
+        SSMRESULT getAffectedModels(std::vector<std::string> *pAffectedModels);
 
         /**
         * @fn     getModelDataCount
@@ -81,7 +81,7 @@ class CDataReader : public IDataReader
         * @exception
         * @see
         */
-        SSMRESULT getModelDataCount(IN std::string modelName, OUT int *pDataCount);
+        SSMRESULT getModelDataCount(std::string modelName, int *pDataCount);
 
         /**
         * @fn     getModelData
@@ -100,7 +100,7 @@ class CDataReader : public IDataReader
         * @exception
         * @see
         */
-        SSMRESULT getModelData(IN std::string modelName, IN int dataIndex, OUT IModelData **ppModelData);
+        SSMRESULT getModelData(std::string modelName, int dataIndex, IModelData **ppModelData);
 };
 
 #endif
index 1e102c2..c635269 100644 (file)
@@ -43,7 +43,7 @@ void CEvaluationEngine::finalRelease()
     terminateEngine();
 }
 
-SSMRESULT CEvaluationEngine::executeSQL_NoReturn(IN std::string strSQL)
+SSMRESULT CEvaluationEngine::executeSQL_NoReturn(std::string strSQL)
 {
     SSMRESULT       res = SSM_E_FAIL;
     sqlite3_stmt    *stmt = NULL;
@@ -57,7 +57,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::executeSQL_IntReturn(IN std::string strSQL, OUT int *pResult)
+SSMRESULT CEvaluationEngine::executeSQL_IntReturn(std::string strSQL, int *pResult)
 {
     SSMRESULT       res = SSM_E_FAIL;
     sqlite3_stmt    *stmt = NULL;
@@ -72,15 +72,15 @@ CLEANUP:
     return res;
 }
 
-void CEvaluationEngine::onSQLTrigger(IN sqlite3_context *context, IN int argc,
-                                     IN sqlite3_value **argv)
+void CEvaluationEngine::onSQLTrigger(sqlite3_context *context, int argc,
+                                     sqlite3_value **argv)
 {
-    CEvaluationEngine *pEvaluationEngine = (CEvaluationEngine *)sqlite3_value_int(argv[0]);
+    CEvaluationEngine *pEvaluationEngine = (CEvaluationEngine *)sqlite3_value_int64(argv[0]);
 
     pEvaluationEngine->onWatcherTriggered(sqlite3_value_int(argv[1]), sqlite3_value_int(argv[2]));
 }
 
-void CEvaluationEngine::onExecute(IN void *pArg)
+void CEvaluationEngine::onExecute(void *pArg)
 {
     std::map<int, IEvaluationEngineEvent *>::iterator itor;
     intptr_t *pData = (intptr_t *)pArg;
@@ -95,13 +95,13 @@ void CEvaluationEngine::onExecute(IN void *pArg)
     m_mtxTriggerId.unlock();
 }
 
-void CEvaluationEngine::onTerminate(IN void *pArg)
+void CEvaluationEngine::onTerminate(void *pArg)
 {
     intptr_t *pData = (intptr_t *)pArg;
     SAFE_ARRAY_DELETE(pData);
 }
 
-SSMRESULT CEvaluationEngine::onWatcherTriggered(IN int triggerId, IN int dataId)
+SSMRESULT CEvaluationEngine::onWatcherTriggered(int triggerId, int dataId)
 {
     intptr_t     *pData = new intptr_t[2];
     pData[0] = triggerId;
@@ -198,7 +198,6 @@ void CEvaluationEngine::terminateEngine()
         SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));
         sstream.str("");
     }
-    m_mtxTriggerId.unlock();
 
     if (strlen(LOCATION_SSM_DB_DUMP) > 0)
     {
@@ -216,12 +215,14 @@ void CEvaluationEngine::terminateEngine()
     m_pSQLite3 = NULL;
 
     res = SSM_S_OK;
+
 CLEANUP:
+    m_mtxTriggerId.unlock();
     return;
 }
 
-SSMRESULT CEvaluationEngine::createModel(IN int parentModelId, IN const char *newModelName,
-        IN ModelPropertyVec *pModelDescs, OUT int *pModelId)
+SSMRESULT CEvaluationEngine::createModel(int parentModelId, const char *newModelName,
+        ModelPropertyVec *pModelDescs, int *pModelId)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -291,8 +292,7 @@ SSMRESULT CEvaluationEngine::createModel(IN int parentModelId, IN const char *ne
                 break;
 
             default:
-                res = SSM_E_FAIL;
-                goto CLEANUP;
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
         }
     }
 
@@ -304,8 +304,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::addModelData(IN int modelId, IN int parentModelId, IN int parentDataId,
-        IN ModelPropertyVec *pModelValues, OUT int *pDataId)
+SSMRESULT CEvaluationEngine::addModelData(int modelId, int parentModelId, int parentDataId,
+        ModelPropertyVec *pModelValues, int *pDataId)
 {
     SSMRESULT           res = SSM_E_FAIL;
     std::stringstream   sstream;
@@ -366,8 +366,7 @@ SSMRESULT CEvaluationEngine::addModelData(IN int modelId, IN int parentModelId,
                 break;
 
             default:
-                res = SSM_E_FAIL;
-                goto CLEANUP;
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
         }
 
         i++;
@@ -404,8 +403,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::updateModelData(IN int modelId, IN int dataId,
-        IN ModelPropertyVec *pModelValues)
+SSMRESULT CEvaluationEngine::updateModelData(int modelId, int dataId,
+        ModelPropertyVec *pModelValues)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -451,8 +450,7 @@ SSMRESULT CEvaluationEngine::updateModelData(IN int modelId, IN int dataId,
                 break;
 
             default:
-                res = SSM_E_FAIL;
-                goto CLEANUP;
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
         }
 
         i++;
@@ -468,7 +466,7 @@ CLEANUP:
     return res;
 }
 /*
-SSMRESULT CEvaluationEngine::DeleteModel(IN int modelId)
+SSMRESULT CEvaluationEngine::DeleteModel(int modelId)
 {
     SSMRESULT       res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -515,7 +513,7 @@ CLEANUP:
     return res;
 }
 */
-SSMRESULT CEvaluationEngine::deleteModelData(IN int modelId, IN int dataId)
+SSMRESULT CEvaluationEngine::deleteModelData(int modelId, int dataId)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -562,8 +560,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::getModelDataSet(IN int modelId, IN int startIndex, IN int count,
-        OUT std::vector<ModelPropertyVec> *pDataSet, OUT int *pLastIndex)
+SSMRESULT CEvaluationEngine::getModelDataSet(int modelId, int startIndex, int count,
+        std::vector<ModelPropertyVec> *pDataSet, int *pLastIndex)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -637,8 +635,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::getModelData(IN int modelId, IN int dataId,
-        OUT ModelPropertyVec *pModelProperties)
+SSMRESULT CEvaluationEngine::getModelData(int modelId, int dataId,
+        ModelPropertyVec *pModelProperties)
 {
     SSMRESULT       res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -704,7 +702,7 @@ CLEANUP:
     return res;
 }
 /*
-SSMRESULT CEvaluationEngine::GetModelSchema(IN int modelId, OUT ModelPropertyVec *pModelProperties)
+SSMRESULT CEvaluationEngine::GetModelSchema(int modelId, ModelPropertyVec *pModelProperties)
 {
     SSMRESULT       res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -753,8 +751,8 @@ CLEANUP:
     return res;
 }
 */
-SSMRESULT CEvaluationEngine::getConditionedModelData(IN int modelId,
-        IN ModelConditionVec *pModelConditions, OUT IntVec *pDataIds)
+SSMRESULT CEvaluationEngine::getConditionedModelData(int modelId,
+        ModelConditionVec *pModelConditions, IntVec *pDataIds)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -795,8 +793,7 @@ SSMRESULT CEvaluationEngine::getConditionedModelData(IN int modelId,
                 break;
 
             default:
-                res = SSM_E_FAIL;
-                goto CLEANUP;
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
         }
 
         switch (itor->modelProperty.propertyType)
@@ -812,8 +809,7 @@ SSMRESULT CEvaluationEngine::getConditionedModelData(IN int modelId,
                 break;
 
             default:
-                res = SSM_E_FAIL;
-                goto CLEANUP;
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
         }
 
         if (itor < pModelConditions->end() - 1)
@@ -840,8 +836,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::watchModelData(IN int modelId, IN ModelConditionVec *pModelConditions,
-        IN IEvaluationEngineEvent *pEvaluationEngineEvent, OUT int *pTriggerId)
+SSMRESULT CEvaluationEngine::watchModelData(int modelId, ModelConditionVec *pModelConditions,
+        IEvaluationEngineEvent *pEvaluationEngineEvent, int *pTriggerId)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -878,8 +874,7 @@ SSMRESULT CEvaluationEngine::watchModelData(IN int modelId, IN ModelConditionVec
                 break;
 
             default:
-                res = SSM_E_FAIL;
-                goto CLEANUP;
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
         }
 
         switch (itor->modelProperty.propertyType)
@@ -895,8 +890,7 @@ SSMRESULT CEvaluationEngine::watchModelData(IN int modelId, IN ModelConditionVec
                 break;
 
             default:
-                res = SSM_E_FAIL;
-                goto CLEANUP;
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
         }
 
         if (itor < pModelConditions->end() - 1)
@@ -933,7 +927,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::dropWatchModelData(IN int triggerId)
+SSMRESULT CEvaluationEngine::dropWatchModelData(int triggerId)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -957,8 +951,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::getParentDataId(IN int modelId, IN int dataId, IN int parentModelId,
-        OUT int *pParentDataId)
+SSMRESULT CEvaluationEngine::getParentDataId(int modelId, int dataId, int parentModelId,
+        int *pParentDataId)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -977,8 +971,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::getChildDataId(IN int modelId, IN int dataId, IN int ChildModelId,
-        OUT IntVec *pChildDataIds)
+SSMRESULT CEvaluationEngine::getChildDataId(int modelId, int dataId, int ChildModelId,
+        IntVec *pChildDataIds)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -1009,7 +1003,7 @@ CLEANUP:
     return res;
 }
 /*
-SSMRESULT CEvaluationEngine::GetPathToRoot(IN int currentModelId, OUT IntVec *pPath)
+SSMRESULT CEvaluationEngine::GetPathToRoot(int currentModelId, IntVec *pPath)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -1035,7 +1029,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::GetModelId(IN const char *modelName, OUT int *pModelId)
+SSMRESULT CEvaluationEngine::GetModelId(const char *modelName, int *pModelId)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -1048,7 +1042,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::GetModelHierarchy(IN int rootModelId, OUT StringVec *pPath)
+SSMRESULT CEvaluationEngine::GetModelHierarchy(int rootModelId, StringVec *pPath)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
@@ -1111,7 +1105,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CEvaluationEngine::GetDataHierarchy(IN int rootModelId, IN int dataId, OUT StringVec *pPath)
+SSMRESULT CEvaluationEngine::GetDataHierarchy(int rootModelId, int dataId, StringVec *pPath)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::stringstream sstream;
index 03da0bf..759f44a 100644 (file)
@@ -45,11 +45,11 @@ class CEvaluationEngine :
         CSimpleMutex        m_mtxDataRelation;
         CObjectPtr<ITasker> m_pTasker;
 
-        SSMRESULT executeSQL_NoReturn(IN std::string strSQL);
+        SSMRESULT executeSQL_NoReturn(std::string strSQL);
 
-        SSMRESULT executeSQL_IntReturn(IN std::string strSQL, OUT int *pResult);
+        SSMRESULT executeSQL_IntReturn(std::string strSQL, int *pResult);
 
-        static void onSQLTrigger(IN sqlite3_context *context, IN int argc, IN sqlite3_value **argv);
+        static void onSQLTrigger(sqlite3_context *context, int argc, sqlite3_value **argv);
 
         SSMRESULT initializeEngine();
 
@@ -60,9 +60,9 @@ class CEvaluationEngine :
 
         void finalRelease();
 
-        void onExecute(IN void *pArg);
+        void onExecute(void *pArg);
 
-        void onTerminate(IN void *pArg);
+        void onTerminate(void *pArg);
 
         /**
         * @fn     onWatcherTriggered
@@ -76,7 +76,7 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT onWatcherTriggered(IN int triggerId, IN int dataId);
+        SSMRESULT onWatcherTriggered(int triggerId, int dataId);
 
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
         {
@@ -108,8 +108,8 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT createModel(IN int parentModelId, IN const char *newModelName,
-                              IN ModelPropertyVec *pModelDescs, OUT int *pModelId);
+        SSMRESULT createModel(int parentModelId, const char *newModelName,
+                              ModelPropertyVec *pModelDescs, int *pModelId);
 
         /**
         * @fn     addModelData
@@ -126,8 +126,8 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT addModelData(IN int modelId, IN int parentModelId, IN int parentDataId,
-                               IN ModelPropertyVec *pModelValues, OUT int *pDataId);
+        SSMRESULT addModelData(int modelId, int parentModelId, int parentDataId,
+                               ModelPropertyVec *pModelValues, int *pDataId);
 
         /**
         * @fn     updateModelData
@@ -142,9 +142,9 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT updateModelData(IN int modelId, IN int dataId, IN ModelPropertyVec *pModelValues);
+        SSMRESULT updateModelData(int modelId, int dataId, ModelPropertyVec *pModelValues);
 
-        //SSMRESULT DeleteModel(IN int modelId);
+        //SSMRESULT DeleteModel(int modelId);
 
         /**
         * @fn     deleteModelData
@@ -158,7 +158,7 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT deleteModelData(IN int modelId, IN int dataId);
+        SSMRESULT deleteModelData(int modelId, int dataId);
 
         /**
         * @fn     getModelData
@@ -173,7 +173,7 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT getModelData(IN int modelId, IN int dataId, OUT ModelPropertyVec *pModelProperties);
+        SSMRESULT getModelData(int modelId, int dataId, ModelPropertyVec *pModelProperties);
 
         /**
         * @fn     getModelDataSet
@@ -190,10 +190,10 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT getModelDataSet(IN int modelId, IN int startIndex, IN int count,
-                                  OUT std::vector<ModelPropertyVec> *pDataSet, OUT int *pLastIndex);
+        SSMRESULT getModelDataSet(int modelId, int startIndex, int count,
+                                  std::vector<ModelPropertyVec> *pDataSet, int *pLastIndex);
 
-        //SSMRESULT GetModelSchema(IN int modelId, OUT ModelPropertyVec *pModelProperties);
+        //SSMRESULT GetModelSchema(int modelId, ModelPropertyVec *pModelProperties);
 
         /**
         * @fn     getConditionedModelData
@@ -208,8 +208,8 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT getConditionedModelData(IN int modelId, IN ModelConditionVec *pModelConditions,
-                                          OUT IntVec *pDataIds);
+        SSMRESULT getConditionedModelData(int modelId, ModelConditionVec *pModelConditions,
+                                          IntVec *pDataIds);
 
         /**
         * @fn     watchModelData
@@ -225,8 +225,8 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT watchModelData(IN int modelId, IN ModelConditionVec *pModelConditions,
-                                 IN IEvaluationEngineEvent *pEvaluationEngineEvent, OUT int *pTriggerId);
+        SSMRESULT watchModelData(int modelId, ModelConditionVec *pModelConditions,
+                                 IEvaluationEngineEvent *pEvaluationEngineEvent, int *pTriggerId);
 
         /**
         * @fn     dropWatchModelData
@@ -239,7 +239,7 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT dropWatchModelData(IN int triggerId);
+        SSMRESULT dropWatchModelData(int triggerId);
 
         /**
         * @fn     getParentDataId
@@ -255,8 +255,8 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT getParentDataId(IN int modelId, IN int dataId, IN int parentModelId,
-                                  OUT int *pParentDataId);
+        SSMRESULT getParentDataId(int modelId, int dataId, int parentModelId,
+                                  int *pParentDataId);
 
         /**
         * @fn     getChildDataId
@@ -272,16 +272,16 @@ class CEvaluationEngine :
         * @exception
         * @see
         */
-        SSMRESULT getChildDataId(IN int modelId, IN int dataId, IN int childModelId,
-                                 OUT IntVec *pChildDataIds);
+        SSMRESULT getChildDataId(int modelId, int dataId, int childModelId,
+                                 IntVec *pChildDataIds);
 
-        //SSMRESULT GetPathToRoot(IN int currentModelId, OUT IntVec *pPath);
+        //SSMRESULT GetPathToRoot(int currentModelId, IntVec *pPath);
 
-        //SSMRESULT GetModelId(IN const char *modelName, OUT int *pModelId);
+        //SSMRESULT GetModelId(const char *modelName, int *pModelId);
 
-        //SSMRESULT GetModelHierarchy(IN int rootModelId, OUT StringVec *pPath);
+        //SSMRESULT GetModelHierarchy(int rootModelId, StringVec *pPath);
 
-        //SSMRESULT GetDataHierarchy(IN int rootModelId, IN int dataId, OUT StringVec *pPath);
+        //SSMRESULT GetDataHierarchy(int rootModelId, int dataId, StringVec *pPath);
 };
 
 #endif
index 450970c..0db6b9c 100644 (file)
@@ -29,12 +29,12 @@ CModelData::~CModelData()
 
 }
 
-void CModelData::setDataId(IN int dataId)
+void CModelData::setDataId(int dataId)
 {
     m_dataId = dataId;
 }
 
-void CModelData::addModelData(IN std::string propertyName, IN std::string propertyValue)
+void CModelData::addModelData(std::string propertyName, std::string propertyValue)
 {
     m_properties[propertyName] = propertyValue;
 }
@@ -49,7 +49,7 @@ int CModelData::getPropertyCount()
     return m_properties.size();
 }
 
-std::string CModelData::getPropertyName(IN int propertyIndex)
+std::string CModelData::getPropertyName(int propertyIndex)
 {
     std::map<std::string, std::string>::iterator idxProperty = m_properties.begin();
     for (int i = 0; i < propertyIndex; i++)
@@ -59,7 +59,7 @@ std::string CModelData::getPropertyName(IN int propertyIndex)
     return idxProperty->first;
 }
 
-std::string CModelData::getPropertyValue(IN int propertyIndex)
+std::string CModelData::getPropertyValue(int propertyIndex)
 {
     std::map<std::string, std::string>::iterator idxProperty = m_properties.begin();
     for (int i = 0; i < propertyIndex; i++)
@@ -69,7 +69,7 @@ std::string CModelData::getPropertyValue(IN int propertyIndex)
     return idxProperty->second;
 }
 
-std::string CModelData::getPropertyValueByName(IN std::string propertyName)
+std::string CModelData::getPropertyValueByName(std::string propertyName)
 {
     return m_properties[propertyName];
 }
index 643af67..850193e 100644 (file)
@@ -52,7 +52,7 @@ class CModelData : public IModelData
         * @exception
         * @see
         */
-        void setDataId(IN int dataId);
+        void setDataId(int dataId);
 
         /**
         * @fn     addModelData
@@ -66,7 +66,7 @@ class CModelData : public IModelData
         * @exception
         * @see
         */
-        void addModelData(IN std::string propertyName, IN std::string propertyValue);
+        void addModelData(std::string propertyName, std::string propertyValue);
 
         /**
         * @fn     getDataId
@@ -107,7 +107,7 @@ class CModelData : public IModelData
         * @exception
         * @see
         */
-        std::string getPropertyName(IN int propertyIndex);
+        std::string getPropertyName(int propertyIndex);
 
         /**
         * @fn     getPropertyValue
@@ -120,7 +120,7 @@ class CModelData : public IModelData
         * @exception
         * @see
         */
-        std::string getPropertyValue(IN int propertyIndex);
+        std::string getPropertyValue(int propertyIndex);
 
         /**
         * @fn     getPropertyValueByName
@@ -133,7 +133,7 @@ class CModelData : public IModelData
         * @exception
         * @see
         */
-        std::string getPropertyValueByName(IN std::string propertyName);
+        std::string getPropertyValueByName(std::string propertyName);
 };
 
 #endif
index 91423e6..7922df1 100644 (file)
@@ -66,8 +66,8 @@ void CPropagationEngine::finalRelease()
     }
 }
 
-SSMRESULT CPropagationEngine::findContextModel(IN std::string modelName,
-        OUT IContextModel  **ppContextModel)
+SSMRESULT CPropagationEngine::findContextModel(std::string modelName,
+        IContextModel  **ppContextModel)
 {
     SSMRESULT res = SSM_S_FALSE;
     std::map<std::string, IContextModel *>::iterator idxContextModel;
@@ -86,8 +86,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CPropagationEngine::registerCondition(IN IContextModel *pContextModel,
-        IN ModelConditionVec *pConditions, IN IConditionedQuery *pConditionedQuery)
+SSMRESULT CPropagationEngine::registerCondition(IContextModel *pContextModel,
+        ModelConditionVec *pConditions, IConditionedQuery *pConditionedQuery)
 {
     SSMRESULT res = SSM_E_FAIL;
     IConditionedModel           *pConditionedModel = NULL;
@@ -102,8 +102,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CPropagationEngine::registerVirtualCondition(IN std::string virtualContextModelName,
-        IN ModelConditionVec *pConditions, IN IConditionedQuery *pConditionedQuery)
+SSMRESULT CPropagationEngine::registerVirtualCondition(std::string virtualContextModelName,
+        ModelConditionVec *pConditions, IConditionedQuery *pConditionedQuery)
 {
     pConditionedQuery->addRef();
     m_mtxLookUpList.lock();
@@ -113,8 +113,8 @@ SSMRESULT CPropagationEngine::registerVirtualCondition(IN std::string virtualCon
     return SSM_S_OK;
 }
 
-SSMRESULT CPropagationEngine::propagateNewModel(IN std::string newModelName,
-        IN IContextModel *pContextModel)
+SSMRESULT CPropagationEngine::propagateNewModel(std::string newModelName,
+        IContextModel *pContextModel)
 {
     SSMRESULT res = SSM_E_FAIL;
     VirtualModelMap::iterator   itorVModels;
@@ -162,7 +162,7 @@ CLEANUP:
 }
 
 //Install new resource and update Device table
-SSMRESULT CPropagationEngine::installContextModelFromISSMResource(IN ISSMResource *pSSMResource)
+SSMRESULT CPropagationEngine::installContextModelFromISSMResource(ISSMResource *pSSMResource)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -243,7 +243,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CPropagationEngine::updateDeviceInfo(IN ISSMResource *pSSMResource, OUT int *deviceId)
+SSMRESULT CPropagationEngine::updateDeviceInfo(ISSMResource *pSSMResource, int *deviceId)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -307,9 +307,9 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CPropagationEngine::installContextModel(IN IContextModel *pParentModel,
-        IN IContextModel::ConstructionType constructionType, IN const char *modelName,
-        IN ModelPropertyVec *pModelDescs, OUT IContextModel **ppContextModel)
+SSMRESULT CPropagationEngine::installContextModel(IContextModel *pParentModel,
+        IContextModel::ConstructionType constructionType, const char *modelName,
+        ModelPropertyVec *pModelDescs, IContextModel **ppContextModel)
 {
     SSMRESULT                   res = SSM_E_FAIL;
     CObject<CContextModel>      *pNewModel;
@@ -360,7 +360,7 @@ CLEANUP:
     return res;
 }
 
-void CPropagationEngine::onExecute(IN void *pArg)
+void CPropagationEngine::onExecute(void *pArg)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -393,15 +393,15 @@ CLEANUP:
     ;
 }
 
-void CPropagationEngine::onTerminate(IN void *pArg)
+void CPropagationEngine::onTerminate(void *pArg)
 {
     intptr_t         *pMessage = (intptr_t *)pArg;
 
     delete[] pMessage;
 }
 
-int CPropagationEngine::onResourceEvent(IN RESOURCE_EVENT_TYPE eventType,
-                                        IN ISSMResource *pSSMResource, IN std::string info)
+int CPropagationEngine::onResourceEvent(RESOURCE_EVENT_TYPE eventType,
+                                        ISSMResource *pSSMResource, std::string info)
 {
     intptr_t          *pMessage = new intptr_t [2];
 
@@ -466,8 +466,8 @@ CLEANUP:
     return;
 }
 
-SSMRESULT CPropagationEngine::getContextModel(IN std:: string modelName,
-        OUT IContextModel **ppContextModel)
+SSMRESULT CPropagationEngine::getContextModel(std:: string modelName,
+        IContextModel **ppContextModel)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -476,9 +476,9 @@ SSMRESULT CPropagationEngine::getContextModel(IN std:: string modelName,
     return res == SSM_S_OK ? SSM_S_OK : SSM_E_FAIL;
 }
 
-SSMRESULT CPropagationEngine::createConditionedQuery(IN IContextModel::ActivationType
-        activationType, IN QueryCondition *pQueryCondition, IN IConditionedQueryEvent *pEvent,
-        OUT IConditionedQuery **ppConditionedQuery)
+SSMRESULT CPropagationEngine::createConditionedQuery(IContextModel::ActivationType
+        activationType, QueryCondition *pQueryCondition, IConditionedQueryEvent *pEvent,
+        IConditionedQuery **ppConditionedQuery)
 {
     SSMRESULT res = SSM_E_FAIL;
     CObject<CConditionedQuery>  *pConditionedQuery;
@@ -518,8 +518,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CPropagationEngine::onModelStatusChange(IN IContextModel::Status newStatus,
-        IN ISSMResource *pSSMResource, IN IContextModel *pModel)
+SSMRESULT CPropagationEngine::onModelStatusChange(IContextModel::Status newStatus,
+        ISSMResource *pSSMResource, IContextModel *pModel)
 {
     switch (newStatus)
     {
@@ -551,8 +551,8 @@ SSMRESULT CPropagationEngine::onModelStatusChange(IN IContextModel::Status newSt
     return SSM_S_OK;
 }
 
-SSMRESULT CPropagationEngine::onQueryContextModel(IN std::string modelName,
-        OUT IContextModel **ppContextModel)
+SSMRESULT CPropagationEngine::onQueryContextModel(std::string modelName,
+        IContextModel **ppContextModel)
 {
     std::map<std::string, IContextModel *>::iterator     itorContextModel;
 
index 0b59a69..6bc2b87 100644 (file)
@@ -62,26 +62,26 @@ class CPropagationEngine :
 
         std::map<std::string, int>                  m_searchedSensorDataId;
 
-        SSMRESULT findContextModel(IN std::string modelName, OUT IContextModel  **ppContextModel);
+        SSMRESULT findContextModel(std::string modelName, IContextModel  **ppContextModel);
 
-        SSMRESULT registerCondition(IN IContextModel *pContextModel, IN ModelConditionVec *pConditions,
-                                    IN IConditionedQuery *pConditionedQuery);
+        SSMRESULT registerCondition(IContextModel *pContextModel, ModelConditionVec *pConditions,
+                                    IConditionedQuery *pConditionedQuery);
 
-        SSMRESULT registerVirtualCondition(IN std::string virtualContextModelName,
-                                           IN ModelConditionVec *pConditions, IN IConditionedQuery *pConditionedQuery);
+        SSMRESULT registerVirtualCondition(std::string virtualContextModelName,
+                                           ModelConditionVec *pConditions, IConditionedQuery *pConditionedQuery);
 
-        SSMRESULT propagateNewModel(IN std::string newModelName, IN IContextModel *pContextModel);
+        SSMRESULT propagateNewModel(std::string newModelName, IContextModel *pContextModel);
 
         SSMRESULT addResourceFromGetList();
 
         //TODO: Install Context model from SSMResource
         SSMRESULT installCurrentSensors();
 
-        SSMRESULT installContextModelFromISSMResource(IN ISSMResource *pSSMResource);
+        SSMRESULT installContextModelFromISSMResource(ISSMResource *pSSMResource);
 
-        SSMRESULT installContextModel(IN IContextModel *pParentModel,
-                                      IN IContextModel::ConstructionType constructionType,
-                                      IN const char *modelName, IN ModelPropertyVec *pModelDescs, OUT IContextModel **ppContextModel);
+        SSMRESULT installContextModel(IContextModel *pParentModel,
+                                      IContextModel::ConstructionType constructionType,
+                                      const char *modelName, ModelPropertyVec *pModelDescs, IContextModel **ppContextModel);
 
         SSMRESULT recoverEngineFromDatabase();
 
@@ -91,16 +91,16 @@ class CPropagationEngine :
 
         void terminateEngine();
 
-        SSMRESULT updateDeviceInfo(IN ISSMResource *pSSMResource, OUT int *deviceId);
+        SSMRESULT updateDeviceInfo(ISSMResource *pSSMResource, int *deviceId);
 
     public:
         SSMRESULT finalConstruct();
 
         void finalRelease();
 
-        void onExecute(IN void *pArg);
+        void onExecute(void *pArg);
 
-        void onTerminate(IN void *pArg);
+        void onTerminate(void *pArg);
 
         /**
         * @fn     onResourceEvent
@@ -115,8 +115,8 @@ class CPropagationEngine :
         * @exception
         * @see
         */
-        int onResourceEvent(IN RESOURCE_EVENT_TYPE eventType, IN ISSMResource *pSSMResource,
-                            IN std::string info);
+        int onResourceEvent(RESOURCE_EVENT_TYPE eventType, ISSMResource *pSSMResource,
+                            std::string info);
 
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
         {
@@ -146,7 +146,7 @@ class CPropagationEngine :
         * @exception
         * @see
         */
-        SSMRESULT getContextModel(IN std::string modelName, OUT IContextModel **ppContextModel);
+        SSMRESULT getContextModel(std::string modelName, IContextModel **ppContextModel);
 
         /**
         * @fn     createConditionedQuery
@@ -162,9 +162,9 @@ class CPropagationEngine :
         * @exception
         * @see
         */
-        SSMRESULT createConditionedQuery(IN IContextModel::ActivationType activationType,
-                                         IN QueryCondition *pQueryCondition,
-                                         IN IConditionedQueryEvent *pEvent, OUT IConditionedQuery **ppConditionedQuery);
+        SSMRESULT createConditionedQuery(IContextModel::ActivationType activationType,
+                                         QueryCondition *pQueryCondition,
+                                         IConditionedQueryEvent *pEvent, IConditionedQuery **ppConditionedQuery);
 
         /**
         * @fn     onModelStatusChange
@@ -179,8 +179,8 @@ class CPropagationEngine :
         * @exception
         * @see
         */
-        SSMRESULT onModelStatusChange(IN IContextModel::Status newStatus, IN ISSMResource *pSSMResource,
-                                      IN IContextModel *pModel);
+        SSMRESULT onModelStatusChange(IContextModel::Status newStatus, ISSMResource *pSSMResource,
+                                      IContextModel *pModel);
 
         /**
         * @fn     onQueryContextModel
@@ -194,6 +194,6 @@ class CPropagationEngine :
         * @exception
         * @see
         */
-        SSMRESULT onQueryContextModel(IN std::string modelName, OUT IContextModel **ppContextModel);
+        SSMRESULT onQueryContextModel(std::string modelName, IContextModel **ppContextModel);
 };
 #endif
index 100de71..7399891 100644 (file)
@@ -60,8 +60,8 @@ void CQueryEngine::finalRelease()
     m_mtxQueries.unlock();
 }
 
-SSMRESULT CQueryEngine::processQueryResult(IN int userTriggerId,
-        IN std::vector<result_model> *result)
+SSMRESULT CQueryEngine::processQueryResult(int userTriggerId,
+        std::vector<result_model> *result)
 {
     SSMRESULT           res = SSM_E_FAIL;
     ModelPropertyVec    modelData;
@@ -83,10 +83,8 @@ SSMRESULT CQueryEngine::processQueryResult(IN int userTriggerId,
     }
 
     m_contextQueries[userTriggerId]->check_result_model();
-    m_contextQueries[userTriggerId]->return_modelID(&modelID);
-
-
     m_contextQueries[userTriggerId]->return_contextName(&contextName);
+    m_contextQueries[userTriggerId]->return_modelID(&modelID);
 
     for (unsigned int i = 0; i < modelID.size(); i++)
     {
@@ -176,8 +174,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CQueryEngine::validateQueryResult(IN IConditionedQueryResult *pConditionedQueryResult,
-        OUT std::vector<result_model> *resultData)
+SSMRESULT CQueryEngine::validateQueryResult(IConditionedQueryResult *pConditionedQueryResult,
+        std::vector<result_model> *resultData)
 {
     SSMRESULT               res = SSM_E_FAIL;
     IContextModel           *pContextModel = NULL;
@@ -219,8 +217,8 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CQueryEngine::onConditionedQueryEvent(IN int userTriggerId,
-        IN IConditionedQueryResult *pConditionedQueryResult)
+SSMRESULT CQueryEngine::onConditionedQueryEvent(int userTriggerId,
+        IConditionedQueryResult *pConditionedQueryResult)
 {
     SSMRESULT                   res = SSM_E_FAIL;
     std::vector<result_model>   result;
@@ -263,12 +261,12 @@ void CQueryEngine::onTerminate(void *pArg)
     switch (pData[0])
     {
         case EVENT_TYPE_INNER:
-            pResult = (std::vector<result_model> *)(((int *)pArg)[2]);
+            pResult = (std::vector<result_model> *)pData[2];
             SAFE_DELETE(pResult);
             break;
 
         case EVENT_TYPE_OUTER:
-            pDataReader = (CDataReader *)(((int *)pArg)[2]);
+            pDataReader = (CDataReader *)pData[2];
             SAFE_DELETE(pDataReader);
             break;
 
@@ -278,7 +276,7 @@ void CQueryEngine::onTerminate(void *pArg)
     SAFE_ARRAY_DELETE(pData);
 }
 
-SSMRESULT CQueryEngine::executeContextQuery(IN std::string contextQuery, OUT int *cqid)
+SSMRESULT CQueryEngine::executeContextQuery(std::string contextQuery, int *cqid)
 {
     SSMRESULT               res = SSM_E_FAIL;
     IConditionedQuery       *pConditionedQuery = NULL;
@@ -289,12 +287,14 @@ SSMRESULT CQueryEngine::executeContextQuery(IN std::string contextQuery, OUT int
     CCQLParser              cqlParser;
     IContextModel::ActivationType   queryCommandType;
 
-    cqlParser.parse(contextQuery, &token);
+    if (!cqlParser.parse(contextQuery, &token))
+    {
+        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+    }
 
     if (!cqlParser.check_grammer(&token))
     {
-        res = SSM_E_FAIL;
-        goto CLEANUP;
+        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
     }
 
     clsContextQuery = new CContextQuery();
@@ -370,13 +370,13 @@ CLEANUP:
 }
 
 //TODO: Registration with multiple instance support
-SSMRESULT CQueryEngine::registerQueryEvent(IN IQueryEngineEvent *pQueryEngineEvent)
+SSMRESULT CQueryEngine::registerQueryEvent(IQueryEngineEvent *pQueryEngineEvent)
 {
     m_pQueryEngineEvent = pQueryEngineEvent;
     return SSM_S_OK;
 }
 
-SSMRESULT CQueryEngine::unregisterQueryEvent(IN IQueryEngineEvent *pQueryEngineEvent)
+SSMRESULT CQueryEngine::unregisterQueryEvent(IQueryEngineEvent *pQueryEngineEvent)
 {
     if (m_pQueryEngineEvent == pQueryEngineEvent)
     {
@@ -387,7 +387,7 @@ SSMRESULT CQueryEngine::unregisterQueryEvent(IN IQueryEngineEvent *pQueryEngineE
     return SSM_E_FAIL;
 }
 
-SSMRESULT CQueryEngine::killContextQuery(IN int cqid)
+SSMRESULT CQueryEngine::killContextQuery(int cqid)
 {
     SSMRESULT res = SSM_E_FAIL;
 
index a1d96c3..f9f533b 100644 (file)
@@ -52,9 +52,9 @@ class CQueryEngine :
         CObjectPtr<ITasker>                 m_pTasker;
 
     private:
-        SSMRESULT processQueryResult(IN int userTriggerId, IN std::vector<result_model> *result);
-        SSMRESULT validateQueryResult(IN IConditionedQueryResult *pConditionedQueryResult,
-                                      OUT std::vector<result_model> *resultData);
+        SSMRESULT processQueryResult(int userTriggerId, std::vector<result_model> *result);
+        SSMRESULT validateQueryResult(IConditionedQueryResult *pConditionedQueryResult,
+                                      std::vector<result_model> *resultData);
 
     public:
         enum EventType {EVENT_TYPE_INNER, EVENT_TYPE_OUTER};
@@ -74,8 +74,8 @@ class CQueryEngine :
         * @exception
         * @see
         */
-        SSMRESULT onConditionedQueryEvent(IN int userTriggerId,
-                                          IN IConditionedQueryResult *pConditionedQueryResult);
+        SSMRESULT onConditionedQueryEvent(int userTriggerId,
+                                          IConditionedQueryResult *pConditionedQueryResult);
 
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
         {
@@ -104,7 +104,7 @@ class CQueryEngine :
         * @exception
         * @see
         */
-        SSMRESULT executeContextQuery(IN std::string contextQuery, OUT int *cqid);
+        SSMRESULT executeContextQuery(std::string contextQuery, int *cqid);
 
         //TODO: Registration with multiple instance support
         /**
@@ -117,7 +117,7 @@ class CQueryEngine :
         * @exception
         * @see
         */
-        SSMRESULT registerQueryEvent(IN IQueryEngineEvent *pQueryEngineEvent);
+        SSMRESULT registerQueryEvent(IQueryEngineEvent *pQueryEngineEvent);
 
 
         /**
@@ -130,7 +130,7 @@ class CQueryEngine :
         * @exception
         * @see
         */
-        SSMRESULT unregisterQueryEvent(IN IQueryEngineEvent *pQueryEngineEvent);
+        SSMRESULT unregisterQueryEvent(IQueryEngineEvent *pQueryEngineEvent);
 
         /**
         * @fn killContextQuery
@@ -143,7 +143,7 @@ class CQueryEngine :
         * @exception
         * @see
         */
-        SSMRESULT killContextQuery(IN int cqid);
+        SSMRESULT killContextQuery(int cqid);
 };
 
 #endif /*_QueryEngine_H_*/
index 5b1340f..023a040 100644 (file)
@@ -23,7 +23,7 @@
 
 static ISoftSensorManager       *g_pSoftSensorManager = NULL;
 
-SSMRESULT CreateQueryEngine(OUT IQueryEngine **ppQueryEngine)
+SSMRESULT CreateQueryEngine(IQueryEngine **ppQueryEngine)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -34,7 +34,7 @@ CLEANUP:
     return res;
 }
 
-unsigned long ReleaseQueryEngine(IN IQueryEngine *pQueryEngine)
+unsigned long ReleaseQueryEngine(IQueryEngine *pQueryEngine)
 {
     if (pQueryEngine == NULL)
     {
@@ -49,19 +49,25 @@ unsigned long ReleaseQueryEngine(IN IQueryEngine *pQueryEngine)
     return g_pSoftSensorManager->releaseQueryEngine(pQueryEngine);
 }
 
-SSMRESULT InitializeSSMCore(IN std::string xmlDescription)
+SSMRESULT InitializeSSMCore(std::string xmlDescription)
 {
     SSMRESULT res = SSM_E_FAIL;
 
+    if (g_pSoftSensorManager != NULL)
+        SSM_CLEANUP_ASSERT(SSM_E_INITIALIZED);
+
     SSM_CLEANUP_ASSERT(CreateGlobalInstanceRepo());
     SSM_CLEANUP_ASSERT(CreateInstance(OID_ISoftSensorManager, (IBase **)&g_pSoftSensorManager));
     SSM_CLEANUP_ASSERT(g_pSoftSensorManager->initializeCore(xmlDescription));
 
 CLEANUP:
-    if (res != SSM_S_OK)
+    if (res != SSM_S_OK &&
+        res != SSM_E_INITIALIZED)
     {
         SAFE_RELEASE(g_pSoftSensorManager);
+        DestroyGlobalInstanceRepo();
     }
+
     return res;
 }
 
@@ -122,6 +128,18 @@ const char *GetSSMError(SSMRESULT res)
             msg = "SSM_E_FAIL";
             break;
 
+        case SSM_E_NOTINIT:
+            msg = "SSM_E_NOTINIT";
+            break;
+
+        case SSM_E_INITIALIZED:
+            msg = "SSM_E_INITIALIZED";
+            break;
+
+        case SSM_E_INVALIDXML:
+            msg = "SSM_E_INVALIDXML";
+            break;
+
         case SSM_E_NOINTERFACE:
             msg = "SSM_E_NOINTERFACE";
             break;
@@ -138,7 +156,7 @@ const char *GetSSMError(SSMRESULT res)
     return msg;
 }
 
-SSMRESULT GetInstalledModelList(OUT std::vector<ISSMResource *> *pList)
+SSMRESULT GetInstalledModelList(std::vector<ISSMResource *> *pList)
 {
     SSMRESULT res = SSM_E_FAIL;
 
index 4c690d4..6ef73b9 100644 (file)
@@ -28,17 +28,6 @@ using namespace OIC;
 
 #define IN
 #define OUT
-/*
-#if defined(WIN32) && defined(SSMCORE_WINDOWS_EXPORTS)
-#define INTERFACE_DECLSPEC    __declspec(dllexport)
-#elif defined(WIN32)
-#define INTERFACE_DECLSPEC    __declspec(dllimport)
-#pragma comment(lib, "SSMCore_Windows.lib")
-#else
-#define INTERFACE_DECLSPEC
-#endif
-*/
-#define INTERFACE_DECLSPEC
 
 /**
 * @class    IQueryEngine
@@ -63,7 +52,7 @@ class IQueryEngine
         * @exception
         * @see
         */
-        virtual SSMRESULT executeContextQuery(IN std::string contextQuery, OUT int *cqid) = 0;
+        virtual SSMRESULT executeContextQuery(std::string contextQuery, int *cqid) = 0;
 
         /**
         * @fn     registerQueryEvent
@@ -76,7 +65,7 @@ class IQueryEngine
         * @exception
         * @see
         */
-        virtual SSMRESULT registerQueryEvent(IN IQueryEngineEvent *pQueryEngineEvent) = 0;
+        virtual SSMRESULT registerQueryEvent(IQueryEngineEvent *pQueryEngineEvent) = 0;
 
         /**
         * @fn     unregisterQueryEvent
@@ -89,7 +78,7 @@ class IQueryEngine
         * @exception
         * @see
         */
-        virtual SSMRESULT unregisterQueryEvent(IN IQueryEngineEvent *pQueryEngineEvent) = 0;
+        virtual SSMRESULT unregisterQueryEvent(IQueryEngineEvent *pQueryEngineEvent) = 0;
 
         /**
         * @fn    killContextQuery
@@ -102,7 +91,7 @@ class IQueryEngine
         * @exception
         * @see
         */
-        virtual SSMRESULT killContextQuery(IN int cqid) = 0;
+        virtual SSMRESULT killContextQuery(int cqid) = 0;
     protected:
         virtual ~IQueryEngine() {};
 };
@@ -123,7 +112,7 @@ extern "C"
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC SSMRESULT CreateQueryEngine(OUT IQueryEngine **ppQueryEngine);
+INTERFACE_DECLSPEC SSMRESULT CreateQueryEngine(IQueryEngine **ppQueryEngine);
 
 /**
 * @fn    ReleaseQueryEngine
@@ -136,7 +125,7 @@ INTERFACE_DECLSPEC SSMRESULT CreateQueryEngine(OUT IQueryEngine **ppQueryEngine)
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC unsigned long ReleaseQueryEngine(IN IQueryEngine *pQueryEngine);
+INTERFACE_DECLSPEC unsigned long ReleaseQueryEngine(IQueryEngine *pQueryEngine);
 
 
 /**
@@ -151,7 +140,7 @@ INTERFACE_DECLSPEC unsigned long ReleaseQueryEngine(IN IQueryEngine *pQueryEngin
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC SSMRESULT InitializeSSMCore(IN std::string xmlDescription);
+INTERFACE_DECLSPEC SSMRESULT InitializeSSMCore(std::string xmlDescription);
 
 /**
 * @fn    StartSSMCore
@@ -190,7 +179,7 @@ INTERFACE_DECLSPEC SSMRESULT StopSSMCore();
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC SSMRESULT TerminateSSMCore(IN bool factoryResetFlag = false);
+INTERFACE_DECLSPEC SSMRESULT TerminateSSMCore(bool factoryResetFlag = false);
 
 /**
 * @fn    GetErrorMessage
@@ -203,7 +192,7 @@ INTERFACE_DECLSPEC SSMRESULT TerminateSSMCore(IN bool factoryResetFlag = false);
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC const char *GetSSMError(IN SSMRESULT res);
+INTERFACE_DECLSPEC const char *GetSSMError(SSMRESULT res);
 
 /**
 * @fn    GetInstalledModelList
@@ -216,7 +205,7 @@ INTERFACE_DECLSPEC const char *GetSSMError(IN SSMRESULT res);
 * @exception
 * @see
 */
-INTERFACE_DECLSPEC SSMRESULT GetInstalledModelList(OUT std::vector<ISSMResource *> *pList);
+INTERFACE_DECLSPEC SSMRESULT GetInstalledModelList(std::vector<ISSMResource *> *pList);
 
 #ifdef __cplusplus
 }
index 9dbb031..f088ed2 100644 (file)
@@ -17,8 +17,9 @@
 * limitations under the License.
 *
 ******************************************************************/
-#include "SSMCore.h"
 #include "SSMInterface/SSMCore_JNI.h"
+
+#include "SSMCore.h"
 #include "Common/PlatformLayer.h"
 
 #define JNI_E_INVALIDARG -1001
@@ -37,7 +38,6 @@ jclass                      g_ClassQueryEngine = NULL;
 jclass                      g_ClassDataReader = NULL;
 jclass                      g_ClassModelData = NULL;
 jclass                      g_ClassQueryEngineEvent = NULL;
-
 jclass                      g_ClassReportReceiver = NULL;
 jobject                     g_objReportReceiver = NULL;
 
@@ -53,13 +53,11 @@ void ReportMessage(const char *tag, const char *msg)
     ATTACH_CURRENT_THREAD(g_JVM, env);
 
     jmethodID midReportReceiver =
-        env->GetMethodID(g_ClassReportReceiver, "OnMessageReceived",
+        env->GetMethodID(g_ClassReportReceiver, "onMessageReceived",
                          "(Ljava/lang/String;Ljava/lang/String;)V");
 
-    jclass nonVIrtualObject = env->GetObjectClass(g_objReportReceiver);
-
-    env->CallNonvirtualVoidMethod(g_objReportReceiver, nonVIrtualObject, midReportReceiver,
-                                  env->NewStringUTF(tag), env->NewStringUTF(msg));
+    env->CallVoidMethod(g_objReportReceiver, midReportReceiver,
+                        env->NewStringUTF(tag), env->NewStringUTF(msg));
 
     DETACH_CURRENT_THREAD(g_JVM);
 
@@ -88,7 +86,7 @@ class QueryEngineEventReceiver
             }
         }
 
-        void SetQueryEngineEventObj(jobject objQueryEngineEvent)
+        void setQueryEngineEventObj(jobject objQueryEngineEvent)
         {
             if (m_objQueryEngineEvent != NULL)
             {
@@ -100,7 +98,7 @@ class QueryEngineEventReceiver
             m_objQueryEngineEvent = objQueryEngineEvent;
         }
 
-        SSMRESULT onQueryEngineEvent(IN int cqid, IN IDataReader *pResult)
+        SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult)
         {
             JNIEnv *env;
             g_JVM->GetEnv((void **) &env, JNI_VERSION_1_6);
@@ -108,19 +106,17 @@ class QueryEngineEventReceiver
             ATTACH_CURRENT_THREAD(g_JVM, env);
 
             jmethodID midQueryEngineEvent =
-                env->GetMethodID(g_ClassQueryEngineEvent, "OnQueryEngineEvent",
-                                 "(ILcom/sec/android/ssmcore/DataReader;)V");
-
-            jclass nonVIrtualObject = env->GetObjectClass(m_objQueryEngineEvent);
+                env->GetMethodID(g_ClassQueryEngineEvent, "onQueryEngineEvent",
+                                 "(ILorg/iotivity/service/ssm/DataReader;)V");
 
             jmethodID cid_DataReader = env->GetMethodID(g_ClassDataReader, "<init>", "(I)V");
 
             if (cid_DataReader == NULL)
                 return SSM_E_FAIL;
 
-            env->CallNonvirtualVoidMethod(m_objQueryEngineEvent, nonVIrtualObject, midQueryEngineEvent,
-                                          (jint)cqid,
-                                          env->NewObject(g_ClassDataReader, cid_DataReader, (jint)pResult));
+            env->CallVoidMethod(m_objQueryEngineEvent, midQueryEngineEvent,
+                                (jint)cqid,
+                                env->NewObject(g_ClassDataReader, cid_DataReader, (jint)pResult));
 
             DETACH_CURRENT_THREAD(g_JVM);
 
@@ -137,19 +133,19 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
         return JNI_ERR;
 
     g_ClassQueryEngine = (jclass) env->NewGlobalRef(
-                             env->FindClass("com/sec/android/ssmcore/QueryEngine"));
+                             env->FindClass("org/iotivity/service/ssm/QueryEngine"));
 
     g_ClassDataReader = (jclass) env->NewGlobalRef(
-                            env->FindClass("com/sec/android/ssmcore/DataReader"));
+                            env->FindClass("org/iotivity/service/ssm/DataReader"));
 
-    g_ClassModelData = (jclass) env->NewGlobalRef(env->FindClass("com/sec/android/ssmcore/ModelData"));
+    g_ClassModelData = (jclass) env->NewGlobalRef(env->FindClass("org/iotivity/service/ssm/ModelData"));
 
     g_ClassQueryEngineEvent = (jclass) env->NewGlobalRef(
-                                  env->FindClass("com/sec/android/ssmcore/IQueryEngineEvent"));
+                                  env->FindClass("org/iotivity/service/ssm/IQueryEngineEvent"));
 
 
     g_ClassReportReceiver = (jclass) env->NewGlobalRef(
-                                env->FindClass("com/sec/android/ssmcore/IReportReceiver"));
+                                env->FindClass("org/iotivity/service/ssm/IReportReceiver"));
 
 
     g_JVM = jvm;
@@ -191,9 +187,16 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jvm, void *reserved)
         delete g_QueryEngineEventReceiver;
 }
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_InitializeSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_initializeSSMCore
 (JNIEnv *env, jclass clz, jstring jstrXmlDescription)
 {
+    if (jstrXmlDescription == NULL)
+    {
+        env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"),
+                      "InitializeSSMCore failed with Invalid parameter");
+        return;
+    }
+
     SSMRESULT res = SSM_E_FAIL;
     const char *xmlDescription = env->GetStringUTFChars(jstrXmlDescription, NULL);
 
@@ -205,28 +208,28 @@ JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_InitializeSSM
         env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), "InitializeSSMCore failed");
 }
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_StartSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_startSSMCore
 (JNIEnv *env, jclass clz)
 {
     if (StartSSMCore() != SSM_S_OK)
         env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), "StartSSMCore failed");
 }
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_StopSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_stopSSMCore
 (JNIEnv *env, jclass clz)
 {
     if (StopSSMCore() != SSM_S_OK)
         env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), "StopSSMCore failed");
 }
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_TerminateSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_terminateSSMCore
 (JNIEnv *env, jclass clz)
 {
     if (TerminateSSMCore() != SSM_S_OK)
         env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), "TerminateSSMCore failed");
 }
 
-JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_CreateQueryEngine
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ssm_CoreController_createQueryEngine
 (JNIEnv *env, jclass clz)
 {
     IQueryEngine        *pQueryEngine = NULL;
@@ -245,13 +248,13 @@ JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_CreateQuer
     return env->NewObject(g_ClassQueryEngine, cid_QueryEngine, (jint)pQueryEngine);
 }
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_ReleaseQueryEngine
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_releaseQueryEngine
 (JNIEnv *env, jclass clz, jobject queryEngine)
 {
     IQueryEngine        *pQueryEngine = NULL;
 
     jmethodID mid_GetQueryEngineInstance = env->GetMethodID(g_ClassQueryEngine,
-                                           "GetQueryEngineInstance", "()I");
+                                           "getQueryEngineInstance", "()I");
 
     if (mid_GetQueryEngineInstance == NULL)
         return JNI_E_METHODID;
@@ -261,10 +264,17 @@ JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_ReleaseQueryE
     return ReleaseQueryEngine(pQueryEngine);
 }
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_ExecuteContextQuery
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_executeContextQuery
 (JNIEnv *env, jclass clz, jint pQueryEngineInstance, jstring jstrContextQuery)
 {
-    int                 cqid = 0;
+    int                 cqid = -1;
+    if (jstrContextQuery == NULL)
+    {
+        env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"),
+                      "ExecuteContextQuery with Invalid context query");
+        return cqid;
+    }
+
     IQueryEngine        *pQueryEngine = (IQueryEngine *)pQueryEngineInstance;
 
     const char *contextQuery = env->GetStringUTFChars(jstrContextQuery, NULL);
@@ -278,7 +288,7 @@ JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_ExecuteContex
     return cqid;
 }
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_RegisterQueryEvent
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_registerQueryEvent
 (JNIEnv *env, jclass clz, jint pQueryEngineInstance, jobject queryEngineEvent)
 {
     IQueryEngine        *pQueryEngine = (IQueryEngine *)pQueryEngineInstance;
@@ -289,11 +299,11 @@ JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_RegisterQuery
         return;
     }
 
-    g_QueryEngineEventReceiver->SetQueryEngineEventObj(env->NewGlobalRef(queryEngineEvent));
+    g_QueryEngineEventReceiver->setQueryEngineEventObj(env->NewGlobalRef(queryEngineEvent));
     pQueryEngine->registerQueryEvent(g_QueryEngineEventReceiver);
 }
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_KillContextQuery
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_killContextQuery
 (JNIEnv *env, jclass clz, jint pQueryEngineInstance, jint cqid)
 {
     IQueryEngine        *pQueryEngine = (IQueryEngine *)pQueryEngineInstance;
@@ -304,7 +314,7 @@ JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_KillContextQu
     }
 }
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetDataId
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_getDataId
 (JNIEnv *env, jclass clz, jint pDataReaderInstance)
 {
     IModelData *pDataReader = (IModelData *)pDataReaderInstance;
@@ -312,7 +322,7 @@ JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetDataId
     return pDataReader->getDataId();
 }
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropertyCount
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_getPropertyCount
 (JNIEnv *env, jclass clz, jint pIModelDataInstance )
 {
     IModelData *pModelData = (IModelData *)pIModelDataInstance;
@@ -320,7 +330,7 @@ JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropertyCo
     return pModelData->getPropertyCount();
 }
 
-JNIEXPORT jstring JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropertyName
+JNIEXPORT jstring JNICALL Java_org_iotivity_service_ssm_CoreController_getPropertyName
 (JNIEnv *env, jclass clz, jint pIModelDataInstance, jint propertyIndex )
 {
     IModelData *pModelData = (IModelData *)pIModelDataInstance;
@@ -328,7 +338,7 @@ JNIEXPORT jstring JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropert
     return env->NewStringUTF(pModelData->getPropertyName(propertyIndex).c_str());
 }
 
-JNIEXPORT jstring JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropertyValue
+JNIEXPORT jstring JNICALL Java_org_iotivity_service_ssm_CoreController_getPropertyValue
 (JNIEnv *env, jclass clz, jint pIModelDataInstance, jint propertyIndex )
 {
     IModelData *pModelData = (IModelData *)pIModelDataInstance;
@@ -336,7 +346,7 @@ JNIEXPORT jstring JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropert
     return env->NewStringUTF(pModelData->getPropertyValue(propertyIndex).c_str());
 }
 
-JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_GetAffectedModels
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ssm_CoreController_getAffectedModels
 (JNIEnv *env, jclass clz, jint pDataReaderInstance)
 {
     IDataReader *pDataReader = (IDataReader *)pDataReaderInstance;
@@ -361,7 +371,7 @@ JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_GetAffecte
     return objAffectedModels;
 }
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetModelDataCount
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_getModelDataCount
 (JNIEnv *env, jclass clz, jint pDataReaderInstance, jstring jstrModelName)
 {
     IDataReader *pDataReader = (IDataReader *)pDataReaderInstance;
@@ -378,7 +388,7 @@ JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetModelDataC
     return modelCount;
 }
 //return IModelData
-JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_GetModelData
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ssm_CoreController_getModelData
 (JNIEnv *env, jclass clz, jint pDataReaderInstance, jstring jstrModelName, jint jintDataIndex )
 {
     IDataReader *pDataReader = (IDataReader *)pDataReaderInstance;
@@ -399,7 +409,7 @@ JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_GetModelDa
     return env->NewObject(g_ClassModelData, cid_ModelData, (jint)pModelData);
 }
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_RegisterReportReceiver
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_registerReportReceiver
 (JNIEnv *env, jclass clz, jobject reportReceiver)
 {
     if (g_objReportReceiver != NULL)
index 4f50e2b..d950bce 100644 (file)
 extern "C" {
 #endif
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_InitializeSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_initializeSSMCore
 (JNIEnv *env, jclass clz, jstring jstrXmlDescription);
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_StartSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_startSSMCore
 (JNIEnv *env, jclass clz);
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_StopSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_stopSSMCore
 (JNIEnv *env, jclass clz);
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_TerminateSSMCore
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_terminateSSMCore
 (JNIEnv *env, jclass clz);
 
-JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_CreateQueryEngine
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ssm_CoreController_createQueryEngine
 (JNIEnv *env, jclass clz);
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_ReleaseQueryEngine
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_releaseQueryEngine
 (JNIEnv *env, jclass clz, jobject queryEngine);
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_ExecuteContextQuery
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_executeContextQuery
 (JNIEnv *env, jclass clz, jint pQueryEngineInstance, jstring jstrContextQuery);
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_RegisterQueryEvent
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_registerQueryEvent
 (JNIEnv *env, jclass clz, jint pQueryEngineInstance, jobject queryEngineEvent);
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_KillContextQuery
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_killContextQuery
 (JNIEnv *env, jclass clz, jint pQueryEngineInstance, jint cqid);
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_Release
-(JNIEnv *env, jclass clz, jint pQueryEngineInstance);
-
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetDataId
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_getDataId
 (JNIEnv *env, jclass clz, jint pDataReaderInstance);
 
-JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_GetAffectedModels
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ssm_CoreController_getAffectedModels
 (JNIEnv *env, jclass clz, jint pDataReaderInstance);
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetModelDataCount
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_getModelDataCount
 (JNIEnv *env, jclass clz, jint pDataReaderInstance, jstring jstrModelName);
 
-JNIEXPORT jobject JNICALL Java_com_sec_android_ssmcore_CoreController_GetModelData
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ssm_CoreController_getModelData
 (JNIEnv *env, jclass clz, jint pDataReaderInstance, jstring jstrModelName, jint jintDataIndex );
 
-JNIEXPORT jint JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropertyCount
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ssm_CoreController_getPropertyCount
 (JNIEnv *env, jclass clz, jint pIModelDataInstance );
 
-JNIEXPORT jstring JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropertyName
+JNIEXPORT jstring JNICALL Java_org_iotivity_service_ssm_CoreController_getPropertyName
 (JNIEnv *env, jclass clz, jint pIModelDataInstance, jint propertyIndex );
 
-JNIEXPORT jstring JNICALL Java_com_sec_android_ssmcore_CoreController_GetPropertyValue
+JNIEXPORT jstring JNICALL Java_org_iotivity_service_ssm_CoreController_getPropertyValue
 (JNIEnv *env, jclass clz, jint pIModelDataInstance, jint propertyIndex );
 
-JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_RegisterReportReceiver
+JNIEXPORT void JNICALL Java_org_iotivity_service_ssm_CoreController_registerReportReceiver
 (JNIEnv *env, jclass clz, jobject reportReceiver );
 
 #ifdef __cplusplus
index c670db3..73cbe58 100644 (file)
 #include <string>
 #include <vector>
 
+#if defined(WIN32)
+
+#if defined(SSMSENSOR_WINDOWS_EXPORTS)
+#define INTERFACE_DECLSPEC    __declspec(dllexport)
+#elif defined(WIN32)
+#define INTERFACE_DECLSPEC    __declspec(dllimport)
+#endif
+
+#elif defined(TIZEN)
+
+#include <tizen.h>
+
+#define INTERFACE_DECLSPEC EXPORT_API
+
+#else
+
+#define INTERFACE_DECLSPEC
+
+#endif
+
 #define SSM_MODEL_RETRY 3
 typedef enum {SSM_ONCE, SSM_REPEAT} TypeofEvent;
 typedef enum {SSM_EVENT_NORMAL, SSM_EVENT_ADDED, SSM_REMOVED, SSM_UPDATED} RESOURCE_EVENT_TYPE;
@@ -37,6 +57,7 @@ class ISSMResource
         ISSMResource(const std::string &n, const std::string &t) :
             name(n), type(t)
         {
+               location = SENSOR_LOCATION_LOCAL;
         }
         SENSOR_LOCATION location;
         std::string name;
index de15320..d11b427 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  *
  ******************************************************************/
-
 #include "SSMResourceServer.h"
 #include "SSMCore.h"
 #include "Common/PlatformLayer.h"
@@ -40,7 +39,7 @@ class CQueryEngineEvent: public IQueryEngineEvent
             m_hSSMResource = resourceHandle;
         }
 
-        SSMRESULT onQueryEngineEvent(IN int cqid, IN IDataReader *pResult)
+        SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult)
         {
             int dataCount = 0;
             IModelData *pModelData = NULL;
@@ -109,7 +108,8 @@ class CQueryEngineEvent: public IQueryEngineEvent
             g_vecQueryEventResults.push_back(queryEventResult);
 
             //TODO: need to modify for notifying proper clients
-            OCPlatform::notifyAllObservers(m_hSSMResource);
+            if (OCPlatform::notifyAllObservers(m_hSSMResource) != OC_STACK_OK)
+                return SSM_E_FAIL;
 
             return SSM_S_OK;
         }
@@ -195,15 +195,8 @@ OCEntityHandlerResult SSMResourceServer::entityHandler(std::shared_ptr< OCResour
         response->setRequestHandle(request->getRequestHandle());
         response->setResourceHandle(request->getResourceHandle());
 
-        if (requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            // entity handler to perform resource initialization operations
-        }
-
         if (requestFlag & RequestHandlerFlag::RequestFlag)
         {
-            cout << "\t\trequestFlag : Request\n";
-
             // If the request type is GET
             if (requestType == "GET")
             {
@@ -274,7 +267,7 @@ OCEntityHandlerResult SSMResourceServer::entityHandler(std::shared_ptr< OCResour
                 }
                 else if (rep.getValue<std::string>("command") == "ReleaseQueryEngine")
                 {
-                    pQueryEngine = (IQueryEngine *) std::stoi(
+                    pQueryEngine = (IQueryEngine *) std::stoll(
                                        rep.getValue<std::string>("queryEngineId"));
 
                     ReleaseQueryEngine(pQueryEngine);
@@ -283,7 +276,7 @@ OCEntityHandlerResult SSMResourceServer::entityHandler(std::shared_ptr< OCResour
                 {
                     int CQID = 0;
 
-                    pQueryEngine = (IQueryEngine *) std::stoi(
+                    pQueryEngine = (IQueryEngine *)std::stoll(
                                        rep.getValue<std::string>("queryEngineId"));
 
                     res = pQueryEngine->executeContextQuery(
@@ -301,7 +294,7 @@ OCEntityHandlerResult SSMResourceServer::entityHandler(std::shared_ptr< OCResour
                 }
                 else if (rep.getValue<std::string>("command") == "KillContextQuery")
                 {
-                    pQueryEngine = (IQueryEngine *) std::stoi(
+                    pQueryEngine = (IQueryEngine *)std::stoll(
                                        rep.getValue<std::string>("queryEngineId"));
 
                     res = pQueryEngine->killContextQuery(std::stoi(rep.getValue<std::string>("CQID")));
index 71c5258..729dc76 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  *
  ******************************************************************/
-
 #ifndef _SSMResourceServer_H_
 #define _SSMResourceServer_H_
 
index 0d0149e..0984c28 100644 (file)
@@ -27,6 +27,7 @@
 #include "SensorProcessor/ContextExecutor.h"
 #include "SensorProcessor/ContextDataReader.h"
 #include "SensorProcessor/ResourceFinder.h"
+#include "rapidxml/rapidxml.hpp"
 
 inline bool operator<( const OID &lhs, const OID &rhs )
 {
@@ -43,7 +44,7 @@ void CSoftSensorManager::finalRelease()
 {
 }
 
-SSMRESULT CSoftSensorManager::initializeCore(IN std::string xmlDescription)
+SSMRESULT CSoftSensorManager::initializeCore(std::string xmlDescription)
 {
     SSMRESULT                   res = SSM_E_FAIL;
     rapidxml::xml_document<>    xmlDoc;
@@ -58,69 +59,84 @@ SSMRESULT CSoftSensorManager::initializeCore(IN std::string xmlDescription)
     std::string                 pathSoftSensors;
     std::string                 pathDescription;
 
-    xmlDoc.parse<0>((char *)xmlDescription.c_str());
+    std::string                 copyDescription = xmlDescription.c_str();
 
-    root = xmlDoc.first_node();
-
-    strKey = root->name();
-
-    if (strKey != "SSMCore")
+    try
     {
-        return SSM_E_FAIL;
-    }
+        xmlDoc.parse<0>((char *)copyDescription.c_str());
 
-    for (itemSSMCore = root->first_node(); itemSSMCore; itemSSMCore = itemSSMCore->next_sibling())
-    {
-        strKey = itemSSMCore->name();
+        root = xmlDoc.first_node();
 
-        if (strKey == "Device")
+        if (!root)
         {
-            for (itemDevice = itemSSMCore->first_node(); itemDevice; itemDevice = itemDevice->next_sibling())
-            {
-                strKey = itemDevice->name();
+            throw rapidxml::parse_error("No Root Element", 0);
+        }
 
-                if (strKey == "Name")
-                {
-                    name = itemDevice->value();
-                }
-                else if (strKey == "Type")
-                {
-                    type = itemDevice->value();
-                }
-                else
-                {
-                    ;/*NULL*/
-                }
-            }
+        strKey = root->name();
+
+        if (strKey != "SSMCore")
+        {
+            throw rapidxml::parse_error("Invalid root tag name", 0);
         }
-        else if (strKey == "Config")
+
+        for (itemSSMCore = root->first_node(); itemSSMCore; itemSSMCore = itemSSMCore->next_sibling())
         {
-            for (itemDevice = itemSSMCore->first_node(); itemDevice; itemDevice = itemDevice->next_sibling())
-            {
-                strKey = itemDevice->name();
+            strKey = itemSSMCore->name();
 
-                if (strKey == "SoftSensorRepository")
-                {
-                    pathSoftSensors = itemDevice->value();
-                }
-                else if (strKey == "SoftSensorDescription")
+            if (strKey == "Device")
+            {
+                for (itemDevice = itemSSMCore->first_node(); itemDevice; itemDevice = itemDevice->next_sibling())
                 {
-                    pathDescription = itemDevice->value();
+                    strKey = itemDevice->name();
+
+                    if (strKey == "Name")
+                    {
+                        name = itemDevice->value();
+                    }
+                    else if (strKey == "Type")
+                    {
+                        type = itemDevice->value();
+                    }
+                    else
+                    {
+                        ;/*NULL*/
+                    }
                 }
-                else
+            }
+            else if (strKey == "Config")
+            {
+                for (itemDevice = itemSSMCore->first_node(); itemDevice; itemDevice = itemDevice->next_sibling())
                 {
-                    ;/*NULL*/
+                    strKey = itemDevice->name();
+
+                    if (strKey == "SoftSensorRepository")
+                    {
+                        pathSoftSensors = itemDevice->value();
+                    }
+                    else if (strKey == "SoftSensorDescription")
+                    {
+                        pathDescription = itemDevice->value();
+                    }
+                    else
+                    {
+                        ;/*NULL*/
+                    }
                 }
             }
+            else
+            {
+                ;/*NULL*/
+            }
         }
-        else
-        {
-            ;/*NULL*/
-        }
+    }
+    catch (rapidxml::parse_error &e)
+    {
+        SSM_CLEANUP_ASSERT(SSM_E_INVALIDXML);
     }
 
-    SSM_CLEANUP_ASSERT(CreateGlobalInstance(OID_IContextRepository, (IBase **)&m_pContextRepository));
     SSM_CLEANUP_ASSERT(CreateGlobalInstance(OID_ISensingEngine, (IBase **)&m_pSensingEngine));
+    SSM_CLEANUP_ASSERT(m_pSensingEngine->queryInterface(OID_IContextRepository,
+                       (IBase **)&m_pContextRepository));
     SSM_CLEANUP_ASSERT(m_pContextRepository->initRepository(name, type, pathSoftSensors,
                        pathDescription));
 
@@ -137,14 +153,22 @@ CLEANUP:
 
 SSMRESULT CSoftSensorManager::startCore()
 {
-    //m_pSharingLayer->Start();
-    return SSM_S_OK;
+    SSMRESULT res = SSM_E_FAIL;
+
+    SSM_CLEANUP_ASSERT(m_pContextRepository->startResourceFinder());
+
+CLEANUP:
+    return res;
 }
 
 SSMRESULT CSoftSensorManager::stopCore()
 {
-    //m_pSharingLayer->Stop();
-    return SSM_S_OK;
+    SSMRESULT res = SSM_E_FAIL;
+
+    SSM_CLEANUP_ASSERT(m_pContextRepository->stopResourceFinder());
+
+CLEANUP:
+    return res;
 }
 
 SSMRESULT CSoftSensorManager::terminateCore(bool factoryResetFlag)
@@ -152,7 +176,7 @@ SSMRESULT CSoftSensorManager::terminateCore(bool factoryResetFlag)
     return SSM_S_OK;
 }
 
-SSMRESULT CSoftSensorManager::createQueryEngine(OUT IQueryEngine **ppQueryEngine)
+SSMRESULT CSoftSensorManager::createQueryEngine(IQueryEngine **ppQueryEngine)
 {
     SSMRESULT res = SSM_E_FAIL;
     IQueryEngineInternal    *pQueryEngineInternal = NULL;
@@ -163,7 +187,7 @@ CLEANUP:
     return res;
 }
 
-unsigned long CSoftSensorManager::releaseQueryEngine(IN IQueryEngine *pQueryEngine)
+unsigned long CSoftSensorManager::releaseQueryEngine(IQueryEngine *pQueryEngine)
 {
     IQueryEngineInternal    *pQueryEngineInternal = NULL;
     pQueryEngineInternal = (IQueryEngineInternal *)(CQueryEngine *)pQueryEngine;
@@ -171,7 +195,7 @@ unsigned long CSoftSensorManager::releaseQueryEngine(IN IQueryEngine *pQueryEngi
     return pQueryEngineInternal->release();
 }
 
-SSMRESULT CSoftSensorManager::getInstalledModelList(OUT std::vector<ISSMResource *> *pList)
+SSMRESULT CSoftSensorManager::getInstalledModelList(std::vector<ISSMResource *> *pList)
 {
     m_pSensingEngine->getList(pList);
 
@@ -182,7 +206,7 @@ CSimpleMutex                *g_mtxGlobalInstance = NULL;
 std::map<OID, IBase *>       *g_globalInstance = NULL;
 IThreadPool                 *g_pThreadPool = NULL;
 
-SSMRESULT CreateGlobalInstance(IN const OID &objectID, OUT IBase **ppvObject)
+SSMRESULT CreateGlobalInstance(const OID &objectID, IBase **ppvObject)
 {
     SSMRESULT res = SSM_E_NOINTERFACE;
 
@@ -271,7 +295,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CreateInstance(IN const OID &objectID, OUT IBase **ppObject)
+SSMRESULT CreateInstance(const OID &objectID, IBase **ppObject)
 {
     SSMRESULT res = SSM_E_NOINTERFACE;
 
index 8baa123..43fc8d3 100644 (file)
@@ -23,7 +23,6 @@
 #include "SSMInterface/SSMCore.h"
 #include "Common/PlatformLayer.h"
 #include "Common/InternalInterface.h"
-#include "Common/rapidxml.hpp"
 
 /**
 * @class    CSoftSensorManager
@@ -85,7 +84,7 @@ class CSoftSensorManager :
         * @exception
         * @see
         */
-        SSMRESULT initializeCore(IN std::string xmlDescription);
+        SSMRESULT initializeCore(std::string xmlDescription);
 
         /**
         * @fn startCore
@@ -124,7 +123,7 @@ class CSoftSensorManager :
         * @exception
         * @see
         */
-        SSMRESULT terminateCore(IN bool factoryResetFlag);
+        SSMRESULT terminateCore(bool factoryResetFlag);
 
         /**
         * @fn createQueryEngine
@@ -138,7 +137,7 @@ class CSoftSensorManager :
         * @exception
         * @see
         */
-        SSMRESULT createQueryEngine(OUT IQueryEngine **ppQueryEngine);
+        SSMRESULT createQueryEngine(IQueryEngine **ppQueryEngine);
 
         /**
         * @fn releaseQueryEngine
@@ -150,7 +149,7 @@ class CSoftSensorManager :
         * @exception
         * @see
         */
-        unsigned long releaseQueryEngine(IN IQueryEngine *pQueryEngine);
+        unsigned long releaseQueryEngine(IQueryEngine *pQueryEngine);
 
         /**
         * @fn getInstalledModelList
@@ -163,7 +162,7 @@ class CSoftSensorManager :
         * @exception
         * @see
         */
-        SSMRESULT getInstalledModelList(OUT std::vector<ISSMResource *> *pList);
+        SSMRESULT getInstalledModelList(std::vector<ISSMResource *> *pList);
 };
 
 #endif
index d043a43..b579987 100644 (file)
@@ -30,7 +30,7 @@ void CContextDataReader::finalRelease()
     m_pContextModelAccessor = NULL;
 }
 
-SSMRESULT CContextDataReader::registerContextModelAccessor(IN IContextModelAccessor
+SSMRESULT CContextDataReader::registerContextModelAccessor(IContextModelAccessor
         *pContextModelAccessor)
 {
     m_pContextModelAccessor = pContextModelAccessor;
@@ -38,8 +38,8 @@ SSMRESULT CContextDataReader::registerContextModelAccessor(IN IContextModelAcces
     return SSM_S_OK;
 }
 
-SSMRESULT CContextDataReader::getContextData(IN std::string modelName, IN int startIndex,
-        IN int count, OUT std::vector<ContextData> *data, OUT int *pLastIndex)
+SSMRESULT CContextDataReader::getContextData(std::string modelName, int startIndex,
+        int count, std::vector<ContextData> *data, int *pLastIndex)
 {
     SSMRESULT res = SSM_E_FAIL;
     std::vector<ModelPropertyVec>   modelDataSet;
index 97026d8..6e9d88a 100644 (file)
@@ -70,7 +70,7 @@ class CContextDataReader :
         * @exception
         * @see
         */
-        SSMRESULT registerContextModelAccessor(IN IContextModelAccessor *pContextModelAccessor);
+        SSMRESULT registerContextModelAccessor(IContextModelAccessor *pContextModelAccessor);
 
         /**
         * @fn     getContextData
@@ -87,7 +87,7 @@ class CContextDataReader :
         * @exception
         * @see
         */
-        SSMRESULT getContextData(IN std::string modelName, IN int startIndex, IN int count,
-                                 OUT std::vector<ContextData> *data, OUT int *pLastIndex);
+        SSMRESULT getContextData(std::string modelName, int startIndex, int count,
+                                 std::vector<ContextData> *data, int *pLastIndex);
 };
 #endif
index 668421f..e5f8078 100644 (file)
@@ -31,8 +31,6 @@ SSMRESULT CContextExecutor::finalConstruct()
 
     SSM_CLEANUP_ASSERT(m_pContextRepository->registerResourceFinderEvent(this));
 
-    SSM_CLEANUP_ASSERT(m_pContextRepository->startResourceFinder());
-
 CLEANUP:
     return res;
 }
@@ -148,7 +146,7 @@ void CContextExecutor::registerContext(TypeofEvent callType, ISSMResource *pSSMR
     }
 }
 
-void CContextExecutor::onExecute(IN void *pArg)
+void CContextExecutor::onExecute(void *pArg)
 {
     intptr_t         *pMessage = (intptr_t *)pArg;
 
@@ -189,7 +187,7 @@ void CContextExecutor::onExecute(IN void *pArg)
     }
 }
 
-void CContextExecutor::onTerminate(IN void *pArg)
+void CContextExecutor::onTerminate(void *pArg)
 {
     intptr_t         *pMessage = (intptr_t *)pArg;
 
@@ -294,9 +292,8 @@ int CContextExecutor::onEvent(std::string type, TypeofEvent callType,
             runLogic(inputData, softSensorName);
         }
     }
-    else //This data is primitive
+    else if (m_registeredResources.find(type) != m_registeredResources.end()) //This data is primitive
     {
-        //TODO: Temporally added for primitive data testing
         addOutput(ctxData);
     }
 
@@ -308,6 +305,10 @@ void  CContextExecutor::unregisterContext(TypeofEvent callType, ISSMResource *pS
 {
     std::vector<ISSMResource *> baseList;
 
+    //////////
+    ///TODO: Need to clean up m_mapResourceLookup list
+    //////////
+
     //This is primitive sensor
     if (pSSMResource->inputList.size() == 0)
     {
@@ -396,4 +397,4 @@ void CContextExecutor::runLogic(std::vector<ContextData> inputData, std::string
         m_ctxEventList[softSensor]->onCtxEvent(SPF_START, inputData);
     }
     m_mtxLibraryIO.unlock();
-}
\ No newline at end of file
+}
index 6b3a6c9..43ed198 100644 (file)
@@ -119,7 +119,7 @@ class CContextExecutor :
         * @exception
         * @see
         */
-        void registerCallback(IN ICtxEvent *pEvent);
+        void registerCallback(ICtxEvent *pEvent);
 
         /**
         * @fn           addOutput
@@ -133,7 +133,7 @@ class CContextExecutor :
         * @exception
         * @see
         */
-        void addOutput(IN std::vector<ContextData> contextData);
+        void addOutput(std::vector<ContextData> contextData);
 
         /**
         * @fn           getDataFromDatabase
@@ -151,8 +151,8 @@ class CContextExecutor :
         * @exception
         * @see
         */
-        void getDataFromDatabase(IN std::string modelName, IN int startIndex, IN int count,
-                                 OUT std::vector<ContextData> *data, OUT int *pLastIndex);
+        void getDataFromDatabase(std::string modelName, int startIndex, int count,
+                                 std::vector<ContextData> *data, int *pLastIndex);
 
         /**
         * @fn           onEvent
@@ -169,7 +169,7 @@ class CContextExecutor :
         * @exception
         * @see
         */
-        int onEvent(IN std::string deviceID, IN TypeofEvent callType, IN std::vector<ContextData> ctxData);
+        int onEvent(std::string deviceID, TypeofEvent callType, std::vector<ContextData> ctxData);
 
         /**
         * @fn           registerContext
@@ -185,7 +185,7 @@ class CContextExecutor :
         * @exception
         * @see
         */
-        void registerContext(IN TypeofEvent callType, IN ISSMResource *pSSMResouce, IN IEvent *pEvent);
+        void registerContext(TypeofEvent callType, ISSMResource *pSSMResouce, IEvent *pEvent);
 
         /**
         * @fn           unregisterContext
@@ -201,19 +201,19 @@ class CContextExecutor :
         * @exception
         * @see
         */
-        void  unregisterContext(IN TypeofEvent callType, IN ISSMResource *pSSMResource, IN IEvent *pEvent);
+        void  unregisterContext(TypeofEvent callType, ISSMResource *pSSMResource, IEvent *pEvent);
 
         void onExecute(void *pArg);
         void onTerminate(void *pArg);
-        int onResourceEvent(IN RESOURCE_EVENT_TYPE eventType, IN ISSMResource *pSSMResource,
-                            IN std::string info);
+        int onResourceEvent(RESOURCE_EVENT_TYPE eventType, ISSMResource *pSSMResource,
+                            std::string info);
 
     private:
-        SSMRESULT findString(IN std::vector<ISSMResource *> *sList, IN const std::string str,
-                             OUT ISSMResource **ppResource);
+        SSMRESULT findString(std::vector<ISSMResource *> *sList, const std::string str,
+                             ISSMResource **ppResource);
         std::map<std::string, std::vector<ContextData> >  getPreparedContextList(
-            IN std::string primitiveSensor);
-        void runLogic(IN std::vector<ContextData> inputData, IN std::string softSensor);
+            std::string primitiveSensor);
+        void runLogic(std::vector<ContextData> inputData, std::string softSensor);
 };
 
 #endif
index d4b133d..7e09d07 100644 (file)
@@ -18,6 +18,7 @@
 *
 ******************************************************************/
 #include "ContextRepository.h"
+#include "rapidxml/rapidxml.hpp"
 
 static inline std::string trim_both(const std::string &str)
 {
@@ -55,7 +56,17 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CContextRepository::registerResourceFinderEvent(IN IResourceEvent *pResourceEvent)
+SSMRESULT CContextRepository::stopResourceFinder()
+{
+    SSMRESULT res = SSM_E_FAIL;
+
+    SSM_CLEANUP_ASSERT(m_resourceFinder->stopResourceFinder());
+
+CLEANUP:
+    return res;
+}
+
+SSMRESULT CContextRepository::registerResourceFinderEvent(IResourceEvent *pResourceEvent)
 {
     m_resourceEvents.push_back(pResourceEvent);
     return SSM_S_OK;
@@ -65,8 +76,8 @@ void CContextRepository::finalRelease()
 {
 }
 
-SSMRESULT CContextRepository::initRepository(IN std::string name, IN std::string type,
-        IN std::string pathSoftSensors, IN std::string pathDescription)
+SSMRESULT CContextRepository::initRepository(std::string name, std::string type,
+        std::string pathSoftSensors, std::string pathDescription)
 {
     SSMRESULT res = SSM_E_FAIL;
 
@@ -77,7 +88,7 @@ SSMRESULT CContextRepository::initRepository(IN std::string name, IN std::string
 
     if (pathSoftSensors.length() == 0)
     {
-        SSM_CLEANUP_ASSERT(GetCurrentPath(&m_pathSoftSensors));
+        SSM_CLEANUP_ASSERT(getCurrentPath(&m_pathSoftSensors));
         m_pathSoftSensors.append("/");
     }
     else
@@ -87,7 +98,7 @@ SSMRESULT CContextRepository::initRepository(IN std::string name, IN std::string
 
     if (pathDescription.length() == 0)
     {
-        SSM_CLEANUP_ASSERT(GetCurrentPath(&m_pathSoftSensorsDescription));
+        SSM_CLEANUP_ASSERT(getCurrentPath(&m_pathSoftSensorsDescription));
         m_pathSoftSensorsDescription.append("/");
         m_pathSoftSensorsDescription.append(DEFAULT_PATH_SOFT_SENSORS);
     }
@@ -108,10 +119,9 @@ SSMRESULT CContextRepository::loadXMLFromString(char *xmlData,
         std::vector<DictionaryData> *dataList)
 {
     // use  rapidxml-----------------------
-    SSMRESULT res = SSM_E_FAIL;
+    SSMRESULT res = SSM_E_INVALIDXML;
     rapidxml::xml_document< char > xmlDoc;
     //xmlDoc.parse< 0 >( &xmlData.front() );
-    xmlDoc.parse< 0 >(xmlData);
 
     std::string keyStr;
     std::string valueStr;
@@ -121,73 +131,84 @@ SSMRESULT CContextRepository::loadXMLFromString(char *xmlData,
     rapidxml::xml_node< char > *subItem2;
     rapidxml::xml_node< char > *subItem3;
 
-    // get value
-    rapidxml::xml_node< char > *root = xmlDoc.first_node();
+    rapidxml::xml_node< char > *root;
 
-    if (!root)
+    try
     {
-        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
-    }
+        xmlDoc.parse< 0 >(xmlData);
 
-    for ( item = root->first_node(); item; item = item->next_sibling() )
-    {
-        DictionaryData dictionaryData;
-        for ( subItem = item->first_node(); subItem ; subItem = subItem->next_sibling() )
+        // get value
+        root = xmlDoc.first_node();
+
+        if (!root)
         {
-            //root name
-            keyStr = subItem->name();  // key
-            valueStr = subItem->value();   // value
+            throw rapidxml::parse_error("No Root Element", 0);
+        }
 
-            if (!keyStr.compare("name"))
-            {
-                dictionaryData.rootName = trim_both(valueStr);
-            }
-            ////std::cout<<keyStr << " : " << subItem->value() <<std::endl<<std::endl; //root_name
-            for (subItem2 = subItem->first_node(); subItem2 ; subItem2 = subItem2->next_sibling())
+        for (item = root->first_node(); item; item = item->next_sibling())
+        {
+            DictionaryData dictionaryData;
+            for (subItem = item->first_node(); subItem; subItem = subItem->next_sibling())
             {
-                std::map<std::string, std::string> propertyMap;
-                std::vector<std::string> enterconditionVector;
+                //root name
+                keyStr = subItem->name();  // key
+                valueStr = subItem->value();   // value
 
-                keyStr = subItem2->name();  // key
-                valueStr = subItem2->value();   // value
-
-                if (!keyStr.compare("input"))
+                if (!keyStr.compare("name"))
                 {
-                    dictionaryData.inputs.push_back(trim_both(valueStr));
+                    dictionaryData.rootName = trim_both(valueStr);
                 }
-                ////std::cout<<name << " :: " << subItem2->value() <<std::endl<<std::endl;
-                for (subItem3 = subItem2->first_node(); subItem3 ; subItem3 = subItem3->next_sibling())
+                ////std::cout<<keyStr << " : " << subItem->value() <<std::endl<<std::endl; //root_name
+                for (subItem2 = subItem->first_node(); subItem2; subItem2 = subItem2->next_sibling())
                 {
-                    std::string newKeyStr = subItem3->name();  // key
-                    valueStr = subItem3->value();   // value
+                    std::map<std::string, std::string> propertyMap;
+                    std::vector<std::string> enterconditionVector;
+
+                    keyStr = subItem2->name();  // key
+                    valueStr = subItem2->value();   // value
 
-                    if (!keyStr.compare("attribute") || !keyStr.compare("output") )
+                    if (!keyStr.compare("input"))
                     {
-                        propertyMap.insert(std::make_pair(trim_both(newKeyStr), trim_both(valueStr)));
+                        dictionaryData.inputs.push_back(trim_both(valueStr));
+                    }
+                    ////std::cout<<name << " :: " << subItem2->value() <<std::endl<<std::endl;
+                    for (subItem3 = subItem2->first_node(); subItem3; subItem3 = subItem3->next_sibling())
+                    {
+                        std::string newKeyStr = subItem3->name();  // key
+                        valueStr = subItem3->value();   // value
+
+                        if (!keyStr.compare("attribute") || !keyStr.compare("output"))
+                        {
+                            propertyMap.insert(std::make_pair(trim_both(newKeyStr), trim_both(valueStr)));
+                        }
+                    }
+                    if (!keyStr.compare("attribute"))
+                    {
+                        dictionaryData.attributeProperty.push_back(propertyMap);
+                    }
+                    else if (!keyStr.compare("output"))
+                    {
+                        dictionaryData.outputProperty.push_back(propertyMap);
                     }
-                }
-                if (!keyStr.compare("attribute"))
-                {
-                    dictionaryData.attributeProperty.push_back(propertyMap);
-                }
-                else if (!keyStr.compare("output"))
-                {
-                    dictionaryData.outputProperty.push_back(propertyMap);
                 }
             }
+            //for accurate data.
+            /*
+            dictionaryData.app_input_count = std::to_string((long long)dictionaryData.app_inputs.size());
+            dictionaryData.input_count = std::to_string((long long)dictionaryData.inputs.size());
+            dictionaryData.attribute_property_count = std::to_string((long long)dictionaryData.attribute_property.size());
+            dictionaryData.output_property_count = std::to_string((long long)dictionaryData.output_property.size());
+            */
+
+            dataList->push_back(dictionaryData);
         }
-        //for accurate data.
-        /*
-        dictionaryData.app_input_count = std::to_string((long long)dictionaryData.app_inputs.size());
-        dictionaryData.input_count = std::to_string((long long)dictionaryData.inputs.size());
-        dictionaryData.attribute_property_count = std::to_string((long long)dictionaryData.attribute_property.size());
-        dictionaryData.output_property_count = std::to_string((long long)dictionaryData.output_property.size());
-        */
-
-        dataList->push_back(dictionaryData);
-    }
 
-    res = SSM_S_OK;
+        res = SSM_S_OK;
+    }
+    catch (rapidxml::parse_error &e)
+    {
+        SSM_CLEANUP_ASSERT(SSM_E_INVALIDXML);
+    }
 
 CLEANUP:
     return res;
@@ -223,7 +244,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CContextRepository::getSoftSensorList(OUT std::vector<ISSMResource *> *pSoftSensorList)
+SSMRESULT CContextRepository::getSoftSensorList(std::vector<ISSMResource *> *pSoftSensorList)
 {
     for (size_t i = 0; i < m_lstSoftSensor.size(); i++)
     {
@@ -233,7 +254,7 @@ SSMRESULT CContextRepository::getSoftSensorList(OUT std::vector<ISSMResource *>
     return SSM_S_OK;
 }
 
-SSMRESULT CContextRepository::getPrimitiveSensorList(OUT std::vector<ISSMResource *>
+SSMRESULT CContextRepository::getPrimitiveSensorList(std::vector<ISSMResource *>
         *pPrimitiveSensorList)
 {
     for (size_t i = 0; i < m_lstPrimitiveSensor.size(); i++)
@@ -244,7 +265,7 @@ SSMRESULT CContextRepository::getPrimitiveSensorList(OUT std::vector<ISSMResourc
     return SSM_S_OK;
 }
 
-SSMRESULT CContextRepository::onResourceFound(IN ISSMResource *pSensor)
+SSMRESULT CContextRepository::onResourceFound(ISSMResource *pSensor)
 {
     m_lstPrimitiveSensor.push_back(pSensor);
 
@@ -256,7 +277,7 @@ SSMRESULT CContextRepository::onResourceFound(IN ISSMResource *pSensor)
     return SSM_S_OK;
 }
 
-SSMRESULT CContextRepository::onResourceLost(IN ISSMResource *pSensor)
+SSMRESULT CContextRepository::onResourceLost(ISSMResource *pSensor)
 {
     std::vector<ISSMResource *>::iterator    itor;
     itor = std::find(m_lstPrimitiveSensor.begin(), m_lstPrimitiveSensor.end(), pSensor);
@@ -270,12 +291,12 @@ SSMRESULT CContextRepository::onResourceLost(IN ISSMResource *pSensor)
     return SSM_E_FAIL;
 }
 
-SSMRESULT CContextRepository::startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent)
+SSMRESULT CContextRepository::startObserveResource(ISSMResource *pSensor, IEvent *pEvent)
 {
     return m_resourceFinder->startObserveResource(pSensor, pEvent);
 }
 
-SSMRESULT CContextRepository::stopObserveResource(IN ISSMResource *pSensor)
+SSMRESULT CContextRepository::stopObserveResource(ISSMResource *pSensor)
 {
     return m_resourceFinder->stopObserveResource(pSensor);
 }
@@ -318,7 +339,7 @@ SSMRESULT CContextRepository::loadSoftSensor(std::string softSensorName, ICtxDel
     std::stringstream   sstream;
     SSMRESULT           res = SSM_E_FAIL;
 
-    typedef void(*InitContext)(IN ICtxDelegate *);
+    typedef void(*InitContext)(ICtxDelegate *);
     InitContext InitializeContextFunction = NULL;
 
     // load dll(so)
@@ -384,7 +405,7 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CContextRepository::GetCurrentPath(std::string *path)
+SSMRESULT CContextRepository::getCurrentPath(std::string *path)
 {
     char        buffer[2048];
     SSMRESULT   res = SSM_E_FAIL;
@@ -428,4 +449,4 @@ SSMRESULT CContextRepository::GetCurrentPath(std::string *path)
 
 CLEANUP:
     return res;
-}
\ No newline at end of file
+}
index d3e13e3..ec9aabd 100644 (file)
@@ -23,8 +23,6 @@
 #include "SSMInterface/SSMCore.h"
 #include "Common/PlatformLayer.h"
 #include "Common/InternalInterface.h"
-#include "Common/rapidxml.hpp"
-#include "Common/rapidxml_print.hpp"
 #include "ResourceFinder.h"
 
 /**
@@ -86,8 +84,8 @@ class CContextRepository :
         * @exception
         * @see
         */
-        SSMRESULT initRepository(IN std::string name, IN std::string type, IN std::string pathSoftSensors,
-                                 IN std::string pathDescription);
+        SSMRESULT initRepository(std::string name, std::string type, std::string pathSoftSensors,
+                                 std::string pathDescription);
 
         /**
         * @fn           getSoftSensorList
@@ -107,7 +105,7 @@ class CContextRepository :
         * @exception
         * @see
         */
-        SSMRESULT getSoftSensorList(OUT std::vector<ISSMResource *> *pSoftSensorList);
+        SSMRESULT getSoftSensorList(std::vector<ISSMResource *> *pSoftSensorList);
 
         /**
         * @fn           getPrimitiveSensorList
@@ -127,26 +125,27 @@ class CContextRepository :
         * @exception
         * @see
         */
-        SSMRESULT getPrimitiveSensorList(OUT std::vector<ISSMResource *> *pPrimitiveSensorList);
+        SSMRESULT getPrimitiveSensorList(std::vector<ISSMResource *> *pPrimitiveSensorList);
 
-        SSMRESULT registerResourceFinderEvent(IN IResourceEvent *pResourceEvent);
+        SSMRESULT registerResourceFinderEvent(IResourceEvent *pResourceEvent);
         SSMRESULT startResourceFinder();
-        SSMRESULT onResourceFound(IN ISSMResource *pSensor);
-        SSMRESULT onResourceLost(IN ISSMResource *pSensor);
+        SSMRESULT stopResourceFinder();
+        SSMRESULT onResourceFound(ISSMResource *pSensor);
+        SSMRESULT onResourceLost(ISSMResource *pSensor);
 
-        SSMRESULT startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent);
-        SSMRESULT stopObserveResource(IN ISSMResource *pSensor);
+        SSMRESULT startObserveResource(ISSMResource *pSensor, IEvent *pEvent);
+        SSMRESULT stopObserveResource(ISSMResource *pSensor);
 
-        SSMRESULT loadSoftSensor(IN std::string softSensorName, IN ICtxDelegate *pDelegate,
-                                 OUT void **hSoftSensor);
-        SSMRESULT unloadSoftSensor(IN void *hSoftSensor);
+        SSMRESULT loadSoftSensor(std::string softSensorName, ICtxDelegate *pDelegate,
+                                 void **hSoftSensor);
+        SSMRESULT unloadSoftSensor(void *hSoftSensor);
 
     private:
-        SSMRESULT makeSSMResourceListForDictionaryData(IN std::vector<DictionaryData> dataList,
-                OUT std::vector<ISSMResource *> *pList) ;
-        SSMRESULT loadXMLFromFile(IN std::string descriptionFilePath,
-                                  IN std::vector<DictionaryData> *dataList);
-        SSMRESULT loadXMLFromString(IN char *xmlData, IN std::vector<DictionaryData> *dataList);
-        SSMRESULT GetCurrentPath(OUT std::string *path);
+        SSMRESULT makeSSMResourceListForDictionaryData(std::vector<DictionaryData> dataList,
+                std::vector<ISSMResource *> *pList) ;
+        SSMRESULT loadXMLFromFile(std::string descriptionFilePath,
+                                  std::vector<DictionaryData> *dataList);
+        SSMRESULT loadXMLFromString(char *xmlData, std::vector<DictionaryData> *dataList);
+        SSMRESULT getCurrentPath(std::string *path);
 };
-#endif
\ No newline at end of file
+#endif
index 57dbe2c..7541ee7 100644 (file)
@@ -32,6 +32,8 @@ SSMRESULT CResourceFinder::finalConstruct()
 
     m_pResourceFinderEvent = NULL;
 
+    m_multicastPresenceHandle = nullptr;
+
 CLEANUP:
     return res;
 }
@@ -40,7 +42,7 @@ void CResourceFinder::finalRelease()
 {
 }
 
-SSMRESULT CResourceFinder::registerResourceFinderEvent(IN IResourceFinderEvent *pEvent)
+SSMRESULT CResourceFinder::registerResourceFinderEvent(IResourceFinderEvent *pEvent)
 {
     m_pResourceFinderEvent = pEvent;
     return SSM_S_OK;
@@ -59,8 +61,6 @@ void CResourceFinder::onResourceFound(std::shared_ptr< OC::OCResource > resource
         pMessage[0] = RESOURCE_DISCOVER_REQUESTPROFILE;
         pMessage[1] = reinterpret_cast<intptr_t> (new  std::shared_ptr<OC::OCResource>(resource));
 
-        std::cout << "Resource Found !! >> " << path << std::endl;
-
         m_pTasker->addTask(this, pMessage);
     }
 }
@@ -71,12 +71,14 @@ void CResourceFinder::presenceHandler(OCStackResult result, const unsigned int n
     SSMRESULT res = SSM_E_FAIL;
     OCStackResult ret = OC_STACK_ERROR;
     intptr_t *pMessage = NULL;
+    std::ostringstream requestURI;
 
     switch (result)
     {
         case OC_STACK_OK:
-            ret = OC::OCPlatform::findResource("",
-                                               "coap://" + hostAddress + "/oc/core?rt=SoftSensorManager.Sensor",
+            requestURI << "coap://" << hostAddress << "/oc/core?rt=SSManager.Sensor";
+
+            ret = OC::OCPlatform::findResource("", requestURI.str(), OC_ALL,
                                                std::bind(&CResourceFinder::onResourceFound, this, std::placeholders::_1));
 
             if (ret != OC_STACK_OK)
@@ -85,7 +87,6 @@ void CResourceFinder::presenceHandler(OCStackResult result, const unsigned int n
             break;
 
         case OC_STACK_PRESENCE_STOPPED:
-        case OC_STACK_PRESENCE_TIMEOUT:
             if (m_mapResources.find(hostAddress) != m_mapResources.end())
             {
                 while (!m_mapResources[hostAddress].empty())
@@ -101,6 +102,9 @@ void CResourceFinder::presenceHandler(OCStackResult result, const unsigned int n
             }
             break;
 
+        case OC_STACK_PRESENCE_TIMEOUT:
+            break;
+
         case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
             break;
 
@@ -117,18 +121,21 @@ SSMRESULT CResourceFinder::startResourceFinder()
     SSMRESULT res = SSM_E_FAIL;
     OCStackResult ret = OC_STACK_ERROR;
 
-    OC::OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+    std::ostringstream requestURI;
+    requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=SSManager.Sensor";
 
-    ret = OC::OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=SoftSensorManager.Sensor",
+    std::ostringstream multicastPresenceURI;
+    multicastPresenceURI << "coap://" << OC_MULTICAST_PREFIX;
+
+    ret = OC::OCPlatform::findResource("", requestURI.str(), OC_ALL,
                                        std::bind(&CResourceFinder::onResourceFound, this, std::placeholders::_1));
 
     if (ret != OC_STACK_OK)
         SSM_CLEANUP_ASSERT(SSM_E_FAIL);
 
-    ret = OC::OCPlatform::subscribePresence(presenceHandle, "coap://224.0.1.187",
-                                            "SoftSensorManager.Sensor",
-                                            std::bind(&CResourceFinder::presenceHandler, this, std::placeholders::_1,
-                                                    std::placeholders::_2, std::placeholders::_3));
+    ret = OC::OCPlatform::subscribePresence(m_multicastPresenceHandle, multicastPresenceURI.str(),
+                                            "SSManager.Sensor", OC_ALL, std::bind(&CResourceFinder::presenceHandler, this,
+                                                    std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
 
     if (ret != OC_STACK_OK)
         SSM_CLEANUP_ASSERT(SSM_E_FAIL);
@@ -139,23 +146,41 @@ CLEANUP:
     return res;
 }
 
-SSMRESULT CResourceFinder::startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent)
+SSMRESULT CResourceFinder::stopResourceFinder()
+{
+    SSMRESULT res = SSM_E_FAIL;
+    OCStackResult ret = OC_STACK_ERROR;
+
+    ret = OC::OCPlatform::unsubscribePresence(m_multicastPresenceHandle);
+
+    if (ret != OC_STACK_OK)
+        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+
+    m_multicastPresenceHandle = nullptr;
+
+    res = SSM_S_OK;
+
+CLEANUP:
+    return res;
+}
+
+SSMRESULT CResourceFinder::startObserveResource(ISSMResource *pSensor, IEvent *pEvent)
 {
     return m_mapResourceHandler[pSensor->name]->startObserve(pEvent);
 }
 
-SSMRESULT CResourceFinder::stopObserveResource(IN ISSMResource *pSensor)
+SSMRESULT CResourceFinder::stopObserveResource(ISSMResource *pSensor)
 {
     return m_mapResourceHandler[pSensor->name]->stopObserve();
 }
 
-void CResourceFinder::onExecute(IN void *pArg)
+void CResourceFinder::onExecute(void *pArg)
 {
     SSMRESULT res = SSM_E_FAIL;
     OCStackResult ret = OC_STACK_ERROR;
     OC::QueryParamsMap queryParams;
     OICResourceHandler *pResourceHandler = NULL;
-    intptr_t                 *pMessage =  reinterpret_cast<intptr_t *>(pArg);
+    intptr_t                 *pMessage = reinterpret_cast<intptr_t *>(pArg);
     std::shared_ptr< OC::OCResource > *pResource = NULL;
     OC::OCPlatform::OCPresenceHandle presenceHandle = NULL;
 
@@ -178,9 +203,8 @@ void CResourceFinder::onExecute(IN void *pArg)
 
             m_mapResources[resourceHostAddress].push_back(resourceFullPath);
 
-            ret = pResource->get()->get(queryParams,
-                                        std::bind(&OICResourceHandler::onGetResourceProfile, pResourceHandler,
-                                                  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
+            ret = pResource->get()->get(queryParams, std::bind(&OICResourceHandler::onGetResourceProfile,
+                                        pResourceHandler, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
 
             if (ret != OC_STACK_OK)
                 SSM_CLEANUP_ASSERT(SSM_E_FAIL);
@@ -192,9 +216,8 @@ void CResourceFinder::onExecute(IN void *pArg)
                 m_mapResourcePresenceHandles.end())
             {
                 ret = OC::OCPlatform::subscribePresence(presenceHandle, ((ISSMResource *)pMessage[1])->ip,
-                                                        "SoftSensorManager.Sensor",
-                                                        std::bind(&CResourceFinder::presenceHandler, this, std::placeholders::_1,
-                                                                std::placeholders::_2, std::placeholders::_3));
+                                                        "SSManager.Sensor", OC_ALL, std::bind(&CResourceFinder::presenceHandler, this,
+                                                                std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
 
                 if (ret != OC_STACK_OK)
                     SSM_CLEANUP_ASSERT(SSM_E_FAIL);
@@ -202,7 +225,11 @@ void CResourceFinder::onExecute(IN void *pArg)
                 m_mapResourcePresenceHandles[((ISSMResource *)pMessage[1])->ip] = presenceHandle;
             }
 
-            m_pResourceFinderEvent->onResourceFound((ISSMResource *) pMessage[1]);
+            m_pResourceFinderEvent->onResourceFound((ISSMResource *)pMessage[1]);
+
+            if (ret != OC_STACK_OK)
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+
             break;
 
         case RESOURCE_DISCOVER_UNINSTALL_RESOURCE:
@@ -211,8 +238,8 @@ void CResourceFinder::onExecute(IN void *pArg)
             if (m_mapResourcePresenceHandles.find(((OICResourceHandler *)pMessage[1])->m_SSMResource.ip) !=
                 m_mapResourcePresenceHandles.end())
             {
-                ret = OC::OCPlatform::unsubscribePresence(
-                          m_mapResourcePresenceHandles[((OICResourceHandler *)pMessage[1])->m_SSMResource.ip]);
+                ret = OC::OCPlatform::unsubscribePresence(m_mapResourcePresenceHandles[((
+                            OICResourceHandler *)pMessage[1])->m_SSMResource.ip]);
 
                 if (ret != OC_STACK_OK)
                     SSM_CLEANUP_ASSERT(SSM_E_FAIL);
@@ -220,6 +247,7 @@ void CResourceFinder::onExecute(IN void *pArg)
                 m_mapResourcePresenceHandles.erase(((OICResourceHandler *)pMessage[1])->m_SSMResource.ip);
             }
 
+            delete m_mapResourceHandler[((OICResourceHandler *)pMessage[1])->m_SSMResource.name];
             m_mapResourceHandler.erase(((OICResourceHandler *) pMessage[1])->m_SSMResource.name);
             break;
     }
@@ -228,7 +256,7 @@ CLEANUP:
     ;
 }
 
-void CResourceFinder::onTerminate(IN void *pArg)
+void CResourceFinder::onTerminate(void *pArg)
 {
     std::shared_ptr< OC::OCResource > *pResource = NULL;
     intptr_t *pMessage = (intptr_t *)pArg;
index 1ad2ccf..d9ea15f 100644 (file)
@@ -50,17 +50,18 @@ class CResourceFinder: public CObjectRoot< CObjectMultiThreadModel >,
         SSMRESULT finalConstruct();
         void finalRelease();
 
-        SSMRESULT registerResourceFinderEvent(IN IResourceFinderEvent *pEvent);
+        SSMRESULT registerResourceFinderEvent(IResourceFinderEvent *pEvent);
         void onResourceFound(std::shared_ptr< OC::OCResource > resource);
         void presenceHandler(OCStackResult result, const unsigned int nonce,
                              const std::string &hostAddress);
         SSMRESULT startResourceFinder();
+        SSMRESULT stopResourceFinder();
 
-        SSMRESULT startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent);
-        SSMRESULT stopObserveResource(IN ISSMResource *pSensor);
+        SSMRESULT startObserveResource(ISSMResource *pSensor, IEvent *pEvent);
+        SSMRESULT stopObserveResource(ISSMResource *pSensor);
 
-        void onExecute(IN void *pArg);
-        void onTerminate(IN void *pArg);
+        void onExecute(void *pArg);
+        void onTerminate(void *pArg);
 
     private:
         class OICResourceHandler
@@ -75,7 +76,7 @@ class CResourceFinder: public CObjectRoot< CObjectMultiThreadModel >,
                 }
 
                 SSMRESULT initHandler(std::shared_ptr< OC::OCResource > resource,
-                                      IN IThreadClient *pThreadClient)
+                                      IThreadClient *pThreadClient)
                 {
                     SSMRESULT res = SSM_E_FAIL;
 
@@ -201,8 +202,10 @@ CLEANUP: return res;
             RESOURCE_DISCOVER_INSTALL_RESOURCE,
             RESOURCE_DISCOVER_UNINSTALL_RESOURCE
         };
+
         IResourceFinderEvent *m_pResourceFinderEvent;
         CObjectPtr< ITasker > m_pTasker;
+        OC::OCPlatform::OCPresenceHandle m_multicastPresenceHandle;
         std::map< std::string, OICResourceHandler * > m_mapResourceHandler;
         std::map< std::string, std::vector<std::string> >
         m_mapResources;    // <hostaddress, std::vector<resources> >
index 7f6827a..bfd6f3c 100644 (file)
@@ -68,6 +68,13 @@ class CSensingEngine :
                 *ppObject = pBase;
                 return SSM_S_OK;
             }
+            else if (IsEqualOID(objectID, OID_IContextRepository))
+            {
+                IBase *pBase = this;
+                pBase->addRef();
+                *ppObject = m_pContextRepository;
+                return SSM_S_OK;
+            }
 
             return SSM_E_NOINTERFACE;
         }
@@ -86,8 +93,8 @@ class CSensingEngine :
         * @exception
         * @see
         */
-        SSMRESULT registerContext(IN TypeofEvent callType, IN ISSMResource *pSSMResource,
-                                  IN IEvent *pEvent);
+        SSMRESULT registerContext(TypeofEvent callType, ISSMResource *pSSMResource,
+                                  IEvent *pEvent);
 
         /**
         * @fn           unregisterContext
@@ -103,8 +110,8 @@ class CSensingEngine :
         * @exception
         * @see
         */
-        SSMRESULT  unregisterContext(IN TypeofEvent callType, IN ISSMResource *pSSMResource,
-                                     IN IEvent *pEvent);
+        SSMRESULT  unregisterContext(TypeofEvent callType, ISSMResource *pSSMResource,
+                                     IEvent *pEvent);
 
         /**
         * @fn           getList
@@ -118,7 +125,7 @@ class CSensingEngine :
         * @exception
         * @see
         */
-        SSMRESULT getList(OUT std::vector<ISSMResource *> *pList);
+        SSMRESULT getList(std::vector<ISSMResource *> *pList);
 
         /**
         * @fn           onEvent
@@ -135,6 +142,6 @@ class CSensingEngine :
         * @exception
         * @see
         */
-        int onEvent(IN std::string name, IN TypeofEvent callType, IN std::vector<ContextData> ctxData);
+        int onEvent(std::string name, TypeofEvent callType, std::vector<ContextData> ctxData);
 };
 #endif
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/Readme_ITScenario.txt b/service/soft-sensor-manager/SampleApp/Readme_ITScenario.txt
new file mode 100644 (file)
index 0000000..094ddf4
--- /dev/null
@@ -0,0 +1,45 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+===============================================================================
+==                What is Indoor Trajectory Scenario                         ==
+===============================================================================
+
+Here we prepare Indoor Trajectory Sample for Soft Sensor Manager.
+
+There are 2 main components and 1 sub module to show how Indoor Trajectory works.
+
+1. Reference Thing is Arduino application that shold be deployed at somewhere
+
+   which should working as signal beacon.
+
+2. Indoor Trajectory Sensor is the soft sensor for tizen platform that 
+   
+   checks the RSSI signal between reference thing and tizen platform using
+
+   tizen BLE api.
+
+3. Trackee_Thing is sub sensor which almost same behavior as Indoor Trajector Sensor
+  
+   which not only belongs to tizen platform. This also can check the RSSI for 
+
+   checking distance and send its measurements to other device using iotivity protocol.
+
+   So you can also get the measurement without using tizen BLE api.
\ No newline at end of file
index 545d993..1563346 100644 (file)
@@ -22,3 +22,8 @@ if target_os == 'linux' :
        SConscript('linux/SSMTesterApp/SConscript')
        SConscript('linux/THSensorApp/SConscript')
        SConscript('linux/THSensorApp1/SConscript')
+       SConscript('linux/HeightSensorApp/SConscript')
+       SConscript('linux/WeightSensorApp/SConscript')
+
+
+
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/AndroidManifest.xml b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..56e20ee
--- /dev/null
@@ -0,0 +1,45 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.iotivity.service.ssm"
+    android:versionCode="1"
+    android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="15" />
+    
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
+       <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
+       <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+       <uses-permission android:name="android.permission.CALL_PHONE" />  
+       <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
+       <uses-permission android:name="android.permission.READ_CONTACTS"/> 
+       <uses-permission android:name="android.permission.INTERNET"/>
+       <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+       <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
+       <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
+       <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
+       <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>    
+       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+       <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
+       <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
+       <uses-permission android:name="android.permission.READ_CALENDAR" />
+    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
+
+    <application android:label="@string/app_name"
+        android:icon="@drawable/ic_launcher"
+        android:theme="@style/AppTheme"
+        android:allowBackup="true" 
+        android:debuggable="true">
+       
+               <activity
+            android:name="org.iotivity.service.ssm.sample.MainActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>            
+    </application>
+
+</manifest>
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/jni/Android.mk b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/jni/Android.mk
new file mode 100644 (file)
index 0000000..3910a38
--- /dev/null
@@ -0,0 +1,26 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := coap
+LOCAL_SRC_FILES := ../libs/libcoap.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc_logger
+LOCAL_SRC_FILES := ../libs/liboc_logger.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := octbstack
+LOCAL_SRC_FILES := ../libs/liboctbstack.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := oc
+LOCAL_SRC_FILES := ../libs/liboc.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := SSMCore
+LOCAL_SRC_FILES := ../libs/libSSMCore.so
+include $(PREBUILT_SHARED_LIBRARY)
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/jni/Application.mk b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/jni/Application.mk
new file mode 100644 (file)
index 0000000..4ffecf6
--- /dev/null
@@ -0,0 +1,2 @@
+APP_STL:=gnustl_shared
+NDK_TOOLCHAIN_VERSION := 4.9
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_action_search.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_action_search.png
new file mode 100644 (file)
index 0000000..67de12d
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_action_search.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_launcher.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..a301d57
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-hdpi/ic_launcher.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_action_search.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_action_search.png
new file mode 100644 (file)
index 0000000..67de12d
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_action_search.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_launcher.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..2c2a58b
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-ldpi/ic_launcher.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_action_search.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_action_search.png
new file mode 100644 (file)
index 0000000..67de12d
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_action_search.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_launcher.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..f91f736
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-mdpi/ic_launcher.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_action_search.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_action_search.png
new file mode 100644 (file)
index 0000000..67de12d
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_action_search.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_launcher.png b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..96095ec
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/layout/activity_main.xml b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..fa54a1b
--- /dev/null
@@ -0,0 +1,184 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical"
+    android:paddingBottom="5dp"
+    android:paddingLeft="10dp"
+    android:paddingRight="10dp"
+    android:paddingTop="10dp" >
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content" >
+
+        <EditText
+            android:id="@+id/editQuery"
+            android:layout_width="wrap_content"
+            android:layout_height="110dp"
+            android:layout_weight="0.92"
+            android:ems="9"
+            android:inputType="textMultiLine"
+            android:text=""
+            android:textSize="15sp" />
+
+        <LinearLayout
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"
+            android:layout_weight="0.92"
+            android:orientation="vertical" >
+
+            <Button
+                android:id="@+id/btnRegisterQuery"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:text="Register"
+                android:textSize="18sp" />
+
+            <Button
+                android:id="@+id/btClear"
+                style="?android:attr/buttonStyleSmall"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:text="CLEAR"
+                android:textSize="18sp" />
+                    
+        </LinearLayout>
+
+    </LinearLayout>
+
+       <LinearLayout
+               android:layout_width="match_parent"
+               android:layout_height="wrap_content"
+               android:orientation="vertical"
+               android:paddingTop="10dp" >
+
+               <TextView
+                   android:id="@+id/textView"
+                   android:layout_width="wrap_content"
+                   android:layout_height="wrap_content"
+                   android:text="Example Queries"
+                   android:textSize="15sp"
+                   android:textStyle="bold" />
+          
+               <LinearLayout
+                       android:layout_width="match_parent"
+                       android:layout_height="wrap_content" >
+
+               <Button
+                   android:id="@+id/btFullDevice"
+                   style="?android:attr/buttonStyleSmall"
+                   android:layout_width="wrap_content"
+                   android:layout_height="wrap_content"
+                   android:text="Search Devices"
+                   android:textSize="17sp" />
+       
+                <Button
+                    android:id="@+id/btDiscomfortIndex"
+                    style="?android:attr/buttonStyleSmall"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="DiscomfortIndex"
+                    android:textSize="17sp" />
+
+               </LinearLayout>
+               
+       </LinearLayout>
+
+       <LinearLayout
+               android:layout_width="match_parent"
+               android:layout_height="wrap_content"
+               android:orientation="vertical"
+               android:paddingTop="10dp" >
+
+               <TextView
+                   android:id="@+id/textView2"
+                   android:layout_width="wrap_content"
+                   android:layout_height="wrap_content"
+                   android:text="Unregister Query"
+                   android:textSize="15sp"
+                   android:textStyle="bold" />
+               
+               <LinearLayout
+                   android:layout_width="match_parent"
+                   android:layout_height="wrap_content" >
+               
+                   <Button
+                       android:id="@+id/btMinus"
+                       style="?android:attr/buttonStyleSmall"
+                       android:layout_width="wrap_content"
+                       android:layout_height="wrap_content"
+                       android:text=" - "
+                       android:textSize="18sp" />
+               
+                   <EditText
+                       android:id="@+id/editUnregisterQuery"
+                       android:layout_width="90dp"
+                       android:layout_height="wrap_content"
+                       android:text="0"
+                       android:textSize="18sp" />
+                               
+                   <Button
+                       android:id="@+id/btPlus"
+                       style="?android:attr/buttonStyleSmall"
+                       android:layout_width="wrap_content"
+                       android:layout_height="wrap_content"
+                       android:text=" + "
+                       android:textSize="18sp" />
+               
+                   <Button
+                       android:id="@+id/btnUnregisterQuery"
+                       android:layout_width="wrap_content"
+                       android:layout_height="wrap_content"
+                       android:text="UnRegister"
+                       android:textSize="18sp" />
+               
+               </LinearLayout>
+
+       </LinearLayout>
+
+       <Space
+               android:layout_width="match_parent"
+               android:layout_height="10dp" />
+
+       <LinearLayout
+           android:layout_width="match_parent"
+           android:layout_height="5dp"
+           android:orientation="vertical"
+           android:background="#111111" >
+       </LinearLayout>
+
+       <Space
+           android:layout_width="match_parent"
+           android:layout_height="5dp" />
+      
+       <LinearLayout
+           android:layout_width="match_parent"
+           android:layout_height="wrap_content"
+           android:orientation="vertical"
+           android:paddingTop="0dp" >
+
+               <Button
+                   android:id="@+id/btLogClear"
+                   android:layout_width="match_parent"
+                   android:layout_height="wrap_content"
+                   android:text="CLEAR LOG"
+                   android:textSize="18sp" />
+
+               <ScrollView
+                   android:id="@+id/sclLog"
+                   android:layout_width="match_parent"
+                   android:layout_height="match_parent" >
+                       
+                       <TextView
+                           android:id="@+id/txtLog"
+                           android:layout_width="match_parent"
+                           android:layout_height="match_parent"
+                           android:layout_alignParentBottom="true"
+                           android:layout_alignParentLeft="true"
+                           android:textSize="15sp" />
+          
+               </ScrollView>
+       
+       </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/menu/activity_main.xml b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/menu/activity_main.xml
new file mode 100644 (file)
index 0000000..cfc10fd
--- /dev/null
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:id="@+id/menu_settings"
+        android:title="@string/menu_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never" />
+</menu>
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values-v11/styles.xml b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..d408cbc
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light" />
+
+</resources>
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values-v14/styles.xml b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..1c089a7
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+
+</resources>
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values/strings.xml b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values/strings.xml
new file mode 100644 (file)
index 0000000..b96a3ca
--- /dev/null
@@ -0,0 +1,7 @@
+<resources>
+
+    <string name="app_name">SSM Sample App</string>    
+    <string name="menu_settings">Settings</string>
+    <string name="title_activity_main">MainActivity</string>
+
+</resources>
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values/styles.xml b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/res/values/styles.xml
new file mode 100644 (file)
index 0000000..4dba0d0
--- /dev/null
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Light" />
+
+</resources>
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/src/org/iotivity/service/ssm/sample/MainActivity.java b/service/soft-sensor-manager/SampleApp/android/SSMTesterApp/src/org/iotivity/service/ssm/sample/MainActivity.java
new file mode 100644 (file)
index 0000000..7a4c12d
--- /dev/null
@@ -0,0 +1,368 @@
+package org.iotivity.service.ssm.sample;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.UUID;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.service.ssm.DataReader;
+import org.iotivity.service.ssm.IQueryEngineEvent;
+import org.iotivity.service.ssm.ModelData;
+import org.iotivity.service.ssm.R;
+import org.iotivity.service.ssm.SSMInterface;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.Editor;
+import android.content.res.AssetManager;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+import android.view.View;
+import android.widget.EditText;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+public class MainActivity extends Activity {
+
+    private SSMInterface       SoftSensorManager         = null;
+    private ArrayList<Integer> mRunningQueries           = new ArrayList<Integer>();
+
+    private IQueryEngineEvent  mQueryEngineEventListener = null;
+    private final String         LOG_TAG = this.getClass().getSimpleName();
+    private static MainActivity  activityObj;
+
+    void PrintLog(String log) {
+        Message msg = new Message();
+        Bundle data = new Bundle();
+        data.putString("Log", log);
+        msg.setData(data);
+        logHandler.sendMessage(msg);
+    }
+
+    private Handler      logHandler         = new Handler() {
+                                                @Override
+                                                public void handleMessage(
+                                                        Message msg) {
+                                                    tvLog.append(msg.getData()
+                                                            .getString("Log")
+                                                            + "\n");
+                                                    svLog.fullScroll(ScrollView.FOCUS_DOWN);
+                                                }
+                                            };
+
+    private TextView     tvLog              = null;
+    private ScrollView   svLog              = null;
+    private EditText     edtQuery           = null;
+    private EditText     edtUnregisterQuery = null;
+
+    View.OnClickListener clickHandler       = null;
+
+    View.OnClickListener textAddHandler     = null;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+
+        tvLog = (TextView) findViewById(R.id.txtLog);
+        svLog = (ScrollView) findViewById(R.id.sclLog);
+        edtQuery = (EditText) findViewById(R.id.editQuery);
+        edtUnregisterQuery = (EditText) findViewById(R.id.editUnregisterQuery);
+        
+        // calling the method to check the Wi-fi connectivity and configuring
+        // the OcPlatform
+        configurePlatform();
+
+        mQueryEngineEventListener = new IQueryEngineEvent() {
+            @Override
+            public void onQueryEngineEvent(int cqid, DataReader result) {
+                Log.i("[SSM]", "event received! cqid=" + cqid);
+                PrintLog("Event from cqid " + cqid + " has received");
+
+                List<String> models = result.getAffectedModels();
+
+                for (String modelName : models) {
+                    PrintLog("Model: " + modelName);
+
+                    try {
+                        int dataCount = result.getModelDataCount(modelName);
+
+                        for (int i = 0; i < dataCount; i++) {
+                            ModelData modelData = result.getModelData(
+                                    modelName, i);
+
+                            for (int j = 0; j < modelData.getPropertyCount(); j++) {
+                                PrintLog("Name: "
+                                        + modelData.getPropertyName(j)
+                                        + " Value: "
+                                        + modelData.getPropertyValue(j));
+
+                            }
+
+                        }
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                        PrintLog("Receiving Event from cqid " + cqid
+                                + " failed");
+                    }
+                }
+            }
+        };
+
+        clickHandler = new View.OnClickListener() {
+
+            public void onClick(View v) {
+                switch (v.getId()) {
+                    case R.id.btnRegisterQuery:
+                        int cqid = 0;
+                        try {
+                            cqid = SoftSensorManager.registerQuery(edtQuery
+                                    .getText().toString(),
+                                    mQueryEngineEventListener);
+                            mRunningQueries.add(cqid);
+                            PrintLog(edtQuery.getText().toString()
+                                    + " has executed, cqid=" + cqid);
+                        } catch (Exception e) {
+                            PrintLog("Register Query failed");
+                        }
+
+                        break;
+
+                    case R.id.btnUnregisterQuery:
+                        Iterator<Integer> it = mRunningQueries.iterator();
+
+                        while (it.hasNext()) {
+                            if (it.next() == Integer
+                                    .parseInt(edtUnregisterQuery.getText()
+                                            .toString())) {
+                                try {
+                                    SoftSensorManager.unregisterQuery(Integer
+                                            .parseInt(edtUnregisterQuery
+                                                    .getText().toString()));
+                                    PrintLog("Unregister Query has executed, cqid="
+                                            + Integer
+                                                    .parseInt(edtUnregisterQuery
+                                                            .getText()
+                                                            .toString()));
+                                    it.remove();
+                                } catch (NumberFormatException e) {
+                                    PrintLog("Invalid Query Id");
+                                } catch (Exception e) {
+                                    PrintLog("UnRegister Query failed");
+                                }
+                                break;
+                            }
+                        }
+                        break;
+
+                    case R.id.btPlus:
+                        int queryNum = 0;
+
+                        try {
+                            queryNum = Integer.parseInt(edtUnregisterQuery
+                                    .getText().toString()) + 1;
+                            edtUnregisterQuery.setText(queryNum + "");
+                        } catch (NumberFormatException e) {
+                            PrintLog("Invalid Query Id");
+                        }
+                        break;
+
+                    case R.id.btMinus:
+                        try {
+                            queryNum = Integer.parseInt(edtUnregisterQuery
+                                    .getText().toString()) - 1;
+                            edtUnregisterQuery.setText(queryNum + "");
+                        } catch (NumberFormatException e) {
+                            PrintLog("Invalid Query Id");
+                        }
+                        break;
+                }
+            }
+        };
+
+        textAddHandler = new View.OnClickListener() {
+
+            public void onClick(View v) {
+                switch (v.getId()) {
+                    case R.id.btClear:
+                        edtQuery.setText("");
+                        break;
+
+                    case R.id.btLogClear:
+                        tvLog.setText("");
+                        break;
+
+                    case R.id.btFullDevice:
+                        edtQuery.setText("subscribe Device if Device.dataId != 0");
+                        break;
+
+                    case R.id.btDiscomfortIndex:
+                        edtQuery.setText("subscribe Device.DiscomfortIndexSensor if Device.DiscomfortIndexSensor.discomfortIndex > 0");
+                        break;
+                }
+            }
+        };
+
+        copyFiles("lib");
+
+        SoftSensorManager = new SSMInterface();
+
+        String initConfig = "<SSMCore>" + "<Device>" + "<UDN>" + getUUID()
+                + "</UDN>" + "<Name>MyMobile</Name>" + "<Type>Mobile</Type>"
+                + "</Device>" + "<Config>"
+                + "<SoftSensorRepository>/data/data/" + getPackageName()
+                + "/files/</SoftSensorRepository>"
+                + "<SoftSensorDescription>/data/data/" + getPackageName()
+                + "/files/SoftSensorDescription.xml</SoftSensorDescription>"
+                + "</Config>" + "</SSMCore>";
+
+        try {
+            SoftSensorManager.startSSMCore(initConfig);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        findViewById(R.id.btnRegisterQuery).setOnClickListener(clickHandler);
+        findViewById(R.id.btnUnregisterQuery).setOnClickListener(clickHandler);
+        findViewById(R.id.btFullDevice).setOnClickListener(textAddHandler);
+        findViewById(R.id.btDiscomfortIndex).setOnClickListener(textAddHandler);
+        findViewById(R.id.btPlus).setOnClickListener(clickHandler);
+        findViewById(R.id.btMinus).setOnClickListener(clickHandler);
+        findViewById(R.id.btClear).setOnClickListener(textAddHandler);
+        findViewById(R.id.btLogClear).setOnClickListener(textAddHandler);
+    }
+
+    @Override
+    protected void onDestroy() {
+        try {
+            SoftSensorManager.stopSSMCore();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        super.onDestroy();
+    }
+
+    private String getUUID() {
+        String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
+        SharedPreferences sharedPrefs = getSharedPreferences(PREF_UNIQUE_ID,
+                Context.MODE_PRIVATE);
+        String uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
+
+        if (uniqueID == null) {
+            uniqueID = UUID.randomUUID().toString();
+            Editor editor = sharedPrefs.edit();
+            editor.putString(PREF_UNIQUE_ID, uniqueID);
+            editor.commit();
+        }
+
+        return uniqueID;
+    }
+
+    private void copyFiles(String path) {
+        AssetManager assetManager = getAssets();
+        String assets[] = null;
+
+        try {
+            assets = assetManager.list(path);
+
+            if (assets.length == 0) {
+                copyFile(path);
+            } else {
+                String fullPath = "/data/data/"
+                        + this.getClass().getPackage().toString() + "/" + path;
+                File dir = new File(fullPath);
+
+                if (!dir.exists())
+                    dir.mkdir();
+                for (int i = 0; i < assets.length; ++i) {
+                    copyFiles(path + "/" + assets[i]);
+                }
+            }
+        } catch (IOException ex) {
+            Log.e("tag", "I/O Exception", ex);
+        }
+    }
+
+    private void copyFile(String filename) {
+        AssetManager assetManager = getAssets();
+        InputStream in = null;
+        OutputStream out = null;
+
+        try {
+            in = assetManager.open(filename);
+            out = openFileOutput(filename.split("/")[1], Context.MODE_PRIVATE);
+
+            byte[] buffer = new byte[1024];
+            int read;
+
+            while ((read = in.read(buffer)) != -1) {
+                out.write(buffer, 0, read);
+            }
+
+            in.close();
+            in = null;
+            out.flush();
+            out.close();
+            out = null;
+        } catch (Exception e) {
+            Log.e("tag", e.getMessage());
+        }
+    }
+    
+    private void configurePlatform() {
+        // local Variables
+        ConnectivityManager connManager;
+        NetworkInfo wifi;
+        AlertDialog dialog;
+        PlatformConfig platformConfigObj;
+
+        // Check the wifi connectivity
+        connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
+        wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+        if (false == wifi.isConnected()) {
+            // WiFi is not connected close the application
+            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
+            dialogBuilder.setTitle("Error");
+            dialogBuilder
+                    .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...");
+            dialogBuilder.setCancelable(false);
+            dialogBuilder.setPositiveButton("OK", new OnClickListener() {
+                @Override
+                public void onClick(DialogInterface dialog, int which) {
+                    // Closing the application
+                    activityObj.finish();
+                }
+            });
+
+            dialog = dialogBuilder.create();
+            dialog.show();
+            return;
+        }
+        // If wifi is connected calling the configure method for configuring the
+        // OcPlatform
+        platformConfigObj = new PlatformConfig(this,ServiceType.IN_PROC,
+                ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+
+        Log.i(LOG_TAG, "Before Calling Configure of ocPlatform");
+        OcPlatform.Configure(platformConfigObj);
+        Log.i(LOG_TAG, "Configuration done Successfully");
+    }
+}
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Makefile b/service/soft-sensor-manager/SampleApp/arduino/Makefile
deleted file mode 100644 (file)
index 52a3596..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-
--include ../../build/linux/environment.mk
-
-MAKE=make
-
-CUR_DIR=${PWD}
-SRCLIST=${wildcard **/**/Makefile}
-DIRLIST=${patsubst %/, % , ${dir ${SRCLIST}} }
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job build post_job 
-
-pre_job:
-       @echo " " 
-       @echo "============= Sample Folder ============" 
-       @echo " "
-       @echo "${DIRLIST}"
-       
-build:
-       @for subdir in ${DIRLIST} ; do \
-       ${MAKE} -C $${subdir} ; \
-       echo " " ; \
-       done
-       @echo " "
-
-post_job:
-       @echo " " 
-       @echo "============ Sample Folder Successful. ============="
-       @echo " " 
-
-
-clean:
-       @for subdir in ${DIRLIST} ; do \
-       ${MAKE} clean -C $${subdir} ; \
-       echo " " ; \
-       done
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile
deleted file mode 100644 (file)
index 6df468b..0000000
+++ /dev/null
@@ -1,130 +0,0 @@
-# //******************************************************************
-# //
-# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // Licensed under the Apache License, Version 2.0 (the "License");
-# // you may not use this file except in compliance with the License.
-# // You may obtain a copy of the License at
-# //
-# //      http://www.apache.org/licenses/LICENSE-2.0
-# //
-# // Unless required by applicable law or agreed to in writing, software
-# // distributed under the License is distributed on an "AS IS" BASIS,
-# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# // See the License for the specific language governing permissions and
-# // limitations under the License.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
--include ../../../../build/arduino/environment.mk
-ARDUINO_DIR = /usr/share/arduino
-
-BUILD := release
-PLATFORM := arduinomega
-ARDUINO_PORT := ttyACM0
-
-SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
-OBJPATH=${SRCLIST:.cpp=.o}
-OBJLIST=${notdir ${OBJPATH}}
-
-SRC_PATH=../src
-# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
-ARDUINOWIFI := 0
-
-APP_NAME := reference
-
-TB_DIR = ../../../../../../resource/csdk
-LOGGER_DIR = $(TB_DIR)/logger
-OC_LOG_DIR = $(TB_DIR)/../oc_logger
-TBSTACK_DIR = $(TB_DIR)/stack
-TBSOCKET_DIR = $(TB_DIR)/ocsocket
-
-include $(TB_DIR)/local.properties
-include $(TB_DIR)/$(PLATFORM).properties
-
-VPATH := $(SDIR_ARD_PLATFORM)
-
-#include directories
-OCSOCK_DIR = $(TB_DIR)/ocsocket
-LOGGER_DIR = $(TB_DIR)/logger
-STACK_DIR  = $(TB_DIR)/stack
-INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include -I../include
-
-CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
-CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
-
-CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
-
-ifeq ($(ARDUINOWIFI),1)
-       CFLAGS += -DARDUINOWIFI
-       ARDUINO_SHIELD_TYPE := "/wifi_shield"
-       TRANSPORT_OBJS = $(WIFI_COBJ)
-else
-       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
-       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
-endif
-
-OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
-
-OBJ_DIR := $(OUT_DIR)/bin
-
-all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-
-core.a: $(PLATFORM_OBJS)
-       @cd $(OBJ_DIR) && $(AR) -x ../../../../$(TB_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a
-       $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o
-       @cd $(OBJ_DIR) && $(RANLIB) $@
-
-prep_dirs:
-       -mkdir $(PLATFORM)
-       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
-       -mkdir $(OUT_DIR)
-       -mkdir $(OBJ_DIR)
-
-%.o: %.c
-       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-%.o: %.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ 
-%.o: ${SRC_PATH}/%.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-
-$(APP_NAME).elf: $(OBJLIST) core.a
-ifeq ($(PLATFORM),arduinomega)
-       $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-$(APP_NAME).hex: $(APP_NAME).elf
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep
-       $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-install: all
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i
-else ifeq ($(PLATFORM),arduinodue)
-       stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb
-       $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-.PHONY: clean
-
-clean: legacy_clean
-       rm -rf arduinomega
-       rm -rf arduinodue
-
-legacy_clean:
-       @rm -rf bin
-       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
index 8356098..a543229 100644 (file)
@@ -1,82 +1,95 @@
-/*
- * bleLib.h
- *
- *  Created on: 2014. 11. 5.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #ifndef BLELIB_H_
 #define BLELIB_H_
 
 #include "Arduino.h"
 
-#define BLE_NOCHANGE   -1
-#define BLE_MASTER             1
-#define BLE_SLAVER             0
+#define BLE_NOCHANGE    -1
+#define BLE_MASTER      1
+#define BLE_SLAVER      0
 
-#define BLE_DISCON             200
-#define BLE_NODATA             100
+#define BLE_DISCON      200
+#define BLE_NODATA      100
 
 
 /***************************************
  *
- *     HM-10 BLE Module Control Class.
- *     Target Board : Arduino-Mega.
+ *  HM-10 BLE Module Control Class.
+ *  Target Board : Arduino-Mega.
  *
  **************************************/
 class Cble
 {
-public :
-       /***
-        * BLE Control Function.
-        */
-       // BLE initialization ( COM baud rate , BLE Master , Slave setting. )
-       void init(long baudRate, int ble_mode, char* SelfMaxAddr);
-
-       void StatusRead( void );
-
-       bool IsSelfArduino( void );
-
-       bool IsConnected( void );
-
-       bool pollingConnect( const char* maxAddr );
-
-       void pollingDisconnect( void );
-       // Get RSSI by BLE communication. (polling method.)
-       int pollingGetRSSI( void );
-       // Send Request to BLE Module. And, Get the response. (polling method.)
-       bool pollingRequest(const char* request, char* data, int dataLen);
-
-       int mustHaveRequest(const char* request, char* data, int dataLen);
-
-       void streamDummy( char* data, int dataLen);
-
-       /***
-        * Debug COM port to BLE COM port.
-        * BLE COM port to Debug COM port.
-        */
-       // BLE Module to Debug Serial port.
-       void BLE2Debug( int autoDiscon );
-       // Debug Serial port to BLE Module.
-       char* Debug2BLE( int BLEwrite );
-
-       /***
-        * If you first setting, you need next-function.
-        */
-       // Restore to factory setting data.
-       void FactoryReset( void );
-       // First setting of COM port.
-       void firstUartSetting( void );
+    public :
+        /***
+         * BLE Control Function.
+         */
+        // BLE initialization ( COM baud rate , BLE Master , Slave setting. )
+        void init(long baudRate, int ble_mode, char *SelfMaxAddr);
+
+        void StatusRead( void );
+
+        bool IsSelfArduino( void );
+
+        bool IsConnected( void );
+
+        bool pollingConnect( const char *maxAddr );
+
+        void pollingDisconnect( void );
+        // Get RSSI by BLE communication. (polling method.)
+        int pollingGetRSSI( void );
+        // Send Request to BLE Module. And, Get the response. (polling method.)
+        bool pollingRequest(const char *request, char *data, int dataLen);
+
+        int mustHaveRequest(const char *request, char *data, int dataLen);
+
+        void streamDummy( char *data, int dataLen);
+
+        /***
+         * Debug COM port to BLE COM port.
+         * BLE COM port to Debug COM port.
+         */
+        // BLE Module to Debug Serial port.
+        void BLE2Debug( int autoDiscon );
+        // Debug Serial port to BLE Module.
+        char *Debug2BLE( int BLEwrite );
+
+        /***
+         * If you first setting, you need next-function.
+         */
+        // Restore to factory setting data.
+        void FactoryReset( void );
+        // First setting of COM port.
+        void firstUartSetting( void );
 };
 
 
 
 #if 0
-#define debug_printf(...)      {                                                       \
-       char* __temp__ = (char*)malloc(sizeof(char)*2048);              \
-       sprintf(__temp__, __VA_ARGS__ );                                        \
-       Serial.print(__temp__);                                                                 \
-       free(__temp__);                                                                                                 \
+#define debug_printf(...)   {                           \
+    char* __temp__ = (char*)malloc(sizeof(char)*2048);      \
+    sprintf(__temp__, __VA_ARGS__ );                    \
+    Serial.print(__temp__);                                 \
+    free(__temp__);                                                 \
 }
 #else
 #define debug_printf(...)
index 41556f6..e227da3 100644 (file)
@@ -1,9 +1,22 @@
-/*
- * oic_lanLib.h
- *
- *  Created on: 2014. 11. 13.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #ifndef OIC_LANLIB_H_
 #define OIC_LANLIB_H_
index c4e12d3..f9cc723 100644 (file)
-/*
- * blsLib.cpp
- *
- *  Created on: 2014. 11. 5.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #include "bleLib.h"
 #include <stdarg.h>
 
-#define ARDUINO                        1
-//#define __INTERNAL_DEBUG__           1
+//#define __INTERNAL_DEBUG__        1
 
+#define LIMIT_COUNT         100
+#define DUMMY_SIZE          30
+#define DEBUG_SIZE          DUMMY_SIZE
+#define SERIAL_SIZE         100
 
-#define LIMIT_COUNT                    100
-#define DUMMY_SIZE                     30
-#define DEBUG_SIZE                     DUMMY_SIZE
-#if (ARDUINO != 0)
-#define SERIAL_SIZE                    100
-#endif
-
-#define BLE            Serial2
+#define BLE     Serial2
 
 bool isConnected = false;
-int SerialCnt=0;
-int BLECnt=0;
+int SerialCnt = 0;
+int BLECnt = 0;
 char SelfMaxaddr[19] = {0,};
 
-char debugD[DEBUG_SIZE]={0,};
+char debugD[DEBUG_SIZE] = {0,};
 
-#if (ARDUINO != 0)
-char SerialData[SERIAL_SIZE]={0,};
-char BLEData[SERIAL_SIZE]={0,};
-#endif
 
-// baudRate이 115200이면, 주의해야한다.
-// Arduino Chip은 16bit Process 이므로 int형의 사이즈가 4byte형 signed int이다.
-void Cble::init(long baudRate, int ble_mode, char* SelfMaxAddr)
+char SerialData[SERIAL_SIZE] = {0,};
+char BLEData[SERIAL_SIZE] = {0,};
+
+
+void Cble::init(long baudRate, int ble_mode, char *SelfMaxAddr)
 {
-       debug_printf("BLE shiled is initialed.-\r\n");
-
-       if(SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE )
-       {
-               debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n");
-               exit(-1);
-       }
-       sprintf(SelfMaxaddr, "%s",SelfMaxAddr);
-
-       BLE.begin(baudRate);
-       BLE.setTimeout(1);
-       delay(1000);
-
-       memset(debugD,0,DEBUG_SIZE);
-
-       if( ble_mode != BLE_NOCHANGE )
-       {
-               while( IsSelfArduino() == false )
-                       this->pollingDisconnect();
-       }
-
-       if( ble_mode == BLE_MASTER )
-       {
-               pollingRequest("AT+ROLE1", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+MODE0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+NOTI0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-       }
-       else if ( ble_mode == BLE_SLAVER )
-       {
-               pollingRequest("AT+ROLE0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+MODE2", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+NOTI0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-       }
-
-       if( ble_mode != BLE_NOCHANGE )
-       {
-               while( IsSelfArduino() == false )
-                       this->pollingDisconnect();
-       }
-
-       delay(250);
+    debug_printf("BLE shiled is initialed.-\r\n");
+
+    if (SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE )
+    {
+        debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n");
+        exit(-1);
+    }
+    sprintf(SelfMaxaddr, "%s", SelfMaxAddr);
+
+    BLE.begin(baudRate);
+    BLE.setTimeout(1);
+    delay(1000);
+
+    memset(debugD, 0, DEBUG_SIZE);
+
+    if ( ble_mode != BLE_NOCHANGE )
+    {
+        while ( IsSelfArduino() == false )
+            this->pollingDisconnect();
+    }
+
+    if ( ble_mode == BLE_MASTER )
+    {
+        pollingRequest("AT+ROLE1", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+MODE0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+NOTI0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+    }
+    else if ( ble_mode == BLE_SLAVER )
+    {
+        pollingRequest("AT+ROLE0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+MODE2", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+NOTI0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+    }
+
+    if ( ble_mode != BLE_NOCHANGE )
+    {
+        while ( IsSelfArduino() == false )
+            this->pollingDisconnect();
+    }
+
+    delay(250);
 }
 
 void Cble::StatusRead( void )
 {
-       debug_printf("StatusRead function called.\r\n");
-
-       pollingRequest("AT+ROLE?", debugD, 9);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+MODE?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+IMME?", debugD, 9);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+TYPE?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+POWE?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+NOTI?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+PIO1?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
+    debug_printf("StatusRead function called.\r\n");
+
+    pollingRequest("AT+ROLE?", debugD, 9);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+MODE?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+IMME?", debugD, 9);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+TYPE?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+POWE?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+NOTI?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+PIO1?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
 }
 
 bool Cble::IsConnected( void )
 {
-       return isConnected;
+    return isConnected;
 }
 
 bool Cble::IsSelfArduino( void )
 {
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("IsSelfArduino is called.\r\n");
+    debug_printf("IsSelfArduino is called.\r\n");
 #endif
-       int length=mustHaveRequest("AT+ADDR?", debugD, 20);
-
-       if( strstr(debugD, SelfMaxaddr) )
-       {
-               isConnected = false;
-               memset(debugD,0,length);
-               return true;
-       }
-       else
-       {
-               isConnected = true;
-               memset(debugD,0,length);
-               return false;
-       }
+    int length = mustHaveRequest("AT+ADDR?", debugD, 20);
+
+    if ( strstr(debugD, SelfMaxaddr) )
+    {
+        isConnected = false;
+        memset(debugD, 0, length);
+        return true;
+    }
+    else
+    {
+        isConnected = true;
+        memset(debugD, 0, length);
+        return false;
+    }
 }
 
-bool Cble::pollingConnect( const charmaxAddr )
+bool Cble::pollingConnect( const char *maxAddr )
 {
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("pollingConnect is called.\r\n");
+    debug_printf("pollingConnect is called.\r\n");
 #endif
 
-#define CONNECT_SIZE           20
-
-       char cmd[CONNECT_SIZE]= {0,};
-
-       // is Connected Address ?
-       pollingRequest("AT+ADDR?", debugD, 20);
-       if( strstr(debugD, maxAddr) )
-       {
-               isConnected = true;
-               memset(debugD,0,DEBUG_SIZE);
-               return isConnected;
-       }
-       memset(debugD,0,DEBUG_SIZE);
-
-       // Try Connection.
-       sprintf(cmd, "AT+CON%s",maxAddr);
-       if( pollingRequest(cmd, debugD, 8) == false )
-       {
-               debug_printf("Error : %s command is failed.\r\n",cmd );
-               memset(debugD,0,DEBUG_SIZE);
-               pollingDisconnect();
-               return false;
-       }
-       else if( strstr(debugD,"OK+CONNA") )
-       {
-               isConnected = true;
-               memset(debugD,0,DEBUG_SIZE);
-       }
-       else
-       {
-               memset(debugD,0,DEBUG_SIZE);
-               pollingDisconnect();
-               return false;
-       }
-
-       // Confirm Connected Address.
-       pollingRequest("AT+ADDR?", debugD, 20);
-
-       if( strstr(debugD, maxAddr) == 0 )
-       {
-               isConnected = false;
-               if ( strstr(debugD, "OK+CONNF") )
-               {
-                       memset(debugD,0,DEBUG_SIZE);
-                       streamDummy(debugD, 8);
-               }
-       }
-       memset(debugD,0,DEBUG_SIZE);
-       delay(5);
-
-       return isConnected;
+#define CONNECT_SIZE        20
+
+    char cmd[CONNECT_SIZE] = {0,};
+
+    // is Connected Address ?
+    pollingRequest("AT+ADDR?", debugD, 20);
+    if ( strstr(debugD, maxAddr) )
+    {
+        isConnected = true;
+        memset(debugD, 0, DEBUG_SIZE);
+        return isConnected;
+    }
+    memset(debugD, 0, DEBUG_SIZE);
+
+    // Try Connection.
+    sprintf(cmd, "AT+CON%s", maxAddr);
+    if ( pollingRequest(cmd, debugD, 8) == false )
+    {
+        debug_printf("Error : %s command is failed.\r\n", cmd );
+        memset(debugD, 0, DEBUG_SIZE);
+        pollingDisconnect();
+        return false;
+    }
+    else if ( strstr(debugD, "OK+CONNA") )
+    {
+        isConnected = true;
+        memset(debugD, 0, DEBUG_SIZE);
+    }
+    else
+    {
+        memset(debugD, 0, DEBUG_SIZE);
+        pollingDisconnect();
+        return false;
+    }
+
+    // Confirm Connected Address.
+    pollingRequest("AT+ADDR?", debugD, 20);
+
+    if ( strstr(debugD, maxAddr) == 0 )
+    {
+        isConnected = false;
+        if ( strstr(debugD, "OK+CONNF") )
+        {
+            memset(debugD, 0, DEBUG_SIZE);
+            streamDummy(debugD, 8);
+        }
+    }
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(5);
+
+    return isConnected;
 
 #undef CONNECT_SIZE
 }
 
 
-#define  CMD_DISCONNECT                "(CMD_DISCON)"
+#define  CMD_DISCONNECT     "(CMD_DISCON)"
 void Cble::pollingDisconnect( void )
 {
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("pollingDisconnect is called.\r\n");
-#endif
-       int length=0;
-#if (ARDUINO == 0)
-       pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL);
-       delay(5);
-
-       length=mustHaveRequest("AT", debugD, 2);
-       if( strstr(debugD,"OK") )
-               isConnected = false;
-
-       memset(debugD,0,length);
-#else
-       if( BLE.available() )
-       {
-               if( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true )
-               {
-                       debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT);
-
-                       do {
-                               debug_printf("pollingDisconnect : Send AT message.\r\n");
-                               if( length )
-                                       memset(debugD, 0, length);
-
-                               length=mustHaveRequest("AT", debugD, 2);
-                       }while( strstr(debugD,"OK") == NULL );
-
-                       debug_printf("pollingDisconnect() is Success.\r\n");
-                       memset(debugD, 0, length);
-               }
-       }
+    debug_printf("pollingDisconnect is called.\r\n");
 #endif
-
-       delay(5);
+    int length = 0;
+
+    if ( BLE.available() )
+    {
+        if ( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true )
+        {
+            debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT);
+
+            do
+            {
+                debug_printf("pollingDisconnect : Send AT message.\r\n");
+                if ( length )
+                    memset(debugD, 0, length);
+
+                length = mustHaveRequest("AT", debugD, 2);
+            }
+            while ( strstr(debugD, "OK") == NULL );
+
+            debug_printf("pollingDisconnect() is Success.\r\n");
+            memset(debugD, 0, length);
+        }
+    }
+
+    delay(5);
 }
 
 int Cble::pollingGetRSSI( void )
 {
-#define RSSI_SIZE              11
-#define RSSI_POS               7
-
-       long time_cnt=0;
-       char c=0;
-       char index=0;
-       char rssi_res[RSSI_SIZE] = {0,};
-
-       streamDummy(NULL, NULL);
-
-       if( isConnected == true )
-       {
-               BLE.write("AT+RSSI?");
-               BLE.flush();
-               delay(5);
-
-               while(1)
-               {
-                       if ( BLE.available() )
-                               c = (char)BLE.read();
-                       else
-                       {
-                               c = 0;
-                               time_cnt++;
-                       }
-
-                       if( c )
-                       {
-                               rssi_res[index] = c;
-                               index++;
-                               if( index == RSSI_SIZE-1 )
-                               {
-                                       rssi_res[index] = '\0';
-                                       goto RESULT;
-                               }
-                       }
-
-                       if( time_cnt == 0xFFFFF )
-                       {
-                               debug_printf("Error : Time Out GetRSSI().\r\n");
-                               return BLE_NODATA;
-                       }
-
-               }
-
-       RESULT :
+#define RSSI_SIZE       11
+#define RSSI_POS        7
+
+    long time_cnt = 0;
+    char c = 0;
+    char index = 0;
+    char rssi_res[RSSI_SIZE] = {0,};
+
+    streamDummy(NULL, NULL);
+
+    if ( isConnected == true )
+    {
+        BLE.write("AT+RSSI?");
+        BLE.flush();
+        delay(5);
+
+        while (1)
+        {
+            if ( BLE.available() )
+                c = (char)BLE.read();
+            else
+            {
+                c = 0;
+                time_cnt++;
+            }
+
+            if ( c )
+            {
+                rssi_res[index] = c;
+                index++;
+                if ( index == RSSI_SIZE - 1 )
+                {
+                    rssi_res[index] = '\0';
+                    goto RESULT;
+                }
+            }
+
+            //      debug_printf("time_cnt=%d\r\n", time_cnt);
+            if ( time_cnt == 0xFFFFF )
+            {
+                debug_printf("Error : Time Out GetRSSI().\r\n");
+                return BLE_NODATA;
+            }
+
+        }
+
+RESULT :
 #ifdef __INTERNAL_DEBUG__
-               debug_printf("res= %s \r\n",rssi_res);
+        debug_printf("res= %s \r\n", rssi_res);
 #endif
-               char* Srssi = &(rssi_res[RSSI_POS]);
-               int rssi = atoi(Srssi);
+        char *Srssi = &(rssi_res[RSSI_POS]);
+        //  debug_printf("[S] rssi=%s\r\n", Srssi);
+        int rssi = atoi(Srssi);
+        //  debug_printf("rssi=%d\r\n", rssi);
 
-               return rssi;
-       }
+        return rssi;
+    }
 
-       return BLE_DISCON;
+    return BLE_DISCON;
 
 #undef RSSI_POS
 #undef RSSI_SIZE
 }
 
-int Cble::mustHaveRequest(const char* request, char* data, int dataLen)
+int Cble::mustHaveRequest(const char *request, char *data, int dataLen)
 {
-       int cnt=0;
-       int length=0;
-       int required_length = dataLen;
-       char* data_index = data;
+    int cnt = 0;
+    int length = 0;
+    int required_length = dataLen;
+    char *data_index = data;
 
-       BLE.write(request);
-       BLE.flush();
-       delay(150);
+    BLE.write(request);
+    BLE.flush();
+    delay(150);
 
 READ_STREAM :
-       while( (length=BLE.readBytes(data_index, required_length)) == 0 )
-       {
-               cnt++;
-               delay(10);
+    while ( (length = BLE.readBytes(data_index, required_length)) == 0 )
+    {
+        cnt++;
+        delay(10);
 
-               if ( cnt >= LIMIT_COUNT/10 )
-               {
+        if ( cnt >= LIMIT_COUNT / 10 )
+        {
 #ifdef __INTERNAL_DEBUG__
-                       debug_printf("=====> Retry Request command Send. <=========\r\n");
+            debug_printf("=====> Retry Request command Send. <=========\r\n");
 #endif
-                       cnt = 0;
-                       BLE.write(request);
-                       BLE.flush();
-
-                       required_length = dataLen;
-                       data_index = data;
-                       length = 0;
-                       delay(50);
-               }
-       }
-
-       required_length -= length;
-       if( required_length != 0 )
-       {
-               data_index = data_index + length;
-               length = 0;
-               goto READ_STREAM;
-       }
+            cnt = 0;
+            BLE.write(request);
+            BLE.flush();
+
+            required_length = dataLen;
+            data_index = data;
+            length = 0;
+            delay(50);
+        }
+    }
+
+    required_length -= length;
+    if ( required_length != 0 )
+    {
+        data_index = data_index + length;
+        length = 0;
+        goto READ_STREAM;
+    }
 
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("[ %s ] %s\r\n\r\n", request, data);
+    debug_printf("[ %s ] %s\r\n\r\n", request, data);
 #endif
-       return dataLen;
+    return dataLen;
 }
 
-bool Cble::pollingRequest(const char* request, char* data, int dataLen)
+bool Cble::pollingRequest(const char *request, char *data, int dataLen)
 {
-       int cnt=0;
-       int length=0;
-       int required_length = dataLen;
-       char* data_index = data;
+    int cnt = 0;
+    int length = 0;
+    int required_length = dataLen;
+    char *data_index = data;
 
-       BLE.write(request);
-       BLE.flush();
+    BLE.write(request);
+    BLE.flush();
 
-       if( data_index )
-       {
-               delay(250);
+    if ( data_index )
+    {
+        delay(250);
 
 READ_STREAM :
-               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
-               {
-                       cnt++;
-                       if ( cnt >= LIMIT_COUNT )
-                       {
-                               debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request);
-                               return false;
-                       }
-               }
-
-               required_length -= length;
-               if( required_length != 0 )
-               {
-                       data_index = data_index + length;
-                       length = 0;
-                       goto READ_STREAM;
-               }
+        while ( (length = BLE.readBytes(data_index, required_length)) == 0 )
+        {
+            cnt++;
+            if ( cnt >= LIMIT_COUNT )
+            {
+                debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request);
+                return false;
+            }
+        }
+
+        required_length -= length;
+        if ( required_length != 0 )
+        {
+            data_index = data_index + length;
+            length = 0;
+            goto READ_STREAM;
+        }
 
 #ifdef __INTERNAL_DEBUG__
-               debug_printf("[ %s ] %s\r\n\r\n", request, data);
+        debug_printf("[ %s ] %s\r\n\r\n", request, data);
 #endif
-       }
-       return true;
+    }
+    return true;
 }
 
-void Cble::streamDummy( chardata, int dataLen)
+void Cble::streamDummy( char *data, int dataLen)
 {
-       int cnt=0;
-       int length=0;
-       int required_length = dataLen;
-       char* data_index = data;
+    int cnt = 0;
+    int length = 0;
+    int required_length = dataLen;
+    char *data_index = data;
 
-       if( data && required_length )
-       {
+    if ( data && required_length )
+    {
 READ_STREAM :
-               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
-               {
-                       cnt++;
-                       if ( cnt >= LIMIT_COUNT )
-                       {
-                               debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n");
-                               return ;
-                       }
-               }
-
-               required_length -= length;
-               if( required_length != 0 )
-               {
-                       data_index = data_index + length;
-                       length = 0;
-                       goto READ_STREAM;
-               }
-
-               debug_printf("[ streamDummy ] %s\r\n\r\n", data);
-       }
-       else
-       {
-               if( BLE.available() )
-               {
-                       BLE.readBytes(debugD, DEBUG_SIZE);
+        while ( (length = BLE.readBytes(data_index, required_length)) == 0 )
+        {
+            cnt++;
+            if ( cnt >= LIMIT_COUNT )
+            {
+                debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n");
+                return ;
+            }
+        }
+
+        required_length -= length;
+        if ( required_length != 0 )
+        {
+            data_index = data_index + length;
+            length = 0;
+            goto READ_STREAM;
+        }
+
+        debug_printf("[ streamDummy ] %s\r\n\r\n", data);
+    }
+    else
+    {
+        if ( BLE.available() )
+        {
+            BLE.readBytes(debugD, DEBUG_SIZE);
 #ifdef __INTERNAL_DEBUG__
-                       debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
+            debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
 #endif
-                       memset(debugD, 0, DEBUG_SIZE);
-               }
-       }
+            memset(debugD, 0, DEBUG_SIZE);
+        }
+    }
 
 }
 
-#if (ARDUINO != 0)
 
-#define REGARD_DISCON                  5000
+#define REGARD_DISCON           5000
 int needDiscon = 0;
 unsigned long global_cnt = 0;
 
 void Cble::BLE2Debug( int autoDiscon )
 {
-       int cnt=0;
-       uint8_t length=0;
-
-       if( BLE.available() )
-       {
-               while( (length=BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 )
-               {
-                       cnt++;
-                       if ( cnt >= LIMIT_COUNT )
-                               return ;
-               }
-
-               global_cnt = 0;
-               needDiscon = 0;
-
-               Serial.println(BLEData);
-               memset(BLEData, 0, length);
-       }
-       else if ( autoDiscon )
-       {
-               global_cnt++;
-//             debug_printf("global_cnt=%u , ", global_cnt );
-//             debug_printf("needDiscon=%d\r\n", needDiscon);
-               if( !needDiscon && global_cnt >= REGARD_DISCON )
-               {
-                       needDiscon = 1;
-                       debug_printf("result : global_cnt=%u , ", global_cnt );
-                       debug_printf("needDiscon=%d\r\n", needDiscon);
-               }
-
-               if ( needDiscon )
-               {
-                       debug_printf("Auto Discon : global_cnt=%u , ", global_cnt );
-                       debug_printf("needDiscon=%d\r\n", needDiscon);
-                       if( pollingRequest("AT", debugD, 2) == true )
-                       {
-                               global_cnt = 0;
-                               needDiscon = 0;
-                       }
-               }
-       }
+    int cnt = 0;
+    uint8_t length = 0;
+
+    if ( BLE.available() )
+    {
+        while ( (length = BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 )
+        {
+            cnt++;
+            if ( cnt >= LIMIT_COUNT )
+                return ;
+        }
+
+        global_cnt = 0;
+        needDiscon = 0;
+
+        Serial.println(BLEData);
+        memset(BLEData, 0, length);
+    }
+    else if ( autoDiscon )
+    {
+        global_cnt++;
+//      debug_printf("global_cnt=%u , ", global_cnt );
+//      debug_printf("needDiscon=%d\r\n", needDiscon);
+        if ( !needDiscon && global_cnt >= REGARD_DISCON )
+        {
+            needDiscon = 1;
+            debug_printf("result : global_cnt=%u , ", global_cnt );
+            debug_printf("needDiscon=%d\r\n", needDiscon);
+        }
+
+        if ( needDiscon )
+        {
+            debug_printf("Auto Discon : global_cnt=%u , ", global_cnt );
+            debug_printf("needDiscon=%d\r\n", needDiscon);
+            if ( pollingRequest("AT", debugD, 2) == true )
+            {
+                global_cnt = 0;
+                needDiscon = 0;
+            }
+        }
+    }
 }
 
-charCble::Debug2BLE( int BLEwrite )
+char *Cble::Debug2BLE( int BLEwrite )
 {
-       char* result = NULL;
-
-       if( Serial.available() )
-       {
-               char c = (char)Serial.read();
-
-               switch(c)
-               {
-               case '\0':
-                       return result;
-               case '\r':
-               case '\n':
-                       debug_printf("\r\n");
-                       if(BLEwrite && SerialCnt)
-                       {
-                               BLE.write(SerialData);
-                               BLE.flush();
-                       }
-
-                       result = (char*)malloc(sizeof(char)*(SerialCnt+1));
-                       memcpy(result, SerialData, SerialCnt );
-                       result[SerialCnt] = NULL;
-
-                       memset(SerialData, 0, SerialCnt+1);
-                       SerialCnt=0;
-                       break;
-               default :
-                       SerialData[SerialCnt] = c;
-                       SerialCnt++;
-                       Serial.print(c);
-                       break;
-               }
-       }
-
-       return result;
-}
-#else
-void Cble::BLE2Debug( int autoDiscon )
-{
-       ;
+    char *result = NULL;
+
+    if ( Serial.available() )
+    {
+        char c = (char)Serial.read();
+
+        switch (c)
+        {
+            case '\0':
+                return result;
+            case '\r':
+            case '\n':
+                debug_printf("\r\n");
+                if (BLEwrite && SerialCnt)
+                {
+                    BLE.write(SerialData);
+                    BLE.flush();
+                }
+
+                result = (char *)malloc(sizeof(char) * (SerialCnt + 1));
+                if (NULL == result)
+                {
+                    debug_printf("Debug2BLE malloc failed .\r\n");
+                    break;
+                }
+                memcpy(result, SerialData, SerialCnt );
+                result[SerialCnt] = NULL;
+
+                memset(SerialData, 0, SerialCnt + 1);
+                SerialCnt = 0;
+                break;
+            default :
+                SerialData[SerialCnt] = c;
+                SerialCnt++;
+                Serial.print(c);
+                break;
+        }
+    }
+
+    return result;
 }
 
-char* Cble::Debug2BLE( int BLEwrite )
-{
-        return NULL;
-}
-#endif
 
 void Cble::FactoryReset( void )
 {
-       debug_printf("FactoryReset is called.\r\n");
+    debug_printf("FactoryReset is called.\r\n");
 
-       pollingRequest("AT+RENEW", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
+    pollingRequest("AT+RENEW", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
 }
 
 
 void Cble::firstUartSetting( void )
 {
-       debug_printf("firstUartSetting is called.\r\n");
+    debug_printf("firstUartSetting is called.\r\n");
 
-       Serial.begin(9600);
-       BLE.begin(9600);
-       BLE.setTimeout(1);
-       delay(1000);
+    Serial.begin(9600);
+    BLE.begin(9600);
+    BLE.setTimeout(1);
+    delay(1000);
 
-       pollingRequest("AT+BAUD4", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
+    pollingRequest("AT+BAUD4", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
 
-       debug_printf("Please Power off and on.\r\n");
-       BLE.end();
-//     delay(1000);
+    debug_printf("Please Power off and on.\r\n");
+    BLE.end();
+//  delay(1000);
 //
-//     BLE.begin(115200);
-//     delay(1000);
+//  BLE.begin(115200);
+//  delay(1000);
 //
-//     pollingRequest("AT", debugD, DEBUG_SIZE);
-//     memset(debugD, 0, DEBUG_SIZE);
+//  pollingRequest("AT", debugD, DEBUG_SIZE);
+//  memset(debugD, 0, DEBUG_SIZE);
 
 
-       exit(0);
+    exit(0);
 }
 
 
index c4a4f26..2497906 100644 (file)
@@ -1,9 +1,22 @@
-/*
- * oic_wifiLib.cpp
- *
- *  Created on: 2014. 11. 13.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #include "logger.h"
 #include "ocstack.h"
@@ -27,7 +40,7 @@
 #endif
 
 
-PROGMEM const char TAG[] = "ReferenceSensor";
+PROGMEM const char TAG[] = "TrackeeSensor";
 
 #ifdef ARDUINOWIFI
 // Arduino WiFi Shield
@@ -38,10 +51,10 @@ PROGMEM const char TAG[] = "ReferenceSensor";
 static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
 
 /// WiFi network info and credentials
-char ssid[] = "SoftSensor_AP";
-char pass[] = "1234567890";
-//char ssid[] = "SoftSensor_2.4G";
-//char pass[] = "12344321";
+//char ssid[] = "SoftSensor_AP";
+//char pass[] = "1234567890";
+char ssid[] = "SoftSensor_2.4G";
+char pass[] = "12344321";
 
 int ConnectToNetwork()
 {
@@ -57,7 +70,7 @@ int ConnectToNetwork()
     // Verify that WiFi Shield is running the firmware with all UDP fixes
     fwVersion = WiFi.firmwareVersion();
     OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
-    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
+    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) != 0 )
     {
         OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
         return -1;
@@ -67,7 +80,7 @@ int ConnectToNetwork()
     while (status != WL_CONNECTED)
     {
         OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
-        status = WiFi.begin(ssid,pass);
+        status = WiFi.begin(ssid, pass);
 
         // wait 10 seconds for connection:
         delay(10000);
index 953032e..0dff6c5 100644 (file)
@@ -1,22 +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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
 
 // Do not remove the include below
 #include "Arduino.h"
@@ -28,7 +28,7 @@
 #include <string.h>
 
 #include "oic_lanLib.h"
-
+//#define ARDUINOWIFI 1
 #define ARDUINO_AVR_MEGA2560 1
 /// This is the port which Arduino Server will use for all unicast communication with it's peers
 #define OC_WELL_KNOWN_PORT 5683
 #define JSON_BASE02 "\",\"3\":\"SERVICETYPE\",\"4\":\"string\",\"5\":\""
 #define JSON_BASE03 "\"}}"
 
-typedef struct REFERRESOURCE {
+typedef struct REFERRESOURCE
+{
     OCResourceHandle m_handle;
-    charm_macaddress;
-    charm_servicetype;
+    char *m_macaddress;
+    char *m_servicetype;
 } REFERResource;
 
 PROGMEM const char TAG[] = "ReferenceSensor";
@@ -49,31 +50,33 @@ PROGMEM const char TAG[] = "ReferenceSensor";
 REFERResource REFER;
 Cble ble;
 
-char macaddress[13]={"9059AF1704D7"};
-char servicetype[15]={"BOOK"};
+//char macaddress[13]={"9059AF1704D7"};
+//char macaddress[13]={"9059AF1700EE"};  R1
+char macaddress[13] = {"34B1F7D004D2"};
+//char macaddress[13]={"9059AF170C1D"};
+char servicetype[15] = {"BOOKLight"};
 
 int g_REFERUnderObservation = 0;
 
 const char *getResult(OCStackResult result);
 void createREFERResource();
 
-#define LENGTH_VAR             100
+#define LENGTH_VAR      100
 static int base_length = 0;
-
-bool JsonGenerator( REFERResource& ref, char* jsonBuf, uint16_t buf_length )
+bool JsonGenerator( REFERResource &ref, char *jsonBuf, uint16_t buf_length )
 {
-       if( (buf_length - base_length) < LENGTH_VAR )
-       {
-               OC_LOG_V(ERROR, TAG, "Error : length is very long.");
-               return false;
-       }
+    if ( (buf_length - base_length) < LENGTH_VAR )
+    {
+        OC_LOG_V(ERROR, TAG, "Error : length is very long.");
+        return false;
+    }
 
-       sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%s",ref.m_macaddress);
-       sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03, ref.m_servicetype);
+    sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%s", ref.m_macaddress);
+    sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03, ref.m_servicetype);
 
-       Serial.println(jsonBuf);
+    Serial.println(jsonBuf);
 
-       return true;
+    return true;
 }
 
 // On Arduino Atmel boards with Harvard memory architecture, the stack grows
@@ -97,68 +100,46 @@ void PrintArduinoMemoryStats()
 
 // This is the entity handler for the registered resource.
 // This is invoked by OCStack whenever it recevies a request for this resource.
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest *entityHandlerRequest )
 {
     OCEntityHandlerResult ehRet = OC_EH_OK;
-    OCEntityHandlerResponse response = {0};
-    char payload[MAX_RESPONSE_LENGTH] = {0};
 
-    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
     {
         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
-        if(OC_REST_GET == entityHandlerRequest->method)
+        if (OC_REST_GET == entityHandlerRequest->method)
         {
-                if(JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH))
-                {
-                }
-           else
+            if (JsonGenerator( REFER, (char *)entityHandlerRequest->resJSONPayload, \
+                               entityHandlerRequest->resJSONPayloadLen))
+            {
+            }
+            else
             {
                 ehRet = OC_EH_ERROR;
             }
         }
-        if(OC_REST_PUT == entityHandlerRequest->method)
+        if (OC_REST_PUT == entityHandlerRequest->method)
         {
             //Do something with the 'put' payload
-            if (JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH))
+            if (JsonGenerator( REFER, (char *)entityHandlerRequest->resJSONPayload, \
+                               entityHandlerRequest->resJSONPayloadLen))
             {
             }
             else
             {
                 ehRet = OC_EH_ERROR;
             }
-         }
-    }
-
-    if (ehRet == OC_EH_OK)
-   {
-          // Format the response.  Note this requires some info about the request
-          response.requestHandle = entityHandlerRequest->requestHandle;
-          response.resourceHandle = entityHandlerRequest->resource;
-          response.ehResult = ehRet;
-          response.payload = (unsigned char *)payload;
-          response.payloadSize = strlen(payload);
-          response.numSendVendorSpecificHeaderOptions = 0;
-          memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
-          memset(response.resourceUri, 0, sizeof response.resourceUri);
-          // Indicate that response is NOT in a persistent buffer
-          response.persistentBufferFlag = 0;
-
-          // Send the response
-          if (OCDoResponse(&response) != OC_STACK_OK)
-          {
-                  OC_LOG(ERROR, TAG, "Error sending response");
-                  ehRet = OC_EH_ERROR;
-          }
+        }
     }
-
     if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
     {
-        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action)
         {
             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
             g_REFERUnderObservation = 1;
         }
-        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action)
         {
             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
         }
@@ -171,62 +152,62 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
 char tempdata[200];
 void ChangeREFERRepresentation (void *param)
 {
-       (void)param;
-       OCStackResult result = OC_STACK_ERROR;
-       result = OCNotifyAllObservers (REFER.m_handle, OC_NA_QOS);
+    (void)param;
+    OCStackResult result = OC_STACK_ERROR;
+    result = OCNotifyAllObservers (REFER.m_handle, OC_NA_QOS);
 
-       OC_LOG_V(INFO, TAG, "%s", JsonGenerator( REFER, tempdata, 200));
+    OC_LOG_V(INFO, TAG, "%s", JsonGenerator( REFER, tempdata, 200));
 
-       if (OC_STACK_NO_OBSERVERS == result)
-       {
-               OC_LOG_V(INFO, TAG, "g_REFERUnderObservation is 0." );
-               g_REFERUnderObservation = 0;
-       }
+    if (OC_STACK_NO_OBSERVERS == result)
+    {
+        OC_LOG_V(INFO, TAG, "g_REFERUnderObservation is 0." );
+        g_REFERUnderObservation = 0;
+    }
 }
 
 //The setup function is called once at startup of the sketch
 void setup()
 {
-       Serial.begin(115200);
+    Serial.begin(115200);
 
-   REFER.m_macaddress = macaddress;
-   REFER.m_servicetype = servicetype;
+    REFER.m_macaddress = macaddress;
+    REFER.m_servicetype = servicetype;
 
-       // Add your initialization code here
-       OC_LOG_INIT();
+    // Add your initialization code here
+    OC_LOG_INIT();
 
-       OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
+    OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
 
-       // Connect to Ethernet or WiFi network
-       if (ConnectToNetwork() != 0)
-       {
-               OC_LOG(ERROR, TAG, "Unable to connect to network");
-               return;
-       }
+    // Connect to Ethernet or WiFi network
+    if (ConnectToNetwork() != 0)
+    {
+        OC_LOG(ERROR, TAG, "Unable to connect to network");
+        return;
+    }
 
-       // Initialize the OC Stack in Server mode
-       if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
-       {
-               OC_LOG(ERROR, TAG, PCF("OCStack init error"));
-               return;
-       }
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack init error"));
+        return;
+    }
 
     OCStartPresence(60);
-       // Declare and create the example resource: PROXI
-       createREFERResource();
+    // Declare and create the example resource: PROXI
+    createREFERResource();
 
-       ble.init( (long)115200, BLE_SLAVER,  REFER.m_macaddress);
+    ble.init( (long)115200, BLE_SLAVER,  REFER.m_macaddress);
 
-//     ble.StatusRead();
+//  ble.StatusRead();
 
-       char str0[] = JSON_BASE00;
-       char str1[] = JSON_BASE01;
-       char str2[] = JSON_BASE02;
-       char str3[] = JSON_BASE03;
+    char str0[] = JSON_BASE00;
+    char str1[] = JSON_BASE01;
+    char str2[] = JSON_BASE02;
+    char str3[] = JSON_BASE03;
 
-       base_length = strlen(str0)+ strlen(str1)+ strlen(str2)+ strlen(str3);
+    base_length = strlen(str0) + strlen(str1) + strlen(str2) + strlen(str3);
 
-       OC_LOG_V(INFO, TAG, "Program Start-\r\n");
+    OC_LOG_V(INFO, TAG, "Program Start-\r\n");
 }
 
 // The loop function is called in an endless loop
@@ -237,72 +218,75 @@ void loop()
 
     // This call displays the amount of free SRAM available on Arduino
     PrintArduinoMemoryStats();
-       delay(5000);
-       if (OCProcess() != OC_STACK_OK)
-       {
-               OC_LOG(ERROR, TAG, PCF("OCStack process error"));
-               return;
-       }
-       ChangeREFERRepresentation(NULL);
-
-       char* user_msg = NULL;
-       user_msg = ble.Debug2BLE( true );
-       ble.BLE2Debug( true );
-
-       if ( user_msg )
-       {
-               free( user_msg );
-               user_msg = NULL;
-       }
+    delay(5000);
+    if (OCProcess() != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack process error"));
+        return;
+    }
+    ChangeREFERRepresentation(NULL);
+
+    char *user_msg = NULL;
+    user_msg = ble.Debug2BLE( true );
+    ble.BLE2Debug( true );
+
+    if ( user_msg )
+    {
+        free( user_msg );
+        user_msg = NULL;
+    }
 }
 
-void createREFERResource() {
+void createREFERResource()
+{
 
     OCStackResult res = OCCreateResource(&REFER.m_handle,
-                                         "SoftSensorManager.Sensor",
-                                         "oc.mi.def",
+                                         "SSManager.Sensor",
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          "/Reference_Thing",
                                          OCEntityHandlerCb,
-                                         OC_DISCOVERABLE|OC_OBSERVABLE);
+                                         OC_DISCOVERABLE | OC_OBSERVABLE);
     OC_LOG_V(INFO, TAG, "Created REFER resource with result: %s", getResult(res));
 }
 
-const char *getResult(OCStackResult result) {
-    switch (result) {
-    case OC_STACK_OK:
-        return "OC_STACK_OK";
-    case OC_STACK_INVALID_URI:
-        return "OC_STACK_INVALID_URI";
-    case OC_STACK_INVALID_QUERY:
-        return "OC_STACK_INVALID_QUERY";
-    case OC_STACK_INVALID_IP:
-        return "OC_STACK_INVALID_IP";
-    case OC_STACK_INVALID_PORT:
-        return "OC_STACK_INVALID_PORT";
-    case OC_STACK_INVALID_CALLBACK:
-        return "OC_STACK_INVALID_CALLBACK";
-    case OC_STACK_INVALID_METHOD:
-        return "OC_STACK_INVALID_METHOD";
-    case OC_STACK_NO_MEMORY:
-        return "OC_STACK_NO_MEMORY";
-    case OC_STACK_COMM_ERROR:
-        return "OC_STACK_COMM_ERROR";
-    case OC_STACK_INVALID_PARAM:
-        return "OC_STACK_INVALID_PARAM";
-    case OC_STACK_NOTIMPL:
-        return "OC_STACK_NOTIMPL";
-    case OC_STACK_NO_RESOURCE:
-        return "OC_STACK_NO_RESOURCE";
-    case OC_STACK_RESOURCE_ERROR:
-        return "OC_STACK_RESOURCE_ERROR";
-    case OC_STACK_SLOW_RESOURCE:
-        return "OC_STACK_SLOW_RESOURCE";
-    case OC_STACK_NO_OBSERVERS:
-        return "OC_STACK_NO_OBSERVERS";
-    case OC_STACK_ERROR:
-        return "OC_STACK_ERROR";
-    default:
-        return "UNKNOWN";
+const char *getResult(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
     }
 }
 
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/trackee.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/trackee.cpp
new file mode 100644 (file)
index 0000000..82780a5
--- /dev/null
@@ -0,0 +1,263 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+#include "bleLib.h"
+#include <stdio.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#include "oic_lanLib.h"
+
+// proximity code s
+#define DATA_EA     400
+#define SLAVER_EA   2
+
+#define ARDUINO_AVR_MEGA2560 1
+/// This is the port which Arduino Server will use for all unicast communication with it's peers
+#define OC_WELL_KNOWN_PORT 5683
+
+PROGMEM const char TAG[] = "TrackeeSensor";
+
+OCResourceHandle m_handle;
+
+
+
+Cble ble;
+char trackeeID[13] = "9059AF16FEF7";
+int slaver_num = 0;
+//char slaveList[SLAVER_EA][13]={"9059AF1700EE"};
+char slaveList[SLAVER_EA][13] = {"9059AF1700EE", "34B1F7D004D2"};
+int g_PROXIUnderObservation = 0;
+
+
+
+const char *getResult(OCStackResult result);
+void createResource();
+
+
+#define LENGTH_VAR      50
+bool JsonGenerator( char *jsonBuf, uint16_t buf_length )
+{
+
+    return true;
+
+}
+
+
+// On Arduino Atmel boards with Harvard memory architecture, the stack grows
+// downwards from the top and the heap grows upwards. This method will print
+// the distance(in terms of bytes) between those two.
+// See here for more details :
+// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
+void PrintArduinoMemoryStats()
+{
+#ifdef ARDUINO_AVR_MEGA2560
+    //This var is declared in avr-libc/stdlib/malloc.c
+    //It keeps the largest address not allocated for heap
+    extern char *__brkval;
+    //address of tmp gives us the current stack boundry
+    int tmp;
+    OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+    OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+             ((unsigned int)&tmp - (unsigned int)__brkval));
+#endif
+}
+
+// This is the entity handler for the registered resource.
+// This is invoked by OCStack whenever it recevies a request for this resource.
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest *entityHandlerRequest )
+{
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+
+    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
+        if (OC_REST_GET == entityHandlerRequest->method)
+        {
+            if ( JsonGenerator( (char *)entityHandlerRequest->resJSONPayload,
+                                entityHandlerRequest->resJSONPayloadLen ) == false )
+            {
+                ehRet  = OC_EH_ERROR;
+            }
+        }
+        if (OC_REST_PUT == entityHandlerRequest->method)
+        {
+            if (JsonGenerator( (char *)entityHandlerRequest->resJSONPayload,
+                               entityHandlerRequest->resJSONPayloadLen ) == false )
+            {
+                ehRet  = OC_EH_ERROR;
+            }
+        }
+    }
+    else if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
+    {
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
+            g_PROXIUnderObservation = 1;
+        }
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
+        }
+    }
+
+    Serial.println((char *)entityHandlerRequest->resJSONPayload);
+
+    return ehRet;
+}
+
+
+
+
+
+
+
+//The setup function is called once at startup of the sketch
+void setup()
+{
+    Serial.begin(115200);
+
+    // Add your initialization code here
+    OC_LOG_INIT();
+
+    OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
+    //    uint16_t port = OC_WELL_KNOWN_PORT;
+
+    // Connect to Ethernet or WiFi network
+    if (ConnectToNetwork() != 0)
+    {
+        OC_LOG(ERROR, TAG, "Unable to connect to network");
+        return;
+    }
+
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack init error"));
+        return;
+    }
+
+    // Declare and create the example resource
+    createResource();
+
+    // This call displays the amount of free SRAM available on Arduino
+    PrintArduinoMemoryStats();
+
+    ble.init( (long)115200, BLE_SLAVER, slaveList[0]);
+
+
+//  ble.StatusRead();
+
+    OC_LOG_V(INFO, TAG, "Program Start-\r\n");
+}
+
+
+// The loop function is called in an endless loop
+void loop()
+{
+    // This artificial delay is kept here to avoid endless spinning
+    // of Arduino microcontroller. Modify it as per specfic application needs.
+
+    if (OCProcess() != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack process error"));
+        return;
+    }
+
+    char *user_cmd = NULL;
+
+//  ble.pollingDisconnect();
+
+    user_cmd = ble.Debug2BLE(true);
+    ble.BLE2Debug( true );
+
+    if ( user_cmd )
+    {
+        free( user_cmd );
+        user_cmd = NULL;
+    }
+
+}
+
+
+
+
+
+
+
+void createResource()
+{
+
+    OCStackResult res = OCCreateResource(&m_handle,
+                                         "SSManager.Sensor",
+                                         OC_RSRVD_INTERFACE_DEFAULT,
+                                         "/Tracker_Thing",
+                                         OCEntityHandlerCb,
+                                         OC_DISCOVERABLE | OC_OBSERVABLE);
+    OC_LOG_V(INFO, TAG, "Created PROXI resource with result: %s", getResult(res));
+}
+
+const char *getResult(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
+    }
+}
+
diff --git a/service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/makefile
deleted file mode 100644 (file)
index 0d7011d..0000000
+++ /dev/null
@@ -1,126 +0,0 @@
-# //******************************************************************
-# //
-# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // Licensed under the Apache License, Version 2.0 (the "License");
-# // you may not use this file except in compliance with the License.
-# // You may obtain a copy of the License at
-# //
-# //      http://www.apache.org/licenses/LICENSE-2.0
-# //
-# // Unless required by applicable law or agreed to in writing, software
-# // distributed under the License is distributed on an "AS IS" BASIS,
-# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# // See the License for the specific language governing permissions and
-# // limitations under the License.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
--include ../../../../build/arduino/environment.mk
-ARDUINO_DIR = /usr/share/arduino
-
-BUILD := release
-PLATFORM := arduinomega
-ARDUINO_PORT := ttyACM0
-
-SRC_PATH=../src
-# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
-ARDUINOWIFI := 0
-
-APP_NAME := thserver
-
-TB_DIR = ../../../../../../resource/csdk
-LOGGER_DIR = $(TB_DIR)/logger
-OC_LOG_DIR = $(TB_DIR)/../oc_logger
-TBSTACK_DIR = $(TB_DIR)/stack
-TBSOCKET_DIR = $(TB_DIR)/ocsocket
-
-include $(TB_DIR)/local.properties
-include $(TB_DIR)/$(PLATFORM).properties
-
-VPATH := $(SDIR_ARD_PLATFORM)
-
-#include directories
-OCSOCK_DIR = $(TB_DIR)/ocsocket
-LOGGER_DIR = $(TB_DIR)/logger
-STACK_DIR  = $(TB_DIR)/stack
-INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include
-
-CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
-CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
-
-CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
-
-ifeq ($(ARDUINOWIFI),1)
-       CFLAGS += -DARDUINOWIFI
-       ARDUINO_SHIELD_TYPE := "/wifi_shield"
-       TRANSPORT_OBJS = $(WIFI_COBJ)
-else
-       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
-       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
-endif
-
-OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
-
-OBJ_DIR := $(OUT_DIR)/bin
-
-all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-
-core.a: $(PLATFORM_OBJS)
-       @cd $(OBJ_DIR) && $(AR) -x ../../../../$(TB_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a
-       $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o
-       @cd $(OBJ_DIR) && $(RANLIB) $@
-
-prep_dirs:
-       -mkdir $(PLATFORM)
-       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
-       -mkdir $(OUT_DIR)
-       -mkdir $(OBJ_DIR)
-
-%.o: %.c
-       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-%.o: %.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ 
-%.o: ${SRC_PATH}/%.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-
-$(APP_NAME).elf: $(APP_NAME).o core.a
-ifeq ($(PLATFORM),arduinomega)
-       $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-$(APP_NAME).hex: $(APP_NAME).elf
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep
-       $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-install: all
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i
-else ifeq ($(PLATFORM),arduinodue)
-       stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb
-       $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-.PHONY: clean
-
-clean: legacy_clean
-       rm -rf arduinomega
-       rm -rf arduinodue
-
-legacy_clean:
-       @rm -rf bin
-       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
index fe41441..5d6ca84 100644 (file)
@@ -1,22 +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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
 
 // Do not remove the include below
 #include "Arduino.h"
@@ -68,23 +68,23 @@ static uint16_t OC_WELL_KNOWN_PORT = 5683;
 
 char temp[100];
 
-#define LENGTH_VAR             100
+#define LENGTH_VAR      100
 static int base_length = 0;
 
-bool JsonGenerator( THResource& th, char* jsonBuf, uint16_t buf_length )
+bool JsonGenerator( THResource &th, char *jsonBuf, uint16_t buf_length )
 {
-       if( (buf_length - base_length) < LENGTH_VAR )
-       {
-               OC_LOG_V(ERROR, TAG, "Error : length is very long.");
-               return false;
-       }
+    if ( (buf_length - base_length) < LENGTH_VAR )
+    {
+        OC_LOG_V(ERROR, TAG, "Error : length is very long.");
+        return false;
+    }
 
-       sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%d",th.m_temp);
-       sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%d"JSON_BASE03, th.m_humid);
+    sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%d", th.m_temp);
+    sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%d"JSON_BASE03, th.m_humid);
 
-       Serial.println(jsonBuf);
+    Serial.println(jsonBuf);
 
-       return true;
+    return true;
 }
 
 byte read_dht11_dat()
@@ -193,26 +193,27 @@ void PrintArduinoMemoryStats()
 
 // This is the entity handler for the registered resource.
 // This is invoked by OCStack whenever it recevies a request for this resource.
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest *entityHandlerRequest )
 {
     OCEntityHandlerResult ehRet = OC_EH_OK;
     OCEntityHandlerResponse response = {0};
     char payload[MAX_RESPONSE_LENGTH] = {0};
 
-    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
     {
         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
-        if(OC_REST_GET == entityHandlerRequest->method)
+        if (OC_REST_GET == entityHandlerRequest->method)
         {
-               if(JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
-                {
-                }
-           else
+            if (JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
+            {
+            }
+            else
             {
                 ehRet = OC_EH_ERROR;
             }
         }
-        if(OC_REST_PUT == entityHandlerRequest->method)
+        if (OC_REST_PUT == entityHandlerRequest->method)
         {
             //Do something with the 'put' payload
             if (JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
@@ -222,29 +223,30 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
             {
                 ehRet = OC_EH_ERROR;
             }
-         }
+        }
 
         if (ehRet == OC_EH_OK)
-               {
-                       // Format the response.  Note this requires some info about the request
-                       response.requestHandle = entityHandlerRequest->requestHandle;
-                       response.resourceHandle = entityHandlerRequest->resource;
-                       response.ehResult = ehRet;
-                       response.payload = (unsigned char *)payload;
-                       response.payloadSize = strlen(payload);
-                       response.numSendVendorSpecificHeaderOptions = 0;
-                       memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
-                       memset(response.resourceUri, 0, sizeof response.resourceUri);
-                       // Indicate that response is NOT in a persistent buffer
-                       response.persistentBufferFlag = 0;
-
-                       // Send the response
-                       if (OCDoResponse(&response) != OC_STACK_OK)
-                       {
-                               OC_LOG(ERROR, TAG, "Error sending response");
-                               ehRet = OC_EH_ERROR;
-                       }
-               }
+        {
+            // Format the response.  Note this requires some info about the request
+            response.requestHandle = entityHandlerRequest->requestHandle;
+            response.resourceHandle = entityHandlerRequest->resource;
+            response.ehResult = ehRet;
+            response.payload = (unsigned char *)payload;
+            response.payloadSize = strlen(payload);
+            response.numSendVendorSpecificHeaderOptions = 0;
+            memset(response.sendVendorSpecificHeaderOptions, 0,
+                   sizeof response.sendVendorSpecificHeaderOptions);
+            memset(response.resourceUri, 0, sizeof response.resourceUri);
+            // Indicate that response is NOT in a persistent buffer
+            response.persistentBufferFlag = 0;
+
+            // Send the response
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, TAG, "Error sending response");
+                ehRet = OC_EH_ERROR;
+            }
+        }
     }
     if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
     {
@@ -319,7 +321,7 @@ void *ChangeTHRepresentation (void *param)
         TH.m_humid = dht11_dat[0];
         TH.m_temp = dht11_dat[2];
 
-           if (g_THUnderObservation)
+        if (g_THUnderObservation)
         {
             OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.m_humid);
             OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.m_temp);
@@ -392,9 +394,9 @@ void createTHResource()
     TH.m_temp = 0;
 
     OCStackResult res = OCCreateResource(&TH.m_handle,
-                                         "SoftSensorManager.Sensor",
-                                         "oc.mi.def",
-                                         "/Thing_TempHumSensor1",
+                                         "SSManager.Sensor",
+                                         OC_RSRVD_INTERFACE_DEFAULT,
+                                         "/Thing_TempHumSensor",
                                          OCEntityHandlerCb,
                                          OC_DISCOVERABLE | OC_OBSERVABLE);
     OC_LOG_V(INFO, TAG, "Created TH resource with result: %s", getResult(res));
diff --git a/service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/readme.txt b/service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/readme.txt
new file mode 100644 (file)
index 0000000..7c041e1
--- /dev/null
@@ -0,0 +1,19 @@
+
+Followings should be done befor building Arudno applications 
+
+1. Applications on arduino conform  the Iotivity Base released on 22-Aug-2014.
+   (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6]))
+
+   For successful execution, you have to copy the file, local.properties, into the following pathes:
+    - oic-resource/csdk/
+    - oic-resource/csdk/libcoap-4.1.1
+
+
+2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings
+
+   Makefile path:  / oic-resource / csdk / libcoap-4.1.1 / makefile
+
+   path to be modified: 
+  
+     - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h
+     - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/thserver.cpp b/service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/thserver.cpp
new file mode 100644 (file)
index 0000000..047ee14
--- /dev/null
@@ -0,0 +1,444 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+// Do not remove the include below
+#include "Arduino.h"
+
+#define dht11_pin 12
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+const char *getResult(OCStackResult result);
+
+PROGMEM const char TAG[] = "ArduinoServer";
+
+int g_THUnderObservation = 0;
+void createTHResource();
+typedef struct THRESOURCE
+{
+    OCResourceHandle m_handle;
+    int m_temp;
+    int m_humid;
+} THResource;
+
+static THResource TH;
+
+/// This is the port which Arduino Server will use for all unicast communication with it's peers
+static uint16_t OC_WELL_KNOWN_PORT = 5683;
+
+#define JSON_BASE00 "{\"href\":\"\",\"rep\":{"
+#define JSON_BASE01 "\"0\":\"temperature\",\"1\":\"int\",\"2\":\""
+#define JSON_BASE02 "\",\"3\":\"humidity\",\"4\":\"int\",\"5\":\""
+#define JSON_BASE03 "\"}}"
+
+char temp[100];
+
+#define LENGTH_VAR      100
+static int base_length = 0;
+
+bool JsonGenerator( THResource &th, char *jsonBuf, uint16_t buf_length )
+{
+    if ( (buf_length - base_length) < LENGTH_VAR )
+    {
+        OC_LOG_V(ERROR, TAG, "Error : length is very long.");
+        return false;
+    }
+
+    sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%d", th.m_temp);
+    sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%d"JSON_BASE03, th.m_humid);
+
+    Serial.println(jsonBuf);
+
+    return true;
+}
+
+byte read_dht11_dat()
+{
+    byte i = 0;
+    byte result = 0;
+    for (i = 0; i < 8; i++)
+    {
+        while (!digitalRead(dht11_pin));
+        delayMicroseconds(30);
+        if (digitalRead(dht11_pin) != 0 )
+            bitSet(result, 7 - i);
+        while (digitalRead(dht11_pin));
+    }
+    return result;
+}
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+
+/// WiFi Shield firmware with Intel patches
+static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
+
+/// WiFi network info and credentials
+char ssid[] = "SoftSensor_AP";
+char pass[] = "1234567890";
+
+//char ssid[] = "Iotivity-1";
+//char pass[] = "1234567890";
+
+int ConnectToNetwork()
+{
+    char *fwVersion;
+    int status = WL_IDLE_STATUS;
+    // check for the presence of the shield:
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
+        return -1;
+    }
+
+    // Verify that WiFi Shield is running the firmware with all UDP fixes
+    fwVersion = WiFi.firmwareVersion();
+    OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
+    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) != 0 )
+    {
+        OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
+        return -1;
+    }
+
+    // attempt to connect to Wifi network:
+    while (status != WL_CONNECTED)
+    {
+        OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
+        status = WiFi.begin(ssid, pass);
+
+        // wait 10 seconds for connection:
+        delay(10000);
+    }
+    OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
+
+    IPAddress ip = WiFi.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#else
+// Arduino Ethernet Shield
+int ConnectToNetwork()
+{
+    // Note: ****Update the MAC address here with your shield's MAC address****
+    uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAC};
+
+    uint8_t error = Ethernet.begin(ETHERNET_MAC);
+    if (error  == 0)
+    {
+        OC_LOG_V(ERROR, TAG, "error is: %d", error);
+        return -1;
+    }
+    IPAddress ip = Ethernet.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#endif //ARDUINOWIFI
+
+// On Arduino Atmel boards with Harvard memory architecture, the stack grows
+// downwards from the top and the heap grows upwards. This method will print
+// the distance(in terms of bytes) between those two.
+// See here for more details :
+// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
+void PrintArduinoMemoryStats()
+{
+#ifdef ARDUINO_AVR_MEGA2560
+    //This var is declared in avr-libc/stdlib/malloc.c
+    //It keeps the largest address not allocated for heap
+    extern char *__brkval;
+    //address of tmp gives us the current stack boundry
+    int tmp;
+    OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+    OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+             ((unsigned int)&tmp - (unsigned int)__brkval));
+#endif
+}
+
+
+// This is the entity handler for the registered resource.
+// This is invoked by OCStack whenever it recevies a request for this resource.
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest *entityHandlerRequest )
+{
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+    OCEntityHandlerResponse response = {0};
+    char payload[MAX_RESPONSE_LENGTH] = {0};
+
+    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
+        if (OC_REST_GET == entityHandlerRequest->method)
+        {
+            if (JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
+            {
+            }
+            else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+        }
+        if (OC_REST_PUT == entityHandlerRequest->method)
+        {
+            //Do something with the 'put' payload
+            if (JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
+            {
+            }
+            else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+        }
+
+        if (ehRet == OC_EH_OK)
+        {
+            // Format the response.  Note this requires some info about the request
+            response.requestHandle = entityHandlerRequest->requestHandle;
+            response.resourceHandle = entityHandlerRequest->resource;
+            response.ehResult = ehRet;
+            response.payload = (unsigned char *)payload;
+            response.payloadSize = strlen(payload);
+            response.numSendVendorSpecificHeaderOptions = 0;
+            memset(response.sendVendorSpecificHeaderOptions, 0,
+                   sizeof response.sendVendorSpecificHeaderOptions);
+            memset(response.resourceUri, 0, sizeof response.resourceUri);
+            // Indicate that response is NOT in a persistent buffer
+            response.persistentBufferFlag = 0;
+
+            // Send the response
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OC_LOG(ERROR, TAG, "Error sending response");
+                ehRet = OC_EH_ERROR;
+            }
+        }
+    }
+    if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
+    {
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
+            g_THUnderObservation = 1;
+        }
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
+        }
+    }
+
+    return ehRet;
+}
+
+// This method is used to display 'Observe' functionality of OC Stack.
+static uint8_t modCounter = 0;
+void *ChangeTHRepresentation (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.
+    {
+
+        byte dht11_dat[5];
+        byte i;// start condition
+
+        digitalWrite(dht11_pin, LOW);
+        delay(18);
+        digitalWrite(dht11_pin, HIGH);
+        delayMicroseconds(1);
+        pinMode(dht11_pin, INPUT);
+        delayMicroseconds(40);
+
+        if (digitalRead(dht11_pin))
+        {
+            Serial.println("dht11 start condition 1 not met"); // wait for DHT response signal: LOW
+            delay(1000);
+            return NULL;
+        }
+        delayMicroseconds(80);
+        if (!digitalRead(dht11_pin))
+        {
+            Serial.println("dht11 start condition 2 not met");  //wair for second response signal:HIGH
+            return NULL;
+        }
+
+        delayMicroseconds(80);// now ready for data reception
+        for (i = 0; i < 5; i++)
+        {
+            dht11_dat[i] = read_dht11_dat();
+        }  //recieved 40 bits data. Details are described in datasheet
+
+        pinMode(dht11_pin, OUTPUT);
+        digitalWrite(dht11_pin, HIGH);
+        byte dht11_check_sum = dht11_dat[0] + dht11_dat[2]; // check check_sum
+        if (dht11_dat[4] != dht11_check_sum)
+        {
+            Serial.println("DHT11 checksum error");
+        }
+        Serial.print("Current humdity = ");
+        Serial.print(dht11_dat[0], DEC);
+        Serial.print("%  ");
+        Serial.print("temperature = ");
+        Serial.print(dht11_dat[2], DEC);
+        Serial.println("C  ");
+
+        TH.m_humid = dht11_dat[0];
+        TH.m_temp = dht11_dat[2];
+
+        if (g_THUnderObservation)
+        {
+            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.m_humid);
+            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.m_temp);
+
+            result = OCNotifyAllObservers (TH.m_handle, OC_NA_QOS);
+
+            if (OC_STACK_NO_OBSERVERS == result)
+            {
+                g_THUnderObservation = 0;
+            }
+        }
+    }
+    return NULL;
+}
+
+
+
+//The setup function is called once at startup of the sketch
+void setup()
+{
+    pinMode(dht11_pin, OUTPUT);
+    digitalWrite(dht11_pin, HIGH);
+
+    // Add your initialization code here
+    OC_LOG_INIT();
+
+    OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
+    uint16_t port = OC_WELL_KNOWN_PORT;
+
+    // Connect to Ethernet or WiFi network
+    if (ConnectToNetwork() != 0)
+    {
+        OC_LOG(ERROR, TAG, "Unable to connect to network");
+        return;
+    }
+
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack init error"));
+        return;
+    }
+    OCStartPresence(60);
+    // Declare and create the example resource: TH
+    createTHResource();
+
+}
+
+// The loop function is called in an endless loop
+void loop()
+{
+    // This artificial delay is kept here to avoid endless spinning
+    // of Arduino microcontroller. Modify it as per specfic application needs.
+    delay(2000);
+
+    // This call displays the amount of free SRAM available on Arduino
+    PrintArduinoMemoryStats();
+
+    if (OCProcess() != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack process error"));
+        return;
+    }
+    ChangeTHRepresentation(NULL);
+}
+
+void createTHResource()
+{
+    TH.m_humid = 0;
+    TH.m_temp = 0;
+
+    OCStackResult res = OCCreateResource(&TH.m_handle,
+                                         "SSManager.Sensor",
+                                         OC_RSRVD_INTERFACE_DEFAULT,
+                                         "/Thing_TempHumSensor1",
+                                         OCEntityHandlerCb,
+                                         OC_DISCOVERABLE | OC_OBSERVABLE);
+    OC_LOG_V(INFO, TAG, "Created TH resource with result: %s", getResult(res));
+}
+
+const char *getResult(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
+    }
+}
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile
deleted file mode 100644 (file)
index d21b780..0000000
+++ /dev/null
@@ -1,130 +0,0 @@
-# //******************************************************************
-# //
-# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // Licensed under the Apache License, Version 2.0 (the "License");
-# // you may not use this file except in compliance with the License.
-# // You may obtain a copy of the License at
-# //
-# //      http://www.apache.org/licenses/LICENSE-2.0
-# //
-# // Unless required by applicable law or agreed to in writing, software
-# // distributed under the License is distributed on an "AS IS" BASIS,
-# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# // See the License for the specific language governing permissions and
-# // limitations under the License.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
--include ../../../../build/arduino/environment.mk
-ARDUINO_DIR = /usr/share/arduino
-
-BUILD := release
-PLATFORM := arduinomega
-ARDUINO_PORT := ttyACM0
-
-SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
-OBJPATH=${SRCLIST:.cpp=.o}
-OBJLIST=${notdir ${OBJPATH}}
-
-SRC_PATH=../src
-# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
-ARDUINOWIFI := 0
-
-APP_NAME := trackee
-
-TB_DIR = ../../../../../../resource/csdk
-LOGGER_DIR = $(TB_DIR)/logger
-OC_LOG_DIR = $(TB_DIR)/../oc_logger
-TBSTACK_DIR = $(TB_DIR)/stack
-TBSOCKET_DIR = $(TB_DIR)/ocsocket
-
-include $(TB_DIR)/local.properties
-include $(TB_DIR)/$(PLATFORM).properties
-
-VPATH := $(SDIR_ARD_PLATFORM)
-
-#include directories
-OCSOCK_DIR = $(TB_DIR)/ocsocket
-LOGGER_DIR = $(TB_DIR)/logger
-STACK_DIR  = $(TB_DIR)/stack
-INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include -I../include
-
-CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
-CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
-
-CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
-
-ifeq ($(ARDUINOWIFI),1)
-       CFLAGS += -DARDUINOWIFI
-       ARDUINO_SHIELD_TYPE := "/wifi_shield"
-       TRANSPORT_OBJS = $(WIFI_COBJ)
-else
-       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
-       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
-endif
-
-OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
-
-OBJ_DIR := $(OUT_DIR)/bin
-
-all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-
-core.a: $(PLATFORM_OBJS)
-       @cd $(OBJ_DIR) && $(AR) -x ../../../../$(TB_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a
-       $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o
-       @cd $(OBJ_DIR) && $(RANLIB) $@
-
-prep_dirs:
-       -mkdir $(PLATFORM)
-       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
-       -mkdir $(OUT_DIR)
-       -mkdir $(OBJ_DIR)
-
-%.o: %.c
-       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-%.o: %.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ 
-%.o: ${SRC_PATH}/%.cpp
-       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
-
-$(APP_NAME).elf: $(OBJLIST) core.a
-ifeq ($(PLATFORM),arduinomega)
-       $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-$(APP_NAME).hex: $(APP_NAME).elf
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep
-       $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else ifeq ($(PLATFORM),arduinodue)
-       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-install: all
-ifeq ($(PLATFORM),arduinomega)
-       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i
-else ifeq ($(PLATFORM),arduinodue)
-       stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb
-       $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R
-else
-       $(error Wrong value for PLATFORM !!)
-endif
-
-.PHONY: clean
-
-clean: legacy_clean
-       rm -rf arduinomega
-       rm -rf arduinodue
-
-legacy_clean:
-       @rm -rf bin
-       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
index 8356098..a543229 100644 (file)
@@ -1,82 +1,95 @@
-/*
- * bleLib.h
- *
- *  Created on: 2014. 11. 5.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #ifndef BLELIB_H_
 #define BLELIB_H_
 
 #include "Arduino.h"
 
-#define BLE_NOCHANGE   -1
-#define BLE_MASTER             1
-#define BLE_SLAVER             0
+#define BLE_NOCHANGE    -1
+#define BLE_MASTER      1
+#define BLE_SLAVER      0
 
-#define BLE_DISCON             200
-#define BLE_NODATA             100
+#define BLE_DISCON      200
+#define BLE_NODATA      100
 
 
 /***************************************
  *
- *     HM-10 BLE Module Control Class.
- *     Target Board : Arduino-Mega.
+ *  HM-10 BLE Module Control Class.
+ *  Target Board : Arduino-Mega.
  *
  **************************************/
 class Cble
 {
-public :
-       /***
-        * BLE Control Function.
-        */
-       // BLE initialization ( COM baud rate , BLE Master , Slave setting. )
-       void init(long baudRate, int ble_mode, char* SelfMaxAddr);
-
-       void StatusRead( void );
-
-       bool IsSelfArduino( void );
-
-       bool IsConnected( void );
-
-       bool pollingConnect( const char* maxAddr );
-
-       void pollingDisconnect( void );
-       // Get RSSI by BLE communication. (polling method.)
-       int pollingGetRSSI( void );
-       // Send Request to BLE Module. And, Get the response. (polling method.)
-       bool pollingRequest(const char* request, char* data, int dataLen);
-
-       int mustHaveRequest(const char* request, char* data, int dataLen);
-
-       void streamDummy( char* data, int dataLen);
-
-       /***
-        * Debug COM port to BLE COM port.
-        * BLE COM port to Debug COM port.
-        */
-       // BLE Module to Debug Serial port.
-       void BLE2Debug( int autoDiscon );
-       // Debug Serial port to BLE Module.
-       char* Debug2BLE( int BLEwrite );
-
-       /***
-        * If you first setting, you need next-function.
-        */
-       // Restore to factory setting data.
-       void FactoryReset( void );
-       // First setting of COM port.
-       void firstUartSetting( void );
+    public :
+        /***
+         * BLE Control Function.
+         */
+        // BLE initialization ( COM baud rate , BLE Master , Slave setting. )
+        void init(long baudRate, int ble_mode, char *SelfMaxAddr);
+
+        void StatusRead( void );
+
+        bool IsSelfArduino( void );
+
+        bool IsConnected( void );
+
+        bool pollingConnect( const char *maxAddr );
+
+        void pollingDisconnect( void );
+        // Get RSSI by BLE communication. (polling method.)
+        int pollingGetRSSI( void );
+        // Send Request to BLE Module. And, Get the response. (polling method.)
+        bool pollingRequest(const char *request, char *data, int dataLen);
+
+        int mustHaveRequest(const char *request, char *data, int dataLen);
+
+        void streamDummy( char *data, int dataLen);
+
+        /***
+         * Debug COM port to BLE COM port.
+         * BLE COM port to Debug COM port.
+         */
+        // BLE Module to Debug Serial port.
+        void BLE2Debug( int autoDiscon );
+        // Debug Serial port to BLE Module.
+        char *Debug2BLE( int BLEwrite );
+
+        /***
+         * If you first setting, you need next-function.
+         */
+        // Restore to factory setting data.
+        void FactoryReset( void );
+        // First setting of COM port.
+        void firstUartSetting( void );
 };
 
 
 
 #if 0
-#define debug_printf(...)      {                                                       \
-       char* __temp__ = (char*)malloc(sizeof(char)*2048);              \
-       sprintf(__temp__, __VA_ARGS__ );                                        \
-       Serial.print(__temp__);                                                                 \
-       free(__temp__);                                                                                                 \
+#define debug_printf(...)   {                           \
+    char* __temp__ = (char*)malloc(sizeof(char)*2048);      \
+    sprintf(__temp__, __VA_ARGS__ );                    \
+    Serial.print(__temp__);                                 \
+    free(__temp__);                                                 \
 }
 #else
 #define debug_printf(...)
index 8e8666a..6d323ad 100644 (file)
@@ -1,18 +1,31 @@
-/*
- * proximity.h
- *
- *  Created on: 2014. 11. 13.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #ifndef PROXIMITY_H_
 #define PROXIMITY_H_
 
 
-#define arraysize      6
-#define RSSI_EA                3
+#define arraysize   6
+#define RSSI_EA     3
 
-float CalculateExponentialAverage(int numberOfSamples, intarray, int startindex, int flag);
+float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag);
 
 float calculateDistance(float avgRSSI, float txPower);
 
index 4271904..a1cd5f4 100644 (file)
@@ -1,15 +1,28 @@
-/*
- * trackee.h
- *
- *  Created on: 2014. 11. 18.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #ifndef TRACKEE_H_
 #define TRACKEE_H_
 
 
-#define ARDUINO                0
+#define ARDUINO     0
 
 
 #endif /* TRACKEE_H_ */
index 31cf5da..a9ad9df 100644 (file)
-/*
- * blsLib.cpp
- *
- *  Created on: 2014. 11. 5.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #include "bleLib.h"
 #include <stdarg.h>
 #include "trackee.h"
 
-//#define __INTERNAL_DEBUG__           1
+//#define __INTERNAL_DEBUG__        1
 
 PROGMEM const char TAG[] = "TrackeeSensor";
-#define LIMIT_COUNT                    100
-#define DUMMY_SIZE                     30
-#define DEBUG_SIZE                     DUMMY_SIZE
+#define LIMIT_COUNT         100
+#define DUMMY_SIZE          30
+#define DEBUG_SIZE          DUMMY_SIZE
 #if (ARDUINO != 0)
-#define SERIAL_SIZE                    100
+#define SERIAL_SIZE         100
 #endif
 
-#define BLE            Serial2
+#define BLE     Serial2
 
 bool isConnected = false;
-int SerialCnt=0;
-int BLECnt=0;
+int SerialCnt = 0;
+int BLECnt = 0;
 char SelfMaxaddr[19] = {0,};
 
-char debugD[DEBUG_SIZE]={0,};
+char debugD[DEBUG_SIZE] = {0,};
 
 #if (ARDUINO != 0)
-char SerialData[SERIAL_SIZE]={0,};
-char BLEData[SERIAL_SIZE]={0,};
+char SerialData[SERIAL_SIZE] = {0,};
+char BLEData[SERIAL_SIZE] = {0,};
 #endif
 
-// baudRate이 115200이면, 주의해야한다.
-// Arduino Chip은 16bit Process 이므로 int형의 사이즈가 4byte형 signed int이다.
-void Cble::init(long baudRate, int ble_mode, char* SelfMaxAddr)
+void Cble::init(long baudRate, int ble_mode, char *SelfMaxAddr)
 {
-       debug_printf("BLE shiled is initialed.-\r\n");
-
-       if(SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE )
-       {
-               debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n");
-               exit(-1);
-       }
-       sprintf(SelfMaxaddr, "%s",SelfMaxAddr);
-
-       BLE.begin(baudRate);
-       BLE.setTimeout(1);
-       delay(1000);
-
-       memset(debugD,0,DEBUG_SIZE);
-
-       if( ble_mode != BLE_NOCHANGE )
-       {
-               while( IsSelfArduino() == false )
-                       this->pollingDisconnect();
-       }
-
-       if( ble_mode == BLE_MASTER )
-       {
-               pollingRequest("AT+ROLE1", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+MODE0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+NOTI0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-       }
-       else if ( ble_mode == BLE_SLAVER )
-       {
-               pollingRequest("AT+ROLE0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+MODE2", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-               delay(150);
-               pollingRequest("AT+NOTI0", debugD, 8);
-               memset(debugD, 0, DEBUG_SIZE);
-       }
-
-       if( ble_mode != BLE_NOCHANGE )
-       {
-               while( IsSelfArduino() == false )
-                       this->pollingDisconnect();
-       }
-
-       delay(250);
+    debug_printf("BLE shiled is initialed.-\r\n");
+
+    if (SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE )
+    {
+        debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n");
+        exit(-1);
+    }
+    sprintf(SelfMaxaddr, "%s", SelfMaxAddr);
+
+    BLE.begin(baudRate);
+    BLE.setTimeout(1);
+    delay(1000);
+
+    memset(debugD, 0, DEBUG_SIZE);
+
+    if ( ble_mode != BLE_NOCHANGE )
+    {
+        while ( IsSelfArduino() == false )
+            this->pollingDisconnect();
+    }
+
+    if ( ble_mode == BLE_MASTER )
+    {
+        pollingRequest("AT+ROLE1", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+MODE0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+NOTI0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+    }
+    else if ( ble_mode == BLE_SLAVER )
+    {
+        pollingRequest("AT+ROLE0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+MODE2", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+        delay(150);
+        pollingRequest("AT+NOTI0", debugD, 8);
+        memset(debugD, 0, DEBUG_SIZE);
+    }
+
+    if ( ble_mode != BLE_NOCHANGE )
+    {
+        while ( IsSelfArduino() == false )
+            this->pollingDisconnect();
+    }
+
+    delay(250);
 }
 
 void Cble::StatusRead( void )
 {
-       debug_printf("StatusRead function called.\r\n");
-
-       pollingRequest("AT+ROLE?", debugD, 9);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+MODE?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+IMME?", debugD, 9);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+TYPE?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+POWE?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+NOTI?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
-       pollingRequest("AT+PIO1?", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
-       delay(150);
+    debug_printf("StatusRead function called.\r\n");
+
+    pollingRequest("AT+ROLE?", debugD, 9);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+MODE?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+IMME?", debugD, 9);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+TYPE?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+POWE?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+NOTI?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
+    pollingRequest("AT+PIO1?", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(150);
 }
 
 bool Cble::IsConnected( void )
 {
-       return isConnected;
+    return isConnected;
 }
 
 bool Cble::IsSelfArduino( void )
 {
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("IsSelfArduino is called.\r\n");
+    debug_printf("IsSelfArduino is called.\r\n");
 #endif
-       int length=mustHaveRequest("AT+ADDR?", debugD, 20);
-
-       if( strstr(debugD, SelfMaxaddr) )
-       {
-               isConnected = false;
-               memset(debugD,0,length);
-               return true;
-       }
-       else
-       {
-               isConnected = true;
-               memset(debugD,0,length);
-               return false;
-       }
+    int length = mustHaveRequest("AT+ADDR?", debugD, 20);
+
+    if ( strstr(debugD, SelfMaxaddr) )
+    {
+        isConnected = false;
+        memset(debugD, 0, length);
+        return true;
+    }
+    else
+    {
+        isConnected = true;
+        memset(debugD, 0, length);
+        return false;
+    }
 }
 
-bool Cble::pollingConnect( const charmaxAddr )
+bool Cble::pollingConnect( const char *maxAddr )
 {
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("pollingConnect is called.\r\n");
+    debug_printf("pollingConnect is called.\r\n");
 #endif
 
-#define CONNECT_SIZE           20
-
-       char cmd[CONNECT_SIZE]= {0,};
-
-       // is Connected Address ?
-       pollingRequest("AT+ADDR?", debugD, 20);
-       if( strstr(debugD, maxAddr) )
-       {
-               isConnected = true;
-               memset(debugD,0,DEBUG_SIZE);
-               return isConnected;
-       }
-       memset(debugD,0,DEBUG_SIZE);
-
-       // Try Connection.
-       sprintf(cmd, "AT+CON%s",maxAddr);
-       if( pollingRequest(cmd, debugD, 8) == false )
-       {
-               debug_printf("Error : %s command is failed.\r\n",cmd );
-               memset(debugD,0,DEBUG_SIZE);
-               pollingDisconnect();
-               return false;
-       }
-       else if( strstr(debugD,"OK+CONNA") )
-       {
-               isConnected = true;
-               memset(debugD,0,DEBUG_SIZE);
-       }
-       else
-       {
-               memset(debugD,0,DEBUG_SIZE);
-               pollingDisconnect();
-               return false;
-       }
-       // Confirm Connected Address.
-       pollingRequest("AT+ADDR?", debugD, 20);
-
-       if( strstr(debugD, maxAddr) == 0 )
-       {
-               isConnected = false;
-               if ( strstr(debugD, "OK+CONNF") )
-               {
-                       memset(debugD,0,DEBUG_SIZE);
-                       streamDummy(debugD, 8);
-               }
-       }
-       memset(debugD,0,DEBUG_SIZE);
-       delay(5);
-
-       return isConnected;
+#define CONNECT_SIZE        20
+
+    char cmd[CONNECT_SIZE] = {0,};
+
+    // is Connected Address ?
+    pollingRequest("AT+ADDR?", debugD, 20);
+    if ( strstr(debugD, maxAddr) )
+    {
+        isConnected = true;
+        memset(debugD, 0, DEBUG_SIZE);
+        return isConnected;
+    }
+    memset(debugD, 0, DEBUG_SIZE);
+
+    // Try Connection.
+    sprintf(cmd, "AT+CON%s", maxAddr);
+    if ( pollingRequest(cmd, debugD, 8) == false )
+    {
+        debug_printf("Error : %s command is failed.\r\n", cmd );
+        memset(debugD, 0, DEBUG_SIZE);
+        pollingDisconnect();
+        return false;
+    }
+    else if ( strstr(debugD, "OK+CONNA") )
+    {
+        isConnected = true;
+        memset(debugD, 0, DEBUG_SIZE);
+    }
+    else
+    {
+        memset(debugD, 0, DEBUG_SIZE);
+        pollingDisconnect();
+        return false;
+    }
+    // Confirm Connected Address.
+    pollingRequest("AT+ADDR?", debugD, 20);
+
+    if ( strstr(debugD, maxAddr) == 0 )
+    {
+        isConnected = false;
+        if ( strstr(debugD, "OK+CONNF") )
+        {
+            memset(debugD, 0, DEBUG_SIZE);
+            streamDummy(debugD, 8);
+        }
+    }
+    memset(debugD, 0, DEBUG_SIZE);
+    delay(5);
+
+    return isConnected;
 
 #undef CONNECT_SIZE
 }
 
 
-#define  CMD_DISCONNECT                "(CMD_DISCON)"
+#define  CMD_DISCONNECT     "(CMD_DISCON)"
 void Cble::pollingDisconnect( void )
 {
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("pollingDisconnect is called.\r\n");
+    debug_printf("pollingDisconnect is called.\r\n");
 #endif
-       int length=0;
+    int length = 0;
 #if (ARDUINO == 0)
-       pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL);
-       delay(5);
+    pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL);
+    delay(5);
 
-       length=mustHaveRequest("AT", debugD, 2);
-       if( strstr(debugD,"OK") )
-               isConnected = false;
+    length = mustHaveRequest("AT", debugD, 2);
+    if ( strstr(debugD, "OK") )
+        isConnected = false;
 
-       memset(debugD,0,length);
+    memset(debugD, 0, length);
 #else
-       if( BLE.available() )
-       {
-               if( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true )
-               {
-                       debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT);
-
-                       do {
-                               debug_printf("pollingDisconnect : Send AT message.\r\n");
-                               if( length )
-                                       memset(debugD, 0, length);
-
-                               length=mustHaveRequest("AT", debugD, 2);
-                       }while( strstr(debugD,"OK") == NULL );
-
-                       debug_printf("pollingDisconnect() is Success.\r\n");
-                       memset(debugD, 0, length);
-               }
-       }
+    if ( BLE.available() )
+    {
+        if ( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true )
+        {
+            debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT);
+
+            do
+            {
+                debug_printf("pollingDisconnect : Send AT message.\r\n");
+                if ( length )
+                    memset(debugD, 0, length);
+
+                length = mustHaveRequest("AT", debugD, 2);
+            }
+            while ( strstr(debugD, "OK") == NULL );
+
+            debug_printf("pollingDisconnect() is Success.\r\n");
+            memset(debugD, 0, length);
+        }
+    }
 #endif
 
-       delay(5);
+    delay(5);
 }
 
 int Cble::pollingGetRSSI( void )
 {
-#define RSSI_SIZE              11
-#define RSSI_POS               7
-
-       long time_cnt=0;
-       char c=0;
-       char index=0;
-       char rssi_res[RSSI_SIZE] = {0,};
-
-       streamDummy(NULL, NULL);
-
-       if( isConnected == true )
-       {
-               BLE.write("AT+RSSI?");
-               BLE.flush();
-               delay(5);
-
-               while(1)
-               {
-                       if ( BLE.available() )
-                               c = (char)BLE.read();
-                       else
-                       {
-                               c = 0;
-                               time_cnt++;
-                       }
-
-                       if( c )
-                       {
-                               rssi_res[index] = c;
-                               index++;
-                               if( index == RSSI_SIZE-1 )
-                               {
-                                       rssi_res[index] = '\0';
-                                       goto RESULT;
-                               }
-                       }
-
-       //              debug_printf("time_cnt=%d\r\n", time_cnt);
-                       if( time_cnt == 0xFFFFF )
-                       {
-                               debug_printf("Error : Time Out GetRSSI().\r\n");
-                               return BLE_NODATA;
-                       }
-
-               }
-
-       RESULT :
+#define RSSI_SIZE       11
+#define RSSI_POS        7
+
+    long time_cnt = 0;
+    char c = 0;
+    char index = 0;
+    char rssi_res[RSSI_SIZE] = {0,};
+
+    streamDummy(NULL, NULL);
+
+    if ( isConnected == true )
+    {
+        BLE.write("AT+RSSI?");
+        BLE.flush();
+        delay(5);
+
+        while (1)
+        {
+            if ( BLE.available() )
+                c = (char)BLE.read();
+            else
+            {
+                c = 0;
+                time_cnt++;
+            }
+
+            if ( c )
+            {
+                rssi_res[index] = c;
+                index++;
+                if ( index == RSSI_SIZE - 1 )
+                {
+                    rssi_res[index] = '\0';
+                    goto RESULT;
+                }
+            }
+
+            //      debug_printf("time_cnt=%d\r\n", time_cnt);
+            if ( time_cnt == 0xFFFFF )
+            {
+                debug_printf("Error : Time Out GetRSSI().\r\n");
+                return BLE_NODATA;
+            }
+
+        }
+
+RESULT :
 #ifdef __INTERNAL_DEBUG__
-               debug_printf("res= %s \r\n",rssi_res);
+        debug_printf("res= %s \r\n", rssi_res);
 #endif
-               char* Srssi = &(rssi_res[RSSI_POS]);
-       //      debug_printf("[S] rssi=%s\r\n", Srssi);
-               int rssi = atoi(Srssi);
-       //      debug_printf("rssi=%d\r\n", rssi);
+        char *Srssi = &(rssi_res[RSSI_POS]);
+        //  debug_printf("[S] rssi=%s\r\n", Srssi);
+        int rssi = atoi(Srssi);
+        //  debug_printf("rssi=%d\r\n", rssi);
 
-               return rssi;
-       }
+        return rssi;
+    }
 
-       return BLE_DISCON;
+    return BLE_DISCON;
 
 #undef RSSI_POS
 #undef RSSI_SIZE
 }
 
-int Cble::mustHaveRequest(const char* request, char* data, int dataLen)
+int Cble::mustHaveRequest(const char *request, char *data, int dataLen)
 {
-       int cnt=0;
-       int length=0;
-       int required_length = dataLen;
-       char* data_index = data;
+    int cnt = 0;
+    int length = 0;
+    int required_length = dataLen;
+    char *data_index = data;
 
-       BLE.write(request);
-       BLE.flush();
-       delay(150);
+    BLE.write(request);
+    BLE.flush();
+    delay(150);
 
 READ_STREAM :
-       while( (length=BLE.readBytes(data_index, required_length)) == 0 )
-       {
-               cnt++;
-               delay(10);
+    while ( (length = BLE.readBytes(data_index, required_length)) == 0 )
+    {
+        cnt++;
+        delay(10);
 
-               if ( cnt >= LIMIT_COUNT/10 )
-               {
+        if ( cnt >= LIMIT_COUNT / 10 )
+        {
 #ifdef __INTERNAL_DEBUG__
-                       debug_printf("=====> Retry Request command Send. <=========\r\n");
+            debug_printf("=====> Retry Request command Send. <=========\r\n");
 #endif
-                       cnt = 0;
-                       BLE.write(request);
-                       BLE.flush();
-
-                       required_length = dataLen;
-                       data_index = data;
-                       length = 0;
-                       delay(50);
-               }
-       }
-
-       required_length -= length;
-       if( required_length != 0 )
-       {
-               data_index = data_index + length;
-               length = 0;
-               goto READ_STREAM;
-       }
+            cnt = 0;
+            BLE.write(request);
+            BLE.flush();
+
+            required_length = dataLen;
+            data_index = data;
+            length = 0;
+            delay(50);
+        }
+    }
+
+    required_length -= length;
+    if ( required_length != 0 )
+    {
+        data_index = data_index + length;
+        length = 0;
+        goto READ_STREAM;
+    }
 
 #ifdef __INTERNAL_DEBUG__
-       debug_printf("[ %s ] %s\r\n\r\n", request, data);
+    debug_printf("[ %s ] %s\r\n\r\n", request, data);
 #endif
-       return dataLen;
+    return dataLen;
 }
 
-bool Cble::pollingRequest(const char* request, char* data, int dataLen)
+bool Cble::pollingRequest(const char *request, char *data, int dataLen)
 {
-       int cnt=0;
-       int length=0;
-       int required_length = dataLen;
-       char* data_index = data;
+    int cnt = 0;
+    int length = 0;
+    int required_length = dataLen;
+    char *data_index = data;
 
-       BLE.write(request);
-       BLE.flush();
+    BLE.write(request);
+    BLE.flush();
 
-       if( data_index )
-       {
-               delay(250);
+    if ( data_index )
+    {
+        delay(250);
 
 READ_STREAM :
-               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
-               {
-                       cnt++;
-                       if ( cnt >= LIMIT_COUNT )
-                       {
-                               debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request);
-                               return false;
-                       }
-               }
-
-               required_length -= length;
-               if( required_length != 0 )
-               {
-                       data_index = data_index + length;
-                       length = 0;
-                       goto READ_STREAM;
-               }
+        while ( (length = BLE.readBytes(data_index, required_length)) == 0 )
+        {
+            cnt++;
+            if ( cnt >= LIMIT_COUNT )
+            {
+                debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request);
+                return false;
+            }
+        }
+
+        required_length -= length;
+        if ( required_length != 0 )
+        {
+            data_index = data_index + length;
+            length = 0;
+            goto READ_STREAM;
+        }
 
 #ifdef __INTERNAL_DEBUG__
-               debug_printf("[ %s ] %s\r\n\r\n", request, data);
+        debug_printf("[ %s ] %s\r\n\r\n", request, data);
 #endif
-       }
-       return true;
+    }
+    return true;
 }
 
-void Cble::streamDummy( chardata, int dataLen)
+void Cble::streamDummy( char *data, int dataLen)
 {
-       int cnt=0;
-       int length=0;
-       int required_length = dataLen;
-       char* data_index = data;
+    int cnt = 0;
+    int length = 0;
+    int required_length = dataLen;
+    char *data_index = data;
 
-       if( data && required_length )
-       {
+    if ( data && required_length )
+    {
 READ_STREAM :
-               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
-               {
-                       cnt++;
-                       if ( cnt >= LIMIT_COUNT )
-                       {
-                               debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n");
-                               return ;
-                       }
-               }
-
-               required_length -= length;
-               if( required_length != 0 )
-               {
-                       data_index = data_index + length;
-                       length = 0;
-                       goto READ_STREAM;
-               }
-
-               debug_printf("[ streamDummy ] %s\r\n\r\n", data);
-       }
-       else
-       {
-               if( BLE.available() )
-               {
-                       BLE.readBytes(debugD, DEBUG_SIZE);
+        while ( (length = BLE.readBytes(data_index, required_length)) == 0 )
+        {
+            cnt++;
+            if ( cnt >= LIMIT_COUNT )
+            {
+                debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n");
+                return ;
+            }
+        }
+
+        required_length -= length;
+        if ( required_length != 0 )
+        {
+            data_index = data_index + length;
+            length = 0;
+            goto READ_STREAM;
+        }
+
+        debug_printf("[ streamDummy ] %s\r\n\r\n", data);
+    }
+    else
+    {
+        if ( BLE.available() )
+        {
+            BLE.readBytes(debugD, DEBUG_SIZE);
 #ifdef __INTERNAL_DEBUG__
-                       debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
+            debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
 #endif
-                       memset(debugD, 0, DEBUG_SIZE);
-               }
-       }
+            memset(debugD, 0, DEBUG_SIZE);
+        }
+    }
 
 }
 
 #if (ARDUINO != 0)
 
-#define REGARD_DISCON                  5000
+#define REGARD_DISCON           5000
 int needDiscon = 0;
 unsigned long global_cnt = 0;
 
 void Cble::BLE2Debug( int autoDiscon )
 {
-       int cnt=0;
-       uint8_t length=0;
-
-       if( BLE.available() )
-       {
-               while( (length=BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 )
-               {
-                       cnt++;
-                       if ( cnt >= LIMIT_COUNT )
-                               return ;
-               }
-
-               global_cnt = 0;
-               needDiscon = 0;
-
-               Serial.println(BLEData);
-               memset(BLEData, 0, length);
-       }
-       else if ( autoDiscon )
-       {
-               global_cnt++;
-//             debug_printf("global_cnt=%u , ", global_cnt );
-//             debug_printf("needDiscon=%d\r\n", needDiscon);
-               if( !needDiscon && global_cnt >= REGARD_DISCON )
-               {
-                       needDiscon = 1;
-                       debug_printf("result : global_cnt=%u , ", global_cnt );
-                       debug_printf("needDiscon=%d\r\n", needDiscon);
-               }
-
-               if ( needDiscon )
-               {
-                       debug_printf("Auto Discon : global_cnt=%u , ", global_cnt );
-                       debug_printf("needDiscon=%d\r\n", needDiscon);
-                       if( pollingRequest("AT", debugD, 2) == true )
-                       {
-                               global_cnt = 0;
-                               needDiscon = 0;
-                       }
-               }
-       }
+    int cnt = 0;
+    uint8_t length = 0;
+
+    if ( BLE.available() )
+    {
+        while ( (length = BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 )
+        {
+            cnt++;
+            if ( cnt >= LIMIT_COUNT )
+                return ;
+        }
+
+        global_cnt = 0;
+        needDiscon = 0;
+
+        Serial.println(BLEData);
+        memset(BLEData, 0, length);
+    }
+    else if ( autoDiscon )
+    {
+        global_cnt++;
+//      debug_printf("global_cnt=%u , ", global_cnt );
+//      debug_printf("needDiscon=%d\r\n", needDiscon);
+        if ( !needDiscon && global_cnt >= REGARD_DISCON )
+        {
+            needDiscon = 1;
+            debug_printf("result : global_cnt=%u , ", global_cnt );
+            debug_printf("needDiscon=%d\r\n", needDiscon);
+        }
+
+        if ( needDiscon )
+        {
+            debug_printf("Auto Discon : global_cnt=%u , ", global_cnt );
+            debug_printf("needDiscon=%d\r\n", needDiscon);
+            if ( pollingRequest("AT", debugD, 2) == true )
+            {
+                global_cnt = 0;
+                needDiscon = 0;
+            }
+        }
+    }
 }
 
-charCble::Debug2BLE( int BLEwrite )
+char *Cble::Debug2BLE( int BLEwrite )
 {
-       char* result = NULL;
-
-       if( Serial.available() )
-       {
-               char c = (char)Serial.read();
-
-               switch(c)
-               {
-               case '\0':
-                       return result;
-               case '\r':
-               case '\n':
-                       debug_printf("\r\n");
-                       if(BLEwrite && SerialCnt)
-                       {
-                               BLE.write(SerialData);
-                               BLE.flush();
-                       }
-
-                       result = (char*)malloc(sizeof(char)*(SerialCnt+1));
-                       memcpy(result, SerialData, SerialCnt );
-                       result[SerialCnt] = NULL;
-
-                       memset(SerialData, 0, SerialCnt+1);
-                       SerialCnt=0;
-                       break;
-               default :
-                       SerialData[SerialCnt] = c;
-                       SerialCnt++;
-                       Serial.print(c);
-                       break;
-               }
-       }
-
-       return result;
+    char *result = NULL;
+
+    if ( Serial.available() )
+    {
+        char c = (char)Serial.read();
+
+        switch (c)
+        {
+            case '\0':
+                return result;
+            case '\r':
+            case '\n':
+                debug_printf("\r\n");
+                if (BLEwrite && SerialCnt)
+                {
+                    BLE.write(SerialData);
+                    BLE.flush();
+                }
+
+                result = (char *)malloc(sizeof(char) * (SerialCnt + 1));
+                memcpy(result, SerialData, SerialCnt );
+                result[SerialCnt] = NULL;
+
+                memset(SerialData, 0, SerialCnt + 1);
+                SerialCnt = 0;
+                break;
+            default :
+                SerialData[SerialCnt] = c;
+                SerialCnt++;
+                Serial.print(c);
+                break;
+        }
+    }
+
+    return result;
 }
 #else
 void Cble::BLE2Debug( int autoDiscon )
 {
-       ;
+    ;
 }
 
-charCble::Debug2BLE( int BLEwrite )
+char *Cble::Debug2BLE( int BLEwrite )
 {
-        return NULL;
+    return NULL;
 }
 #endif
 
 void Cble::FactoryReset( void )
 {
-       debug_printf("FactoryReset is called.\r\n");
+    debug_printf("FactoryReset is called.\r\n");
 
-       pollingRequest("AT+RENEW", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
+    pollingRequest("AT+RENEW", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
 }
 
 
 void Cble::firstUartSetting( void )
 {
-       debug_printf("firstUartSetting is called.\r\n");
+    debug_printf("firstUartSetting is called.\r\n");
 
-       Serial.begin(9600);
-       BLE.begin(9600);
-       BLE.setTimeout(1);
-       delay(1000);
+    Serial.begin(9600);
+    BLE.begin(9600);
+    BLE.setTimeout(1);
+    delay(1000);
 
-       pollingRequest("AT+BAUD4", debugD, 8);
-       memset(debugD, 0, DEBUG_SIZE);
+    pollingRequest("AT+BAUD4", debugD, 8);
+    memset(debugD, 0, DEBUG_SIZE);
 
-       debug_printf("Please Power off and on.\r\n");
-       BLE.end();
-//     delay(1000);
+    debug_printf("Please Power off and on.\r\n");
+    BLE.end();
+//  delay(1000);
 //
-//     BLE.begin(115200);
-//     delay(1000);
+//  BLE.begin(115200);
+//  delay(1000);
 //
-//     pollingRequest("AT", debugD, DEBUG_SIZE);
-//     memset(debugD, 0, DEBUG_SIZE);
+//  pollingRequest("AT", debugD, DEBUG_SIZE);
+//  memset(debugD, 0, DEBUG_SIZE);
 
 
-       exit(0);
+    exit(0);
 }
 
 
index 432ee0d..e668fa4 100644 (file)
@@ -1,9 +1,22 @@
-/*
- * oic_wifiLib.cpp
- *
- *  Created on: 2014. 11. 13.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #include "logger.h"
 #include "ocstack.h"
@@ -57,7 +70,7 @@ int ConnectToNetwork()
     // Verify that WiFi Shield is running the firmware with all UDP fixes
     fwVersion = WiFi.firmwareVersion();
     OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
-    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
+    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) != 0 )
     {
         OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
         return -1;
@@ -67,7 +80,7 @@ int ConnectToNetwork()
     while (status != WL_CONNECTED)
     {
         OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
-        status = WiFi.begin(ssid,pass);
+        status = WiFi.begin(ssid, pass);
 
         // wait 10 seconds for connection:
         delay(10000);
index 351f930..efefc74 100644 (file)
-/*
- * proximity.cpp
- *
- *  Created on: 2014. 11. 13.
- *      Author: eunseok
- */
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
 
 #include "Arduino.h"
 #include "proximity.h"
 #include <math.h>
 
 // Proximity code start
-float CalculateExponentialAverage(int numberOfSamples, int* array, int startindex, int flag){
-       float numerator = 0;
-       float denominator = 0;
-
-       float average = 0.0;
-
-       if (flag < arraysize / RSSI_EA)   // first loop buffer full
-       {
-               for (int i = 0; i < startindex; i++)
-               {
-                       average += array[i];
-               }
-               if(startindex == 0){}
-               else{
-                       average = average / startindex;
-               }
+float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag)
+{
+    float numerator = 0;
+    float denominator = 0;
 
-               Serial.print("average1 : ");
-               Serial.println(average);
-       }
-       else
-       {
-               for (int i = 0; i < arraysize; i++)
-               {
-                       average += array[i];
-               }
+    float average = 0.0;
 
-               for (int i = startindex; i < startindex + RSSI_EA; i++)
-               {
-                       average -= array[i];
-               }
-               average = average / (arraysize - numberOfSamples);
+    if (flag < arraysize / RSSI_EA)   // first loop buffer full
+    {
+        for (int i = 0; i < startindex; i++)
+        {
+            average += array[i];
+        }
+        if (startindex == 0) {}
+        else
+        {
+            average = average / startindex;
+        }
+        //       Serial.print("exp: ");
+        Serial.print("average1 : ");
+        Serial.println(average);
+    }
+    else
+    {
+        for (int i = 0; i < arraysize; i++)
+        {
+            average += array[i];
+        }
 
-               Serial.print("average2 : ");
-               Serial.println(average);
-       }
-       //exponential moving average
-       int i = 0;
-       //CHANGE THIS FOR DIFFERENT SMOOTHING EFFECT
-       float beta=0.8f;
-       for (i = startindex + numberOfSamples - 1; i >= startindex; i--)
-       {
-               numerator += array[i]* pow(beta, startindex + numberOfSamples - i - 1);
-               denominator += pow(beta, startindex + numberOfSamples - i - 1);
-       }
+        for (int i = startindex; i < startindex + RSSI_EA; i++)
+        {
+            average -= array[i];
+        }
+        average = average / (arraysize - numberOfSamples);
+        //            Serial.print("exp: ");
+        Serial.print("average2 : ");
+        Serial.println(average);
+    }
+    //exponential moving average
+    int i = 0;
+    //CHANGE THIS FOR DIFFERENT SMOOTHING EFFECT
+    float beta = 0.8f;
+    for (i = startindex + numberOfSamples - 1; i >= startindex; i--)
+    {
+        numerator += array[i] * pow(beta, startindex + numberOfSamples - i - 1);
+        denominator += pow(beta, startindex + numberOfSamples - i - 1);
+    }
 
-       int offset = 3;
-       if(average != 0.0){
-         numerator += average * pow(beta, offset + numberOfSamples);
-         denominator += pow(beta, offset + numberOfSamples);
-       }
-       return numerator / denominator;
+    int offset = 3;
+    if (average != 0.0)
+    {
+        numerator += average * pow(beta, offset + numberOfSamples);
+        denominator += pow(beta, offset + numberOfSamples);
+    }
+    return numerator / denominator;
 }
 
 
 float calculateDistance(float avgRSSI, float txPower)
 {
-       if (avgRSSI == 0)
-       {
-               return -1.0;
-       }
+    if (avgRSSI == 0)
+    {
+        return -1.0;
+    }
 
-       float ratio = avgRSSI*1.0/txPower;
-       if (ratio < 1.0)
-       {
-               return pow(ratio,10);
-       }
-       else
-       {
-               float distance =  (0.7)*pow(ratio,10) + 0.024;
-               return distance;
-       }
+    float ratio = avgRSSI * 1.0 / txPower;
+    if (ratio < 1.0)
+    {
+        return pow(ratio, 10);
+    }
+    else
+    {
+        float distance =  (0.7) * pow(ratio, 10) + 0.024;
+        return distance;
+    }
 }
 
 // proximity code end
index 8d78c5b..312ae75 100644 (file)
@@ -1,22 +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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
 
 
 
@@ -33,8 +33,8 @@
 #include "trackee.h"
 
 // proximity code s
-#define DATA_EA                400
-#define SLAVER_EA      2
+#define DATA_EA     400
+#define SLAVER_EA   2
 
 #define ARDUINO_AVR_MEGA2560 1
 /// This is the port which Arduino Server will use for all unicast communication with it's peers
@@ -42,7 +42,7 @@
 
 PROGMEM const char TAG[] = "TrackeeSensor";
 
-OCResourceHandle m_handle;             // OIC base를 handling하기위해서 필요한 handler.
+OCResourceHandle m_handle;
 
 #if (ARDUINO == 0)
 #include "proximity.h"
@@ -60,7 +60,8 @@ OCResourceHandle m_handle;            // OIC base를 handling하기위해서 필요한 han
 #define JSON_BASE09 "\",\"27\":\"SD\",\"28\":\"float\",\"29\":\""
 #define JSON_BASE10 "\"}}"
 
-typedef struct PROXIRESOURCE {
+typedef struct PROXIRESOURCE
+{
     float m_distance[SLAVER_EA];
     float m_proximity[SLAVER_EA];
 } PROXIResource;
@@ -76,11 +77,11 @@ int flag[SLAVER_EA] = {0,};
 #endif
 
 Cble ble;
-
+//char trackeeID[13] = "9059AF170C1D";
 char trackeeID[13] = "9059AF16FEF7";
 int slaver_num = 0;
-
-char slaveList[SLAVER_EA][13]={"9059AF1700EE","34B1F7D004D2"};
+//char slaveList[SLAVER_EA][13]={"9059AF1704D7"};
+char slaveList[SLAVER_EA][13] = {"9059AF1700EE", "34B1F7D004D2"};
 int g_PROXIUnderObservation = 0;
 
 
@@ -89,47 +90,53 @@ const char *getResult(OCStackResult result);
 void createResource();
 
 
-#define LENGTH_VAR             50
-bool JsonGenerator( charjsonBuf, uint16_t buf_length )
+#define LENGTH_VAR      50
+bool JsonGenerator( char *jsonBuf, uint16_t buf_length )
 {
-       if( g_PROXIUnderObservation == 1 )
-       {
+    if ( g_PROXIUnderObservation == 1 )
+    {
 #if (ARDUINO == 0)
-               PROXIResource* ref = &PROXI;
-               int ref_cnt = SLAVER_EA;
-               uint16_t base_length = 0;
-               base_length = strlen(JSON_BASE)+ strlen(JSON_BASE00)+ strlen(JSON_BASE01)+ strlen(JSON_BASE02)+ strlen(JSON_BASE03)+\
-                                     strlen(JSON_BASE04)+ strlen(JSON_BASE05)+ strlen(JSON_BASE06)+ strlen(JSON_BASE07)+\
-                                     strlen(JSON_BASE08)+ strlen(JSON_BASE09)+ strlen(JSON_BASE10);
+        PROXIResource *ref = &PROXI;
+        int ref_cnt = SLAVER_EA;
+        uint16_t base_length = 0;
+        base_length = strlen(JSON_BASE) + strlen(JSON_BASE00) + strlen(JSON_BASE01) + strlen(
+                          JSON_BASE02) + strlen(JSON_BASE03) + \
+                      strlen(JSON_BASE04) + strlen(JSON_BASE05) + strlen(JSON_BASE06) + strlen(JSON_BASE07) + \
+                      strlen(JSON_BASE08) + strlen(JSON_BASE09) + strlen(JSON_BASE10);
 
-               OC_LOG_V(INFO, TAG, "base length = %d, buf_length=%d", base_length, buf_length );
+//      base_length = strlen(JSON_BASE00)+ strlen(JSON_BASE01)+ strlen(JSON_BASE02)+ strlen(JSON_BASE03)+\
+//                    strlen(JSON_BASE04)+ strlen(JSON_BASE05)+ strlen(JSON_BASE10);
 
-               if( ((long)buf_length - (long)base_length) < LENGTH_VAR )
-               {
-                       OC_LOG_V(ERROR, TAG, "Error : length is very long.");
-                       return false;
-               }
+        OC_LOG_V(INFO, TAG, "base length = %d, buf_length=%d", base_length, buf_length );
 
-               sprintf(jsonBuf, JSON_BASE );
-               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE00"%s"JSON_BASE01"%d", trackeeID, ref_cnt);
-               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03"%d.%03d", slaveList[0], (int)ref->m_distance[0], (int)((ref->m_distance[0]-(int)ref->m_distance[0])*1000.0) );
-               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE04"%d"JSON_BASE05"0.0", (int)ref->m_proximity[0] );
-               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE06"%s"JSON_BASE07"%d.%03d", slaveList[1], (int)ref->m_distance[1], (int)((ref->m_distance[1]-(int)ref->m_distance[1])*1000.0) );
-               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE08"%d"JSON_BASE09"0.0", (int)ref->m_proximity[1] );
-               strcpy(jsonBuf+strlen(jsonBuf), JSON_BASE10 );
+        if ( ((long)buf_length - (long)base_length) < LENGTH_VAR )
+        {
+            OC_LOG_V(ERROR, TAG, "Error : length is very long.");
+            return false;
+        }
+
+        sprintf(jsonBuf, JSON_BASE );
+        sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE00"%s"JSON_BASE01"%d", trackeeID, ref_cnt);
+        sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03"%d.%03d", slaveList[0],
+                (int)ref->m_distance[0], (int)((ref->m_distance[0] - (int)ref->m_distance[0]) * 1000.0) );
+        sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE04"%d"JSON_BASE05"0.0", (int)ref->m_proximity[0] );
+        sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE06"%s"JSON_BASE07"%d.%03d", slaveList[1],
+                (int)ref->m_distance[1], (int)((ref->m_distance[1] - (int)ref->m_distance[1]) * 1000.0) );
+        sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE08"%d"JSON_BASE09"0.0", (int)ref->m_proximity[1] );
+        strcpy(jsonBuf + strlen(jsonBuf), JSON_BASE10 );
 
-               OC_LOG_V(INFO, TAG, "json length = %u", strlen(jsonBuf) );
+        OC_LOG_V(INFO, TAG, "json length = %u", strlen(jsonBuf) );
 
-               return true;
+        return true;
 
-#else          // Slave Json Code.
+#else       // Slave Json Code.
 
-               return true;
+        return true;
 #endif
-       }
+    }
 
-       OC_LOG_V(INFO, TAG, "Not Support Observer unfounded mode." );
-       return false;
+    OC_LOG_V(INFO, TAG, "Not Support Observer unfounded mode." );
+    return false;
 }
 
 
@@ -154,72 +161,51 @@ void PrintArduinoMemoryStats()
 
 // This is the entity handler for the registered resource.
 // This is invoked by OCStack whenever it recevies a request for this resource.
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest *entityHandlerRequest )
 {
     OCEntityHandlerResult ehRet = OC_EH_OK;
-    OCEntityHandlerResponse response = {0};
-    char payload[MAX_RESPONSE_LENGTH] = {0};
 
-    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
     {
         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
-        if(OC_REST_GET == entityHandlerRequest->method)
+        if (OC_REST_GET == entityHandlerRequest->method)
         {
-                if(JsonGenerator(payload, MAX_RESPONSE_LENGTH))
-                {
-                }
-           else
+            if (JsonGenerator((char *)entityHandlerRequest->resJSONPayload, \
+                              entityHandlerRequest->resJSONPayloadLen))
+            {
+            }
+            else
             {
                 ehRet = OC_EH_ERROR;
             }
         }
-        if(OC_REST_PUT == entityHandlerRequest->method)
+        if (OC_REST_PUT == entityHandlerRequest->method)
         {
             //Do something with the 'put' payload
-            if (JsonGenerator(payload, MAX_RESPONSE_LENGTH))
+            if (JsonGenerator((char *)entityHandlerRequest->resJSONPayload, \
+                              entityHandlerRequest->resJSONPayloadLen))
             {
             }
             else
             {
                 ehRet = OC_EH_ERROR;
             }
-         }
-    }
-
-    if (ehRet == OC_EH_OK)
-   {
-          // Format the response.  Note this requires some info about the request
-          response.requestHandle = entityHandlerRequest->requestHandle;
-          response.resourceHandle = entityHandlerRequest->resource;
-          response.ehResult = ehRet;
-          response.payload = (unsigned char *)payload;
-          response.payloadSize = strlen(payload);
-          response.numSendVendorSpecificHeaderOptions = 0;
-          memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
-          memset(response.resourceUri, 0, sizeof response.resourceUri);
-          // Indicate that response is NOT in a persistent buffer
-          response.persistentBufferFlag = 0;
-
-          // Send the response
-          if (OCDoResponse(&response) != OC_STACK_OK)
-          {
-                  OC_LOG(ERROR, TAG, "Error sending response");
-                  ehRet = OC_EH_ERROR;
-          }
+        }
     }
-
     if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
     {
-        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action)
         {
             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
             g_PROXIUnderObservation = 1;
         }
-        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action)
         {
             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
         }
     }
+
     return ehRet;
 }
 
@@ -227,82 +213,95 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
 #if (ARDUINO == 0)
 void ChangePROXIRepresentation (void *param)
 {
-       (void)param;
-       OCStackResult result = OC_STACK_ERROR;
-       float avg[SLAVER_EA] = {0,};
-
-       for(int i = 0; i < SLAVER_EA; i++)
-       {
-                 if( rssicnt[i] > arraysize - 1)
-                 {
-                       rssicnt[i] = rssicnt[i] % arraysize;
-                 }
-
-               ble.streamDummy(NULL, NULL);
-
-               while(ble.pollingConnect(&slaveList[slaver_num][0]) == false){
-                       ble.streamDummy(NULL, NULL);
-               }
-
-               if( ble.IsConnected() == true )
-               {
-                       // print the string when a newline arrives:
-                       OC_LOG_V(INFO, TAG, "Connected. (%s)\r\n", slaveList[slaver_num]);
-
-                       for(int j=0; j < RSSI_EA; j++){
-                               rssi[i][rssicnt[i]] = ble.pollingGetRSSI();
-                               OC_LOG_V(INFO, TAG, "rssi val : %d \r\n", rssi[i][rssicnt[i]]);
-                          rssicnt[i]++;
-                       }
-
-                       while( ble.IsSelfArduino() == false )
-                               ble.pollingDisconnect();
-
-                       slaver_num++;
-                       slaver_num = slaver_num % SLAVER_EA;
-               }
-
-               avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]);
-               Serial.println(avg[i]);
-               Serial.print("distance : ");
-
-               PROXI.m_distance[i] = calculateDistance(avg[i], -58);
-
-               if(PROXI.m_distance[i] <= 1){
-                       PROXI.m_proximity[i] = 1;
-               }
-               else if(PROXI.m_distance[i] <= 2){
-                       PROXI.m_proximity[i] = 2;
-               }
-               else{
-                       PROXI.m_proximity[i] = 3;
-               }
-
-               Serial.println(PROXI.m_distance[i]);
-               Serial.println(PROXI.m_proximity[i]);
-
-               startindex[i] += RSSI_EA;
-
-               // This call displays the amount of free SRAM available on Arduino
-               PrintArduinoMemoryStats();
-
-               if(startindex[i] >= arraysize){
-                       startindex[i] = 0;
-               }
-
-               if(flag[i] < (arraysize / RSSI_EA))
-               {
-                       flag[i]++;
-               }
-       }
-
-       result = OCNotifyAllObservers (m_handle, OC_NA_QOS);
-
-       if (OC_STACK_NO_OBSERVERS == result)
-       {
-               OC_LOG_V(INFO, TAG, "g_PROXIUnderObservation is 0." );
-               g_PROXIUnderObservation = 0;
-       }
+    (void)param;
+    OCStackResult result = OC_STACK_ERROR;
+    float avg[SLAVER_EA] = {0,};
+
+    for (int i = 0; i < SLAVER_EA; i++)
+    {
+        if ( rssicnt[i] > arraysize - 1)
+        {
+            rssicnt[i] = rssicnt[i] % arraysize;
+        }
+
+        ble.streamDummy(NULL, NULL);
+        /*  if( ble.pollingConnect(&slaveList[slaver_num][0]) == false )
+            {
+                OC_LOG_V("Error : Not Connected.\r\n");
+            }*/
+        while (ble.pollingConnect(&slaveList[slaver_num][0]) == false)
+        {
+            ble.streamDummy(NULL, NULL);
+        }
+
+        if ( ble.IsConnected() == true )
+        {
+            // print the string when a newline arrives:
+            OC_LOG_V(INFO, TAG, "Connected. (%s)\r\n", slaveList[slaver_num]);
+
+//          time = millis();
+            for (int j = 0; j < RSSI_EA; j++)
+            {
+                rssi[i][rssicnt[i]] = ble.pollingGetRSSI();
+                OC_LOG_V(INFO, TAG, "rssi val : %d \r\n", rssi[i][rssicnt[i]]);
+                rssicnt[i]++;
+            }
+//          oldTime = millis();
+//          float TpR = (float)(((oldTime-time)/1000.0)/20.0);
+//          OC_LOG_V("time per rssi : %d.%03d\r\n", (int)TpR, (int)(TpR*1000.0 -((int)TpR)*1000.0) );
+
+            while ( ble.IsSelfArduino() == false )
+                ble.pollingDisconnect();
+
+            slaver_num++;
+            slaver_num = slaver_num % SLAVER_EA;
+        }
+
+        avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]);
+        Serial.println(avg[i]);
+        Serial.print("distance : ");
+
+        PROXI.m_distance[i] = calculateDistance(avg[i], -58);
+
+        if (PROXI.m_distance[i] <= 1)
+        {
+            PROXI.m_proximity[i] = 1;
+        }
+        else if (PROXI.m_distance[i] <= 2)
+        {
+            PROXI.m_proximity[i] = 2;
+        }
+        else
+        {
+            PROXI.m_proximity[i] = 3;
+        }
+
+        Serial.println(PROXI.m_distance[i]);
+        Serial.println(PROXI.m_proximity[i]);
+        //Serial.println(calculateDistance(avg[i], -58));
+        startindex[i] += RSSI_EA;
+
+        // This call displays the amount of free SRAM available on Arduino
+        PrintArduinoMemoryStats();
+
+        if (startindex[i] >= arraysize)
+        {
+            startindex[i] = 0;
+        }
+
+        if (flag[i] < (arraysize / RSSI_EA))
+        {
+            flag[i]++;
+        }
+    }
+
+    result = OCNotifyAllObservers (m_handle, OC_NA_QOS);
+
+    if (OC_STACK_NO_OBSERVERS == result)
+    {
+        OC_LOG_V(INFO, TAG, "g_PROXIUnderObservation is 0." );
+        g_PROXIUnderObservation = 0;
+    }
 
 }
 #endif
@@ -313,45 +312,45 @@ void ChangePROXIRepresentation (void *param)
 //The setup function is called once at startup of the sketch
 void setup()
 {
-       Serial.begin(115200);
+    Serial.begin(115200);
 
-       // Add your initialization code here
-       OC_LOG_INIT();
+    // Add your initialization code here
+    OC_LOG_INIT();
 
-       OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
-       //    uint16_t port = OC_WELL_KNOWN_PORT;
+    OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
+    //    uint16_t port = OC_WELL_KNOWN_PORT;
 
-       // Connect to Ethernet or WiFi network
-       if (ConnectToNetwork() != 0)
-       {
-               OC_LOG(ERROR, TAG, "Unable to connect to network");
-               return;
-       }
+    // Connect to Ethernet or WiFi network
+    if (ConnectToNetwork() != 0)
+    {
+        OC_LOG(ERROR, TAG, "Unable to connect to network");
+        return;
+    }
 
-       // Initialize the OC Stack in Server mode
-       if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
-       {
-               OC_LOG(ERROR, TAG, PCF("OCStack init error"));
-               return;
-       }
+    // Initialize the OC Stack in Server mode
+    if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack init error"));
+        return;
+    }
 
     OCStartPresence(60);
-       // Declare and create the example resource
-       createResource();
+    // Declare and create the example resource
+    createResource();
 
-       // This call displays the amount of free SRAM available on Arduino
-       PrintArduinoMemoryStats();
+    // This call displays the amount of free SRAM available on Arduino
+    PrintArduinoMemoryStats();
 #if (ARDUINO == 0)
-       ble.init( (long)115200, BLE_MASTER, trackeeID);
+    ble.init( (long)115200, BLE_MASTER, trackeeID);
 #elif (ARDUINO == 1)
-       ble.init( (long)115200, BLE_SLAVER, slaveList[0]);
+    ble.init( (long)115200, BLE_SLAVER, slaveList[0]);
 #elif (ARDUINO == 2)
-       ble.init( (long)115200, BLE_SLAVER, slaveList[1]);
+    ble.init( (long)115200, BLE_SLAVER, slaveList[1]);
 #endif
 
-//     ble.StatusRead();
+//  ble.StatusRead();
 
-       OC_LOG_V(INFO, TAG, "Program Start-\r\n");
+    OC_LOG_V(INFO, TAG, "Program Start-\r\n");
 }
 
 
@@ -361,26 +360,26 @@ void loop()
     // This artificial delay is kept here to avoid endless spinning
     // of Arduino microcontroller. Modify it as per specfic application needs.
 
-       if (OCProcess() != OC_STACK_OK)
-       {
-               OC_LOG(ERROR, TAG, PCF("OCStack process error"));
-               return;
-       }
+    if (OCProcess() != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, PCF("OCStack process error"));
+        return;
+    }
 #if (ARDUINO == 0)
-       ChangePROXIRepresentation(NULL);
+    ChangePROXIRepresentation(NULL);
 #else
-       char* user_cmd = NULL;
+    char *user_cmd = NULL;
 
-//     ble.pollingDisconnect();
+//  ble.pollingDisconnect();
 
-       user_cmd = ble.Debug2BLE(true);
-       ble.BLE2Debug( true );
+    user_cmd = ble.Debug2BLE(true);
+    ble.BLE2Debug( true );
 
-       if( user_cmd )
-       {
-               free( user_cmd );
-               user_cmd = NULL;
-       }
+    if ( user_cmd )
+    {
+        free( user_cmd );
+        user_cmd = NULL;
+    }
 
 #endif
 }
@@ -391,53 +390,56 @@ void loop()
 
 
 
-void createResource() {
+void createResource()
+{
 
     OCStackResult res = OCCreateResource(&m_handle,
-                                         "SoftSensorManager.Sensor",
-                                         "oc.mi.def",
+                                         "SSManager.Sensor",
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          "/Tracker_Thing",
                                          OCEntityHandlerCb,
-                                         OC_DISCOVERABLE|OC_OBSERVABLE);
+                                         OC_DISCOVERABLE | OC_OBSERVABLE);
     OC_LOG_V(INFO, TAG, "Created PROXI resource with result: %s", getResult(res));
 }
 
-const char *getResult(OCStackResult result) {
-    switch (result) {
-    case OC_STACK_OK:
-        return "OC_STACK_OK";
-    case OC_STACK_INVALID_URI:
-        return "OC_STACK_INVALID_URI";
-    case OC_STACK_INVALID_QUERY:
-        return "OC_STACK_INVALID_QUERY";
-    case OC_STACK_INVALID_IP:
-        return "OC_STACK_INVALID_IP";
-    case OC_STACK_INVALID_PORT:
-        return "OC_STACK_INVALID_PORT";
-    case OC_STACK_INVALID_CALLBACK:
-        return "OC_STACK_INVALID_CALLBACK";
-    case OC_STACK_INVALID_METHOD:
-        return "OC_STACK_INVALID_METHOD";
-    case OC_STACK_NO_MEMORY:
-        return "OC_STACK_NO_MEMORY";
-    case OC_STACK_COMM_ERROR:
-        return "OC_STACK_COMM_ERROR";
-    case OC_STACK_INVALID_PARAM:
-        return "OC_STACK_INVALID_PARAM";
-    case OC_STACK_NOTIMPL:
-        return "OC_STACK_NOTIMPL";
-    case OC_STACK_NO_RESOURCE:
-        return "OC_STACK_NO_RESOURCE";
-    case OC_STACK_RESOURCE_ERROR:
-        return "OC_STACK_RESOURCE_ERROR";
-    case OC_STACK_SLOW_RESOURCE:
-        return "OC_STACK_SLOW_RESOURCE";
-    case OC_STACK_NO_OBSERVERS:
-        return "OC_STACK_NO_OBSERVERS";
-    case OC_STACK_ERROR:
-        return "OC_STACK_ERROR";
-    default:
-        return "UNKNOWN";
+const char *getResult(OCStackResult result)
+{
+    switch (result)
+    {
+        case OC_STACK_OK:
+            return "OC_STACK_OK";
+        case OC_STACK_INVALID_URI:
+            return "OC_STACK_INVALID_URI";
+        case OC_STACK_INVALID_QUERY:
+            return "OC_STACK_INVALID_QUERY";
+        case OC_STACK_INVALID_IP:
+            return "OC_STACK_INVALID_IP";
+        case OC_STACK_INVALID_PORT:
+            return "OC_STACK_INVALID_PORT";
+        case OC_STACK_INVALID_CALLBACK:
+            return "OC_STACK_INVALID_CALLBACK";
+        case OC_STACK_INVALID_METHOD:
+            return "OC_STACK_INVALID_METHOD";
+        case OC_STACK_NO_MEMORY:
+            return "OC_STACK_NO_MEMORY";
+        case OC_STACK_COMM_ERROR:
+            return "OC_STACK_COMM_ERROR";
+        case OC_STACK_INVALID_PARAM:
+            return "OC_STACK_INVALID_PARAM";
+        case OC_STACK_NOTIMPL:
+            return "OC_STACK_NOTIMPL";
+        case OC_STACK_NO_RESOURCE:
+            return "OC_STACK_NO_RESOURCE";
+        case OC_STACK_RESOURCE_ERROR:
+            return "OC_STACK_RESOURCE_ERROR";
+        case OC_STACK_SLOW_RESOURCE:
+            return "OC_STACK_SLOW_RESOURCE";
+        case OC_STACK_NO_OBSERVERS:
+            return "OC_STACK_NO_OBSERVERS";
+        case OC_STACK_ERROR:
+            return "OC_STACK_ERROR";
+        default:
+            return "UNKNOWN";
     }
 }
 
diff --git a/service/soft-sensor-manager/SampleApp/arduino/environment.mk b/service/soft-sensor-manager/SampleApp/arduino/environment.mk
deleted file mode 100644 (file)
index 4599f82..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-
-BOOST_DIR=/home/choi/devel/boost_1_56_0
-
diff --git a/service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/SConscript b/service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/SConscript
new file mode 100644 (file)
index 0000000..2400b34
--- /dev/null
@@ -0,0 +1,39 @@
+##
+# linux sample app  build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+linux_sample_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(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 = ['oc'])
+linux_sample_env.AppendUnique(LIBS = ['octbstack'])
+linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction'])
+linux_sample_env.AppendUnique(LIBS = ['libcoap'])
+linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
+linux_sample_env.AppendUnique(LIBS = ['pthread'])
+
+if env.get('SECURED') == '1':
+    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
+
+######################################################################
+#build sampleapp
+######################################################################
+heightsensorapp = linux_sample_env.Program('HeightSensorApp', 'src/HeightSensorApp.cpp')
+Alias("heightsensorapp_sample", heightsensorapp)
+env.AppendTarget('heightsensorapp')
diff --git a/service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/include/HeightSensorApp.h b/service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/include/HeightSensorApp.h
new file mode 100644 (file)
index 0000000..43a3ab4
--- /dev/null
@@ -0,0 +1,97 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+/*
+ * HeightSensorApp.h
+ */
+
+#ifndef HEIGHTSENSORAPP_H_
+#define HEIGHTSENSORAPP_H_
+
+#include <functional>
+#include <pthread.h>
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace std;
+
+#include <string>
+#include <cstdlib>
+
+#define COAP_IP                 "0.0.0.0"
+#define COAP_PORT               0
+#define COAP_MODE               ModeType::Server
+#define COAP_SRVTYPE        ServiceType::InProc
+
+#define COAP_TYPE_NAME          "SSManager.Sensor"
+
+//  testing case
+#define INTERVAL_FOR_CHECK          4   // seconds
+#define INTERVAL_FOR_MEASUREMENT    3   // seconds
+#define INIT_VAL                    1   // default value
+#define DIFF_VAL                    0.02   // default value
+
+
+
+// Forward declaring the entityHandler
+
+class HeightResource
+{
+    public:
+        /// Access this property from a TB client
+//        int m_humid;
+//        int m_temp;
+        double m_height;
+        std::string m_resourceUri;
+        std::vector<std::string> m_resourceTypes;
+        std::vector<std::string> m_resourceInterfaces;
+        OCResourceHandle m_resourceHandle;
+        OCRepresentation m_resourceRep;
+        ObservationIds m_interestedObservers;
+
+    public:
+        /// Constructor
+        HeightResource() :
+            /*m_humid(0), m_temp(0), */ m_height(0), m_resourceHandle(0)
+        {
+            m_resourceUri = "/Thing_HeightSensor";
+            m_resourceTypes.push_back(COAP_TYPE_NAME);
+            m_resourceInterfaces.push_back(DEFAULT_INTERFACE);
+
+            printf("Running thing as %s\n", m_resourceUri.c_str());
+            m_resourceRep.setUri(m_resourceUri);
+            m_resourceRep.setResourceTypes(m_resourceTypes);
+            m_resourceRep.setResourceInterfaces(m_resourceInterfaces);
+        }
+
+        ~HeightResource()
+        {
+        }
+
+        void registerResource();
+
+        OCResourceHandle getHandle();
+
+        void setResourceRepresentation(OCRepresentation &rep);
+
+        OCRepresentation getResourceRepresentation();
+};
+
+#endif /* THINGRESOURCESERVER_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/src/HeightSensorApp.cpp b/service/soft-sensor-manager/SampleApp/linux/HeightSensorApp/src/HeightSensorApp.cpp
new file mode 100644 (file)
index 0000000..36d1f4b
--- /dev/null
@@ -0,0 +1,245 @@
+
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <HeightSensorApp.h>
+
+int g_Observation = 0;
+
+OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request);
+
+/*
+ * TempResourceFunctions
+ */
+
+void HeightResource::registerResource()
+{
+    uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+
+    // This will internally create and register the resource.
+    OCStackResult result = OC::OCPlatform::registerResource(m_resourceHandle, m_resourceUri,
+                           m_resourceTypes[0], m_resourceInterfaces[0], &entityHandler, resourceProperty);
+
+    if (OC_STACK_OK != result)
+    {
+        cout << "Resource creation was unsuccessful\n";
+    }
+}
+
+OCResourceHandle HeightResource::getHandle()
+{
+    return m_resourceHandle;
+}
+
+void HeightResource::setResourceRepresentation(OCRepresentation &rep)
+{
+    double tempHeight;
+
+
+
+    rep.getValue("2", tempHeight);
+
+
+    m_height= tempHeight;
+
+    cout << "\t\t\t" << "Received representation: " << endl;
+
+    cout << "\t\t\t\t" << "height" << m_height << endl;
+
+}
+
+OCRepresentation HeightResource::getResourceRepresentation()
+{
+
+    m_resourceRep.setValue("0", std::string("height"));
+    m_resourceRep.setValue("1", std::string("double"));
+    m_resourceRep.setValue("2", std::to_string(m_height));
+
+    return m_resourceRep;
+}
+
+// Create the instance of the TemphumidResource class
+HeightResource g_myResource;
+
+void *TestSensorVal(void *param)
+{
+
+    bool bFlag = true;
+    int nSleep_time=INTERVAL_FOR_CHECK;
+    double nHeight;
+
+    std::cout << "[HeightSensorAPP] ::" << __func__ << " is called."
+              << std::endl;
+
+//     g_myResource.m_height = 1;
+
+       nHeight=INIT_VAL;
+
+    // This function continuously monitors for the changes
+    while (1)
+    {
+
+
+        sleep(nSleep_time);
+
+
+        if (g_Observation)
+        {
+
+            if(bFlag){
+
+                nSleep_time =INTERVAL_FOR_MEASUREMENT;
+                nHeight+=DIFF_VAL;
+                g_myResource.m_height=nHeight;
+            }
+            else{
+                nSleep_time =INTERVAL_FOR_CHECK;
+                g_myResource.m_height=0;
+
+
+            }
+            bFlag=bFlag^true;
+
+
+                       cout << "\n height updated to : " << g_myResource.m_height << endl;
+            cout << "Notifying observers with resource handle: " << g_myResource.getHandle()
+                 << endl;
+
+                       OCStackResult result = OCPlatform::notifyAllObservers(g_myResource.getHandle());
+
+
+            if (OC_STACK_NO_OBSERVERS == result)
+            {
+                cout << "No More observers, stopping notifications" << endl;
+                g_Observation = 0;
+            }
+
+        }
+        else{
+
+            nSleep_time=INTERVAL_FOR_CHECK ;
+        }
+
+    }
+    return NULL;
+}
+
+OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
+{
+    cout << "\tIn Server CPP entity handler:\n";
+
+    auto response = std::make_shared<OC::OCResourceResponse>();
+
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        response->setRequestHandle(request->getRequestHandle());
+        response->setResourceHandle(request->getResourceHandle());
+
+        if (requestFlag & RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\t\trequestFlag : Request\n";
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                cout << "\t\t\trequestType : GET\n";
+
+                // Check for query params (if any)
+                // Process query params and do required operations ..
+
+                // Get the representation of this resource at this point and send it as response
+                OCRepresentation rep = g_myResource.getResourceRepresentation();
+
+                if (response)
+                {
+                    // TODO Error Code
+                    response->setErrorCode(200);
+                    response->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+                }
+            }
+            else if (requestType == "PUT")
+            {
+                // PUT request operations
+            }
+            else if (requestType == "POST")
+            {
+                // POST request operations
+            }
+            else if (requestType == "DELETE")
+            {
+                // DELETE request operations
+            }
+        }
+
+        if (requestFlag & RequestHandlerFlag::ObserverFlag)
+        {
+            pthread_t threadId;
+
+            cout << "\t\trequestFlag : Observer\n";
+            g_Observation = 1;
+
+            static int startedThread = 0;
+
+            if (!startedThread)
+            {
+                pthread_create(&threadId, NULL, TestSensorVal, (void *) NULL);
+                startedThread = 1;
+            }
+        }
+    }
+    else
+    {
+        std::cout << "Request invalid" << std::endl;
+    }
+
+    return OCPlatform::sendResponse(response) == OC_STACK_OK ? OC_EH_OK : OC_EH_ERROR;
+}
+
+int main()
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg(COAP_SRVTYPE, COAP_MODE, COAP_IP, COAP_PORT, OC::QualityOfService::LowQos);
+
+    try
+    {
+        OC::OCPlatform::Configure(cfg);
+
+        OC::OCPlatform::startPresence(60);
+
+        g_myResource.registerResource();
+
+        int input = 0;
+        cout << "Type any key to terminate" << endl;
+        cin >> input;
+
+        OC::OCPlatform::stopPresence();
+    }
+    catch (std::exception e)
+    {
+        cout << e.what() << endl;
+    }
+
+    return 0;
+}
+
diff --git a/service/soft-sensor-manager/SampleApp/linux/Makefile b/service/soft-sensor-manager/SampleApp/linux/Makefile
deleted file mode 100644 (file)
index 67a1609..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
--include ../../build/linux/root_path.inc
--include ../../build/linux/environment.mk
-
-MAKE=make
-
-CUR_DIR=${PWD}
-SRCLIST=${wildcard **/**/Makefile}
-DIRLIST=${patsubst %/, % , ${dir ${SRCLIST}} }
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job build post_job 
-
-pre_job:
-       @echo " " 
-       @echo "============= Sample Folder ============" 
-       @echo " "
-       @echo "${DIRLIST}"
-       
-build:
-       @for subdir in ${DIRLIST} ; do \
-       ${MAKE} -C $${subdir} ; \
-       echo " " ; \
-       done
-       @echo " "
-
-post_job:
-       @echo " " 
-       @echo "============ Sample Folder Successful. ============="
-       @echo " " 
-
-
-clean:
-       @for subdir in ${DIRLIST} ; do \
-       ${MAKE} clean -C $${subdir} ; \
-       echo " " ; \
-       done
index 30f44d6..b7a0b4d 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,14 +38,22 @@ 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'])
 linux_sample_env.AppendUnique(LIBS = ['octbstack'])
+linux_sample_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+linux_sample_env.AppendUnique(LIBS = ['coap'])
 linux_sample_env.AppendUnique(LIBS = ['libcoap'])
 linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
 linux_sample_env.AppendUnique(LIBS = ['dl'])
-linux_sample_env.AppendUnique(LIBS = ['pthread'])
+if env.get('SECURED') == '1':
+    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
 
 ######################################################################
 #build sampleapp
@@ -33,3 +61,4 @@ linux_sample_env.AppendUnique(LIBS = ['pthread'])
 ssmtesterapp = linux_sample_env.Program('SSMTesterApp', 'src/SSMTestApp.cpp')
 Alias("ssmtesterapp_sample", ssmtesterapp)
 env.AppendTarget('SSMTesterApp')
+
diff --git a/service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/build/Makefile b/service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/build/Makefile
deleted file mode 100644 (file)
index abf7cf7..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
--include ../../../../build/linux/root_path.inc
--include ../../../../build/linux/environment.mk
-
-BOOST=${BOOST_BASE}
-SRC_PATH=../src
-INC_PATH=../include
-RST_NAME=release
-
-# Insert your project name.
-TARGET=SSMTesterApp
-
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -DLINUX
-CXX_INC=-I${SRC_PATH}/ -I${INC_PATH}/ -I${OUTPUTS_DIR} -I${BOOST}
-
-
-CXX_LIB+=${OUTPUTS_DIR}/${SSM_LIB} 
-CXX_LIB+=${OUTPUTS_DIR}/${SSMCORE_LIB} 
-CXX_LIB+=${IOT_RELEASE}/${IOT_LIB}
-CXX_LIB+=${IOT_CSDK_RELEASE}/${IOT_CSDK_LIB} 
-CXX_LIB+=${IOT_LOG_DIR}/lib/${IOT_LOG_LIB}
-CXX_LIB+=-lpthread -ldl
-
-SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
-OBJPATH=${SRCLIST:.cpp=.o}
-OBJLIST=${notdir ${OBJPATH}}
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job ${TARGET} post_job
-
-pre_job:
-       @echo " " 
-       @echo "--------- ${TARGET} Build Begin. -----------" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-
-${TARGET}: ${OBJLIST}
-       $(CXX) $(CXX_FLAGS) -o ./${RST_NAME}/$@ $^ ${CXX_LIB}
-       @echo " "
-
-%.o : ${SRC_PATH}/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o $@
-       @echo " "
-
-post_job:
-       @echo " " 
-       cp -Rdp ./${RST_NAME}/${TARGET} ${OUTPUTS_DIR}/
-       @echo "----------- ${TARGET} Build Successful. ------------"
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " " 
-       
-       
-clean:
-       rm -f -v *.o ${TARGET}
-       rm -rf ./${RST_NAME}
-       
index c68304d..edb6b79 100644 (file)
@@ -35,21 +35,24 @@ namespace APPMenu
 {
     typedef enum
     {
-        NONE = 0, REGISTER, UNREGISTER, DISCOMFORT_SAMPLE, EXIT = 9
+        NONE = 0, REGISTER, UNREGISTER, DISCOMFORT_SAMPLE, ITS_SAMPLE, BMI_SAMPLE, EXIT = 9
     } APPMenu;
 }
 ;
 
 typedef enum
 {
+    UNKOWNBMI = 0, UNDERWEIGHT, NORMALRANGE, OVERWEIGHT, OBESE
+} BMIResult;
+
+
+typedef enum
+{
     ALL_DISCOMPORT = 2, HALF_DISCOMPORT, LITTLE_DISCOMPORT, ALL_COMPORT
 } DIResult;
 
 class SSMTestApp: public IQueryEngineEvent
 {
-    private:
-        SSMInterface m_SSMClient;
-
     public:
 
         SSMTestApp();
@@ -58,6 +61,8 @@ class SSMTestApp: public IQueryEngineEvent
         void registerQuery(std::string queryString);
         void unregisterQuery();
 
+        void TrajectoryDataOutput(IModelData *pModelData);
+
         /* operations from listener interface */
         SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult);
 };
index 50ba8fc..750123f 100644 (file)
@@ -21,6 +21,7 @@
 #include <string>
 #include <stdio.h>
 #include <iostream>
+#include <stdlib.h>
 
 #include "SSMTestApp.h"
 
@@ -38,6 +39,8 @@ void SSMTestApp::displayMenu()
     printf("   1. Register Query \n");
     printf("   2. Unregister Query \n");
     printf("   3. Register DiscomfortIndexSensor sample query \n");
+    printf("   4. Register IndoorTrajectorySensor sample query \n");
+    printf("   5. Register BMISensor sample query \n");
     printf("   9. exit \n");
     printf("===============================================\n");
     printf("   Please Enter the NO: ");
@@ -52,11 +55,10 @@ void SSMTestApp::registerQuery(std::string queryString)
     if (queryString.size() == 0)
     {
         printf("   Please Enter query string: ");
-        cin.ignore();
         getline(cin, queryString);
     }
 
-    rtn = m_SSMClient.registerQuery(queryString, this, qid);
+    rtn = RegisterQuery(queryString, this, qid);
 
     if (rtn == SSM_S_OK)
     {
@@ -64,7 +66,7 @@ void SSMTestApp::registerQuery(std::string queryString)
         printf("QID : %d\n", qid);
     }
     else
-        printf("Error occured(%d)", rtn);
+        printf("Error occured(%d)\n", rtn);
 }
 
 /* unRegister Query.*/
@@ -73,11 +75,10 @@ void SSMTestApp::unregisterQuery(void)
     std::string qid;
     SSMRESULT rtn = SSM_E_FAIL;
 
-    printf("   Please Enter query string: ");
-    cin.ignore();
+    printf("   Please Enter query Id: ");
     getline(cin, qid);
 
-    rtn = m_SSMClient.unregisterQuery(atoi(qid.c_str()));
+    rtn = UnregisterQuery(atoi(qid.c_str()));
 
     if (rtn == SSM_S_OK)
         printf("The query has been unregistered!\n");
@@ -85,6 +86,89 @@ void SSMTestApp::unregisterQuery(void)
         printf("Error occured(%d)\n", (int) rtn);
 }
 
+
+#define INPUT_EA        9
+char input_name[INPUT_EA][10] = { "trackeeID", "timeT0", "ref01T0", "ref02T0", "ref03T0", "timeT1", "ref01T1", "ref02T1", "ref03T1" };
+
+void SSMTestApp::TrajectoryDataOutput(IModelData *pModelData)
+{
+    std::string name = "";
+    int l = 0;
+
+    std::string trackeeID;
+    std::string T0DateTime;
+    std::string T0Ref01;
+    std::string T0Ref02;
+    std::string T0Ref03;
+    std::string T1DateTime;
+    std::string T1Ref01;
+    std::string T1Ref02;
+    std::string T1Ref03;
+
+    for (int j = 0; j < pModelData->getPropertyCount(); j++)
+    {
+        name = pModelData->getPropertyName(j);
+
+        for (l = 0; l < INPUT_EA; l++)
+        {
+            if (name.compare(input_name[l]) == 0)
+                break;
+        }
+
+        switch (l)
+        {
+            case 0:
+                trackeeID = pModelData->getPropertyValue(j);
+                break;
+            case 1:
+                T0DateTime = pModelData->getPropertyValue(j);
+                break;
+            case 2:
+                T0Ref01 = pModelData->getPropertyValue(j);
+                break;
+            case 3:
+                T0Ref02 = pModelData->getPropertyValue(j);
+                break;
+            case 4:
+                T0Ref03 = pModelData->getPropertyValue(j);
+                break;
+            case 5:
+                T1DateTime = pModelData->getPropertyValue(j);
+                break;
+            case 6:
+                T1Ref01 = pModelData->getPropertyValue(j);
+                break;
+            case 7:
+                T1Ref02 = pModelData->getPropertyValue(j);
+                break;
+            case 8:
+                T1Ref03 = pModelData->getPropertyValue(j);
+                break;
+            default:
+                ;
+        }
+    }
+
+    printf("===========================================\n");
+    printf("        ITS Trajectory Data Output         \n");
+    printf("===========================================\n");
+    printf("\n");
+    printf(" < Trackee Thing ID : %s > \n", trackeeID.c_str());
+    printf("   - Trajectory 01         \n");
+    printf("     0. Date, Time : %s    \n", T0DateTime.c_str());
+    printf("     1. Ref. Thing : %s    \n", T0Ref01.c_str());
+    printf("     2. Ref. Thing : %s    \n", T0Ref02.c_str());
+    printf("     3. Ref. Thing : %s    \n", T0Ref03.c_str());
+    printf("\n");
+    printf("   - Trajectory 02         \n");
+    printf("     0. Date, Time : %s    \n", T1DateTime.c_str());
+    printf("     1. Ref. Thing : %s    \n", T1Ref01.c_str());
+    printf("     2. Ref. Thing : %s    \n", T1Ref02.c_str());
+    printf("     3. Ref. Thing : %s    \n", T1Ref03.c_str());
+    printf("\n");
+    printf("===========================================\n");
+}
+
 /* APP. Level Callback Function for Observer of client. */
 SSMRESULT SSMTestApp::onQueryEngineEvent(int cqid, IDataReader *pResult)
 {
@@ -110,6 +194,8 @@ SSMRESULT SSMTestApp::onQueryEngineEvent(int cqid, IDataReader *pResult)
                 cout << "Type: " << pModelData->getPropertyName(j) << " Value: " << pModelData->getPropertyValue(
                          j) << endl;
             }
+
+            //TrajectoryDataOutput(pModelData);
         }
     }
 
@@ -125,14 +211,25 @@ int main()
     printf("searching SSMResource\n");
     SSMTestApp *SSMApp = new SSMTestApp();
     APPMenu::APPMenu menu = APPMenu::NONE;
+    std::string strMenu;
+
+    std::string xmlDescription = "<SSMCore>"
+                                 "<Device>"
+                                 "<UDN>abcde123-31f8-11b4-a222-08002b34c003</UDN>"
+                                 "<Name>MyPC</Name>"
+                                 "<Type>PC</Type>"
+                                 "</Device>"
+                                 "</SSMCore>";
+
+    if (InitializeSSM(xmlDescription) != SSM_S_OK)
+        std::cout << "core init failed" << std::endl;
 
     while (menu != APPMenu::EXIT)
     {
         SSMApp->displayMenu();
 
-        menu = (APPMenu::APPMenu) (getchar() - '0');
-        if ((APPMenu::APPMenu) 0 > menu || menu > APPMenu::EXIT)
-            menu = (APPMenu::APPMenu) (getchar() - '0');
+        getline(cin, strMenu);
+        menu = (APPMenu::APPMenu) (atoi(strMenu.c_str()));
 
         switch (menu)
         {
@@ -151,6 +248,21 @@ int main()
                                       "if Device.DiscomfortIndexSensor.discomfortIndex > 0");
                 break;
 
+            case APPMenu::ITS_SAMPLE:
+                SSMApp->registerQuery("subscribe Device.IndoorTrajectorySensor "\
+                                      "if Device.IndoorTrajectorySensor.trackeeID == \"9059AF16FEF7\"");
+                break;
+
+            case APPMenu::BMI_SAMPLE:
+                SSMApp->registerQuery("subscribe Device.BMISensor "\
+                                      "if Device.BMISensor.BMIresult > 0");
+
+                break;
+
+
+
+
+
             case APPMenu::EXIT:
                 std::cout << "program exit." << std::endl;
                 break;
@@ -160,6 +272,10 @@ int main()
         }
     } // while
 
+    TerminateSSM();
+
     delete SSMApp;
+
+    return 0;
 }
 
index 9ea870c..78b6119 100644 (file)
@@ -13,15 +13,24 @@ linux_sample_env = lib_env.Clone()
 # Build flags
 ######################################################################
 linux_sample_env.AppendUnique(CPPPATH = ['include'])
-linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+linux_sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-pthread','-std=c++0x'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 linux_sample_env.AppendUnique(LIBS = ['oc'])
 linux_sample_env.AppendUnique(LIBS = ['octbstack'])
+linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction'])
 linux_sample_env.AppendUnique(LIBS = ['libcoap'])
 linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
 linux_sample_env.AppendUnique(LIBS = ['pthread'])
 
+if env.get('SECURED') == '1':
+    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+#
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
+
 ######################################################################
 #build sampleapp
 ######################################################################
diff --git a/service/soft-sensor-manager/SampleApp/linux/THSensorApp/build/Makefile b/service/soft-sensor-manager/SampleApp/linux/THSensorApp/build/Makefile
deleted file mode 100644 (file)
index 28802e8..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
--include ../../../../build/linux/root_path.inc
--include ../../../../build/linux/environment.mk
-
-BOOST=${BOOST_BASE}
-SRC_PATH=../src
-INC_PATH=../include
-RST_NAME=release
-
-# Insert your project name.
-TARGET=THSensorApp
-
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -DLINUX
-CXX_INC=-I${INC_PATH}/ -I${IOT_BASE}/include/ -I${IOT_LOG_DIR}/include/ -I${IOT_BASE}/csdk/stack/include -I${IOT_BASE}/csdk/ocsocket/include -I${IOT_BASE}/csdk/ocrandom/include -I${IOT_BASE}/csdk/logger/include -I${BOOST}
-
-CXX_LIB+=${IOT_RELEASE}/${IOT_LIB}
-CXX_LIB+=${IOT_CSDK_RELEASE}/${IOT_CSDK_LIB} 
-CXX_LIB+=${IOT_LOG_DIR}/lib/${IOT_LOG_LIB}
-CXX_LIB+=-lpthread
-
-SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
-OBJPATH=${SRCLIST:.cpp=.o}
-OBJLIST=${notdir ${OBJPATH}}
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job ${TARGET} post_job
-
-pre_job:
-       @echo " " 
-       @echo "---------- ${TARGET} Build Begin. ------------" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-
-${TARGET}: ${OBJLIST}
-       $(CXX) -o ./${RST_NAME}/$@ $^ ${CXX_LIB}
-       @echo " "
-
-%.o : ${SRC_PATH}/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o $@
-       @echo " "
-
-post_job:
-       @echo " " 
-       cp -Rdp ./${RST_NAME}/* ${OUTPUTS_DIR}/
-       @echo "----------- ${TARGET} Build Successful. -------------"
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " " 
-       
-       
-clean:
-       rm -f -v *.o ${TARGET}
-       rm -rf ./${RST_NAME}
-       
index 712a83b..acb6e65 100644 (file)
@@ -40,7 +40,7 @@ using namespace std;
 #define COAP_MODE               ModeType::Server
 #define COAP_SRVTYPE        ServiceType::InProc
 
-#define COAP_TYPE_NAME          "SoftSensorManager.Sensor"
+#define COAP_TYPE_NAME          "SSManager.Sensor"
 
 // Forward declaring the entityHandler
 
index 73f43e7..d1def40 100644 (file)
@@ -127,13 +127,6 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request
         response->setRequestHandle(request->getRequestHandle());
         response->setResourceHandle(request->getResourceHandle());
 
-        if (requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-
         if (requestFlag & RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
@@ -217,4 +210,6 @@ int main()
     {
         cout << e.what() << endl;
     }
+
+    return 0;
 }
index a238dc0..6fc0eb9 100644 (file)
@@ -13,15 +13,24 @@ linux_sample_env = lib_env.Clone()
 # Build flags
 ######################################################################
 linux_sample_env.AppendUnique(CPPPATH = ['include'])
-linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+linux_sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-pthread','-std=c++0x'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 linux_sample_env.AppendUnique(LIBS = ['oc'])
 linux_sample_env.AppendUnique(LIBS = ['octbstack'])
+linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction'])
 linux_sample_env.AppendUnique(LIBS = ['libcoap'])
 linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
 linux_sample_env.AppendUnique(LIBS = ['pthread'])
 
+if env.get('SECURED') == '1':
+    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
+
 ######################################################################
 #build sampleapp
 ######################################################################
diff --git a/service/soft-sensor-manager/SampleApp/linux/THSensorApp1/build/Makefile b/service/soft-sensor-manager/SampleApp/linux/THSensorApp1/build/Makefile
deleted file mode 100644 (file)
index a195f01..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
--include ../../../../build/linux/root_path.inc
--include ../../../../build/linux/environment.mk
-
-BOOST=${BOOST_BASE}
-SRC_PATH=../src
-INC_PATH=../include
-RST_NAME=release
-
-# Insert your project name.
-TARGET=THSensorApp1
-
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -DLINUX
-CXX_INC=-I${INC_PATH}/ -I${IOT_BASE}/include/ -I${IOT_LOG_DIR}/include/ -I${IOT_BASE}/csdk/stack/include -I${IOT_BASE}/csdk/ocsocket/include -I${IOT_BASE}/csdk/ocrandom/include -I${IOT_BASE}/csdk/logger/include -I${BOOST}
-
-CXX_LIB+=${IOT_RELEASE}/${IOT_LIB}
-CXX_LIB+=${IOT_CSDK_RELEASE}/${IOT_CSDK_LIB} 
-CXX_LIB+=${IOT_LOG_DIR}/lib/${IOT_LOG_LIB}
-CXX_LIB+=-lpthread
-
-SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
-OBJPATH=${SRCLIST:.cpp=.o}
-OBJLIST=${notdir ${OBJPATH}}
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job ${TARGET} post_job
-
-pre_job:
-       @echo " " 
-       @echo "---------- ${TARGET} Build Begin. ------------" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-
-${TARGET}: ${OBJLIST}
-       $(CXX) -o ./${RST_NAME}/$@ $^ ${CXX_LIB}
-       @echo " "
-
-%.o : ${SRC_PATH}/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o $@
-       @echo " "
-
-post_job:
-       @echo " " 
-       cp -Rdp ./${RST_NAME}/* ${OUTPUTS_DIR}/
-       @echo "----------- ${TARGET} Build Successful. -------------"
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " " 
-       
-       
-clean:
-       rm -f -v *.o ${TARGET}
-       rm -rf ./${RST_NAME}
-       
index c854f69..60316d4 100644 (file)
@@ -40,7 +40,7 @@ using namespace std;
 #define COAP_MODE               ModeType::Server
 #define COAP_SRVTYPE        ServiceType::InProc
 
-#define COAP_TYPE_NAME          "SoftSensorManager.Sensor"
+#define COAP_TYPE_NAME          "SSManager.Sensor"
 
 // Forward declaring the entityHandler
 
index 93c8e0d..d2bdd2a 100644 (file)
@@ -127,13 +127,6 @@ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request
         response->setRequestHandle(request->getRequestHandle());
         response->setResourceHandle(request->getResourceHandle());
 
-        if (requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-
         if (requestFlag & RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
@@ -217,4 +210,6 @@ int main()
     {
         cout << e.what() << endl;
     }
+
+    return 0;
 }
diff --git a/service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/SConscript b/service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/SConscript
new file mode 100644 (file)
index 0000000..f20cde8
--- /dev/null
@@ -0,0 +1,39 @@
+##
+# linux sample app  build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+linux_sample_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(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 = ['oc'])
+linux_sample_env.AppendUnique(LIBS = ['octbstack'])
+linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction'])
+linux_sample_env.AppendUnique(LIBS = ['libcoap'])
+linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
+linux_sample_env.AppendUnique(LIBS = ['pthread'])
+
+if env.get('SECURED') == '1':
+    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
+
+######################################################################
+#build sampleapp
+######################################################################
+weightsensorapp = linux_sample_env.Program('WeightSensorApp', 'src/WeightSensorApp.cpp')
+Alias("weightsensorapp_sample", weightsensorapp)
+env.AppendTarget('weightsensorapp')
diff --git a/service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/include/WeightSensorApp.h b/service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/include/WeightSensorApp.h
new file mode 100644 (file)
index 0000000..ee04991
--- /dev/null
@@ -0,0 +1,97 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+/*
+ * WeightSensorApp.h
+ */
+
+#ifndef WEIGHTSENSORAPP_H_
+#define WEIGHTSENSORAPP_H_
+
+#include <functional>
+#include <pthread.h>
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace std;
+
+#include <string>
+#include <cstdlib>
+
+#define COAP_IP                 "0.0.0.0"
+#define COAP_PORT               0
+#define COAP_MODE               ModeType::Server
+#define COAP_SRVTYPE        ServiceType::InProc
+
+#define COAP_TYPE_NAME          "SSManager.Sensor"
+
+//  testing case
+#define INTERVAL_FOR_CHECK          14   // seconds
+#define INTERVAL_FOR_MEASUREMENT    3   // seconds
+#define INIT_VAL                    33   // default value
+#define DIFF_VAL                    0.01   // default value
+
+
+
+// Forward declaring the entityHandler
+
+class WeightResource
+{
+    public:
+        /// Access this property from a TB client
+//        int m_humid;
+//        int m_temp;
+        double m_weight;
+        std::string m_resourceUri;
+        std::vector<std::string> m_resourceTypes;
+        std::vector<std::string> m_resourceInterfaces;
+        OCResourceHandle m_resourceHandle;
+        OCRepresentation m_resourceRep;
+        ObservationIds m_interestedObservers;
+
+    public:
+        /// Constructor
+        WeightResource() :
+            m_weight(0), m_resourceHandle(0)
+        {
+            m_resourceUri = "/Thing_WeightSensor";
+            m_resourceTypes.push_back(COAP_TYPE_NAME);
+            m_resourceInterfaces.push_back(DEFAULT_INTERFACE);
+
+            printf("Running thing as %s\n", m_resourceUri.c_str());
+            m_resourceRep.setUri(m_resourceUri);
+            m_resourceRep.setResourceTypes(m_resourceTypes);
+            m_resourceRep.setResourceInterfaces(m_resourceInterfaces);
+        }
+
+        ~WeightResource()
+        {
+        }
+
+        void registerResource();
+
+        OCResourceHandle getHandle();
+
+        void setResourceRepresentation(OCRepresentation &rep);
+
+        OCRepresentation getResourceRepresentation();
+};
+
+#endif /* THINGRESOURCESERVER_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/src/WeightSensorApp.cpp b/service/soft-sensor-manager/SampleApp/linux/WeightSensorApp/src/WeightSensorApp.cpp
new file mode 100644 (file)
index 0000000..d54023c
--- /dev/null
@@ -0,0 +1,243 @@
+
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <WeightSensorApp.h>
+
+int g_Observation = 0;
+
+OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request);
+
+/*
+ * TempResourceFunctions
+ */
+
+void WeightResource::registerResource()
+{
+    uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+
+    // This will internally create and register the resource.
+    OCStackResult result = OC::OCPlatform::registerResource(m_resourceHandle, m_resourceUri,
+                           m_resourceTypes[0], m_resourceInterfaces[0], &entityHandler, resourceProperty);
+
+    if (OC_STACK_OK != result)
+    {
+        cout << "Resource creation was unsuccessful\n";
+    }
+}
+
+OCResourceHandle WeightResource::getHandle()
+{
+    return m_resourceHandle;
+}
+
+void WeightResource::setResourceRepresentation(OCRepresentation &rep)
+{
+    double tempWeight;
+
+
+
+    rep.getValue("2", tempWeight);
+
+
+    m_weight= tempWeight;
+
+    cout << "\t\t\t" << "Received representation: " << endl;
+
+    cout << "\t\t\t\t" << "Weight" << m_weight << endl;
+
+}
+
+OCRepresentation WeightResource::getResourceRepresentation()
+{
+
+    m_resourceRep.setValue("0", std::string("weight"));
+    m_resourceRep.setValue("1", std::string("double"));
+    m_resourceRep.setValue("2", std::to_string(m_weight));
+
+    return m_resourceRep;
+}
+
+// Create the instance of the TemphumidResource class
+WeightResource g_myResource;
+
+void *TestSensorVal(void *param)
+{
+
+    bool bFlag = true;
+    int nSleep_time=INTERVAL_FOR_CHECK;
+    double nWeight;
+
+    std::cout << "[WeightSensorAPP] ::" << __func__ << " is called."
+              << std::endl;
+
+//     g_myResource.m_weight = 33;
+       nWeight=INIT_VAL;
+
+    // This function continuously monitors for the changes
+    while (1)
+    {
+
+
+        sleep(nSleep_time);
+
+
+        if (g_Observation)
+        {
+
+                       //g_myResource.m_weight+=0.01;
+
+            if(bFlag){
+
+                nSleep_time =INTERVAL_FOR_MEASUREMENT;
+                nWeight+=DIFF_VAL;
+                g_myResource.m_weight=nWeight;
+            }
+            else{
+                nSleep_time =INTERVAL_FOR_CHECK;
+                g_myResource.m_weight=0;
+
+
+            }
+            bFlag=bFlag^true;
+
+                       cout << "\n weight updated to : " << g_myResource.m_weight << endl;
+            cout << "Notifying observers with resource handle: " << g_myResource.getHandle()
+                 << endl;
+
+            OCStackResult result = OCPlatform::notifyAllObservers(g_myResource.getHandle());
+
+            if (OC_STACK_NO_OBSERVERS == result)
+            {
+                cout << "No More observers, stopping notifications" << endl;
+                g_Observation = 0;
+            }
+        }
+        else{
+
+            nSleep_time=INTERVAL_FOR_CHECK ;
+        }
+
+    }
+    return NULL;
+}
+
+OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
+{
+    cout << "\tIn Server CPP entity handler:\n";
+
+    auto response = std::make_shared<OC::OCResourceResponse>();
+
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        response->setRequestHandle(request->getRequestHandle());
+        response->setResourceHandle(request->getResourceHandle());
+
+        if (requestFlag & RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\t\trequestFlag : Request\n";
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                cout << "\t\t\trequestType : GET\n";
+
+                // Check for query params (if any)
+                // Process query params and do required operations ..
+
+                // Get the representation of this resource at this point and send it as response
+                OCRepresentation rep = g_myResource.getResourceRepresentation();
+
+                if (response)
+                {
+                    // TODO Error Code
+                    response->setErrorCode(200);
+                    response->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+                }
+            }
+            else if (requestType == "PUT")
+            {
+                // PUT request operations
+            }
+            else if (requestType == "POST")
+            {
+                // POST request operations
+            }
+            else if (requestType == "DELETE")
+            {
+                // DELETE request operations
+            }
+        }
+
+        if (requestFlag & RequestHandlerFlag::ObserverFlag)
+        {
+            pthread_t threadId;
+
+            cout << "\t\trequestFlag : Observer\n";
+            g_Observation = 1;
+
+            static int startedThread = 0;
+
+            if (!startedThread)
+            {
+                pthread_create(&threadId, NULL, TestSensorVal, (void *) NULL);
+                startedThread = 1;
+            }
+        }
+    }
+    else
+    {
+        std::cout << "Request invalid" << std::endl;
+    }
+
+    return OCPlatform::sendResponse(response) == OC_STACK_OK ? OC_EH_OK : OC_EH_ERROR;
+}
+
+int main()
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg(COAP_SRVTYPE, COAP_MODE, COAP_IP, COAP_PORT, OC::QualityOfService::LowQos);
+
+    try
+    {
+        OC::OCPlatform::Configure(cfg);
+
+        OC::OCPlatform::startPresence(60);
+
+        g_myResource.registerResource();
+
+        int input = 0;
+        cout << "Type any key to terminate" << endl;
+        cin >> input;
+
+        OC::OCPlatform::stopPresence();
+    }
+    catch (std::exception e)
+    {
+        cout << e.what() << endl;
+    }
+
+    return 0;
+}
+
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.cproject b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.cproject
new file mode 100644 (file)
index 0000000..c9ca9aa
--- /dev/null
@@ -0,0 +1,500 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+    <storageModule moduleId="org.eclipse.cdt.core.settings">
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.1759354984">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.1759354984" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="ssmtesterapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.1759354984" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.1759354984." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.1524125598" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.438965509" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder arguments="--eval=&quot;SHELL=cmd&quot; -r" autoBuildTarget="all" buildPath="${workspace_loc:/SSMTesterApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1272946954" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.907623847" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1464317827" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.1920031956" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.2131247620" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.835883654" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.246263650" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.609559263" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.1557878834" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                    <listOptionValue builtIn="false" value="../../../../SDK/cpp/include"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1610915586" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.preprocessor.def.262882436" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.1647886114" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+                                <option id="gnu.cpp.compiler.option.debugging.prof.1349765601" name="Generate prof information (-p)" superClass="gnu.cpp.compiler.option.debugging.prof" value="true" valueType="boolean"/>
+                                <option id="gnu.cpp.compiler.option.debugging.gprof.1355052147" name="Generate gprof information (-pg)" superClass="gnu.cpp.compiler.option.debugging.gprof" value="true" valueType="boolean"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.647889480" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2042697550" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1983500575" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.875840698" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.601846887" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.114207163" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.776351665" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.1247920699" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.912909608" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.preprocessor.def.symbols.1018307890" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.906299864" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1207528008" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.175848365" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1944778649" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.1904479113" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.libs.1117844346" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+                                    <listOptionValue builtIn="false" value="DiscomfortIndexSensor"/>
+                                    <listOptionValue builtIn="false" value="SSMSDK"/>
+                                    <listOptionValue builtIn="false" value="SSMCore"/>
+                                    <listOptionValue builtIn="false" value="oc"/>
+                                    <listOptionValue builtIn="false" value="octbstack"/>
+                                    <listOptionValue builtIn="false" value="coap"/>
+                                    <listOptionValue builtIn="false" value="oc_logger"/>
+                                    <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.debugging.prof.212252607" name="Generate prof information (-p)" superClass="gnu.cpp.link.option.debugging.prof" value="true" valueType="boolean"/>
+                                <option id="gnu.cpp.link.option.debugging.gprof.279130410" name="Generate gprof information (-pg)" superClass="gnu.cpp.link.option.debugging.gprof" value="true" valueType="boolean"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.185903547" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1918776742" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.133784198" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.1811143577" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.1871688522" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.1389706774" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.648727761" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.359523702" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.247885576" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1828853666">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1828853666" moduleId="org.eclipse.cdt.core.settings" name="Release">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="ssmtesterapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1828853666" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1828853666." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.554647662" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1489649649" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder buildPath="${workspace_loc:/SSMTesterApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.1140017860" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.2069329217" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.842331421" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.780111871" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.890745088" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.cpp.compiler.option.166413107" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.439465397" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1589175012" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.713140808" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.2116397008" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1065457838" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.332088326" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1635443652" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.1885401470" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.c.compiler.option.1663673007" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.903755728" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.2010312163" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.752143517" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.611905049" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1375990853" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.598995844" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2110452371" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.709019684" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.1652494195" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.126637398" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.188655324" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.576018509" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.1099322714" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.1354250034" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.855577227" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.1343076491" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1488434689" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.597076044" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+    </storageModule>
+    <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+        <project id="SSMTesterApp.org.tizen.nativecore.target.sbi.gcc45.app.1919622753" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+    </storageModule>
+    <storageModule moduleId="scannerConfiguration">
+        <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1828853666">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.1759354984">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+    </storageModule>
+    <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+    <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+    <storageModule moduleId="refreshScope" versionNumber="2">
+        <configuration configurationName="Debug">
+            <resource resourceType="PROJECT" workspacePath="/SSMTesterApp"/>
+        </configuration>
+        <configuration configurationName="Release">
+            <resource resourceType="PROJECT" workspacePath="/SSMTesterApp"/>
+        </configuration>
+    </storageModule>
+    <storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+</cproject>
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.exportMap b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.exportMap
new file mode 100644 (file)
index 0000000..43e310e
--- /dev/null
@@ -0,0 +1,4 @@
+{
+       global: main;
+       local: *;
+};
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.gitignore b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.gitignore
new file mode 100644 (file)
index 0000000..98bbc31
--- /dev/null
@@ -0,0 +1 @@
+/Debug
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.project b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.project
new file mode 100644 (file)
index 0000000..724dd3a
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>SSMTesterApp</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+            <triggers>full,incremental,</triggers>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.tizen.nativecore.apichecker.core.builder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.cdt.core.cnature</nature>
+        <nature>org.eclipse.cdt.core.ccnature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+        <nature>org.tizen.nativecore.apichecker.core.tizenCppNature</nature>
+    </natures>
+    <filteredResources>
+        <filter>
+            <id>1421295144734</id>
+            <name></name>
+            <type>26</type>
+            <matcher>
+                <id>org.eclipse.ui.ide.multiFilter</id>
+                <arguments>1.0-projectRelativePath-matches-false-false-*/.tpk</arguments>
+            </matcher>
+        </filter>
+    </filteredResources>
+</projectDescription>
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.rds_delta b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.rds_delta
new file mode 100644 (file)
index 0000000..3eac727
--- /dev/null
@@ -0,0 +1,6 @@
+#delete
+#add
+#modify
+author-signature.xml
+signature1.xml
+bin/ssmtesterapp
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.sdk_delta.info b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.sdk_delta.info
new file mode 100644 (file)
index 0000000..9017e05
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.sdk_delta.info differ
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.tproject b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/.tproject
new file mode 100644 (file)
index 0000000..f1cc1fd
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<tproject xmlns="http://www.tizen.org/tproject">
+    <platforms>
+        <platform>
+            <name>mobile-2.3</name>
+        </platform>
+    </platforms>
+    <package>
+        <blacklist/>
+    </package>
+</tproject>
index 7aa6d40..7ec7d7e 100644 (file)
@@ -10,7 +10,6 @@ SET(CMAKE_EXE_LINKER_FLAGS " -Wl,--as-needed -Wl,--hash-style=both")
 
 #INCLUDE_DIRECTORIES(include)
 #INCLUDE_DIRECTORIES(csdk/stack/include)
-#INCLUDE_DIRECTORIES(csdk/ocsocket/include)
 #INCLUDE_DIRECTORIES(csdk/ocrandom/include)
 #INCLUDE_DIRECTORIES(csdk/logger/include)
 #INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/boost)
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.
 
+
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/inc/ssmtesterapp.h b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/inc/ssmtesterapp.h
new file mode 100644 (file)
index 0000000..20f8e61
--- /dev/null
@@ -0,0 +1,19 @@
+#ifndef __ssmtesterapp_H__
+#define __ssmtesterapp_H__
+
+#include <app.h>
+#include <Elementary.h>
+#include <system_settings.h>
+#include <efl-extension/efl_extension.h>
+#include <dlog.h>
+
+#ifdef  LOG_TAG
+#undef  LOG_TAG
+#endif
+#define LOG_TAG "ssmtesterapp"
+
+#if !defined(PACKAGE)
+#define PACKAGE "org.iotivity.service.ssm.ssmtesterapp"
+#endif
+
+#endif /* __ssmtesterapp_H__ */
index 85ece27..43e841f 100644 (file)
@@ -13,7 +13,6 @@ CXX_FLAGS.release   := -std=c++0x -Wall -pthread
 
 CXX_INC          := -I./include/
 CXX_INC          += -I./csdk/stack/include
-CXX_INC          += -I./csdk/ocsocket/include
 CXX_INC          += -I./csdk/ocrandom/include
 CXX_INC          += -I./csdk/logger/include
 CXX_INC   += -I/usr/local/boost_1_51_0
@@ -68,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)
+
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-log.h b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-log.h
deleted file mode 100644 (file)
index a0b3484..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2010 Samsung Electronics, Inc.
- * All rights reserved.
- *
- * This software is a confidential and proprietary information
- * of Samsung Electronics, Inc. ("Confidential Information").  You
- * shall not disclose such Confidential Information and shall use
- * it only in accordance with the terms of the license agreement
- * you entered into with Samsung Electronics.
- */
-#ifndef __OICAPP_LOG_H__
-#define __OICAPP_LOG_H__
-
-#define TIZEN_DEBUG_ENABLE
-#define LOG_TAG "OIC_TEST"
-#include <dlog.h>
-
-#define LOG_COLOR_RED       "\033[0;31m"
-#define LOG_COLOR_BROWN     "\033[0;33m"
-#define LOG_COLOR_BLUE      "\033[0;34m"
-#define LOG_COLOR_END       "\033[0;m"
-
-
-#if 1
-#define _DBG(fmt, arg...) SLOGD(fmt, ##arg)
-#define _INFO(fmt, arg...) SLOGI(fmt, ##arg)
-#define _WARN(fmt, arg...) SLOGW(fmt, ##arg)
-#define _ERR(fmt, arg...) SLOGE(fmt, ##arg)
-#else
-#define _DBG(fmt, arg...) \
-    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
-#define _INFO(fmt, arg...) \
-    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
-#define _WARN(fmt, arg...) \
-    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
-#define _ERR(fmt, arg...) \
-    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
-#endif
-
-#define DBG(fmt, arg...) _DBG(fmt, ##arg)
-#define WARN(fmt, arg...) _WARN(LOG_COLOR_BROWN fmt LOG_COLOR_END, ##arg)
-#define ERR(fmt, arg...) _ERR(LOG_COLOR_RED fmt LOG_COLOR_END, ##arg)
-#define INFO(fmt, arg...) _INFO(LOG_COLOR_BLUE fmt LOG_COLOR_END, ##arg)
-
-#define ret_if(expr) \
-    do { \
-        if (expr) { \
-            ERR("(%s)", #expr); \
-            return; \
-        }\
-    } while(0)
-#define retv_if(expr, val) \
-    do {\
-        if (expr) { \
-            ERR("(%s)", #expr); \
-            return (val); \
-        } \
-    } while(0)
-#define retm_if(expr, fmt, arg...) \
-    do {\
-        if (expr) { \
-            ERR(fmt, ##arg); \
-            return; \
-        }\
-    } while(0)
-#define retvm_if(expr, val, fmt, arg...) \
-    do {\
-        if (expr) { \
-            ERR(fmt, ##arg); \
-            return (val); \
-        } \
-    } while(0)
-#define warn_if(expr) \
-    do { \
-        if (expr) { \
-            WARN("(%s)", #expr); \
-        } \
-    } while (0)
-
-
-#endif //__OICAPP_LOG_H__
-
index 826ef69..551a997 100644 (file)
@@ -67,7 +67,6 @@ class CQueryEngineEvent : public IQueryEngineEvent
 };
 
 CQueryEngineEvent   *g_SSMClientListener = new CQueryEngineEvent();
-SSMInterface        *g_SSMClient = new SSMInterface();
 
 static Elm_Object_Item *oicapp_append_separator(Evas_Object *genlist,
         oicapp_data *ad)
@@ -290,7 +289,7 @@ static void _btn_clicked(void *data, Evas_Object *obj, void *event_info)
         str.replace(foundLT, strLT.length(), "<");
     }
 
-    g_SSMClient->registerQuery(str, g_SSMClientListener, g_CQID);
+    RegisterQuery(str, g_SSMClientListener, g_CQID);
 
     sstream << "Query executed! cqid = " << g_CQID << std::ends;
 
@@ -429,7 +428,7 @@ static int oicapp_terminate(void *data)
     oicapp_data *ad = (oicapp_data *)data;
 
     if (g_CQID != 9999)
-        g_SSMClient->unregisterQuery(g_CQID);
+        UnregisterQuery(g_CQID);
 
     if (ad->win)
         evas_object_del(ad->win);
@@ -495,3 +494,4 @@ int main(int argc, char *argv[])
     return appcore_efl_main(PACKAGE, &argc, &argv, &ops);
 }
 
+
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
+
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/res/ui_controls.edc b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/res/ui_controls.edc
new file mode 100644 (file)
index 0000000..cd6c582
--- /dev/null
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd 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.
+ *
+ */
+
+collections {
+   base_scale: 1.8;
+   group { name: "mainpage_layout";
+   parts{
+          part { name: "query_text_bg";
+                type: RECT;
+                scale: 1;
+                description { state: "default" 0.0;
+                   color: 220 220 220 255;
+                                   
+                     align: 0.0 0.02;
+                     // set the size to 200x200
+                     min: 200 200;
+                     max: 350 250;     
+                }
+             }
+          
+        part { name: "query_text";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;                   
+                     rel1.to: "query_text_bg";
+              rel2.to: "query_text_bg";             
+                       }
+       }
+       part { name: "register";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.2 0.01;
+
+                     min: 100 100;
+                     max: 275 100;               
+
+                     rel1.relative: 1.0 0.1;
+                     rel1.to: "query_text";
+                     //rel2.relative: 1.0 1.0;                                  
+                       }
+       }
+       part { name: "clear";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.0 0.02;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 275 100;                                  
+                     rel1.relative: 0.0 1.0;
+                     rel1.to: "register";
+                    // rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "example_queries";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.0 0.02;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 500 100;                                  
+                     rel1.relative: 0.0 1.0;
+                     rel1.to: "query_text";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "search_devices";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.0 0.0;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 360 100;                                  
+                     rel1.relative: 0.0 0.7;
+                     rel1.to: "example_queries";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "discomfort_index";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.1 0.0;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 360 100;                                  
+                     rel1.relative: 1.0 0.0;
+                     rel1.to: "search_devices";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "unregister_query_label";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.0 0.02;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 500 100;                                  
+                     rel1.relative: 0.0 1.0;
+                     rel1.to: "search_devices";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "minus";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.0 0.02;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 100 100;                                  
+                     rel1.relative: 0.0 0.7;
+                     rel1.to: "unregister_query_label";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "unregister_query_id_bg";
+                type: RECT;
+                scale: 1;
+                description { state: "default" 0.0;
+                   color: 220 220 220 255;
+                                   
+                     align: 0.02 0.0;
+                     // set the size to 200x200
+                     min: 100 75;
+                     max: 175 75;      
+                     
+                     rel1.relative: 1.0 0.0;
+                     rel1.to: "minus";
+                     rel2.relative: 1.0 1.0;  
+                }
+             }
+       
+       
+       part { name: "unregister_query_id";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                         rel1.to: "unregister_query_id_bg";
+              rel2.to: "unregister_query_id_bg";                                                                             
+                       }
+       }
+       
+       part { name: "plus";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.02 0.0;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 100 100;                                  
+                     rel1.relative: 1.0 0.0;
+                     rel1.to: "unregister_query_id";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "unregister_button";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.2 0.0;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 250 100;                                  
+                     rel1.relative: 1.0 0.0;
+                     rel1.to: "plus";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "log_button";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.0 0.05;
+                     // set the size to 200x200
+                     min: 100 100;
+                     max: 720 100;                                  
+                     rel1.relative: 0.0 1.0;
+                     rel1.to: "minus";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+       
+       part { name: "log_text_bg";
+                  type: RECT;
+                  scale: 1;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                     align: 0.02 0.02;
+                      color: 220 220 220 255;
+                     // set the size to 200x200
+                     min: 100 400;
+                     max: 720 200;                                  
+                     rel1.relative: 0.0 1.0;
+                     rel1.to: "log_button";
+                     rel2.relative: 1.0 1.0;   
+                       }
+       }
+               
+       part { name: "log_text";
+                  type: SWALLOW;
+                  description 
+                  { 
+                     state: "default" 0.0;
+                       rel1.to: "log_text_bg";
+              rel2.to: "log_text_bg";
+                       }
+       }
+   }
+}
+}
+
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/shared/res/ssmtesterapp.png b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/shared/res/ssmtesterapp.png
new file mode 100644 (file)
index 0000000..9765b1b
Binary files /dev/null and b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/shared/res/ssmtesterapp.png differ
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/src/ssmtesterapp.cpp b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/src/ssmtesterapp.cpp
new file mode 100644 (file)
index 0000000..ad06fe5
--- /dev/null
@@ -0,0 +1,660 @@
+#include <tizen.h>
+#include <wifi.h>
+#include <net_connection.h>
+#include <algorithm>
+#include "string.h"
+#include "ssmtesterapp.h"
+#include "SSMInterface.h"
+
+typedef struct appdata {
+       Evas_Object *win;
+       Evas_Object *conform;
+       Evas_Object *naviframe;
+       Evas_Object *layout;
+       Evas_Object *scroller;
+       Evas_Object *box;
+
+       Evas_Object *query_text;
+       Evas_Object *log;
+       Evas_Object *unregister_query_id;
+
+       Evas_Object *register_button;
+       Evas_Object *clear_button;
+       Evas_Object *unregister_button;
+       Evas_Object *search_devices_button;
+       Evas_Object *discomfort_index_button;
+       Evas_Object *plus_button;
+       Evas_Object *minus_button;
+       Evas_Object *clear_log_button;
+
+       Evas_Object *example_queries_label;
+       Evas_Object *unregister_query_label;
+} appdata_s;
+
+typedef struct threadContext{
+       appdata_s *ad;
+       const char *log;
+} threadContext_s;
+
+#define ELM_DEMO_EDJ "opt/usr/apps/org.iotivity.service.ssm.ssmtesterapp/res/ui_controls.edj"
+
+char log_buffer[10000];
+void updateLog(appdata_s *ad, const char *newlog)
+{
+       const char *log_text = NULL;
+
+       log_text = elm_entry_entry_get(ad->log);
+       strcpy(log_buffer,log_text);
+       strcat(log_buffer,newlog);
+       elm_entry_entry_set(ad->log,log_buffer);
+       elm_entry_cursor_end_set(ad->log);
+}
+
+void* updateCallbackLog(void *data)
+{
+       threadContext_s  *pThreadContext = (threadContext_s*)data;
+
+       updateLog(pThreadContext->ad, pThreadContext->log);
+
+       return NULL;
+}
+
+static int s_hc2i(char hexChar)
+{
+    if ((hexChar <= '9') && (hexChar >= '0')) return (int)hexChar-(int)'0';
+    if ((hexChar <= 'F') && (hexChar >= 'A')) return 10+(int)hexChar-(int)'A';
+    if ((hexChar <= 'f') && (hexChar >= 'a')) return 10+(int)hexChar-(int)'a';
+    return -1;
+}
+
+long long s_h2uint64(const char *hex, size_t maxdigit)
+{
+    long long nNumber = 0;
+    int nInt;
+    size_t nLen=0;
+    while (nLen < maxdigit && (nInt = s_hc2i(*hex)) >= 0) {
+        nNumber=(nNumber*(long long)16) + (long long)nInt;
+        hex++;
+        nLen++;
+    }
+    return nNumber;
+}
+
+int s_h2i(char *strHex) {
+    return (int) s_h2uint64(strHex, sizeof(int)*2);
+}
+
+void unescape(char *val)
+{
+    char *tmp = (char *)val;
+    int i,nChar;
+    int len;
+
+    if (!val) return;
+    len=(int)strlen(val);
+
+    // process special chars
+    while (*tmp) {
+        if (!strncmp((char *)tmp,"&amp;",5)) {
+            *tmp='&';
+            memmove(&tmp[1],&tmp[5],strlen((char *)&tmp[5])+1);
+        }
+        else if (!strncmp((char *)tmp,"&nbsp;",6)) {
+            *tmp=' ';
+            memmove(&tmp[1],&tmp[6],strlen((char *)&tmp[6])+1);
+        }
+        else if (!strncmp((char *)tmp,"&lt;",4)) {
+            *tmp='<';
+            memmove(&tmp[1],&tmp[4],strlen((char *)&tmp[4])+1);
+        }
+        else if (!strncmp((char *)tmp,"&gt;",4)) {
+            *tmp='>';
+            memmove(&tmp[1],&tmp[4],strlen((char *)&tmp[4])+1);
+        }
+        else if (!strncmp((char *)tmp,"&apos;",6)) {
+            *tmp='\'';
+            memmove(&tmp[1],&tmp[6],strlen((char *)&tmp[6])+1);
+        }
+        else if (!strncmp((char *)tmp,"&quot;",6)) {
+            *tmp='"';
+            memmove(&tmp[1],&tmp[6],strlen((char *)&tmp[6])+1);
+        }
+        else if (!strncmp((char *)tmp,"&#",2)) { // &#nnn; || &#xnn;
+            for(i=2;i<7;i++) {
+                if (tmp[i] == ';') {
+                    if (tmp[2]=='x') nChar=s_h2i((char *)&tmp[3]);
+                    else nChar=atoi((char *)&tmp[2]);
+                    *tmp=(char)nChar;
+                    memmove(&tmp[1],&tmp[i+1],strlen((char *)&tmp[i+1])+1);
+                    break;
+                }
+            }
+        }
+        tmp++;
+    }
+
+    if (tmp < (char *)(val+len))
+        *tmp='\0';
+}
+
+class CQueryEngineEvent : public OIC::IQueryEngineEvent
+{
+private:
+       appdata_s *m_pAppData;
+       threadContext_s m_ThreadContext;
+
+public:
+       CQueryEngineEvent(appdata_s *pAppData)
+       {
+               m_pAppData = pAppData;
+               m_ThreadContext.ad = m_pAppData;
+               m_ThreadContext.log = NULL;
+       }
+
+       OIC::SSMRESULT onQueryEngineEvent(int cqid, OIC::IDataReader *pResult)
+       {
+               int     dataCount = 0;
+               char log[2000],buf[100];
+               OIC::IModelData      *pModelData = NULL;
+               std::vector<std::string>        affectedModels;
+
+               dlog_print(DLOG_ERROR,LOG_TAG,"Event received!");
+
+               sprintf(buf,"Event received! cqid = %d<br>", cqid);
+               strcpy(log,buf);
+
+               pResult->getAffectedModels(&affectedModels);
+
+               for (std::vector<std::string>::iterator itor = affectedModels.begin();
+                               itor != affectedModels.end(); ++itor)
+               {
+                       sprintf(buf,"Printing = %s model<br>", (*itor).c_str());
+                       strcat(log,buf);
+
+                       pResult->getModelDataCount(*itor, &dataCount);
+                       for (int i = 0; i < dataCount; i++)
+                       {
+                               pResult->getModelData(*itor, i, &pModelData);
+                               sprintf(buf,"dataId: %d<br>", pModelData->getDataId());
+                               strcat(log,buf);
+                               for (int j = 0; j < pModelData->getPropertyCount(); j++)
+                               {
+                                       sprintf(buf,"Type: %s Value: %s<br>", (pModelData->getPropertyName(j)).c_str(), (pModelData->getPropertyValue(j)).c_str());
+                                       strcat(log,buf);
+                               }
+                               m_ThreadContext.log = log;
+                               ecore_main_loop_thread_safe_call_sync((void *(*)(void *))updateCallbackLog, &m_ThreadContext);
+                       }
+               }
+
+               return OIC::SSM_S_OK;
+       }
+};
+
+CQueryEngineEvent              *g_pQueryEngineEvent = NULL;
+
+
+static void
+win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       ui_app_exit();
+}
+
+static void
+win_back_cb(void *data, Evas_Object *obj, void *event_info)
+{
+       //appdata_s *ad = (appdata_s *)data;
+       /* Let window go to hide state. */
+       //elm_win_lower(ad->win);
+       ui_app_exit();
+}
+
+
+static void
+register_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       const char *main_text = NULL;
+       char *escaped_text = NULL;
+       if (!ad->query_text)
+               return;
+       main_text = elm_entry_entry_get(ad->query_text);
+       if (!main_text || (strlen(main_text) == 0))
+               return;
+
+       //invoke registerQuery
+       int qid = 0;
+       char log[50];
+
+       escaped_text = strdup(main_text);
+       unescape(escaped_text);
+
+    dlog_print(DLOG_ERROR,LOG_TAG,"registering query");
+
+       OIC::SSMRESULT res = OIC::RegisterQuery(escaped_text, g_pQueryEngineEvent, qid);
+       if(res == OIC::SSM_S_OK)
+       {
+               updateLog(ad, "The query has been registered!<br>");
+               sprintf(log, "QID : %d<br>", qid);
+               updateLog(ad, log);
+       }
+       else
+       {
+               sprintf(log,"Error occured(%d)<br>", res);
+               updateLog(ad, log);
+       }
+
+       free(escaped_text);
+
+       dlog_print(DLOG_ERROR,LOG_TAG,"registering query done");
+}
+
+static void
+search_devices_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       elm_entry_entry_set(ad->query_text, "subscribe Device if Device.dataId > 0");
+}
+
+static void
+discomfort_index_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       elm_entry_entry_set(ad->query_text, "subscribe Device.DiscomfortIndexSensor "\
+                       "if Device.DiscomfortIndexSensor.discomfortIndex != 0");
+}
+
+static void
+minus_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       char output[10];
+       const char *query_id_str = elm_entry_entry_get(ad->unregister_query_id);
+       if (!query_id_str || (strlen(query_id_str) == 0))
+               return;
+       try{
+               int val = atoi(query_id_str);
+               sprintf(output,"%d",val-1);
+               elm_entry_entry_set(ad->unregister_query_id,output);
+       }
+       catch(...){
+               dlog_print(DLOG_ERROR,LOG_TAG,"#### atoi() conversion error");
+       }
+}
+
+static void
+plus_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       char output[10];
+       const char *query_id_str = elm_entry_entry_get(ad->unregister_query_id);
+       if (!query_id_str || (strlen(query_id_str) == 0))
+               return;
+       try{
+               int val = atoi(query_id_str);
+               sprintf(output,"%d",val+1);
+               elm_entry_entry_set(ad->unregister_query_id,output);
+       }
+       catch(...){
+               dlog_print(DLOG_ERROR,LOG_TAG,"#### atoi() conversion error");
+       }
+}
+
+static void
+unregister_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       const char *qidstr = NULL;
+       if (!ad->unregister_query_id)
+               return;
+       qidstr = elm_entry_entry_get(ad->unregister_query_id);
+       if (!qidstr || (strlen(qidstr) == 0))
+               return;
+       char log[50];
+       int qid;
+       try{
+               qid = atoi(qidstr);
+               //invoke unregisterQuery
+               OIC::SSMRESULT res = OIC::UnregisterQuery(qid);
+               if(res == OIC::SSM_S_OK)
+               {
+                       updateLog(ad, "The query has been unregistered!<br>");
+                       sprintf(log, "QID : %d<br>", qid);
+                       updateLog(ad, log);
+               }
+               else
+               {
+                       sprintf(log,"Error occured(%d)<br>", res);
+                       updateLog(ad, log);
+               }
+       }
+       catch(...){
+               dlog_print(DLOG_ERROR,LOG_TAG,"#### atoi() conversion error");
+       }
+}
+
+static void
+clear_log_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       elm_entry_entry_set(ad->log,"");
+}
+
+static void
+clear_cb(void *data , Evas_Object *obj , void *event_info)
+{
+       appdata_s *ad = (appdata_s *)data;
+       elm_entry_entry_set(ad->query_text,"");
+}
+
+bool is_connected()
+{
+       bool isConnected = false;
+
+       static connection_h connection;
+
+       if(connection_create(&connection) == CONNECTION_ERROR_NONE)
+       {
+           char *ip_addr = NULL;
+           connection_get_ip_address(connection, CONNECTION_ADDRESS_FAMILY_IPV4, &ip_addr);
+           connection_destroy(connection);
+           if(strlen(ip_addr) > 0)
+               isConnected = true;
+           free(ip_addr);
+       }
+
+       return isConnected;
+}
+
+static void
+create_base_gui(appdata_s *ad)
+{
+       /* Window */
+       ad->win = elm_win_util_standard_add(PACKAGE, PACKAGE);
+       elm_win_conformant_set(ad->win, EINA_TRUE);
+       elm_win_autodel_set(ad->win, EINA_TRUE);
+
+       if (elm_win_wm_rotation_supported_get(ad->win)) {
+               int rots[4] = { 0, 90, 180, 270 };
+               elm_win_wm_rotation_available_rotations_set(ad->win, (const int *)(&rots), 4);
+       }
+
+       evas_object_smart_callback_add(ad->win, "delete,request", win_delete_request_cb, NULL);
+       eext_object_event_callback_add(ad->win, EEXT_CALLBACK_BACK, win_back_cb, ad);
+
+       /* Conformant */
+       ad->conform = elm_conformant_add(ad->win);
+       evas_object_size_hint_weight_set(ad->conform, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+       elm_win_resize_object_add(ad->win, ad->conform);
+       evas_object_show(ad->conform);
+
+       /* naviframe */
+       ad->naviframe = elm_naviframe_add(ad->conform);
+       elm_object_content_set(ad->conform,ad->naviframe);
+       evas_object_show(ad->naviframe);
+
+       /* scroller */
+       ad->scroller = elm_scroller_add(ad->naviframe);
+
+       /* Box container */
+       ad->box = elm_box_add(ad->scroller);
+       evas_object_size_hint_align_set(ad->box, EVAS_HINT_FILL, 0.0);
+       evas_object_size_hint_weight_set(ad->box, EVAS_HINT_EXPAND, 0.0);
+       elm_object_content_set(ad->scroller, ad->box);
+
+       ad->layout = elm_layout_add(ad->box);
+       evas_object_size_hint_weight_set(ad->layout, EVAS_HINT_EXPAND, 0.0);
+       //elm_layout_theme_set(ad->layout, "layout", "application", "default");
+       evas_object_size_hint_align_set(ad->layout, EVAS_HINT_FILL, 0.0);
+       elm_layout_file_set(ad->layout,ELM_DEMO_EDJ,"mainpage_layout");
+
+       ad->query_text = elm_entry_add(ad->layout);
+       elm_object_part_text_set(ad->query_text, "elm.guide", "Enter the query here!!!");
+       evas_object_size_hint_align_set(ad->query_text, EVAS_HINT_FILL, EVAS_HINT_FILL);
+       evas_object_size_hint_weight_set(ad->query_text, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+       elm_object_part_content_set(ad->layout,"query_text",ad->query_text);
+       elm_entry_scrollable_set(ad->query_text,EINA_TRUE);
+       //evas_object_show(ad->query_text);
+       elm_entry_input_panel_show_on_demand_set(ad->query_text,EINA_TRUE);
+
+       ad->register_button = elm_button_add(ad->layout);
+       elm_object_text_set(ad->register_button, "Register");
+       evas_object_size_hint_weight_set(ad->register_button, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+       evas_object_size_hint_align_set(ad->register_button, EVAS_HINT_FILL, EVAS_HINT_FILL);
+       evas_object_smart_callback_add(ad->register_button, "clicked", register_cb, ad);
+       elm_object_part_content_set(ad->layout,"register",ad->register_button);
+       //evas_object_show(ad->register_button);
+
+       ad->clear_button = elm_button_add(ad->layout);
+       elm_object_text_set(ad->clear_button, "Clear");
+       evas_object_size_hint_weight_set(ad->search_devices_button, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+       evas_object_size_hint_align_set(ad->search_devices_button, EVAS_HINT_FILL, EVAS_HINT_FILL);
+       evas_object_smart_callback_add(ad->clear_button, "clicked", clear_cb, ad);
+       elm_object_part_content_set(ad->layout,"clear",ad->clear_button);
+       //evas_object_show(ad->clear_button);
+
+       ad->example_queries_label = elm_label_add(ad->layout);
+       elm_object_text_set(ad->example_queries_label, _("<color=#00008BFF><b><align=left>Example Queries</align></b></color>"));
+       elm_object_part_content_set(ad->layout,"example_queries",ad->example_queries_label);
+       //evas_object_show(ad->example_queries_label);
+
+       ad->search_devices_button = elm_button_add(ad->layout);
+       //evas_object_size_hint_align_set(ad->search_devices_button, EVAS_HINT_FILL, 0.0);
+       elm_object_text_set(ad->search_devices_button, "Search Devices");
+       evas_object_smart_callback_add(ad->search_devices_button, "clicked", search_devices_cb, ad);
+       elm_object_part_content_set(ad->layout,"search_devices",ad->search_devices_button);
+       //evas_object_show(ad->search_devices_button);
+
+       ad->discomfort_index_button = elm_button_add(ad->layout);
+       //evas_object_size_hint_align_set(ad->discomfort_index_button, EVAS_HINT_FILL, 0.0);
+       elm_object_part_content_set(ad->layout,"discomfort_index",ad->discomfort_index_button);
+       elm_object_text_set(ad->discomfort_index_button, "Discomfort Index");
+       evas_object_smart_callback_add(ad->discomfort_index_button, "clicked", discomfort_index_cb, ad);
+       //evas_object_show(ad->discomfort_index_button);
+
+       ad->unregister_query_label = elm_label_add(ad->layout);
+       elm_object_text_set(ad->unregister_query_label,_("<color=#00008BFF><b><align=left>Unregister Query</align></b></color>"));
+       //evas_object_size_hint_weight_set(ad->unregister_query_label, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+       elm_object_part_content_set(ad->layout,"unregister_query_label",ad->unregister_query_label);
+       //evas_object_show(ad->unregister_query_label);
+
+
+       ad->minus_button = elm_button_add(ad->layout);
+       //evas_object_size_hint_align_set(ad->discomfort_index_button, EVAS_HINT_FILL, 0.0);
+       elm_object_part_content_set(ad->layout,"minus",ad->minus_button);
+       elm_object_text_set(ad->minus_button, "-");
+       evas_object_smart_callback_add(ad->minus_button, "clicked", minus_cb, ad);
+       //evas_object_show(ad->minus_button);
+
+       ad->unregister_query_id = elm_entry_add(ad->layout);
+       elm_object_part_text_set(ad->unregister_query_id, "elm.guide", "Query id!!!");
+       //evas_object_size_hint_align_set(ad->unregister_query_id, EVAS_HINT_FILL, EVAS_HINT_FILL);
+       elm_object_part_content_set(ad->layout,"unregister_query_id",ad->unregister_query_id);
+       elm_entry_input_panel_show_on_demand_set(ad->unregister_query_id,EINA_TRUE);
+       elm_entry_input_panel_layout_set(ad->unregister_query_id,ELM_INPUT_PANEL_LAYOUT_NUMBER);
+       evas_object_show(ad->unregister_query_id);
+
+       ad->plus_button = elm_button_add(ad->layout);
+       //evas_object_size_hint_align_set(ad->discomfort_index_button, EVAS_HINT_FILL, 0.0);
+       elm_object_part_content_set(ad->layout,"plus",ad->plus_button);
+       elm_object_text_set(ad->plus_button, "+");
+       evas_object_smart_callback_add(ad->plus_button, "clicked", plus_cb, ad);
+       //evas_object_show(ad->plus_button);
+
+       ad->unregister_button = elm_button_add(ad->layout);
+       //evas_object_size_hint_align_set(ad->unregister_button, EVAS_HINT_FILL, 0.0);
+       elm_object_part_content_set(ad->layout,"unregister_button",ad->unregister_button);
+       elm_object_text_set(ad->unregister_button, "Unregister");
+       evas_object_smart_callback_add(ad->unregister_button, "clicked", unregister_cb, ad);
+       //evas_object_show(ad->unregister_button);
+
+       ad->clear_log_button = elm_button_add(ad->layout);
+       //evas_object_size_hint_align_set(ad->clear_log_button, EVAS_HINT_FILL, 0.0);
+       elm_object_part_content_set(ad->layout,"log_button",ad->clear_log_button);
+       elm_object_text_set(ad->clear_log_button, "Clear Log");
+       evas_object_smart_callback_add(ad->clear_log_button, "clicked", clear_log_cb, ad);
+       //evas_object_show(ad->clear_log_button);
+
+       ad->log = elm_entry_add(ad->layout);
+       elm_object_part_content_set(ad->layout,"log_text",ad->log);
+       elm_object_part_text_set(ad->log, "elm.guide", "Log messages will be update here!!!");
+       elm_entry_scrollable_set(ad->log,EINA_TRUE);
+       elm_entry_editable_set(ad->log,EINA_FALSE);
+       //evas_object_size_hint_align_set(ad->log, EVAS_HINT_FILL, EVAS_HINT_FILL);
+       //evas_object_show(ad->log);
+
+       elm_box_pack_end(ad->box, ad->layout);
+       evas_object_show(ad->layout);
+       elm_naviframe_item_push(ad->naviframe, "Soft Sensor Manager App", NULL, NULL, ad->scroller, NULL);
+
+       //Show window after base gui is set up
+       evas_object_show(ad->win);
+}
+
+static bool
+app_create(void *data)
+{
+       /* Hook to take necessary actions before main event loop starts
+               Initialize UI resources and application's data
+               If this function returns true, the main loop of application starts
+               If this function returns false, the application is terminated */
+       appdata_s *ad = (appdata_s *)data;
+
+       std::string xmlDescription = "<SSMCore>"
+                               "<Device>"
+                               "<UDN>abcde123-31f8-11b4-a222-08002b34c050</UDN>"
+                               "<Name>MyPC</Name>"
+                               "<Type>PC</Type>"
+                               "</Device>"
+                               "<Config>"
+                               "<SoftSensorDescription>/opt/usr/apps/org.iotivity.service.ssm.ssmtesterapp/lib/SoftSensorDescription.xml</SoftSensorDescription>"
+                               "<SoftSensorRepository>/opt/usr/apps/org.iotivity.service.ssm.ssmtesterapp/lib/</SoftSensorRepository>"
+                               "</Config>"
+                               "</SSMCore>";
+
+       g_pQueryEngineEvent = new CQueryEngineEvent(ad);
+
+       create_base_gui(ad);
+
+       if(is_connected())
+       {
+           if (OIC::InitializeSSM(xmlDescription) == OIC::SSM_S_OK){
+                   dlog_print(DLOG_DEBUG, LOG_TAG, "#### InitializeSSM() returned SSM_S_OK");
+               }
+               else{
+                   dlog_print(DLOG_DEBUG, LOG_TAG, "#### InitializeSSM() failed");
+               }
+       }
+       else
+       {
+           updateLog(ad, "WiFi not connected, connect first and re-run application");
+
+       }
+
+       return true;
+}
+
+static void
+app_control(app_control_h app_control, void *data)
+{
+       /* Handle the launch request. */
+       dlog_print(DLOG_INFO,LOG_TAG,"#### in app_control");
+}
+
+static void
+app_pause(void *data)
+{
+       /* Take necessary actions when application becomes invisible. */
+       dlog_print(DLOG_INFO,LOG_TAG,"#### in app_pause");
+}
+
+static void
+app_resume(void *data)
+{
+       /* Take necessary actions when application becomes visible. */
+       dlog_print(DLOG_INFO,LOG_TAG,"#### in app_resume");
+}
+
+static void
+app_terminate(void *data)
+{
+       /* Release all resources. */
+       dlog_print(DLOG_INFO,LOG_TAG,"#### in app_terminate");
+
+       if (OIC::TerminateSSM() == OIC::SSM_S_OK){
+               dlog_print(DLOG_DEBUG, LOG_TAG, "#### TerminateSSM() returned SSM_S_OK");
+       }
+       else{
+               dlog_print(DLOG_DEBUG, LOG_TAG, "#### TerminateSSM() failed");
+       }
+
+       delete g_pQueryEngineEvent;
+}
+
+static void
+ui_app_lang_changed(app_event_info_h event_info, void *user_data)
+{
+       /*APP_EVENT_LANGUAGE_CHANGED*/
+       char *locale = NULL;
+       system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale);
+       elm_language_set(locale);
+       free(locale);
+       return;
+}
+
+static void
+ui_app_orient_changed(app_event_info_h event_info, void *user_data)
+{
+       /*APP_EVENT_DEVICE_ORIENTATION_CHANGED*/
+       dlog_print(DLOG_INFO,LOG_TAG,"#### app orient changed");
+       return;
+}
+
+static void
+ui_app_region_changed(app_event_info_h event_info, void *user_data)
+{
+       /*APP_EVENT_REGION_FORMAT_CHANGED*/
+}
+
+static void
+ui_app_low_battery(app_event_info_h event_info, void *user_data)
+{
+       /*APP_EVENT_LOW_BATTERY*/
+}
+
+static void
+ui_app_low_memory(app_event_info_h event_info, void *user_data)
+{
+       /*APP_EVENT_LOW_MEMORY*/
+}
+
+int
+main(int argc, char *argv[])
+{
+       appdata_s ad = {0,};
+       int ret = 0;
+
+       ui_app_lifecycle_callback_s event_callback = {0,};
+       app_event_handler_h handlers[5] = {NULL, };
+
+       event_callback.create = app_create;
+       event_callback.terminate = app_terminate;
+       event_callback.pause = app_pause;
+       event_callback.resume = app_resume;
+       event_callback.app_control = app_control;
+
+       ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY, ui_app_low_battery, &ad);
+       ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY, ui_app_low_memory, &ad);
+       ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED], APP_EVENT_DEVICE_ORIENTATION_CHANGED, ui_app_orient_changed, &ad);
+       ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED], APP_EVENT_LANGUAGE_CHANGED, ui_app_lang_changed, &ad);
+       ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED], APP_EVENT_REGION_FORMAT_CHANGED, ui_app_region_changed, &ad);
+       ui_app_remove_event_handler(handlers[APP_EVENT_LOW_MEMORY]);
+
+       ret = ui_app_main(argc, argv, &event_callback, &ad);
+
+       if (ret != APP_ERROR_NONE) {
+               dlog_print(DLOG_ERROR, LOG_TAG, "app_main() is failed. err = %d", ret);
+       }
+
+       return ret;
+}
diff --git a/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/tizen-manifest.xml b/service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/tizen-manifest.xml
new file mode 100644 (file)
index 0000000..1e1a74e
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="2.3" package="org.iotivity.service.ssm.ssmtesterapp" version="1.0.0">
+    <profile name="mobile"/>
+    <ui-application appid="org.iotivity.service.ssm.ssmtesterapp" exec="ssmtesterapp" multiple="false" nodisplay="false" taskmanage="true" type="capp">
+        <label>ssmtesterapp</label>
+        <icon>ssmtesterapp.png</icon>
+    </ui-application>
+    <privileges>
+        <privilege>http://tizen.org/privilege/network.get</privilege>
+        <privilege>http://tizen.org/privilege/internet</privilege>
+    </privileges>
+    <feature name="http://tizen.org/feature/network.wifi">true</feature>
+</manifest>
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/include/BMISensor.h b/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/include/BMISensor.h
new file mode 100644 (file)
index 0000000..d0557e1
--- /dev/null
@@ -0,0 +1,127 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/*
+ * BMISensor.h
+ */
+
+#ifndef BMISENSOR_H_
+#define BMISENSOR_H_
+
+/**
+ * This header file is included to define _EXPORT_.
+ */
+#include "SSMModelDefinition.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+INTERFACE_DECLSPEC void InitializeContext(ICtxDelegate *pDelegate);
+#ifdef __cplusplus
+}
+;
+#endif
+
+
+#if 0
+Who BMI
+weight / height*hegith
+
+< 18.5  :underweight
+18.5 <= < 25 : Normal Range
+<= 25  < 30 : Overweight
+<= 30 : Obese
+#endif
+
+#define UNKOWNBMI   -1
+#define OUTOFDATEBMI   0
+#define UNDERWEIGHT     1
+#define NORMALRANGE     2
+#define OVERWEIGHT      3
+#define OBESE           4
+
+
+#define UNDERWEIGHT_VAL     18.5
+#define NORMALRANGE_VAL     25.9
+#define OVERWEIGHT_VAL      30
+
+
+#define DIFFTIME      4     // valid time difference. (seconds)
+
+
+
+
+
+namespace BMISensorName
+{
+//#define PHYSICAL_EA 2
+
+
+    typedef struct _physicalInput_
+    {
+        char *m_thingName;
+        int m_inputNum;
+        void *m_pInputStruct;
+    } physicalInput;
+
+    typedef enum
+    {
+        SUCCESS = 0, ERROR
+    } DIResult;
+
+    class BMISensor: public ICtxEvent
+    {
+        private:
+
+ //           static physicalInput s_PHYSICAL_SOFTSENSORs[PHYSICAL_EA];
+
+            class InValue
+            {
+                public:
+                    std::string m_usrname;          // each user. ; for future
+                    std::string m_timestamp;
+                    double  m_height; // Height.
+                    double  m_weight; // Weight
+                    time_t  m_timepstampH;
+                    time_t  m_timepstampW;
+                    int m_BMIresult;
+
+            };
+
+            //InValue m_DI[PHYSICAL_EA];
+            InValue m_result;
+
+            int runLogic(std::vector< ContextData > &contextDataList);
+
+        public:
+            BMISensor();
+
+            void onCtxEvent(enum CTX_EVENT_TYPE eventType, std::vector< ContextData > contextDataList);
+
+            DIResult getInput(std::vector< ContextData > &contextDataList);
+            DIResult makeBMI(void);
+            ContextData setOutput(int property_count);
+
+            friend void INTERFACE_DECLSPEC initializeContext(ICtxDelegate *pDelegate);
+    };
+};
+
+#endif /* BMISENSOR_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/include/SysTimer.h b/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/include/SysTimer.h
new file mode 100644 (file)
index 0000000..1101fe5
--- /dev/null
@@ -0,0 +1,37 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+/*
+ * SysTimer.h
+ */
+
+#ifndef SYSTIMER_H_
+#define SYSTIMER_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string>
+class SysTimer
+{
+    public:
+        static std::string MilliSecondAsString();
+        static std::string UTCSecondAsString();
+};
+
+#endif /* SYSTIMER_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/src/BMISensor.cpp b/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/src/BMISensor.cpp
new file mode 100644 (file)
index 0000000..a6cdb06
--- /dev/null
@@ -0,0 +1,289 @@
+/******************************************************************
+ *
+ * Copyright 2015 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 file contains the exported symbol.
+ */
+#include <stdlib.h>
+#include <map>
+#include <string>
+#include <sstream>
+#include <iostream>
+
+#include "BMISensor.h"
+#include "SysTimer.h"
+
+#ifdef __ANDROID__
+#include "OCAndroid.h"
+#endif
+
+using namespace BMISensorName;
+
+#define SENSOR_NAME "BMISensor"
+
+#define WEIGHTSENSOR_NAME ((char *)"Thing_WeightSensor")
+#define HEIGHTSENSOR_NAME ((char *)"Thing_HeightSensor")
+
+#define WEIGHT_NAME ((char *)"weight")
+#define HEIGHT_NAME ((char *)"height")
+
+
+
+
+ICtxDelegate *g_pDelegate;
+
+void InitializeContext(ICtxDelegate *pDelegate)
+{
+    std::cout << "[BMISensor] Sensor::" << __func__ << " is called."
+              << std::endl;
+
+   std::vector < ContextData > contextData;
+
+    BMISensor *eventCls = new BMISensor();
+    pDelegate->registerCallback(eventCls);
+    g_pDelegate = pDelegate;
+
+    std::cout << "BMISensor loaded" << std::endl;
+
+    return;
+}
+
+BMISensor::BMISensor()
+{
+    m_result.m_usrname = "";       // each user.
+    m_result.m_timestamp = "";     // measured time
+    m_result.m_weight = 0;         // Height
+    m_result.m_height = 0;         // Weight
+    time(&(m_result.m_timepstampW));
+    time(&(m_result.m_timepstampH));
+    m_result.m_BMIresult = UNKOWNBMI;
+
+
+
+}
+
+void BMISensor::onCtxEvent(enum CTX_EVENT_TYPE eventType,
+                                       std::vector< ContextData > contextDataList)
+{
+
+
+    switch (eventType)
+    {
+        case SPF_START:
+            runLogic(contextDataList);
+            break;
+        default:
+            std::cout << "Not support onCtxEvent" << std::endl;
+            break;
+    }
+}
+
+int BMISensor::runLogic(std::vector< ContextData > &contextDataList)
+{
+
+    DIResult result;
+
+    if (getInput(contextDataList) == SUCCESS)
+    {
+
+
+
+
+        if ((result = makeBMI()) != SUCCESS)
+        {
+            std::cout << "Error : makeBMI() result = " << result << std::endl;
+            return -1;
+        }
+
+        std::vector < ContextData > outList;
+        ContextData out = setOutput(1);
+        outList.push_back(out);
+        g_pDelegate->addOutput(outList);
+
+        return 0;
+    }
+
+    return -1;
+}
+
+
+
+DIResult BMISensor::getInput(std::vector< ContextData > &contextDataList)
+{
+
+    int contextSize = 0;
+    double temp;
+
+//    std::cout << "[BMISensor] BMISensor::" << "contextDataList.size() : "<< contextDataList.size() << std::endl;
+
+
+
+    if ((contextSize = contextDataList.size()) == 0)    // number of input things
+    {
+          std::cout << "Physical Context data is not exist." << std::endl;
+          return ERROR;
+    }
+
+    for (int i = 0; i < contextSize; i++)
+    {
+
+        std::vector < std::map< std::string, std::string > > lVector =
+                            contextDataList[i].outputProperty;
+        std::string name = lVector[0]["name"];
+
+
+        if (contextDataList[i].rootName == WEIGHTSENSOR_NAME)
+        {
+
+
+            if (name.compare(WEIGHT_NAME) == 0){
+
+                temp=std::stod( lVector[0]["value"]);
+
+                if (temp > 0){
+                    time(&(m_result.m_timepstampW));
+                    m_result.m_weight=temp;
+                }
+
+
+
+            }
+
+
+        }
+        else if (contextDataList[i].rootName == HEIGHTSENSOR_NAME)
+        {
+
+            if (name.compare(HEIGHT_NAME) == 0){
+
+                temp=std::stod( lVector[0]["value"]);
+                if (temp > 0){
+                    time(&(m_result.m_timepstampH));
+                    m_result.m_height=temp;
+                }
+
+            }
+
+        }
+
+    }
+
+    return SUCCESS;
+}
+
+/**
+ * Calculation of BMI with Weight&Height
+ */
+
+
+
+DIResult BMISensor::makeBMI(void)
+{
+
+
+    //    std::cout << "[BMISensor] BMISensor::" << __func__ << " is called."
+    //              << std::endl;
+
+    double BMIvalue, timediffsecond;
+
+    timediffsecond = abs( difftime( m_result.m_timepstampW,m_result.m_timepstampH));
+
+
+    if(  timediffsecond >  DIFFTIME ){
+
+           BMIvalue= 0;
+           m_result.m_BMIresult=UNKOWNBMI;
+           std::cout << "[BMISensor] :   OUTOFDATEBMI: "<<  m_result.m_BMIresult << std::endl;
+    }
+    else if( (m_result.m_height > 0)   &&  (m_result.m_weight > 0 )){
+        BMIvalue=  m_result.m_weight / (m_result.m_height  *  m_result.m_height);
+
+
+        std::cout << "[BMISensor] height : " << m_result.m_height << " weight : " << m_result.m_weight << " BMIvalue : "<< BMIvalue  <<" timediff : "<<timediffsecond  << std::endl;
+
+
+
+            if (BMIvalue >= OVERWEIGHT_VAL)
+            {
+                m_result.m_BMIresult = (int) OBESE;
+                std::cout << "[BMISensor] : BMIresult:" << m_result.m_BMIresult<< " OBESE "<< std::endl;
+            }
+            else if (BMIvalue >= NORMALRANGE_VAL )
+            {
+                m_result.m_BMIresult = (int) OVERWEIGHT;
+                std::cout << "[BMISensor] : BMIresult:" << m_result.m_BMIresult<< " OVERWEIGHT "<< std::endl;
+
+            }
+            else if (BMIvalue >= UNDERWEIGHT_VAL )
+            {
+                m_result.m_BMIresult = (int) NORMALRANGE;
+                std::cout << "[BMISensor] : BMIresult:" << m_result.m_BMIresult<< " NORMALRANGE "<< std::endl;
+
+            }
+            else
+            {
+                m_result.m_BMIresult = (int) UNDERWEIGHT;
+                std::cout << "[BMISensor] : BMIresult:" << m_result.m_BMIresult<< " UNDERWEIGHT "<< std::endl;
+            }
+
+        }
+        else {
+            BMIvalue= -1;
+            m_result.m_BMIresult=UNKOWNBMI;
+            std::cout << "[BMISensor] :   UNKOWNBMI: "<<  m_result.m_BMIresult << std::endl;
+        }
+
+
+
+    return SUCCESS;
+
+
+}
+
+
+ContextData BMISensor::setOutput(int property_count)
+{
+    ContextData out;
+
+    std::map < std::string, std::string > output_property;
+
+
+//    std::cout << "[BMISensor] BMISensor::" << __func__ << " is called."
+//              << std::endl;
+
+    out.rootName = SENSOR_NAME;
+    out.outputPropertyCount = property_count;
+
+
+    std::ostringstream convert;
+    convert << m_result.m_BMIresult;
+
+
+    output_property.insert(std::make_pair("name", "BMIresult"));
+    output_property.insert(std::make_pair("type", "int"));
+    output_property.insert(std::make_pair("value",  convert.str() ));
+    out.outputProperty.push_back(output_property);
+
+
+
+    return out;
+}
+
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/src/SysTimer.cpp b/service/soft-sensor-manager/SoftSensorPlugin/BMISensor/src/SysTimer.cpp
new file mode 100644 (file)
index 0000000..5387a53
--- /dev/null
@@ -0,0 +1,56 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <cstdlib>
+#include <sys/time.h>
+#include <string>
+#include <iostream>
+#include <sstream>
+
+#include "SysTimer.h"
+
+#include <stdint.h>
+std::string SysTimer::MilliSecondAsString()
+{
+    std::stringstream ss;
+    struct timeval tv;
+
+    gettimeofday(&tv, NULL);
+    long long val = tv.tv_sec * (long long) 1000 + tv.tv_usec / 1000;
+
+    ss << val;
+    std::string strTime = ss.str();
+
+    return strTime;
+}
+
+std::string SysTimer::UTCSecondAsString()
+{
+    std::stringstream ss;
+    struct timeval tv;
+
+    gettimeofday(&tv, NULL);
+    unsigned long val = tv.tv_sec;
+
+    ss << val;
+    std::string strTime = ss.str();
+
+    return strTime;
+}
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/build/linux/Makefile b/service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/build/linux/Makefile
deleted file mode 100644 (file)
index d87e604..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
--include ../../../../build/linux/root_path.inc
--include ../../../../build/linux/environment.mk
-
-SRC_PATH=../../src
-INC_PATH=../../include
-RST_NAME=release
-
-# Insert your project name.
-TARGET=DiscomfortIndexSensor
-
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -DLINUX
-CXX_INC=-I${INC_PATH} -I${OUTPUTS_DIR}
-
-SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
-OBJPATH=${SRCLIST:.cpp=.o}
-OBJLIST=${notdir ${OBJPATH}}
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job ${TARGET} post_job
-
-pre_job:
-       @echo " " 
-       @echo "---------- ${TARGET} Build Begin. ------------" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-
-${TARGET}: ${OBJLIST}
-       $(CXX) -shared -o ./${RST_NAME}/lib$@.so $^
-       @echo " "
-
-%.o : ${SRC_PATH}/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o $@
-       @echo " "
-
-post_job:
-       @echo " " 
-       cp -Rdp ./${RST_NAME}/lib${TARGET}.so ${OUTPUTS_DIR}/
-       cp -Rdp ../../../${SSXML_NAME} ${OUTPUTS_DIR}/
-       @echo "-------------- ${TARGET} Build Successful. -------------"
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " " 
-       
-       
-clean:
-       rm -f -v *.o ${TARGET}
-       rm -rf ./${RST_NAME}
-       
index a0145f2..6bed98e 100644 (file)
  */
 #include "SSMModelDefinition.h"
 
-#define _EXPORT_
-
 #ifdef __cplusplus
 extern "C"
 {
 #endif
-void _EXPORT_ InitializeContext(ICtxDelegate *pDelegate);
+INTERFACE_DECLSPEC void InitializeContext(ICtxDelegate *pDelegate);
 #ifdef __cplusplus
-
 }
 ;
 #endif
@@ -88,7 +85,7 @@ namespace DiscomfortIndexSensorName
             DIResult makeDiscomfortIndex(InValue *data);
             ContextData setOutput(int property_count, InValue *data);
 
-            friend void _EXPORT_ initializeContext(ICtxDelegate *pDelegate);
+            friend void INTERFACE_DECLSPEC initializeContext(ICtxDelegate *pDelegate);
     };
 }
 ;
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/GeneralData.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/GeneralData.h
new file mode 100644 (file)
index 0000000..2435a21
--- /dev/null
@@ -0,0 +1,153 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef GENERALDATA_H_
+#define GENERALDATA_H_
+
+#include <iostream>
+#include <map>
+#include <vector>
+
+#define TYPE_NODEFINE   0
+#define TYPE_STRING     1
+#define TYPE_CHAR           2
+#define TYPE_INT            3
+#define TYPE_SHORT      4
+#define TYPE_FLOAT      5
+#define TYPE_DOUBLE     6
+
+// Macro Function.
+#define VOIDINIT_CHECK()                                            \
+    if ( flag == false ) {                                          \
+        printf("Error : Not yet set data.\n");      \
+        return ;                                                                    \
+    }
+
+#define BOOLINIT_CHECK()                                            \
+    if ( flag == false ) {                                          \
+        printf("Error : Not yet set data.\n");      \
+        return false;                                                           \
+    }
+
+
+class Virtual_data
+{
+    private :
+        int dataType;
+
+        void s2data( const char *value);
+
+    public :
+
+        Virtual_data( void );
+
+        Virtual_data(int type);
+
+        void put(std::string value);
+
+        void put(char *value);
+
+        int get( std::string *value);
+
+        template <typename TYPE>
+        int get( TYPE *value)
+        {
+            void *data = get_data();
+
+            switch (dataType)
+            {
+                case TYPE_CHAR :
+                case TYPE_INT :
+                case TYPE_SHORT :
+                    *value = (TYPE)(*(int *)data);
+                    return 1;
+                    break;
+                case TYPE_FLOAT :
+                    *value = (TYPE)(*(float *)data);
+                    return 1;
+                case TYPE_DOUBLE :
+                    *value = (TYPE)(*(double *)data);
+                    return 1;
+                    break;
+                case TYPE_NODEFINE :
+                    printf("Error : Not yet defined with dataType variable.\n");
+            }
+
+            return 0;
+        }
+
+        // Virtual Function.
+        virtual void put_data( void *value ) = 0;
+
+        virtual void *get_data( void ) = 0;
+};
+
+
+
+class GeneralData
+{
+    private :
+        bool flag;
+        std::string Name;
+        int dataType;
+        class Virtual_data *pValue;
+
+        void set_dataType(const char *type);
+
+    public :
+        GeneralData( void );
+
+        GeneralData( std::string name, std::string type );
+
+        GeneralData( std::string name, std::string type, std::string value );
+
+        bool initial( std::string name, std::string type );
+
+        bool get_Name( std::string &name );
+
+        void put( std::string value );
+
+        void put( const char *value );
+
+        int get_DataType( void );
+
+        bool get( std::string *data );
+
+        template <typename TYPE>
+        bool get( TYPE *data)
+        {
+            BOOLINIT_CHECK();
+
+            if ( pValue->get(data) == NULL )
+            {
+                printf("Error : No data.\n");
+                *data = 0;
+                return false;
+            }
+
+            return true;
+        }
+
+};
+
+void Conversion_DataFormat( std::vector < std::map< std::string, std::string > > lVector ,
+                            std::vector< GeneralData > &gVector );
+
+#endif /* GENERALDATA_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h
new file mode 100644 (file)
index 0000000..9d245ba
--- /dev/null
@@ -0,0 +1,125 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/*
+ * Indoor Trajectory Soft Sensor
+ */
+
+#ifndef INDOORTRAJECTORYSENSOR_H_
+#define INDOORTRAJECTORYSENSOR_H_
+
+/**
+ * This header file is included to define _EXPORT_.
+ */
+#include "SSMModelDefinition.h"
+#include "Trajectory.h"
+
+#define _EXPORT_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+INTERFACE_DECLSPEC void InitializeContext(ICtxDelegate *pDelegate);
+#ifdef __cplusplus
+
+};
+#endif
+
+namespace ITSName
+{
+#define PHYSICAL_EA 1
+
+    typedef struct _physicalInput_
+    {
+        char *m_thingName;
+        int m_inputNum;
+        void *m_pInputStruct;
+    } physicalInput;
+
+    typedef enum
+    {
+        SUCCESS = 0, ERROR, NO_ELEMENT
+    } ITSResult;
+
+    class SThing
+    {
+        public:
+            std::string timestamp;
+            std::string ID;
+            float distance;
+            int   proximity;
+            float SD;
+
+            SThing( void ) : timestamp(""), ID(""), distance(0.0), proximity(0), SD(0.0) {}
+            ~SThing( void ) {}
+    };
+
+    class Things
+    {
+        public :
+            SThing *things;
+            int EA;
+
+            Things(void) : EA(0), things(0) {}
+            Things( int ea ) : EA(ea), things(0)
+            {
+                things = new SThing[EA]();
+            }
+            ~Things( void )
+            {
+                if (things)
+                {
+                    delete [] things;
+                    things = 0;
+                }
+            }
+    };
+
+    class ITS: public ICtxEvent
+    {
+        private:
+            static ITS *singleton;
+            Things *m_TList;
+            SThing *m_closestThing;
+
+            int runLogic(std::vector< ContextData > &contextDataList);
+
+        public:
+            static physicalInput s_PHYSICAL_SENSORs[PHYSICAL_EA];
+
+            static ITS *GetInstance( void );
+            ITS();
+            ~ITS();
+
+            static void *SelfTrajectoryThread(void *param);
+            void onCtxEvent(enum CTX_EVENT_TYPE eventType, std::vector< ContextData > contextDataList);
+
+            ITSResult getInput(std::vector< ContextData > &contextDataList, CurrentService *CService );
+            ITSResult searchValidService( Things *things , CurrentService *CService );
+            Trajectory *makeTrajectory(CurrentService *CService);
+            ITSResult setOutput( Trajectory *m_result, ContextData *out );
+
+            friend void INTERFACE_DECLSPEC initializeContext(ICtxDelegate *pDelegate);
+    };
+}
+;
+
+#endif /* INDOORTRAJECTORYSENSOR_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/SysTimer.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/SysTimer.h
new file mode 100644 (file)
index 0000000..33fe3fa
--- /dev/null
@@ -0,0 +1,38 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+/*
+ * SysTimer.h
+ */
+
+#ifndef SYSTIMER_H_
+#define SYSTIMER_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string>
+class SysTimer
+{
+    public:
+        static std::string MilliSecondTime();
+        static std::string MilliSecondAsString();
+        static std::string UTCSecondAsString();
+};
+
+#endif /* SYSTIMER_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/Trajectory.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/Trajectory.h
new file mode 100644 (file)
index 0000000..a675aba
--- /dev/null
@@ -0,0 +1,110 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef TRAJECTORY_H_
+#define TRAJECTORY_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+struct TrackeeInfo
+{
+    public :
+        std::string ID;
+};
+
+struct ThingInfo
+{
+    public :
+        std::string ID;
+        std::string ServiceType;
+        int proximity;
+};
+
+typedef std::map < std::string, ThingInfo >     MAP_TYPE;
+
+class ServiceInfo
+{
+    private :
+        int things_ea;
+        MAP_TYPE validThings;
+
+    public :
+        std::string timestamp;
+
+        ServiceInfo( void );
+
+        ~ServiceInfo();
+
+        MAP_TYPE::iterator ThingBegin( void );
+
+        MAP_TYPE::iterator ThingEnd( void );
+
+        void insert( ThingInfo &thing );
+
+        ThingInfo *find( std::string thingID );
+
+        int getThingsEA( void );
+};
+
+class CurrentService
+{
+    public :
+        TrackeeInfo trackee;
+        ServiceInfo service;
+
+        CurrentService( void );
+
+        CurrentService( std::string trackeeID, std::string time );
+
+        ~CurrentService();
+};
+
+class Trajectory
+{
+    private :
+        TrackeeInfo trackee;
+        int latestServiceNum;
+        std::vector< ServiceInfo > ServiceList;
+        std::vector< ServiceInfo > *resultList;
+
+    public :
+        Trajectory( void );
+
+        Trajectory( std::string trackeeID );
+
+        ~Trajectory( void );
+
+        std::string getTrackeeID( void );
+
+//      std::string getTrackeeServiceType( void );
+
+        int getTrajectoryDeepSize( void );
+
+        int TrajectoryUpdate( CurrentService &CurrentSvc );
+
+        std::vector<ServiceInfo> *getTrajectoryList( int latestNum, int ListSize );
+
+};
+
+
+
+#endif /* TRAJECTORY_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/lib_proximity.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/lib_proximity.h
new file mode 100644 (file)
index 0000000..6d323ad
--- /dev/null
@@ -0,0 +1,32 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef PROXIMITY_H_
+#define PROXIMITY_H_
+
+
+#define arraysize   6
+#define RSSI_EA     3
+
+float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag);
+
+float calculateDistance(float avgRSSI, float txPower);
+
+#endif /* PROXIMITY_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_CbleDevice.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_CbleDevice.h
new file mode 100644 (file)
index 0000000..41fa53b
--- /dev/null
@@ -0,0 +1,62 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef CBLEDEVICE_H_
+#define CBLEDEVICE_H_
+
+#include <bluetooth.h>
+#include <map>
+#include <string>
+
+
+class CbleDevice
+{
+    private :
+        typedef bt_adapter_device_discovery_info_s ble_value;
+        typedef std::map<std::string, ble_value>    CbleDeviceMAP;
+        CbleDeviceMAP device;
+
+    public :
+        unsigned long time_count;
+
+        CbleDevice();
+        ~CbleDevice();
+
+        int insert( ble_value *discovery_info );
+
+        ble_value *getNext( int seq );
+
+        int setRSSI( std::string addr, int rssi );
+
+        ble_value *get( std::string addr );
+
+        bool find( std::string addr );
+
+        int size( void );
+
+        void erase( CbleDeviceMAP::iterator itr );
+
+        void clear( void );
+
+        bool isTimeOut( void );
+};
+
+
+#endif /* CBLEDEVICE_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_ble_bgthread.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_ble_bgthread.h
new file mode 100644 (file)
index 0000000..f0a9535
--- /dev/null
@@ -0,0 +1,91 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef BLE_LIB_H_
+#define BLE_LIB_H_
+
+#include <bluetooth.h>
+#include "tizen_CbleDevice.h"
+
+void what_return_value( bt_error_e returnValue );
+
+
+#define PROCESS_FREE                0
+#define PROCESS_TRYING          1
+#define PROCESS_FOUND               2
+#define PROCESS_COMPLETE        3
+
+class CbleBGthread
+{
+    public :
+        typedef void (*workfunc)( void *);
+
+    private :
+        static CbleBGthread *singleton;
+
+        static bool ble_adapter_flag;
+        static int ble_discover_flag;
+        static int ble_bond_flag;
+        static int reg_bond_cnt;
+        static workfunc workProcess;
+
+        static bool ble_discovery( void );
+
+        static bool find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info ,
+                                         CbleDevice *pdevice );
+
+    public :
+        static bool isThreadRun;
+        static pthread_t Thandle;
+
+        CbleBGthread( workfunc func );
+
+        ~CbleBGthread( void );
+
+        static CbleBGthread *GetInstance( workfunc func );
+
+        // ETC. function List.
+//  static void set_workProcess(workfunc func);
+        static void set_adapter_state_flag(void);
+
+
+        // Thread List.
+        static void *ble_thread(void *param);
+        // Callback List.
+        static void CB_adapter_state_change(int result, bt_adapter_state_e adapter_state, void *user_data);
+        static void CB_discover_state_change(int result,
+                                             bt_adapter_device_discovery_state_e discovery_state,
+                                             bt_adapter_device_discovery_info_s *discovery_info, void *user_data);
+        static void CB_bond_create(int result, bt_device_info_s *device_info, void *user_data);
+
+};
+
+
+//#define BT_ERROR_CHECK( _FUNC_ )      {                               \
+//      bt_error_e __err__ = (bt_error_e)(_FUNC_);      \
+//  if ( __err__ != BT_ERROR_NONE )                             \
+//  {                                                                                                   \
+//      what_return_value( __err__ );                               \
+//      goto BT_ERROR;                                              \
+//  }                                                                               \
+//}
+
+
+#endif /* BLE_LIB_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_log.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_log.h
new file mode 100644 (file)
index 0000000..e197c4c
--- /dev/null
@@ -0,0 +1,102 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#ifndef __OICAPP_LOG_H__
+#define __OICAPP_LOG_H__
+
+#define TIZEN_DEBUG_ENABLE
+#define LOG_TAG "OIC_TEST"
+#include <dlog.h>
+
+#define LOG_COLOR_RED       "\033[0;31m"
+#define LOG_COLOR_BROWN     "\033[0;33m"
+#define LOG_COLOR_BLUE      "\033[0;34m"
+#define LOG_COLOR_END       "\033[0;m"
+
+
+#if 0
+#define _DBG(fmt, arg...) SLOGD(fmt, ##arg)
+#define _INFO(fmt, arg...) SLOGI(fmt, ##arg)
+#define _WARN(fmt, arg...) SLOGW(fmt, ##arg)
+#define _ERR(fmt, arg...) SLOGE(fmt, ##arg)
+#else
+#define _DBG(fmt, arg...) \
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+#define _INFO(fmt, arg...) \
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+#define _WARN(fmt, arg...) \
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+#define _ERR(fmt, arg...) \
+    printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+#endif
+
+#define DBG(fmt, arg...) _DBG(fmt, ##arg)
+#define WARN(fmt, arg...) _WARN(LOG_COLOR_BROWN fmt LOG_COLOR_END, ##arg)
+#define ERR(fmt, arg...) _ERR(LOG_COLOR_RED fmt LOG_COLOR_END, ##arg)
+#define INFO(fmt, arg...) _INFO(LOG_COLOR_BLUE fmt LOG_COLOR_END, ##arg)
+
+#define ret_if(expr) \
+    do { \
+        if (expr) { \
+            ERR("(%s)", #expr); \
+            return; \
+        }\
+    } while(0)
+#define retv_if(expr, val) \
+    do {\
+        if (expr) { \
+            ERR("(%s)", #expr); \
+            return (val); \
+        } \
+    } while(0)
+#define retm_if(expr, fmt, arg...) \
+    do {\
+        if (expr) { \
+            ERR(fmt, ##arg); \
+            return; \
+        }\
+    } while(0)
+#define retvm_if(expr, val, fmt, arg...) \
+    do {\
+        if (expr) { \
+            ERR(fmt, ##arg); \
+            return (val); \
+        } \
+    } while(0)
+#define warn_if(expr) \
+    do { \
+        if (expr) { \
+            WARN("(%s)", #expr); \
+        } \
+    } while (0)
+
+
+
+#define BT_ERROR_CHECK( _FUNC_ )        {                               \
+        bt_error_e __err__ = (bt_error_e)(_FUNC_);      \
+    if ( __err__ != BT_ERROR_NONE )                             \
+    {                                                                                                   \
+        what_return_value( __err__ );                               \
+        goto BT_ERROR;                                              \
+    }                                                                               \
+}
+
+
+#endif //__OICAPP_LOG_H__
+
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_proximity.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_proximity.h
new file mode 100644 (file)
index 0000000..476053d
--- /dev/null
@@ -0,0 +1,113 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef TIZEN_PROXIMITY_H_
+#define TIZEN_PROXIMITY_H_
+
+#include <bluetooth.h>
+#include <map>
+#include "tizen_CbleDevice.h"
+
+void proximity_loop( void *param );
+void what_return_value( bt_error_e returnValue );
+
+#define JOB_NONE                0
+#define JOB_GET_RSSI        1
+#define JOB_GET_PROX        2
+#define JOB_PUT_OUTPUT  3
+#define JOB_BUSY                4
+
+class CRSSI
+{
+    public:
+        int cnt;
+        int *rssi;
+
+        CRSSI() : cnt(0), rssi(0) {}
+        CRSSI( int count ) : cnt(0), rssi(0) {   init(count);    }
+        ~CRSSI()
+        {
+            if ( rssi )
+            {
+                cnt = 0;
+                delete [] rssi;
+                rssi = 0;
+            }
+        }
+
+        void init( int count )
+        {
+            if ( rssi == NULL )
+            {
+                rssi = new int[count];
+                cnt = count;
+            }
+        }
+
+};
+
+class CProximity
+{
+    public :
+        typedef void *(*workfunc)( void *);
+        typedef std::map<std::string, CRSSI>    rssiMAP;
+    private :
+        static int loop_flag;
+        static int get_rssi_cnt;
+        static int num_set_rssi;
+        static rssiMAP map_rssi;
+
+        workfunc threadFunc;
+
+        int reference_ea;
+        float *m_distance;
+        int *m_proximity;
+    public :
+        pthread_t Thandle;
+
+        CProximity( workfunc func );
+
+        ~CProximity( void );
+
+        static bool find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info ,
+                                         CbleDevice *pdevice );
+
+        static void CB_discover_state_change(int result,
+                                             bt_adapter_device_discovery_state_e discovery_state, \
+                                             bt_adapter_device_discovery_info_s *discovery_info, void *user_data);
+
+        bool GetRSSI(CbleDevice *pdevice);
+
+        void GetProximity(CbleDevice *pdevice);
+
+        bool set_threadFunc(workfunc func);
+
+        workfunc get_threadFunc(void);
+
+        void set_output( CbleDevice *pdevice );
+
+        void prox_first_setting( int reference_ea );
+
+        friend void proximity_loop( void *param );
+};
+
+
+
+#endif /* TIZEN_PROXIMITY_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_public_ble.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_public_ble.h
new file mode 100644 (file)
index 0000000..d410ae5
--- /dev/null
@@ -0,0 +1,33 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef PUBLIC_BLE_H_
+#define PUBLIC_BLE_H_
+
+
+#define REF_NAME            "reference"
+
+void ble_init( void (*func)(void *) );
+
+void proximity_init( void *(*func)(void *) );
+
+void proximity_loop( void *param );
+
+#endif /* PUBLIC_BLE_H_ */
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp
new file mode 100644 (file)
index 0000000..c8ba0f3
--- /dev/null
@@ -0,0 +1,406 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "GeneralData.h"
+
+//#define __INTER_DEBUG__
+// Hidden Class define.
+template <typename TYPE>
+class AllFormat_data : public Virtual_data
+{
+        typedef Virtual_data base;
+    private :
+        TYPE data;
+
+    public :
+        AllFormat_data(int typenum) : base(typenum)
+        {
+#ifdef __INTER_DEBUG__
+            printf("[DEBUG] Test_data Constructor().\n");
+#endif
+        }
+
+        virtual void put_data( void *value)
+        {
+            data = *(TYPE *)value;
+        }
+
+        virtual void *get_data( void )
+        {
+            return (void *)&data;
+        }
+};
+
+
+
+/*******************************************
+ * Virtual_data class member function define.
+ */
+void Virtual_data::s2data( const char *value)
+{
+    switch (dataType)
+    {
+        case TYPE_CHAR :
+            {
+                char data = atoi(value);
+                put_data( (void *)&data );
+            }
+        case TYPE_INT :
+        case TYPE_SHORT :
+            {
+                int data = atoi(value);
+                put_data( (void *)&data );
+            }
+            break;
+        case TYPE_FLOAT :
+            {
+                float data = atof(value);
+                put_data( (void *)&data );
+            }
+            break;
+        case TYPE_DOUBLE :
+            {
+                double data = atof(value);
+                put_data( (void *)&data );
+            }
+            break;
+        case TYPE_NODEFINE :
+            printf("Error: dataType must have defined.\n");
+            break;
+        default :
+            printf("Error: Not yet supported type.\n");
+            break;
+    }
+}
+
+Virtual_data::Virtual_data( void )
+{
+    dataType = TYPE_NODEFINE;
+}
+
+Virtual_data::Virtual_data(int type)
+{
+#ifdef __INTER_DEBUG__
+    printf("[DEBUG] Virtual_data Constructor().\n");
+#endif
+    dataType = type;
+}
+
+void Virtual_data::put(std::string value)
+{
+    if (dataType == TYPE_STRING )
+        put_data( (void *)&value );
+    else
+        s2data( value.c_str() );
+}
+
+void Virtual_data::put(char *value)
+{
+    if (dataType == TYPE_STRING )
+    {
+        std::string temp = std::string(value);
+        put_data( (void *)&temp );
+    }
+    else
+        s2data( value );
+}
+
+int Virtual_data::get( std::string *value)
+{
+    if (dataType != TYPE_STRING)
+    {
+        printf("Error : dataType is Not string.\n");
+        return 0;
+    }
+
+    void *data = get_data();
+    *value = *(std::string *)data;
+    return 1;
+}
+
+void Virtual_data::put_data( void *value )
+{
+    printf("Error: virtual function(put_data) called.\n");
+}
+
+void *Virtual_data::get_data( void )
+{
+    printf("Error: virtual function(get) called.\n");
+    return NULL;
+}
+
+
+
+
+
+
+/*******************************************
+ * GeneralData class member function define.
+ */
+void GeneralData::set_dataType(const char *type)
+{
+    if ( strstr(type, "string") != NULL )
+    {
+        dataType = TYPE_STRING;
+#ifdef __INTER_DEBUG__
+        printf("DataType is std::string.\n");
+#endif
+        return ;
+    }
+    if ( strstr(type, "char") != NULL )
+    {
+        dataType = TYPE_CHAR;
+#ifdef __INTER_DEBUG__
+        printf("DataType is Character.\n");
+#endif
+        return ;
+    }
+    if ( strstr(type, "int") != NULL )
+    {
+        dataType = TYPE_INT;
+#ifdef __INTER_DEBUG__
+        printf("DataType is Integer.\n");
+#endif
+        return ;
+    }
+    if ( strstr(type, "short") != NULL )
+    {
+        dataType = TYPE_SHORT;
+#ifdef __INTER_DEBUG__
+        printf("DataType is Short.\n");
+#endif
+        return ;
+    }
+    if ( strstr(type, "float") != NULL )
+    {
+        dataType = TYPE_FLOAT;
+#ifdef __INTER_DEBUG__
+        printf("DataType is Floating.\n");
+#endif
+        return ;
+    }
+    if ( strstr(type, "double") != NULL )
+    {
+        dataType = TYPE_DOUBLE;
+#ifdef __INTER_DEBUG__
+        printf("DataType is Double.\n");
+#endif
+        return ;
+    }
+
+    dataType = TYPE_NODEFINE;
+}
+
+GeneralData::GeneralData( void )
+{
+#ifdef __INTER_DEBUG__
+    printf("[DEBUG] Virtual_Test Constructor().\n");
+#endif
+    flag = false;
+    Name = "";
+    dataType = TYPE_NODEFINE;
+    pValue = 0;
+}
+
+GeneralData::GeneralData( std::string name, std::string type )
+{
+#ifdef __INTER_DEBUG__
+    printf("[DEBUG] Data_Normal Constructor().\n");
+#endif
+    flag = false;
+    Name = "";
+    dataType = TYPE_NODEFINE;
+    pValue = 0;
+
+    flag = initial( name, type );
+}
+
+GeneralData::GeneralData( std::string name, std::string type, std::string value )
+{
+#ifdef __INTER_DEBUG__
+    printf("[DEBUG] Data_Normal Constructor().\n");
+#endif
+    flag = false;
+    Name = "";
+    dataType = TYPE_NODEFINE;
+    pValue = 0;
+
+    flag = initial( name, type );
+    put(value);
+}
+
+bool GeneralData::initial( std::string name, std::string type )
+{
+    Name = name;
+    set_dataType( type.c_str() );
+
+    switch (dataType)
+    {
+        case TYPE_STRING :
+            pValue = new AllFormat_data<std::string>(dataType);
+            break;
+        case TYPE_CHAR :
+            pValue = new AllFormat_data<char>(dataType);
+            break;
+        case TYPE_INT :
+            pValue = new AllFormat_data<int>(dataType);
+            break;
+        case TYPE_SHORT :
+            pValue = new AllFormat_data<short>(dataType);
+            break;
+        case TYPE_FLOAT :
+            pValue = new AllFormat_data<float>(dataType);
+            break;
+        case TYPE_DOUBLE :
+            pValue = new AllFormat_data<double>(dataType);
+            break;
+        case TYPE_NODEFINE :
+            pValue = 0;
+            printf("Error : set_dataType()function is returned TYPE_NODEFINE.\n");
+            break;
+    }
+
+    return true;
+}
+
+bool GeneralData::get_Name( std::string &name )
+{
+    BOOLINIT_CHECK();
+
+    name = Name;
+    return true;
+}
+
+void GeneralData::put( std::string value )
+{
+    VOIDINIT_CHECK();
+    pValue->put(value);
+}
+
+void GeneralData::put( const char *value )
+{
+    VOIDINIT_CHECK();
+    pValue->put(value);
+}
+
+int GeneralData::get_DataType( void )
+{
+    BOOLINIT_CHECK();
+
+    return dataType;
+}
+
+bool GeneralData::get( std::string *data )
+{
+    BOOLINIT_CHECK();
+
+    if ( pValue->get(data) == NULL )
+    {
+        printf("Error : No data.\n");
+        *data = "";
+        return false;
+    }
+
+    return true;
+}
+
+
+
+void Conversion_DataFormat( std::vector < std::map< std::string, std::string > > lVector ,
+                            std::vector< GeneralData > &gVector )
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    std::string name;
+    std::string type;
+    std::string value;
+
+    for (unsigned int j = 0; j < lVector.size(); j++)
+    {
+        name = lVector[j]["name"];
+        type = lVector[j]["type"];
+        value = lVector[j]["value"];
+
+        GeneralData pValue(name, type, value);
+        gVector.push_back(pValue);
+    }
+
+    /*************************************************
+     * Debugging print ( GeneralData format confirm. )
+     */
+#ifdef __INTERNAL_DEBUG__
+    for (unsigned int j = 0; j < gVector.size(); j++)
+    {
+        if ( gVector[j].get_Name(name) == false )
+        {
+            printf("Error : Not initialed.\n");
+            return ;
+        }
+
+        int dataType = gVector[j].get_DataType();
+        switch (dataType)
+        {
+            case TYPE_STRING :
+                {
+                    std::string data;
+                    if ( gVector[j].get(&data) == false )
+                    {
+                        printf("Error : Not initialed.\n");
+                        return ;
+                    }
+                    printf("name=%s , type=%d, value=%s\n", name.c_str(), dataType, data.c_str() );
+                }
+                break;
+            case TYPE_CHAR :
+            case TYPE_SHORT :
+            case TYPE_INT :
+                {
+                    int data;
+                    if ( gVector[j].get(&data) == false )
+                    {
+                        printf("Error : Not initialed.\n");
+                        return ;
+                    }
+                    printf("name=%s , type=%d, value=%d\n", name.c_str(), dataType, data );
+                }
+                break;
+            case TYPE_FLOAT :
+            case TYPE_DOUBLE :
+                {
+                    float data;
+                    if ( gVector[j].get(&data) == false )
+                    {
+                        printf("Error : Not initialed.\n");
+                        return ;
+                    }
+                    printf("name=%s , type=%d, value=%f\n", name.c_str(), dataType, data );
+                }
+                break;
+        }
+    }
+#endif
+
+    printf("Conversion_DataFormat() is Successful.\n");
+}
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp
new file mode 100644 (file)
index 0000000..fa578da
--- /dev/null
@@ -0,0 +1,574 @@
+/******************************************************************
+ *
+ * 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 file contains the exported symbol.
+ */
+#include <stdlib.h>
+#include <map>
+#include <string>
+#include <sstream>
+#include <iostream>
+
+#include "ITS.h"
+#include "GeneralData.h"
+#include "SysTimer.h"
+
+#include "tizen_public_ble.h"
+
+using namespace ITSName;
+
+//#define __INTERNAL_DEBUG__
+#define SENSOR_NAME "IndoorTrajectorySensor"
+
+
+#define INPUT_EA            4
+#define SEQ_ID                  0
+#define SEQ_DISTANCE        1
+#define SEQ_PROXIMITY       2
+#define SEQ_SD                  3
+
+
+
+#define TRACKEEID_NAME          "trackeeID"
+#define THINGS_NAME                 "things"
+char *inputName[INPUT_EA] =
+{ (char *)"ID", (char *)"distance", (char *)"proximity", (char *)"SD" };
+
+#define INDEX_TRACKER_THING     0
+physicalInput ITS::s_PHYSICAL_SENSORs[PHYSICAL_EA] =
+{
+    { (char *)"Tracker_Thing", INPUT_EA, (void *) &inputName },
+//  { (char*)"Thing_TempHumSensor1", INPUT_EA, (void*)&inputName }
+};
+
+ICtxDelegate *g_pDelegate;
+ITS *ITS::singleton = NULL;
+
+// map<TrackeeID, Trajectory>
+typedef std::map < std::string, Trajectory >        TrajectoryMap;
+TrajectoryMap trajectorys;
+
+
+void parserTracker_Thing( int seq, std::vector< GeneralData > &gVector, CurrentService *CService,
+                          Things **output )
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] " << __func__ << " is called." << std::endl;
+#endif
+
+    int isted_cnt = 0;
+
+    int InputNum = ITS::s_PHYSICAL_SENSORs[seq].m_inputNum;
+    char **pchar = (char **) (ITS::s_PHYSICAL_SENSORs[seq].m_pInputStruct);
+    if (InputNum == 0)
+    {
+        std::cout << "No input List." << std::endl;
+        return ;
+    }
+
+
+    std::string name = "";
+    gVector[0].get_Name(name);
+
+    if (name.compare(TRACKEEID_NAME) == 0 )
+    {
+        gVector[0].get( &(CService->trackee.ID) );
+    }
+
+    if ( CService->trackee.ID == "" || CService->trackee.ID.length() == 0 )
+    {
+        printf("Error : trackee.ID is NULL.\n");
+        return ;
+    }
+
+    CService->service.timestamp = SysTimer::MilliSecondTime();
+
+
+    name = "";
+    gVector[1].get_Name(name);
+
+    if (name.compare(THINGS_NAME) == 0 )
+    {
+        int ea = 0;
+        gVector[1].get(&ea);
+
+        if ( *output)
+        {
+            delete *output;
+            *output = 0;
+        }
+
+        if ( *output == NULL )
+        {
+            *output = new Things(ea);
+        }
+    }
+
+    if ( *output == NULL )
+    {
+        printf("Error : m_TList is NULL.\n");
+        return ;
+    }
+
+
+    for (unsigned int j = 2; j < gVector.size(); j++)
+    {
+        gVector[j].get_Name(name);
+
+        int l = 0;
+        for ( l = 0; l < InputNum ; l++ )
+        {
+            if (name.compare(*(pchar + l)) == 0)
+                break;
+        }
+
+        switch (l)
+        {
+            case SEQ_ID:        // id
+                gVector[j].get( &((*output)->things[isted_cnt / INPUT_EA].ID) );
+                break;
+            case SEQ_DISTANCE:      // distance
+                gVector[j].get( &((*output)->things[isted_cnt / INPUT_EA].distance) );
+                break;
+            case SEQ_PROXIMITY: // proximity
+                gVector[j].get( &((*output)->things[isted_cnt / INPUT_EA].proximity) );
+                break;
+            case SEQ_SD:    // SD
+                gVector[j].get( &((*output)->things[isted_cnt / INPUT_EA].SD) );
+                break;
+            default:
+                std::cout << "Not Yet Supported Option." << std::endl;
+                return ;
+        }   // switch
+
+        isted_cnt++;
+    }   // for
+}
+
+
+void InitializeContext(ICtxDelegate *pDelegate)
+{
+    std::vector < ContextData > contextData;
+
+    ITS *eventCls = ITS::GetInstance();
+    pDelegate->registerCallback(eventCls);
+    g_pDelegate = pDelegate;
+
+    proximity_init(ITS::SelfTrajectoryThread);
+    ble_init(proximity_loop);
+    std::cout << "ITS sensor loaded -02-" << std::endl;
+
+    return;
+}
+
+
+/******************************************************
+ * Loop function based thread.
+ */
+void *ITS::SelfTrajectoryThread(void *param)
+{
+//#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+//#endif
+
+    ContextData out;
+    CurrentService CService;
+    Things *TList = (Things *)param;
+    Trajectory *tra = 0;
+    ITSResult flag = ERROR;
+    ITS *its = ITS::GetInstance();
+
+    CService.trackee.ID = "SelfTrackee";
+    CService.service.timestamp = SysTimer::MilliSecondTime();
+
+    if ( (flag = its->searchValidService( TList, &CService )) != SUCCESS )
+    {
+        if ( flag == NO_ELEMENT )
+            return 0;
+
+        std::cout << "Error : searchValidService() function failed." << std::endl;
+        return NULL;
+    }
+
+    if ( (tra = its->makeTrajectory(&CService)) == NULL)
+    {
+        std::cout << "Error : makeTrajectory() function failed." << std::endl;
+        return NULL;
+    }
+
+    if ( its->setOutput( tra, &out ) != SUCCESS )
+    {
+        std::cout << "Error : setOutput() function failed." << std::endl;
+        return NULL;
+    }
+
+    std::vector < ContextData > outList;
+    outList.push_back(out);
+    g_pDelegate->addOutput(outList);
+
+    return NULL;
+}
+
+ITS *ITS::GetInstance( void )
+{
+    if ( singleton == NULL )
+        singleton = new ITS();
+
+    return singleton;
+}
+
+ITS::ITS()
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    m_TList = 0;
+    m_closestThing = 0;
+}
+
+ITS::~ITS()
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    if (m_TList)
+    {
+        delete m_TList;
+        m_TList = 0;
+        m_closestThing = 0;
+    }
+
+    if ( singleton )
+        delete singleton;
+}
+
+void ITS::onCtxEvent(enum CTX_EVENT_TYPE eventType,
+                     std::vector< ContextData > contextDataList)
+{
+    switch (eventType)
+    {
+        case SPF_START:
+            runLogic(contextDataList);
+            break;
+        default:
+            std::cout << "Not support onCtxEvent" << std::endl;
+            break;
+    }
+}
+
+int ITS::runLogic(std::vector< ContextData > &contextDataList)
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    ContextData out;
+    CurrentService CService;
+    Trajectory *tra = 0;
+    ITSResult flag = ERROR;
+
+    if (getInput(contextDataList, &CService) != SUCCESS)
+    {
+        std::cout << "Error : getInput() function failed." << std::endl;
+        return -1;
+    }
+
+    if ( (flag = searchValidService( m_TList, &CService )) != SUCCESS )
+    {
+        if ( flag == NO_ELEMENT )
+            return 0;
+
+        std::cout << "Error : searchValidService() function failed." << std::endl;
+        return -1;
+    }
+
+    if ( (tra = makeTrajectory(&CService)) == NULL)
+    {
+        std::cout << "Error : makeTrajectory() function failed." << std::endl;
+        return -1;
+    }
+
+    if ( setOutput( tra, &out ) != SUCCESS )
+    {
+        std::cout << "Error : setOutput() function failed." << std::endl;
+        return -1;
+    }
+
+    std::vector < ContextData > outList;
+    outList.push_back(out);
+    g_pDelegate->addOutput(outList);
+
+    return 0;
+}
+
+/**
+ * Get Input data (temperature, humidity) using resource Client of Iotivity base.
+ */
+ITSResult ITS::getInput(std::vector< ContextData > &contextDataList, CurrentService *CService )
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    int contextSize = 0;
+
+    if ((contextSize = contextDataList.size()) == 0)
+    {
+        std::cout << "Physical Context data is not exist." << std::endl;
+        return ERROR;
+    }
+
+    for (int i = 0; i < contextSize; i++)
+    {
+        for (int k = 0; k < PHYSICAL_EA; k++)
+        {
+            if (contextDataList[i].rootName == s_PHYSICAL_SENSORs[k].m_thingName)
+            {
+                std::vector< GeneralData > gVector;
+                Conversion_DataFormat( contextDataList[i].outputProperty, gVector );
+
+                switch ( k )
+                {
+                    case INDEX_TRACKER_THING:
+                        parserTracker_Thing( k, gVector, CService, &m_TList);
+                        break;
+                    default :
+                        break;
+                }
+
+            } // if
+            break;
+        } // for
+    }
+
+    std::cout << "Success : " << __func__ << std::endl;
+    return SUCCESS;
+}
+
+/**
+ * searchValidService Function.
+  */
+ITSResult ITS::searchValidService( Things *things , CurrentService *CService )
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    if ( things == NULL )
+    {
+        printf("Error : input Things List is null.\n");
+        return ERROR;
+    }
+
+#ifdef __INTERNAL_DEBUG__
+    for ( int i = 0; i < things->EA ; i++ )
+    {
+        printf("ID=%s, distance=%f, proximity=%d, SD=%f\n", things->things[i].ID.c_str(),
+               things->things[i].distance, things->things[i].proximity, things->things[i].SD );
+    }
+#endif
+    int validThingEA = 0;
+    for ( int i = 0; i < things->EA ; i++ )
+    {
+        if ( things->things[i].proximity <= 1 )
+        {
+            ThingInfo validThing;
+
+            validThing.ID = things->things[i].ID;
+            //      validThing.ServiceType = things->things[i].ServiceType;
+            validThing.proximity = things->things[i].proximity;
+            CService->service.insert(validThing);
+            validThingEA++;
+        }
+    }
+
+    if ( CService->service.getThingsEA() == NULL )
+    {
+        printf("Valid Thing elements is not exist.\n");
+        return NO_ELEMENT;
+    }
+
+#ifdef __INTERNAL_DEBUG__
+    MAP_TYPE::iterator itr = CService->service.ThingBegin();
+    for ( ; itr != CService->service.ThingEnd() ; itr++ )
+    {
+        printf("CService: ID=%s, proximity=%d\n", itr->second.ID.c_str() , itr->second.proximity );
+    }
+#endif
+
+    return SUCCESS;
+}
+
+/**
+ * makeTrajectory Function.
+  */
+Trajectory *ITS::makeTrajectory(CurrentService *CService)
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    if ( CService == NULL )
+    {
+        printf("Error : input Current Service is null.\n");
+        return NULL;
+    }
+
+    // Trajectory Code contents.
+    Trajectory *tra = 0;
+    TrajectoryMap::iterator itr = trajectorys.find( CService->trackee.ID );
+
+    if ( itr == trajectorys.end() )
+    {
+        printf("itr == trajectorys.end().\n");
+        Trajectory tempTra(CService->trackee.ID);
+        trajectorys[CService->trackee.ID] = tempTra;
+        tra = &trajectorys[CService->trackee.ID];
+        printf("itr = %d\n", tra);
+    }
+    else
+    {
+        printf("itr is find trackeeID in trajectorys.\n");
+        tra = &itr->second;
+    }
+
+    tra->TrajectoryUpdate( *CService );
+
+    return tra;
+}
+
+std::string intToString(int n)
+{
+    std::stringstream ss;
+    ss << n;
+    return ss.str();
+}
+
+std::string floatToString(float n)
+{
+    std::stringstream ss;
+    ss << n;
+    return ss.str();
+}
+
+#define OUTPUT_TRAJECTORY_SIZE      2
+ITSResult ITS::setOutput( Trajectory *m_result, ContextData *out )
+{
+#ifdef __INTERNAL_DEBUG__
+    std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl;
+#endif
+
+    std::map < std::string, std::string > output_property;
+
+    out->rootName = SENSOR_NAME;
+    out->outputPropertyCount = 4 * OUTPUT_TRAJECTORY_SIZE + 1;      // ref_count + 1;
+
+    std::vector< ServiceInfo > *serviceTra = m_result->getTrajectoryList(0, OUTPUT_TRAJECTORY_SIZE);
+    if ( serviceTra == NULL )
+    {
+        printf("Error : getTrajectoryList() is failed.\n");
+        return ERROR;
+    }
+    int serviceTraSize = serviceTra->size();
+
+    output_property.insert(std::make_pair("name", "trackeeID"));
+    output_property.insert(std::make_pair("type", "string"));
+    output_property.insert(std::make_pair("value", m_result->getTrackeeID()));
+
+    out->outputProperty.push_back(output_property);
+
+
+    for ( int i = 0; i < OUTPUT_TRAJECTORY_SIZE; i++ )
+    {
+        std::string time_value = "null";
+        std::string ref01_value = "null";
+        std::string ref02_value = "null";
+        std::string ref03_value = "null";
+
+        if ( i < serviceTraSize )
+        {
+            MAP_TYPE::iterator itr;
+            time_value = (*serviceTra)[i].timestamp;
+
+            switch ( (*serviceTra)[i].getThingsEA() )
+            {
+                case 0:
+                    break;
+                case 1:
+                    itr = (*serviceTra)[i].ThingBegin();
+                    ref01_value = itr->second.ID;
+                    break;
+                case 2:
+                    itr = (*serviceTra)[i].ThingBegin();
+                    ref01_value = itr->second.ID;
+                    itr++;
+                    ref02_value = itr->second.ID;
+                    break;
+                default :
+                    itr = (*serviceTra)[i].ThingBegin();
+                    ref01_value = itr->second.ID;
+                    itr++;
+                    ref02_value = itr->second.ID;
+                    itr++;
+                    ref03_value = itr->second.ID;
+                    break;
+            }
+        }
+
+        output_property.clear();
+        std::string time_name = "timeT" + intToString(i);
+        output_property.insert(std::make_pair("name", time_name));
+        output_property.insert(std::make_pair("type", "string"));
+        output_property.insert(std::make_pair("value", time_value ));
+
+        out->outputProperty.push_back(output_property);
+
+        output_property.clear();
+        std::string ref01_name = "ref01T" + intToString(i);
+        output_property.insert(std::make_pair("name", ref01_name));
+        output_property.insert(std::make_pair("type", "string"));
+        output_property.insert(std::make_pair("value", ref01_value ));
+
+        out->outputProperty.push_back(output_property);
+
+        output_property.clear();
+        std::string ref02_name = "ref02T" + intToString(i);
+        output_property.insert(std::make_pair("name", ref02_name));
+        output_property.insert(std::make_pair("type", "string"));
+        output_property.insert(std::make_pair("value", ref02_value ));
+
+        out->outputProperty.push_back(output_property);
+
+        output_property.clear();
+        std::string ref03_name = "ref03T" + intToString(i);
+        output_property.insert(std::make_pair("name", ref03_name));
+        output_property.insert(std::make_pair("type", "string"));
+        output_property.insert(std::make_pair("value", ref03_value ));
+
+        out->outputProperty.push_back(output_property);
+    }
+
+    std::cout << "Success : " << __func__ << std::endl;
+    return SUCCESS;
+}
+
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/SysTimer.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/SysTimer.cpp
new file mode 100644 (file)
index 0000000..703155d
--- /dev/null
@@ -0,0 +1,81 @@
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <cstdlib>
+#include <sys/time.h>
+#include <string>
+#include <iostream>
+#include <sstream>
+
+#include "SysTimer.h"
+
+#include <stdint.h>
+#include <stdio.h>
+
+std::string SysTimer::MilliSecondTime()
+{
+    std::stringstream ss;
+    struct timeval tv;
+    time_t              *p_time = NULL;
+    struct tm           *localT = NULL;
+    char                time_str[30] = {0,};
+
+    gettimeofday(&tv, NULL);
+    p_time = (time_t *) & (tv.tv_sec);
+    localT = localtime( p_time );
+
+    sprintf( time_str, "%04d-%02d-%02d %02d:%02d:%02d.%03ld",       \
+             localT->tm_year + 1900, localT->tm_mon + 1, localT->tm_mday,    \
+             localT->tm_hour,      localT->tm_min,   localT->tm_sec,     \
+             tv.tv_usec / 1000 );
+
+    ss << time_str;
+    std::string strTime = ss.str();
+
+    return strTime;
+}
+
+std::string SysTimer::MilliSecondAsString()
+{
+    std::stringstream ss;
+    struct timeval tv;
+
+    gettimeofday(&tv, NULL);
+    long long val = tv.tv_sec * (long long) 1000 + tv.tv_usec / 1000;
+
+    ss << val;
+    std::string strTime = ss.str();
+
+    return strTime;
+}
+
+std::string SysTimer::UTCSecondAsString()
+{
+    std::stringstream ss;
+    struct timeval tv;
+
+    gettimeofday(&tv, NULL);
+    unsigned long val = tv.tv_sec;
+
+    ss << val;
+    std::string strTime = ss.str();
+
+    return strTime;
+}
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp
new file mode 100644 (file)
index 0000000..8025595
--- /dev/null
@@ -0,0 +1,184 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+#include "Trajectory.h"
+
+#include <stdlib.h>
+#include <iostream>
+
+// ServiceInfo Class member Function define.
+ServiceInfo::ServiceInfo( void ) : timestamp(""), things_ea(0) {    validThings.clear(); }
+
+ServiceInfo::~ServiceInfo()
+{
+    if ( things_ea )
+    {
+        validThings.clear();
+        things_ea = 0;
+    }
+}
+
+MAP_TYPE::iterator ServiceInfo::ThingBegin( void )
+{
+    return validThings.begin();
+}
+
+MAP_TYPE::iterator ServiceInfo::ThingEnd( void )
+{
+    return validThings.end();
+}
+
+void ServiceInfo::insert( ThingInfo &thing )
+{
+    if ( find(thing.ID) == NULL )
+    {
+        validThings[thing.ID] = thing;
+        things_ea++;
+    }
+}
+
+ThingInfo *ServiceInfo::find( std::string thingID )
+{
+    MAP_TYPE::iterator itr = validThings.find( thingID );
+
+    if ( itr == validThings.end() )
+        return NULL;
+
+    return &itr->second;
+}
+
+int ServiceInfo::getThingsEA( void )
+{
+    return things_ea;
+}
+
+//
+// CurrentService Class member Function define.
+CurrentService::CurrentService( void )
+{
+    trackee.ID = "";
+}
+
+CurrentService::CurrentService( std::string trackeeID, std::string time)
+{
+    trackee.ID = trackeeID;
+    service.timestamp = time;
+}
+
+CurrentService::~CurrentService()
+{
+    trackee.ID = "";
+}
+
+//
+// Trajectory Class member Function define.
+Trajectory::Trajectory( void )
+{
+    trackee.ID = "";
+    ServiceList.clear();
+    latestServiceNum = ServiceList.size();
+    resultList = NULL;
+}
+
+Trajectory::Trajectory( std::string trackeeID )
+{
+    trackee.ID = trackeeID;
+    ServiceList.clear();
+    latestServiceNum = ServiceList.size();
+    resultList = NULL;
+}
+
+Trajectory::~Trajectory( void )
+{
+    ServiceList.clear();
+    latestServiceNum = ServiceList.size();
+    if ( resultList )
+    {
+        delete resultList;
+        resultList = NULL;
+    }
+}
+
+std::string Trajectory::getTrackeeID( void )
+{
+    return trackee.ID;
+}
+
+int Trajectory::getTrajectoryDeepSize( void )
+{
+    return latestServiceNum;
+}
+
+int Trajectory::TrajectoryUpdate( CurrentService &CurrentSvc )
+{
+    if ( latestServiceNum <= 0 )
+        goto INSERT_ELEMENT;
+
+    if ( trackee.ID.compare( CurrentSvc.trackee.ID ) == 0 )
+    {
+        // if trackee.ID of CurrentSvc == trackee.ID ,
+        ServiceInfo *recentSvc = &ServiceList[latestServiceNum - 1];
+        ServiceInfo *crtSvc = &CurrentSvc.service;
+
+        if ( recentSvc->getThingsEA() != crtSvc->getThingsEA() )
+            goto INSERT_ELEMENT ;
+
+        MAP_TYPE::iterator itr = crtSvc->ThingBegin();
+        for ( ; itr != crtSvc->ThingEnd() ; itr++ )
+        {
+            if ( recentSvc->find( itr->second.ID ) == NULL )
+                goto INSERT_ELEMENT;
+        }
+
+        return latestServiceNum;
+    }
+
+INSERT_ELEMENT :
+    ServiceList.push_back( CurrentSvc.service );
+    latestServiceNum = ServiceList.size();
+
+    return latestServiceNum;
+}
+
+std::vector<ServiceInfo> *Trajectory::getTrajectoryList( int latestNum, int ListSize )
+{
+    if ( latestServiceNum <= 0 || latestServiceNum <= latestNum )
+        return NULL;
+
+    if ( resultList )
+    {
+        delete resultList;
+        resultList = NULL;
+    }
+    resultList = new std::vector<ServiceInfo>;
+
+    int endIndex = 0;
+    if ( latestServiceNum >= (latestNum + ListSize) && ListSize > 0 )
+    {
+        endIndex = latestServiceNum - latestNum - ListSize;
+    }
+
+    for ( int i = (latestServiceNum - 1 - latestNum) ; i >= endIndex ; i-- )
+        resultList->push_back( ServiceList[i] );
+
+    return resultList;
+}
+
+
+
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/lib_proximity.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/lib_proximity.cpp
new file mode 100644 (file)
index 0000000..45cf149
--- /dev/null
@@ -0,0 +1,110 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include <stdio.h>
+#include "tizen_log.h"
+#include "lib_proximity.h"
+#include <math.h>
+
+// Proximity code start
+float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag)
+{
+    float numerator = 0;
+    float denominator = 0;
+
+    float average = 0.0;
+
+    if (flag < arraysize / RSSI_EA)   // first loop buffer full
+    {
+
+        for (int i = 0; i < startindex; i++)
+        {
+            average += array[i];
+        }
+
+        if (startindex == 0) {}
+        else
+        {
+            average = average / startindex;
+        }
+        //       DBG("exp: ");
+        DBG("average1 : %f", average);
+    }
+    else
+    {
+        for (int i = 0; i < arraysize; i++)
+        {
+            average += array[i];
+        }
+
+        for (int i = startindex; i < startindex + RSSI_EA; i++)
+        {
+            average -= array[i];
+        }
+
+        average = average / (arraysize - numberOfSamples);
+
+        //            DBG("exp: ");
+        DBG("average2 : %f", average);
+    }
+
+    //exponential moving average
+    int i = 0;
+    //CHANGE THIS FOR DIFFERENT SMOOTHING EFFECT
+    float beta = 0.8f;
+    for (i = startindex + numberOfSamples - 1; i >= startindex; i--)
+    {
+        double temp = pow(beta, startindex + numberOfSamples - i - 1);
+        numerator += array[i] * (float)temp;
+        denominator += (float)temp;
+    }
+
+    int offset = 3;
+    if (average != 0.0)
+    {
+        numerator += average * pow(beta, offset + numberOfSamples);
+        denominator += pow(beta, offset + numberOfSamples);
+    }
+
+    return numerator / denominator;
+}
+
+
+float calculateDistance(float avgRSSI, float txPower)
+{
+    if (avgRSSI == 0)
+    {
+        return -1.0;
+    }
+
+    float ratio = avgRSSI * 1.0 / txPower;
+    if (ratio < 1.0)
+    {
+        return pow(ratio, 10);
+    }
+    else
+    {
+        float distance =  (0.7) * pow(ratio, 10) + 0.024;
+        return distance;
+    }
+}
+
+// proximity code end
+
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_CbleDevice.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_CbleDevice.cpp
new file mode 100644 (file)
index 0000000..fb47d62
--- /dev/null
@@ -0,0 +1,160 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include <stdio.h>
+#include "tizen_log.h"
+#include "tizen_CbleDevice.h"
+
+#define TIME_LIMITE     5       // unit : second
+
+CbleDevice::CbleDevice() : time_count(0) { clear(); }
+CbleDevice::~CbleDevice() { clear(); }
+
+int CbleDevice::insert( CbleDevice::ble_value *discovery_info )
+{
+    DBG("Enter.");
+    std::string addr = std::string(discovery_info->remote_address);
+
+    if ( find(addr) == false )
+    {
+        device[addr] = *discovery_info;
+
+        device[addr].remote_address = new char[ strlen(discovery_info->remote_address) + 1 ];
+        strcpy( device[addr].remote_address, discovery_info->remote_address);
+        device[addr].remote_name = new char[ strlen(discovery_info->remote_name) + 1 ];
+        strcpy( device[addr].remote_name, discovery_info->remote_name);
+        device[addr].service_uuid = NULL;
+        device[addr].service_count = 0;
+    }
+
+    return device.size();
+}
+
+CbleDevice::ble_value *CbleDevice::getNext( int seq )
+{
+    DBG("Enter.");
+    CbleDeviceMAP::iterator itr = device.begin();
+
+    if ( seq < 0 || seq >= device.size())
+    {
+#if __INTERNAL_DEBUG_
+        DBG("return null");
+#endif
+        return NULL;
+    }
+
+    for (; seq ; seq--)
+        itr++;
+
+#if __INTERNAL_DEBUG_
+    DBG("return %s pointer", itr->second.remote_address );
+#endif
+    return &itr->second;
+}
+
+int CbleDevice::setRSSI( std::string addr, int rssi )
+{
+    DBG("Enter.");
+    CbleDeviceMAP::iterator itr = device.find( addr );
+
+    if ( itr == device.end() )
+        return NULL;
+
+    ble_value *pdevice = &itr->second;
+
+    if ( rssi == NULL )
+    {
+        pdevice->service_count = NULL;
+        pdevice->rssi = 0;
+    }
+    else if ( pdevice->service_count == NULL )
+    {
+        pdevice->service_count = 1;
+        pdevice->rssi = rssi;
+    }
+    else
+        return NULL;
+
+    return pdevice->rssi;
+}
+
+CbleDevice::ble_value *CbleDevice::get( std::string addr )
+{
+    DBG("Enter.");
+    CbleDeviceMAP::iterator itr = device.find( addr );
+
+    if ( itr == device.end() )
+        return NULL;
+
+    return &itr->second;
+}
+
+bool CbleDevice::find( std::string addr )
+{
+    DBG("Enter.");
+    CbleDeviceMAP::iterator itr = device.find( addr );
+
+    if ( itr == device.end() )
+        return false;
+
+    return true;
+}
+
+int CbleDevice::size( void )
+{
+    DBG("Enter.");
+    return device.size();
+}
+
+void CbleDevice::erase( CbleDeviceMAP::iterator itr )
+{
+    ble_value *value = &itr->second;
+
+    if ( value->remote_address )
+        delete value->remote_address;
+    if ( value->remote_name )
+        delete value->remote_name;
+    if ( value->service_uuid )
+        delete [] value->service_uuid;
+
+    device.erase(itr);
+}
+
+void CbleDevice::clear( void )
+{
+    CbleDeviceMAP::iterator itr = device.begin();
+
+    if ( itr != device.end() )
+    {
+        erase(itr);
+        itr++;
+    }
+}
+
+bool CbleDevice::isTimeOut( void )
+{
+    DBG("Enter.");
+    if ( time_count > TIME_LIMITE )
+        return true;
+    else
+        return false;
+}
+
+
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_ble_bgthread.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_ble_bgthread.cpp
new file mode 100644 (file)
index 0000000..55375cb
--- /dev/null
@@ -0,0 +1,463 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include <stdio.h>
+#include <iostream>
+#include "tizen_log.h"
+#include <pthread.h>
+#include <unistd.h>
+
+#include "tizen_public_ble.h"
+#include "tizen_ble_bgthread.h"
+#include "tizen_CbleDevice.h"
+
+CbleBGthread *CbleBGthread::singleton = NULL;
+CbleBGthread::workfunc CbleBGthread::workProcess = NULL;
+bool CbleBGthread::ble_adapter_flag = false;
+int CbleBGthread::ble_discover_flag = PROCESS_FREE;
+int CbleBGthread::ble_bond_flag = PROCESS_FREE;
+bool CbleBGthread::isThreadRun = false;
+int CbleBGthread::reg_bond_cnt = 0;
+pthread_t CbleBGthread::Thandle = 0;
+
+// tizen ble init function.
+void ble_init( CbleBGthread::workfunc func )
+{
+    DBG("Enter.");
+
+    CbleBGthread *ble = CbleBGthread::GetInstance( func );
+    if ( ble == NULL )
+    {
+        DBG("Error : function is failed.");
+        return ;
+    }
+
+    BT_ERROR_CHECK( bt_initialize() );
+
+    BT_ERROR_CHECK( bt_adapter_set_state_changed_cb(CbleBGthread::CB_adapter_state_change, NULL) );
+    sleep(1);
+
+    bt_error_e returnValue;
+    returnValue = (bt_error_e)bt_adapter_enable();
+    if (returnValue != BT_ERROR_NONE )
+    {
+        what_return_value( returnValue );
+        if ( returnValue != BT_ERROR_ALREADY_DONE)
+            return ;
+        else
+        {
+#if __INTERNAL_DEBUG_
+            DBG("return == BT_ERROR_ALREADY_DONE");
+#endif
+            CbleBGthread::set_adapter_state_flag();
+        }
+    }
+
+#if __INTERNAL_DEBUG_
+    DBG("Register discovery callback func.");
+#endif
+    static CbleDevice device;
+    BT_ERROR_CHECK( bt_adapter_set_device_discovery_state_changed_cb(
+                        CbleBGthread::CB_discover_state_change, &device) );
+//  sleep(1);
+
+//  DBG("Register bond create callback func.");
+//  BT_ERROR_CHECK( bt_device_set_bond_created_cb( CbleBGthread::CB_bond_create , &device) );
+//  sleep(1);
+
+    ble->isThreadRun = true;
+    pthread_create(&ble->Thandle, NULL, CbleBGthread::ble_thread, &device);
+
+    DBG("Exit.");
+    return ;
+
+BT_ERROR:
+    DBG("Error Exception. Exit.");
+
+}
+
+//void workProcess( void )
+//{
+//  DBG("WorkProcess run.");
+//}
+
+/*********************************
+ * CbleBGthread class definition.
+ */
+CbleBGthread::CbleBGthread(workfunc func)
+{
+    workProcess = func;
+    ble_adapter_flag = false;
+    ble_discover_flag = PROCESS_FREE;
+    ble_bond_flag = PROCESS_FREE;
+    isThreadRun = false;
+    reg_bond_cnt = 0;
+    Thandle = 0;
+}
+
+CbleBGthread::~CbleBGthread()
+{
+    if ( singleton )
+    {
+        singleton = NULL;
+    }
+}
+
+CbleBGthread *CbleBGthread::GetInstance( workfunc func )
+{
+    if ( func == NULL )
+        return NULL;
+
+    if (singleton == NULL)
+        singleton = new CbleBGthread(func);
+
+    return singleton;
+}
+
+/*****************************
+ * BLE processing thread.
+ */
+void *CbleBGthread::ble_thread(void *param)
+{
+    DBG("Enter.");
+    CbleDevice *pdevice = (CbleDevice *)param;
+
+    while (isThreadRun )
+    {
+        sleep(1);
+        pdevice->time_count++;
+
+        if ( ble_adapter_flag )
+        {
+            // discovery
+            if ( ble_discover_flag == PROCESS_FREE)
+            {
+                if ( ble_discovery() == false)
+                    goto BT_ERROR;
+
+                ble_discover_flag = PROCESS_TRYING;
+            }
+
+            // bond create
+//          if( ble_discover_flag == PROCESS_COMPLETE && ble_bond_flag == PROCESS_FREE )
+//          {
+//              if( pdevice )
+//              {
+//                  DBG( "Try bond referenceThing List. size=%d, cnt=%d", pdevice->size(), reg_bond_cnt );
+//                  if( reg_bond_cnt < pdevice->size() )
+//                  {
+//                      BT_ERROR_CHECK(bt_device_create_bond( (pdevice->getNext(reg_bond_cnt))->remote_address ));
+//                      ble_bond_flag = PROCESS_TRYING;
+//                  }
+////                    for( int i = 0; i < pdevice->size(); i++ )
+////                        BT_ERROR_CHECK(bt_device_create_bond( (pdevice->getNext(i))->remote_address ));
+//              }
+//          }
+
+//          if( ble_bond_flag == PROCESS_COMPLETE )
+            if ( ble_discover_flag == PROCESS_COMPLETE )
+                break;
+
+            continue ;
+
+BT_ERROR:
+            continue ;
+        }   // if ( ble_adapter_flag )
+    }// while(isThreadRun )
+
+
+    while (isThreadRun)
+    {
+        // working process
+        workProcess( (void *)pdevice );
+    }
+
+    DBG("Exit.");
+    return 0;
+}
+
+
+/******************************
+ * Callback Function definition.
+ */
+
+// Called by adapter_enable / adapter_disable function.
+void CbleBGthread::CB_adapter_state_change(int result, bt_adapter_state_e adapter_state,
+        void *user_data)
+{
+    DBG("callback called.");
+
+    set_adapter_state_flag();
+}
+
+// Called by bt_adapter_start_device_discovery / bt_adapter_stop_device_discovery function.
+void CbleBGthread::CB_discover_state_change(int result,
+        bt_adapter_device_discovery_state_e discovery_state, \
+        bt_adapter_device_discovery_info_s *discovery_info, void *user_data)
+{
+    DBG("callback called.");
+#if __INTERNAL_DEBUG_
+    DBG("result = %d", result);
+#endif
+
+    if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FOUND )
+    {
+        CbleDevice *pdevice = (CbleDevice *)user_data;
+
+        if ( discovery_info == NULL)
+            goto BT_ERROR;
+
+#if __INTERNAL_DEBUG_
+        printf("=========== discovered device =============\n");
+        printf("= address  \t : %s \n", discovery_info->remote_address);
+        printf("= name     \t : %s \n", discovery_info->remote_name);
+        printf("= rssi     \t : %d \n", (discovery_info->rssi - 65535) );
+        printf("= is_bonded\t : %d \n", discovery_info->is_bonded);
+        printf("= svc_count\t : %d \n", discovery_info->service_count);
+        printf("= dev_type \t : %d \n", discovery_info->device_type);
+        printf("===========================================\n");
+#endif
+
+        find_referenceThing( discovery_info , pdevice );
+
+        if ( pdevice->isTimeOut() == true )
+        {
+#if __INTERNAL_DEBUG_
+            DBG("Stop searching device.");
+#endif
+            BT_ERROR_CHECK( bt_adapter_stop_device_discovery() );
+        }
+    }
+    else if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED )
+    {
+#if __INTERNAL_DEBUG_
+        DBG("state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED");
+#endif
+        reg_bond_cnt = 0;
+        ble_discover_flag = PROCESS_COMPLETE;
+    }
+
+    return ;
+
+BT_ERROR:
+    return ;
+}
+
+// (*bt_device_bond_created_cb)
+void CbleBGthread::CB_bond_create(int result, bt_device_info_s *device_info, void *user_data)
+{
+    DBG("callback called.");
+    if ( (bt_error_e)result != BT_ERROR_NONE )
+    {
+        what_return_value( (bt_error_e)result );
+        if ( (bt_error_e)result == BT_ERROR_REMOTE_DEVICE_NOT_FOUND )
+            ble_bond_flag = PROCESS_FREE;
+
+        return ;
+    }
+
+    CbleDevice *pdevice = (CbleDevice *)user_data;
+
+    if ( pdevice )
+    {
+#if __INTERNAL_DEBUG_
+        printf("=========== bonded device =============\n");
+        printf("= address  \t : %s \n", device_info->remote_address);
+        printf("= name     \t : %s \n", device_info->remote_name);
+        printf("= is_bonded\t : %d \n", device_info->is_bonded);
+        printf("= is_connec\t : %d \n", device_info->is_connected);
+        printf("= is_autho \t : %d \n", device_info->is_authorized);
+        printf("= svc_count\t : %d \n", device_info->service_count);
+        printf("===========================================\n");
+#endif
+
+        if ( pdevice->find( std::string(device_info->remote_address) ) )
+        {
+            reg_bond_cnt++;
+            ble_bond_flag = PROCESS_FREE;
+#if __INTERNAL_DEBUG_
+            DBG( "bonded_cnt = %d", reg_bond_cnt );
+#endif
+        }
+
+        if ( reg_bond_cnt == pdevice->size() )
+        {
+#if __INTERNAL_DEBUG_
+            DBG("bond_flag is PROCESS_COMPLETE");
+#endif
+            reg_bond_cnt = 0;
+            ble_bond_flag = PROCESS_COMPLETE;
+        }
+    }
+
+    return ;
+}
+
+
+
+/********************************
+ * ETC. function definition.
+ */
+void CbleBGthread::set_adapter_state_flag(void)
+{
+    DBG("Enter.");
+
+    // Get adapter state.
+    bt_adapter_state_e state;
+    BT_ERROR_CHECK( bt_adapter_get_state(&state) );
+
+    if ( state == BT_ADAPTER_ENABLED)
+        ble_adapter_flag = true;
+    else
+        ble_adapter_flag = false;
+
+    return ;
+
+BT_ERROR:
+    DBG("Error Exception. Exit.");
+}
+
+// return : true --> OK
+//                  false --> ERROR
+bool CbleBGthread::ble_discovery( void )
+{
+    DBG("is Searching device.");
+    bool isDiscovery = false;
+    BT_ERROR_CHECK(bt_adapter_is_discovering(&isDiscovery));
+
+    if ( isDiscovery == false )
+    {
+#if __INTERNAL_DEBUG_
+        DBG("Start searching device.");
+#endif
+        BT_ERROR_CHECK( bt_adapter_start_device_discovery() );
+    }
+
+    return true;
+
+BT_ERROR:
+    return false;
+}
+
+bool CbleBGthread::find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info ,
+                                        CbleDevice *pdevice )
+{
+    DBG("Enter.");
+
+    if ( strstr( discovery_info->remote_name, REF_NAME ) )
+    {
+#if __INTERNAL_DEBUG_
+        DBG("Find %s device.", REF_NAME);
+        DBG("Register %s device to reference-Thing.", discovery_info->remote_name );
+#endif
+        pdevice->insert( discovery_info );
+    }
+
+    return true;
+}
+
+void what_return_value( bt_error_e returnValue )
+{
+    printf("\n");
+    DBG("returnValue=%d", returnValue);
+
+    switch (returnValue)
+    {
+        case BT_ERROR_NONE:
+            DBG("return value is BT_ERROR_NONE\n");
+            break;
+        case BT_ERROR_CANCELLED:
+            DBG("return value is BT_ERROR_CANCELLED\n");
+            break;
+        case BT_ERROR_INVALID_PARAMETER:
+            DBG("return value is BT_ERROR_INVALID_PARAMETER\n");
+            break;
+        case BT_ERROR_OUT_OF_MEMORY:
+            DBG("return value is BT_ERROR_OUT_OF_MEMORY\n");
+            break;
+        case BT_ERROR_RESOURCE_BUSY:
+            DBG("return value is BT_ERROR_RESOURCE_BUSY\n");
+            break;
+        case BT_ERROR_TIMED_OUT:
+            DBG("return value is BT_ERROR_TIMED_OUT\n");
+            break;
+        case BT_ERROR_NOW_IN_PROGRESS:
+            DBG("return value is BT_ERROR_NOW_IN_PROGRESS\n");
+            break;
+        case BT_ERROR_NOT_INITIALIZED:
+            DBG("return value is BT_ERROR_NOT_INITIALIZED\n");
+            break;
+        case BT_ERROR_NOT_ENABLED:
+            DBG("return value is BT_ERROR_NOT_ENABLED\n");
+            break;
+        case BT_ERROR_ALREADY_DONE:
+            DBG("return value is BT_ERROR_ALREADY_DONE\n");
+            break;
+        case BT_ERROR_OPERATION_FAILED:
+            DBG("return value is BT_ERROR_OPERATION_FAILED\n");
+            break;
+        case BT_ERROR_NOT_IN_PROGRESS:
+            DBG("return value is BT_ERROR_NOT_IN_PROGRESS\n");
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_BONDED:
+            DBG("return value is BT_ERROR_REMOTE_DEVICE_NOT_BONDED\n");
+            break;
+        case BT_ERROR_AUTH_REJECTED:
+            DBG("return value is BT_ERROR_AUTH_REJECTED\n");
+            break;
+        case BT_ERROR_AUTH_FAILED:
+            DBG("return value is BT_ERROR_AUTH_FAILED\n");
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_FOUND:
+            DBG("return value is BT_ERROR_REMOTE_DEVICE_NOT_FOUND\n");
+            break;
+        case BT_ERROR_SERVICE_SEARCH_FAILED:
+            DBG("return value is BT_ERROR_SERVICE_SEARCH_FAILED\n");
+            break;
+        case BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED:
+            DBG("return value is BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED\n");
+            break;
+        case BT_ERROR_PERMISSION_DENIED:
+            DBG("return value is BT_ERROR_PERMISSION_DENIED\n");
+            break;
+    }
+}
+
+
+//int bt_adapter_get_le_state  ( bt_adapter_le_state_e *  adapter_le_state )
+//bt_adapter_le_enable()
+// bt_adapter_get_state()
+
+// bt_adapter_start_device_discovery().
+//      bt_adapter_device_discovery_state_changed_cb().
+// bt_device_connect_le().
+//      bt_device_gatt_state_changed_cb().
+// bt_device_read_rssi_value(const char *address);
+
+
+//int bt_device_set_connection_state_changed_cb(bt_device_connection_state_changed_cb callback, void *user_data);
+//typedef void (*bt_device_connection_state_changed_cb)(bool connected, const char *remote_address, void *user_data);
+
+
+// bt_adapter_start_device_discovery().
+//      bt_adapter_device_discovery_state_changed_cb().
+// bt_device_create_bond()
+//      bt_device_bond_created_cb().
+// bt_device_set_alias(address,name)
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_proximity.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_proximity.cpp
new file mode 100644 (file)
index 0000000..de501cc
--- /dev/null
@@ -0,0 +1,446 @@
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include <stdio.h>
+#include <iostream>
+#include "tizen_log.h"
+#include <pthread.h>
+#include <unistd.h>
+#include "tizen_proximity.h"
+#include "tizen_CbleDevice.h"
+#include "lib_proximity.h"
+
+#include "ITS.h"
+
+CProximity *prox = NULL;
+ITSName::Things *output = NULL;
+int CProximity::get_rssi_cnt = 0;
+int CProximity::num_set_rssi = 0;
+int CProximity::loop_flag = JOB_GET_RSSI;
+CProximity::rssiMAP CProximity::map_rssi;
+
+// Proximity variables
+int **rssi = 0;
+int *rssicnt = 0;
+int *startindex = 0;
+int *flag = 0;
+
+
+void proximity_init( void *(*func)(void *) )
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter.");
+#endif
+    prox = new CProximity( func );
+    output = NULL;
+}
+
+void proximity_loop( void *param )
+{
+//  DBG("called. main loop function.");
+    CbleDevice *pdevice = (CbleDevice *)param;
+
+    if ( prox == NULL || pdevice == NULL )
+    {
+        DBG("Error : proximity_loop is occurred error.");
+        return ;
+    }
+
+    // Get BLE RSSI and Calculate Proximity value. ( choi job )
+    if ( prox->loop_flag == JOB_GET_RSSI )
+    {
+        prox->GetRSSI( pdevice );
+        prox->loop_flag = JOB_BUSY;
+    }
+
+    if ( prox->loop_flag == JOB_GET_PROX )
+    {
+        prox->GetProximity( pdevice );
+        prox->loop_flag = JOB_PUT_OUTPUT;
+    }
+
+    if ( prox->loop_flag == JOB_PUT_OUTPUT )
+    {
+        // Result Setting and transmit data from proximity to ITS
+        prox->set_output( pdevice );
+        pthread_create(&prox->Thandle, NULL, prox->threadFunc, output);
+        prox->loop_flag = JOB_GET_RSSI;
+    }
+
+    usleep(100);
+//  DBG("Exit.");
+}
+
+
+
+
+/****************************************
+ *
+ * CProximity class definition.
+ *
+ */
+
+CProximity::CProximity( workfunc func )
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter.");
+#endif
+    if ( set_threadFunc(func) == false)
+        DBG("Error: set_threadFunc is failed.");
+
+    loop_flag = JOB_GET_RSSI;
+    get_rssi_cnt = 0;
+    num_set_rssi = 0;
+
+    reference_ea = 0;
+    m_distance = 0;
+    m_proximity = 0;
+    map_rssi.clear();
+}
+
+CProximity::~CProximity( void )
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter.");
+#endif
+    if ( rssi )
+    {
+        delete [] rssi;
+        rssi = NULL;
+    }
+
+    if ( rssicnt )
+    {
+        delete rssicnt;
+        rssicnt = NULL;
+    }
+
+    if ( startindex )
+    {
+        delete startindex;
+        startindex = NULL;
+    }
+
+    if ( flag )
+    {
+        delete flag;
+        flag = NULL;
+    }
+
+    if ( m_distance )
+    {
+        delete m_distance;
+        m_distance = NULL;
+    }
+
+    if ( m_proximity )
+    {
+        delete m_proximity;
+        m_proximity = NULL;
+    }
+
+}
+
+bool CProximity::find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info ,
+                                      CbleDevice *pdevice )
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter");
+#endif
+    if ( pdevice->find(discovery_info->remote_address) == false  )
+    {
+        return false;
+    }
+#if __INTERNAL_DEBUG_
+    DBG("Find %s device.", discovery_info->remote_address);
+#endif
+    if ( pdevice->setRSSI( discovery_info->remote_address,
+                           discovery_info->rssi ) == discovery_info->rssi )
+    {
+        map_rssi[ discovery_info->remote_address ].init( RSSI_EA );
+        map_rssi[ discovery_info->remote_address ].rssi[get_rssi_cnt - 1] = discovery_info->rssi - 65535;
+#if __INTERNAL_DEBUG_
+        DBG("Get RSSI. %d", map_rssi[ discovery_info->remote_address ].rssi[get_rssi_cnt - 1] );
+#endif
+        num_set_rssi++;
+    }
+
+    return true;
+}
+
+// Called by bt_adapter_start_device_discovery / bt_adapter_stop_device_discovery function.
+void CProximity::CB_discover_state_change(int result,
+        bt_adapter_device_discovery_state_e discovery_state, \
+        bt_adapter_device_discovery_info_s *discovery_info, void *user_data)
+{
+    DBG("callback called.");
+#if __INTERNAL_DEBUG_
+    DBG("result = %d", result);
+#endif
+
+    CbleDevice *pdevice = (CbleDevice *)user_data;
+
+    if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FOUND )
+    {
+        if ( discovery_info == NULL)
+            goto BT_ERROR;
+#if __INTERNAL_DEBUG_
+        printf("=========== Get RSSI =============\n");
+        printf("= address  \t : %s \n", discovery_info->remote_address);
+        printf("= name     \t : %s \n", discovery_info->remote_name);
+        printf("= rssi     \t : %d \n", (discovery_info->rssi - 65535) );
+        printf("===========================================\n");
+#endif
+        find_referenceThing( discovery_info , pdevice );
+
+        if ( num_set_rssi == pdevice->size()  )
+        {
+#if __INTERNAL_DEBUG_
+            DBG("Stop searching device.");
+#endif
+            BT_ERROR_CHECK( bt_adapter_stop_device_discovery() );
+        }
+    }
+    else if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED )
+    {
+        DBG("state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED");
+
+        num_set_rssi = 0;
+        if ( get_rssi_cnt == RSSI_EA )
+        {
+            get_rssi_cnt = 0;
+            loop_flag = JOB_GET_PROX;
+        }
+        else
+            loop_flag = JOB_GET_RSSI;
+    }
+
+    return ;
+
+BT_ERROR:
+    return ;
+}
+
+
+bool CProximity::GetRSSI(CbleDevice *pdevice)
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter");
+#endif
+    if ( num_set_rssi == 0 && get_rssi_cnt == 0)
+        map_rssi.clear();
+
+    num_set_rssi = 0;
+    get_rssi_cnt++;
+
+    for ( int i = 0; i < pdevice->size(); i++ )
+        pdevice->setRSSI( (pdevice->getNext(i))->remote_address, 0);
+
+    BT_ERROR_CHECK( bt_adapter_set_device_discovery_state_changed_cb(
+                        CProximity::CB_discover_state_change, pdevice) );
+
+    BT_ERROR_CHECK( bt_adapter_start_device_discovery() );
+
+    return true;
+
+BT_ERROR:
+    return false;
+}
+
+bool is_first = true;
+void CProximity::GetProximity(CbleDevice *pdevice)
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter.");
+#endif
+//#if __INTERNAL_DEBUG_
+    DBG("thing ea = %d", map_rssi.size() );
+    DBG("RSSI ea = %d", RSSI_EA );
+
+    for (int num = 0; num < map_rssi.size(); num++ )
+    {
+        std::string addr = pdevice->getNext(num)->remote_address;
+        DBG("Addr -> %s", addr.c_str() );
+        for (int i = 0; i < RSSI_EA ; i++)
+            DBG(" %d th. rssi = %d", i, map_rssi[addr].rssi[i] );
+    }
+//#endif
+
+    reference_ea = map_rssi.size();
+    float *avg = new float[reference_ea];
+
+    if ( is_first )
+        prox_first_setting( reference_ea );
+
+    for (int i = 0; i < reference_ea; i++)
+    {
+        std::string addr = pdevice->getNext(i)->remote_address;
+
+        if ( rssicnt[i] > arraysize - 1)
+            rssicnt[i] = rssicnt[i] % arraysize;
+
+        for (int j = 0; j < RSSI_EA; j++)
+        {
+            rssi[i][rssicnt[i]] = map_rssi[addr].rssi[j];
+            rssicnt[i]++;
+        }
+
+        avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]);
+        m_distance[i] = calculateDistance(avg[i], -58);
+
+        if ( m_distance[i] <= 1.0 )
+        {
+            m_proximity[i] = 1;
+        }
+        else if (m_distance[i] <= 2)
+        {
+            m_proximity[i] = 2;
+        }
+        else
+        {
+            m_proximity[i] = 3;
+        }
+
+        DBG("distance = %f", m_distance[i]);
+        DBG("proximity = %d", m_proximity[i]);
+        //Serial.println(calculateDistance(avg[i], -58));
+        startindex[i] += RSSI_EA;
+
+        if (startindex[i] >= arraysize)
+        {
+            startindex[i] = 0;
+        }
+
+        if (flag[i] < (arraysize / RSSI_EA))
+        {
+            flag[i]++;
+        }
+    } // for
+
+    delete avg;
+}
+
+bool CProximity::set_threadFunc(workfunc func)
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter.");
+#endif
+    if ( func == NULL )
+    {
+        DBG("Error: func is null.");
+        return false;
+    }
+
+    threadFunc = func;
+    return true;
+}
+
+CProximity::workfunc CProximity::get_threadFunc(void)
+{
+    return threadFunc;
+}
+
+void CProximity::set_output( CbleDevice *pdevice )
+{
+#if __INTERNAL_DEBUG_
+    DBG("Enter.");
+#endif
+
+    if (output)
+    {
+        delete output;
+        output = NULL;
+    }
+
+    if ( output == NULL )
+    {
+        output = new ITSName::Things(reference_ea);
+    }
+
+    if ( output == NULL )
+    {
+        DBG("Error : output is NULL.");
+        return ;
+    }
+
+    // Set Output value.
+    for (int i = 0; i < reference_ea; i++)
+    {
+        output->things[i].ID = pdevice->getNext(i)->remote_address;
+        output->things[i].SD = 0.0;
+        output->things[i].distance = m_distance[i];
+        output->things[i].proximity = m_proximity[i];
+    }
+}
+
+
+
+
+void CProximity::prox_first_setting( int reference_ea )
+{
+    if ( rssi == NULL )
+    {
+        rssi = new int *[reference_ea];
+
+        for (int i = 0; i < reference_ea; i++)
+        {
+            rssi[i] = new int[arraysize];
+            for (int j = 0; j < arraysize; j++)
+                rssi[i][j] = 0;
+        }
+    }
+
+    if ( rssicnt == NULL )
+    {
+        rssicnt = new int[reference_ea];
+        for (int j = 0; j < reference_ea; j++)
+            rssicnt[j] = 0;
+    }
+
+    if ( startindex == NULL )
+    {
+        startindex = new int[reference_ea];
+        for (int j = 0; j < reference_ea; j++)
+            startindex[j] = 0;
+    }
+
+    if ( flag == NULL)
+    {
+        flag = new int[reference_ea];
+        for (int j = 0; j < reference_ea; j++)
+            flag[j] = 0;
+    }
+
+    if ( m_distance == NULL )
+    {
+        m_distance = new float[reference_ea];
+        for (int j = 0; j < reference_ea; j++)
+            m_distance[j] = 0;
+    }
+
+    if ( m_proximity == NULL )
+    {
+        m_proximity = new int[reference_ea];
+        for (int j = 0; j < reference_ea; j++)
+            m_proximity[j] = 0;
+    }
+
+    is_first = false;
+}
\ No newline at end of file
index bdf8018..e1deecd 100644 (file)
     </inputs>
   </softsensor>
   
+  <softsensor>
+    <name>BMISensor</name>
+    <attributes>
+      <attribute>
+        <name>version</name>
+        <type>string</type>
+        <value>1.0</value>
+      </attribute>
+      <attribute>
+        <name>lifetime</name>
+        <type>int</type>
+        <value>60</value>
+      </attribute>
+    </attributes>
+    <outputs>
+      <output>
+        <name>BMIresult</name>
+        <type>int</type>
+      </output>
+    </outputs>
+    <inputs>
+     <input>Thing_WeightSensor</input>  
+     <input>Thing_HeightSensor</input>
+    </inputs>
+  </softsensor>
+
+
 </softsensors>
diff --git a/service/soft-sensor-manager/build/arduino/Makefile b/service/soft-sensor-manager/build/arduino/Makefile
deleted file mode 100644 (file)
index 1c3ae15..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-IOTIVITY_DIR=${shell cd ../../../../ && pwd}
-${shell echo "ROOT_DIR=${IOTIVITY_DIR}" > ./root_path.inc}
-
--include ./root_path.inc
--include ./environment.mk
-
-MAKE=make
-RST_NAME=release
-CUR_DIR=${PWD}
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job build post_job 
-
-pre_job:
-       @echo " " 
-       @echo "*********************************************************" 
-       @echo "*           Samsung Electronics. Open Source.           *"
-       @echo "*                                                       *"
-       @echo "* It's build script for SoftSensorManagement system.    *"
-       @echo "* Before build, Open the environment.mk file.           *"
-       @echo "* And, Modify ROOT_DIR path, which depend on your PC.   *"
-       @echo "* And, Modify BOOST_BASE path, which depend on your PC. *"
-       @echo "*                                                       *"
-       @echo "*********************************************************" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-
-       
-build:
-       @for subdir in ${MAKE_LIST} ; do \
-       echo ">>>>>>>>>>>> $${subdir}/Makefile run <<<<<<<<<<<<<" ; \
-       cd $${subdir} && ${MAKE} ${OPTION} ; \
-       echo " " ; \
-       done
-       @echo " "
-
-post_job:
-       @echo " " 
-       @echo "*********************************************************" 
-       @echo "*                                                       *"
-       @echo "*               Success. build script.                  *"
-       @echo "*                    - End -                            *"
-       @echo "*********************************************************" 
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " " 
-
-clean:
-
-       rm -rf ./${RST_NAME}
-       @for subdir in ${MAKE_LIST} ; do \
-       echo ">>>>>>>>>>>> $${subdir}/Makefile clean run <<<<<<<<<<<<<<" ; \
-       ${MAKE} clean -C $${subdir} ; \
-       echo " " ; \
-       done
diff --git a/service/soft-sensor-manager/build/arduino/environment.mk b/service/soft-sensor-manager/build/arduino/environment.mk
deleted file mode 100644 (file)
index 2d8949e..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-
-# ioc-resource folder path.
-IOT_BASE=${ROOT_DIR}/resource
-IOT_MAKE_PATH=${IOT_BASE}
-IOT_RELEASE=${IOT_BASE}/release/obj
-IOT_CSDK_LINUX_RELEASE=${IOT_BASE}/csdk/linux/release
-IOT_CSDK_ARDUINOMEGA_RELEASE=${IOT_BASE}/csdk/arduinomega/release
-
-# oic-service folder path.
-FD_SSM=${ROOT_DIR}/service/soft-sensor-manager
-FD_SAMPLEAPP=${FD_SSM}/SampleApp
-FD_BUILD=${FD_SSM}/build
-
-# outputs directory path.
-OUTPUTS_DIR=${FD_BUILD}/arduino/release
-
-#OPTION=PLATFORM=arduinomega ARDUINOWIFI=1
-# SoftSensorManager makefile path
-MAKE_00=${FD_SAMPLEAPP}/arduino
-MAKE_01=${FD_SAMPLEAPP}/arduino/THSensorApp/build
-MAKE_03=${FD_SAMPLEAPP}/arduino/Trackee_Thing/build
-MAKE_04=${FD_SAMPLEAPP}/arduino/Reference_Thing/build
-
-MAKE_LIST=${MAKE_01} ${MAKE_03} ${MAKE_04}
-
diff --git a/service/soft-sensor-manager/build/linux/Makefile b/service/soft-sensor-manager/build/linux/Makefile
deleted file mode 100644 (file)
index 2b79304..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-IOTIVITY_DIR=${shell cd ../../../../ && pwd}
-${shell echo "ROOT_DIR=${IOTIVITY_DIR}" > ./root_path.inc}
-
--include ./root_path.inc
--include ./environment.mk
-
-MAKE=make
-RST_NAME=release
-
-CUR_DIR=${PWD}
-SRCLIST=${wildcard **/**/Makefile}
-DIRLIST=${patsubst %/, % , ${dir ${SRCLIST}} }
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job build post_job 
-
-pre_job:
-       @echo " " 
-       @echo "*********************************************************" 
-       @echo "*           Samsung Electronics. Open Source.           *"
-       @echo "*                                                       *"
-       @echo "* It's build script for SoftSensorManagement system.    *"
-       @echo "* Before build, Open the environment.mk file.           *"
-       @echo "* And, Modify BOOST_BASE path, which depend on your PC. *"
-       @echo "*                                                       *"
-       @echo "*********************************************************" 
-       @mkdir -p ${RST_NAME}
-       @echo " "
-#      @cd ${IOT_BASE} &&      ${MAKE};
-#      @cd ${CUR_DIR};
-       
-build:
-       @for subdir in ${MAKE_LIST} ; do \
-       echo ">>>>>>>>>>>> $${subdir}/Makefile run <<<<<<<<<<<<<" ; \
-       ${MAKE} -C $${subdir} ; \
-       echo " " ; \
-       done
-       @echo " "
-
-post_job:
-       @echo " " 
-       @echo "*********************************************************" 
-       @echo "*                                                       *"
-       @echo "*               Success. build script.                  *"
-       @echo "*                    - End -                            *"
-       @echo "*********************************************************" 
-       @echo "Enter to ${RST_NAME} folder."
-       @echo " "
-
-
-clean:
-       
-       rm -rf ./${RST_NAME}
-       @for subdir in ${MAKE_LIST} ; do \
-       echo ">>>>>>>>>>>> $${subdir}/Makefile clean run <<<<<<<<<<<<<<" ; \
-       ${MAKE} clean -C $${subdir} ; \
-       echo " " ; \
-       done
-       rm -rf ./root_path.inc
diff --git a/service/soft-sensor-manager/build/linux/environment.mk b/service/soft-sensor-manager/build/linux/environment.mk
deleted file mode 100644 (file)
index 500f7d1..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-# boost folder path.
-BOOST_BASE=/usr/include
-
-# ioc-resource folder path.
-IOT_BASE=${ROOT_DIR}/resource
-IOT_MAKE_PATH=${IOT_BASE}
-IOT_RELEASE=${IOT_MAKE_PATH}/release/obj
-IOT_CSDK_RELEASE=${IOT_BASE}/csdk/linux/release
-IOT_LOG_DIR=${IOT_BASE}/oc_logger
-IOT_LIB=liboc.a
-IOT_CSDK_LIB=liboctbstack.a
-IOT_LOG_LIB=oc_logger.a
-
-# service folder path.
-FD_SSM=${ROOT_DIR}/service/soft-sensor-manager
-FD_SDK=${FD_SSM}/SDK/cpp
-FD_SSMCORE=${FD_SSM}/SSMCore
-FD_SAMPLEAPP=${FD_SSM}/SampleApp
-FD_SOFTSENSOR=${FD_SSM}/SoftSensorPlugin
-FD_BUILD=${FD_SSM}/build
-
-# outputs directory path.
-OUTPUTS_DIR=${FD_BUILD}/linux/release
-EXEC_DIR=${OUTPUTS_DIR}
-SSXML_NAME="SoftSensorDescription.xml"
-SSM_LIB = libSSMSDK.a
-SSMCORE_LIB=libSSMCore.a
-
-# SoftSensorManager makefile path
-MAKE_01=${FD_SSMCORE}/build/linux
-MAKE_02=${FD_SDK}/build/linux
-MAKE_03=${FD_SAMPLEAPP}/linux
-MAKE_04=${FD_SAMPLEAPP}/arduino
-MAKE_05=${FD_SOFTSENSOR}/DiscomfortIndexSensor/build/linux
-MAKE_06=${FD_SOFTSENSOR}/IndoorTrajectorySensor/build/linux
-
-
-MAKE_LIST=${MAKE_01} ${MAKE_02} ${MAKE_03} ${MAKE_05} ${MAKE_06}
\ No newline at end of file
index e3c5f74..788dbdd 100644 (file)
@@ -32,7 +32,5 @@ SourceCode/tgmtest
 IDE/LINUX_TEST/tgmtest
 inc4.7/
 .settings/
-.cproject
-.project
 TestApp/introspection/tgmclient
 TestApp/introspection/introspectionServer
\ No newline at end of file
old mode 100755 (executable)
new mode 100644 (file)
index 412907c..00fbf5b 100644 (file)
@@ -1,7 +1,27 @@
+#******************************************************************
+#
+# 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
 ##
-
+import os
 Import('env')
 
 # Add third party libraries
@@ -13,23 +33,27 @@ target_os = env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
-things_manager_env.AppendUnique(CPPPATH = ['sdk/inc', 'sdk/src'])
+things_manager_env.AppendUnique(CPPPATH = ['../../extlibs/timer', 'sdk/inc', 'sdk/src'])
 
 if target_os not in ['windows', 'winrt']:
-       things_manager_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
-       if target_os != 'android':
-               things_manager_env.AppendUnique(CXXFLAGS = ['-pthread'])
+    things_manager_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+    if target_os != 'android':
+        things_manager_env.AppendUnique(CXXFLAGS = ['-pthread'])
 
 if target_os == 'android':
-       things_manager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+    things_manager_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+    things_manager_env.PrependUnique(LIBS = ['oc', 'octbstack', 'gnustl_shared', 'android_cpp11_compat', 'log'])
 
 ######################################################################
 # Source files and Targets
 ######################################################################
-tgm_src = env.Glob('sdk/src/*.cpp')
-tgmsdk = things_manager_env.StaticLibrary('TGMSDKLibrary', tgm_src)
+tgm_src = env.Glob('sdk/src/*.cpp', '../../extlibs/timer/timer.c')
+tgmsdk_static = things_manager_env.StaticLibrary('TGMSDKLibrary', tgm_src)
+tgmsdk_shared = things_manager_env.SharedLibrary('TGMSDKLibrary', tgm_src)
 
-things_manager_env.InstallTarget(tgmsdk, 'libTGMSDK')
+things_manager_env.InstallTarget([tgmsdk_static,tgmsdk_shared], 'libTGMSDK')
 
 #Go to build sample apps
 SConscript('sampleapp/SConscript')
+
+
diff --git a/service/things-manager/build/linux/makefile b/service/things-manager/build/linux/makefile
deleted file mode 100644 (file)
index 4fc7d7e..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-.PHONY : pre resource sdk sampleapp
-#.PHONY : lib tgm sdk sampleapp
-all: .PHONY
-
-pre:
-       -mkdir release
-
-resource:
-       cd ../../../../resource && $(MAKE)
-
-
-sdk:
-       cd ../../sdk/build/linux && $(MAKE)
-       cp -Rdp ../../sdk/build/linux/*.a release/
-
-sampleapp:
-       cd ../../sampleapp/linux && $(MAKE)
-       cp -Rdp ../../sampleapp/linux/configuration/con-server release/
-       cp -Rdp ../../sampleapp/linux/configuration/con-client release/
-       cp -Rdp ../../sampleapp/linux/configuration/bootstrapserver release/
-       cp -Rdp ../../sampleapp/linux/groupaction/groupserver release/
-       cp -Rdp ../../sampleapp/linux/groupaction/bookmark release/
-       cp -Rdp ../../sampleapp/linux/groupaction/lightserver release/
-       cp -Rdp ../../sampleapp/linux/groupsyncaction/group release/
-       cp -Rdp ../../sampleapp/linux/groupsyncaction/musicplayer release/
-       cp -Rdp ../../sampleapp/linux/groupsyncaction/phone release/
-       cp -Rdp ../../sampleapp/linux/groupsyncaction/speaker release/
-
-clean:
-       cd ../../sdk/build/linux && $(MAKE) clean
-       cd ../../sampleapp/linux && $(MAKE) clean
-       rm -rf ./release
index 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
 ##
diff --git a/service/things-manager/sampleapp/android/Sample/.classpath b/service/things-manager/sampleapp/android/Sample/.classpath
new file mode 100644 (file)
index 0000000..7bc01d9
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="src" path="gen"/>
+       <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+       <classpathentry kind="output" path="bin/classes"/>
+</classpath>
diff --git a/service/things-manager/sampleapp/android/Sample/.project b/service/things-manager/sampleapp/android/Sample/.project
new file mode 100644 (file)
index 0000000..3261c83
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>Sample</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+       </natures>
+</projectDescription>
diff --git a/service/things-manager/sampleapp/android/Sample/AndroidManifest.xml b/service/things-manager/sampleapp/android/Sample/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..561e289
--- /dev/null
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.tm.sample"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+   <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="21" />
+
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/iot"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity
+            android:name=".GroupApiActivity"
+            android:label="@string/app_name" >
+        </activity>
+        <activity
+            android:name=".ConfigurationApiActivity"
+            android:label="@string/app_name" >  
+        </activity>
+    </application>
+
+</manifest>
diff --git a/service/things-manager/sampleapp/android/Sample/ic_launcher-web.png b/service/things-manager/sampleapp/android/Sample/ic_launcher-web.png
new file mode 100644 (file)
index 0000000..a18cbb4
Binary files /dev/null and b/service/things-manager/sampleapp/android/Sample/ic_launcher-web.png differ
diff --git a/service/things-manager/sampleapp/android/Sample/project.properties b/service/things-manager/sampleapp/android/Sample/project.properties
new file mode 100644 (file)
index 0000000..68e5d52
--- /dev/null
@@ -0,0 +1,15 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-20
+android.library.reference.1=../../../sdk/java
diff --git a/service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/ic_launcher.png b/service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/iot.jpg b/service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/iot.jpg
new file mode 100644 (file)
index 0000000..17c5a93
Binary files /dev/null and b/service/things-manager/sampleapp/android/Sample/res/drawable-hdpi/iot.jpg differ
diff --git a/service/things-manager/sampleapp/android/Sample/res/drawable-mdpi/ic_launcher.png b/service/things-manager/sampleapp/android/Sample/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..6ae570b
Binary files /dev/null and b/service/things-manager/sampleapp/android/Sample/res/drawable-mdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/Sample/res/drawable-xhdpi/ic_launcher.png b/service/things-manager/sampleapp/android/Sample/res/drawable-xhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..d4fb7cd
Binary files /dev/null and b/service/things-manager/sampleapp/android/Sample/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/Sample/res/drawable-xxhdpi/ic_launcher.png b/service/things-manager/sampleapp/android/Sample/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..85a6081
Binary files /dev/null and b/service/things-manager/sampleapp/android/Sample/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/Sample/res/layout/activity_main.xml b/service/things-manager/sampleapp/android/Sample/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..ec14de4
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+     <ListView
+              android:id="@+id/list"
+              android:layout_height="wrap_content"
+              android:layout_width="match_parent">
+         </ListView>
+</RelativeLayout>
diff --git a/service/things-manager/sampleapp/android/Sample/res/layout/configapis.xml b/service/things-manager/sampleapp/android/Sample/res/layout/configapis.xml
new file mode 100644 (file)
index 0000000..d27b96d
--- /dev/null
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical" >
+     
+      <ListView
+          android:id="@+id/configApisList"
+          android:layout_width="wrap_content"
+          android:layout_height="320dp" >
+
+         </ListView>
+         
+      
+      <EditText
+        android:id="@+id/EditText"
+        android:layout_width="fill_parent"
+        android:layout_height="250dp"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/configApisList"
+        android:layout_marginTop="15dp"
+        android:ems="10" 
+        android:editable="false" >
+
+        <requestFocus />
+    </EditText>
+      
+</RelativeLayout>
+
+
diff --git a/service/things-manager/sampleapp/android/Sample/res/layout/custom_dialog.xml b/service/things-manager/sampleapp/android/Sample/res/layout/custom_dialog.xml
new file mode 100644 (file)
index 0000000..5230c5b
--- /dev/null
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical" >
+    
+    
+    <DatePicker
+         android:id="@+id/datePicker1"
+         android:layout_width="wrap_content"
+         android:layout_height="wrap_content" >
+    </DatePicker>
+
+    <TimePicker
+        android:id="@+id/timePicker1"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/datePicker1"
+        android:layout_marginTop="63dp" />
+
+    <Button
+        android:id="@+id/ok"
+        android:layout_width="200px"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/timePicker1"
+        android:layout_marginLeft="16dp"
+        android:layout_marginTop="53dp"
+        android:text="OK" />
+
+    <Button
+        android:id="@+id/cancel"
+        android:layout_width="200px"
+        android:layout_height="wrap_content"
+        android:layout_alignBaseline="@+id/ok"
+        android:layout_alignBottom="@+id/ok"
+        android:layout_alignParentRight="true"
+        android:layout_marginRight="34dp"
+        android:text="Cancel" />
+
+</RelativeLayout>
diff --git a/service/things-manager/sampleapp/android/Sample/res/layout/groupapis.xml b/service/things-manager/sampleapp/android/Sample/res/layout/groupapis.xml
new file mode 100644 (file)
index 0000000..a1eca50
--- /dev/null
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent" >
+    
+       <Button
+        android:id="@+id/button1"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_alignParentTop="true"
+        android:text="Find Group" />
+       
+       
+        <ListView
+            android:id="@+id/groupaApiList"
+            android:layout_width="match_parent"
+            android:layout_height="300dp" 
+             android:layout_below="@id/button1">
+         </ListView>
+         
+         <EditText
+        android:id="@+id/EditText"
+        android:layout_width="fill_parent"
+        android:layout_height="250dp"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/groupaApiList"
+        android:layout_marginTop="15dp"
+        android:ems="10" 
+        android:editable="false" >
+
+        <requestFocus />
+    </EditText>
+      
+        
+</RelativeLayout>
diff --git a/service/things-manager/sampleapp/android/Sample/res/layout/userinputforregionvalue.xml b/service/things-manager/sampleapp/android/Sample/res/layout/userinputforregionvalue.xml
new file mode 100644 (file)
index 0000000..5b3a089
--- /dev/null
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical" >
+
+      <EditText
+          android:id="@+id/region"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:layout_alignParentTop="true"
+          android:layout_centerHorizontal="true"
+          android:layout_marginTop="28dp"
+          android:ems="10"
+          android:hint="Enter the Region Value" />
+
+      <Button
+          android:id="@+id/ok"
+          android:layout_width="150dp"
+          android:layout_height="wrap_content"
+          android:layout_alignParentLeft="true"
+          android:layout_below="@+id/region"
+          android:layout_marginTop="101dp"
+          android:text="OK" />
+
+       <Button
+           android:id="@+id/cancel"
+           android:layout_width="150dp"
+           android:layout_height="wrap_content"
+           android:layout_alignBaseline="@+id/ok"
+           android:layout_alignBottom="@+id/ok"
+           android:layout_alignParentRight="true"
+           android:text="Cancel" />
+
+</RelativeLayout>
diff --git a/service/things-manager/sampleapp/android/Sample/res/menu/main.xml b/service/things-manager/sampleapp/android/Sample/res/menu/main.xml
new file mode 100644 (file)
index 0000000..c002028
--- /dev/null
@@ -0,0 +1,9 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+    <item
+        android:id="@+id/action_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never"
+        android:title="@string/action_settings"/>
+
+</menu>
diff --git a/service/things-manager/sampleapp/android/Sample/res/values-v11/styles.xml b/service/things-manager/sampleapp/android/Sample/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..1074513
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>
+
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+    </style>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/Sample/res/values-v14/styles.xml b/service/things-manager/sampleapp/android/Sample/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..2d1ebfe
--- /dev/null
@@ -0,0 +1,9 @@
+  <resources>
+
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+    </style>
+
+    <style name="AppTheme" parent="AppBaseTheme">
+    </style>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/Sample/res/values-w820dp/dimens.xml b/service/things-manager/sampleapp/android/Sample/res/values-w820dp/dimens.xml
new file mode 100644 (file)
index 0000000..f3e7020
--- /dev/null
@@ -0,0 +1,10 @@
+<resources>
+
+    <!--
+         Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
+    -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/Sample/res/values/dimens.xml b/service/things-manager/sampleapp/android/Sample/res/values/dimens.xml
new file mode 100644 (file)
index 0000000..55c1e59
--- /dev/null
@@ -0,0 +1,7 @@
+<resources>
+
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/Sample/res/values/strings.xml b/service/things-manager/sampleapp/android/Sample/res/values/strings.xml
new file mode 100644 (file)
index 0000000..b4f60ae
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="app_name">TMSample</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="action_settings">Settings</string>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/Sample/res/values/styles.xml b/service/things-manager/sampleapp/android/Sample/res/values/styles.xml
new file mode 100644 (file)
index 0000000..3ccf2b0
--- /dev/null
@@ -0,0 +1,12 @@
+<resources>
+
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+
+    </style>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ActionListener.java b/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ActionListener.java
new file mode 100644 (file)
index 0000000..a509fe7
--- /dev/null
@@ -0,0 +1,127 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+package com.tm.sample;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.tm.Action;
+import org.iotivity.service.tm.ActionSet;
+import org.iotivity.service.tm.Capability;
+import org.iotivity.service.tm.IActionListener;
+
+import android.os.Message;
+import android.util.Log;
+
+/*
+ * For getting the put,get,observe and post Callback and updating
+ *  the UI i.e. logMessage(TextBox) of GroupApiActivity.
+ */
+public class ActionListener implements IActionListener {
+
+    private final String     LOG_TAG             = this.getClass()
+                                                         .getSimpleName();
+    private static Message   msg;
+    private String           logMessage;
+    private GroupApiActivity groupApiActivityObj = null;
+
+    @Override
+    public void onPostResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onPostResponseCallback");
+
+        groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+        logMessage = "API Result : SUCCESS" + "\n";
+        logMessage = logMessage
+                + "Recieved Callback for called API (OnPostCallback)" + "\n";
+
+        // sending message to handler of GroupApiActivity to Update the UI
+        GroupApiActivity.setMessageLog(logMessage);
+        msg = Message.obtain();
+        msg.what = 1;
+        groupApiActivityObj.getHandler().sendMessage(msg);
+
+    }
+
+    @Override
+    public void onGetResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onGetResponseCallback");
+
+        String actionSetStr = rep.getValueString("ActionSet");
+        groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+        logMessage = "Recieved Callback for called API (onGetResponseCallback)"
+                + "\n" + "ActionSet:" + actionSetStr;
+
+        GroupApiActivity.setMessageLog(logMessage);
+        // sending message to handler of GroupApiActivity to Update the UI
+        msg = Message.obtain();
+        msg.what = 1;
+        groupApiActivityObj.getHandler().sendMessage(msg);
+
+        if (actionSetStr != null) {
+            ActionSet actionSet = ActionSet.toActionSet(actionSetStr);
+            if (actionSet != null) {
+                System.out.println("ActionSet Name : "
+                        + actionSet.actionsetName);
+                for (int i = 0; i < actionSet.listOfAction.size(); i++) {
+                    Action action = actionSet.listOfAction.get(i);
+                    System.out.println("Target : " + action.target);
+
+                    Vector<Capability> listOfCapability = action.listOfCapability;
+                    for (int j = 0; j < listOfCapability.size(); j++) {
+                        Capability capability = listOfCapability.get(j);
+                        System.out.println("Capability : "
+                                + capability.capability);
+                        System.out.println("Status : " + capability.status);
+                    }
+                }
+            }
+        }
+
+        groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+        GroupApiActivity.setMessageLog(logMessage);
+        msg = Message.obtain();
+        msg.what = 1;
+        groupApiActivityObj.getHandler().sendMessage(msg);
+
+    }
+
+    @Override
+    public void onPutResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onPutResponseCallback");
+
+        groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+        logMessage = "API Result : SUCCESS" + "\n";
+        logMessage = logMessage
+                + "Recieved Callback for called API (onPutResponseCallback)"
+                + "\n";
+        GroupApiActivity.setMessageLog(logMessage);
+        // sending message to handler of GroupApiActivity to Update the UI
+        msg = Message.obtain();
+        msg.what = 1;
+        groupApiActivityObj.getHandler().sendMessage(msg);
+
+    }
+
+}
diff --git a/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ConfigurationApiActivity.java b/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ConfigurationApiActivity.java
new file mode 100644 (file)
index 0000000..4795338
--- /dev/null
@@ -0,0 +1,828 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.tm.sample;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.service.tm.IConfigurationListener;
+import org.iotivity.service.tm.IDiagnosticsListener;
+import org.iotivity.service.tm.IFindCandidateResourceListener;
+import org.iotivity.service.tm.OCStackResult;
+import org.iotivity.service.tm.ThingsManager;
+
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ListView;
+import android.widget.Toast;
+
+/*
+ * Activity for Handling all Configuration Apis as per user's selection on the UI.
+ * and updating of UI
+ */
+public class ConfigurationApiActivity extends Activity {
+
+    private class ResourceInformation {
+        OcResource       resource       = null;
+        OcResourceHandle resourceHandle = null;
+    }
+
+    private final String                     LOG_TAG                                = "[TMSample] "
+                                                                                            + this.getClass()
+                                                                                                    .getSimpleName();
+
+    private final String                     CONFIGURATION_COLLECTION_RESOURCE_URI  = "/core/configuration/resourceset";
+    private final String                     CONFIGURATION_COLLECTION_RESOURCE_TYPE = "core.configuration.resourceset";
+    private final String                     DIAGNOSTIC_COLLECTION_RESOURCE_URI     = "/core/diagnostics/resourceset";
+    private final String                     DIAGNOSTIC_COLLECTION_RESOURCE_TYPE    = "core.diagnostics.resourceset";
+    private final String                     FACTORYSET_COLLECTION_RESOURCE_URI     = "/core/factoryset/resourceset";
+    private final String                     FACTORYSET_COLLECTION_RESOURCE_TYPE    = "core.factoryset.resourceset";
+
+    private final String                     CONFIGURATION_RESOURCE_URI             = "/oic/con";
+    private final String                     DIAGNOSTIC_RESOURCE_URI                = "/oic/diag";
+    private final String                     FACTORYSET_RESOURCE_URI                = "/factorySet";
+
+    private ListView                         list;
+    private ArrayAdapter<String>             configurationApis;
+    private ArrayList<String>                configurationApisList;
+
+    private static int                       messageCount                           = 0;
+    private static EditText                  logs;
+    private static String                    logMessage                             = "";
+    private static Handler                   mHandler;
+    private static Message                   msg;
+
+    private ThingsManager                    thingsManager                          = null;
+    private Map<String, ResourceInformation> resourceList                           = null;
+    private Map<String, ResourceInformation> collectionList                         = null;
+
+    public boolean                           configurationResourceFlag              = false;
+    public boolean                           factorySetResourceFlag                 = false;
+    public boolean                           diagnosticsResourceFlag                = false;
+
+    public static Context                    mcontext;
+    public String                            region                                 = "";
+    public boolean                           findGroupPressedFlag                   = false;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.configapis);
+
+        mcontext = this;
+        thingsManager = new ThingsManager();
+
+        // set the listeners
+        setResourceListener();
+        setConfigurationListener();
+        setDiagnosticsListener();
+
+        // Create API menu list
+        configurationApisList = new ArrayList<String>();
+
+        logs = (EditText) findViewById(R.id.EditText);
+
+        list = (ListView) findViewById(R.id.configApisList);
+        configurationApisList.add("Find All Groups");
+        configurationApisList.add("Find All Resources");
+        configurationApisList.add("Get a Configuration Resource");
+        configurationApisList.add("Update Attribute (Region)");
+        configurationApisList.add("Factory Reset");
+        configurationApisList.add("Reboot");
+        configurationApisList.add("Get Supported Configuration Units");
+        configurationApis = new ArrayAdapter<String>(this,
+                android.R.layout.simple_list_item_1, configurationApisList);
+        list.setAdapter(configurationApis);
+
+        // setting the Listener for calling the APIs as per User selection
+        list.setOnItemClickListener(new OnItemClickListener() {
+
+            @Override
+            public void onItemClick(AdapterView<?> parent, View view,
+                    int position, long id) {
+
+                // Find All Groups
+                if (position == 0) {
+                    Vector<String> resourceTypes = new Vector<String>();
+                    resourceTypes.add("core.configuration.resourceset");
+                    findCandidateResources(resourceTypes);
+
+                    logMessage = "";
+                    messageCount = 0;
+                    messageCount++;
+
+                    resourceTypes.clear();
+                    resourceTypes.add("core.diagnostics.resourceset");
+                    findCandidateResources(resourceTypes);
+
+                    messageCount++;
+
+                    resourceTypes.clear();
+                    resourceTypes.add("core.factoryset.resourceset");
+                    findCandidateResources(resourceTypes);
+
+                    messageCount++;
+
+                } else if (position == 1) { // Find All Resources
+                    if (false == findGroupPressedFlag) {
+                        displayToastMessage("Configuration collection resource does not exist!");
+                    } else {
+                        Vector<String> resourceTypes = new Vector<String>();
+                        resourceTypes.add("oic.con");
+                        findCandidateResources(resourceTypes);
+
+                        logMessage = "";
+                        messageCount = 0;
+                        messageCount++;
+
+                        resourceTypes.clear();
+                        resourceTypes.add("oic.diag");
+                        findCandidateResources(resourceTypes);
+
+                        messageCount++;
+
+                        resourceTypes.clear();
+                        resourceTypes.add("factorySet");
+                        findCandidateResources(resourceTypes);
+
+                        messageCount++;
+                    }
+                } else if (position == 2) { // Get Configuration
+                    getConfiguration();
+                } else if (position == 3) { // Update Attribute (Region)
+                    userInputDialog();
+                } else if (position == 4) { // Factory Reset
+                    factoryReset();
+                } else if (position == 5) { // Reboot
+                    reboot();
+                } else if (position == 6) { // Get Supported Configuration Units
+                    String configurationUnits;
+                    configurationUnits = getListOfSupportedConfigurationUnits();
+                    Log.i(LOG_TAG, "Configuration Units:" + configurationUnits);
+                    logMessage = configurationUnits;
+                    logs.setText("");
+                    logs.setText(logMessage);
+
+                }
+            }
+        });
+
+        resourceList = new HashMap<String, ResourceInformation>();
+        collectionList = new HashMap<String, ResourceInformation>();
+
+        try {
+            createResourceCollection(CONFIGURATION_COLLECTION_RESOURCE_URI,
+                    CONFIGURATION_COLLECTION_RESOURCE_TYPE);
+            createResourceCollection(DIAGNOSTIC_COLLECTION_RESOURCE_URI,
+                    DIAGNOSTIC_COLLECTION_RESOURCE_TYPE);
+            createResourceCollection(FACTORYSET_COLLECTION_RESOURCE_URI,
+                    FACTORYSET_COLLECTION_RESOURCE_TYPE);
+        } catch (OcException e) {
+            Log.e(LOG_TAG, "OcException occured! " + e.toString());
+        }
+
+        // handler for updating the UI i.e. LogMessage TextBox
+        mHandler = new Handler() {
+            @Override
+            public void handleMessage(Message msg) {
+                switch (msg.what) {
+                    case 0:
+                        logs.setText("");
+                        logs.setText(logMessage);
+                }
+            }
+        };
+
+    }
+
+    private void userInputDialog() {
+
+        ResourceInformation configurationCollection = collectionList
+                .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+        if (null == configurationCollection
+                || null == configurationCollection.resource) {
+            Log.e(LOG_TAG, "configuration collection resource doest not exist!");
+            displayToastMessage("Configuration collection resource does not exist!");
+        }
+        if (false == configurationResourceFlag) {
+            Log.e(LOG_TAG, "configuration resource doest not exist!");
+            displayToastMessage("Configuration resource does not exist!");
+        } else {
+            final Dialog dialog = new Dialog(mcontext);
+            dialog.setContentView(R.layout.userinputforregionvalue);
+            dialog.setTitle("Enter the Region Value");
+
+            dialog.setCancelable(false);
+            dialog.show();
+            Button ok = (Button) dialog.findViewById(R.id.ok);
+            Button cancel = (Button) dialog.findViewById(R.id.cancel);
+
+            ok.setOnClickListener(new OnClickListener() {
+                @Override
+                public void onClick(View v) {
+
+                    EditText regionValue = (EditText) dialog
+                            .findViewById(R.id.region);
+                    region = regionValue.getText().toString();
+                    if (region.equalsIgnoreCase("")) {
+                        String toastmessage = "Please enter the Region Value";
+                        displayToastMessage(toastmessage);
+                    } else {
+                        dialog.dismiss();
+                        updateConfiguration(region);
+                    }
+                }
+            });
+            cancel.setOnClickListener(new OnClickListener() {
+                @Override
+                public void onClick(View v) {
+                    dialog.dismiss();
+                }
+            });
+        }
+    }
+
+    @Override
+    public void onBackPressed() {
+        super.onBackPressed();
+
+        // unregistering resource from the platform
+        deleteResources();
+        resourceList.clear();
+        resourceList = null;
+        collectionList.clear();
+        collectionList = null;
+    }
+
+    private void setResourceListener() {
+        thingsManager
+                .setFindCandidateResourceListener(new IFindCandidateResourceListener() {
+
+                    @Override
+                    synchronized public void onResourceCallback(
+                            Vector<OcResource> resources) {
+                        Log.i(LOG_TAG, "onResourceCallback: enter");
+                        for (int i = 0; i < resources.size(); i++) {
+                            OcResource resource = resources.get(i);
+                            String uri = resource.getUri();
+                            String host = resource.getHost();
+
+                            // Display resource information
+                            Log.i(LOG_TAG, "Resource URI:" + uri);
+                            Log.i(LOG_TAG, "Resource HOST: " + host);
+                            Log.i(LOG_TAG, "Resource types: ");
+                            logMessage = logMessage + "Resource URI : " + uri
+                                    + "\n";
+                            logMessage = logMessage + "Resource Host : " + host
+                                    + "\n";
+
+                            List<String> resourcetypes = resource
+                                    .getResourceTypes();
+                            for (int j = 0; j < resourcetypes.size(); j++) {
+                                Log.i(LOG_TAG, resourcetypes.get(j));
+                                logMessage = logMessage + "ResourceType "
+                                        + (j + 1) + " : "
+                                        + resourcetypes.get(j) + "\n";
+                            }
+
+                            Log.i(LOG_TAG, "Interface types: ");
+                            List<String> interfacetypes = resource
+                                    .getResourceInterfaces();
+                            for (int j = 0; j < interfacetypes.size(); j++) {
+                                Log.i(LOG_TAG, interfacetypes.get(j));
+                                logMessage = logMessage + "interfacetype "
+                                        + (j + 1) + " : "
+                                        + interfacetypes.get(j) + "\n";
+                            }
+
+                            try {
+                                if (true == uri.contains("/resourceset")) {
+                                    collectionFound(resource);
+                                } else {
+                                    resourceFound(resource);
+                                }
+                            } catch (OcException e) {
+                                Log.e(LOG_TAG,
+                                        "OcExcepion occured! " + e.toString());
+                            }
+                        }
+                        if (messageCount == 3) {
+                            msg = Message.obtain();
+                            msg.what = 0;
+                            mHandler.sendMessage(msg);
+                        }
+                    }
+                });
+    }
+
+    private void setConfigurationListener() {
+        thingsManager.setConfigurationListener(new IConfigurationListener() {
+            @Override
+            public void onBootStrapCallback(
+                    Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+                    int errorValue) {
+                Log.i(LOG_TAG, "onBootStrapCallback: enter");
+            }
+
+            @Override
+            public void onUpdateConfigurationsCallback(
+                    Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+                    int errorValue) {
+                Log.i(LOG_TAG, "onUpdateConfigurationsCallback: enter");
+                Log.i(LOG_TAG, "Resource URI: " + rep.getUri());
+                if (rep.hasAttribute("loc")) {
+                    logMessage = logMessage + "Location : "
+                            + rep.getValueString("loc") + "\n";
+                }
+                if (rep.hasAttribute("st")) {
+                    logMessage = logMessage + "System Time : "
+                            + rep.getValueString("loc") + "\n";
+                }
+                if (rep.hasAttribute("c")) {
+                    logMessage = logMessage + "Currency : "
+                            + rep.getValueString("c") + "\n";
+                }
+                if (rep.hasAttribute("r")) {
+                    logMessage = logMessage + "Region : "
+                            + rep.getValueString("r") + "\n";
+                }
+
+            }
+
+            @Override
+            public void onGetConfigurationsCallback(
+                    Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+                    int errorValue) {
+                Log.i(LOG_TAG, "onGetConfigurationsCallback: enter");
+                Log.i(LOG_TAG, "Resource URI: " + rep.getUri());
+                logMessage = logMessage + "Resource URI : " + rep.getUri()
+                        + "\n";
+
+                if (rep.hasAttribute("loc")) {
+                    logMessage = logMessage + "Location : "
+                            + rep.getValueString("loc") + "\n";
+                }
+                if (rep.hasAttribute("st")) {
+                    logMessage = logMessage + "System Time : "
+                            + rep.getValueString("st") + "\n";
+                }
+                if (rep.hasAttribute("c")) {
+                    logMessage = logMessage + "Currency : "
+                            + rep.getValueString("c") + "\n";
+                }
+                if (rep.hasAttribute("r")) {
+                    logMessage = logMessage + "Region : "
+                            + rep.getValueString("r") + "\n";
+                }
+
+                msg = Message.obtain();
+                msg.what = 0;
+                mHandler.sendMessage(msg);
+            }
+        });
+    }
+
+    private void setDiagnosticsListener() {
+        thingsManager.setDiagnosticsListener(new IDiagnosticsListener() {
+
+            @Override
+            public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+                    OcRepresentation rep, int errorValue) {
+                Log.i(LOG_TAG, "onRebootCallback: enter");
+            }
+
+            @Override
+            public void onFactoryResetCallback(
+                    Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+                    int errorValue) {
+                Log.i(LOG_TAG, "onFactoryResetCallback: enter");
+            }
+        });
+    }
+
+    /**
+     * This method find the resources available in network.
+     */
+    private void findCandidateResources(Vector<String> resourceTypes) {
+        OCStackResult result = thingsManager.findCandidateResources(
+                resourceTypes, 5);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "Error while calling findCandidateResources");
+            String toastmessage = "findCandidateResources API returned error! ["
+                    + result + "]";
+            displayToastMessage(toastmessage);
+        }
+        if (messageCount == 1)
+            logMessage = logMessage + "API RESULT : " + result.toString()
+                    + "\n";
+    }
+
+    /**
+     * This method gets the configuration data from con-server.
+     */
+    private void getConfiguration() {
+        Log.i(LOG_TAG, "There are " + resourceList.size()
+                + " servers present in network");
+        ResourceInformation configurationCollection = collectionList
+                .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+        if (null == configurationCollection
+                || null == configurationCollection.resource) {
+            Log.e(LOG_TAG, "configuration collection resource doest not exist!");
+            displayToastMessage("Configuration collection resource does not exist!");
+            return;
+        }
+        if (false == configurationResourceFlag) {
+
+            Log.e(LOG_TAG, "configuration resource doest not exist!");
+            displayToastMessage("Configuration resource does not exist!");
+            return;
+        }
+
+        String name = "all";
+        Vector<String> configs = new Vector<String>();
+        configs.add(name);
+
+        OCStackResult result = OCStackResult.OC_STACK_ERROR;
+        try {
+            result = thingsManager.getConfigurations(
+                    configurationCollection.resource, configs);
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "getConfigurations failed!");
+            String toastmessage = "getConfigurations API returned error! ["
+                    + result + "]";
+            displayToastMessage(toastmessage);
+        }
+        logMessage = "API RESULT : " + result.toString() + "\n";
+        msg = Message.obtain();
+        msg.what = 0;
+        mHandler.sendMessage(msg);
+    }
+
+    /**
+     * This method update the configuration resource region attribute to given
+     * value.
+     *
+     * @param region
+     */
+    private void updateConfiguration(String region) {
+        ResourceInformation configurationCollection = collectionList
+                .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+        String name = "r";
+        Map<String, String> configurations = new HashMap<String, String>();
+
+        try {
+            configurations.put(name, region);
+        } catch (Exception e) {
+            Log.e(LOG_TAG, "Exception occured! " + e.toString());
+        }
+
+        OCStackResult result = OCStackResult.OC_STACK_ERROR;
+        try {
+            result = thingsManager.updateConfigurations(
+                    configurationCollection.resource, configurations);
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "updateConfigurations failed!");
+            String toastmessage = "updateConfigurations API returned error! ["
+                    + result + "]";
+            displayToastMessage(toastmessage);
+        }
+        logMessage = "API RESULT : " + result.toString() + "\n";
+        logMessage = logMessage + "Updating region to " + region;
+        msg = Message.obtain();
+        msg.what = 0;
+        mHandler.sendMessage(msg);
+    }
+
+    /**
+     * This method send request to reset all the configuration attribute values
+     * to default.
+     */
+    private void factoryReset() {
+        ResourceInformation diagnosticsCollection = collectionList
+                .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+        if (null == diagnosticsCollection
+                || null == diagnosticsCollection.resource) {
+            Log.e(LOG_TAG, "Diagnostic collection doest not exist!");
+            displayToastMessage("Diagnostic collection does not exist!");
+            return;
+        }
+
+        if (false == diagnosticsResourceFlag) {
+            Log.e(LOG_TAG, "Diagnostic resource doest not exist!");
+            displayToastMessage("Diagnostic resource does not exist!");
+            return;
+        }
+
+        OCStackResult result = OCStackResult.values()[30];
+
+        try {
+            result = thingsManager.factoryReset(diagnosticsCollection.resource);
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "factoryReset failed!");
+            String toastmessage = "factoryReset API returned error! [" + result
+                    + "]";
+            displayToastMessage(toastmessage);
+
+        }
+        logMessage = "API RESULT : " + result.toString() + "\n";
+        msg = Message.obtain();
+        msg.what = 0;
+        mHandler.sendMessage(msg);
+    }
+
+    /**
+     * This method send request to reboot server.
+     */
+    private void reboot() {
+        ResourceInformation diagnosticsCollection = collectionList
+                .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+        if (null == diagnosticsCollection
+                || null == diagnosticsCollection.resource) {
+            Log.e(LOG_TAG, "Diagnostic collection doest not exist!");
+            displayToastMessage("Diagnostic collection does not exist!");
+            return;
+        }
+        if (false == diagnosticsResourceFlag) {
+            Log.e(LOG_TAG, "Diagnostic resource doest not exist!");
+            displayToastMessage("Diagnostic resource does not exist!");
+            return;
+        }
+
+        OCStackResult result = OCStackResult.OC_STACK_ERROR;
+        try {
+            result = thingsManager.reboot(diagnosticsCollection.resource);
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "reboot failed!");
+            String toastmessage = "reboot API returned error! [" + result + "]";
+            displayToastMessage(toastmessage);
+        }
+        logMessage = "API RESULT : " + result.toString() + "\n";
+        msg = Message.obtain();
+        msg.what = 0;
+        mHandler.sendMessage(msg);
+    }
+
+    /**
+     * This method is for getting list of all supported configuration values.
+     * Response will be in JSON format (key-value pair).
+     */
+    private String getListOfSupportedConfigurationUnits() {
+        return thingsManager.getListOfSupportedConfigurationUnits();
+    }
+
+    private void displayToastMessage(String message) {
+        Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
+        toast.show();
+    }
+
+    private void collectionFound(OcResource resource) {
+        String uri = resource.getUri();
+        ResourceInformation resourceInfo = collectionList.get(uri);
+        if (null == resourceInfo) {
+            Log.e(LOG_TAG, "Collection is not created!");
+            return;
+        }
+
+        if (null != resourceInfo.resource) {
+            Log.e(LOG_TAG, "Collection resource already updated!");
+            return;
+        }
+
+        resourceInfo.resource = resource;
+        if (3 == messageCount) {
+            findGroupPressedFlag = true;
+        }
+    }
+
+    /**
+     * This callback will be invoked when the interested resource discovered in
+     * network.
+     */
+    private void resourceFound(OcResource resource) throws OcException {
+        String uri = resource.getUri();
+        String host = resource.getHost();
+
+        // Check if the resource already exist in the map table
+        ResourceInformation resourceInfo = resourceList.get(uri + host);
+        if (null != resourceInfo) {
+            Log.e(LOG_TAG, "Resource already exists!");
+            return;
+        }
+
+        // Create resource
+        resourceInfo = new ResourceInformation();
+        resourceInfo.resource = resource;
+        if (uri.equalsIgnoreCase("/oic/con")) {
+            ResourceInformation collectionResource = collectionList
+                    .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+            if (null == collectionResource
+                    || null == collectionResource.resourceHandle) {
+                Log.e(LOG_TAG, "Invalid Configuration collection!");
+                return;
+            }
+
+            ResourceInformation resourceInfoCollection;
+            resourceInfoCollection = collectionList
+                    .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+            OcResourceHandle handle;
+            handle = resourceInfoCollection.resourceHandle;
+            resourceInfo.resourceHandle = handle;
+            resourceInfo.resourceHandle = thingsManager.bindResourceToGroup(
+                    resource, handle);
+
+            resourceList.put(uri + host, resourceInfo);
+            configurationResourceFlag = true;
+        } else if (uri.equalsIgnoreCase("/oic/diag")) {
+            ResourceInformation diagnosticResource = collectionList
+                    .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+            if (null == diagnosticResource
+                    || null == diagnosticResource.resourceHandle) {
+                Log.e(LOG_TAG, "Invalid Configuration collection!");
+                return;
+            }
+
+            ResourceInformation resourceInfoCollection;
+            resourceInfoCollection = collectionList
+                    .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+            OcResourceHandle handle;
+            handle = resourceInfoCollection.resourceHandle;
+            resourceInfo.resourceHandle = handle;
+            resourceInfo.resourceHandle = thingsManager.bindResourceToGroup(
+                    resource, handle);
+
+            resourceList.put(uri + host, resourceInfo);
+            diagnosticsResourceFlag = true;
+        } else if (uri.equalsIgnoreCase("/factorySet")) {
+            ResourceInformation factorysetResource = collectionList
+                    .get(FACTORYSET_COLLECTION_RESOURCE_URI);
+            if (null == factorysetResource
+                    || null == factorysetResource.resourceHandle) {
+                Log.e(LOG_TAG, "Invalid Configuration collection!");
+                return;
+            }
+
+            ResourceInformation resourceInfoCollection;
+            resourceInfoCollection = collectionList
+                    .get(FACTORYSET_COLLECTION_RESOURCE_URI);
+            OcResourceHandle handle;
+            handle = resourceInfoCollection.resourceHandle;
+            resourceInfo.resourceHandle = handle;
+            resourceInfo.resourceHandle = thingsManager.bindResourceToGroup(
+                    resource, handle);
+
+            resourceList.put(uri + host, resourceInfo);
+            factorySetResourceFlag = true;
+        } else {
+            Log.e(LOG_TAG, "Resource is of different type: " + uri);
+            return;
+        }
+    }
+
+    private void createResourceCollection(String uri, String typename)
+            throws OcException {
+
+        Map<String, OcResourceHandle> groupList = new HashMap<String, OcResourceHandle>();
+
+        Log.i(LOG_TAG, "createGroup: " + typename);
+        // Check if the resource collection is already created
+        if (null != collectionList.get(uri)) {
+            Log.e(LOG_TAG, "Collection is already exist!");
+            return;
+        }
+
+        OcResourceHandle resourceHandle = null;
+
+        // Crate group
+        OCStackResult result = thingsManager.createGroup(typename);
+        if ((OCStackResult.OC_STACK_OK != result)) {
+            Log.e(LOG_TAG, "createGroup returned error: " + result.name());
+            return;
+        } else {
+            Log.e(LOG_TAG, "createGroup returned: " + result.name());
+        }
+        groupList = thingsManager.getGroupList();
+        if (groupList.containsKey(typename)) {
+            resourceHandle = groupList.get(typename);
+        } else {
+            Log.e(LOG_TAG, "group does not contain groupResourceType: "
+                    + result.name());
+        }
+
+        if (null == resourceHandle) {
+            Log.e(LOG_TAG, " createResourceCollection : resourceHandle is NULL");
+
+        }
+        // Add the collection resource to map table
+        ResourceInformation resourceInfo = new ResourceInformation();
+        resourceInfo.resourceHandle = resourceHandle;
+        collectionList.put(uri, resourceInfo);
+        Log.i(LOG_TAG, "size of collectionList : " + collectionList.size());
+    }
+
+    private void deleteResources() {
+        Log.i(LOG_TAG, "deleteResources: enter");
+        try {
+            // unregister all resources
+            for (ResourceInformation resource : resourceList.values()) {
+                if (null != resource.resourceHandle) {
+                    if (resource.resource.getUri().equalsIgnoreCase(
+                            CONFIGURATION_RESOURCE_URI)) {
+                        ResourceInformation collectionResource = collectionList
+                                .get(CONFIGURATION_COLLECTION_RESOURCE_URI);
+                        if (null != collectionResource
+                                && null != collectionResource.resourceHandle) {
+                            OcPlatform
+                                    .unregisterResource(resource.resourceHandle);
+                            Log.i(LOG_TAG, "unregistered resource"
+                                    + CONFIGURATION_COLLECTION_RESOURCE_URI);
+
+                        }
+                    } else if (resource.resource.getUri().equalsIgnoreCase(
+                            DIAGNOSTIC_RESOURCE_URI)) {
+                        ResourceInformation diagnosticResource = collectionList
+                                .get(DIAGNOSTIC_COLLECTION_RESOURCE_URI);
+                        if (null != diagnosticResource
+                                && null != diagnosticResource.resourceHandle) {
+                            OcPlatform
+                                    .unregisterResource(resource.resourceHandle);
+                            Log.i(LOG_TAG, "unregistered resource"
+                                    + CONFIGURATION_COLLECTION_RESOURCE_URI);
+                        }
+                    } else if (resource.resource.getUri().equalsIgnoreCase(
+                            FACTORYSET_RESOURCE_URI)) {
+                        ResourceInformation factorysetResource = collectionList
+                                .get(FACTORYSET_COLLECTION_RESOURCE_URI);
+                        if (null != factorysetResource
+                                && null != factorysetResource.resourceHandle) {
+                            OcPlatform
+                                    .unregisterResource(resource.resourceHandle);
+                            Log.i(LOG_TAG, "unregistered resource"
+                                    + CONFIGURATION_COLLECTION_RESOURCE_URI);
+
+                        }
+                    }
+                }
+            }
+
+            // delete all the groups
+            thingsManager.deleteGroup(CONFIGURATION_COLLECTION_RESOURCE_TYPE);
+            thingsManager.deleteGroup(DIAGNOSTIC_COLLECTION_RESOURCE_TYPE);
+            thingsManager.deleteGroup(FACTORYSET_COLLECTION_RESOURCE_TYPE);
+        } catch (OcException e) {
+            Log.e(LOG_TAG, "OcException occured! " + e.toString());
+        }
+    }
+}
diff --git a/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ConfigurationListener.java b/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/ConfigurationListener.java
new file mode 100644 (file)
index 0000000..935eb4f
--- /dev/null
@@ -0,0 +1,59 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.tm.sample;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.tm.IConfigurationListener;
+
+import android.util.Log;
+
+/*
+ * For receiving configuration APIs callback : Update and Get
+ */
+public class ConfigurationListener implements IConfigurationListener {
+
+    private final String LOG_TAG = this.getClass().getSimpleName();
+
+    @Override
+    public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onBootStrapCallback");
+    }
+
+    @Override
+    public void onUpdateConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onUpdateConfigurationsCallback");
+
+    }
+
+    @Override
+    public void onGetConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onGetConfigurationsCallback");
+
+    }
+
+}
diff --git a/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/DiagnosticListener.java b/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/DiagnosticListener.java
new file mode 100644 (file)
index 0000000..31132d8
--- /dev/null
@@ -0,0 +1,51 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.tm.sample;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.service.tm.IDiagnosticsListener;
+
+import android.util.Log;
+
+/**
+ * For receiving Diagnostic APIs callback : BootStrap,Reboot & FactoryReset
+ */
+public class DiagnosticListener implements IDiagnosticsListener {
+
+    private final String LOG_TAG = this.getClass().getSimpleName();
+
+    @Override
+    public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onRebootCallback");
+
+    }
+
+    @Override
+    public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "Got Callback : onFactoryResetCallback");
+
+    }
+
+}
diff --git a/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/GroupApiActivity.java b/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/GroupApiActivity.java
new file mode 100644 (file)
index 0000000..02a3c5f
--- /dev/null
@@ -0,0 +1,253 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.tm.sample;
+
+import java.util.ArrayList;
+import java.util.Calendar;
+
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.DatePicker;
+import android.widget.DatePicker.OnDateChangedListener;
+import android.widget.EditText;
+import android.widget.ListView;
+import android.widget.TimePicker;
+import android.widget.TimePicker.OnTimeChangedListener;
+import android.widget.Toast;
+
+/*
+ * Activity for handling user's selection on UI for GroupApis.
+ * & for updating UI.
+ */
+public class GroupApiActivity extends Activity {
+
+    private ListView                list;
+    private Button                  findGroup;
+    private ArrayAdapter<String>    groupApis;
+    private ArrayList<String>       groupApisList;
+    private static GroupApiActivity groupApiActivityObj;
+    private GroupClient             groupClientObj;
+    private static Handler          mHandler;
+
+    private static EditText         logs;
+    private static String           logMessage;
+
+    // For Scheduled ActionSet
+    public static Context           mcontext;
+    public static Calendar          scheduleTime;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.groupapis);
+
+        groupApiActivityObj = this;
+        mcontext = this;
+
+        groupClientObj = new GroupClient();
+        groupApisList = new ArrayList<String>();
+        list = (ListView) findViewById(R.id.groupaApiList);
+        findGroup = (Button) findViewById(R.id.button1);
+        logs = (EditText) findViewById(R.id.EditText);
+
+        // adding the item to list that will be displayed on the UI.
+        groupApisList.add("1. Create ActionSet (ALLBULBON & ALLBULBOFF)");
+        groupApisList.add("2. Execute ActionSet (ALLBULBON)");
+        groupApisList.add("3. Execute ActionSet (AllBULBOFF)");
+
+        // Recursive GroupAction
+        groupApisList.add("4. Create ActionSet (Recursive_ALLBULBON)");
+        groupApisList.add("      4.1 Execute ActionSet");
+        groupApisList.add("      4.2 Cancel ActionSet");
+
+        // scheduled GroupAction
+        groupApisList.add("5. Create ActionSet (Scheduled_ALLBULBOFF)");
+        groupApisList.add("      5.1 Execute ActionSet");
+        groupApisList.add("      5.2 Cancel ActionSet");
+
+        groupApisList.add("6. Get ActionSet(ALLBULBOFF)");
+        groupApisList.add("7. Delete ActionSet(ALLBULBOFF)");
+        groupApisList.add("8. Find BookMark to Observe");
+
+        // handler for updating the UI i.e. MessageLog (TextBox) & ListView
+        mHandler = new Handler() {
+            @Override
+            public void handleMessage(Message msg) {
+                switch (msg.what) {
+                    case 0:
+                        groupApis = new ArrayAdapter<String>(
+                                groupApiActivityObj,
+                                android.R.layout.simple_list_item_1,
+                                groupApisList);
+                        list.setAdapter(groupApis);
+                        list.bringToFront();
+                        break;
+                    case 1:
+                        logs.setText("");
+                        logs.setText(logMessage);
+                }
+            }
+        };
+        setHandler(mHandler);
+
+        // find group Button Listener
+        findGroup.setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                groupClientObj.findGroup();
+            }
+        });
+
+        // Listener for item clicked by the user on the UI
+        list.setOnItemClickListener(new OnItemClickListener() {
+            @Override
+            public void onItemClick(AdapterView<?> parent, View view,
+                    int position, long id) {
+                if (position == 0) {
+                    groupClientObj.createActionSetBulbOn();
+                    groupClientObj.createActionSetBulbOff();
+                } else if (position == 1) {
+                    groupClientObj.executeActionSetBulbOn(0);
+                } else if (position == 2) {
+                    groupClientObj.executeActionSetBulbOff(0);
+                } else if (position == 3) {
+                    groupClientObj.createRecursiveActionSetBulbOn();
+                } else if (position == 4) {
+                    groupClientObj.executeRecursiveActionSetBulbOn(0);
+                } else if (position == 5) {
+                    groupClientObj.cancelRecursiveActionSetBulbOn();
+                } else if (position == 6) {
+                    showDateAndTimeDialog();
+                } else if (position == 7) {
+                    groupClientObj.executeScheduledActionSetBulbOff(0);
+                } else if (position == 8) {
+                    groupClientObj.cancelScheduledActionSetBulbOff();
+                } else if (position == 9) {
+                    groupClientObj.getActionSetBulbOff();
+                } else if (position == 10) {
+                    groupClientObj.deleteActionSetBulbOff();
+                } else if (position == 11) {
+                    groupClientObj.findBookMarkResources();
+                }
+            }
+        });
+
+        // creating group and find light resources
+        groupClientObj.createGroup();
+        groupClientObj.findLightResources();
+    }
+
+    public void showDateAndTimeDialog() {
+        // for scheduled actionSet
+        scheduleTime = Calendar.getInstance();
+
+        final Dialog dialog = new Dialog(mcontext);
+        dialog.setContentView(R.layout.custom_dialog);
+        dialog.setTitle("Choose date and time for Secheduling");
+
+        TimePicker tp = (TimePicker) dialog.findViewById(R.id.timePicker1);
+        DatePicker dp = (DatePicker) dialog.findViewById(R.id.datePicker1);
+        Button ok = (Button) dialog.findViewById(R.id.ok);
+        Button cancel = (Button) dialog.findViewById(R.id.cancel);
+
+        dialog.setCancelable(false);
+        dialog.show();
+        tp.setOnTimeChangedListener(new OnTimeChangedListener() {
+            @Override
+            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
+                scheduleTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
+                scheduleTime.set(Calendar.MINUTE, minute);
+            }
+        });
+        dp.init(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(),
+                new OnDateChangedListener() {
+                    @Override
+                    public void onDateChanged(DatePicker arg0, int arg1,
+                            int arg2, int arg3) {
+                        scheduleTime.set(arg1, arg2, arg3);
+                    }
+                });
+        ok.setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                dialog.dismiss();
+
+                // Calculate the time difference in delay
+                Calendar localTime = Calendar.getInstance();
+                if (scheduleTime.compareTo(localTime) != 1) {
+                    groupApiActivityObj
+                            .displayToastMessage("Invalid set time!");
+                    return;
+                }
+
+                long delay = scheduleTime.getTimeInMillis()
+                        - localTime.getTimeInMillis();
+                delay /= 1000;
+
+                groupClientObj.createScheduledActionSetBulbOff(delay);
+            }
+        });
+        cancel.setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                dialog.dismiss();
+            }
+        });
+    }
+
+    public static void setMessageLog(String message) {
+        logMessage = message;
+    }
+
+    @Override
+    public void onBackPressed() {
+        super.onBackPressed();
+        // unregister the resource and set callback listener to null
+        groupClientObj.leaveGroup();
+    }
+
+    // for update UI these functions will be called from GroupClient Class
+    public static GroupApiActivity getGroupApiActivityObj() {
+        return groupApiActivityObj;
+    }
+
+    public Handler getHandler() {
+        return mHandler;
+    }
+
+    public void setHandler(Handler mHandler) {
+        GroupApiActivity.mHandler = mHandler;
+    }
+
+    public void displayToastMessage(String message) {
+        Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
+        toast.show();
+    }
+}
diff --git a/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/GroupClient.java b/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/GroupClient.java
new file mode 100644 (file)
index 0000000..093dfac
--- /dev/null
@@ -0,0 +1,746 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.tm.sample;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResource.OnObserveListener;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.service.tm.Action;
+import org.iotivity.service.tm.ActionSet;
+import org.iotivity.service.tm.Capability;
+import org.iotivity.service.tm.IFindCandidateResourceListener;
+import org.iotivity.service.tm.IFindGroupListener;
+import org.iotivity.service.tm.OCStackResult;
+import org.iotivity.service.tm.ThingsManager;
+import org.iotivity.service.tm.Time.ActionSetType;
+
+import android.os.Message;
+import android.util.Log;
+
+/**
+ * For calling the group APIs as per user selection on UI and for updating the
+ * UI
+ */
+public class GroupClient {
+
+    private static final String     LOG_TAG             = "GroupClient";
+    private static Message          msg;
+    public String                   logMessage;
+
+    private final String groupResourceType = "b.collection";
+
+    private final ThingsManager     thingsManagerObj;
+    private final ActionListener    actionListener;
+    private final ObserveListener   observeListener;
+    private OcResource              groupResource;
+    private OcResourceHandle        groupResourceHandle;
+    private OcResourceHandle        foundLightHandle;
+    private static GroupApiActivity groupApiActivityObj = null;
+    public static Vector<String>    lights              = new Vector<String>();
+    public static Vector<String>    bookmarks           = new Vector<String>();
+
+    /**
+     * Listener for receiving observe notifications.
+     */
+    private class ObserveListener implements OnObserveListener {
+        @Override
+        public void onObserveCompleted(List<OcHeaderOption> headerOptionList,
+                OcRepresentation ocRepresentation, int sequenceNumber) {
+            Log.i(LOG_TAG, "onObserveCompleted invoked");
+            if (0 == ocRepresentation.getValueInt("level")) {
+                createActionSetBulbOn();
+                executeActionSetBulbOn(0);
+            } else if (5 == ocRepresentation.getValueInt("level")) {
+                createActionSetBulbOff();
+                executeActionSetBulbOff(0);
+            }
+        }
+
+        @Override
+        public void onObserveFailed(Throwable arg0) {
+        }
+    }
+
+    /**
+     * Listener for receiving groups discovered in network.
+     */
+    private class FindGroupListener implements IFindGroupListener {
+        @Override
+        public void onGroupFindCallback(OcResource resource) {
+            Log.i(LOG_TAG, "onGroupFindCallback invoked");
+            if (resource != null) {
+                String uri = resource.getUri();
+                if (uri.equals("/b/collection") == true) {
+                    String hostAddress = resource.getHost();
+                    Log.d("URI: onGroupFindCallback", uri);
+                    Log.d("HOST: onGroupFindCallback", hostAddress);
+
+                    groupResource = resource;
+                    Message msg = Message.obtain();
+                    msg.what = 0;
+                    groupApiActivityObj.getHandler().sendMessage(msg);
+
+                    logMessage = "onGroupFind" + "\n";
+                    logMessage = logMessage + "URI : " + uri + "\n";
+                    logMessage = logMessage + "Host :" + hostAddress;
+                    GroupApiActivity.setMessageLog(logMessage);
+                    msg = Message.obtain();
+                    msg.what = 1;
+                    groupApiActivityObj.getHandler().sendMessage(msg);
+                } else {
+                    Log.d("onGroupFindCallback URI : ", uri);
+                }
+            } else {
+                Log.i(LOG_TAG, "Resource is NULL");
+            }
+        }
+    };
+
+    /**
+     * Listener for receiving Light resource and Observe resources discovered in
+     * network.
+     */
+    private class FindCadidateResourceListener implements
+            IFindCandidateResourceListener {
+        @Override
+        public void onResourceCallback(Vector<OcResource> resources) {
+            Log.i(LOG_TAG, "onResourceCallback invoked");
+
+            if (resources != null) {
+                for (int i = 0; i < resources.size(); i++) {
+                    Log.d(LOG_TAG, "Resource information");
+                    OcResource ocResource = resources.get(i);
+                    String resourceURI = ocResource.getUri();
+                    String hostAddress = ocResource.getHost();
+
+                    logMessage = "API RESULT : " + "OC_STACK_OK" + "\n";
+                    logMessage = logMessage + "URI: " + resourceURI + "\n";
+                    logMessage = logMessage + "Host:" + hostAddress;
+                    GroupApiActivity.setMessageLog(logMessage);
+                    msg = Message.obtain();
+                    msg.what = 1;
+                    groupApiActivityObj.getHandler().sendMessage(msg);
+
+                    if (resourceURI.equals("/a/light") == true) {
+                        if (lights.contains((hostAddress + resourceURI)) == false) {
+                            lights.add((hostAddress + resourceURI));
+                            if (groupApiActivityObj != null) {
+
+                                logMessage = "API RESULT : " + "OC_STACK_OK"
+                                        + "\n";
+                                logMessage = logMessage + "URI: " + resourceURI
+                                        + "\n";
+                                logMessage = logMessage + "Host:" + hostAddress;
+                                GroupApiActivity.setMessageLog(logMessage);
+                                msg = Message.obtain();
+                                msg.what = 1;
+                                groupApiActivityObj.getHandler().sendMessage(
+                                        msg);
+                                try {
+                                    foundLightHandle = thingsManagerObj
+                                            .bindResourceToGroup(ocResource,
+                                                    groupResourceHandle);
+
+                                } catch (OcException e) {
+                                    Log.i(LOG_TAG,
+                                            "bindResourceToGroup Exception!");
+                                }
+                            }
+                        } else {
+                            Log.i(LOG_TAG, "Resource is already registered!");
+                        }
+                    } else if (resourceURI.equalsIgnoreCase("/core/bookmark")) {
+                        if (bookmarks.contains((hostAddress + resourceURI)) == false) {
+                            bookmarks.add((hostAddress + resourceURI));
+                            if (groupApiActivityObj != null) {
+                                logMessage = "API RESULT : " + "OC_STACK_OK"
+                                        + "\n";
+                                logMessage = logMessage + "URI: " + resourceURI
+                                        + "\n";
+                                logMessage = logMessage + "Host:" + hostAddress;
+                                GroupApiActivity.setMessageLog(logMessage);
+                                msg = Message.obtain();
+                                msg.what = 1;
+                                groupApiActivityObj.getHandler().sendMessage(
+                                        msg);
+
+                            }
+                            observe(ocResource);
+                        }
+                    }
+                }
+            }
+        }
+    };
+
+    private final FindCadidateResourceListener findCandidateResourceListener;
+    private final FindGroupListener            findGroupListener;
+
+    public GroupClient() {
+        thingsManagerObj = new ThingsManager();
+        findGroupListener = new FindGroupListener();
+        actionListener = new ActionListener();
+        observeListener = new ObserveListener();
+        findCandidateResourceListener = new FindCadidateResourceListener();
+
+        thingsManagerObj.setGroupListener(findGroupListener);
+        thingsManagerObj
+                .setFindCandidateResourceListener(findCandidateResourceListener);
+        thingsManagerObj.setActionListener(actionListener);
+
+        groupApiActivityObj = GroupApiActivity.getGroupApiActivityObj();
+    }
+
+    /**
+     * This method creates group of the type "b.collection" handling light
+     * resources.
+     */
+    public void createGroup() {
+        Map<String, OcResourceHandle> groupList = new HashMap<String, OcResourceHandle>();
+
+        // creating group of type b.collection
+        OCStackResult result = thingsManagerObj.createGroup(groupResourceType);
+        if ((OCStackResult.OC_STACK_OK != result)) {
+            Log.e(LOG_TAG, "createGroup returned error: " + result.name());
+            return;
+        } else {
+            Log.e(LOG_TAG, "createGroup success: " + result.name());
+        }
+
+        // getting the Created group Handle
+        groupList = thingsManagerObj.getGroupList();
+        if (groupList.containsKey(groupResourceType)) {
+            groupResourceHandle = groupList.get(groupResourceType);
+        } else {
+            Log.e(LOG_TAG, "group does not contain groupResourceType: "
+                    + result.name());
+        }
+    }
+
+    /**
+     * This method finds the group of type "b.collection".
+     */
+    public void findGroup() {
+        Log.d(LOG_TAG, "finding group");
+
+        Vector<String> resourceTypes = new Vector<String>();
+        resourceTypes.add(groupResourceType);
+        OCStackResult result = thingsManagerObj.findGroup(resourceTypes);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "findGroup returned error: " + result.name());
+            return;
+        }
+
+        logMessage = "API RESULT : " + result.toString();
+        GroupApiActivity.setMessageLog(logMessage);
+        logMessage = "";
+        if (groupApiActivityObj != null) {
+            msg = Message.obtain();
+            msg.what = 1;
+            groupApiActivityObj.getHandler().sendMessage(msg);
+        }
+    }
+
+    /**
+     * This method finds the light resources of type "core.light".
+     */
+    public void findLightResources() {
+        Log.d(LOG_TAG, "finding light resources");
+
+        Vector<String> types = new Vector<String>();
+        types.add("core.light");
+        OCStackResult result = thingsManagerObj
+                .findCandidateResources(types, 5);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG,
+                    "findCandidateResources returned error: " + result.name());
+        }
+    }
+
+    /**
+     * This method finds the bookmark resources of type "core.bookmark".
+     */
+    public void findBookMarkResources() {
+        Log.d(LOG_TAG, "finding bookmark resources");
+
+        Vector<String> types = new Vector<String>();
+        types.add("core.bookmark");
+        OCStackResult result = thingsManagerObj
+                .findCandidateResources(types, 5);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG,
+                    "findCandidateResources returned error: " + result.name());
+        }
+    }
+
+    /**
+     * This method creates the action set for bulb on action.
+     */
+    public void createActionSetBulbOn() {
+        Log.i(LOG_TAG, "creating action set for bulb on action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        ActionSet actionSet = new ActionSet();
+        actionSet.actionsetName = "AllBulbOn";
+
+        // Create actions list
+        for (int i = 0; i < lights.size(); i++) {
+            Action action = new Action();
+            action.target = lights.get(i);
+
+            Capability capability = new Capability();
+            capability.capability = "power";
+            capability.status = "on";
+
+            action.listOfCapability.add(capability);
+            actionSet.listOfAction.add(action);
+        }
+
+        try {
+            OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+                    actionSet);
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+            return;
+        }
+    }
+
+    /**
+     * This method creates the action set for bulb off action.
+     */
+    public void createActionSetBulbOff() {
+        Log.i(LOG_TAG, "creating action set for bulb off action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        ActionSet actionSet = new ActionSet();
+        actionSet.actionsetName = "AllBulbOff";
+
+        // Create actions list
+        for (int i = 0; i < lights.size(); i++) {
+            Action action = new Action();
+            action.target = lights.get(i);
+
+            Capability capability = new Capability();
+            capability.capability = "power";
+            capability.status = "off";
+
+            action.listOfCapability.add(capability);
+            actionSet.listOfAction.add(action);
+        }
+
+        try {
+            OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+                    actionSet);
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+            return;
+        }
+    }
+
+    /**
+     * This method creates the recursive action set for bulb on action.
+     */
+    public void createRecursiveActionSetBulbOn() {
+        Log.i(LOG_TAG, "creating recursive action set for bulb on action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        ActionSet actionSet = new ActionSet();
+        actionSet.actionsetName = "AllBulbOnRecursive";
+        actionSet.setType(ActionSetType.RECURSIVE);
+        actionSet.mYear = 0;
+        actionSet.mMonth = 0;
+        actionSet.mDay = 0;
+        actionSet.mHour = 0;
+        actionSet.mMin = 0;
+        actionSet.mSec = 5;
+        actionSet.setDelay(actionSet.getSecAbsTime());
+
+        // Create actions list
+        for (int i = 0; i < lights.size(); i++) {
+            Action action = new Action();
+            action.target = lights.get(i);
+
+            Capability capability = new Capability();
+            capability.capability = "power";
+            capability.status = "on";
+
+            action.listOfCapability.add(capability);
+            actionSet.listOfAction.add(action);
+        }
+
+        try {
+            OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+                    actionSet);
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+            return;
+        }
+    }
+
+    /**
+     * This method creates the scheduled action set for bulb off action.
+     */
+    public void createScheduledActionSetBulbOff(long delay) {
+        Log.i(LOG_TAG, "creating scheduled action set for bulb off action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        ActionSet actionSet = new ActionSet();
+        actionSet.actionsetName = "AllBulbOffScheduled";
+        actionSet.setType(ActionSetType.SCHEDULED);
+        actionSet.setDelay(delay);
+        Log.i(LOG_TAG, "Set the delay of " + delay + " seconds");
+
+        // Create actions list
+        for (int i = 0; i < lights.size(); i++) {
+            Action action = new Action();
+            action.target = lights.get(i);
+
+            Capability capability = new Capability();
+            capability.capability = "power";
+            capability.status = "off";
+
+            action.listOfCapability.add(capability);
+            actionSet.listOfAction.add(action);
+        }
+
+        try {
+            OCStackResult result = thingsManagerObj.addActionSet(groupResource,
+                    actionSet);
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG, "addActionSet returned error: " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+            return;
+        }
+    }
+
+    /**
+     * This method is for executing the action Set "AllBulbOn".
+     */
+    public void executeActionSetBulbOn(long delay) {
+        Log.i(LOG_TAG, "executing the action set of bulb on action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        executeActionSet("AllBulbOn", delay);
+    }
+
+    /**
+     * This method is for executing the action Set "AllBulbOff".
+     */
+    public void executeActionSetBulbOff(long delay) {
+        Log.i(LOG_TAG, "executing the action set of bulb off action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        executeActionSet("AllBulbOff", delay);
+    }
+
+    /**
+     * This method is for executing the recursive action Set
+     * "AllBulbOnRecursive".
+     */
+    public void executeRecursiveActionSetBulbOn(long delay) {
+        Log.i(LOG_TAG, "executing the recursive action set of bulb on action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        executeActionSet("AllBulbOnRecursive", delay);
+    }
+
+    /**
+     * This method is for executing the schedule action Set
+     * "AllBulbOffScheduled".
+     */
+    public void executeScheduledActionSetBulbOff(long delay) {
+        Log.i(LOG_TAG, "executing the schedule action set of bulb off action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        executeActionSet("AllBulbOffScheduled", delay);
+    }
+
+    /**
+     * This method is for canceling the action Set "AllBulbOn".
+     */
+    public void cancelActionSetBulbOn() {
+        Log.i(LOG_TAG, "cancelling the action set of bulb on action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        cancelActionSet("AllBulbOn");
+    }
+
+    /**
+     * This method is for canceling the action Set "AllBulbOff".
+     */
+    public void cancelActionSetBulbOff() {
+        Log.i(LOG_TAG, "cancelling the action set of bulb off action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        cancelActionSet("AllBulbOff");
+    }
+
+    /**
+     * This method is for canceling the recursive action Set
+     * "AllBulbOnRecursive".
+     */
+    public void cancelRecursiveActionSetBulbOn() {
+        Log.i(LOG_TAG, "cancelling the recursive action set of bulb on action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        cancelActionSet("AllBulbOnRecursive");
+    }
+
+    /**
+     * This method is for canceling the scheduled action Set
+     * "AllBulbOffScheduled".
+     */
+    public void cancelScheduledActionSetBulbOff() {
+        Log.i(LOG_TAG, "cancelling the scheduled action set of bulb off action");
+
+        if (lights.size() == 0) {
+            groupApiActivityObj
+                    .displayToastMessage("No Light server found in network!");
+            return;
+        }
+
+        cancelActionSet("AllBulbOffScheduled");
+    }
+
+    /**
+     * This method is for getting the action Set "AllBulbOn".
+     */
+    public void getActionSetBulbOn() {
+        Log.i(LOG_TAG, "getting the action set of bulb on action");
+
+        try {
+            OCStackResult result = thingsManagerObj.getActionSet(groupResource,
+                    "AllBulbOn");
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG,
+                        "getActionSetOn returned error: " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * This method is for getting the action Set "AllBulbOff".
+     */
+    public void getActionSetBulbOff() {
+        Log.i(LOG_TAG, "getting the action set of bulb off action");
+
+        try {
+            OCStackResult result = thingsManagerObj.getActionSet(groupResource,
+                    "AllBulbOff");
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG,
+                        "getActionSetOn returned error: " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * This method is for deleting the action Set "AllBulbOn".
+     */
+    public void deleteActionSetBulbOn() {
+        Log.i(LOG_TAG, "deleting the action set of bulb on action");
+
+        try {
+            OCStackResult result = thingsManagerObj.deleteActionSet(
+                    groupResource, "AllBulbOn");
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG,
+                        "deleteActionSet returned error : " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * This method is for deleting the action Set "AllBulbOff".
+     */
+    public void deleteActionSetBulbOff() {
+        Log.i(LOG_TAG, "deleting the action set of bulb off action");
+
+        try {
+            OCStackResult result = thingsManagerObj.deleteActionSet(
+                    groupResource, "AllBulbOff");
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG,
+                        "deleteActionSet returned error : " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * This method is for observing the bulb on/off status.
+     */
+    public void observe(OcResource resource) {
+        Log.i(LOG_TAG, "Registering observer for bookmark resources status");
+
+        Map<String, String> queryMap = new HashMap<String, String>();
+        try {
+            resource.observe(ObserveType.OBSERVE, queryMap, observeListener);
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * This method is for unbinding and unregister all the found resources and
+     * groups.
+     */
+    public void leaveGroup() {
+        thingsManagerObj.setGroupListener(null);
+        thingsManagerObj.setFindCandidateResourceListener(null);
+        thingsManagerObj.setActionListener(null);
+
+        if (null != foundLightHandle) {
+            try {
+                OcPlatform.unregisterResource(foundLightHandle);
+            } catch (OcException e) {
+                e.printStackTrace();
+                Log.i(LOG_TAG, "Resource Unregister Exception");
+            }
+        } else {
+            Log.i(LOG_TAG, "foundLightHandle is NULL");
+        }
+        if (null != groupResourceHandle) {
+
+            thingsManagerObj.deleteGroup(groupResourceType);
+        } else {
+            Log.i(LOG_TAG, "groupResourceHandle is NULL");
+        }
+    }
+
+    private void executeActionSet(String actonSetName, long delay) {
+        try {
+            OCStackResult result = thingsManagerObj.executeActionSet(
+                    groupResource, actonSetName, delay);
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG,
+                        "executeActionSet retuned error : " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+    }
+
+    private void cancelActionSet(String actionSetName) {
+        try {
+            OCStackResult result = thingsManagerObj.cancelActionSet(
+                    groupResource, actionSetName);
+            if (OCStackResult.OC_STACK_OK != result) {
+                Log.e(LOG_TAG,
+                        "cancelActionSet returned error : " + result.name());
+                return;
+            }
+        } catch (OcException e) {
+            e.printStackTrace();
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/MainActivity.java b/service/things-manager/sampleapp/android/Sample/src/com/tm/sample/MainActivity.java
new file mode 100644 (file)
index 0000000..2482055
--- /dev/null
@@ -0,0 +1,144 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.tm.sample;
+
+import java.util.ArrayList;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.service.tm.ThingsManager;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.content.Intent;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+
+/**
+ * Starting Activity of the application responsible for configuring the
+ * OcPlatform and redirecting to other activity according to user's selection on
+ * UI.
+ */
+public class MainActivity extends Activity {
+
+    private static MainActivity  activityObj;
+    private ArrayAdapter<String> apis;
+    private ArrayList<String>    apisList;
+    private ListView             list;
+    private final String         LOG_TAG          = this.getClass()
+                                                          .getSimpleName();
+    public ThingsManager         thingsManagerObj = new ThingsManager();
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+        activityObj = this;
+
+        list = (ListView) findViewById(R.id.list);
+        apisList = new ArrayList<String>();
+
+        // adding the item to list that will be displayed on the UI.
+        apisList.add("GROUP APIS");
+        apisList.add("CONFIGURATION APIS");
+        apis = new ArrayAdapter<String>(activityObj,
+                android.R.layout.simple_list_item_1, apisList);
+        list.setAdapter(apis);
+
+        // handling user's selection on the UI
+        list.setOnItemClickListener(new OnItemClickListener() {
+            @Override
+            public void onItemClick(AdapterView<?> parent, View view,
+                    int position, long id) {
+
+                if (position == 0) {
+                    Intent intent = new Intent(activityObj,
+                            GroupApiActivity.class);
+                    startActivity(intent);
+                } else if (position == 1) {
+                    Intent intent = new Intent(activityObj,
+                            ConfigurationApiActivity.class);
+                    startActivity(intent);
+                }
+            }
+        });
+
+        // calling the method to check the Wi-fi connectivity and configuring
+        // the OcPlatform
+        configurePlatform();
+    }
+
+    @Override
+    public void onBackPressed() {
+        apisList.clear();
+        super.onBackPressed();
+    }
+
+    private void configurePlatform() {
+        // local Variables
+        ConnectivityManager connManager;
+        NetworkInfo wifi;
+        AlertDialog dialog;
+        PlatformConfig platformConfigObj;
+
+        // Check the wifi connectivity
+        connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
+        wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+        if (false == wifi.isConnected()) {
+            // WiFi is not connected close the application
+            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
+            dialogBuilder.setTitle("Error");
+            dialogBuilder
+                    .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...");
+            dialogBuilder.setCancelable(false);
+            dialogBuilder.setPositiveButton("OK", new OnClickListener() {
+                @Override
+                public void onClick(DialogInterface dialog, int which) {
+                    // Closing the application
+                    activityObj.finish();
+                }
+            });
+
+            dialog = dialogBuilder.create();
+            dialog.show();
+            return;
+        }
+        // If wifi is connected calling the configure method for configuring the
+        // OcPlatform
+        platformConfigObj = new PlatformConfig(getApplicationContext(),ServiceType.IN_PROC,
+                ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+
+        Log.i(LOG_TAG, "Before Calling Configure of ocPlatform");
+        OcPlatform.Configure(platformConfigObj);
+        Log.i(LOG_TAG, "Configuration done Successfully");
+    }
+}
diff --git a/service/things-manager/sampleapp/android/con-server/.classpath b/service/things-manager/sampleapp/android/con-server/.classpath
new file mode 100644 (file)
index 0000000..7bc01d9
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="src" path="gen"/>
+       <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+       <classpathentry kind="output" path="bin/classes"/>
+</classpath>
diff --git a/service/things-manager/sampleapp/android/con-server/.project b/service/things-manager/sampleapp/android/con-server/.project
new file mode 100644 (file)
index 0000000..06d9ae7
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>con-server</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+       </natures>
+</projectDescription>
diff --git a/service/things-manager/sampleapp/android/con-server/AndroidManifest.xml b/service/things-manager/sampleapp/android/con-server/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..4d431a9
--- /dev/null
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.con_server"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="21" />
+        <uses-permission android:name="android.permission.INTERNET" />
+        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name="com.example.con_server.MainActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/service/things-manager/sampleapp/android/con-server/ic_launcher-web.png b/service/things-manager/sampleapp/android/con-server/ic_launcher-web.png
new file mode 100644 (file)
index 0000000..a18cbb4
Binary files /dev/null and b/service/things-manager/sampleapp/android/con-server/ic_launcher-web.png differ
diff --git a/service/things-manager/sampleapp/android/con-server/project.properties b/service/things-manager/sampleapp/android/con-server/project.properties
new file mode 100644 (file)
index 0000000..fb6cc13
--- /dev/null
@@ -0,0 +1,16 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-20
+
+android.library.reference.1=../../../sdk/java
diff --git a/service/things-manager/sampleapp/android/con-server/res/drawable-hdpi/ic_launcher.png b/service/things-manager/sampleapp/android/con-server/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/service/things-manager/sampleapp/android/con-server/res/drawable-hdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/con-server/res/drawable-mdpi/ic_launcher.png b/service/things-manager/sampleapp/android/con-server/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..6ae570b
Binary files /dev/null and b/service/things-manager/sampleapp/android/con-server/res/drawable-mdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/con-server/res/drawable-xhdpi/ic_launcher.png b/service/things-manager/sampleapp/android/con-server/res/drawable-xhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..d4fb7cd
Binary files /dev/null and b/service/things-manager/sampleapp/android/con-server/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/con-server/res/drawable-xxhdpi/ic_launcher.png b/service/things-manager/sampleapp/android/con-server/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..85a6081
Binary files /dev/null and b/service/things-manager/sampleapp/android/con-server/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/service/things-manager/sampleapp/android/con-server/res/layout/activity_main.xml b/service/things-manager/sampleapp/android/con-server/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..28cb336
--- /dev/null
@@ -0,0 +1,41 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    tools:context="com.example.con_server.MainActivity" >
+
+    
+    <Button
+        android:id="@+id/button1"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_alignParentTop="true"
+        android:layout_centerHorizontal="true"
+        android:text="doBootStrap" />
+
+    <Button
+        android:id="@+id/button2"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/button1"
+        android:text="Create Configuration Resources" />
+
+    <EditText
+        android:id="@+id/EditText"
+        android:layout_width="fill_parent"
+        android:layout_height="300dp"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/button2"
+        android:layout_marginTop="15dp"
+        android:ems="10" 
+        android:editable="false">
+
+        <requestFocus />
+    </EditText>
+
+</RelativeLayout>
diff --git a/service/things-manager/sampleapp/android/con-server/res/menu/main.xml b/service/things-manager/sampleapp/android/con-server/res/menu/main.xml
new file mode 100644 (file)
index 0000000..d227c49
--- /dev/null
@@ -0,0 +1,9 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+    <item
+        android:id="@+id/action_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never"
+        android:title="@string/action_settings"/>
+
+</menu>
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/android/con-server/res/values-v11/styles.xml b/service/things-manager/sampleapp/android/con-server/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..5b212de
--- /dev/null
@@ -0,0 +1,6 @@
+<resources>
+
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+    </style>
+
+</resources>
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/android/con-server/res/values-v14/styles.xml b/service/things-manager/sampleapp/android/con-server/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..cca9f43
--- /dev/null
@@ -0,0 +1,9 @@
+<resources>
+
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+    </style>
+
+    <style name="AppTheme" parent="AppBaseTheme">
+    </style>
+
+</resources>
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/android/con-server/res/values-w820dp/dimens.xml b/service/things-manager/sampleapp/android/con-server/res/values-w820dp/dimens.xml
new file mode 100644 (file)
index 0000000..f3e7020
--- /dev/null
@@ -0,0 +1,10 @@
+<resources>
+
+    <!--
+         Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
+    -->
+    <dimen name="activity_horizontal_margin">64dp</dimen>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/con-server/res/values/dimens.xml b/service/things-manager/sampleapp/android/con-server/res/values/dimens.xml
new file mode 100644 (file)
index 0000000..55c1e59
--- /dev/null
@@ -0,0 +1,7 @@
+<resources>
+
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/con-server/res/values/strings.xml b/service/things-manager/sampleapp/android/con-server/res/values/strings.xml
new file mode 100644 (file)
index 0000000..eaf9a00
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="app_name">con-server</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="action_settings">Settings</string>
+
+</resources>
diff --git a/service/things-manager/sampleapp/android/con-server/res/values/styles.xml b/service/things-manager/sampleapp/android/con-server/res/values/styles.xml
new file mode 100644 (file)
index 0000000..2d2984d
--- /dev/null
@@ -0,0 +1,12 @@
+<resources>
+
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+
+    </style>
+
+</resources>
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/ConfigurationResource.java b/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/ConfigurationResource.java
new file mode 100644 (file)
index 0000000..69a1f41
--- /dev/null
@@ -0,0 +1,163 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.example.con_server;
+
+import java.util.EnumSet;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.ResourceProperty;
+
+import android.util.Log;
+
+//For creating/deleting the configuration Resource
+public class ConfigurationResource {
+    private final String       LOG_TAG                 = "[CON-SERVER]"
+                                                               + this.getClass()
+                                                                       .getSimpleName();
+    // Configuration resource members
+    protected String           configurationUri;
+    protected String           location;
+    protected String           systemTime;
+    protected String           currency;
+    protected String           region;
+    protected Vector<String>   configurationTypes      = new Vector<String>();
+    protected Vector<String>   configurationInterfaces = new Vector<String>();
+    protected OcRepresentation configurationRep        = new OcRepresentation();
+    protected OcResourceHandle configurationHandle;
+
+    // constructors
+    public ConfigurationResource() {
+        Log.i(LOG_TAG, "ConfigurationResource: enter");
+
+        location = ConfigurationDefaultValues.defaultLocation;
+        systemTime = ConfigurationDefaultValues.defaultSystemTime;
+        currency = ConfigurationDefaultValues.defaultCurrency;
+        region = ConfigurationDefaultValues.defaultRegion;
+
+        configurationUri = ConfigurationDefaultValues.ConURIPrefix;
+        configurationTypes
+                .add(ConfigurationDefaultValues.ConResourceTypePrefix);
+        configurationInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+
+        configurationRep.setValueString("loc", location);
+        configurationRep.setValueString("st", systemTime);
+        configurationRep.setValueString("c", currency);
+        configurationRep.setValueString("r", region);
+        configurationRep.setUri(configurationUri);
+        configurationRep.setResourceTypes(configurationTypes);
+        configurationRep.setResourceInterfaces(configurationInterfaces);
+    }
+
+    // For creating Configuration Resource
+    public void createResource(OcPlatform.EntityHandler listener)
+            throws OcException {
+        Log.i(LOG_TAG, "createResource(configuration): enter");
+        EnumSet<ResourceProperty> propertySet = EnumSet.of(
+                ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE);
+
+        // Register configuration resource
+        configurationHandle = OcPlatform.registerResource(configurationUri,
+                configurationTypes.elementAt(0),
+                configurationInterfaces.elementAt(0), listener, propertySet);
+
+        Log.i(LOG_TAG, "createResource(configuration): exit");
+    }
+
+    // Setters and Getters methods for Configuration resource
+    public void setConfigurationRepresentation(OcRepresentation rep) {
+        Log.i(LOG_TAG, "setConfigurationRepresentation: enter");
+
+        String loc;
+        String st;
+        String cur;
+        String reg;
+        loc = rep.getValueString("loc");
+        st = rep.getValueString("st");
+        cur = rep.getValueString("c");
+        reg = rep.getValueString("r");
+        if (!(loc.equalsIgnoreCase(""))) {
+            location = loc;
+            Log.i(LOG_TAG,
+                    "setConfigurationRepresentation: New value(location): "
+                            + location);
+        }
+        if (!(st.equalsIgnoreCase(""))) {
+            systemTime = st;
+            Log.i(LOG_TAG,
+                    "setConfigurationRepresentation: New value(system time): "
+                            + systemTime);
+        }
+        if (!(cur.equalsIgnoreCase(""))) {
+            currency = cur;
+            Log.i(LOG_TAG,
+                    "setConfigurationRepresentation: New value(currency): "
+                            + currency);
+        }
+        if (!(reg.equalsIgnoreCase(""))) {
+            region = reg;
+            Log.i(LOG_TAG,
+                    "setConfigurationRepresentation: New value(region): "
+                            + region);
+        }
+
+        Log.i(LOG_TAG, "setConfigurationRepresentation: exit");
+    }
+
+    public OcRepresentation getConfigurationRepresentation() {
+
+        configurationRep.setValueString("loc", location);
+        configurationRep.setValueString("st", systemTime);
+        configurationRep.setValueString("c", currency);
+        configurationRep.setValueString("r", region);
+        return configurationRep;
+    }
+
+    public String getUri() {
+        return configurationUri;
+    }
+
+    // For resetting the default values to configuration Resource
+    public void factoryReset() {
+
+        location = ConfigurationDefaultValues.defaultLocation;
+        systemTime = ConfigurationDefaultValues.defaultSystemTime;
+        currency = ConfigurationDefaultValues.defaultCurrency;
+        region = ConfigurationDefaultValues.defaultRegion;
+        Log.i(LOG_TAG, "ConfiguartionResource: factoryReset done");
+
+    }
+
+    // Deleting all the resources, that we have created using createResources()
+    public void deleteResource() {
+        try {
+            if (null != configurationHandle) {
+                // Unregister the Configuration resource
+                OcPlatform.unregisterResource(configurationHandle);
+            }
+
+        } catch (OcException e) {
+            Log.e(LOG_TAG, "OcException occured! " + e.toString());
+        }
+    }
+}
diff --git a/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/ConfigurationServer.java b/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/ConfigurationServer.java
new file mode 100644 (file)
index 0000000..671da02
--- /dev/null
@@ -0,0 +1,281 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.example.con_server;
+
+import java.util.EnumSet;
+import java.util.Vector;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.service.tm.IConfigurationListener;
+import org.iotivity.service.tm.IDiagnosticsListener;
+import org.iotivity.service.tm.OCStackResult;
+import org.iotivity.service.tm.ThingsManager;
+
+import android.os.Message;
+import android.util.Log;
+
+/*
+ * For Creating the Resources [configurtion, Diagnostic & FactoryRest]  &
+ * for Handling of the Client's Request
+ */
+public class ConfigurationServer implements IDiagnosticsListener,
+        IConfigurationListener, OcPlatform.EntityHandler {
+    private final String          LOG_TAG            = "[CON-SERVER]"
+                                                             + this.getClass()
+                                                                     .getSimpleName();
+    private ThingsManager         thingsmanager      = null;
+    private ConfigurationResource conResource        = null;
+    private DiagnosticsResource   diagResource       = null;
+    private FactorySetResource    factorySetResource = null;
+
+    // constructor
+    public ConfigurationServer() {
+        thingsmanager = new ThingsManager();
+        thingsmanager.setDiagnosticsListener(this);
+        thingsmanager.setConfigurationListener(this);
+    }
+
+    public void DoBootStrap() {
+        Log.i(LOG_TAG, "DoBootStrap: enter");
+
+        OCStackResult result = thingsmanager.doBootstrap();
+        if (OCStackResult.OC_STACK_ERROR == result) {
+            Log.e(LOG_TAG, "doBootStrap returned error: "
+                    + OCStackResult.OC_STACK_ERROR.name());
+        }
+        Log.i(LOG_TAG, "DoBootStrap: exit");
+    }
+
+    // Creating resources : configuration, diagnostics, factoryReset
+    public void CreateConfigurationResource() {
+        Log.i(LOG_TAG, "CreateConfigurationResource: enter");
+
+        try {
+            conResource = new ConfigurationResource();
+            conResource.createResource(this);
+
+            diagResource = new DiagnosticsResource();
+            diagResource.createResource(this);
+
+            factorySetResource = new FactorySetResource();
+            factorySetResource.createResource(this);
+        } catch (OcException e) {
+            Log.e(LOG_TAG, "OcException occured: " + e.toString());
+        }
+
+        Log.i(LOG_TAG, "CreateConfigurationResource: exit");
+
+        String message = "Resources Created Successfully(Server is Ready)";
+
+        Message msg = Message.obtain();
+        msg.what = 0;
+        MainActivity mainActivityObj = MainActivity.getMainActivityObject();
+        MainActivity.setmessage(message);
+        mainActivityObj.getmHandler().sendMessage(msg);
+
+    }
+
+    // For deleting all the resources
+    public void deleteResources() {
+        if (null != conResource)
+            conResource.deleteResource();
+        if (null != diagResource)
+            diagResource.deleteResource();
+        if (null != factorySetResource)
+            factorySetResource.deleteResource();
+    }
+
+    // Callback Function for doBootStrap
+    @Override
+    public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        String message;
+        Log.i(LOG_TAG, "onBootStrapCallback");
+
+        // setting the default values received from bootstrap Server
+
+        ConfigurationDefaultValues.defaultRegion = rep.getValueString("r");
+        ConfigurationDefaultValues.defaultSystemTime = rep.getValueString("st");
+        ConfigurationDefaultValues.defaultCurrency = rep.getValueString("c");
+        ConfigurationDefaultValues.defaultLocation = rep.getValueString("loc");
+
+        // forming the message to display on UI
+        message = "URI : " + rep.getUri() + "\n";
+        message = message + "Region : "
+                + ConfigurationDefaultValues.defaultRegion + "\n";
+        message = message + "System Time : "
+                + ConfigurationDefaultValues.defaultSystemTime + "\n";
+        message = message + "Currency : "
+                + ConfigurationDefaultValues.defaultCurrency + "\n";
+        message = message + "Location : "
+                + ConfigurationDefaultValues.defaultLocation + "\n";
+
+        Log.i(LOG_TAG, "Resource URI: " + rep.getUri());
+        Log.i(LOG_TAG, "Region: " + ConfigurationDefaultValues.defaultRegion);
+        Log.i(LOG_TAG, "System Time: "
+                + ConfigurationDefaultValues.defaultSystemTime);
+        Log.i(LOG_TAG, "Currency: "
+                + ConfigurationDefaultValues.defaultCurrency);
+        Log.i(LOG_TAG, "Location: "
+                + ConfigurationDefaultValues.defaultLocation);
+
+        // showing the formed message on the UI
+        Message msg = Message.obtain();
+        msg.what = 0;
+        MainActivity mainActivityObj = MainActivity.getMainActivityObject();
+        MainActivity.setmessage(message);
+        mainActivityObj.getmHandler().sendMessage(msg);
+    }
+
+    // Callback Function for Reboot
+    @Override
+    public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "onRebootCallback");
+    }
+
+    // Callback Function for FactoryReset
+    @Override
+    public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        Log.i(LOG_TAG, "onFactoryResetCallback");
+    }
+
+    // For Handling the Client's Request
+    @Override
+    public EntityHandlerResult handleEntity(OcResourceRequest request) {
+        Log.i(LOG_TAG, "handleEntity: enter");
+
+        EntityHandlerResult result = EntityHandlerResult.ERROR;
+        if (null == request) {
+            Log.e(LOG_TAG, "handleEntity: Invalid OcResourceRequest!");
+            return result;
+        }
+
+        RequestType requestType = request.getRequestType();
+        EnumSet<RequestHandlerFlag> requestHandlerFlag = request
+                .getRequestHandlerFlagSet();
+        Log.i(LOG_TAG, "prepareResponseForResource: request type: "
+                + requestType.name());
+        Log.i(LOG_TAG, "prepareResponseForResource: request for resource: "
+                + request.getResourceUri());
+
+        if (requestHandlerFlag.contains(RequestHandlerFlag.REQUEST)) {
+            if (RequestType.GET == requestType) {
+                sendResponse(request);
+            } else if (RequestType.PUT == requestType) {
+                OcRepresentation rep = request.getResourceRepresentation();
+                if (null == rep) {
+                    Log.e(LOG_TAG,
+                            "handleEntity: Invalid resource representation!");
+                    return result;
+                }
+
+                if (request.getResourceUri().equalsIgnoreCase(
+                        conResource.getUri())) {
+                    conResource.setConfigurationRepresentation(rep);
+                } else if (request.getResourceUri().equalsIgnoreCase(
+                        diagResource.getUri())) {
+
+                    String factorySetAtt = rep.getValueString("fr");
+                    if (factorySetAtt.equalsIgnoreCase("true")) {
+                        conResource.factoryReset();
+                    }
+                    diagResource.setDiagnosticsRepresentation(rep);
+                }
+                sendResponse(request);
+            }
+        }
+
+        Log.i(LOG_TAG, "handleEntity: exit");
+        return result;
+    }
+
+    // For sending response to the client
+    private void sendResponse(OcResourceRequest request) {
+        Log.i(LOG_TAG, "sendResponse: enter");
+
+        OcResourceResponse response = new OcResourceResponse();
+        OcRepresentation rep = null;
+
+        response.setRequestHandle(request.getRequestHandle());
+        response.setResourceHandle(request.getResourceHandle());
+
+        if (request.getResourceUri().equalsIgnoreCase(conResource.getUri())) {
+            rep = conResource.getConfigurationRepresentation();
+        } else if (request.getResourceUri().equalsIgnoreCase(
+                diagResource.getUri())) {
+            rep = diagResource.getDiagnosticsRepresentation();
+        }
+        response.setResourceRepresentation(rep, OcPlatform.DEFAULT_INTERFACE);
+        response.setErrorCode(200);
+
+        try {
+            OcPlatform.sendResponse(response);
+        } catch (OcException e) {
+            Log.e(LOG_TAG, "sendResponse: OcException occured: " + e.toString());
+        }
+        Log.i(LOG_TAG, "sendResponse: exit");
+    }
+
+    @Override
+    public void onUpdateConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void onGetConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue) {
+        // TODO Auto-generated method stub
+
+    }
+}
+
+// Default values for Resources
+class ConfigurationDefaultValues {
+
+    // configuration Resource default values
+    public static String defaultLocation        = new String();
+    public static String defaultRegion          = new String();
+    public static String defaultSystemTime      = new String();
+    public static String defaultCurrency        = new String();
+    public static String ConURIPrefix           = "/oic/con";
+    public static String ConResourceTypePrefix  = "oic.con";
+
+    // Diagnostics Resource default values
+    public static String diagURIPrefix          = "/oic/diag";
+    public static String diagResourceTypePrefix = "oic.diag";
+    public static String diagnosticsValue       = "false";
+    public static String defaultFactoryReset    = "false";
+    public static String defaultReboot          = "false";
+    public static String defaultStartCollection = "false";
+}
diff --git a/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/DiagnosticsResource.java b/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/DiagnosticsResource.java
new file mode 100644 (file)
index 0000000..2d1826b
--- /dev/null
@@ -0,0 +1,197 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.example.con_server;
+
+import java.util.EnumSet;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.ResourceProperty;
+
+import android.util.Log;
+
+//For creating/deleting the Diagnostics Resource
+public class DiagnosticsResource {
+    private final String     LOG_TAG               = "[CON-SERVER]"
+                                                           + this.getClass()
+                                                                   .getSimpleName();
+    // diagnostics members
+    private String           diagnosticsUri;
+    private String           factoryReset;
+    private String           reboot;
+    private String           startCollection;
+    private Vector<String>   diagnosticsTypes      = new Vector<String>();
+    private Vector<String>   diagnosticsInterfaces = new Vector<String>();
+    private OcResourceHandle diagnosticsHandle;
+    private OcRepresentation diagnosticsRep        = new OcRepresentation();
+
+    // constructor
+    public DiagnosticsResource() {
+        Log.i(LOG_TAG, "DiagnosticsCollection: enter");
+
+        factoryReset = ConfigurationDefaultValues.defaultFactoryReset;
+        reboot = ConfigurationDefaultValues.defaultReboot;
+        startCollection = ConfigurationDefaultValues.defaultStartCollection;
+
+        diagnosticsUri = ConfigurationDefaultValues.diagURIPrefix;
+        diagnosticsTypes.add(ConfigurationDefaultValues.diagResourceTypePrefix);
+        diagnosticsInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+        diagnosticsRep.setValueString("fr", factoryReset);
+        diagnosticsRep.setValueString("rb", reboot);
+        diagnosticsRep.setValueString("ssc", startCollection);
+        diagnosticsRep.setUri(diagnosticsUri);
+        diagnosticsRep.setResourceTypes(diagnosticsTypes);
+        diagnosticsRep.setResourceInterfaces(diagnosticsInterfaces);
+
+    }
+
+    // for creating Diagnostic Resource
+    public void createResource(OcPlatform.EntityHandler listener)
+            throws OcException {
+        Log.i(LOG_TAG, "createResource(Diagnostics): enter");
+        EnumSet<ResourceProperty> propertySet = EnumSet.of(
+                ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE);
+        if (null == listener) {
+            Log.i(LOG_TAG, "CallBack Should be binded");
+            return;
+        }
+
+        // Register diagnostic resource
+        diagnosticsHandle = OcPlatform.registerResource(diagnosticsUri,
+                diagnosticsTypes.get(0), diagnosticsInterfaces.get(0),
+                listener, propertySet);
+        if (null == diagnosticsHandle) {
+            Log.e(LOG_TAG, "registerResource failed!");
+            return;
+        }
+
+        Thread thread = new Thread() {
+            @Override
+            public void run() {
+                try {
+                    while (true) {
+                        // Put this thread for sleep for 1 sec.
+                        // Sleep value can be changed as per the developer
+                        // convenience.
+                        Thread.sleep(1000);
+                        if (reboot.equalsIgnoreCase("true")) {
+                            Log.i(LOG_TAG, "Reboot will be soon...");
+                            MainActivity mainActivityObj = MainActivity
+                                    .getMainActivityObject();
+                            if (null == mainActivityObj) {
+                                Log.e(LOG_TAG,
+                                        "Mainactivity object is invalid!");
+                                return;
+                            }
+                            try {
+                                mainActivityObj.runOnUiThread(new Runnable() {
+                                    @Override
+                                    public void run() {
+                                        try {
+                                            MainActivity.reboot();
+                                        } catch (InterruptedException e) {
+                                            e.printStackTrace();
+                                        }
+                                    }
+                                });
+                            } catch (Exception e) {
+                                Log.e(LOG_TAG, "InterruptedException occured: "
+                                        + e.toString());
+                                continue;
+                            }
+                            reboot = ConfigurationDefaultValues.defaultReboot;
+                        }
+                        if (factoryReset.equalsIgnoreCase("true")) {
+                            factoryReset = ConfigurationDefaultValues.defaultFactoryReset;
+                            factoryReset();
+                        }
+                    }
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        };
+        thread.start();
+        Log.i(LOG_TAG, "createResource(Diagnostics): exit");
+    }
+
+    // getters and Setters Methods for diagnostics Resource
+    public void setDiagnosticsRepresentation(OcRepresentation rep) {
+        Log.i(LOG_TAG, "setDiagnosticsRepresentation: enter");
+
+        String fr = rep.getValueString("fr");
+        String rb = rep.getValueString("rb");
+        String ssc = rep.getValueString("ssc");
+
+        if (!(fr.equalsIgnoreCase(""))) {
+            factoryReset = fr;
+            Log.i(LOG_TAG,
+                    "setConfigurationRepresentation: New value(FactoryReset): "
+                            + fr);
+        }
+        if (!(rb.equalsIgnoreCase(""))) {
+            reboot = rb;
+            Log.i(LOG_TAG, "setDiagnosticsRepresentation: new value:(reboot) "
+                    + rb);
+        }
+
+        if (!(ssc.equalsIgnoreCase(""))) {
+            startCollection = ssc;
+            Log.i(LOG_TAG,
+                    "setDiagnosticsRepresentation: new value:(startcollection) "
+                            + ssc);
+        }
+
+        Log.i(LOG_TAG, "setDiagnosticsRepresentation: exit");
+    }
+
+    OcRepresentation getDiagnosticsRepresentation() {
+        diagnosticsRep.setValueString("fr", factoryReset);
+        diagnosticsRep.setValueString("rb", reboot);
+        diagnosticsRep.setValueString("ssc", startCollection);
+        return diagnosticsRep;
+    }
+
+    public String getUri() {
+        return diagnosticsUri;
+    }
+
+    // For Resetting diagnostics Resource attributes to their default values
+    public void factoryReset() {
+        factoryReset = ConfigurationDefaultValues.defaultFactoryReset;
+        reboot = ConfigurationDefaultValues.defaultReboot;
+        startCollection = ConfigurationDefaultValues.defaultStartCollection;
+    }
+
+    // For Deleting diagnostic resource
+    public void deleteResource() {
+        try {
+            if (null != diagnosticsHandle) {
+                // Unregister the collection resource
+                OcPlatform.unregisterResource(diagnosticsHandle);
+            }
+        } catch (OcException e) {
+            Log.e(LOG_TAG, "OcException occured! " + e.toString());
+        }
+    }
+}
diff --git a/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/FactorySetResource.java b/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/FactorySetResource.java
new file mode 100644 (file)
index 0000000..df47cf0
--- /dev/null
@@ -0,0 +1,128 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.example.con_server;
+
+import java.util.EnumSet;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.ResourceProperty;
+
+import android.util.Log;
+
+// For creating & deleting the FactorySet Resource
+public class FactorySetResource extends ConfigurationResource {
+    private final String LOG_TAG = "[CON-SERVER]"
+                                         + this.getClass().getSimpleName();
+
+    // constructor
+    public FactorySetResource() {
+        Log.i(LOG_TAG, "FactorySetCollection: enter");
+
+        configurationUri = "/factorySet"; // uri of the resource
+        configurationTypes.clear();
+        configurationTypes.add("factorySet");
+        configurationRep.setUri(configurationUri);
+        configurationRep.setResourceTypes(configurationTypes);
+    }
+
+    // for creating FactoryReset Resource
+    public void createResource(OcPlatform.EntityHandler listener)
+            throws OcException {
+        Log.i(LOG_TAG, "createResource(Factory Set): enter");
+        EnumSet<ResourceProperty> propertySet = EnumSet.of(
+                ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE);
+        if (null == listener) {
+            Log.i(LOG_TAG, "CallBack Should be binded");
+            return;
+        }
+
+        // Register factoryset resource
+        configurationHandle = OcPlatform.registerResource(configurationUri,
+                configurationTypes.elementAt(0),
+                configurationInterfaces.elementAt(0), listener, propertySet);
+        if (null == configurationHandle) {
+            Log.e(LOG_TAG, "registerResource failed!");
+            return;
+        }
+        Log.i(LOG_TAG, "createResource (Factory Set): exit");
+    }
+
+    // getters and Setters Methods for FacoryReset Resource
+    public void setFactorySetRepresentation(OcRepresentation rep) {
+        Log.i(LOG_TAG, "setFactorySetRepresentation: enter");
+
+        String loc;
+        String st;
+        String cur;
+        String reg;
+        loc = rep.getValueString("loc");
+        st = rep.getValueString("st");
+        cur = rep.getValueString("c");
+        reg = rep.getValueString("r");
+        if (null != loc) {
+            location = loc;
+            Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+                    + location);
+        }
+        if (null != st) {
+            // systemTime = st;
+            Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+                    + systemTime);
+        }
+        if (null != cur) {
+            currency = cur;
+            Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+                    + currency);
+        }
+        if (null != reg) {
+            region = reg;
+            Log.i(LOG_TAG, "setConfigurationRepresentation: New value: "
+                    + region);
+        }
+        Log.i(LOG_TAG, "setFactorySetRepresentation: exit");
+    }
+
+    OcRepresentation getFactorySetRepresentation() {
+
+        configurationRep.setValueString("loc", location);
+        configurationRep.setValueString("st", systemTime);
+        configurationRep.setValueString("c", currency);
+        configurationRep.setValueString("r", region);
+        return configurationRep;
+    }
+
+    public String getUri() {
+        return configurationUri;
+    }
+
+    // For deletingFactorySet Resource
+    public void deleteResource() {
+        try {
+            if (null != configurationHandle) {
+                // Unregister the collection resource
+                OcPlatform.unregisterResource(configurationHandle);
+            }
+        } catch (OcException e) {
+            Log.e(LOG_TAG, "OcException occured! " + e.toString());
+        }
+    }
+}
diff --git a/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/MainActivity.java b/service/things-manager/sampleapp/android/con-server/src/com/example/con_server/MainActivity.java
new file mode 100644 (file)
index 0000000..63d9286
--- /dev/null
@@ -0,0 +1,197 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+package com.example.con_server;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.ProgressDialog;
+import android.content.DialogInterface;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.EditText;
+
+/*
+ * Starting Activity of the application responsible for
+ * configuring the OcPlatform and for handling user's selection on UI.
+ */
+public class MainActivity extends Activity {
+
+    private final String         LOG_TAG = this.getClass().getSimpleName();
+    private Handler              mHandler;
+    private static MainActivity  mainActivityObj;
+    private ConfigurationServer  conServerObj;
+    private static String        message;
+    private EditText             editText;
+    public static ProgressDialog dialog;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+
+        mainActivityObj = this;
+        Button doBootStrap = (Button) findViewById(R.id.button1);
+        final Button createConfig = (Button) findViewById(R.id.button2);
+        editText = (EditText) findViewById(R.id.EditText);
+        conServerObj = new ConfigurationServer();
+
+        // handler for updating the UI i.e. MessageLog (TextBox)
+        mHandler = new Handler() {
+            @Override
+            public void handleMessage(Message msg) {
+                switch (msg.what) {
+                    case 0:
+                        editText.setText(message);
+                }
+            }
+        };
+        setmHandler(mHandler);
+
+        // listener for doBootStrap Button
+        doBootStrap.setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                conServerObj.DoBootStrap();
+                createConfig.setEnabled(true);
+            }
+        });
+
+        // listener for createConfiguration Resource Button
+        createConfig.setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                conServerObj.CreateConfigurationResource();
+                createConfig.setEnabled(false);
+            }
+        });
+
+        // calling the method to check the Wi-fi connectivity and configuring
+        // the OcPlatform
+        configurePlatform();
+    }
+
+    private void configurePlatform() {
+
+        // Check the wi-fi connectivity
+        ConnectivityManager connmanager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
+        NetworkInfo wifi = connmanager
+                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+        if (false == wifi.isConnected()) {
+            // WiFi is not connected close the application
+            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
+            dialogBuilder.setTitle("Error");
+            dialogBuilder
+                    .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...");
+            dialogBuilder.setCancelable(false);
+            dialogBuilder.setPositiveButton("OK",
+                    new DialogInterface.OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            // Closing the application
+                            mainActivityObj.finish();
+                        }
+                    });
+
+            AlertDialog dialog = dialogBuilder.create();
+            dialog.show();
+            return;
+        }
+
+        // If wifi is connected calling the configure method for configuring the
+        // ocPlatform
+        PlatformConfig cfg = new PlatformConfig(getApplicationContext(),ServiceType.IN_PROC,
+                ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
+        OcPlatform.Configure(cfg);
+        Log.i(LOG_TAG, "Configuration done Successfully");
+    }
+
+    @Override
+    public void onBackPressed() {
+        super.onBackPressed();
+
+        // deleting all the resources that we have created.
+        if (null != conServerObj)
+            conServerObj.deleteResources();
+    }
+
+    @SuppressWarnings("unused")
+    private Handler handler = new Handler() {
+                                @Override
+                                public void handleMessage(Message msg) {
+                                    dialog.dismiss();
+                                }
+                            };
+
+    // Function called when receive a reboot Request
+    public static void reboot() throws InterruptedException {
+
+        dialog = new ProgressDialog(mainActivityObj);
+        dialog.setMessage("Rebooting..");
+        dialog.setTitle("Please wait ...");
+        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
+        dialog.setProgress(0);
+        dialog.setMax(100);
+        dialog.show();
+        Thread thread = new Thread() {
+            @Override
+            public void run() {
+                try {
+                    sleep(5000);
+                    dialog.dismiss();
+
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        };
+        thread.start();
+    }
+
+    // Functions required for updating the UI
+
+    public Handler getmHandler() {
+        return mHandler;
+    }
+
+    public void setmHandler(Handler mHandler) {
+        this.mHandler = mHandler;
+    }
+
+    public static MainActivity getMainActivityObject() {
+        return mainActivityObj;
+    }
+
+    public static void setmessage(String msg) {
+        message = msg;
+    }
+}
index 7ee28d1..1096799 100644 (file)
@@ -33,7 +33,7 @@
 using namespace OC;
 
 /// This function internally calls registerResource API.
-void ConfigurationCollection::createResources(ResourceEntityHandler callback)
+void ConfigurationResource::createResources(ResourceEntityHandler callback)
 {
     using namespace OC::OCPlatform;
 
@@ -53,539 +53,57 @@ void ConfigurationCollection::createResources(ResourceEntityHandler callback)
         std::cout << "Resource creation (configuration) was unsuccessful\n";
     }
 
-    result = bindInterfaceToResource(m_configurationHandle, m_configurationInterfaces[1]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_configurationHandle, m_configurationInterfaces[2]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = registerResource(m_regionHandle, m_regionUri, m_regionTypes[0], m_regionInterfaces[0],
-            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (region) was unsuccessful\n";
-    }
-
-    result = registerResource(m_timeHandle, m_timeUri, m_timeTypes[0], m_timeInterfaces[0],
-            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (time) was unsuccessful\n";
-    }
-
-    result = registerResource(m_networkHandle, m_networkUri, m_networkTypes[0],
-            m_networkInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (network) was unsuccessful\n";
-    }
-
-    result = registerResource(m_securityHandle, m_securityUri, m_securityTypes[0],
-            m_securityInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (security) was unsuccessful\n";
-    }
-
-    result = bindResource(m_configurationHandle, m_regionHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding region resource to room was unsuccessful\n";
-    }
-
-    result = bindResource(m_configurationHandle, m_timeHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding time resource to room was unsuccessful\n";
-    }
-
-    result = bindResource(m_configurationHandle, m_networkHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding network resource to room was unsuccessful\n";
-    }
-
-    result = bindResource(m_configurationHandle, m_securityHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding security resource to room was unsuccessful\n";
-    }
-
-    std::cout << "Configuration Collection is Created!(URI: " << m_configurationUri << ") \n";
-
-    myTimeCollection->createResources(callback);
-    myNetworkCollection->createResources(callback);
-    mySecurityCollection->createResources(callback);
-
+    std::cout << "Configuration Resource is Created!(URI: " << m_configurationUri << ") \n";
 }
 
-void ConfigurationCollection::setConfigurationRepresentation(OCRepresentation& rep)
+void ConfigurationResource::setConfigurationRepresentation(OCRepresentation& rep)
 {
     string value;
 
-    if (rep.getValue("value", value))
+    if (rep.getValue("loc", value))
     {
-        m_configurationValue = value;
-
-        std::cout << "\t\t\t\t" << "m_configurationValue: " << m_configurationValue << std::endl;
+        m_location = value;
+        std::cout << "\t\t\t\t" << "m_location: " << m_location << std::endl;
     }
-}
-
-void ConfigurationCollection::setTimeRepresentation(OCRepresentation& rep)
-{
-    string value;
 
-    if (rep.getValue("link", value))
+    if (rep.getValue("st", value))
     {
-        // NOT ALLOWED
-
-        std::cout << "\t\t\t\t" << "link: " << m_timeLink << std::endl;
+        std::cout << "\t\t\t\t" << "SystemTime is not allowed to be written." << std::endl;
     }
-}
-
-void ConfigurationCollection::setNetworkRepresentation(OCRepresentation& rep)
-{
-    string value;
 
-    if (rep.getValue("link", value))
+    if (rep.getValue("c", value))
     {
-        // NOT ALLOWED
-
-        std::cout << "\t\t\t\t" << "link: " << m_networkLink << std::endl;
+        m_currency = value;
+        std::cout << "\t\t\t\t" << "m_currency: " << m_currency << std::endl;
     }
-}
 
-void ConfigurationCollection::setSecurityRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("link", value))
+    if (rep.getValue("r", value))
     {
-        // NOT ALLOWED
-
-        std::cout << "\t\t\t\t" << "link: " << m_securityLink << std::endl;
+        m_region = value;
+        std::cout << "\t\t\t\t" << "m_region: " << m_region << std::endl;
     }
 }
 
-void ConfigurationCollection::setRegionRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("value", value))
-    {
-        m_regionValue = value;
-
-        std::cout << "\t\t\t\t" << "value: " << m_regionValue << std::endl;
-    }
-}
-
-OCRepresentation ConfigurationCollection::getTimeRepresentation()
-{
-    m_timeRep.setValue("link", m_timeLink);
-
-    return m_timeRep;
-}
-
-OCRepresentation ConfigurationCollection::getNetworkRepresentation()
-{
-    m_networkRep.setValue("link", m_networkLink);
-
-    return m_networkRep;
-}
-
-OCRepresentation ConfigurationCollection::getSecurityRepresentation()
+OCRepresentation ConfigurationResource::getConfigurationRepresentation()
 {
-    m_securityRep.setValue("link", m_securityLink);
-
-    return m_securityRep;
-}
-
-OCRepresentation ConfigurationCollection::getRegionRepresentation()
-{
-    m_regionRep.setValue("value", m_regionValue);
-
-    return m_regionRep;
-}
-
-OCRepresentation ConfigurationCollection::getConfigurationRepresentation()
-{
-    m_configurationRep.clearChildren();
-
-    m_configurationRep.addChild(getRegionRepresentation());
-    m_configurationRep.addChild(getTimeRepresentation());
-    m_configurationRep.addChild(getNetworkRepresentation());
-    m_configurationRep.addChild(getSecurityRepresentation());
-
-    m_configurationRep.setValue("value", m_configurationValue);
+    m_configurationRep.setValue("loc", m_location);
+    m_configurationRep.setValue("st", m_systemTime);
+    m_configurationRep.setValue("c", m_currency);
+    m_configurationRep.setValue("r", m_region);
 
     return m_configurationRep;
 }
 
-std::string ConfigurationCollection::getConfigurationUri()
+std::string ConfigurationResource::getUri()
 {
     return m_configurationUri;
 }
 
-std::string ConfigurationCollection::getTimeUri()
-{
-    return m_timeUri;
-}
-
-std::string ConfigurationCollection::getNetworkUri()
-{
-    return m_networkUri;
-}
-
-std::string ConfigurationCollection::getSecurityUri()
-{
-    return m_securityUri;
-}
-
-std::string ConfigurationCollection::getRegionUri()
-{
-    return m_regionUri;
-}
-
-void ConfigurationCollection::factoryReset()
-{
-    m_configurationValue = defaultConfigurationValue;
-    m_regionValue = defaultRegionValue;
-    m_timeLink = defaultTimeLink;
-    m_networkLink = defaultNetworkLink;
-    m_securityLink = defaultSecurityLink;
-
-    myTimeCollection->factoryReset();
-    myNetworkCollection->factoryReset();
-    mySecurityCollection->factoryReset();
-}
-
-/// This function internally calls registerResource API.
-void TimeCollection::createResources(ResourceEntityHandler callback)
-{
-    using namespace OC::OCPlatform;
-
-    if (callback == NULL)
-    {
-        std::cout << "callback should be binded\t";
-        return;
-    }
-
-    // This will internally create and register the resource.
-    OCStackResult result = registerResource(m_timeHandle, m_timeUri, m_timeTypes[0],
-            m_timeInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (time) was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_timeHandle, m_timeInterfaces[1]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_timeHandle, m_timeInterfaces[2]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = registerResource(m_currentTimeHandle, m_currentTimeUri, m_currentTimeTypes[0],
-            m_currentTimeInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (currentTime) was unsuccessful\n";
-    }
-
-    result = bindResource(m_timeHandle, m_currentTimeHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding currentTime resource to room was unsuccessful\n";
-    }
-
-    std::cout << "Time Collection is Created!(URI: " << m_timeUri << ") \n";
-}
-
-void TimeCollection::setTimeRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("value", value))
-    {
-        m_timeValue = value;
-
-        std::cout << "\t\t\t\t" << "m_timeValue: " << m_timeValue << std::endl;
-    }
-}
-
-void TimeCollection::setCurrentTimeRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("currentTime", value))
-    {
-        m_currentTimeValue = value;
-
-        std::cout << "\t\t\t\t" << "value: " << m_currentTimeValue << std::endl;
-    }
-}
-
-OCRepresentation TimeCollection::getCurrentTimeRepresentation()
-{
-    m_currentTimeRep.setValue("value", m_currentTimeValue);
-
-    return m_currentTimeRep;
-}
-
-OCRepresentation TimeCollection::getTimeRepresentation()
-{
-    m_timeRep.clearChildren();
-
-    m_timeRep.addChild(getCurrentTimeRepresentation());
-
-    m_timeRep.setValue("value", m_timeValue);
-
-    return m_timeRep;
-}
-
-std::string TimeCollection::getTimeUri()
-{
-    return m_timeUri;
-}
-
-std::string TimeCollection::getCurrentTimeUri()
-{
-    return m_currentTimeUri;
-}
-
-void TimeCollection::factoryReset()
-{
-    m_timeValue = defaultTimeValue;
-    m_currentTimeValue = defaultCurrentTimeValue;
-}
-
-/// This function internally calls registerResource API.
-void NetworkCollection::createResources(ResourceEntityHandler callback)
-{
-    using namespace OC::OCPlatform;
-
-    if (callback == NULL)
-    {
-        std::cout << "callback should be binded\t";
-        return;
-    }
-
-    // This will internally create and register the resource.
-    OCStackResult result = registerResource(m_networkHandle, m_networkUri, m_networkTypes[0],
-            m_networkInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (network) was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_networkHandle, m_networkInterfaces[1]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_networkHandle, m_networkInterfaces[2]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = registerResource(m_IPAddressHandle, m_IPAddressUri, m_IPAddressTypes[0],
-            m_IPAddressInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (IPAddress) was unsuccessful\n";
-    }
-
-    result = bindResource(m_networkHandle, m_IPAddressHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding IPAddress resource to room was unsuccessful\n";
-    }
-
-    std::cout << "Network Collection is Created!(URI: " << m_networkUri << ") \n";
-}
-
-void NetworkCollection::setNetworkRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("value", value))
-    {
-        m_networkValue = value;
-
-        std::cout << "\t\t\t\t" << "m_networkValue: " << m_networkValue << std::endl;
-    }
-}
-
-void NetworkCollection::setIPAddressRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("IPAddress", value))
-    {
-        m_IPAddressValue = value;
-
-        std::cout << "\t\t\t\t" << "value: " << m_IPAddressValue << std::endl;
-    }
-}
-OCRepresentation NetworkCollection::getIPAddressRepresentation()
-{
-    m_IPAddressRep.setValue("value", m_IPAddressValue);
-
-    return m_IPAddressRep;
-}
-
-OCRepresentation NetworkCollection::getNetworkRepresentation()
-{
-    m_networkRep.clearChildren();
-
-    m_networkRep.addChild(getIPAddressRepresentation());
-
-    m_networkRep.setValue("value", m_networkValue);
-
-    return m_networkRep;
-}
-
-std::string NetworkCollection::getNetworkUri()
-{
-    return m_networkUri;
-}
-
-std::string NetworkCollection::getIPAddressUri()
-{
-    return m_IPAddressUri;
-}
-
-void NetworkCollection::factoryReset()
-{
-    m_networkValue = defaultNetworkValue;
-    m_IPAddressValue = defaultIPAddressValue;
-}
-
-/// This function internally calls registerResource API.
-void SecurityCollection::createResources(ResourceEntityHandler callback)
-{
-    using namespace OC::OCPlatform;
-
-    if (callback == NULL)
-    {
-        std::cout << "callback should be binded\t";
-        return;
-    }
-
-    // This will internally create and register the resource.
-    OCStackResult result = registerResource(m_securityHandle, m_securityUri, m_securityTypes[0],
-            m_securityInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (security) was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_securityHandle, m_securityInterfaces[1]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_securityHandle, m_securityInterfaces[2]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = registerResource(m_modeHandle, m_modeUri, m_modeTypes[0], m_modeInterfaces[0],
-            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (mode) was unsuccessful\n";
-    }
-
-    result = bindResource(m_securityHandle, m_modeHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding mode resource to room was unsuccessful\n";
-    }
-
-    std::cout << "Security Collection is Created!(URI: " << m_securityUri << ") \n";
-}
-
-void SecurityCollection::setSecurityRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("value", value))
-    {
-        m_securityValue = value;
-
-        std::cout << "\t\t\t\t" << "m_securityValue: " << m_securityValue << std::endl;
-    }
-}
-
-void SecurityCollection::setModeRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("mode", value))
-    {
-        m_modeValue = value;
-
-        std::cout << "\t\t\t\t" << "value: " << m_modeValue << std::endl;
-    }
-}
-
-OCRepresentation SecurityCollection::getModeRepresentation()
-{
-    m_modeRep.setValue("value", m_modeValue);
-
-    return m_modeRep;
-}
-
-OCRepresentation SecurityCollection::getSecurityRepresentation()
-{
-    m_securityRep.clearChildren();
-
-    m_securityRep.addChild(getModeRepresentation());
-
-    m_securityRep.setValue("value", m_securityValue);
-
-    return m_securityRep;
-}
-
-std::string SecurityCollection::getSecurityUri()
-{
-    return m_securityUri;
-}
-
-std::string SecurityCollection::getModeUri()
-{
-    return m_modeUri;
-}
-
-void SecurityCollection::factoryReset()
+void ConfigurationResource::factoryReset()
 {
-    m_securityValue = defaultSecurityValue;
-    m_modeValue = defaultModeValue;
+    m_location = defaultLocation;
+    m_systemTime = defaultSystemTime;
+    m_currency = defaultCurrency;
+    m_region = defaultRegion;
 }
 
index cbc1db5..2dc3bbf 100644 (file)
 
 using namespace OC;
 
-typedef std::function< OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+typedef std::function<
+    OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
 
 static std::string defaultURIPrefix = "/oic/con";
 static std::string defaultResourceTypePrefix = "oic.con";
 
-extern std::string defaultTimeValue;
-extern std::string defaultCurrentTimeValue;
+extern std::string defaultLocation;
+extern std::string defaultSystemTime;
+extern std::string defaultCurrency;
+extern std::string defaultRegion;
 
-class TimeCollection
+class ConfigurationResource
 {
 public:
-
-    // diagnostics members
-    std::string m_timeUri;
-    std::string m_timeValue;
-    std::vector< std::string > m_timeTypes;
-    std::vector< std::string > m_timeInterfaces;
-    OCResourceHandle m_timeHandle;
-    OCRepresentation m_timeRep;
-
-    // factory reset members
-    std::string m_currentTimeUri;
-    std::string m_currentTimeValue;
-    std::vector< std::string > m_currentTimeTypes;
-    std::vector< std::string > m_currentTimeInterfaces;
-    OCResourceHandle m_currentTimeHandle;
-    OCRepresentation m_currentTimeRep;
-
-public:
-    /// Constructor
-    TimeCollection() :
-            m_timeValue(defaultTimeValue), m_currentTimeValue(defaultCurrentTimeValue)
-    {
-        m_currentTimeUri = defaultURIPrefix + "/time/0/currentTime"; // URI of the resource
-        m_currentTimeTypes.push_back("oic.con.time.currentTime"); // resource type name.
-        m_currentTimeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_currentTimeRep.setUri(m_currentTimeUri);
-        m_currentTimeRep.setResourceTypes(m_currentTimeTypes);
-        m_currentTimeRep.setResourceInterfaces(m_currentTimeInterfaces);
-        m_currentTimeRep.setValue("value", m_currentTimeValue);
-        m_currentTimeHandle = NULL;
-
-        m_timeUri = defaultURIPrefix + "/time"; // URI of the resource
-        m_timeTypes.push_back("oic.con.time"); // resource type name.
-        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_timeInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_timeInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_timeRep.setValue("value", m_timeValue);
-        m_timeRep.setUri(m_timeUri);
-        m_timeRep.setResourceTypes(m_timeTypes);
-        m_timeRep.setResourceInterfaces(m_timeInterfaces);
-        m_timeHandle = NULL;
-    }
-    ;
-
-    /// Constructor
-    TimeCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
-            m_timeValue(defaultTimeValue), m_currentTimeValue(defaultCurrentTimeValue)
-    {
-        m_currentTimeUri = URIPrefix + "/time/0/currentTime"; // URI of the resource
-        m_currentTimeTypes.push_back(ResourceTypePrefix + ".time.currentTime"); // type name.
-        m_currentTimeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_currentTimeRep.setUri(m_currentTimeUri);
-        m_currentTimeRep.setResourceTypes(m_currentTimeTypes);
-        m_currentTimeRep.setResourceInterfaces(m_currentTimeInterfaces);
-        m_currentTimeRep.setValue("value", m_currentTimeValue);
-        m_currentTimeHandle = NULL;
-
-        m_timeUri = URIPrefix + "/time"; // URI of the resource
-        m_timeTypes.push_back(ResourceTypePrefix + ".time"); // resource type name.
-        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_timeInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_timeInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_timeRep.setValue("value", m_timeValue);
-        m_timeRep.setUri(m_timeUri);
-        m_timeRep.setResourceTypes(m_timeTypes);
-        m_timeRep.setResourceInterfaces(m_timeInterfaces);
-        m_timeHandle = NULL;
-    }
-    ;
-
-    /// This function internally calls registerResource API.
-    void createResources(ResourceEntityHandler callback);
-
-    void setTimeRepresentation(OCRepresentation& rep);
-    void setCurrentTimeRepresentation(OCRepresentation& rep);
-
-    OCRepresentation getTimeRepresentation();
-    OCRepresentation getCurrentTimeRepresentation();
-
-    std::string getTimeUri();
-    std::string getCurrentTimeUri();
-
-    void factoryReset();
-
-};
-
-extern std::string defaultNetworkValue;
-extern std::string defaultIPAddressValue;
-
-class NetworkCollection
-{
-public:
-
-    // diagnostics members
-    std::string m_networkUri;
-    std::string m_networkValue;
-    std::vector< std::string > m_networkTypes;
-    std::vector< std::string > m_networkInterfaces;
-    OCResourceHandle m_networkHandle;
-    OCRepresentation m_networkRep;
-
-    // factory reset members
-    std::string m_IPAddressUri;
-    std::string m_IPAddressValue;
-    std::vector< std::string > m_IPAddressTypes;
-    std::vector< std::string > m_IPAddressInterfaces;
-    OCResourceHandle m_IPAddressHandle;
-    OCRepresentation m_IPAddressRep;
-
-public:
-
-    /// Constructor
-    NetworkCollection() :
-            m_networkValue(defaultNetworkValue), m_IPAddressValue(defaultIPAddressValue)
-    {
-        m_IPAddressUri = defaultURIPrefix + "/network/0/IPAddress"; // URI of the resource
-        m_IPAddressTypes.push_back("oic.con.network.IPAddress"); // resource type name.
-        m_IPAddressInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_IPAddressRep.setUri(m_IPAddressUri);
-        m_IPAddressRep.setResourceTypes(m_IPAddressTypes);
-        m_IPAddressRep.setResourceInterfaces(m_IPAddressInterfaces);
-        m_IPAddressRep.setValue("value", m_IPAddressValue);
-        m_IPAddressHandle = NULL;
-
-        m_networkUri = defaultURIPrefix + "/network"; // URI of the resource
-        m_networkTypes.push_back("oic.con.network"); // resource type name.
-        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_networkInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_networkInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_networkRep.setValue("value", m_networkValue);
-        m_networkRep.setUri(m_networkUri);
-        m_networkRep.setResourceTypes(m_networkTypes);
-        m_networkRep.setResourceInterfaces(m_networkInterfaces);
-        m_networkHandle = NULL;
-    }
-    ;
-
-    /// Constructor
-    NetworkCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
-            m_networkValue(defaultNetworkValue), m_IPAddressValue(defaultIPAddressValue)
-    {
-        m_IPAddressUri = URIPrefix + "/network/0/IPAddress"; // URI of the resource
-        m_IPAddressTypes.push_back(ResourceTypePrefix + "network.IPAddress"); // resource type name.
-        m_IPAddressInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_IPAddressRep.setUri(m_IPAddressUri);
-        m_IPAddressRep.setResourceTypes(m_IPAddressTypes);
-        m_IPAddressRep.setResourceInterfaces(m_IPAddressInterfaces);
-        m_IPAddressRep.setValue("value", m_IPAddressValue);
-        m_IPAddressHandle = NULL;
-
-        m_networkUri = URIPrefix + "/network"; // URI of the resource
-        m_networkTypes.push_back(ResourceTypePrefix + ".network"); // resource type name.
-        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_networkInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_networkInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_networkRep.setValue("value", m_networkValue);
-        m_networkRep.setUri(m_networkUri);
-        m_networkRep.setResourceTypes(m_networkTypes);
-        m_networkRep.setResourceInterfaces(m_networkInterfaces);
-        m_networkHandle = NULL;
-    }
-    ;
-
-    /// This function internally calls registerResource API.
-    void createResources(ResourceEntityHandler callback);
-
-    void setNetworkRepresentation(OCRepresentation& rep);
-    void setIPAddressRepresentation(OCRepresentation& rep);
-
-    OCRepresentation getNetworkRepresentation();
-    OCRepresentation getIPAddressRepresentation();
-
-    std::string getNetworkUri();
-    std::string getIPAddressUri();
-
-    void factoryReset();
-
-};
-
-extern std::string defaultSecurityValue;
-extern std::string defaultModeValue;
-
-class SecurityCollection
-{
-public:
-
-    // diagnostics members
-    std::string m_securityUri;
-    std::string m_securityValue;
-    std::vector< std::string > m_securityTypes;
-    std::vector< std::string > m_securityInterfaces;
-    OCResourceHandle m_securityHandle;
-    OCRepresentation m_securityRep;
-
-    // factory reset members
-    std::string m_modeUri;
-    std::string m_modeValue;
-    std::vector< std::string > m_modeTypes;
-    std::vector< std::string > m_modeInterfaces;
-    OCResourceHandle m_modeHandle;
-    OCRepresentation m_modeRep;
-
-public:
-    /// Constructor
-    SecurityCollection() :
-            m_securityValue(defaultSecurityValue), m_modeValue(defaultModeValue)
-    {
-        m_modeUri = defaultURIPrefix + "/security/0/mode"; // URI of the resource
-        m_modeTypes.push_back("oic.con.security.mode"); // resource type name.
-        m_modeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_modeRep.setUri(m_modeUri);
-        m_modeRep.setResourceTypes(m_modeTypes);
-        m_modeRep.setResourceInterfaces(m_modeInterfaces);
-        m_modeRep.setValue("value", m_modeValue);
-        m_modeHandle = NULL;
-
-        m_securityUri = defaultURIPrefix + "/security"; // URI of the resource
-        m_securityTypes.push_back("oic.con.security"); // resource type name.
-        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_securityInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_securityInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_securityRep.setValue("value", m_securityValue);
-        m_securityRep.setUri(m_securityUri);
-        m_securityRep.setResourceTypes(m_securityTypes);
-        m_securityRep.setResourceInterfaces(m_securityInterfaces);
-        m_securityHandle = NULL;
-    }
-    ;
-
-    /// Constructor
-    SecurityCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
-            m_securityValue(defaultSecurityValue), m_modeValue(defaultModeValue)
-    {
-        m_modeUri = URIPrefix + "/security/0/mode"; // URI of the resource
-        m_modeTypes.push_back(ResourceTypePrefix + ".security.mode"); // resource type name.
-        m_modeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_modeRep.setUri(m_modeUri);
-        m_modeRep.setResourceTypes(m_modeTypes);
-        m_modeRep.setResourceInterfaces(m_modeInterfaces);
-        m_modeRep.setValue("value", m_modeValue);
-        m_modeHandle = NULL;
-
-        m_securityUri = URIPrefix + "/security"; // URI of the resource
-        m_securityTypes.push_back(ResourceTypePrefix + ".security"); // resource type name.
-        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_securityInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_securityInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_securityRep.setValue("value", m_securityValue);
-        m_securityRep.setUri(m_securityUri);
-        m_securityRep.setResourceTypes(m_securityTypes);
-        m_securityRep.setResourceInterfaces(m_securityInterfaces);
-        m_securityHandle = NULL;
-    }
-    ;
-
-    /// This function internally calls registerResource API.
-    void createResources(ResourceEntityHandler callback);
-
-    void setSecurityRepresentation(OCRepresentation& rep);
-    void setModeRepresentation(OCRepresentation& rep);
-
-    OCRepresentation getSecurityRepresentation();
-    OCRepresentation getModeRepresentation();
-
-    std::string getSecurityUri();
-    std::string getModeUri();
-
-    void factoryReset();
-
-};
-
-extern std::string defaultConfigurationValue;
-extern std::string defaultRegionValue;
-static std::string defaultTimeLink = "/con/con/0/time";
-static std::string defaultNetworkLink = "/con/con/0/network";
-static std::string defaultSecurityLink = "/con/con/0/security";
-
-class ConfigurationCollection
-{
-public:
-    TimeCollection *myTimeCollection;
-    NetworkCollection *myNetworkCollection;
-    SecurityCollection *mySecurityCollection;
-
-public:
     // Configuration members
     std::string m_configurationUri;
-    std::string m_configurationValue;
+    std::string m_location;
+    std::string m_systemTime;
+    std::string m_currency;
+    std::string m_region;
     std::vector< std::string > m_configurationTypes;
     std::vector< std::string > m_configurationInterfaces;
     OCResourceHandle m_configurationHandle;
     OCRepresentation m_configurationRep;
 
-    // Security members
-    std::string m_regionUri;
-    std::string m_regionValue;
-    std::vector< std::string > m_regionTypes;
-    std::vector< std::string > m_regionInterfaces;
-    OCResourceHandle m_regionHandle;
-    OCRepresentation m_regionRep;
-
-    // Time members
-    std::string m_timeUri;
-    std::string m_timeLink;
-    std::vector< std::string > m_timeTypes;
-    std::vector< std::string > m_timeInterfaces;
-    OCResourceHandle m_timeHandle;
-    OCRepresentation m_timeRep;
-
-    // Network members
-    std::string m_networkUri;
-    std::string m_networkLink;
-    std::vector< std::string > m_networkTypes;
-    std::vector< std::string > m_networkInterfaces;
-    OCResourceHandle m_networkHandle;
-    OCRepresentation m_networkRep;
-
-    // Security members
-    std::string m_securityUri;
-    std::string m_securityLink;
-    std::vector< std::string > m_securityTypes;
-    std::vector< std::string > m_securityInterfaces;
-    OCResourceHandle m_securityHandle;
-    OCRepresentation m_securityRep;
-
 public:
     /// Constructor
-    ConfigurationCollection() :
-            m_configurationValue(defaultConfigurationValue), m_regionValue(defaultRegionValue), m_timeLink(
-                    defaultTimeLink), m_networkLink(defaultNetworkLink), m_securityLink(
-                    defaultSecurityLink)
+    ConfigurationResource() :
+            m_location(defaultLocation), m_systemTime(defaultSystemTime), m_currency(
+                    defaultCurrency), m_region(defaultRegion)
     {
-        m_regionUri = defaultURIPrefix + "/0/region"; // URI of the resource
-        m_regionTypes.push_back(defaultResourceTypePrefix + ".region"); // resource type name.
-        m_regionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_regionRep.setUri(m_regionUri);
-        m_regionRep.setResourceTypes(m_regionTypes);
-        m_regionRep.setResourceInterfaces(m_regionInterfaces);
-        m_regionRep.setValue("value", m_regionValue);
-        m_regionHandle = NULL;
-
-        m_timeUri = defaultURIPrefix + "/0/time"; // URI of the resource
-        m_timeTypes.push_back(defaultResourceTypePrefix + ".time"); // resource type name.
-        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_timeRep.setUri(m_timeUri);
-        m_timeRep.setResourceTypes(m_timeTypes);
-        m_timeRep.setResourceInterfaces(m_timeInterfaces);
-        m_timeRep.setValue("link", m_timeLink);
-        m_timeHandle = NULL;
-
-        m_networkUri = defaultURIPrefix + "/0/net"; // URI of the resource
-        m_networkTypes.push_back(defaultResourceTypePrefix + ".net"); // resource type name.
-        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_networkRep.setUri(m_networkUri);
-        m_networkRep.setResourceTypes(m_networkTypes);
-        m_networkRep.setResourceInterfaces(m_networkInterfaces);
-        m_networkRep.setValue("link", m_networkLink);
-        m_networkHandle = NULL;
-
-        m_securityUri = defaultURIPrefix + "/0/sec"; // URI of the resource
-        m_securityTypes.push_back(defaultResourceTypePrefix + ".sec"); // resource type name.
-        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_securityRep.setUri(m_securityUri);
-        m_securityRep.setResourceTypes(m_securityTypes);
-        m_securityRep.setResourceInterfaces(m_securityInterfaces);
-        m_securityRep.setValue("link", m_securityLink);
-        m_securityHandle = NULL;
-
-        m_configurationUri = defaultURIPrefix + ""; // URI of the resource
-        m_configurationTypes.push_back(defaultResourceTypePrefix + ""); // resource type name.
+        m_configurationUri = "/oic/con"; // URI of the resource
+        m_configurationTypes.push_back("oic.con"); // resource type name.
         m_configurationInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_configurationInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_configurationInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_configurationRep.setValue("value", m_configurationValue);
+        //m_configurationInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        //m_configurationInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_configurationRep.setValue("loc", m_location);
+        m_configurationRep.setValue("st", m_systemTime);
+        m_configurationRep.setValue("c", m_currency);
+        m_configurationRep.setValue("r", m_region);
         m_configurationRep.setUri(m_configurationUri);
         m_configurationRep.setResourceTypes(m_configurationTypes);
         m_configurationRep.setResourceInterfaces(m_configurationInterfaces);
         m_configurationHandle = NULL;
-
-        myTimeCollection = new TimeCollection();
-        myNetworkCollection = new NetworkCollection();
-        mySecurityCollection = new SecurityCollection();
     }
     ;
 
-    /// Constructor
-    ConfigurationCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
-            m_configurationValue(defaultConfigurationValue), m_regionValue(defaultRegionValue), m_timeLink(
-                    defaultTimeLink), m_networkLink(defaultNetworkLink), m_securityLink(
-                    defaultSecurityLink)
+    ~ConfigurationResource()
     {
-        m_regionUri = URIPrefix + "/0/region"; // URI of the resource
-        m_regionTypes.push_back(ResourceTypePrefix + ".region"); // type name.
-        m_regionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_regionRep.setUri(m_regionUri);
-        m_regionRep.setResourceTypes(m_regionTypes);
-        m_regionRep.setResourceInterfaces(m_regionInterfaces);
-        m_regionRep.setValue("value", m_regionValue);
-        m_regionHandle = NULL;
-
-        m_timeUri = URIPrefix + "/0/time"; // URI of the resource
-        m_timeTypes.push_back(ResourceTypePrefix + ".time"); // resource type name.
-        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_timeRep.setUri(m_timeUri);
-        m_timeRep.setResourceTypes(m_timeTypes);
-        m_timeRep.setResourceInterfaces(m_timeInterfaces);
-        m_timeRep.setValue("link", m_timeLink);
-        m_timeHandle = NULL;
-
-        m_networkUri = URIPrefix + "/0/net"; // URI of the resource
-        m_networkTypes.push_back(ResourceTypePrefix + ".net"); // resource type name.
-        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
 
-        m_networkRep.setUri(m_networkUri);
-        m_networkRep.setResourceTypes(m_networkTypes);
-        m_networkRep.setResourceInterfaces(m_networkInterfaces);
-        m_networkRep.setValue("link", m_networkLink);
-        m_networkHandle = NULL;
-
-        m_securityUri = URIPrefix + "/0/sec"; // URI of the resource
-        m_securityTypes.push_back(ResourceTypePrefix + ".sec"); // resource type name.
-        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_securityRep.setUri(m_securityUri);
-        m_securityRep.setResourceTypes(m_securityTypes);
-        m_securityRep.setResourceInterfaces(m_securityInterfaces);
-        m_securityRep.setValue("link", m_securityLink);
-        m_securityHandle = NULL;
-
-        m_configurationUri = URIPrefix + ""; // URI of the resource
-        m_configurationTypes.push_back(ResourceTypePrefix + ""); // resource type name.
-        m_configurationInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_configurationInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_configurationInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_configurationRep.setValue("value", m_configurationValue);
-        m_configurationRep.setUri(m_configurationUri);
-        m_configurationRep.setResourceTypes(m_configurationTypes);
-        m_configurationRep.setResourceInterfaces(m_configurationInterfaces);
-        m_configurationHandle = NULL;
-
-        myTimeCollection = new TimeCollection(URIPrefix, ResourceTypePrefix);
-        myNetworkCollection = new NetworkCollection(URIPrefix, ResourceTypePrefix);
-        mySecurityCollection = new SecurityCollection(URIPrefix, ResourceTypePrefix);
-    }
-    ;
-
-    ~ConfigurationCollection()
-    {
-        free(myTimeCollection);
-        free(myNetworkCollection);
-        free(mySecurityCollection);
     }
 
     /// This function internally calls registerResource API.
     void createResources(ResourceEntityHandler callback);
-
     void setConfigurationRepresentation(OCRepresentation& rep);
-    void setTimeRepresentation(OCRepresentation& rep);
-    void setNetworkRepresentation(OCRepresentation& rep);
-    void setSecurityRepresentation(OCRepresentation& rep);
-    void setRegionRepresentation(OCRepresentation& rep);
-
-    OCRepresentation getTimeRepresentation();
-    OCRepresentation getNetworkRepresentation();
-    OCRepresentation getSecurityRepresentation();
-    OCRepresentation getRegionRepresentation();
     OCRepresentation getConfigurationRepresentation();
-
-    std::string getConfigurationUri();
-    std::string getTimeUri();
-    std::string getNetworkUri();
-    std::string getSecurityUri();
-    std::string getRegionUri();
+    std::string getUri();
 
     void factoryReset();
 
index 31eaf1e..7809396 100644 (file)
@@ -33,7 +33,7 @@
 using namespace OC;
 
 /// This function internally calls registerResource API.
-void DiagnosticsCollection::createResources(ResourceEntityHandler callback)
+void DiagnosticsResource::createResources(ResourceEntityHandler callback)
 {
     using namespace OC::OCPlatform;
 
@@ -53,192 +53,72 @@ void DiagnosticsCollection::createResources(ResourceEntityHandler callback)
         std::cout << "Resource creation (diagnostics) was unsuccessful\n";
     }
 
-    result = bindInterfaceToResource(m_diagnosticsHandle, m_diagnosticsInterfaces[1]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_diagnosticsHandle, m_diagnosticsInterfaces[2]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = registerResource(m_factoryResetHandle, m_factoryResetUri, m_factoryResetTypes[0],
-            m_factoryResetInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (factoryReset) was unsuccessful\n";
-    }
-
-    result = registerResource(m_rebootHandle, m_rebootUri, m_rebootTypes[0], m_rebootInterfaces[0],
-            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (reboot) was unsuccessful\n";
-    }
-
-    result = registerResource(m_startCollectionHandle, m_startCollectionUri,
-            m_startCollectionTypes[0], m_startCollectionInterfaces[0], callback,
-            OC_DISCOVERABLE | OC_OBSERVABLE);
-
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Resource creation (startCollection) was unsuccessful\n";
-    }
-
-    result = bindResource(m_diagnosticsHandle, m_factoryResetHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding installedLocation resource to room was unsuccessful\n";
-    }
-
-    result = bindResource(m_diagnosticsHandle, m_rebootHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding time resource to room was unsuccessful\n";
-    }
-
-    result = bindResource(m_diagnosticsHandle, m_startCollectionHandle);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding network resource to room was unsuccessful\n";
-    }
-
     thread exec(
             std::function< void(int second) >(
-                    std::bind(&DiagnosticsCollection::diagnosticsMonitor, this,
+                    std::bind(&DiagnosticsResource::diagnosticsMonitor, this,
                             std::placeholders::_1)), 10); // every 10 seconds
     exec.detach();
 
-    std::cout << "Diagnostics Collection is Created!\n";
-}
-
-void DiagnosticsCollection::setDiagnosticsRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("value", value))
-    {
-        m_diagnosticsValue = value;
-
-        std::cout << "\t\t\t\t" << "m_diagnosticsValue: " << m_diagnosticsValue << std::endl;
-    }
+    std::cout << "Diagnostics Resource is Created!\n";
 }
 
-void DiagnosticsCollection::setFactoryResetRepresentation(OCRepresentation& rep)
+void DiagnosticsResource::setDiagnosticsRepresentation(OCRepresentation& rep)
 {
     string value;
 
-    if (rep.getValue("value", value))
+    if (rep.getValue("fr", value))
     {
-        m_factoryResetValue = value;
-
-        std::cout << "\t\t\t\t" << "value: " << m_factoryResetValue << std::endl;
+        m_factoryReset = value;
+        std::cout << "\t\t\t\t" << "m_factoryReset: " << m_factoryReset << std::endl;
     }
-}
-
-void DiagnosticsCollection::setRebootRepresentation(OCRepresentation& rep)
-{
-    string value;
 
-    if (rep.getValue("value", value))
+    if (rep.getValue("rb", value))
     {
-        m_rebootValue = value;
-
-        std::cout << "\t\t\t\t" << "value: " << m_rebootValue << std::endl;
+        m_reboot = value;
+        std::cout << "\t\t\t\t" << "m_reboot: " << m_reboot << std::endl;
     }
-}
-
-void DiagnosticsCollection::setStartCollectionRepresentation(OCRepresentation& rep)
-{
-    string value;
 
-    if (rep.getValue("value", value))
+    if (rep.getValue("ssc", value))
     {
-        m_startCollectionValue = value;
-
-        std::cout << "\t\t\t\t" << "value: " << m_startCollectionValue << std::endl;
+        m_startStatCollection = value;
+        std::cout << "\t\t\t\t" << "m_startStatCollection: " << m_startStatCollection << std::endl;
     }
 }
 
-OCRepresentation DiagnosticsCollection::getFactoryResetRepresentation()
-{
-    m_factoryResetRep.setValue("value", m_factoryResetValue);
-
-    return m_factoryResetRep;
-}
-
-OCRepresentation DiagnosticsCollection::getRebootRepresentation()
+OCRepresentation DiagnosticsResource::getDiagnosticsRepresentation()
 {
-    m_rebootRep.setValue("value", m_rebootValue);
-
-    return m_rebootRep;
-}
-
-OCRepresentation DiagnosticsCollection::getStartCollectionRepresentation()
-{
-    m_startCollectionRep.setValue("value", m_startCollectionValue);
-
-    return m_startCollectionRep;
-}
-
-OCRepresentation DiagnosticsCollection::getDiagnosticsRepresentation()
-{
-    m_diagnosticsRep.clearChildren();
-
-    m_diagnosticsRep.addChild(getFactoryResetRepresentation());
-    m_diagnosticsRep.addChild(getRebootRepresentation());
-    m_diagnosticsRep.addChild(getStartCollectionRepresentation());
-
-    m_diagnosticsRep.setValue("value", m_diagnosticsValue);
+    m_diagnosticsRep.setValue("fr", m_factoryReset);
+    m_diagnosticsRep.setValue("rb", m_reboot);
+    m_diagnosticsRep.setValue("ssc", m_startStatCollection);
 
     return m_diagnosticsRep;
 }
 
-std::string DiagnosticsCollection::getDiagnosticsUri()
+std::string DiagnosticsResource::getUri()
 {
     return m_diagnosticsUri;
 }
 
-std::string DiagnosticsCollection::getFactoryResetUri()
-{
-    return m_factoryResetUri;
-}
-
-std::string DiagnosticsCollection::getRebootUri()
-{
-    return m_rebootUri;
-}
-
-std::string DiagnosticsCollection::getStartCollectionUri()
-{
-    return m_startCollectionUri;
-}
-
-void DiagnosticsCollection::diagnosticsMonitor(int second)
+void DiagnosticsResource::diagnosticsMonitor(int second)
 {
     while (1)
     {
         sleep(second);
 
-        if (m_rebootValue == "true")
+        if (m_reboot == "true")
         {
             int res;
             std::cout << "Reboot will be soon..." << std::endl;
-            m_rebootValue = defaultReboot;
+            m_reboot = defaultReboot;
             res = system("sudo reboot"); // System reboot
 
             std::cout << "return: " << res << std::endl;
 
         }
-        else if (m_factoryResetValue == "true")
+        else if (m_factoryReset == "true")
         {
             std::cout << "Factory Reset will be soon..." << std::endl;
-            m_factoryResetValue = defaultFactoryReset;
+            m_factoryReset = defaultFactoryReset;
             factoryReset();
         }
     }
index df4c83e..27f91a4 100644 (file)
 
 using namespace OC;
 
-typedef std::function< OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+typedef std::function<
+    OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
 
-static std::string defaultDiagnosticsValue = "false";
 static std::string defaultFactoryReset = "false";
 static std::string defaultReboot = "false";
-static std::string defaultStartCollection = "false";
+static std::string defaultStartStatCollection = "false";
 
-class DiagnosticsCollection
+class DiagnosticsResource
 {
 public:
 
     // diagnostics members
     std::string m_diagnosticsUri;
-    std::string m_diagnosticsValue;
+    std::string m_factoryReset;
+    std::string m_reboot;
+    std::string m_startStatCollection;
     std::vector< std::string > m_diagnosticsTypes;
     std::vector< std::string > m_diagnosticsInterfaces;
     OCResourceHandle m_diagnosticsHandle;
     OCRepresentation m_diagnosticsRep;
 
-    // factory reset members
-    std::string m_factoryResetUri;
-    std::string m_factoryResetValue;
-    std::vector< std::string > m_factoryResetTypes;
-    std::vector< std::string > m_factoryResetInterfaces;
-    OCResourceHandle m_factoryResetHandle;
-    OCRepresentation m_factoryResetRep;
-
-    // reboot members
-    std::string m_rebootUri;
-    std::string m_rebootValue;
-    std::vector< std::string > m_rebootTypes;
-    std::vector< std::string > m_rebootInterfaces;
-    OCResourceHandle m_rebootHandle;
-    OCRepresentation m_rebootRep;
-
-    // startcollection members
-    std::string m_startCollectionUri;
-    std::string m_startCollectionValue;
-    std::vector< std::string > m_startCollectionTypes;
-    std::vector< std::string > m_startCollectionInterfaces;
-    OCResourceHandle m_startCollectionHandle;
-    OCRepresentation m_startCollectionRep;
-
 public:
     /// Constructor
-    DiagnosticsCollection() :
-            m_diagnosticsValue(defaultDiagnosticsValue), m_factoryResetValue(defaultFactoryReset), m_rebootValue(
-                    defaultReboot), m_startCollectionValue(defaultStartCollection)
+    DiagnosticsResource() :
+           m_factoryReset(defaultFactoryReset), m_reboot(defaultReboot),
+            m_startStatCollection(defaultStartStatCollection)
     {
-        m_factoryResetUri = "/oic/diag/0/factoryReset"; // URI of the resource
-        m_factoryResetTypes.push_back("oic.diag.factoryReset"); // resource type name.
-        m_factoryResetInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_factoryResetRep.setUri(m_factoryResetUri);
-        m_factoryResetRep.setResourceTypes(m_factoryResetTypes);
-        m_factoryResetRep.setResourceInterfaces(m_factoryResetInterfaces);
-        m_factoryResetRep.setValue("value", m_factoryResetValue);
-        m_factoryResetHandle = NULL;
-
-        m_rebootUri = "/oic/diag/0/reboot"; // URI of the resource
-        m_rebootTypes.push_back("oic.diag.reboot"); // resource type name.
-        m_rebootInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_rebootRep.setUri(m_rebootUri);
-        m_rebootRep.setResourceTypes(m_rebootTypes);
-        m_rebootRep.setResourceInterfaces(m_rebootInterfaces);
-        m_rebootRep.setValue("value", m_rebootValue);
-        m_rebootHandle = NULL;
-
-        m_startCollectionUri = "/oic/diag/0/startCollection"; // URI of the resource
-        m_startCollectionTypes.push_back("oic.diag.startCollection"); // resource type name.
-        m_startCollectionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_startCollectionRep.setUri(m_startCollectionUri);
-        m_startCollectionRep.setResourceTypes(m_startCollectionTypes);
-        m_startCollectionRep.setResourceInterfaces(m_startCollectionInterfaces);
-        m_startCollectionRep.setValue("value", m_startCollectionValue);
-        m_startCollectionHandle = NULL;
-
         m_diagnosticsUri = "/oic/diag"; // URI of the resource
         m_diagnosticsTypes.push_back("oic.diag"); // resource type name.
         m_diagnosticsInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_diagnosticsInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_diagnosticsInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_diagnosticsRep.setValue("value", m_diagnosticsValue);
+        m_diagnosticsRep.setValue("fr", m_factoryReset);
+        m_diagnosticsRep.setValue("rb", m_reboot);
+        m_diagnosticsRep.setValue("ssc", m_startStatCollection);
         m_diagnosticsRep.setUri(m_diagnosticsUri);
         m_diagnosticsRep.setResourceTypes(m_diagnosticsTypes);
         m_diagnosticsRep.setResourceInterfaces(m_diagnosticsInterfaces);
@@ -129,19 +77,10 @@ public:
     void createResources(ResourceEntityHandler callback);
 
     void setDiagnosticsRepresentation(OCRepresentation& rep);
-    void setFactoryResetRepresentation(OCRepresentation& rep);
-    void setRebootRepresentation(OCRepresentation& rep);
-    void setStartCollectionRepresentation(OCRepresentation& rep);
 
     OCRepresentation getDiagnosticsRepresentation();
-    OCRepresentation getFactoryResetRepresentation();
-    OCRepresentation getRebootRepresentation();
-    OCRepresentation getStartCollectionRepresentation();
-
-    std::string getDiagnosticsUri();
-    std::string getFactoryResetUri();
-    std::string getRebootUri();
-    std::string getStartCollectionUri();
+
+    std::string getUri();
 
     void diagnosticsMonitor(int second);
 
index d050096..36c4d93 100644 (file)
 
 using namespace OC;
 
+FactorySetResource::FactorySetResource()
+{
+    m_configurationUri = "/factorySet"; // URI of the resource
+    m_configurationTypes.clear();
+    m_configurationTypes.push_back("factorySet"); // resource type name.
+    m_configurationRep.setUri(m_configurationUri);
+    m_configurationRep.setResourceTypes(m_configurationTypes);
+}
+
+FactorySetResource::~FactorySetResource(){}
+
 /// This function internally calls registerResource API.
-void FactorySetCollection::createResources(ResourceEntityHandler callback)
+void FactorySetResource::createResources(ResourceEntityHandler callback)
 {
     using namespace OC::OCPlatform;
 
@@ -44,8 +55,8 @@ void FactorySetCollection::createResources(ResourceEntityHandler callback)
     }
 
     // This will internally create and register the resource.
-    OCStackResult result = registerResource(m_factorySetHandle, m_factorySetUri,
-            m_factorySetTypes[0], m_factorySetInterfaces[0], callback,
+    OCStackResult result = registerResource(m_configurationHandle, m_configurationUri,
+            m_configurationTypes[0], m_configurationInterfaces[0], callback,
             OC_DISCOVERABLE | OC_OBSERVABLE);
 
     if (OC_STACK_OK != result)
@@ -53,89 +64,49 @@ void FactorySetCollection::createResources(ResourceEntityHandler callback)
         std::cout << "Resource creation (configuration) was unsuccessful\n";
     }
 
-    result = bindInterfaceToResource(m_factorySetHandle, m_factorySetInterfaces[1]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
-
-    result = bindInterfaceToResource(m_factorySetHandle, m_factorySetInterfaces[2]);
-    if (OC_STACK_OK != result)
-    {
-        std::cout << "Binding TypeName to Resource was unsuccessful\n";
-    }
+    std::cout << "FactorySet Resource is Created!\n";
+}
 
-    result = registerResource(m_configurationCollectionHandle, m_configurationCollectionUri,
-            m_configurationCollectionTypes[0], m_configurationCollectionInterfaces[0], callback,
-            OC_DISCOVERABLE | OC_OBSERVABLE);
+void FactorySetResource::setFactorySetRepresentation(OCRepresentation& rep)
+{
+    string value;
 
-    if (OC_STACK_OK != result)
+    if (rep.getValue("loc", value))
     {
-        std::cout << "Resource creation (installedLocation) was unsuccessful\n";
+        m_location = value;
+        std::cout << "\t\t\t\t" << "m_location: " << m_location << std::endl;
     }
 
-    result = bindResource(m_factorySetHandle, m_configurationCollectionHandle);
-    if (OC_STACK_OK != result)
+    if (rep.getValue("st", value))
     {
-        std::cout << "Binding installedLocation resource to room was unsuccessful\n";
+        std::cout << "\t\t\t\t" << "SystemTime is not allowed to be written." << std::endl;
     }
 
-    defaultConfigurationCollection = new ConfigurationCollection(defaultConfigurationURIPrefix,
-            defaultConfigurationResourceTypePrefix);
-    //defaultConfigurationCollection->bindEntityHander(callback);
-    defaultConfigurationCollection->createResources(callback);
-
-    std::cout << "FactorySet Collection is Created!\n";
-}
-
-void FactorySetCollection::setFactorySetRepresentation(OCRepresentation& rep)
-{
-    string value;
-
-    if (rep.getValue("value", value))
+    if (rep.getValue("c", value))
     {
-        m_factorySetValue = value;
-
-        std::cout << "\t\t\t\t" << "m_factorySetValue: " << m_factorySetValue << std::endl;
+        m_currency = value;
+        std::cout << "\t\t\t\t" << "m_currency: " << m_currency << std::endl;
     }
-}
-
-void FactorySetCollection::setConfigurationCollectionRepresentation(OCRepresentation& rep)
-{
-    string value;
 
-    if (rep.getValue("link", value))
+    if (rep.getValue("r", value))
     {
-        // NOT ALLOWED
-
-        std::cout << "\t\t\t\t" << "link: " << m_configurationCollectionLink << std::endl;
+        m_region = value;
+        std::cout << "\t\t\t\t" << "m_region: " << m_region << std::endl;
     }
 }
 
-OCRepresentation FactorySetCollection::getConfigurationCollectionRepresentation()
+OCRepresentation FactorySetResource::getFactorySetRepresentation()
 {
-    m_configurationCollectionRep.setValue("link", m_configurationCollectionLink);
+    m_configurationRep.setValue("loc", m_location);
+    m_configurationRep.setValue("st", m_systemTime);
+    m_configurationRep.setValue("c", m_currency);
+    m_configurationRep.setValue("r", m_region);
 
-    return m_configurationCollectionRep;
+    return m_configurationRep;
 }
 
-OCRepresentation FactorySetCollection::getFactorySetRepresentation()
+std::string FactorySetResource::getUri()
 {
-    m_factorySetRep.clearChildren();
-
-    m_factorySetRep.addChild(getConfigurationCollectionRepresentation());
-
-    m_factorySetRep.setValue("value", m_factorySetValue);
-
-    return m_factorySetRep;
+    return m_configurationUri;
 }
 
-std::string FactorySetCollection::getFactorySetUri()
-{
-    return m_factorySetUri;
-}
-
-std::string FactorySetCollection::getConfigurationCollectionUri()
-{
-    return m_configurationCollectionUri;
-}
index bc20a71..15b5f3f 100644 (file)
 
 using namespace OC;
 
-typedef std::function< OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+typedef std::function<
+    OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
 
-extern std::string defaultFactorySetValue;
-static std::string defaultConfigurationCollectionLink = "/factorySet/oic/con";
-
-static std::string defaultConfigurationURIPrefix = "/factorySet/oic/con";
-static std::string defaultConfigurationResourceTypePrefix = "factorySet.oic.con";
-
-class FactorySetCollection
+class FactorySetResource : public ConfigurationResource
 {
 public:
-
-    ConfigurationCollection *defaultConfigurationCollection;
-
-public:
-
-    // diagnostics members
-    std::string m_factorySetUri;
-    std::string m_factorySetValue;
-    std::vector< std::string > m_factorySetTypes;
-    std::vector< std::string > m_factorySetInterfaces;
-    OCResourceHandle m_factorySetHandle;
-    OCRepresentation m_factorySetRep;
-
-    // Configuration members
-    std::string m_configurationCollectionUri;
-    std::string m_configurationCollectionLink;
-    std::vector< std::string > m_configurationCollectionTypes;
-    std::vector< std::string > m_configurationCollectionInterfaces;
-    OCResourceHandle m_configurationCollectionHandle;
-    OCRepresentation m_configurationCollectionRep;
-
-public:
     /// Constructor
-    FactorySetCollection() :
-            m_factorySetValue(defaultFactorySetValue), m_configurationCollectionLink(
-                    defaultConfigurationCollectionLink)
-    {
-        m_configurationCollectionUri = "/factorySet/0/con"; // URI of the resource
-        m_configurationCollectionTypes.push_back("factorySet.con"); // resource type name.
-        m_configurationCollectionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-
-        m_configurationCollectionRep.setUri(m_configurationCollectionUri);
-        m_configurationCollectionRep.setResourceTypes(m_configurationCollectionTypes);
-        m_configurationCollectionRep.setResourceInterfaces(m_configurationCollectionInterfaces);
-        m_configurationCollectionRep.setValue("link", m_configurationCollectionLink);
-        m_configurationCollectionHandle = NULL;
-
-        m_factorySetUri = "/factorySet"; // URI of the resource
-        m_factorySetTypes.push_back("factorySet"); // resource type name.
-        m_factorySetInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
-        m_factorySetInterfaces.push_back(BATCH_INTERFACE); // resource interface.
-        m_factorySetInterfaces.push_back(LINK_INTERFACE); // resource interface.
-        m_factorySetRep.setValue("value", m_factorySetValue);
-        m_factorySetRep.setUri(m_factorySetUri);
-        m_factorySetRep.setResourceTypes(m_factorySetTypes);
-        m_factorySetRep.setResourceInterfaces(m_factorySetInterfaces);
-        m_factorySetHandle = NULL;
-
-        defaultConfigurationCollection = NULL;
-    }
-    ;
+    FactorySetResource();
 
-    ~FactorySetCollection()
-    {
-        if (defaultConfigurationCollection != NULL)
-            free(defaultConfigurationCollection);
-    }
-    ;
+    ~FactorySetResource();
 
     /// This function internally calls registerResource API.
     void createResources(ResourceEntityHandler callback);
-
     void setFactorySetRepresentation(OCRepresentation& rep);
-    void setConfigurationCollectionRepresentation(OCRepresentation& rep);
-
     OCRepresentation getFactorySetRepresentation();
-    OCRepresentation getConfigurationCollectionRepresentation();
-
-    std::string getFactorySetUri();
-    std::string getConfigurationCollectionUri();
 
+    std::string getUri();
 };
 
index d4a8c5d..c3332ce 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
 ##
@@ -13,12 +33,22 @@ linux_sample_env = lib_env.Clone()
 # Build flags
 ######################################################################
 linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../../../extlibs/timer'])
 linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
 linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src'])
 linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack', 'libcoap', 'liboc_logger', 'dl', 'pthread'])
+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'])
+
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
 
 ######################################################################
 #build sampleapp
index e53f61c..a1548e6 100644 (file)
@@ -37,15 +37,11 @@ bool prepareResponse(std::shared_ptr< OCResourceRequest > request);
 OCStackResult sendResponse(std::shared_ptr< OCResourceRequest > pRequest);
 OCEntityHandlerResult entityHandlerBootstrap(std::shared_ptr< OCResourceRequest > request);
 
-#define DefaultConfigurationValue "Configuration Collection"
-#define DefaultRegionValue "Seoul, Korea"
-#define DefaultTimeValue "Time Collection"
-#define DefaultCurrentTimeValue "00:00:00"
-#define DefaultNetworkValue "Network Collection"
-#define DefaultIPAddressValue "192.168.0.2"
-#define DefaultSecurityValue "SecurityValue"
-#define DefaultModeValue "NoSec"
-#define DefaultFactorySetValue "FactorySet Value"
+#define DefaultRegion "Seoul, Korea"
+#define DefaultSystemTime "00:00:00"
+#define DefaultLocation "37.256616, 127.052806"
+#define DefaultCurrency "Won"
+
 
 class BootstrapResource
 {
@@ -92,15 +88,10 @@ public:
 
     OCRepresentation getBootstrapRepresentation()
     {
-        m_bootstrapRep.setValue< std::string >("regionValue", DefaultRegionValue);
-        m_bootstrapRep.setValue< std::string >("timeValue", DefaultTimeValue);
-        m_bootstrapRep.setValue< std::string >("currentTimeValue", DefaultCurrentTimeValue);
-        m_bootstrapRep.setValue< std::string >("networkValue", DefaultNetworkValue);
-        m_bootstrapRep.setValue< std::string >("IPAddressValue", DefaultIPAddressValue);
-        m_bootstrapRep.setValue< std::string >("securityValue", DefaultSecurityValue);
-        m_bootstrapRep.setValue< std::string >("modeValue", DefaultModeValue);
-        m_bootstrapRep.setValue< std::string >("configurationValue", DefaultConfigurationValue);
-        m_bootstrapRep.setValue< std::string >("factorySetValue", DefaultFactorySetValue);
+        m_bootstrapRep.setValue< std::string >("r", DefaultRegion);
+        m_bootstrapRep.setValue< std::string >("st", DefaultSystemTime);
+        m_bootstrapRep.setValue< std::string >("loc", DefaultLocation);
+        m_bootstrapRep.setValue< std::string >("c", DefaultCurrency);
 
         return m_bootstrapRep;
     }
@@ -120,13 +111,7 @@ bool prepareResponse(std::shared_ptr< OCResourceRequest > request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if (requestFlag == RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        if (requestFlag == RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
 
index 278c3e2..fddc87c 100644 (file)
@@ -34,6 +34,9 @@ using namespace OIC;
 
 int g_Steps = 0;
 int isWaiting = 0; //0: none to wait, 1: wait for the response of "getConfigurationValue"
+pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER;
+
+const int SUCCESS_RESPONSE = 0;
 
 static ThingsManager* g_thingsmanager;
 
@@ -62,61 +65,94 @@ typedef std::function<
 typedef std::string ConfigurationName;
 typedef std::string ConfigurationValue;
 
+void timeCheck(int timeSec)
+{
+    sleep(timeSec);
+    pthread_mutex_lock(&mutex_lock);
+    isWaiting = 0;
+    pthread_mutex_unlock(&mutex_lock);
+}
+
 void onReboot(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+    pthread_mutex_lock(&mutex_lock);
+    isWaiting = 0;
+    pthread_mutex_unlock(&mutex_lock);
 
-    std::cout << "\t\tReboot:" << rep.getValue< std::string >("value") << std::endl;
+    if (eCode != SUCCESS_RESPONSE)
+    {
+        return ;
+    }
 
-    isWaiting = 0;
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+    std::cout << "\t\tReboot:" << rep.getValue< std::string >("value") << std::endl;
 }
 
 void onFactoryReset(const HeaderOptions& headerOptions, const OCRepresentation& rep,
         const int eCode)
 {
-    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+    pthread_mutex_lock(&mutex_lock);
+    isWaiting = 0;
+    pthread_mutex_unlock(&mutex_lock);
 
+    if (eCode != SUCCESS_RESPONSE)
+    {
+       return ;
+    }
+
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
     std::cout << "\t\tFactoryReset:" << rep.getValue< std::string >("value") << std::endl;
-    isWaiting = 0;
 }
 
 void onUpdate(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+    pthread_mutex_lock(&mutex_lock);
+    isWaiting = 0;
+    pthread_mutex_unlock(&mutex_lock);
 
-    std::cout << "\t\tvalue:" << rep.getValue< std::string >("value") << std::endl;
+    if (eCode != SUCCESS_RESPONSE)
+    {
+        return ;
+    }
 
-    isWaiting = 0;
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    if (rep.hasAttribute("loc"))
+        std::cout << "\t\tLocation:" << rep.getValue< std::string >("loc") << std::endl;
+    if (rep.hasAttribute("st"))
+        std::cout << "\t\tSystemTime:" << rep.getValue< std::string >("st") << std::endl;
+    if (rep.hasAttribute("c"))
+        std::cout << "\t\tCurrency:" << rep.getValue< std::string >("c") << std::endl;
+    if (rep.hasAttribute("r"))
+        std::cout << "\t\tRegion:" << rep.getValue< std::string >("r") << std::endl;
 }
 
 void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
-
-    if (rep.hasAttribute("value"))
-        std::cout << "\t\tvalue:" << rep.getValue< std::string >("value") << std::endl;
-    else if (rep.hasAttribute("link"))
-        std::cout << "\t\tlink:" << rep.getValue< std::string >("link") << std::endl;
-
-    std::vector< OCRepresentation > children = rep.getChildren();
+    pthread_mutex_lock(&mutex_lock);
+    isWaiting = 0;
+    pthread_mutex_unlock(&mutex_lock);
 
-    for (auto oit = children.begin(); oit != children.end(); ++oit)
+    if (eCode != SUCCESS_RESPONSE)
     {
-        std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
-
-        if (oit->hasAttribute("value"))
-            std::cout << "\t\tvalue:" << oit->getValue< std::string >("value") << std::endl;
-        else if (oit->hasAttribute("link"))
-            std::cout << "\t\tlink:" << oit->getValue< std::string >("link") << std::endl;
+        return ;
     }
 
-    isWaiting = 0;
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    if (rep.hasAttribute("loc"))
+        std::cout << "\t\tLocation:" << rep.getValue< std::string >("loc") << std::endl;
+    if (rep.hasAttribute("st"))
+        std::cout << "\t\tSystemTime:" << rep.getValue< std::string >("st") << std::endl;
+    if (rep.hasAttribute("c"))
+        std::cout << "\t\tCurrency:" << rep.getValue< std::string >("c") << std::endl;
+    if (rep.hasAttribute("r"))
+        std::cout << "\t\tRegion:" << rep.getValue< std::string >("r") << std::endl;
 }
 
 // Callback to found collection resource
 void onFoundCollectionResource(std::vector< std::shared_ptr< OCResource > > resources)
 {
-
     std::string resourceURI;
     std::string hostAddress;
     try
@@ -136,7 +172,9 @@ void onFoundCollectionResource(std::vector< std::shared_ptr< OCResource > > reso
                     g_setCollection = resource;
                 else
                 {
+                    pthread_mutex_lock(&mutex_lock);
                     isWaiting = 0;
+                    pthread_mutex_unlock(&mutex_lock);
                     return;
                 }
             }
@@ -150,23 +188,18 @@ void onFoundCollectionResource(std::vector< std::shared_ptr< OCResource > > reso
     }
     catch (std::exception& e)
     {
-        //log(e.what());
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 
-    if (g_configurationCollection != NULL && g_diagnosticsCollection != NULL
-            && g_setCollection != NULL)
-        isWaiting = 0;
+    isWaiting = 0;
 }
 
 // Callback to found resources
-void onFoundCandidateCollection(std::vector< std::shared_ptr< OCResource > > resources)
+void onFoundCandidateResource(std::vector< std::shared_ptr< OCResource > > resources)
 {
-
     std::string resourceURI;
     std::string hostAddress;
 
-    static bool flagForCon = false, flagForDiag = false, flagForSet = false;
-
     try
     {
         // Do some operations with resource object.
@@ -194,7 +227,6 @@ void onFoundCandidateCollection(std::vector< std::shared_ptr< OCResource > > res
                     {
                         if (resource->uri() == "/oic/con")
                         {
-                            flagForCon = true;
                             OCPlatform::bindResource(configurationCollectionHandle,
                                     foundResourceHandle);
                             if (g_configurationResource == NULL)
@@ -202,7 +234,6 @@ void onFoundCandidateCollection(std::vector< std::shared_ptr< OCResource > > res
                         }
                         else if (resource->uri() == "/oic/diag")
                         {
-                            flagForDiag = true;
                             OCPlatform::bindResource(diagnosticsCollectionHandle,
                                     foundResourceHandle);
                             if (g_diagnosticsResource == NULL)
@@ -210,7 +241,6 @@ void onFoundCandidateCollection(std::vector< std::shared_ptr< OCResource > > res
                         }
                         else if (resource->uri() == "/factorySet")
                         {
-                            flagForSet = true;
                             OCPlatform::bindResource(setCollectionHandle, foundResourceHandle);
                             if (g_setResource == NULL)
                                 g_setResource = resource;
@@ -236,212 +266,250 @@ void onFoundCandidateCollection(std::vector< std::shared_ptr< OCResource > > res
     }
     catch (std::exception& e)
     {
-        //log(e.what());
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 
-    if (flagForCon && flagForDiag && flagForSet)
-        isWaiting = 0;
+    pthread_mutex_lock(&mutex_lock);
+    isWaiting = 0;
+    pthread_mutex_unlock(&mutex_lock);
 }
 
 int main(int argc, char* argv[])
 {
+    std::string str_steps;
 
-    //**************************************************************
-    // STEP 0
-    PlatformConfig cfg
-    { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
-
-    OCPlatform::Configure(cfg);
-    g_thingsmanager = new ThingsManager();
+    try
+    {
+        //**************************************************************
+        // STEP 0
+        PlatformConfig cfg
+        { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
 
-    //**************************************************************
+        OCPlatform::Configure(cfg);
+        g_thingsmanager = new ThingsManager();
 
-    while (true)
-    {
+        //**************************************************************
 
-        if (isWaiting > 0)
-            continue;
-
-        isWaiting = 0;
-
-        cout << endl << endl << "(0) Quit" << std::endl;
-        cout << "(1) Find all resources(URI: /oic/con, /oic/diag, /factoryset)" << std::endl;
-        cout << "(2) Find all groups" << std::endl;
-        cout << "(3) Get a new value (of \"Configuration\" Collection)" << std::endl;
-        cout << "(4) Update a value (of \"Region\" Resource)" << std::endl;
-        cout << "(5) Get a value (for \"Region\" Resource)" << std::endl;
-        cout << "(6) FactoryReset (for the group)" << std::endl;
-        cout << "(7) Reboot (for the group)" << std::endl;
-        cout << "(10) Show Configuration Units" << std::endl;
-
-        cin >> g_Steps;
-        //
-        if (g_Steps == 0)
-            break;
-        else if (g_Steps == 1)
+        while (true)
         {
-            std::vector< std::string > types;
-            { // For Registering a collection resource for configuration resources
+            pthread_mutex_lock(&mutex_lock);
+            if (isWaiting > 0)
+            {
+                pthread_mutex_unlock(&mutex_lock);
+                continue;
+            }
 
-                string resourceURI = "/core/a/configuration/resourceset";
-                string resourceTypeName = "core.configuration.resourceset";
-                string resourceInterface = BATCH_INTERFACE;
+            isWaiting = 0;
+            pthread_mutex_unlock(&mutex_lock);
 
-                if (configurationCollectionHandle != NULL)
+            cout << endl << endl << "(0) Quit" << std::endl;
+            cout << "(1) Find all resources(URI: /oic/con, /oic/diag, /factoryset)" << std::endl;
+            cout << "(2) Find all groups" << std::endl;
+            cout << "(3) Get a Configuration resource" << std::endl;
+            cout << "(4) Update a region attribute value" << std::endl;
+            cout << "(5) FactoryReset (for the group)" << std::endl;
+            cout << "(6) Reboot (for the group)" << std::endl;
+            cout << "(10) Show Configuration Units" << std::endl;
+
+            try
+            {
+                std::getline (std::cin, str_steps);
+
+                if(str_steps == "")
                 {
-                    std::cout << "already exists" << std::endl;
                     continue;
                 }
+                else
+                {
+                    g_Steps = std::stoi(str_steps);
+                }
+            }
+            catch(std::invalid_argument&)
+            {
+                std::cout << "Please put a digit, not string" << std::endl;
+                continue;
+            }
 
-                OCPlatform::registerResource(configurationCollectionHandle, resourceURI,
+            if (g_Steps == 0)
+            {
+                break;
+            }
+            else if (g_Steps == 1)
+            {
+                std::vector< std::string > types;
+
+                // For Registering a collection resource for configuration resources
+                if (configurationCollectionHandle == NULL)
+                {
+                    string resourceURI = "/core/a/configuration/resourceset";
+                    string resourceTypeName = "core.configuration.resourceset";
+                    string resourceInterface = BATCH_INTERFACE;
+
+                    OCPlatform::registerResource(configurationCollectionHandle, resourceURI,
                         resourceTypeName, resourceInterface, NULL,
                         //&entityHandler, // entityHandler
                         OC_DISCOVERABLE);
 
-                OCPlatform::bindInterfaceToResource(configurationCollectionHandle, GROUP_INTERFACE);
-                OCPlatform::bindInterfaceToResource(configurationCollectionHandle,
+                    OCPlatform::bindInterfaceToResource(configurationCollectionHandle, GROUP_INTERFACE);
+                    OCPlatform::bindInterfaceToResource(configurationCollectionHandle,
                         DEFAULT_INTERFACE);
+                }
 
-                // instead of registration
-                types.push_back("oic.con");
-                std::cout << "Finding Configuration Resource... " << std::endl;
-            }
-
-            { // For Registering a collection resource for diagnostics resources
-
-                string resourceURI = "/core/a/diagnostics/resourceset";
-                string resourceTypeName = "core.diagnostics.resourceset";
-                string resourceInterface = BATCH_INTERFACE;
-
-                if (diagnosticsCollectionHandle != NULL)
+                // For Registering a collection resource for diagnostics resources
+                if (diagnosticsCollectionHandle == NULL)
                 {
-                    std::cout << "already exists" << std::endl;
-                    continue;
-                }
+                    string resourceURI = "/core/a/diagnostics/resourceset";
+                    string resourceTypeName = "core.diagnostics.resourceset";
+                    string resourceInterface = BATCH_INTERFACE;
 
-                OCPlatform::registerResource(diagnosticsCollectionHandle, resourceURI,
+                    OCPlatform::registerResource(diagnosticsCollectionHandle, resourceURI,
                         resourceTypeName, resourceInterface, NULL,
                         //&entityHandler, // entityHandler
                         OC_DISCOVERABLE);
 
-                OCPlatform::bindInterfaceToResource(diagnosticsCollectionHandle, GROUP_INTERFACE);
-                OCPlatform::bindInterfaceToResource(diagnosticsCollectionHandle, DEFAULT_INTERFACE);
-
-                // instead of registration
-                types.push_back("oic.diag");
-                std::cout << "Finding Diagnostics Resource... " << std::endl;
-
-            }
-
-            { // For Registering a collection resource for set resources
-
-                string resourceURI = "/core/a/factoryset/resourceset";
-                string resourceTypeName = "core.factoryset.resourceset";
-                string resourceInterface = BATCH_INTERFACE;
+                    OCPlatform::bindInterfaceToResource(diagnosticsCollectionHandle, GROUP_INTERFACE);
+                    OCPlatform::bindInterfaceToResource(diagnosticsCollectionHandle, DEFAULT_INTERFACE);
+                }
 
-                if (setCollectionHandle != NULL)
+                // For Registering a collection resource for set resources
+                if (setCollectionHandle == NULL)
                 {
-                    std::cout << "already exists" << std::endl;
-                    continue;
-                }
+                    string resourceURI = "/core/a/factoryset/resourceset";
+                    string resourceTypeName = "core.factoryset.resourceset";
+                    string resourceInterface = BATCH_INTERFACE;
 
-                OCPlatform::registerResource(setCollectionHandle, resourceURI, resourceTypeName,
+                    OCPlatform::registerResource(setCollectionHandle, resourceURI, resourceTypeName,
                         resourceInterface, NULL,
                         //&entityHandler, // entityHandler
                         OC_DISCOVERABLE);
 
-                OCPlatform::bindInterfaceToResource(setCollectionHandle, GROUP_INTERFACE);
-                OCPlatform::bindInterfaceToResource(setCollectionHandle, DEFAULT_INTERFACE);
+                    OCPlatform::bindInterfaceToResource(setCollectionHandle, GROUP_INTERFACE);
+                    OCPlatform::bindInterfaceToResource(setCollectionHandle, DEFAULT_INTERFACE);
+                }
 
-                // instead of registration
+                types.push_back("oic.con");
+                types.push_back("oic.diag");
                 types.push_back("factorySet");
-                std::cout << "Finding Set Resource... " << std::endl;
-            }
 
-            g_thingsmanager->findCandidateResources(types, &onFoundCandidateCollection, 5);
+                std::cout << "Finding Configuration Resource... " << std::endl;
+                std::cout << "Finding Diagnostics Resource... " << std::endl;
+                std::cout << "Finding Set Resource... " << std::endl;
 
-            isWaiting = 1;
-        }
-        else if (g_Steps == 2) // make a group with found things
-        {
-            std::vector< std::string > types;
-            types.push_back("core.configuration.resourceset");
-            types.push_back("core.diagnostics.resourceset");
-            types.push_back("core.factoryset.resourceset");
+                g_thingsmanager->findCandidateResources(types, &onFoundCandidateResource, 5);
 
-            g_thingsmanager->findCandidateResources(types, &onFoundCollectionResource, 5);
+                pthread_mutex_lock(&mutex_lock);
+                isWaiting = 1;
+                pthread_mutex_unlock(&mutex_lock);
 
-            std::cout << "Finding Collection resource... " << std::endl;
-            isWaiting = 1;
+                thread t(&timeCheck, 5);
+                t.join();       // After 5 seconds, isWaiting value will be 0.
+            }
+            else if (g_Steps == 2) // make a group with found things
+            {
+                std::vector< std::string > types;
+                types.push_back("core.configuration.resourceset");
+                types.push_back("core.diagnostics.resourceset");
+                types.push_back("core.factoryset.resourceset");
 
-        }
-        else if (g_Steps == 3)
-        {
-            // get a value
+                g_thingsmanager->findCandidateResources(types, &onFoundCollectionResource, 5);
 
-            ConfigurationName name = "configuration";
+                std::cout << "Finding Collection resource... " << std::endl;
+                
+                pthread_mutex_lock(&mutex_lock);
+                isWaiting = 1;
+                pthread_mutex_unlock(&mutex_lock);
 
-            std::cout << "For example, get configuration collection's value" << std::endl;
+                thread t(&timeCheck, 5);
+                t.join();       // After 5 seconds, isWaiting value will be 0.
+            }
+            else if (g_Steps == 3)
+            {
+                // get a value
 
-            std::vector< ConfigurationName > configurations;
+                ConfigurationName name = "all";
 
-            configurations.push_back(name);
+                std::cout << "For example, get configuration resources's value" << std::endl;
 
-            if (g_thingsmanager->getConfigurations(g_configurationResource, configurations, &onGet)
-                    != OC_STACK_ERROR)
-                isWaiting = 1;
-        }
-        else if (g_Steps == 4)
-        {
-            ConfigurationName name = "region";
-            ConfigurationValue value = "U.S.A (new region)";
+                std::vector< ConfigurationName > configurations;
 
-            std::cout << "For example, change region resource's value" << std::endl;
-            std::cout << g_configurationCollection->uri() << std::endl;
+                configurations.push_back(name);
 
-            std::map< ConfigurationName, ConfigurationValue > configurations;
+                if (g_thingsmanager->getConfigurations(g_configurationCollection, configurations, &onGet)
+                        != OC_STACK_ERROR)
+                {
+                    pthread_mutex_lock(&mutex_lock);
+                    isWaiting = 0;
+                    pthread_mutex_unlock(&mutex_lock);
+                }
+            }
+            else if (g_Steps == 4)
+            {
+                ConfigurationName name = "r";
+                ConfigurationValue value = "U.S.A (new region)";
 
-            configurations.insert(std::make_pair(name, value));
+                if(g_configurationCollection == NULL)
+                {
+                    std::cout<<"Note that you first create a group to use this command." << std::endl;
+                    continue;
+                }
 
-            if (g_thingsmanager->updateConfigurations(g_configurationCollection, configurations,
-                    &onUpdate) != OC_STACK_ERROR)
-                isWaiting = 1;
-        }
-        else if (g_Steps == 5)
-        {
-            // get a value
+                std::cout << "For example, change region resource's value" << std::endl;
+                std::cout << g_configurationCollection->uri() << std::endl;
 
-            ConfigurationName name = "region";
+                std::map< ConfigurationName, ConfigurationValue > configurations;
 
-            std::cout << "For example, get region resource's value" << std::endl;
+                configurations.insert(std::make_pair(name, value));
 
-            std::vector< ConfigurationName > configurations;
+                if (g_thingsmanager->updateConfigurations(g_configurationCollection, configurations,
+                        &onUpdate) != OC_STACK_ERROR)
+                {
+                    pthread_mutex_lock(&mutex_lock);
+                    isWaiting = 0;
+                    pthread_mutex_unlock(&mutex_lock);
+                }
+            }
+            else if (g_Steps == 5)
+            {
+                // factory reset
+                if(g_diagnosticsCollection == NULL)
+                {
+                    std::cout<<"Note that you first create a group to use this command." << std::endl;
+                    continue;
+                }
 
-            configurations.push_back(name);
+                if (g_thingsmanager->factoryReset(g_diagnosticsCollection, &onFactoryReset)
+                        != OC_STACK_ERROR)
+                {
+                    pthread_mutex_lock(&mutex_lock);
+                    isWaiting = 0;
+                    pthread_mutex_unlock(&mutex_lock);
+                }
+            }
+            else if (g_Steps == 6)
+            {
+                // reboot
+                if(g_diagnosticsCollection == NULL)
+                {
+                    std::cout<<"Note that you first create a group to use this command." << std::endl;
+                    continue;
+                }
 
-            if (g_thingsmanager->getConfigurations(g_configurationCollection, configurations,
-                    &onGet) != OC_STACK_ERROR)
-                isWaiting = 1;
-        }
-        else if (g_Steps == 6)
-        {
-            // factory reset
-            if (g_thingsmanager->factoryReset(g_diagnosticsCollection, &onFactoryReset)
-                    != OC_STACK_ERROR)
-                isWaiting = 1;
-        }
-        else if (g_Steps == 7)
-        {
-            // reboot
-            if (g_thingsmanager->reboot(g_diagnosticsCollection, &onReboot) != OC_STACK_ERROR)
-                isWaiting = 1;
-        }
-        else if (g_Steps == 10)
-        {
-            std::cout << g_thingsmanager->getListOfSupportedConfigurationUnits() << std::endl;
+                if (g_thingsmanager->reboot(g_diagnosticsCollection, &onReboot) != OC_STACK_ERROR)
+                {
+                    pthread_mutex_lock(&mutex_lock);
+                    isWaiting = 0;
+                    pthread_mutex_unlock(&mutex_lock);
+                }
+            }
+            else if (g_Steps == 10)
+            {
+                std::cout << g_thingsmanager->getListOfSupportedConfigurationUnits() << std::endl;
 
+            }
         }
-
+    }catch (OCException e)
+    {
+        std::cout << "Exception in main: " << e.what();
     }
 
     return 0;
old mode 100755 (executable)
new mode 100644 (file)
index c83c7a0..f609adb
@@ -23,7 +23,7 @@
 ///
 
 #include <functional>
-#include <thread>
+#include <pthread.h>
 
 #include "OCPlatform.h"
 #include "OCApi.h"
@@ -38,19 +38,15 @@ using namespace OIC;
 const int SUCCESS_RESPONSE = 0;
 int g_Steps = 0;
 int isWaiting = 0;
+pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER;
 
 // Default system configuration value's variables
 // The variable's names should be same as the names of "extern" variables defined in
-// "ConfigurationCollection.h"
-std::string defaultRegionValue;
-std::string defaultTimeValue;
-std::string defaultCurrentTimeValue;
-std::string defaultNetworkValue;
-std::string defaultIPAddressValue;
-std::string defaultSecurityValue;
-std::string defaultModeValue;
-std::string defaultConfigurationValue;
-std::string defaultFactorySetValue;
+// "ConfigurationResource.h"
+std::string defaultLocation;
+std::string defaultRegion;
+std::string defaultSystemTime;
+std::string defaultCurrency;
 
 static ThingsManager* g_thingsmanager;
 
@@ -59,9 +55,9 @@ bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request);
 OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest);
 OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request);
 
-ConfigurationCollection *myConfigurationCollection;
-DiagnosticsCollection *myDiagnosticsCollection;
-FactorySetCollection *myFactorySetCollection;
+ConfigurationResource *myConfigurationResource;
+DiagnosticsResource *myDiagnosticsResource;
+FactorySetResource *myFactorySetResource;
 
 typedef std::function< void(OCRepresentation&) > putFunc;
 typedef std::function< OCRepresentation(void) > getFunc;
@@ -70,33 +66,15 @@ getFunc getGetFunction(std::string uri)
 {
     getFunc res = NULL;
 
-    if (uri == myConfigurationCollection->getTimeUri())
+    if (uri == myConfigurationResource->getUri())
     {
-        res = std::bind(&ConfigurationCollection::getTimeRepresentation, myConfigurationCollection);
+        res = std::bind(&ConfigurationResource::getConfigurationRepresentation,
+                myConfigurationResource);
     }
-    else if (uri == myConfigurationCollection->getConfigurationUri())
+    else if (uri == myDiagnosticsResource->getUri())
     {
-        res = std::bind(&ConfigurationCollection::getConfigurationRepresentation,
-                myConfigurationCollection);
-    }
-    else if (uri == myConfigurationCollection->myTimeCollection->getCurrentTimeUri())
-    {
-        res = std::bind(&TimeCollection::getCurrentTimeRepresentation,
-                myConfigurationCollection->myTimeCollection);
-    }
-    else if (uri == myConfigurationCollection->getRegionUri())
-    {
-        res = std::bind(&ConfigurationCollection::getRegionRepresentation,
-                myConfigurationCollection);
-    }
-    else if (uri == myDiagnosticsCollection->getFactoryResetUri())
-    {
-        res = std::bind(&DiagnosticsCollection::getFactoryResetRepresentation,
-                myDiagnosticsCollection);
-    }
-    else if (uri == myDiagnosticsCollection->getRebootUri())
-    {
-        res = std::bind(&DiagnosticsCollection::getRebootRepresentation, myDiagnosticsCollection);
+        res = std::bind(&DiagnosticsResource::getDiagnosticsRepresentation,
+                myDiagnosticsResource);
     }
 
     return res;
@@ -106,25 +84,15 @@ putFunc getPutFunction(std::string uri)
 {
     putFunc res = NULL;
 
-    if (uri == myConfigurationCollection->getRegionUri())
+    if (uri == myConfigurationResource->getUri())
     {
-        res = std::bind(&ConfigurationCollection::setRegionRepresentation,
-                myConfigurationCollection, std::placeholders::_1);
+        res = std::bind(&ConfigurationResource::setConfigurationRepresentation,
+                myConfigurationResource, std::placeholders::_1);
     }
-    else if (uri == myConfigurationCollection->myTimeCollection->getCurrentTimeUri())
+    else if (uri == myDiagnosticsResource->getUri())
     {
-        res = std::bind(&TimeCollection::setCurrentTimeRepresentation,
-                myConfigurationCollection->myTimeCollection, std::placeholders::_1);
-    }
-    else if (uri == myDiagnosticsCollection->getFactoryResetUri())
-    {
-        res = std::bind(&DiagnosticsCollection::setFactoryResetRepresentation,
-                myDiagnosticsCollection, std::placeholders::_1);
-    }
-    else if (uri == myDiagnosticsCollection->getRebootUri())
-    {
-        res = std::bind(&DiagnosticsCollection::setRebootRepresentation, myDiagnosticsCollection,
-                std::placeholders::_1);
+        res = std::bind(&DiagnosticsResource::setDiagnosticsRepresentation,
+                myDiagnosticsResource, std::placeholders::_1);
     }
 
     return res;
@@ -141,13 +109,7 @@ bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if (requestFlag == RequestHandlerFlag::InitFlag)
-        {
-            std::cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        if (requestFlag == RequestHandlerFlag::RequestFlag)
         {
             std::cout << "\t\trequestFlag : Request\n";
 
@@ -231,6 +193,8 @@ OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceReques
     std::cout << "\tIn Server CPP (entityHandlerForResource) entity handler:\n";
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
 
+    QueryParamsMap test = request->getQueryParameters();
+
     if (prepareResponseForResource(request))
     {
         if (OC_STACK_OK == sendResponseForResource(request))
@@ -252,38 +216,29 @@ OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceReques
 // callback handler on GET request
 void onBootstrap(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
 {
-    if (eCode == SUCCESS_RESPONSE)
-    {
-        std::cout << "\n\nGET request was successful" << std::endl;
-        std::cout << "\tResource URI: " << rep.getUri() << std::endl;
-
-        defaultRegionValue = rep.getValue< std::string >("regionValue");
-        defaultTimeValue = rep.getValue< std::string >("timeValue");
-        defaultCurrentTimeValue = rep.getValue< std::string >("currentTimeValue");
-        defaultNetworkValue = rep.getValue< std::string >("networkValue");
-        defaultIPAddressValue = rep.getValue< std::string >("IPAddressValue");
-        defaultSecurityValue = rep.getValue< std::string >("securityValue");
-        defaultModeValue = rep.getValue< std::string >("modeValue");
-        defaultConfigurationValue = rep.getValue< std::string >("configurationValue");
-        defaultFactorySetValue = rep.getValue< std::string >("factorySetValue");
-
-        std::cout << "\tregionValue : " << defaultRegionValue << std::endl;
-        std::cout << "\ttimeValue : " << defaultTimeValue << std::endl;
-        std::cout << "\tcurrentTimeValue : " << defaultCurrentTimeValue << std::endl;
-        std::cout << "\tnetworkValue : " << defaultNetworkValue << std::endl;
-        std::cout << "\tIPAddressValue : " << defaultIPAddressValue << std::endl;
-        std::cout << "\tsecurityValue : " << defaultSecurityValue << std::endl;
-        std::cout << "\tmodeValue : " << defaultModeValue << std::endl;
-        std::cout << "\tconfigurationValue : " << defaultConfigurationValue << std::endl;
-        std::cout << "\tfactorySetValue : " << defaultFactorySetValue << std::endl;
+    pthread_mutex_lock(&mutex_lock);
+    isWaiting = 0;
+    pthread_mutex_unlock(&mutex_lock);
 
-    }
-    else
+    if (eCode != SUCCESS_RESPONSE)
     {
         std::cout << "onGET Response error: " << eCode << std::endl;
-        std::exit(-1);
+        return ;
     }
-    isWaiting = 0;
+
+    std::cout << "\n\nGET request was successful" << std::endl;
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    defaultRegion = rep.getValue< std::string >("r");
+    defaultSystemTime = rep.getValue< std::string >("st");
+    defaultCurrency = rep.getValue< std::string >("c");
+    defaultLocation = rep.getValue< std::string >("loc");
+
+    std::cout << "\tLocation : " << defaultLocation << std::endl;
+    std::cout << "\tSystemTime : " << defaultSystemTime << std::endl;
+    std::cout << "\tCurrency : " << defaultCurrency << std::endl;
+    std::cout << "\tRegion : " << defaultRegion << std::endl;
+
 }
 
 int main()
@@ -309,41 +264,57 @@ int main()
         // Perform app tasks
         while (true)
         {
-
+            pthread_mutex_lock(&mutex_lock);
             if (isWaiting > 0)
+            {
+                pthread_mutex_unlock(&mutex_lock);
                 continue;
+            }
 
             isWaiting = 0;
+            pthread_mutex_unlock(&mutex_lock);
 
             std::cout << endl << endl << "(0) Quit" << std::endl;
             std::cout << "(1) Bootstrap" << std::endl;
             std::cout << "(2) Create Configuration Resources" << std::endl;
 
             cin >> g_Steps;
-            //
+
             if (g_Steps == 0)
+            {
                 break;
+            }
             else if (g_Steps == 1)
             {
                 if( g_thingsmanager->doBootstrap(&onBootstrap) == OC_STACK_OK)
+                {
+                    pthread_mutex_lock(&mutex_lock);
                     isWaiting = 1;
+                    pthread_mutex_unlock(&mutex_lock);
+                }
                 else
+                {
                     std::cout << "A callback pointer of the function is NULL." << std::endl;
+                }
             }
             else if (g_Steps == 2)
             {
-                myConfigurationCollection = new ConfigurationCollection();
-                myConfigurationCollection->createResources(&entityHandlerForResource);
+                myConfigurationResource = new ConfigurationResource();
+                myConfigurationResource->createResources(&entityHandlerForResource);
+
+                myDiagnosticsResource = new DiagnosticsResource();
+                myDiagnosticsResource->createResources(&entityHandlerForResource);
+
 
-                myDiagnosticsCollection = new DiagnosticsCollection();
-                myDiagnosticsCollection->createResources(&entityHandlerForResource);
+                myFactorySetResource = new FactorySetResource();
+                myFactorySetResource->createResources(&entityHandlerForResource);
+                myDiagnosticsResource->factoryReset = std::function < void()
+                        > (std::bind(&ConfigurationResource::factoryReset,
+                                myConfigurationResource));
 
-                myFactorySetCollection = new FactorySetCollection();
-                myFactorySetCollection->createResources(&entityHandlerForResource);
-                myDiagnosticsCollection->factoryReset = std::function < void()
-                        > (std::bind(&ConfigurationCollection::factoryReset,
-                                myConfigurationCollection));
+                pthread_mutex_lock(&mutex_lock);
                 isWaiting = 1;
+                pthread_mutex_unlock(&mutex_lock);
             }
         }
     }
@@ -354,5 +325,6 @@ int main()
 
     // No explicit call to stop the platform.
     // When OCPlatform destructor is invoked, internally we do platform cleanup
+    return 0;
 }
 
diff --git a/service/things-manager/sampleapp/linux/configuration/makefile b/service/things-manager/sampleapp/linux/configuration/makefile
deleted file mode 100644 (file)
index 37824a9..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-TGMROOT=../../../
-IOT_BASE=${TGMROOT}../../resource
-RST_NAME=.
-TARGET1=con-server
-TARGET2=con-client
-TARGET3=bootstrapserver
-
-OBJS = ConfigurationCollection.o DiagnosticsCollection.o FactorySetCollection.o con-server.o
-SRCS = $(OBJS:.o=.c)
-
-# C++ type Compile Flag define.
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
-
-CXX_INC        := -I../../ -I../../inc/ -I../../../sdk/inc/ -I../../../sdk/src/
-CXX_INC        += -I${IOT_BASE}/include/
-CXX_INC        += -I${IOT_BASE}/oc_logger/include
-CXX_INC        += -I${IOT_BASE}/csdk/stack/include
-CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include
-CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include
-CXX_INC        += -I${IOT_BASE}/csdk/logger/include
-CXX_INC        += -I${IOT_BASE}/dependencies/cereal/include
-
-CXX_LIB=-L""
-
-CXX_SRCPATH=${wildcard ../../src/*.cpp}
-CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
-CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
-CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
-
-
-TGM = ../../
-SDK = ${TGMROOT}sdk
-TGM_INC = -I${TGMROOT}sdk/inc
-SDK_LIB = ${TGMROOT}sdk/build/linux/libTGMSDKLibrary.a
-
-LIB_OC_LOGGER := $(IOT_BASE)/oc_logger/lib/oc_logger.a
-
-LD_LIB := $(IOT_BASE)/release/obj/liboc.a
-LD_LIB += $(IOT_BASE)/csdk/linux/release/liboctbstack.a
-LD_LIB += $(LIB_OC_LOGGER)
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: ${TARGET1} ${TARGET2} ${TARGET3}
-
-.cpp.o:
-       $(CXX) $(CXX_FLAGS) -c -o $@ $<  $(CXX_INC)  $(TGM_INC)
-
-$(TARGET1): $(OBJS)
-       $(CXX) $(CXX_FLAGS) -o $@ ${OBJS} $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-${TARGET2}: con-client.cpp
-       $(CXX) $(CXX_FLAGS) -o ${TARGET2} $<  $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-${TARGET3}: bootstrapserver.cpp
-       $(CXX) $(CXX_FLAGS) -o ${TARGET3} $<  $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-
-dep:
-       gccmakedep $(SRCS)
-
-clean:
-       rm -f -v *.o con-client
-       rm -f -v *.o con-server
-       rm -f -v *.o bootstrapserver
-
-#dep:
-#      gccmakedep $(SRCS)
index 1ed0695..dd73a8a 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
 ##
@@ -13,13 +33,22 @@ linux_sample_env = lib_env.Clone()
 # Build flags
 ######################################################################
 linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../../../extlibs/timer'])
 linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
 linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src'])
-linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-DLINUX', '-pthread'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack', 'libcoap', 'liboc_logger', 'dl', 'pthread'])
+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'])
 
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
 
 ######################################################################
 #build sampleapp
index 6f67aef..bd7493b 100644 (file)
@@ -49,13 +49,7 @@ private:
             std::string requestType = request->getRequestType();
             int requestFlag = request->getRequestHandlerFlag();
 
-            if (requestFlag & RequestHandlerFlag::InitFlag)
-            {
-                cout << "\t\trequestFlag : Init\n";
-
-                // entity handler to perform resource initialization operations
-            }
-            else if (requestFlag & RequestHandlerFlag::RequestFlag)
+            if (requestFlag & RequestHandlerFlag::RequestFlag)
             {
                 auto pResponse = std::make_shared< OC::OCResourceResponse >();
                 pResponse->setRequestHandle(request->getRequestHandle());
@@ -230,6 +224,6 @@ int main()
     }
     catch (OCException e)
     {
-        std::cout << "Exception in main: " << e.what();
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 }
index 47177c7..413b324 100644 (file)
@@ -25,6 +25,8 @@
 #include <pthread.h>
 #include <iostream>
 
+#include "timer.h"
+
 #include <ThingsManager.h>
 
 using namespace std;
@@ -35,41 +37,48 @@ namespace PH = std::placeholders;
 bool isReady = false;
 
 OCResourceHandle resourceHandle;
-std::vector< OCResourceHandle > resourceHandleVector;
+std::vector<OCResourceHandle> resourceHandleVector;
 
-shared_ptr< OCResource > g_resource;
-vector< string > lights;
+shared_ptr<OCResource> g_resource;
+vector<string> lights;
 
 ThingsManager *thingsMgr = new ThingsManager();
 
-void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCode);
+void onGet(const HeaderOptions& opt, const OCRepresentation &rep,
+        const int eCode);
 
-void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
+void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+        const int eCode);
 
-void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
+void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+        const int eCode);
 
-void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, const int& eCode,
-        const int& sequenceNumber);
+void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
+        const int& eCode, const int& sequenceNumber);
 
 void allBulbOn();
 void allBulbOff();
 
-void foundResources(std::vector< std::shared_ptr< OC::OCResource > > listOfResource)
+shared_ptr<OCResource> g_light;
+
+void foundResources(
+        std::vector<std::shared_ptr<OC::OCResource> > listOfResource)
 {
 
-    for (auto rsrc = listOfResource.begin(); rsrc != listOfResource.end(); ++rsrc)
+    for (auto rsrc = listOfResource.begin(); rsrc != listOfResource.end();
+            ++rsrc)
     {
         std::string resourceURI = (*rsrc)->uri();
         std::string hostAddress = (*rsrc)->host();
 
         if (resourceURI == "/a/light")
         {
-
             cout << "\tResource URI : " << resourceURI << endl;
             cout << "\tResource Host : " << hostAddress << endl;
 
             OCResourceHandle foundResourceHandle;
-            OCStackResult result = OCPlatform::registerResource(foundResourceHandle, (*rsrc));
+            OCStackResult result = OCPlatform::registerResource(
+                    foundResourceHandle, (*rsrc));
             cout << "\tresource registed!" << endl;
             if (result == OC_STACK_OK)
             {
@@ -82,21 +91,23 @@ void foundResources(std::vector< std::shared_ptr< OC::OCResource > > listOfResou
             }
 
             lights.push_back((hostAddress + resourceURI));
+
+            g_light = (*rsrc);
         }
     }
 
     isReady = true;
 }
 
-void foundResource(std::shared_ptr< OCResource > resource)
+void foundResource(std::shared_ptr<OCResource> resource)
 {
     std::string resourceURI;
     std::string hostAddress;
 
+    cout << "FOUND RESOURCE" << endl;
+
     try
     {
-        cout << "FOUND RESOURCE" << endl;
-
         if (resource)
         {
             resourceURI = resource->uri();
@@ -107,41 +118,44 @@ void foundResource(std::shared_ptr< OCResource > resource)
 
                 // g_resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), onGet);
 
-                printf("\tHOST :: %s\n", resource->host().c_str());
+                cout << "FOUND " << resourceURI << endl;
+                // printf("\tHOST :: %s\n", resource->host().c_str());
             }
             else if (resourceURI == "/core/bookmark")
             {
-                resource->observe(ObserveType::Observe, QueryParamsMap(), &onObserve);
+                resource->observe(ObserveType::Observe, QueryParamsMap(),
+                        &onObserve);
             }
-
-            // p_platform.bindResource(resourceHandle, foundResourceHandle);
-
         }
     }
     catch (std::exception& e)
     {
-        std::cout << "" << std::endl;
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 }
 
-void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCode)
+void onGet(const HeaderOptions& opt, const OCRepresentation &rep,
+        const int eCode)
 {
-    // std::vector<OCRepresentation> children = rep.getChildren();
-
-    // cout << "\n\n\nCHILD RESOURCE OF GROUP" << endl;
-    // for( auto iter = children.begin(); iter != children.end();  ++iter )
-    // {
-    //     lights.push_back((*iter).getUri());
-    //     cout << "\tURI :: " << (*iter).getUri() << endl;
-    // }
+    cout << "\nonGet" << endl;
+    if (eCode == OC_STACK_OK)
+        cout << "\tResult is OK." << endl;
+    else
+        cout << "\tInvalid parameter." << endl;
 }
 
-void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+        const int eCode)
 {
-    printf("\nonPut\n");
+    cout << "\nonPut" << endl;
+    if (eCode == OC_STACK_OK)
+        cout << "\tResult is OK." << endl;
+    else
+        cout << "\tInvalid parameter." << endl;
 }
 
-void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+        const int eCode)
 {
     printf("\nonPost\n");
 
@@ -154,17 +168,19 @@ void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, con
             ActionSet *actionset = thingsMgr->getActionSetfromString(plainText);
             if (actionset != NULL)
             {
-                cout << endl << "\tACTIONSET NAME :: " << actionset->actionsetName << endl;
+                cout << endl << "\tACTIONSET NAME :: "
+                        << actionset->actionsetName << endl;
                 for (auto actIter = actionset->listOfAction.begin();
                         actIter != actionset->listOfAction.end(); ++actIter)
                 {
                     cout << "\t\tTARGET :: " << (*actIter)->target << endl;
 
                     for (auto capaIter = (*actIter)->listOfCapability.begin();
-                            capaIter != (*actIter)->listOfCapability.end(); ++capaIter)
+                            capaIter != (*actIter)->listOfCapability.end();
+                            ++capaIter)
                     {
-                        cout << "\t\t\t" << (*capaIter)->capability << " :: " << (*capaIter)->status
-                                << endl;
+                        cout << "\t\t\t" << (*capaIter)->capability << " :: "
+                                << (*capaIter)->status << endl;
                     }
                 }
             }
@@ -195,7 +211,8 @@ void allBulbOff()
 
     if (g_resource)
     {
-        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), &onPost);
+        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
+                &onPost);
     }
 }
 
@@ -207,12 +224,43 @@ void allBulbOn()
 
     if (g_resource)
     {
-        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), &onPost);
+        OCStackResult res = g_resource->post("a.collection", GROUP_INTERFACE,
+            rep, QueryParamsMap(), &onPost);
+
+        if( res != OC_STACK_OK )
+            cout << "failed" << endl;
     }
 }
 
-void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, const int& eCode,
-        const int& sequenceNumber)
+void Scheduled_AllbulbOff()
+{
+    thingsMgr->executeActionSet(g_resource, "AllBulbOffScheduledCall", &onPost);
+}
+void Scheduled_AllbulbOffEx()
+{
+    thingsMgr->executeActionSet(g_resource, "AllBulbOffScheduledCall", 10, &onPost);
+}
+void CancelScheduled_AllBulbOff()
+{
+    thingsMgr->cancelActionSet(g_resource, "AllBulbOffScheduledCall", &onPost);
+}
+void Recursive_allBulbOn()
+{
+    thingsMgr->executeActionSet(g_resource, "AllBulbOnRecursiveCall", &onPost);
+}
+void Recursive_allBulbOnEx()
+{
+    thingsMgr->executeActionSet(g_resource, "AllBulbOnRecursiveCall", 10, &onPost);
+}
+
+void CancelRecursive_allBulbOn()
+{
+
+    thingsMgr->cancelActionSet(g_resource, "AllBulbOnRecursiveCall", &onPost);
+}
+
+void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
+        const int& eCode, const int& sequenceNumber)
 {
     if (eCode == OC_STACK_OK)
     {
@@ -259,18 +307,9 @@ void createActionSet_AllBulbOff()
         action->listOfCapability.push_back(capa);
         allBulbOff->listOfAction.push_back(action);
     }
-    // actionsetDesc = thingsMgr->getStringFromActionSet(allBulbOff);
-
-    // cout << "ActionSet :: " << actionsetDesc << endl;
-
-    // OCRepresentation rep;
-    // rep.setValue("ActionSet", actionsetDesc);
-
     if (g_resource)
     {
         thingsMgr->addActionSet(g_resource, allBulbOff, onPut);
-        // g_resource->put("a.collection", GROUP_INTERFACE, rep,
-        //     QueryParamsMap(), &onPut);
     }
 
     delete allBulbOff;
@@ -294,27 +333,97 @@ void createActionSet_AllBulbOn()
         action->listOfCapability.push_back(capa);
         allBulbOff->listOfAction.push_back(action);
     }
-    // actionsetDesc = thingsMgr->getStringFromActionSet(allBulbOff);
+    if (g_resource)
+    {
+        thingsMgr->addActionSet(g_resource, allBulbOff, onPut);
+    }
 
-    // cout << "ActionSet :: " << actionsetDesc << endl;
+    delete allBulbOff;
+}
+
+void createScheduledActionSet_AllBulbOff()
+{
+    string actionsetDesc;
+    ActionSet *allBulbOff = new ActionSet();
+    allBulbOff->type = OIC::ACTIONSET_TYPE::SCHEDULED;
+    allBulbOff->actionsetName = "AllBulbOffScheduledCall";
+
+    printf("ENTER(YYYY-MM-DD hh:mm:ss) :: ");
+    int res = scanf("%d-%d-%d %d:%d:%d", &allBulbOff->mTime.tm_year,
+            &allBulbOff->mTime.tm_mon, &allBulbOff->mTime.tm_mday,
+            &allBulbOff->mTime.tm_hour, &allBulbOff->mTime.tm_min,
+            &allBulbOff->mTime.tm_sec);
+    if( res < 0 )
+    {
+        printf("Invalid Input. try again.");
+        delete allBulbOff;
+        return;
+    }
+
+    allBulbOff->setDelay(allBulbOff->getSecondsFromAbsoluteTime());
+    printf("DELAY :: %ld\n", allBulbOff->getSecondsFromAbsoluteTime());
+
+    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+    {
+        Action *action = new Action();
+        action->target = (*iter);
 
-    // OCRepresentation rep;
-    // rep.setValue("ActionSet", actionsetDesc);
+        Capability *capa = new Capability();
+        capa->capability = "power";
+        capa->status = "off";
 
+        action->listOfCapability.push_back(capa);
+        allBulbOff->listOfAction.push_back(action);
+    }
     if (g_resource)
     {
         thingsMgr->addActionSet(g_resource, allBulbOff, onPut);
-        // g_resource->put("a.collection", GROUP_INTERFACE, rep,
-        //     QueryParamsMap(), &onPut);
     }
 
     delete allBulbOff;
 }
 
+void createRecursiveActionSet_AllBulbOn()
+{
+    string actionsetDesc;
+    ActionSet *allBulbOn = new ActionSet();
+    allBulbOn->type = OIC::ACTIONSET_TYPE::RECURSIVE;
+
+    allBulbOn->actionsetName = "AllBulbOnRecursiveCall";
+    allBulbOn->mTime.tm_year = 0;
+    allBulbOn->mTime.tm_mon = 0;
+    allBulbOn->mTime.tm_mday = 0;
+    allBulbOn->mTime.tm_hour = 0;
+    allBulbOn->mTime.tm_min = 0;
+    allBulbOn->mTime.tm_sec = 5;
+
+    allBulbOn->setDelay(allBulbOn->getSecAbsTime());
+
+    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+    {
+        Action *action = new Action();
+        action->target = (*iter);
+
+        Capability *capa = new Capability();
+        capa->capability = "power";
+        capa->status = "on";
+
+        action->listOfCapability.push_back(capa);
+        allBulbOn->listOfAction.push_back(action);
+    }
+    if (g_resource)
+    {
+        thingsMgr->addActionSet(g_resource, allBulbOn, onPut);
+    }
+
+    delete allBulbOn;
+}
+
 int main()
 {
     PlatformConfig config
-    { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+    { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0,
+            OC::QualityOfService::LowQos };
 
     try
     {
@@ -324,14 +433,18 @@ int main()
         OCPlatform::Configure(config);
 
         // Find lights for group creation.
-        vector< string > types;
+        vector<string> types;
         types.push_back("core.light");
         thingsMgr->findCandidateResources(types, &foundResources, 5);
 
-        OCPlatform::registerResource(resourceHandle, resourceURI, resourceTypeName,
-                resourceInterface, NULL,
-                //&entityHandler, // entityHandler
-                OC_DISCOVERABLE);
+        OCStackResult res = OCPlatform::registerResource(resourceHandle, resourceURI,
+                resourceTypeName, resourceInterface, NULL, OC_DISCOVERABLE);
+
+        if( res != OC_STACK_OK )
+        {
+            cout << "Resource registeration failed." << endl;
+            return 0;
+        }
 
         cout << "registerResource is called." << endl;
 
@@ -347,86 +460,130 @@ int main()
                 int n;
 
                 cout << endl;
-                cout << "1 :: CREATE ACTIONSET 2 :: EXECUTE ACTIONSET(ALLBULBON)"
-                        << "3 :: EXECUTE ACTIONSET(ALLBULBOFF)" << endl;
-                cout << "4 :: GET ACTIONSET 5 :: DELETE ACTIONSET 6 :: QUIT" << endl;
-                cout << "9 :: FIND GROUP 0 :: FIND BOOKMARK TO OBSERVE" << endl;
-
-                fflush(stdin);
+                cout << "1 :: CREATE ACTIONSET" << endl;
+                cout << "2 :: EXECUTE ACTIONSET(ALLBULBON)" << endl;
+                cout << "3 :: EXECUTE ACTIONSET(ALLBULBOFF)" << endl;
+                cout << "4 :: CREATE ACTIONSET(R_ALLBULBON)" << endl;
+                cout << "\t41 :: EXECUTE ACTIONSET 42 :: CANCEL ACTIONSET" << endl;
+                cout << "5 :: CREATE ACTIONSET(S_ALLBULBON)" << endl;
+                cout << "\t51 :: EXECUTE ACTIONSET 52 :: CANCEL ACTIONSET" << endl;
+                cout << "6 :: GET ACTIONSET" << endl;
+                cout << "7 :: DELETE ACTIONSET" << endl;
+                cout << "8 :: QUIT" << endl;
+                cout << "9 :: FIND GROUP" << endl;
+                cout << "0 :: FIND BOOKMARK TO OBSERVE"
+                        << endl;
+
+                //fflush(stdin);
                 cin >> n;
 
                 if (n == 9)
                 {
-                    OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=a.collection",
+                    std::string query = OC_MULTICAST_DISCOVERY_URI;
+                    query.append("?rt=");
+                    query.append(resourceTypeName);
+
+                    OCPlatform::findResource("",
+                            query,
+                            OC_ALL,
                             &foundResource);
+
+                    // OCPlatform::findResource("",
+                    //         query,
+                    //         OC_WIFI,
+                    //         &foundResource);
                 }
                 else if (n == 0)
                 {
-                    OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.bookmark",
+                    std::string query = OC_MULTICAST_DISCOVERY_URI;
+                    query.append("?rt=");
+                    query.append("core.bookmark");
+
+                    OCPlatform::findResource("",
+                            query,
+                            OC_ALL,
                             &foundResource);
+                    // OCPlatform::findResource("",
+                    //         query,
+                    //         OC_WIFI,
+                    //         &foundResource);
                 }
                 else if (n == 1)
                 {
-
-                    // Craete Action Set
-                    // "AllBulbOff"
-                    //"movieTime*uri=coap://10.251.44.228:49858/a/light|power=10";
                     createActionSet_AllBulbOff();
                     createActionSet_AllBulbOn();
-
                 }
                 else if (n == 2)
                 {
-
                     allBulbOn();
-                    // thingsMgr->executeActionSet(g_resource, "AllBulbOn", onPost);
-
                 }
                 else if (n == 3)
                 {
-
                     allBulbOff();
-                    // thingsMgr->executeActionSet(g_resource, "AllBulbOff", onPost);
-
                 }
                 else if (n == 4)
                 {
-                    // OCRepresentation rep;
-
-                    // rep.setValue("GetActionSet", std::string("AllBulbOff"));
-
-                    // if(g_resource)
-                    // {
-                    //     g_resource->post("a.collection", GROUP_INTERFACE, rep,
-                    //         QueryParamsMap(), &onPost);
-                    // }
-
-                    thingsMgr->getActionSet(g_resource, "AllBulbOff", onPost);
+                    createRecursiveActionSet_AllBulbOn();
+                }
+                else if (n == 41)
+                {
+                    Recursive_allBulbOn();
+                }
+                else if (n == 42)
+                {
+                    CancelRecursive_allBulbOn();
+                }
+                // Exampel of
+                else if (n == 43)
+                {
+                    Recursive_allBulbOnEx();
                 }
                 else if (n == 5)
                 {
-                    // OCRepresentation rep;
-
-                    // rep.setValue("DelActionSet", std::string("AllBulbOff"));
-
-                    // if(g_resource)
-                    // {
-                    //     g_resource->put("a.collection", GROUP_INTERFACE, rep,
-                    //         QueryParamsMap(), &onPut);
-                    // }
-                    thingsMgr->deleteActionSet(g_resource, "AllBulbOff", onPut);
+                    createScheduledActionSet_AllBulbOff();
+                }
+                else if (n == 51)
+                {
+                    Scheduled_AllbulbOff();
+                }
+                else if (n == 52)
+                {
+                    CancelScheduled_AllBulbOff();
+                }
+                else if (n == 53)
+                {
+                    Scheduled_AllbulbOffEx();
                 }
                 else if (n == 6)
                 {
+                    thingsMgr->getActionSet(g_resource, "AllBulbOff", onPost);
+                }
+                else if (n == 7)
+                {
+                    thingsMgr->deleteActionSet(g_resource, "AllBulbOff", onPut);
+                }
+                else if (n == 8)
+                {
                     isRun = false;
                     break;
                 }
+                else if(n == 100)
+                {
+
+                    OCRepresentation rep;
+
+                    rep.setValue("power", std::string("on"));
+
+                    g_light->put(rep, QueryParamsMap(), &onPut);
+
+                }
             }
         }
+        usleep(500*1000);
     }
     catch (OCException& e)
     {
-
+        cout << "ERROR :: " << e.reason() << endl;
     }
 
     return 0;
index d73bf5e..dc3566b 100644 (file)
@@ -184,12 +184,6 @@ private:
             std::string requestType = request->getRequestType();
             int requestFlag = request->getRequestHandlerFlag();
 
-            if (requestFlag & RequestHandlerFlag::InitFlag)
-            {
-                cout << "\t\trequestFlag : Init\n";
-
-                // entity handler to perform resource initialization operations
-            }
             if (requestFlag & RequestHandlerFlag::RequestFlag)
             {
                 cout << "\t\trequestFlag : Request\n";
diff --git a/service/things-manager/sampleapp/linux/groupaction/makefile b/service/things-manager/sampleapp/linux/groupaction/makefile
deleted file mode 100644 (file)
index 6604c3c..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-
-TGMROOT=../../../
-IOT_BASE=${TGMROOT}../../resource
-RST_NAME=.
-
-
-
-# C++ type Compile Flag define.
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
-
-DEPEND_DIR:= ../../../../../resource/dependencies/
-CEREAL_DIR:= $(DEPEND_DIR)/cereal
-
-CXX_INC        := -I../../ -I../../inc/
-CXX_INC        += -I${IOT_BASE}/include/
-CXX_INC        += -I${IOT_BASE}/oc_logger/include
-CXX_INC        += -I${IOT_BASE}/csdk/stack/include
-CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include
-CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include
-CXX_INC        += -I${IOT_BASE}/csdk/logger/include
-CXX_INC        += -I$(CEREAL_DIR)/include
-CXX_INC        += -I../../../sdk/inc
-CXX_INC        += -I../../../sdk/src
-
-
-CXX_LIB=-L""
-
-CXX_SRCPATH=${wildcard ../../src/*.cpp}
-CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
-CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
-CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
-
-
-TGM = ../../
-SDK = ${TGMROOT}sdk
-TGM_INC = -I${TGMROOT}sdk/inc
-SDK_LIB = ${TGMROOT}sdk/build/linux/libTGMSDKLibrary.a
-
-LIB_OC_LOGGER := $(IOT_BASE)/oc_logger/lib/oc_logger.a
-
-LD_LIB := $(IOT_BASE)/release/obj/liboc.a
-LD_LIB += $(IOT_BASE)/csdk/linux/release/liboctbstack.a
-LD_LIB += $(LIB_OC_LOGGER)
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: bookmark lightserver groupserver
-
-#groupclient
-bookmark: ./bookmark.cpp
-       $(CXX) $(CXX_FLAGS) -o bookmark ./bookmark.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-lightserver: ./lightserver.cpp
-       $(CXX) $(CXX_FLAGS) -o lightserver ./lightserver.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-groupserver: ./groupserver.cpp
-       $(CXX) $(CXX_FLAGS) -o groupserver ./groupserver.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-# groupclient: ./groupclient.cpp
-#      $(CXX) $(CXX_FLAGS) -o groupclient ./groupclient.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-clean:
-       rm -f -v *.o ${TARGET}
-       rm -f groupserver
-       rm -f groupclient
-       rm -f lightserver
-       rm -f bookmark
index 25d9b49..e4efebb 100644 (file)
@@ -13,13 +13,22 @@ linux_sample_env = lib_env.Clone()
 # Build flags
 ######################################################################
 linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../../../extlibs/timer'])
 linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
 linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src'])
-linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-DLINUX', '-pthread'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack', 'libcoap', 'liboc_logger', 'dl', 'pthread'])
+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'])
 
+# On some platforms link order can miss functions so librt needs to be
+# re-scanned at the end if present. gcc 4.6 is one with this issue.
+if 'rt' in linux_sample_env.get('LIBS'):
+    linux_sample_env.Append(LIBS = ['rt'])
 
 ######################################################################
 #build sampleapp
index d8b1082..91e9950 100644 (file)
@@ -75,7 +75,6 @@ void onFindResource(std::shared_ptr< OCResource > resource)
 
 int main(int argc, char* argv[])
 {
-
     // Create PlatformConfig object
     PlatformConfig cfg
     { OC::ServiceType::InProc, OC::ModeType::Both/*OC::ModeType::Server*/, "0.0.0.0", 0,
@@ -113,8 +112,20 @@ int main(int argc, char* argv[])
             }
             else if (selectedMenu == 11)
             {
+                ostringstream query;
+                query << OC_MULTICAST_DISCOVERY_URI << "?rt=core.musicplayer";
+
+                cout << query.str() << endl;
                 result = OCPlatform::findResource("",
-                        "coap://224.0.1.187/oc/core?rt=core.musicplayer", onFindResource);
+                            query.str(),
+                            OC_ALL,
+                            onFindResource);
+
+                result = OCPlatform::findResource("",
+                            "coap://224.0.1.187/oc/core?rt=core.musicplayer",
+                            OC_ALL,
+                            onFindResource);
+
                 if (OC_STACK_OK == result)
                 {
                     cout << "Finding music player was successful\n";
@@ -126,8 +137,13 @@ int main(int argc, char* argv[])
             }
             else if (selectedMenu == 12)
             {
-                result = OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.speaker",
-                        onFindResource);
+                ostringstream query;
+                query << OC_MULTICAST_DISCOVERY_URI << "?rt=core.speaker";
+                result = OCPlatform::findResource("",
+                            query.str(),
+                            OC_ALL,
+                            onFindResource);
+
                 if (OC_STACK_OK == result)
                 {
                     cout << "Finding speaker was successful\n";
@@ -161,6 +177,9 @@ int main(int argc, char* argv[])
                     }
                 }
 
+                if(It == gResourceHandleList.end())
+                    continue;
+
                 gResourceHandleList.erase(It);
                 result = OCPlatform::unregisterResource(resourceHandle);
                 if (OC_STACK_OK == result)
@@ -196,6 +215,9 @@ int main(int argc, char* argv[])
                     }
                 }
 
+                if(It == gResourceHandleList.end())
+                    continue;
+
                 gResourceHandleList.erase(It);
                 result = OCPlatform::unregisterResource(resourceHandle);
                 if (OC_STACK_OK == result)
@@ -215,7 +237,7 @@ int main(int argc, char* argv[])
     }
     catch (OCException& e)
     {
-        //log(e.what());
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 
     return 0;
diff --git a/service/things-manager/sampleapp/linux/groupsyncaction/makefile b/service/things-manager/sampleapp/linux/groupsyncaction/makefile
deleted file mode 100644 (file)
index 0ee1e5c..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-
-TGMROOT=../../../
-IOT_BASE=${TGMROOT}../../resource
-RST_NAME=.
-TARGET1=group
-TARGET2=phone
-TARGET3=musicplayer
-TARGET4=speaker
-BUILD:=release
-
-# C++ type Compile Flag define.
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
-
-CXX_INC        := -I../../ -I../../inc/ -I../../../sdk/inc/ -I../../../sdk/src/
-CXX_INC        += -I${IOT_BASE}/include/
-CXX_INC += -I${IOT_BASE}/oc_logger/include
-CXX_INC        += -I${IOT_BASE}/csdk/stack/include
-CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include
-CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include
-CXX_INC        += -I${IOT_BASE}/csdk/logger/include
-CXX_INC        += -I${IOT_BASE}/dependencies/cereal/include
-
-CXX_LIB=-L""
-
-CXX_SRCPATH=${wildcard ../../src/*.cpp}
-CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
-CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
-CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
-
-
-TGM = ../../
-SDK = ${TGMROOT}sdk
-TGM_INC = -I${TGMROOT}sdk/inc
-SDK_LIB = ${TGMROOT}sdk/build/linux/libTGMSDKLibrary.a
-
-LIB_OC_LOGGER := $(IOT_BASE)/oc_logger/lib/oc_logger.a
-
-LD_LIB := $(IOT_BASE)/$(BUILD)/obj/liboc.a
-LD_LIB += $(IOT_BASE)/csdk/linux/$(BUILD)/liboctbstack.a
-LD_LIB += $(LIB_OC_LOGGER)
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: ${TARGET1} ${TARGET2} ${TARGET3} ${TARGET4}
-
-${TARGET1}: ./group.cpp
-       $(CXX) $(CXX_FLAGS) -o ${TARGET1} ./group.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-${TARGET2}: ./phone.cpp
-       $(CXX) $(CXX_FLAGS) -o ${TARGET2} ./phone.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-${TARGET3}: ./musicplayer.cpp
-       $(CXX) $(CXX_FLAGS) -o ${TARGET3} ./musicplayer.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-${TARGET4}: ./speaker.cpp
-       $(CXX) $(CXX_FLAGS) -o ${TARGET4} ./speaker.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-
-clean:
-       rm -f -v *.o ${TARGET1}
-       rm -f -v *.o ${TARGET2}
-       rm -f -v *.o ${TARGET3}
-       rm -f -v *.o ${TARGET4}
index 9a898a3..fa148b2 100644 (file)
@@ -38,13 +38,7 @@ OCEntityHandlerResult mpEntityHandler(const std::shared_ptr< OCResourceRequest >
         int requestFlag = request->getRequestHandlerFlag();
         std::string action;
 
-        if (requestFlag == RequestHandlerFlag::InitFlag)
-        {
-            cout << "\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        if (requestFlag == RequestHandlerFlag::RequestFlag)
         {
             cout << "\trequestFlag : Request\n";
 
@@ -155,7 +149,7 @@ int main(int argc, char* argv[])
     }
     catch (OCException& e)
     {
-        //log(e.what());
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 
     return 0;
index 57494d0..1e9ad79 100644 (file)
@@ -98,7 +98,6 @@ void onGetChild(const HeaderOptions& headerOptions, const OCRepresentation& rep,
         std::string resourceURI;
 
         QueryParamsMap query;
-        OCRepresentation rep;
         std::string playStart;
         std::string playStop;
 
@@ -249,7 +248,9 @@ int main(int argc, char* argv[])
                 std::string resourceInterface = DEFAULT_INTERFACE;
 
                 result = OCPlatform::registerResource(gPhoneResourceHandle, resourceURi,
-                        resourceTypeName, resourceInterface, NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+                        resourceTypeName, resourceInterface,
+                        NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+
                 if (OC_STACK_OK == result)
                 {
                     cout << "To register phone resource was successful\n";
@@ -433,7 +434,7 @@ int main(int argc, char* argv[])
                     continue;
                 }
 
-                result = gThingManager->leaveGroup(collectionResourceType, gPhoneResourceHandle);
+                result = gThingManager->leaveGroup(gFindGroup, collectionResourceType,  gPhoneResourceHandle);
                 if (OC_STACK_OK == result)
                 {
                     cout << "Leaving group was successful\n";
@@ -470,7 +471,7 @@ int main(int argc, char* argv[])
     }
     catch (OCException& e)
     {
-        //log(e.what());
+        std::cout << "Exception: " << e.what() << std::endl;
     }
 
     return 0;
index 41abb36..4e90f3f 100644 (file)
@@ -38,13 +38,7 @@ OCEntityHandlerResult speakerEntityHandler(const std::shared_ptr< OCResourceRequ
         int requestFlag = request->getRequestHandlerFlag();
         std::string action;
 
-        if (requestFlag == RequestHandlerFlag::InitFlag)
-        {
-            cout << "\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
-        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        if (requestFlag == RequestHandlerFlag::RequestFlag)
         {
             cout << "\trequestFlag : Request\n";
 
@@ -157,7 +151,7 @@ int main(int argc, char* argv[])
     }
     catch (OCException& e)
     {
-        //log(e.what());
+         std::cout << "Exception: " << e.what() << std::endl;
     }
 
     return 0;
diff --git a/service/things-manager/sampleapp/linux/makefile b/service/things-manager/sampleapp/linux/makefile
deleted file mode 100644 (file)
index 092d768..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-MAKE=make
-
-DIRLIST=configuration groupaction  groupsyncaction
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: build
-
-build:
-       @for subdir in ${DIRLIST} ; do \
-       ${MAKE} -C $${subdir} ; \
-       echo " " ; \
-       done
-       @echo " "
-
-clean:
-       @for subdir in ${DIRLIST} ; do \
-       ${MAKE} clean -C $${subdir} ; \
-       echo " " ; \
-       done
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/.cproject b/service/things-manager/sampleapp/tizen/ConServerApp/.cproject
new file mode 100644 (file)
index 0000000..544c81e
--- /dev/null
@@ -0,0 +1,499 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+    <storageModule moduleId="org.eclipse.cdt.core.settings">
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="conserverapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.1732789683" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.784108973" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder arguments="--eval=&quot;SHELL=cmd&quot; -r" autoBuildTarget="all" buildPath="${workspace_loc:/ConServerApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.991141288" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.498617409" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.847181660" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.1877648524" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.30268440" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.39285929" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1365166625" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.195721954" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.2031608880" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\sdk\inc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\sdk\src&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\stack\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\logger\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\occoap\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocrandom\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocsocket\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\oc_logger\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\extlibs\timer&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.2019722103" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.preprocessor.def.1628062174" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.1552197767" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+                                <option id="gnu.cpp.compiler.option.other.other.1077700307" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=gnu++0x" valueType="string"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.546425854" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.1904769633" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1301963388" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.1501054876" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.5248569" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.916623032" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1523138456" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.295281858" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.1144492600" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.preprocessor.def.symbols.1496533463" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.misc.other.1752913740" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=gnu++0x" valueType="string"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.183281612" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1326307127" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1156278367" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.387163191" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.1160023692" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.libs.1981950125" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+                                    <listOptionValue builtIn="false" value="TGMSDKLibrary"/>
+                                    <listOptionValue builtIn="false" value="oc"/>
+                                    <listOptionValue builtIn="false" value="octbstack"/>
+                                    <listOptionValue builtIn="false" value="coap"/>
+                                    <listOptionValue builtIn="false" value="oc_logger"/>
+                                    <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.linker.option.shared_flag.core.1600357455" name="Linker.Shared" superClass="sbi.gnu.cpp.linker.option.shared_flag.core" value="false" valueType="boolean"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1548223100" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                                <outputType id="cdt.managedbuild.tool.gnu.cpp.linker.output.so.1567998933" outputPrefix="" superClass="cdt.managedbuild.tool.gnu.cpp.linker.output.so"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1801679035" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1012512773" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.719506497" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.1591459501" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.483946980" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.539557992" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1541244945" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1328146458" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227" moduleId="org.eclipse.cdt.core.settings" name="Release">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="conserverapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.1806554459" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1882260991" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder buildPath="${workspace_loc:/ConServerApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.1480786483" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.101665077" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.906486264" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.325943992" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.819826799" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.cpp.compiler.option.1888932227" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.911460631" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.740263234" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.1207714584" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1142433860" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1397777277" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.1731044300" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.225459286" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.291907753" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.c.compiler.option.1322971988" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1895593459" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.2053809161" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.2104973765" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.1764818276" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1553289120" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1602883613" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1501052901" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.561516003" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.973160572" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.204670616" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1928734833" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.326189069" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.1298411328" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.891775659" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.706788156" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.2024368653" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.188711953" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.601836947" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+    </storageModule>
+    <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+        <project id="ConServerApp.org.tizen.nativecore.target.sbi.gcc45.app.2088063880" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+    </storageModule>
+    <storageModule moduleId="scannerConfiguration">
+        <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.879388275">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.791116227">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+    </storageModule>
+    <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+    <storageModule moduleId="refreshScope"/>
+    <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+</cproject>
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/.exportMap b/service/things-manager/sampleapp/tizen/ConServerApp/.exportMap
new file mode 100644 (file)
index 0000000..43e310e
--- /dev/null
@@ -0,0 +1,4 @@
+{
+       global: main;
+       local: *;
+};
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/.project b/service/things-manager/sampleapp/tizen/ConServerApp/.project
new file mode 100644 (file)
index 0000000..561df87
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>ConServerApp</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+            <triggers>full,incremental,</triggers>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.tizen.nativecore.apichecker.core.builder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.cdt.core.cnature</nature>
+        <nature>org.eclipse.cdt.core.ccnature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+        <nature>org.tizen.nativecore.apichecker.core.tizenCppNature</nature>
+    </natures>
+    <filteredResources>
+        <filter>
+            <id>1424773747755</id>
+            <name></name>
+            <type>26</type>
+            <matcher>
+                <id>org.eclipse.ui.ide.multiFilter</id>
+                <arguments>1.0-projectRelativePath-matches-false-false-*/.tpk</arguments>
+            </matcher>
+        </filter>
+    </filteredResources>
+</projectDescription>
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/inc/configurationresource.h b/service/things-manager/sampleapp/tizen/ConServerApp/inc/configurationresource.h
new file mode 100644 (file)
index 0000000..14bfd8b
--- /dev/null
@@ -0,0 +1,75 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#ifndef __CONFIGURATION_RESOURCE_H__
+#define __CONFIGURATION_RESOURCE_H__
+
+#include <functional>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function<OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request)>
+ResourceEntityHandler;
+
+static std::string defaultURIPrefix = "/oic/con";
+static std::string defaultResourceTypePrefix = "oic.con";
+
+extern std::string defaultLocation;
+extern std::string defaultSystemTime;
+extern std::string defaultCurrency;
+extern std::string defaultRegion;
+
+class ConfigurationResource
+{
+    public:
+        // Configuration members
+        std::string m_configurationUri;
+        std::string m_location;
+        std::string m_systemTime;
+        std::string m_currency;
+        std::string m_region;
+        std::vector< std::string > m_configurationTypes;
+        std::vector< std::string > m_configurationInterfaces;
+        OCResourceHandle m_configurationHandle;
+        OCRepresentation m_configurationRep;
+
+    public:
+
+        ConfigurationResource();
+
+        void createResource(ResourceEntityHandler callback);
+
+        void setConfigurationRepresentation(OCRepresentation &rep);
+
+        OCRepresentation getConfigurationRepresentation();
+
+        std::string getUri();
+
+        void factoryReset();
+
+        void deleteResource();
+};
+
+#endif // __CONFIGURATION_RESOURCE_H__
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/inc/conserverapp.h b/service/things-manager/sampleapp/tizen/ConServerApp/inc/conserverapp.h
new file mode 100644 (file)
index 0000000..2950d70
--- /dev/null
@@ -0,0 +1,45 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef __CONSERVERAPP_H__
+#define __CONSERVERAPP_H__
+
+#include <app.h>
+#include <Elementary.h>
+#include <system_settings.h>
+#include <efl_extension.h>
+#include <dlog.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "thingsmanager.h"
+
+#ifdef  LOG_TAG
+#undef  LOG_TAG
+#endif
+#define LOG_TAG "conserverapp"
+
+#if !defined(PACKAGE)
+#define PACKAGE "org.tizen.conserverapp"
+#endif
+
+#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.conserverapp/res/ui_controls.edj"
+
+#endif // __CONSERVERAPP_H__
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/inc/diagnosticsresource.h b/service/things-manager/sampleapp/tizen/ConServerApp/inc/diagnosticsresource.h
new file mode 100644 (file)
index 0000000..6943ae6
--- /dev/null
@@ -0,0 +1,72 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#ifndef __DIAGNOSTICS_RESOURCE_H__
+#define __DIAGNOSTICS_RESOURCE_H__
+
+#include <functional>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function<OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request)>
+ResourceEntityHandler;
+
+static std::string defaultFactoryReset = "false";
+static std::string defaultReboot = "false";
+static std::string defaultStartStatCollection = "false";
+
+class DiagnosticsResource
+{
+    public:
+        // Diagnostics members
+        std::string m_diagnosticsUri;
+        std::string m_factoryReset;
+        std::string m_reboot;
+        std::string m_startStatCollection;
+        std::vector< std::string > m_diagnosticsTypes;
+        std::vector< std::string > m_diagnosticsInterfaces;
+        OCResourceHandle m_diagnosticsHandle;
+        OCRepresentation m_diagnosticsRep;
+
+    public:
+
+        DiagnosticsResource();
+
+        void createResource(ResourceEntityHandler callback);
+
+        void setDiagnosticsRepresentation(OCRepresentation &rep);
+
+        OCRepresentation getDiagnosticsRepresentation();
+
+        std::string getUri();
+
+        void diagnosticsMonitor(int second);
+
+        std::function< void() > factoryReset;
+
+        void deleteResource();
+};
+
+#endif // __DIAGNOSTICS_RESOURCE_H__
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/inc/factorysetresource.h b/service/things-manager/sampleapp/tizen/ConServerApp/inc/factorysetresource.h
new file mode 100644 (file)
index 0000000..edd18b2
--- /dev/null
@@ -0,0 +1,56 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#ifndef __FACTORYSET_RESOURCE_H__
+#define __FACTORYSET_RESOURCE_H__
+
+#include <functional>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+#include "configurationresource.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function<OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request)>
+ResourceEntityHandler;
+
+class FactorySetResource : public ConfigurationResource
+{
+    public:
+
+        FactorySetResource();
+
+        ~FactorySetResource();
+
+        void createResource(ResourceEntityHandler callback);
+
+        void setFactorySetRepresentation(OCRepresentation &rep);
+
+        OCRepresentation getFactorySetRepresentation();
+
+        std::string getUri();
+
+        void deleteResource();
+};
+
+#endif // __FACTORYSET_RESOURCE_H__
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/res/ui_controls.edc b/service/things-manager/sampleapp/tizen/ConServerApp/res/ui_controls.edc
new file mode 100644 (file)
index 0000000..e5fea9c
--- /dev/null
@@ -0,0 +1,77 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+collections
+{
+    base_scale: 1.8;
+    group
+    {
+        name: "mainpage_layout";
+        parts
+        {
+            part
+            {
+                name: "bootstrap_button";
+                type: SWALLOW;
+                scale: 1;
+                description
+                {
+                    rel1.relative: 0.01 0.02;
+                    rel2.relative: 0.99 0.11;
+                }
+            }
+            part
+            {
+                name: "create_conf_button";
+                type: SWALLOW;
+                scale: 1;
+                description
+                {
+                    rel1.relative: 0.01 0.13;
+                    rel2.relative: 0.99 0.22;
+                }
+            }
+            part
+            {
+                name: "log_bg";
+                type: RECT;
+                scale: 1;
+                description
+                {
+                    state: "default" 0.0;
+                    rel1.relative: 0.01 0.23;
+                    rel2.relative: 0.99 0.99;
+                    color: 220 220 220 255;
+                }
+            }
+            part
+            {
+                name: "log";
+                type: SWALLOW;
+                scale: 1;
+                description
+                {
+                    rel1.to: "log_bg";
+                    rel2.to: "log_bg";
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/shared/res/conserverapp.png b/service/things-manager/sampleapp/tizen/ConServerApp/shared/res/conserverapp.png
new file mode 100644 (file)
index 0000000..9765b1b
Binary files /dev/null and b/service/things-manager/sampleapp/tizen/ConServerApp/shared/res/conserverapp.png differ
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/src/configurationresource.cpp b/service/things-manager/sampleapp/tizen/ConServerApp/src/configurationresource.cpp
new file mode 100644 (file)
index 0000000..529a13f
--- /dev/null
@@ -0,0 +1,140 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "configurationresource.h"
+
+#include <functional>
+#include <dlog.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+using namespace OC;
+
+// Constructor
+ConfigurationResource::ConfigurationResource() :
+    m_location(defaultLocation), m_systemTime(defaultSystemTime), m_currency(
+        defaultCurrency), m_region(defaultRegion)
+{
+    m_configurationUri = "/oic/con"; // URI of the resource
+    m_configurationTypes.push_back("oic.con"); // resource type name
+    m_configurationInterfaces.push_back(DEFAULT_INTERFACE); // resource interface
+    m_configurationRep.setValue("loc", m_location);
+    m_configurationRep.setValue("st", m_systemTime);
+    m_configurationRep.setValue("c", m_currency);
+    m_configurationRep.setValue("r", m_region);
+    m_configurationRep.setUri(m_configurationUri);
+    m_configurationRep.setResourceTypes(m_configurationTypes);
+    m_configurationRep.setResourceInterfaces(m_configurationInterfaces);
+    m_configurationHandle = NULL;
+}
+
+// Creates a ConfigurationResource
+void ConfigurationResource::createResource(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (NULL == callback)
+    {
+        dlog_print(DLOG_INFO, "ConfigurationResource", "#### Callback should be binded");
+        return;
+    }
+
+    // This will internally create and register the resource
+    OCStackResult result = registerResource(m_configurationHandle, m_configurationUri,
+                                            m_configurationTypes[0], m_configurationInterfaces[0],
+                                            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        dlog_print(DLOG_INFO, "ConfigurationResource", "#### Resource creation"
+                   "(configuration) was unsuccessful");
+        return;
+    }
+
+    dlog_print(DLOG_INFO, "ConfigurationResource", "#### Configuration Resource is Created");
+}
+
+void ConfigurationResource::setConfigurationRepresentation(OCRepresentation &rep)
+{
+    string value;
+
+    if (rep.getValue("loc", value))
+    {
+        m_location = value;
+        dlog_print(DLOG_INFO, "ConfigurationResource", "#### m_location: %s",
+                   m_location.c_str());
+    }
+
+    if (rep.getValue("st", value))
+    {
+        dlog_print(DLOG_INFO, "ConfigurationResource", "#### SystemTime is not"
+                   "allowed to be written");
+    }
+
+    if (rep.getValue("c", value))
+    {
+        m_currency = value;
+        dlog_print(DLOG_INFO, "ConfigurationResource", "#### m_currency: %s",
+                   m_currency.c_str());
+    }
+
+    if (rep.getValue("r", value))
+    {
+        m_region = value;
+        dlog_print(DLOG_INFO, "ConfigurationResource", "#### m_region: %s",
+                   m_region.c_str());
+    }
+}
+
+OCRepresentation ConfigurationResource::getConfigurationRepresentation()
+{
+    m_configurationRep.setValue("loc", m_location);
+    m_configurationRep.setValue("st", m_systemTime);
+    m_configurationRep.setValue("c", m_currency);
+    m_configurationRep.setValue("r", m_region);
+
+    return m_configurationRep;
+}
+
+std::string ConfigurationResource::getUri()
+{
+    return m_configurationUri;
+}
+
+// Assigns default values to all the attributes of the configuration resource
+void ConfigurationResource::factoryReset()
+{
+    m_location = defaultLocation;
+    m_systemTime = defaultSystemTime;
+    m_currency = defaultCurrency;
+    m_region = defaultRegion;
+}
+
+// Deletes the configuration resource which has been created using createResource()
+void ConfigurationResource::deleteResource()
+{
+    // Unregister the resource
+    if (NULL != m_configurationHandle)
+    {
+        OCPlatform::unregisterResource(m_configurationHandle);
+    }
+}
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/src/conserverapp.cpp b/service/things-manager/sampleapp/tizen/ConServerApp/src/conserverapp.cpp
new file mode 100644 (file)
index 0000000..de6c1b3
--- /dev/null
@@ -0,0 +1,560 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "conserverapp.h"
+
+#include <tizen.h>
+#include <pthread.h>
+
+#include "configurationresource.h"
+#include "diagnosticsresource.h"
+#include "factorysetresource.h"
+
+using namespace std;
+using namespace OC;
+using namespace OIC;
+
+namespace PH = std::placeholders;
+
+/* Default system configuration value's variables
+   The variable's names should be same as the names of "extern" variables defined in
+   "configurationresource.h" */
+std::string defaultLocation;
+std::string defaultRegion;
+std::string defaultSystemTime;
+std::string defaultCurrency;
+
+static ThingsManager *g_thingsmanager;
+
+const int SUCCESS_RESPONSE = 0;
+
+bool resources_created = false;
+
+// Forward declaring the entityHandler (Configuration)
+bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request);
+OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest);
+OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request);
+
+ConfigurationResource *myConfigurationResource;
+DiagnosticsResource *myDiagnosticsResource;
+FactorySetResource *myFactorySetResource;
+
+typedef std::function< void(OCRepresentation &) > putFunc;
+typedef std::function< OCRepresentation(void) > getFunc;
+
+typedef struct appdata
+{
+    Evas_Object *win;
+    Evas_Object *conform;
+    Evas_Object *naviframe;
+    Evas_Object *scroller;
+    Evas_Object *layout, *base_layout;
+    Evas_Object *bootButton;
+    Evas_Object *createConfButton;
+} appdata_s;
+
+Evas_Object *log_entry;
+
+std::string logMessage;
+
+getFunc getGetFunction(std::string uri)
+{
+    getFunc res = NULL;
+
+    if (uri == myConfigurationResource->getUri())
+    {
+        res = std::bind(&ConfigurationResource::getConfigurationRepresentation,
+                        myConfigurationResource);
+    }
+    else if (uri == myDiagnosticsResource->getUri())
+    {
+        res = std::bind(&DiagnosticsResource::getDiagnosticsRepresentation,
+                        myDiagnosticsResource);
+    }
+
+    return res;
+}
+
+putFunc getPutFunction(std::string uri)
+{
+    putFunc res = NULL;
+
+    if (uri == myConfigurationResource->getUri())
+    {
+        res = std::bind(&ConfigurationResource::setConfigurationRepresentation,
+                        myConfigurationResource, std::placeholders::_1);
+    }
+    else if (uri == myDiagnosticsResource->getUri())
+    {
+        res = std::bind(&DiagnosticsResource::setDiagnosticsRepresentation,
+                        myDiagnosticsResource, std::placeholders::_1);
+    }
+
+    return res;
+}
+
+// This function prepares a response for the incoming request
+bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### In Server CPP prepareResponseForResource");
+    bool result = false;
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        if (requestFlag == RequestHandlerFlag::RequestFlag)
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### requestFlag : Request");
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                dlog_print(DLOG_INFO, LOG_TAG, "#### requestType : GET");
+
+                // GET operations are directly handled while sending the response
+                result = true;
+            }
+            else if (requestType == "PUT")
+            {
+                dlog_print(DLOG_INFO, LOG_TAG, "#### requestType : PUT");
+                putFunc putFunction;
+                OCRepresentation rep = request->getResourceRepresentation();
+
+                // Get appropriate function to be called for the PUT request
+                putFunction = getPutFunction(request->getResourceUri());
+
+                // Do related operations related to PUT request
+                putFunction(rep);
+                result = true;
+            }
+            else if (requestType == "POST")
+            {
+                // POST request operations
+            }
+            else if (requestType == "DELETE")
+            {
+                // DELETE request operations
+            }
+        }
+        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### requestFlag : Observer");
+        }
+    }
+    else
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Request invalid");
+    }
+
+    return result;
+}
+
+// This function sends a response for the incoming request
+OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest)
+{
+    auto pResponse = std::make_shared< OC::OCResourceResponse >();
+
+    // Check for query params (if any)
+    QueryParamsMap queryParamsMap = pRequest->getQueryParameters();
+
+    pResponse->setRequestHandle(pRequest->getRequestHandle());
+    pResponse->setResourceHandle(pRequest->getResourceHandle());
+
+    getFunc getFunction;
+    getFunction = getGetFunction(pRequest->getResourceUri());
+
+    OCRepresentation rep;
+    rep = getFunction();
+
+    auto findRes = queryParamsMap.find("if");
+
+    if (findRes != queryParamsMap.end())
+    {
+        pResponse->setResourceRepresentation(rep, findRes->second);
+    }
+    else
+    {
+        pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+    }
+
+    pResponse->setErrorCode(200);
+    pResponse->setResponseResult(OC_EH_OK);
+
+    return OCPlatform::sendResponse(pResponse);
+}
+
+// This function handles the requests and sends the response
+OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### In Server CPP (entityHandlerForResource) entity"
+               "handler:");
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+    if (prepareResponseForResource(request))
+    {
+        if (OC_STACK_OK == sendResponseForResource(request))
+        {
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### sendResponse failed.");
+        }
+    }
+    else
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### PrepareResponse failed.");
+    }
+    return ehResult;
+}
+
+// Updates the log in the UI
+void *updateLog(void *data)
+{
+    string *log = (string *)data;
+    //Show the log
+    elm_entry_entry_append(log_entry, log->c_str());
+    elm_entry_cursor_end_set(log_entry);
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### updateLog exit!!!!");
+
+    return NULL;
+}
+
+static void
+win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    ui_app_exit();
+}
+
+// Function to delete all the configuration resources which are created
+void deleteResources()
+{
+    if (NULL != myConfigurationResource)
+        myConfigurationResource->deleteResource();
+    if (NULL != myDiagnosticsResource)
+        myDiagnosticsResource->deleteResource();
+    if (NULL != myFactorySetResource)
+        myFactorySetResource->deleteResource();
+}
+
+static void
+win_back_cb(void *data, Evas_Object *obj, void *event_info)
+{
+
+    deleteResources();
+
+    ui_app_exit();
+}
+
+/* Callback Function to be called by the platform
+   when response arrives from the BootStrap Server */
+void onBootStrapCallback(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+                         const int eCode)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onBootStrap entry");
+
+    if (SUCCESS_RESPONSE != eCode)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### onBootStrap -- onGET Response error: %d", eCode);
+        return ;
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onBootStrap -- GET request was successful");
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onBootStrap -- Resource URI: %s", rep.getUri().c_str());
+
+    logMessage = "----------------------------<br>";
+    logMessage += "GET request was successful<br>";
+    logMessage += "URI : " + rep.getUri() + "<br>";
+
+    defaultRegion = rep.getValue< std::string >("r");
+    defaultSystemTime = rep.getValue< std::string >("st");
+    defaultCurrency = rep.getValue< std::string >("c");
+    defaultLocation = rep.getValue< std::string >("loc");
+
+    logMessage += "Location : " + defaultLocation + "<br>";
+    logMessage += "SystemTime : " + defaultSystemTime + "<br>";
+    logMessage += "currency : " + defaultCurrency + "<br>";
+    logMessage += "Region : " + defaultRegion + "<br>";
+
+    //Call updateLog in the thread safe mode
+    ecore_main_loop_thread_safe_call_sync(updateLog, &logMessage);
+
+}
+
+// Function to be called when the doBootStrap UI button is clicked
+static void
+doBootStrap_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    OCStackResult result = g_thingsmanager->doBootstrap(&onBootStrapCallback);
+    if (OC_STACK_OK == result)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### doBootstrap returned OC_STACK_OK");
+    }
+    else
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### doBootstrap failed");
+    }
+}
+
+// Function to be called when Create Configuration Resources UI button is clicked
+static void
+createConfResource_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    logMessage = "----------------------------<br>";
+    if (!resources_created)
+    {
+        resources_created = true;
+        myConfigurationResource = new ConfigurationResource();
+        myConfigurationResource->createResource(&entityHandlerForResource);
+
+        myDiagnosticsResource = new DiagnosticsResource();
+        myDiagnosticsResource->createResource(&entityHandlerForResource);
+
+        myFactorySetResource = new FactorySetResource();
+        myFactorySetResource->createResource(&entityHandlerForResource);
+
+        myDiagnosticsResource->factoryReset = std::function < void()
+                                              > (std::bind(&ConfigurationResource::factoryReset,
+                                                      myConfigurationResource));
+
+        logMessage += "Resources Created Successfully!!! Server is Ready!!!<br>";
+    }
+    else
+    {
+        logMessage += "Resources were created already!!! <br>";
+    }
+    // Show the log in the UI
+    ecore_main_loop_thread_safe_call_sync(updateLog, &logMessage);
+}
+
+static void
+create_base_gui(appdata_s *ad)
+{
+    // Window
+    ad->win = elm_win_util_standard_add(PACKAGE, PACKAGE);
+    elm_win_autodel_set(ad->win, EINA_TRUE);
+
+    if (elm_win_wm_rotation_supported_get(ad->win))
+    {
+        int rots[4] = { 0, 90, 180, 270 };
+        elm_win_wm_rotation_available_rotations_set(ad->win, (const int *)(&rots), 4);
+    }
+
+    evas_object_smart_callback_add(ad->win, "delete,request", win_delete_request_cb, NULL);
+    eext_object_event_callback_add(ad->win, EEXT_CALLBACK_BACK, win_back_cb, ad);
+
+    // Conformant
+    ad->conform = elm_conformant_add(ad->win);
+    evas_object_size_hint_weight_set(ad->conform, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_win_resize_object_add(ad->win, ad->conform);
+    evas_object_show(ad->conform);
+
+    // Base Layout
+    ad->base_layout = elm_layout_add(ad->conform);
+    evas_object_size_hint_weight_set(ad->base_layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_layout_theme_set(ad->base_layout, "layout", "application", "default");
+    evas_object_show(ad->base_layout);
+
+    elm_object_content_set(ad->conform, ad->base_layout);
+
+    // naviframe
+    ad->naviframe = elm_naviframe_add(ad->base_layout);
+    elm_object_part_content_set(ad->base_layout, "elm.swallow.content", ad->naviframe);
+
+    // Scroller
+    ad->scroller = elm_scroller_add(ad->naviframe);
+    elm_scroller_bounce_set(ad->scroller, EINA_FALSE, EINA_TRUE);
+    elm_scroller_policy_set(ad->scroller, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_AUTO);
+
+    // layout
+    ad->layout = elm_layout_add(ad->naviframe);
+    evas_object_size_hint_weight_set(ad->layout, EVAS_HINT_EXPAND, 0.0);
+    elm_layout_file_set(ad->layout, ELM_DEMO_EDJ, "mainpage_layout");
+
+    elm_object_content_set(ad->scroller, ad->layout);
+
+    ad->bootButton = elm_button_add(ad->layout);
+    elm_object_text_set(ad->bootButton, "doBootStrap");
+    evas_object_size_hint_weight_set(ad->bootButton, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(ad->bootButton, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    evas_object_smart_callback_add(ad->bootButton, "clicked", doBootStrap_cb, ad);
+    elm_object_part_content_set(ad->layout, "bootstrap_button", ad->bootButton);
+
+    ad->createConfButton = elm_button_add(ad->layout);
+    elm_object_text_set(ad->createConfButton, "Create Configuration Resources");
+    evas_object_size_hint_weight_set(ad->createConfButton, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(ad->createConfButton, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    evas_object_smart_callback_add(ad->createConfButton, "clicked", createConfResource_cb, ad);
+    elm_object_part_content_set(ad->layout, "create_conf_button", ad->createConfButton);
+
+    log_entry = elm_entry_add(ad->layout);
+    elm_entry_scrollable_set(log_entry, EINA_TRUE);
+    elm_entry_editable_set(log_entry, EINA_FALSE);
+    elm_object_part_text_set(log_entry, "elm.guide", "Logs will be updated here!!!");
+    evas_object_size_hint_weight_set(log_entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    elm_object_part_content_set(ad->layout, "log", log_entry);
+
+    elm_naviframe_item_push(ad->naviframe, "Configuration Server", NULL, NULL, ad->scroller, NULL);
+
+    // Show window after base gui is set up
+    evas_object_show(ad->win);
+}
+
+// Function which configures the OCPlatform
+static void
+configure_platform()
+{
+    try
+    {
+        PlatformConfig config
+        { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+        OCPlatform::Configure(config);
+
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration done!!!!");
+    }
+    catch (OCException &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+}
+
+
+static bool
+app_create(void *data)
+{
+    /* Hook to take necessary actions before main event loop starts
+        Initialize UI resources and application's data
+        If this function returns true, the main loop of application starts
+        If this function returns false, the application is terminated */
+    appdata_s *ad = (appdata_s *)data;
+
+    elm_app_base_scale_set(1.8);
+
+    // Create and show the UI
+    create_base_gui(ad);
+
+    // Configure the OCPlatform
+    configure_platform();
+
+    g_thingsmanager = new ThingsManager();
+
+    return true;
+}
+
+static void
+app_control(app_control_h app_control, void *data)
+{
+    // Handle the launch request.
+}
+
+static void
+app_pause(void *data)
+{
+    // Take necessary actions when application becomes invisible.
+}
+
+static void
+app_resume(void *data)
+{
+    // Take necessary actions when application becomes visible.
+}
+
+static void
+app_terminate(void *data)
+{
+    // Release all resources.
+}
+
+static void
+ui_app_lang_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LANGUAGE_CHANGED
+    char *locale = NULL;
+    system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale);
+    elm_language_set(locale);
+    free(locale);
+    return;
+}
+
+static void
+ui_app_orient_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_DEVICE_ORIENTATION_CHANGED
+    return;
+}
+
+static void
+ui_app_region_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_REGION_FORMAT_CHANGED
+}
+
+static void
+ui_app_low_battery(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_BATTERY
+}
+
+static void
+ui_app_low_memory(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_MEMORY
+}
+
+int
+main(int argc, char *argv[])
+{
+    appdata_s ad = {0,};
+    int ret = 0;
+
+    ui_app_lifecycle_callback_s event_callback = {0,};
+    app_event_handler_h handlers[5] = {NULL, };
+
+    event_callback.create = app_create;
+    event_callback.terminate = app_terminate;
+    event_callback.pause = app_pause;
+    event_callback.resume = app_resume;
+    event_callback.app_control = app_control;
+
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY,
+                             ui_app_low_battery, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY,
+                             ui_app_low_memory, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED],
+                             APP_EVENT_DEVICE_ORIENTATION_CHANGED, ui_app_orient_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED], APP_EVENT_LANGUAGE_CHANGED,
+                             ui_app_lang_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED],
+                             APP_EVENT_REGION_FORMAT_CHANGED, ui_app_region_changed, &ad);
+    ui_app_remove_event_handler(handlers[APP_EVENT_LOW_MEMORY]);
+
+    ret = ui_app_main(argc, argv, &event_callback, &ad);
+    if (APP_ERROR_NONE != ret)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "app_main() is failed. err = %d", ret);
+    }
+
+    return ret;
+}
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/src/diagnosticsresource.cpp b/service/things-manager/sampleapp/tizen/ConServerApp/src/diagnosticsresource.cpp
new file mode 100644 (file)
index 0000000..7510b8c
--- /dev/null
@@ -0,0 +1,165 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "diagnosticsresource.h"
+
+#include <functional>
+#include <dlog.h>
+
+#include "conserverapp.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+extern string logMessage;
+
+extern void *updateLog(void *);
+
+using namespace OC;
+
+// Constructor
+DiagnosticsResource::DiagnosticsResource() :
+    m_factoryReset(defaultFactoryReset), m_reboot(defaultReboot),
+    m_startStatCollection(defaultStartStatCollection)
+{
+    m_diagnosticsUri = "/oic/diag"; // URI of the resource
+    m_diagnosticsTypes.push_back("oic.diag"); // resource type name
+    m_diagnosticsInterfaces.push_back(DEFAULT_INTERFACE); // resource interface
+    m_diagnosticsRep.setValue("fr", m_factoryReset);
+    m_diagnosticsRep.setValue("rb", m_reboot);
+    m_diagnosticsRep.setValue("ssc", m_startStatCollection);
+    m_diagnosticsRep.setUri(m_diagnosticsUri);
+    m_diagnosticsRep.setResourceTypes(m_diagnosticsTypes);
+    m_diagnosticsRep.setResourceInterfaces(m_diagnosticsInterfaces);
+    m_diagnosticsHandle = NULL;
+}
+
+// Creates a DiagnosticResource
+void DiagnosticsResource::createResource(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (NULL == callback)
+    {
+        dlog_print(DLOG_INFO, "DiagnosticsResource", "#### Callback should be binded");
+        return;
+    }
+
+    // This will internally create and register the resource
+    OCStackResult result = registerResource(m_diagnosticsHandle, m_diagnosticsUri,
+                                            m_diagnosticsTypes[0], m_diagnosticsInterfaces[0],
+                                            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        dlog_print(DLOG_INFO, "DiagnosticsResource", "#### Resource creation"
+                   "(configuration) was unsuccessful");
+        return;
+    }
+
+    thread exec(
+        std::function< void(int second) >(
+            std::bind(&DiagnosticsResource::diagnosticsMonitor, this,
+                      std::placeholders::_1)), 1);
+    exec.detach();
+
+    dlog_print(DLOG_INFO, "DiagnosticsResource", "#### Diagnostics Resource is Created");
+}
+
+void DiagnosticsResource::setDiagnosticsRepresentation(OCRepresentation &rep)
+{
+    string value;
+
+    if (rep.getValue("fr", value))
+    {
+        m_factoryReset = value;
+        dlog_print(DLOG_INFO, "DiagnosticsResource", "#### m_factoryReset: %s",
+                   m_factoryReset.c_str());
+    }
+
+    if (rep.getValue("rb", value))
+    {
+        m_reboot = value;
+        dlog_print(DLOG_INFO, "DiagnosticsResource", "#### m_reboot: %s", m_reboot.c_str());
+    }
+
+    if (rep.getValue("ssc", value))
+    {
+        m_startStatCollection = value;
+        dlog_print(DLOG_INFO, "DiagnosticsResource", "#### m_startStatCollection: %s",
+                   m_startStatCollection.c_str());
+    }
+}
+
+OCRepresentation DiagnosticsResource::getDiagnosticsRepresentation()
+{
+    m_diagnosticsRep.setValue("fr", m_factoryReset);
+    m_diagnosticsRep.setValue("rb", m_reboot);
+    m_diagnosticsRep.setValue("ssc", m_startStatCollection);
+
+    return m_diagnosticsRep;
+}
+
+std::string DiagnosticsResource::getUri()
+{
+    return m_diagnosticsUri;
+}
+
+// Handles the Reboot and FactoryReset request
+void DiagnosticsResource::diagnosticsMonitor(int second)
+{
+    while (1)
+    {
+        sleep(second);
+
+        if (m_reboot == "true")
+        {
+            int res;
+            dlog_print(DLOG_INFO, "DiagnosticsResource", "#### Reboot will be soon...");
+            m_reboot = defaultReboot;
+            res = system("sudo reboot"); // System reboot
+
+            dlog_print(DLOG_INFO, "DiagnosticsResource", "#### return: %d", res);
+
+            logMessage = "----------------------------<br>";
+            logMessage += "*** System Reboot Success ***<br>";
+
+            //Show the log
+            ecore_main_loop_thread_safe_call_sync(updateLog, &logMessage);
+
+        }
+        else if (m_factoryReset == "true")
+        {
+            dlog_print(DLOG_INFO, "DiagnosticsResource", "#### Factory Reset will be soon...");
+            m_factoryReset = defaultFactoryReset;
+            factoryReset();
+        }
+    }
+}
+
+// Deletes the diagnostic resource which has been created using createResource()
+void DiagnosticsResource::deleteResource()
+{
+    // Unregister the resource
+    if (NULL != m_diagnosticsHandle)
+    {
+        OCPlatform::unregisterResource(m_diagnosticsHandle);
+    }
+}
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/src/factorysetresource.cpp b/service/things-manager/sampleapp/tizen/ConServerApp/src/factorysetresource.cpp
new file mode 100644 (file)
index 0000000..fc2d666
--- /dev/null
@@ -0,0 +1,124 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "factorysetresource.h"
+
+#include <functional>
+#include <dlog.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+using namespace OC;
+
+FactorySetResource::FactorySetResource()
+{
+    m_configurationUri = "/factorySet"; // URI of the resource
+    m_configurationTypes.clear();
+    m_configurationTypes.push_back("factorySet"); // resource type name.
+    m_configurationRep.setUri(m_configurationUri);
+    m_configurationRep.setResourceTypes(m_configurationTypes);
+}
+
+FactorySetResource::~FactorySetResource() {}
+
+// This function internally calls registerResource API.
+void FactorySetResource::createResource(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (NULL == callback)
+    {
+        dlog_print(DLOG_INFO, "FactorySetResource", "#### Callback should be binded");
+        return;
+    }
+
+    // This will internally create and register the resource
+    OCStackResult result = registerResource(m_configurationHandle, m_configurationUri,
+                                            m_configurationTypes[0], m_configurationInterfaces[0],
+                                            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        dlog_print(DLOG_INFO, "FactorySetResource", "#### Resource creation"
+                   "(configuration) was unsuccessful");
+        return;
+    }
+
+    dlog_print(DLOG_INFO, "FactorySetResource", "#### Configuration Resource is Created");
+}
+
+void FactorySetResource::setFactorySetRepresentation(OCRepresentation &rep)
+{
+    string value;
+
+    if (rep.getValue("loc", value))
+    {
+        m_location = value;
+        dlog_print(DLOG_INFO, "FactorySetResource", "#### m_location: %s",
+                   m_location.c_str());
+    }
+
+    if (rep.getValue("st", value))
+    {
+        dlog_print(DLOG_INFO, "FactorySetResource", "#### SystemTime is not"
+                   "allowed to be written");
+    }
+
+    if (rep.getValue("c", value))
+    {
+        m_currency = value;
+        dlog_print(DLOG_INFO, "FactorySetResource", "#### m_currency: %s",
+                   m_currency.c_str());
+    }
+
+    if (rep.getValue("r", value))
+    {
+        m_region = value;
+        dlog_print(DLOG_INFO, "FactorySetResource", "#### m_region: %s",
+                   m_region.c_str());
+    }
+}
+
+OCRepresentation FactorySetResource::getFactorySetRepresentation()
+{
+    m_configurationRep.setValue("loc", m_location);
+    m_configurationRep.setValue("st", m_systemTime);
+    m_configurationRep.setValue("c", m_currency);
+    m_configurationRep.setValue("r", m_region);
+
+    return m_configurationRep;
+}
+
+std::string FactorySetResource::getUri()
+{
+    return m_configurationUri;
+}
+
+// Deletes the factoryset resource which has been created using createResource()
+void FactorySetResource::deleteResource()
+{
+    // Unregister the Configuration resource
+    if (NULL != m_configurationHandle)
+    {
+        OCPlatform::unregisterResource(m_configurationHandle);
+    }
+}
diff --git a/service/things-manager/sampleapp/tizen/ConServerApp/tizen-manifest.xml b/service/things-manager/sampleapp/tizen/ConServerApp/tizen-manifest.xml
new file mode 100644 (file)
index 0000000..78beaa1
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="2.3" package="org.tizen.conserverapp" version="1.0.0">
+    <profile name="mobile"/>
+    <ui-application appid="org.tizen.conserverapp" exec="conserverapp" multiple="false" nodisplay="false" taskmanage="true" type="capp">
+        <label>conserverapp</label>
+        <icon>conserverapp.png</icon>
+    </ui-application>
+    <privileges>
+        <privilege>http://tizen.org/privilege/network.get</privilege>
+        <privilege>http://tizen.org/privilege/internet</privilege>
+    </privileges>
+    <feature name="http://tizen.org/feature/network.wifi">true</feature>
+</manifest>
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/.cproject b/service/things-manager/sampleapp/tizen/TMSampleApp/.cproject
new file mode 100644 (file)
index 0000000..2d67c99
--- /dev/null
@@ -0,0 +1,506 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+    <storageModule moduleId="org.eclipse.cdt.core.settings">
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.266200202" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1788661429" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder arguments="--eval=&quot;SHELL=cmd&quot; -r" autoBuildTarget="all" buildPath="${workspace_loc:/TMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1749302123" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.345678603" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1794187316" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.719656926" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.378028433" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.831567474" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1543030783" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1612037830" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\sdk\inc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\sdk\src&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\stack\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\logger\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\occoap\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocrandom\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\csdk\ocsocket\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\resource\oc_logger\include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\..\extlibs\timer&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1095600730" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.preprocessor.def.371963530" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" useByScannerDiscovery="false" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.dialect.std.1929207991" name="Language standard" superClass="gnu.cpp.compiler.option.dialect.std" value="gnu.cpp.compiler.dialect.default" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.755649926" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+                                <option id="gnu.cpp.compiler.option.other.other.1760093561" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1956958926" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2072036030" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1042898971" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.135607770" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.571493571" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.107632308" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1275911900" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-mthumb"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.109116980" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.1552601669" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.preprocessor.def.symbols.2021130927" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" useByScannerDiscovery="false" valueType="definedSymbols">
+                                    <listOptionValue builtIn="false" value="_DEBUG"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.misc.pic.core.1304419386" name="-fPIC option" superClass="sbi.gnu.c.compiler.option.misc.pic.core" value="false" valueType="boolean"/>
+                                <option id="gnu.c.compiler.option.misc.other.2029079564" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1859092644" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.944066372" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1667264058" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1178784315" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.1087248355" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.libs.2039500142" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+                                    <listOptionValue builtIn="false" value="TGMSDKLibrary"/>
+                                    <listOptionValue builtIn="false" value="oc"/>
+                                    <listOptionValue builtIn="false" value="octbstack"/>
+                                    <listOptionValue builtIn="false" value="coap"/>
+                                    <listOptionValue builtIn="false" value="oc_logger"/>
+                                    <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1585687908" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.89256350" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.353447784" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.734608698" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.125567506" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.2107204356" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1190161351" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1621384631" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+        <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+            <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" moduleId="org.eclipse.cdt.core.settings" name="Release">
+                <externalSettings/>
+                <extensions>
+                    <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+                    <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+                    <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+                </extensions>
+            </storageModule>
+            <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+                <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+                    <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396." name="/" resourcePath="">
+                        <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.32000863" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+                            <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1750758769" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+                            <builder buildPath="${workspace_loc:/TMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.2029564551" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.224082468" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1434486618" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+                                <option id="gnu.cpp.compiler.option.optimization.level.1709393206" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+                                <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.221700213" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.cpp.compiler.option.710876023" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1622581330" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1695583788" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.cpp.compiler.option.include.paths.585301879" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.cpp.compiler.option.frameworks.core.708669314" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2006056090" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+                            </tool>
+                            <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.601285388" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+                                <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1778561828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+                                <option id="sbi.gnu.c.compiler.option.debugging.level.core.1695949408" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+                                <option id="sbi.gnu.c.compiler.option.1422818783" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1871683675" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libxml2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SDK_PATH}/library&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/AL&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appcore-agent&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/appfw&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/base&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/cairo&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/calendar-service2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ckm&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/contacts-svc&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/curl&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dbus-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/dbus-1.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/dlog&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ecore-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/e_dbus-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/edje-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efreet-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1/eina&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eina-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/elementary-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ethumb-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/evas-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/fontconfig&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/freetype2&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/gio-unix-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/glib-2.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/lib/glib-2.0/include&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/libexif&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media-content&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/media&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/minizip&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/network&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/notification&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/shortcut&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/storage&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/system&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ui&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/vconf&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/web&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/badge&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/eio-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/email-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/embryo-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/messaging&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/msg-service&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ug-1&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/context-manager&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/telephony-client&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/ewebkit2-0&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/location&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/sensor&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/efl-extension&quot;"/>
+                                    <listOptionValue builtIn="false" value="&quot;${SBI_SYSROOT}/usr/include/wifi-direct&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.371848582" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+                                    <listOptionValue builtIn="false" value=" -fPIE"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                </option>
+                                <option id="gnu.c.compiler.option.include.paths.1254567673" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
+                                </option>
+                                <option id="sbi.gnu.c.compiler.option.frameworks.core.627340354" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+                                    <listOptionValue builtIn="false" value="Native_API"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.749706957" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1794486202" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+                            <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2579106" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+                                <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1582557344" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+                                    <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+                                    <listOptionValue builtIn="false" value="-pie -lpthread "/>
+                                    <listOptionValue builtIn="false" value="-Xlinker -rpath=&quot;/home/developer/sdk_tools/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="--sysroot=&quot;${SBI_SYSROOT}&quot;"/>
+                                    <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+                                    <listOptionValue builtIn="false" value="-L&quot;${SBI_SYSROOT}/usr/lib&quot;"/>
+                                    <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+                                </option>
+                                <option id="gnu.cpp.link.option.paths.1396123174" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+                                    <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/lib}&quot;"/>
+                                </option>
+                                <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.768667264" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+                                    <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+                                    <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+                                </inputType>
+                            </tool>
+                            <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.380499784" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+                                <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1638213209" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+                            </tool>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.1617359663" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+                            <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.759297757" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.ast.495578509" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+                            <tool id="org.tizen.nativecore.tool.ast.cpp.91235808" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.po.compiler.619869321" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+                            <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1045552473" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+                        </toolChain>
+                    </folderInfo>
+                    <sourceEntries>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+                        <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+                    </sourceEntries>
+                </configuration>
+            </storageModule>
+            <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+        </cconfiguration>
+    </storageModule>
+    <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+        <project id="TMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.278712545" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+    </storageModule>
+    <storageModule moduleId="scannerConfiguration">
+        <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+        <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+            <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+        </scannerConfigBuildInfo>
+    </storageModule>
+    <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+    <storageModule moduleId="refreshScope" versionNumber="2">
+        <configuration configurationName="Debug">
+            <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+        </configuration>
+        <configuration configurationName="Release">
+            <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+        </configuration>
+    </storageModule>
+    <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+</cproject>
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/.exportMap b/service/things-manager/sampleapp/tizen/TMSampleApp/.exportMap
new file mode 100644 (file)
index 0000000..43e310e
--- /dev/null
@@ -0,0 +1,4 @@
+{
+       global: main;
+       local: *;
+};
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/.project b/service/things-manager/sampleapp/tizen/TMSampleApp/.project
new file mode 100644 (file)
index 0000000..eea1d58
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>TMSampleApp</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+            <triggers>full,incremental,</triggers>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.tizen.nativecore.apichecker.core.builder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.cdt.core.cnature</nature>
+        <nature>org.eclipse.cdt.core.ccnature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+        <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+        <nature>org.tizen.nativecore.apichecker.core.tizenCppNature</nature>
+    </natures>
+    <filteredResources>
+        <filter>
+            <id>1424257681824</id>
+            <name></name>
+            <type>26</type>
+            <matcher>
+                <id>org.eclipse.ui.ide.multiFilter</id>
+                <arguments>1.0-projectRelativePath-matches-false-false-*/.tpk</arguments>
+            </matcher>
+        </filter>
+    </filteredResources>
+</projectDescription>
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/edc_resource/configuration_control.edc b/service/things-manager/sampleapp/tizen/TMSampleApp/edc_resource/configuration_control.edc
new file mode 100644 (file)
index 0000000..fb6e82a
--- /dev/null
@@ -0,0 +1,125 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#define POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 15
+#define POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC 96
+
+group
+{
+    name: "configuration_layout";
+    parts
+    {
+        part
+        {
+            name: "list";
+            type: SWALLOW;
+            scale: 1;
+            description
+            {
+                rel1.relative: 0.01 0.01;
+                rel2.relative: 0.99 0.6;
+            }
+        }
+        part
+        {
+            name: "log_bg";
+            type: RECT;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                rel1.relative: 0.01 0.61;
+                rel2.relative: 0.98 1.0;
+                color: 220 220 220 255;
+            }
+        }
+        part
+        {
+            name: "log";
+            type: SWALLOW;
+            scale: 1;
+            description
+            {
+                rel1.to: "log_bg";
+                rel2.to: "log_bg";
+            }
+        }
+    }
+}
+group
+{
+    name: "popup_region_text";
+    parts
+    {
+        part
+        {
+            name: "pad_l";
+            type: SPACER;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
+                fixed: 1 0;
+                rel1.relative: 0.0 0.0;
+                rel2.relative: 0.0 1.0;
+                align: 0.0 0.0;
+            }
+        }
+        part
+        {
+            name: "pad_r";
+            type: SPACER;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
+                fixed: 1 0;
+                rel1.relative: 1.0 0.0;
+                rel2.relative: 1.0 1.0;
+                align: 1.0 0.0;
+            }
+        }
+        part
+        {
+            name: "elm.swallow.content";
+            type: SWALLOW;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                min: 0 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
+                max: -1 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
+                align: 0.5 0.5;
+                rel1
+                {
+                    relative: 1.0 0.0;
+                    to_x: "pad_l";
+                }
+                rel2
+                {
+                    relative: 0.0 1.0;
+                    to_x: "pad_r";
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/edc_resource/group_control.edc b/service/things-manager/sampleapp/tizen/TMSampleApp/edc_resource/group_control.edc
new file mode 100644 (file)
index 0000000..0c868eb
--- /dev/null
@@ -0,0 +1,137 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#define POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 15
+#define POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC 96
+
+group
+{
+    name: "group_layout";
+    parts
+    {
+        part
+        {
+            name: "find_button";
+            type: SWALLOW;
+            scale: 1;
+            description
+            {
+                rel1.relative: 0.01 0.01;
+                rel2.relative: 0.5 0.09;
+            }
+        }
+        part
+        {
+            name: "list";
+            type: SWALLOW;
+            scale: 1;
+            description
+            {
+                rel1.relative: 0.01 0.1;
+                rel2.relative: 0.99 0.7;
+            }
+        }
+        part
+        {
+            name: "log_bg";
+            type: RECT;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                rel1.relative: 0.01 0.71;
+                rel2.relative: 0.98 1.0;
+                color: 220 220 220 255;
+            }
+        }
+        part
+        {
+            name: "log";
+            type: SWALLOW;
+            scale: 1;
+            description
+            {
+                rel1.to: "log_bg";
+                rel2.to: "log_bg";
+            }
+        }
+    }
+}
+
+group
+{
+    name: "popup_datetime_text";
+    parts
+    {
+        part
+        {
+            name: "pad_l";
+            type: SPACER;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
+                fixed: 1 0;
+                rel1.relative: 0.0 0.0;
+                rel2.relative: 0.0 1.0;
+                align: 0.0 0.0;
+            }
+        }
+        part
+        {
+            name: "pad_r";
+            type: SPACER;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
+                fixed: 1 0;
+                rel1.relative: 1.0 0.0;
+                rel2.relative: 1.0 1.0;
+                align: 1.0 0.0;
+            }
+        }
+        part
+        {
+            name: "elm.swallow.content";
+            type: SWALLOW;
+            scale: 1;
+            description
+            {
+                state: "default" 0.0;
+                min: 0 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
+                max: -1 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
+                align: 0.5 0.5;
+                rel1
+                {
+                    relative: 1.0 0.0;
+                    to_x: "pad_l";
+                }
+                rel2
+                {
+                    relative: 0.0 1.0;
+                    to_x: "pad_r";
+                }
+            }
+        }
+    }
+}
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/inc/tmsampleapp.h b/service/things-manager/sampleapp/tizen/TMSampleApp/inc/tmsampleapp.h
new file mode 100644 (file)
index 0000000..851998e
--- /dev/null
@@ -0,0 +1,49 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef __TMSAMPLEAPP_H__
+#define __TMSAMPLEAPP_H__
+
+#include <app.h>
+#include <Elementary.h>
+#include <system_settings.h>
+#include <efl_extension.h>
+#include <dlog.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+
+#ifdef  LOG_TAG
+#undef  LOG_TAG
+#endif
+#define LOG_TAG "tmsampleapp"
+
+#if !defined(PACKAGE)
+#define PACKAGE "org.tizen.tmsampleapp"
+#endif
+
+#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.tmsampleapp/res/ui_controls.edj"
+
+void group_cb(void *data, Evas_Object *obj, void *event_info);
+void configuration_cb(void *data, Evas_Object *obj, void *event_info);
+
+#endif // __TMSAMPLEAPP_H__
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/inc/tmutil.h b/service/things-manager/sampleapp/tizen/TMSampleApp/inc/tmutil.h
new file mode 100644 (file)
index 0000000..373ec4f
--- /dev/null
@@ -0,0 +1,30 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include<iostream>
+
+using namespace std;
+
+#ifndef __TMUTIL_H__
+#define __TMUTIL_H__
+
+extern std::string getOCStackResultStringFromInt(int result);
+
+#endif // __TMUTIL_H__
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/res/ui_controls.edc b/service/things-manager/sampleapp/tizen/TMSampleApp/res/ui_controls.edc
new file mode 100644 (file)
index 0000000..a45bbb7
--- /dev/null
@@ -0,0 +1,26 @@
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+collections
+{
+    base_scale: 1.8;
+    #include "../edc_resource/configuration_control.edc"
+    #include "../edc_resource/group_control.edc"
+}
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/shared/res/tmsampleapp.png b/service/things-manager/sampleapp/tizen/TMSampleApp/shared/res/tmsampleapp.png
new file mode 100644 (file)
index 0000000..9765b1b
Binary files /dev/null and b/service/things-manager/sampleapp/tizen/TMSampleApp/shared/res/tmsampleapp.png differ
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/src/configuration.cpp b/service/things-manager/sampleapp/tizen/TMSampleApp/src/configuration.cpp
new file mode 100644 (file)
index 0000000..509a086
--- /dev/null
@@ -0,0 +1,879 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "tmsampleapp.h"
+#include "tmutil.h"
+
+using namespace std;
+using namespace OC;
+using namespace OIC;
+
+int isWaiting = 0; // 0: none to wait, 1: wait for the response of "getConfigurationValue"
+const int SUCCESS_RESPONSE = 0;
+
+OCResourceHandle configurationCollectionHandle = NULL;
+OCResourceHandle configurationFoundHandle = NULL;
+std::shared_ptr< OCResource > g_configurationCollection; // For a group of multiple resources
+std::shared_ptr< OCResource > g_configurationResource; // For a single resource
+
+OCResourceHandle diagnosticsCollectionHandle = NULL;
+OCResourceHandle diagnosticsFoundHandle = NULL;
+std::shared_ptr< OCResource > g_diagnosticsCollection; // For a group of multiple resources
+std::shared_ptr< OCResource > g_diagnosticsResource; // For a single resource
+
+OCResourceHandle setCollectionHandle = NULL;
+OCResourceHandle setFoundHandle = NULL;
+std::shared_ptr< OCResource > g_setCollection; // For a group of multiple resources
+std::shared_ptr< OCResource > g_setResource; // For a single resource
+
+std::map< std::string, std::shared_ptr< OCResource > > resourceTable;
+std::vector< OCResourceHandle > configResourceHandleVector;
+
+typedef std::string ConfigurationName;
+typedef std::string ConfigurationValue;
+
+static Evas_Object *log_entry = NULL;
+
+string CONFIGURATION_COLLECTION_RESOURCE_URI  = "/core/a/configuration/resourceset";
+string CONFIGURATION_COLLECTION_RESOURCE_TYPE = "core.configuration.resourceset";
+string DIAGNOSTIC_COLLECTION_RESOURCE_URI     = "/core/a/diagnostics/resourceset";
+string DIAGNOSTIC_COLLECTION_RESOURCE_TYPE    = "core.diagnostics.resourceset";
+string FACTORYSET_COLLECTION_RESOURCE_URI     = "/core/a/factoryset/resourceset";
+string FACTORYSET_COLLECTION_RESOURCE_TYPE    = "core.factoryset.resourceset";
+
+string CONFIGURATION_RESOURCE_URI             = "/oic/con";
+string DIAGNOSTIC_RESOURCE_URI                = "/oic/diag";
+string FACTORYSET_RESOURCE_URI                = "/factorySet";
+
+ThingsManager *configthingsMgr = new ThingsManager();
+
+typedef struct region_popup
+{
+    Evas_Object *popup;
+    Evas_Object *entry;
+} region_popup_fields;
+
+void *updateConfigLog(void *data)
+{
+    string *log = (string *)data;
+    // Show the log
+    elm_entry_entry_append(log_entry, (*log).c_str());
+    elm_entry_cursor_end_set(log_entry);
+    return NULL;
+}
+
+// Callback to found collection resource
+void onFoundCollectionResource(std::vector< std::shared_ptr< OCResource > > resources)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onFoundCollectionResource ENTRY!!!!");
+    try
+    {
+        // Do some operations with resource object.
+        for (unsigned int i = 0; i < resources.size(); ++i)
+        {
+            string logMessage;
+            std::shared_ptr< OCResource > resource = resources.at(i);
+            if (resource)
+            {
+                string resourceURI = resource->host();
+                string hostAddress = resource->uri();
+                logMessage = "FoundHost: " + resource->host() + "<br>";
+                logMessage += "FoundUri : " + resource->uri() + "<br>";
+                logMessage += "----------------------<br>";
+                dlog_print(DLOG_INFO, LOG_TAG, "FoundHost: %s", resourceURI.c_str());
+                dlog_print(DLOG_INFO, LOG_TAG, "FoundUri : %s", hostAddress.c_str());
+                ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
+                                                      &logMessage);
+
+                if (resource->uri() == CONFIGURATION_COLLECTION_RESOURCE_URI)
+                    g_configurationCollection = resource;
+                else if (resource->uri() == DIAGNOSTIC_COLLECTION_RESOURCE_URI)
+                    g_diagnosticsCollection = resource;
+                else if (resource->uri() == FACTORYSET_COLLECTION_RESOURCE_URI)
+                    g_setCollection = resource;
+                else
+                {
+                    isWaiting = 0;
+                    return;
+                }
+            }
+            else
+            {
+                // Resource is invalid
+                logMessage = "Found Resource invalid!";
+                ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
+                                                      &logMessage);
+            }
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+    isWaiting = 0;
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onFoundCollectionResource EXIT!!!!");
+}
+
+// Callback to found candidate resources
+void onFoundCandidateResource(std::vector< std::shared_ptr< OCResource > > resources)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onFoundCandidateCollection ENTRY!!!!");
+    try
+    {
+        // Do some operations with resource object.
+        for (unsigned int i = 0; i < resources.size(); ++i)
+        {
+            string logMessage;
+            std::shared_ptr< OCResource > resource = resources.at(i);
+            if (resource)
+            {
+                // Check if the resource is new one. If so, store it.
+                std::map< std::string, std::shared_ptr< OCResource > >::iterator iter =
+                    resourceTable.find(resource->host() + resource->uri());
+
+                if (iter == resourceTable.end()) // new one
+                {
+                    resourceTable[resource->host() + resource->uri()] = resource;
+
+                    OCResourceHandle foundResourceHandle = NULL;
+                    OCStackResult result = OCPlatform::registerResource(foundResourceHandle,
+                                           resource);
+                    // TODO: null check for foundResourceHandle
+                    dlog_print(DLOG_INFO, LOG_TAG, "#### (%s) REGISTERED",
+                               resource->host().c_str());
+                    if (OC_STACK_OK == result)
+                    {
+                        string resourceURI = resource->host();
+                        string hostAddress = resource->uri();
+                        logMessage = "FoundHost: " + resource->host() + "<br>";
+                        logMessage += "FoundUri: " + resource->uri()
+                                      + " Registered <br>";
+                        logMessage += "----------------------<br>";
+                        dlog_print(DLOG_INFO, LOG_TAG, "Host: %s", resourceURI.c_str());
+                        dlog_print(DLOG_INFO, LOG_TAG, "Uri : %s", hostAddress.c_str());
+                        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
+                                                              &logMessage);
+
+                        if (resource->uri() == CONFIGURATION_RESOURCE_URI &&
+                            NULL != configurationCollectionHandle)
+                        {
+                            OCPlatform::bindResource(configurationCollectionHandle,
+                                                     foundResourceHandle);
+                            configurationFoundHandle = foundResourceHandle;
+                            if (NULL == g_configurationResource)
+                            {
+                                dlog_print(DLOG_INFO, LOG_TAG, "g_configurationResource updated");
+                                g_configurationResource = resource;
+                            }
+                            else
+                            {
+                                dlog_print(DLOG_INFO, LOG_TAG,
+                                           "g_configurationResource is not null");
+                            }
+                        }
+                        else if (resource->uri() == DIAGNOSTIC_RESOURCE_URI &&
+                                 NULL != diagnosticsCollectionHandle)
+                        {
+                            OCPlatform::bindResource(diagnosticsCollectionHandle,
+                                                     foundResourceHandle);
+                            diagnosticsFoundHandle = foundResourceHandle;
+                            if (NULL == g_diagnosticsResource)
+                            {
+                                dlog_print(DLOG_INFO, LOG_TAG,
+                                           "g_diagnosticsResource updated");
+                                g_diagnosticsResource = resource;
+                            }
+                            else
+                            {
+                                dlog_print(DLOG_INFO, LOG_TAG,
+                                           "g_diagnosticsResource is not null");
+                            }
+                        }
+                        else if (resource->uri() == FACTORYSET_RESOURCE_URI &&
+                                 NULL != setCollectionHandle)
+                        {
+                            OCPlatform::bindResource(setCollectionHandle, foundResourceHandle);
+                            setFoundHandle = foundResourceHandle;
+                            if (NULL == g_setResource)
+                            {
+                                dlog_print(DLOG_INFO, LOG_TAG, "g_setResource updated");
+                                g_setResource = resource;
+                            }
+                            else
+                            {
+                                dlog_print(DLOG_INFO, LOG_TAG, "g_setResource is not null");
+                            }
+                        }
+                        configResourceHandleVector.push_back(foundResourceHandle);
+                    }
+                    else
+                    {
+                        logMessage = "Resource Error!";
+                        dlog_print(DLOG_INFO, LOG_TAG, "Resource Error!");
+                        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
+                                                              &logMessage);
+                    }
+                }
+            }
+            else
+            {
+                // Resource is invalid
+                logMessage = "Resource is invalid!";
+                dlog_print(DLOG_INFO, LOG_TAG, "Resource is invalid!");
+                ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
+                                                      &logMessage);
+            }
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    isWaiting = 0;
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onFoundCandidateCollection EXIT!!!!");
+}
+
+// Callback to updateConfiguration
+static void onUpdateConfigurationsCallback(const HeaderOptions &headerOptions,
+        const OCRepresentation &rep,
+        const int eCode)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onUpdateConfigurationsCallback: ENTRY!!!!");
+    isWaiting = 0;
+
+    if (SUCCESS_RESPONSE != eCode)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "#### onUpdateConfigurationsCallback: "
+                   "ERROR RESPONSE!!!!");
+        return;
+    }
+
+    string logMessage = "Resource URI: " + rep.getUri() + "<br>";
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Resource URI: %s", rep.getUri().c_str());
+
+    if (rep.hasAttribute("loc"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Location : %s",
+                   rep.getValue< std::string >("loc").c_str());
+        logMessage = logMessage + "Location : " + rep.getValue< std::string >("loc") + "<br>";
+    }
+    if (rep.hasAttribute("st"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### SystemTime : %s",
+                   rep.getValue< std::string >("st").c_str());
+        logMessage = logMessage + "SystemTime : " + rep.getValue< std::string >("st") + "<br>";
+    }
+    if (rep.hasAttribute("c"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Currency : %s",
+                   rep.getValue< std::string >("c").c_str());
+        logMessage = logMessage + "Currency : " + rep.getValue< std::string >("c") + "<br>";
+    }
+    if (rep.hasAttribute("r"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Region : %s",
+                   rep.getValue< std::string >("r").c_str());
+        logMessage = logMessage + "Region : " + rep.getValue< std::string >("r") + "<br>";
+    }
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog,
+                                          &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onUpdateConfigurationsCallback: EXIT!!!!");
+}
+
+// Callback to getConfiguration
+static void onGetConfigurationsCallback(const HeaderOptions &headerOptions,
+                                        const OCRepresentation &rep,
+                                        const int eCode)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onGetConfigurationsCallback: enter!!!!");
+    isWaiting = 0;
+
+    if (SUCCESS_RESPONSE != eCode)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "#### onGetConfigurationsCallback: "
+                   "ERROR RESPONSE!!!!");
+        return ;
+    }
+
+    string logMessage = "Resource URI: " + rep.getUri() + "<br>";
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Resource URI: %s", rep.getUri().c_str());
+
+    if (rep.hasAttribute("loc"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Location : %s",
+                   rep.getValue< std::string >("loc").c_str());
+        logMessage = logMessage + "Location : " + rep.getValue< std::string >("loc") + "<br>";
+    }
+    if (rep.hasAttribute("st"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### SystemTime : %s",
+                   rep.getValue< std::string >("st").c_str());
+        logMessage = logMessage + "SystemTime : " + rep.getValue< std::string >("st") + "<br>";
+    }
+    if (rep.hasAttribute("c"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Currency : %s",
+                   rep.getValue< std::string >("c").c_str());
+        logMessage = logMessage + "Currency : " + rep.getValue< std::string >("c") + "<br>";
+    }
+    if (rep.hasAttribute("r"))
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Region : %s",
+                   rep.getValue< std::string >("r").c_str());
+        logMessage = logMessage + "Region : " + rep.getValue< std::string >("r") + "<br>";
+    }
+
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onGetConfigurationsCallback: exit!!!!");
+}
+
+static void onFactoryReset(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+                           const int eCode)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onFactoryReset: enter!!!!");
+    isWaiting = 0;
+
+    if (SUCCESS_RESPONSE != eCode)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "#### onFactoryReset: ERROR RESPONSE!!!!");
+        return ;
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Resource URI: %s", rep.getUri().c_str());
+    dlog_print(DLOG_INFO, LOG_TAG, "#### FactoryReset : %s",
+               rep.getValue< std::string >("value").c_str());
+    string logMessage = "Resource URI : " + rep.getUri() + "<br>";
+    logMessage = logMessage + "FactoryReset : " +
+                 rep.getValue< std::string >("value") + "<br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onFactoryReset: exit!!!!");
+}
+
+static void onReboot(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+                     const int eCode)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onReboot: enter!!!!");
+    isWaiting = 0;
+
+    if (SUCCESS_RESPONSE != eCode)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "#### onReboot: ERROR RESPONSE!!!!");
+        return ;
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Resource URI: %s", rep.getUri().c_str());
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Reboot : %s",
+               rep.getValue< std::string >("value").c_str());
+    string logMessage = "Resource URI : " + rep.getUri() + "<br>";
+    logMessage = logMessage + "Reboot : " +
+                 rep.getValue< std::string >("value") + "<br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onReboot: exit!!!!");
+}
+
+static void createResourceCollection(string uri, string typeName, OCResourceHandle &tempHandle)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createResourceCollection: enter!!!!");
+    if (NULL != tempHandle)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Resource already exists!!!!");
+        return;
+    }
+
+    // Create resource collection
+    OCPlatform::registerResource(tempHandle, uri, typeName, BATCH_INTERFACE, NULL,
+                                 OC_DISCOVERABLE);
+    OCPlatform::bindInterfaceToResource(tempHandle, GROUP_INTERFACE);
+    OCPlatform::bindInterfaceToResource(tempHandle, DEFAULT_INTERFACE);
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Resource created : %s", typeName.c_str());
+    string logMessage;
+    logMessage = "Resource created : <br>" + typeName + "<br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createResourceCollection: exit!!!!");
+}
+
+// Unbinds and unregisters all resources
+static void deleteResource(OCResourceHandle &tempCollectionHandle,
+                           OCResourceHandle &tempResourceHandle)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### calling deleteResources ENTRY!!!!");
+
+    if (NULL == tempCollectionHandle || NULL == tempResourceHandle)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Collection or resource does not exists");
+        return;
+    }
+
+    try
+    {
+        OCPlatform::unbindResource(tempCollectionHandle, tempResourceHandle);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### unbindResource DONE!!!!");
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception Occured! (%s)", e.what());
+    }
+
+    try
+    {
+        OCPlatform::unregisterResource(tempResourceHandle);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### unregisterResource DONE!!!!");
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception Occured! (%s)", e.what());
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### calling deleteResources EXIT!!!!");
+}
+
+static void findAllGroups(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### calling findCandidateResources ENTRY!!!!");
+    std::vector<string> resourceTypes;
+    resourceTypes.push_back(CONFIGURATION_COLLECTION_RESOURCE_TYPE);
+
+    if (NULL != configthingsMgr)
+    {
+        configthingsMgr->findCandidateResources(resourceTypes, &onFoundCollectionResource, 5);
+    }
+
+    resourceTypes.clear();
+    resourceTypes.push_back(DIAGNOSTIC_COLLECTION_RESOURCE_TYPE);
+    if (NULL != configthingsMgr)
+    {
+        configthingsMgr->findCandidateResources(resourceTypes, &onFoundCollectionResource, 5);
+    }
+
+    resourceTypes.clear();
+    resourceTypes.push_back(FACTORYSET_COLLECTION_RESOURCE_TYPE);
+    if (NULL != configthingsMgr)
+    {
+        configthingsMgr->findCandidateResources(resourceTypes, &onFoundCollectionResource, 5);
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### calling findCandidateResources EXIT!!!!");
+}
+
+static void findAllResources(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### calling findCandidateResources ENTRY!!!!");
+    std::vector<string> resourceTypes;
+    resourceTypes.push_back("oic.con");
+
+    if (NULL != configthingsMgr)
+    {
+        configthingsMgr->findCandidateResources(resourceTypes, &onFoundCandidateResource, 7);
+    }
+
+    resourceTypes.clear();
+    resourceTypes.push_back("oic.diag");
+    if (NULL != configthingsMgr)
+    {
+        configthingsMgr->findCandidateResources(resourceTypes, &onFoundCandidateResource, 7);
+    }
+
+    resourceTypes.clear();
+    resourceTypes.push_back("factorySet");
+    if (NULL != configthingsMgr)
+    {
+        configthingsMgr->findCandidateResources(resourceTypes, &onFoundCandidateResource, 7);
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### calling findCandidateResources EXIT!!!!");
+}
+
+static void getConfiguration(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getConfiguration ENTRY!!!!");
+    if (NULL == g_configurationCollection || NULL == g_configurationCollection.get())
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Note that you first create a group to use this command");
+        string logMessage = "FIRST CREATE GROUP <br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
+    ConfigurationName name = "all";
+    std::vector< ConfigurationName > configurations;
+    configurations.push_back(name);
+
+    try
+    {
+        configthingsMgr->getConfigurations(g_configurationCollection, configurations,
+                                           &onGetConfigurationsCallback);
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception is occured! (%s)", e.what());
+    }
+
+    isWaiting = 1;
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getConfiguration EXIT!!!!");
+}
+
+// Updates the configuration i.e. region value to INDIA
+static void updateConfiguration(std::string newRegionValue)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### updateConfiguration ENTRY!!!!");
+    dlog_print(DLOG_INFO, LOG_TAG, "#### %s", newRegionValue.c_str());
+
+    if (NULL == g_configurationCollection || NULL == g_configurationCollection.get())
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Note that you first create a group to use this command");
+        string logMessage = "FIRST CREATE GROUP <br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
+    OCStackResult result;
+    ConfigurationName name = "r";
+    ConfigurationValue value = newRegionValue;
+
+    std::map< ConfigurationName, ConfigurationValue > configurations;
+    configurations.insert(std::make_pair(name, value));
+
+    try
+    {
+        result = configthingsMgr->updateConfigurations(g_configurationCollection, configurations,
+                 &onUpdateConfigurationsCallback);
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception is occured! (%s)", e.what());
+    }
+
+    if (OC_STACK_OK == result)
+    {
+        string logMessage = "UpdateConfigurations called successfully<br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### updateConfiguration EXIT!!!!");
+}
+
+// This method will reset all the configuration attributes to their default values
+static void factoryReset(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### factoryReset ENTRY!!!!");
+    if (NULL == g_diagnosticsCollection || NULL == g_diagnosticsCollection.get())
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Note that you first create a group to use this command");
+        string logMessage = "FIRST CREATE GROUP <br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
+    OCStackResult result;
+
+    try
+    {
+        result = configthingsMgr->factoryReset(g_diagnosticsCollection, &onFactoryReset);
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception is occured! (%s)", e.what());
+    }
+
+    if (OC_STACK_OK == result)
+    {
+        string logMessage = "FactoryReset called successfully<br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### factoryReset EXIT!!!!");
+}
+
+// Reboots the server
+static void reboot(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### reboot ENTRY!!!!");
+    if (NULL == g_diagnosticsCollection || NULL == g_diagnosticsCollection.get())
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "Note that you first create a group to use this command");
+        string logMessage = "FIRST CREATE GROUP <br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
+    OCStackResult result;
+
+    try
+    {
+        result = configthingsMgr->reboot(g_diagnosticsCollection, &onReboot);
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception is occured! (%s)", e.what());
+    }
+
+    if (OC_STACK_OK == result)
+    {
+        string logMessage = "Reboot called successfully<br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    }
+    dlog_print(DLOG_INFO, LOG_TAG, "#### reboot EXIT!!!!");
+}
+
+/* For getting list of all supported configuration Values it will give all
+   configuration in JSON format (key-value pair) */
+static void getListOfSupportedConfigurationUnits(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getListOfSupportedConfigurationUnits ENTRY!!!!");
+    string listOfSupportedConfigurationUnits =
+        configthingsMgr->getListOfSupportedConfigurationUnits();
+    dlog_print(DLOG_INFO, LOG_TAG, "#### List : %s", listOfSupportedConfigurationUnits.c_str());
+
+    string logMessage;
+    logMessage = "Supported Configuration List :<br>" + listOfSupportedConfigurationUnits + "<br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getListOfSupportedConfigurationUnits EXIT!!!!");
+}
+
+// Creates all the resources
+static void onStartConfigure()
+{
+    createResourceCollection(CONFIGURATION_COLLECTION_RESOURCE_URI,
+                             CONFIGURATION_COLLECTION_RESOURCE_TYPE,
+                             configurationCollectionHandle);
+    createResourceCollection(DIAGNOSTIC_COLLECTION_RESOURCE_URI,
+                             DIAGNOSTIC_COLLECTION_RESOURCE_TYPE,
+                             diagnosticsCollectionHandle);
+    createResourceCollection(FACTORYSET_COLLECTION_RESOURCE_URI,
+                             FACTORYSET_COLLECTION_RESOURCE_TYPE,
+                             setCollectionHandle);
+}
+
+// Deletes all the resources
+static void onDestroyConfigure()
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Destroy sequence called");
+
+    deleteResource(configurationCollectionHandle, configurationFoundHandle);
+
+    deleteResource(diagnosticsCollectionHandle, diagnosticsFoundHandle);
+
+    deleteResource(setCollectionHandle, setFoundHandle);
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Resources destroyed successfully");
+}
+
+static void
+popup_cancel_clicked_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    region_popup_fields *popup_fields = (region_popup_fields *)data;
+    evas_object_del(popup_fields->popup);
+    free(popup_fields);
+}
+
+static void
+popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    region_popup_fields *popup_fields = (region_popup_fields *)data;
+    Evas_Object *entry = popup_fields->entry;
+    const char *newRegionValue = elm_entry_entry_get(entry);
+    if (NULL == newRegionValue || strlen(newRegionValue) < 1)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL RegionValue");
+        string logMessage = "Region Value should not be NULL<br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+    }
+    else
+    {
+        std::string regionValue = std::string(newRegionValue);
+        updateConfiguration(regionValue);
+    }
+    evas_object_del(popup_fields->popup);
+    free(popup_fields);
+}
+
+static void
+list_update_region_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    if (NULL == g_configurationCollection || NULL == g_configurationCollection.get())
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Note that you first create a group to use this command");
+        string logMessage = "FIRST CREATE GROUP <br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
+    Evas_Object *popup, *btn;
+    Evas_Object *nf = (Evas_Object *)data;
+    Evas_Object *entry;
+    Evas_Object *layout;
+
+    /* popup */
+    popup = elm_popup_add(nf);
+    elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
+    eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
+    evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_object_part_text_set(popup, "title,text", "Enter New Region Value");
+
+    layout = elm_layout_add(popup);
+    elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_region_text");
+    evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_object_content_set(popup, layout);
+
+    entry = elm_entry_add(layout);
+    elm_entry_single_line_set(entry, EINA_TRUE);
+    elm_entry_scrollable_set(entry, EINA_TRUE);
+    evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
+    elm_object_part_text_set(entry, "elm.guide", "region value");
+    elm_object_part_content_set(layout, "elm.swallow.content" , entry);
+
+    region_popup_fields *popup_fields;
+    popup_fields = (region_popup_fields *)malloc(sizeof(region_popup_fields));
+    if (NULL == popup_fields)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Memory allocation failed");
+        popup_fields->popup = NULL;
+        popup_fields->entry = NULL;
+    }
+    else
+    {
+        popup_fields->popup = popup;
+        popup_fields->entry = entry;
+    }
+
+    /* Cancel button */
+    btn = elm_button_add(popup);
+    elm_object_style_set(btn, "popup");
+    elm_object_text_set(btn, "Cancel");
+    elm_object_part_content_set(popup, "button1", btn);
+    evas_object_smart_callback_add(btn, "clicked", popup_cancel_clicked_cb, popup_fields);
+
+    /* Set button */
+    btn = elm_button_add(popup);
+    elm_object_style_set(btn, "popup");
+    elm_object_text_set(btn, "Set");
+    elm_object_part_content_set(popup, "button2", btn);
+    evas_object_smart_callback_add(btn, "clicked", popup_set_clicked_cb, popup_fields);
+
+    evas_object_show(popup);
+}
+
+static void
+list_selected_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    Elm_Object_Item *it = (Elm_Object_Item *)event_info;
+    elm_list_item_selected_set(it, EINA_FALSE);
+}
+
+void
+test_fn(void *data, Evas_Object *obj, void *event_info)
+{
+    if (NULL != log_entry)
+    {
+        elm_entry_entry_append(log_entry, "First item selected");
+        elm_entry_cursor_end_set(log_entry);
+    }
+    else
+    {
+        dlog_print(DLOG_ERROR, "test_fn", "log_entry object is NULL");
+    }
+}
+
+static Eina_Bool
+naviframe_pop_cb(void *data, Elm_Object_Item *it)
+{
+    onDestroyConfigure();
+    if (NULL != log_entry)
+    {
+        evas_object_del(log_entry);
+        log_entry = NULL;
+    }
+    return EINA_TRUE;
+}
+
+// Method to be called when configuration API UI button is selected
+void
+configuration_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    Evas_Object *layout;
+    Evas_Object *scroller;
+    Evas_Object *list;
+    Evas_Object *nf = (Evas_Object *)data;
+    Elm_Object_Item *nf_it;
+
+    // Scroller
+    scroller = elm_scroller_add(nf);
+    elm_scroller_bounce_set(scroller, EINA_FALSE, EINA_TRUE);
+    elm_scroller_policy_set(scroller, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_AUTO);
+
+    // Layout
+    layout = elm_layout_add(nf);
+    elm_layout_file_set(layout, ELM_DEMO_EDJ, "configuration_layout");
+    evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+
+    elm_object_content_set(scroller, layout);
+
+    // List
+    list = elm_list_add(layout);
+    elm_list_mode_set(list, ELM_LIST_COMPRESS);
+    evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
+    elm_object_part_content_set(layout, "list", list);
+    elm_list_go(list);
+
+    // log_entry - text area for log
+    log_entry = elm_entry_add(layout);
+    elm_entry_scrollable_set(log_entry, EINA_TRUE);
+    elm_entry_editable_set(log_entry, EINA_FALSE);
+    elm_object_part_text_set(log_entry, "elm.guide", "logs will be updated here!!!");
+    evas_object_size_hint_weight_set(log_entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    elm_object_part_content_set(layout, "log", log_entry);
+
+    nf_it = elm_naviframe_item_push(nf, "configuration APIs", NULL, NULL, scroller, NULL);
+    elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
+
+    onStartConfigure();
+
+    // Shows the UI list of group APIs
+    elm_list_item_append(list, "Find All Groups", NULL, NULL, findAllGroups, NULL);
+    elm_list_item_append(list, "Find All Resources",
+                         NULL, NULL, findAllResources, NULL);
+    elm_list_item_append(list, "Get a Configuration Resource", NULL, NULL, getConfiguration, NULL);
+    elm_list_item_append(list, "Update Attribute (Region)", NULL, NULL,
+                         list_update_region_cb, nf);
+    elm_list_item_append(list, "Factory Reset", NULL, NULL, factoryReset, NULL);
+    elm_list_item_append(list, "Reboot", NULL, NULL, reboot, NULL);
+    elm_list_item_append(list, "Get Supported Configuration Units", NULL, NULL,
+                         getListOfSupportedConfigurationUnits, NULL);
+
+    elm_list_go(list);
+}
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/src/group.cpp b/service/things-manager/sampleapp/tizen/TMSampleApp/src/group.cpp
new file mode 100644 (file)
index 0000000..3175137
--- /dev/null
@@ -0,0 +1,1151 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <algorithm>
+
+#include "tmsampleapp.h"
+#include "tmutil.h"
+
+using namespace std;
+using namespace OC;
+using namespace OIC;
+
+namespace PH = std::placeholders;
+
+static Evas_Object *log_entry = NULL;
+static Evas_Object *list = NULL;
+static Evas_Object *naviframe = NULL;
+
+string BULBOFF              = "AllBulbOff";
+string BULBON               = "AllBulbOn";
+string resourceURI          = "/core/b/collection";
+string resourceTypeName     = "b.collection";
+
+std::vector< OCResourceHandle > groupResourceHandleVector;
+OCResourceHandle resourceHandle = NULL;
+OCResourceHandle foundResourceHandle = NULL;
+shared_ptr< OCResource > g_resource ;
+std::vector< string > lights;
+
+ThingsManager *groupThingsMgr = new ThingsManager();
+
+typedef struct datetime_popup
+{
+    Evas_Object *popup;
+    Evas_Object *entry;
+} datetime_popup_fields;
+
+// Function to update the log in UI
+void *updateGroupLog(void *data)
+{
+    string *log = (string *)data;
+    // Show the log
+    elm_entry_entry_append(log_entry, (*log).c_str());
+    elm_entry_cursor_end_set(log_entry);
+    return NULL;
+}
+
+void onPut(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+{
+    string logMessage;
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onPut Callback Received!!!!");
+    logMessage += "API Result: Success<br>onPut Callback Received<br>";
+    if (OC_STACK_OK == eCode)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Result is OK");
+    }
+    else
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Invalid Parameter");
+    }
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                          &logMessage);
+}
+
+void onPost(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onPost callback received ENTRY!!!!");
+    string logMessage;
+    logMessage += "API Result: Success<br>onPost Callback Received<br>";
+
+    if (rep.hasAttribute("ActionSet"))
+    {
+        string plainText;
+        if (rep.getValue("ActionSet", plainText))
+        {
+            ActionSet *actionset = groupThingsMgr->getActionSetfromString(plainText);
+            if (NULL != actionset)
+            {
+                dlog_print(DLOG_INFO, LOG_TAG, "#### ACTIONSET NAME :: (%s)",
+                           actionset->actionsetName.c_str());
+                logMessage += "ACTIONSET NAME :: " + actionset->actionsetName + "<br>";
+                for (auto actIter = actionset->listOfAction.begin();
+                     actIter != actionset->listOfAction.end(); ++actIter)
+                {
+                    dlog_print(DLOG_INFO, LOG_TAG, "#### TARGET :: (%s)",
+                               (*actIter)->target.c_str());
+                    logMessage += logMessage + "TARGET :: " + (*actIter)->target + "<br>";
+                    for (auto capaIter = (*actIter)->listOfCapability.begin();
+                         capaIter != (*actIter)->listOfCapability.end(); ++capaIter)
+                    {
+                        dlog_print(DLOG_INFO, LOG_TAG, "#### POWER :: (%s)",
+                                   (*capaIter)->status.c_str());
+                        logMessage += logMessage + "CAPABILITY :: " +
+                                      (*capaIter)->status + "<br>";
+                    }
+                }
+            }
+            delete actionset;
+        }
+    }
+    else if (rep.hasAttribute("DoAction"))
+    {
+        string plainText;
+        if (rep.getValue("DoAction", plainText))
+        {
+            logMessage += plainText + "<br>";
+            dlog_print(DLOG_INFO, LOG_TAG, "#### DO ACTION :: (%s)", plainText.c_str());
+
+        }
+    }
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                          &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### onPost callback received EXIT!!!!");
+}
+
+// Method for Creating the action Set AllBulbOff
+static void createActionSet_AllBulbOff()
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createActionSet_AllBulbOff ENTRY");
+
+    OIC::ActionSet *actionSet = new OIC::ActionSet();
+    actionSet->actionsetName = BULBOFF;
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                              &logMessage);
+        delete actionSet;
+        return;
+    }
+
+    for (int i = 0; i < size; i++)
+    {
+        OIC::Action *action = new OIC::Action();
+        action->target = lights.at(i);
+
+        OIC::Capability *capability = new OIC::Capability();
+        capability->capability = "power";
+        capability->status = "off";
+
+        action->listOfCapability.push_back(capability);
+        actionSet->listOfAction.push_back(action);
+    }
+    dlog_print(DLOG_INFO, LOG_TAG, "#### G_URI: %s", g_resource->uri().c_str());
+    dlog_print(DLOG_INFO, LOG_TAG, "#### G_HOST: %S", g_resource->host().c_str());
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->addActionSet(g_resource, actionSet, onPut);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+    delete actionSet;
+
+    string logMessage = "Create actionset AllBulbOFF success <br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createActionSet_AllBulbOff EXIT");
+}
+
+/* Method for Creating the action Set AllBulbOn
+   once we create the ActionSet we can execute Action Set using executeActionSetOn()
+   or delete using deleteActionSetOn() */
+static void createActionSet_AllBulbOn()
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createActionSet_AllBulbOn ENTRY");
+
+    OIC::ActionSet *actionSet = new OIC::ActionSet();
+    actionSet->actionsetName = BULBON;
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        delete actionSet;
+        return;
+    }
+
+    for (int i = 0; i < size; i++)
+    {
+        OIC::Action *action = new OIC::Action();
+        action->target = lights.at(i);
+
+        OIC::Capability *capability = new OIC::Capability();
+        capability->capability = "power";
+        capability->status = "on";
+
+        action->listOfCapability.push_back(capability);
+        actionSet->listOfAction.push_back(action);
+    }
+    string URI = g_resource->uri();
+    string host = g_resource->host();
+    dlog_print(DLOG_INFO, LOG_TAG, "#### G_URI: %s", g_resource->uri().c_str());
+    dlog_print(DLOG_INFO, LOG_TAG, "#### G_HOST: %S", g_resource->host().c_str());
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->addActionSet(g_resource, actionSet, onPut);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+    delete actionSet;
+
+    string logMessage = "Create actionset AllBulbON success <br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createActionSet_AllBulbOff OFF EXIT");
+}
+
+static void createRecursiveActionSet_AllBulbOn(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createRecursiveActionSet_AllBulbOn ENTRY");
+    string actionsetDesc;
+    ActionSet *allBulbOn = new ActionSet();
+    allBulbOn->type = OIC::ACTIONSET_TYPE::RECURSIVE;
+
+    allBulbOn->actionsetName = "AllBulbOnRecursiveCall";
+    allBulbOn->mTime.tm_year = 0;
+    allBulbOn->mTime.tm_mon = 0;
+    allBulbOn->mTime.tm_mday = 0;
+    allBulbOn->mTime.tm_hour = 0;
+    allBulbOn->mTime.tm_min = 0;
+    allBulbOn->mTime.tm_sec = 5;
+
+    allBulbOn->setDelay(allBulbOn->getSecAbsTime());
+
+    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+    {
+        Action *action = new Action();
+        action->target = (*iter);
+
+        Capability *capa = new Capability();
+        capa->capability = "power";
+        capa->status = "on";
+
+        action->listOfCapability.push_back(capa);
+        allBulbOn->listOfAction.push_back(action);
+    }
+    if (g_resource)
+    {
+        groupThingsMgr->addActionSet(g_resource, allBulbOn, onPut);
+    }
+
+    delete allBulbOn;
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createRecursiveActionSet_AllBulbOn EXIT");
+}
+
+static void createScheduledActionSet_AllBulbOff(int date, int month, int year,
+        int hour, int minute, int second)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createScheduledActionSet_AllBulbOff ENTRY");
+    string actionsetDesc;
+    ActionSet *allBulbOff = new ActionSet();
+    allBulbOff->type = OIC::ACTIONSET_TYPE::SCHEDULED;
+    allBulbOff->actionsetName = "AllBulbOffScheduledCall";
+    allBulbOff->mTime.tm_year = year;
+    allBulbOff->mTime.tm_mon = month;
+    allBulbOff->mTime.tm_mday = date;
+    allBulbOff->mTime.tm_hour = hour;
+    allBulbOff->mTime.tm_min = minute;
+    allBulbOff->mTime.tm_sec = second;
+    dlog_print(DLOG_INFO, LOG_TAG, "#### allBulbOff->mTime.tm_year :: %ld",
+               allBulbOff->mTime.tm_year);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### allBulbOff->mTime.tm_mon :: %ld",
+               allBulbOff->mTime.tm_mon);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### allBulbOff->mTime.tm_mday :: %ld",
+               allBulbOff->mTime.tm_mday);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### allBulbOff->mTime.tm_hour :: %ld",
+               allBulbOff->mTime.tm_hour);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### allBulbOff->mTime.tm_min :: %ld",
+               allBulbOff->mTime.tm_min);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### allBulbOff->mTime.tm_sec :: %ld",
+               allBulbOff->mTime.tm_sec);
+
+    allBulbOff->setDelay(allBulbOff->getSecondsFromAbsoluteTime());
+
+    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+    {
+        Action *action = new Action();
+        action->target = (*iter);
+
+        Capability *capa = new Capability();
+        capa->capability = "power";
+        capa->status = "off";
+
+        action->listOfCapability.push_back(capa);
+        allBulbOff->listOfAction.push_back(action);
+    }
+    if (g_resource)
+    {
+        groupThingsMgr->addActionSet(g_resource, allBulbOff, onPut);
+    }
+
+    delete allBulbOff;
+    dlog_print(DLOG_INFO, LOG_TAG, "#### createScheduledActionSet_AllBulbOff EXIT");
+}
+
+static void scheduled_AllbulbOff(void *data, Evas_Object *obj, void *event_info)
+{
+    groupThingsMgr->executeActionSet(g_resource, "AllBulbOffScheduledCall", &onPost);
+}
+
+static void scheduled_AllbulbOffEx(void *data, Evas_Object *obj, void *event_info)
+{
+    groupThingsMgr->executeActionSet(g_resource, "AllBulbOffScheduledCall", 10, &onPost);
+}
+
+static void cancelScheduled_AllBulbOff(void *data, Evas_Object *obj, void *event_info)
+{
+    groupThingsMgr->cancelActionSet(g_resource, "AllBulbOffScheduledCall", &onPost);
+}
+
+static void recursive_allBulbOn(void *data, Evas_Object *obj, void *event_info)
+{
+    groupThingsMgr->executeActionSet(g_resource, "AllBulbOnRecursiveCall", &onPost);
+}
+
+static void recursive_allBulbOnEx(void *data, Evas_Object *obj, void *event_info)
+{
+    groupThingsMgr->executeActionSet(g_resource, "AllBulbOnRecursiveCall", 10, &onPost);
+}
+
+static void cancelRecursive_allBulbOn(void *data, Evas_Object *obj, void *event_info)
+{
+
+    groupThingsMgr->cancelActionSet(g_resource, "AllBulbOnRecursiveCall", &onPost);
+}
+
+/* Method for executing the action Set AllBulbOff that we have created using
+   createActionSet_AllBulbOff() */
+static void executeActionSetOff(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### executeActionSetOff ENTRY");
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        return;
+    }
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->executeActionSet(g_resource, BULBOFF, &onPost);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    string logMessage = "Actionset OFF called successfully <br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### executeActionSetOff EXIT");
+}
+
+/* Method for executing the action Set AllBulbOn that we have created using
+   createActionSet_AllBulbOn() */
+static void executeActionSetOn(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### executeActionSetOn ENTRY");
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        return;
+    }
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->executeActionSet(g_resource, BULBON, &onPost);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    string logMessage = "Actionset ON called successfully <br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### executeActionSetOn EXIT");
+}
+
+/* Method for getting the action Set AllBulbOff that we have created using
+   createActionSet_AllBulbOff() */
+static void getActionSetOff(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getActionSetOff ENTRY");
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        return;
+    }
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->getActionSet(g_resource, BULBOFF, &onPost);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getActionSetOff EXIT");
+}
+
+/* Method for getting the action Set AllBulbOn that we have created using
+   createActionSet_AllBulbOn() */
+static void getActionSetOn(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getActionSetOn ENTRY");
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        return;
+    }
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->getActionSet(g_resource, BULBON, &onPost);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### getActionSetOn EXIT");
+}
+
+/* Method for deleting the action Set AllBulbOff that we have created using
+   createActionSet_AllBulbOff() */
+static void deleteActionSetOff(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### deleteActionSetOff ENTRY");
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        return;
+    }
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->deleteActionSet(g_resource, BULBOFF, &onPost);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    string logMessage = "Actionset OFF DELETED <br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### deleteActionSetOff EXIT");
+}
+
+/* Method for deleting the action Set AllBulbOn that we have created using
+   createActionSet_AllBulbOn() */
+static void deleteActionSetOn(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### deleteActionSetOn ENTRY");
+    int size = lights.size();
+
+    if (0 == size)
+    {
+        string logMessage = "NO LIGHTSERVER FOUND <br>";
+        logMessage += "----------------------<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### NO LIGHT SERVER FOUND");
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+        return;
+    }
+
+    try
+    {
+        if (g_resource)
+        {
+            groupThingsMgr->deleteActionSet(g_resource, BULBON, &onPost);
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    string logMessage = "Actionset ON DELETED <br>";
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+    dlog_print(DLOG_INFO, LOG_TAG, "#### deleteActionSetOn EXIT");
+}
+
+void onObserve(const HeaderOptions headerOptions, const OCRepresentation &rep, const int &eCode,
+               const int &sequenceNumber)
+{
+    string logMessage;
+    char *buf;
+    if (OC_STACK_OK == eCode)
+    {
+        int level;
+        buf = (char *)malloc(4 * sizeof(char));
+        if (NULL == buf)
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, " buf malloc failed");
+            return;
+        }
+        sprintf(buf, "%d", sequenceNumber);
+        logMessage = "OBSERVE RESULT <br>";
+        logMessage += "Sequencenumber:" + string(buf) + "<br>";
+
+        if (rep.getValue("level", level))
+        {
+            if (level == 0)
+            {
+                createActionSet_AllBulbOn();
+                executeActionSetOn(NULL, NULL, NULL);
+            }
+            else
+            {
+                createActionSet_AllBulbOff();
+                executeActionSetOff(NULL, NULL, NULL);
+            }
+        }
+        sprintf(buf, "%d", level);
+        logMessage += "level:" + string(buf) + "<br>";
+    }
+    else
+    {
+        logMessage = "onObserve error!!!";
+    }
+    logMessage += "----------------------<br>";
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                          &logMessage);
+}
+
+// Callback to be called when resources are found in the network
+void foundResources(std::vector< std::shared_ptr< OC::OCResource > > listOfResource)
+{
+    try
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### foundResources entry!!!!");
+
+        for (auto rsrc = listOfResource.begin(); rsrc != listOfResource.end(); ++rsrc)
+        {
+            string resourceURI = (*rsrc)->uri();
+            string hostAddress = (*rsrc)->host();
+
+            dlog_print(DLOG_INFO, LOG_TAG, "#### found uri: %s", resourceURI.c_str());
+            dlog_print(DLOG_INFO, LOG_TAG, "#### found host address: %s", hostAddress.c_str());
+            string logMessage = "URI: " + resourceURI + "<br>";
+            logMessage = logMessage + "Host:" + hostAddress + "<br>";
+            logMessage += "----------------------<br>";
+
+            if (resourceURI == "/a/light")
+            {
+                bool found;
+                found = std::find(lights.begin(), lights.end(),
+                                  hostAddress + resourceURI) != lights.end();
+                if (found == false)
+                {
+                    lights.push_back((hostAddress + resourceURI));
+
+                    try
+                    {
+                        dlog_print(DLOG_INFO, LOG_TAG, "#### Registering Resource");
+                        OCStackResult result = OCPlatform::registerResource(foundResourceHandle,
+                                               (*rsrc));
+                        dlog_print(DLOG_INFO, LOG_TAG, "#### %s REGISTERED", resourceURI.c_str());
+                        if (result == OC_STACK_OK)
+                        {
+                            OCPlatform::bindResource(resourceHandle, foundResourceHandle);
+                            dlog_print(DLOG_INFO, LOG_TAG, "#### Bind Resource Done");
+                            groupResourceHandleVector.push_back(foundResourceHandle);
+                        }
+                        else
+                        {
+                            dlog_print(DLOG_ERROR, LOG_TAG, "#### Register Resource ERROR");
+                        }
+                    }
+                    catch (std::exception &e)
+                    {
+                        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+                    }
+                }
+            }
+            else if (resourceURI == "/core/bookmark")
+            {
+                logMessage += "OBSERVING : " + resourceURI + "<br>";
+                logMessage += "----------------------<br>";
+                (*rsrc)->observe(ObserveType::Observe, QueryParamsMap(), &onObserve);
+                dlog_print(DLOG_INFO, LOG_TAG, "#### after calling observe() for bookmark!!!!");
+            }
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                                  &logMessage);
+        }
+
+        dlog_print(DLOG_INFO, LOG_TAG, "#### foundResources exit!!!!");
+    }
+    catch (...)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Exception caught in foundResources");
+    }
+}
+
+static void create_group()
+{
+    if (NULL != groupThingsMgr)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### calling findCandidateResources from "
+                   "create_group!!!!");
+        vector< string > types;
+        types.push_back("core.light");
+        groupThingsMgr->findCandidateResources(types, &foundResources, 5);
+    }
+
+    try
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### calling registerResource from create_group!!!!");
+        OCPlatform::registerResource(resourceHandle, resourceURI, resourceTypeName,
+                                     BATCH_INTERFACE, NULL,
+                                     OC_DISCOVERABLE | OC_OBSERVABLE);
+
+        if (NULL != resourceHandle)
+            dlog_print(DLOG_INFO, LOG_TAG, "#### Obtained resourceHandle from "
+                       "registerResource!!!!");
+
+        dlog_print(DLOG_INFO, LOG_TAG, "#### calling bindInterfaceToResource from "
+                   "create_group!!!!");
+        OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE);
+        OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE);
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+}
+
+// Method for Finding the Light Resource
+void findLightResource(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### findLightResource ENTRY");
+    if (NULL != groupThingsMgr)
+    {
+        vector< string > types;
+        types.push_back("core.light");
+        OCStackResult result = groupThingsMgr->findCandidateResources(types, &foundResources, 5);
+        if (result == OC_STACK_OK)
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### create_group -- findCandidateResources :: "
+                       "OC_STACK_OK!!!!");
+        }
+        else
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### create_group - findCandidateResources failed!!");
+        }
+    }
+    dlog_print(DLOG_INFO, LOG_TAG, "#### findLightResource EXIT");
+}
+
+// Method for observing the Bookmark Resource
+void observeBookMark(void *data, Evas_Object *obj, void *event_info)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### observeBookMark ENTRY");
+    if (NULL != groupThingsMgr)
+    {
+        vector< string > types;
+        types.push_back("core.bookmark");
+        OCStackResult result = groupThingsMgr->findCandidateResources(types, &foundResources, 5);
+        if (OC_STACK_OK == result)
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### create_group - findCandidateResources :: "
+                       "OC_STACK_OK!!!!");
+        }
+        else
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### create_group - findCandidateResources failed!!");
+        }
+    }
+    dlog_print(DLOG_INFO, LOG_TAG, "#### observeBookMark EXIT");
+}
+
+static void onDestroy()
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### Destroy sequence called");
+
+    try
+    {
+        if (NULL != foundResourceHandle)
+        {
+            OCPlatform::unregisterResource(foundResourceHandle);
+            dlog_print(DLOG_INFO, LOG_TAG, "#### Light Resource unregistered");
+            lights.clear();
+        }
+        else
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### No resouceHandle found to unregister");
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+
+    try
+    {
+        if (NULL != resourceHandle)
+        {
+            // Unbind Light resource
+            if (NULL != foundResourceHandle)
+            {
+                OCPlatform::unbindResource(resourceHandle, foundResourceHandle);
+                dlog_print(DLOG_INFO, LOG_TAG, "#### Resource Unbind Done");
+            }
+            OCPlatform::unregisterResource(resourceHandle);
+            dlog_print(DLOG_INFO, LOG_TAG, "#### Group Unregistered");
+        }
+        else
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### foundResourceHandle is NULL");
+        }
+    }
+    catch (std::exception &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+}
+
+static void createActionSet(void *data, Evas_Object *obj, void *event_info)
+{
+    createActionSet_AllBulbOff();
+    createActionSet_AllBulbOn();
+}
+
+static void
+popup_cancel_clicked_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    datetime_popup_fields *popup_fields = (datetime_popup_fields *)data;
+    evas_object_del(popup_fields->popup);
+    free(popup_fields);
+}
+
+static int parseString(const char *str, int slen, int *beg, int what)
+{
+    int i, val = 0, ch = '/';
+    if (2 == what)
+    {
+        ch = ' ';
+    }
+    else if (3 <= what)
+    {
+        if (5 == what)
+        {
+            ch = '\0';
+        }
+        else
+        {
+            ch = ':';
+        }
+    }
+    // Remove whitespaces(if any) at the beginning
+    while (str[*beg] == ' ')
+    {
+        (*beg)++;
+    }
+    for (i = *beg; i < slen; i++)
+    {
+        if (str[i] != ch)
+        {
+            val = (val * 10) + (str[i] - 48);
+            continue;
+        }
+        break;
+    }
+    (*beg) = i + 1;
+    return val;
+}
+
+static bool validate(int date, int month, int year, int hour, int minute, int second)
+{
+    if (date <= 0 || month <= 0 || year <= 0 || hour < 0 || minute < 0 || second < 0
+        || month >= 13 || hour >= 24 || minute >= 60 || second >= 60)
+    {
+        return false;
+    }
+    return true;
+}
+
+static void
+popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    datetime_popup_fields *popup_fields = (datetime_popup_fields *)data;
+    Evas_Object *entry = popup_fields->entry;
+    const char *dateTimeValue = elm_entry_entry_get(entry);
+    int len;
+    len = strlen(dateTimeValue);
+    if (NULL == dateTimeValue || 1 > len)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL DateTime Value");
+        string logMessage = "DateTime should not be NULL<br>";
+        logMessage += "----------------------<br>";
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
+    }
+    else
+    {
+        int date, month, year, hour, minute, second;
+        int beg = 0;
+        date = parseString(dateTimeValue, len, &beg, 0);
+        month = parseString(dateTimeValue, len, &beg, 1);
+        year = parseString(dateTimeValue, len, &beg, 2);
+        hour = parseString(dateTimeValue, len, &beg, 3);
+        minute = parseString(dateTimeValue, len, &beg, 4);
+        second = parseString(dateTimeValue, len, &beg, 5);
+
+        dlog_print(DLOG_INFO, LOG_TAG, "#### %d", date);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### %d", month);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### %d", year);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### %d", hour);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### %d", minute);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### %d", second);
+        bool valid = validate(date, month, year, hour, minute, second);
+        if (valid)
+        {
+            createScheduledActionSet_AllBulbOff(date, month, year, hour, minute, second);
+        }
+        else
+        {
+            dlog_print(DLOG_INFO, LOG_TAG, "#### Incorrect date/time values");
+            string logMessage = "Incorrect date/time value<br>";
+            logMessage += "----------------------<br>";
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                                  &logMessage);
+        }
+    }
+    evas_object_del(popup_fields->popup);
+    free(popup_fields);
+}
+
+static void
+list_scheduled_actionset_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    Evas_Object *popup, *btn;
+    Evas_Object *nf = naviframe;
+    Evas_Object *entry;
+    Evas_Object *layout;
+
+    /* popup */
+    popup = elm_popup_add(nf);
+    elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
+    eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
+    evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_object_part_text_set(popup, "title,text", "Enter the date and time");
+
+    layout = elm_layout_add(popup);
+    elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_datetime_text");
+    evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_object_content_set(popup, layout);
+
+    entry = elm_entry_add(layout);
+    elm_entry_single_line_set(entry, EINA_TRUE);
+    elm_entry_scrollable_set(entry, EINA_TRUE);
+    evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
+    elm_object_part_text_set(entry, "elm.guide", "dd/mm/yyyy hh:mm:ss");
+    elm_entry_input_panel_layout_set(entry, ELM_INPUT_PANEL_LAYOUT_NUMBER);
+    elm_object_part_content_set(layout, "elm.swallow.content", entry);
+
+    datetime_popup_fields *popup_fields;
+    popup_fields = (datetime_popup_fields *)malloc(sizeof(datetime_popup_fields));
+    if (NULL == popup_fields)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Memory allocation failed");
+        popup_fields->popup = NULL;
+        popup_fields->entry = NULL;
+    }
+    else
+    {
+        popup_fields->popup = popup;
+        popup_fields->entry = entry;
+    }
+
+    /* Cancel button */
+    btn = elm_button_add(popup);
+    elm_object_style_set(btn, "popup");
+    elm_object_text_set(btn, "Cancel");
+    elm_object_part_content_set(popup, "button1", btn);
+    evas_object_smart_callback_add(btn, "clicked", popup_cancel_clicked_cb, popup_fields);
+
+    /* Set button */
+    btn = elm_button_add(popup);
+    elm_object_style_set(btn, "popup");
+    elm_object_text_set(btn, "Set");
+    elm_object_part_content_set(popup, "button2", btn);
+    evas_object_smart_callback_add(btn, "clicked", popup_set_clicked_cb, popup_fields);
+
+    evas_object_show(popup);
+}
+
+void *showGroupAPIs(void *data)
+{
+    // Add items to the list only if the list is empty
+    const Eina_List *eina_list = elm_list_items_get(list);
+    int count = eina_list_count(eina_list);
+    if (!count)
+    {
+        elm_list_item_append(list, "1. Create ActionSet<br>(ALLBULBON and ALLBULBOFF)", NULL, NULL,
+                             createActionSet, NULL);
+
+        elm_list_item_append(list, "2. Execute ActionSet (ALLBULBON)", NULL, NULL,
+                             executeActionSetOn, NULL);
+
+        elm_list_item_append(list, "3. Execute ActionSet (ALLBULBOFF)", NULL, NULL,
+                             executeActionSetOff, NULL);
+
+        elm_list_item_append(list, "4. Create ActionSet<br>(Recursive_ALLBULBON)", NULL, NULL,
+                             createRecursiveActionSet_AllBulbOn, NULL);
+
+        elm_list_item_append(list, "    4.1 Execute ActionSet", NULL, NULL,
+                             recursive_allBulbOn, NULL);
+
+        elm_list_item_append(list, "    4.2 Cancel ActionSet", NULL, NULL,
+                             cancelRecursive_allBulbOn, NULL);
+
+        elm_list_item_append(list, "5. Create ActionSet<br>(Scheduled_ALLBULBOFF)", NULL, NULL,
+                             list_scheduled_actionset_cb, NULL);
+
+        elm_list_item_append(list, "    5.1 Execute ActionSet", NULL, NULL,
+                             scheduled_AllbulbOff, NULL);
+
+        elm_list_item_append(list, "    5.2 Cancel ActionSet", NULL, NULL,
+                             cancelScheduled_AllBulbOff, NULL);
+
+        elm_list_item_append(list, "6. Get ActionSet (All BULBOFF)", NULL, NULL,
+                             getActionSetOff, NULL);
+
+        elm_list_item_append(list, "7. Delete ActionSet (All BULBOFF)", NULL, NULL,
+                             deleteActionSetOff, NULL);
+
+        elm_list_item_append(list, "8. Find BookMark to Observe", NULL, NULL,
+                             observeBookMark, NULL);
+
+        elm_list_go(list);
+    }
+    return NULL;
+}
+
+// Callback to be called when a resource is found in the network
+void foundResource(shared_ptr< OCResource > resource)
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### foundResource entry!!!!");
+
+    if (resource)
+    {
+        string resourceURI = resource->uri();
+        string hostAddress = resource->host();
+        string logMessage;
+        if (resourceURI == "/core/b/collection")
+        {
+            g_resource = resource;
+            dlog_print(DLOG_INFO, LOG_TAG, "#### FOUND URI: %s", resourceURI.c_str());
+            dlog_print(DLOG_INFO, LOG_TAG, "#### FOUND HOST: %s", hostAddress.c_str());
+            logMessage = "FOUND RESOURCE URI <br>" + resourceURI + "<br>";
+            logMessage += "FOUND RESOURCE HOST <br>" + hostAddress + "<br>";
+            logMessage += "----------------------<br>";
+            // Show the UI list of group APIs
+            ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showGroupAPIs, NULL);
+
+        }
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+                                              &logMessage);
+    }
+
+    dlog_print(DLOG_INFO, LOG_TAG, "#### foundResource exit!!!!");
+}
+
+static void list_selected_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    Elm_Object_Item *it = (Elm_Object_Item *)event_info;
+    elm_list_item_selected_set(it, EINA_FALSE);
+}
+
+// Method for Finding the Group
+static void find_group()
+{
+    dlog_print(DLOG_INFO, LOG_TAG, "#### findGroup ENTRY");
+    vector< string > resourceTypes;
+    resourceTypes.push_back(resourceTypeName);
+    OCStackResult result = groupThingsMgr->findGroup(resourceTypes, &foundResource);
+    if (OC_STACK_OK == result)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### findGroup returned OC_STACK_OK");
+    }
+    else
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "#### findGroup failed");
+    }
+    dlog_print(DLOG_INFO, LOG_TAG, "#### findGroup EXIT");
+}
+
+// Method to be called when the Find Group UI Button is selected
+static void
+find_group_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    if (NULL != list)
+    {
+        find_group();
+    }
+    else
+    {
+        dlog_print(DLOG_ERROR, "find_group_cb", "list is NULL - So unable to add items!!!");
+    }
+}
+
+static Eina_Bool
+naviframe_pop_cb(void *data, Elm_Object_Item *it)
+{
+    onDestroy();
+
+    if (NULL != log_entry)
+    {
+        evas_object_del(log_entry);
+        log_entry = NULL;
+    }
+    if (NULL != list)
+    {
+        evas_object_del(list);
+        list = NULL;
+    }
+    return EINA_TRUE;
+}
+
+// Method to be called when the Group APIs UI Button is selected
+void group_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    Evas_Object *layout;
+    Evas_Object *scroller;
+    Evas_Object *nf = (Evas_Object *)data;
+    Evas_Object *find_button;
+    Elm_Object_Item *nf_it;
+
+    naviframe = nf;
+
+    // Scroller
+    scroller = elm_scroller_add(nf);
+    elm_scroller_bounce_set(scroller, EINA_FALSE, EINA_TRUE);
+    elm_scroller_policy_set(scroller, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_AUTO);
+
+    // Layout
+    layout = elm_layout_add(nf);
+    elm_layout_file_set(layout, ELM_DEMO_EDJ, "group_layout");
+    evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+
+    elm_object_content_set(scroller, layout);
+
+    // Button
+    find_button = elm_button_add(layout);
+    elm_object_part_content_set(layout, "find_button", find_button);
+    elm_object_text_set(find_button, "Find Group");
+    evas_object_smart_callback_add(find_button, "clicked", find_group_cb, NULL);
+
+    // List
+    list = elm_list_add(layout);
+    elm_list_mode_set(list, ELM_LIST_COMPRESS);
+    evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
+    elm_object_part_content_set(layout, "list", list);
+    elm_list_go(list);
+
+    // log_entry - textarea for log
+    log_entry = elm_entry_add(layout);
+    elm_entry_scrollable_set(log_entry, EINA_TRUE);
+    elm_entry_editable_set(log_entry, EINA_FALSE);
+    elm_object_part_text_set(log_entry, "elm.guide", "Logs will be updated here!!!");
+    evas_object_size_hint_weight_set(log_entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
+    elm_object_part_content_set(layout, "log", log_entry);
+
+    nf_it = elm_naviframe_item_push(nf, "Group APIs", NULL, NULL, scroller, NULL);
+    elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
+
+    create_group();
+}
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/src/tmsampleapp.cpp b/service/things-manager/sampleapp/tizen/TMSampleApp/src/tmsampleapp.cpp
new file mode 100644 (file)
index 0000000..f78b844
--- /dev/null
@@ -0,0 +1,256 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "tmsampleapp.h"
+#include <tizen.h>
+
+typedef struct appdata
+{
+    Evas_Object *win;
+    Evas_Object *conform;
+    Evas_Object *layout;
+    Evas_Object *nf;
+    Evas_Object *findButton;
+    Evas_Object *logtext;
+    Evas_Object *listview;
+} appdata_s;
+
+static void
+win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
+{
+    ui_app_exit();
+}
+
+static void
+list_selected_cb(void *data, Evas_Object *obj, void *event_info)
+{
+    Elm_Object_Item *it = (Elm_Object_Item *)event_info;
+    elm_list_item_selected_set(it, EINA_FALSE);
+}
+
+static Eina_Bool
+naviframe_pop_cb(void *data, Elm_Object_Item *it)
+{
+    ui_app_exit();
+    return EINA_FALSE;
+}
+
+static void
+create_list_view(appdata_s *ad)
+{
+    Evas_Object *list;
+    Evas_Object *btn;
+    Evas_Object *nf = ad->nf;
+    Elm_Object_Item *nf_it;
+
+    // List
+    list = elm_list_add(nf);
+    elm_list_mode_set(list, ELM_LIST_COMPRESS);
+    evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
+
+    // Main Menu Items Here
+    elm_list_item_append(list, "Group APIs", NULL, NULL, group_cb, nf);
+    elm_list_item_append(list, "Configuration APIs", NULL, NULL, configuration_cb, nf);
+
+    elm_list_go(list);
+
+    // This button is set for devices which doesn't have H/W back key.
+    btn = elm_button_add(nf);
+    elm_object_style_set(btn, "naviframe/end_btn/default");
+    nf_it = elm_naviframe_item_push(nf, "Things Manager", btn, NULL, list, NULL);
+    elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
+}
+
+
+static void
+create_base_gui(appdata_s *ad)
+{
+    // Window
+    ad->win = elm_win_util_standard_add(PACKAGE, PACKAGE);
+    elm_win_conformant_set(ad->win, EINA_TRUE);
+    elm_win_autodel_set(ad->win, EINA_TRUE);
+
+    if (elm_win_wm_rotation_supported_get(ad->win))
+    {
+        int rots[4] = { 0, 90, 180, 270 };
+        elm_win_wm_rotation_available_rotations_set(ad->win, (const int *)(&rots), 4);
+    }
+
+    evas_object_smart_callback_add(ad->win, "delete,request", win_delete_request_cb, NULL);
+
+    // Conformant
+    ad->conform = elm_conformant_add(ad->win);
+    evas_object_size_hint_weight_set(ad->conform, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_win_resize_object_add(ad->win, ad->conform);
+    evas_object_show(ad->conform);
+
+    // Base Layout
+    ad->layout = elm_layout_add(ad->conform);
+    evas_object_size_hint_weight_set(ad->layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+    elm_layout_theme_set(ad->layout, "layout", "application", "default");
+    evas_object_show(ad->layout);
+
+    elm_object_content_set(ad->conform, ad->layout);
+
+    // Naviframe
+    ad->nf = elm_naviframe_add(ad->layout);
+    create_list_view(ad);
+    elm_object_part_content_set(ad->layout, "elm.swallow.content", ad->nf);
+    eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_BACK, eext_naviframe_back_cb, NULL);
+    eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_MORE, eext_naviframe_more_cb, NULL);
+
+    // Show window after base gui is set up
+    evas_object_show(ad->win);
+}
+
+// Configures the OCPlatform
+static void
+configure_platform()
+{
+    try
+    {
+        PlatformConfig config
+        { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+        OCPlatform::Configure(config);
+
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration done!!!!");
+    }
+    catch (OCException &e)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+    }
+}
+
+static bool
+app_create(void *data)
+{
+    /* Hook to take necessary actions before main event loop starts
+       Initialize UI resources and application's data
+       If this function returns true, the main loop of application starts
+       If this function returns false, the application is terminated */
+    appdata_s *ad = (appdata_s *)data;
+
+    elm_app_base_scale_set(1.8);
+
+    create_base_gui(ad);
+
+    configure_platform();
+
+    return true;
+}
+
+static void
+app_control(app_control_h app_control, void *data)
+{
+    // Handle the launch request.
+}
+
+static void
+app_pause(void *data)
+{
+    // Take necessary actions when application becomes invisible.
+}
+
+static void
+app_resume(void *data)
+{
+    // Take necessary actions when application becomes visible.
+}
+
+static void
+app_terminate(void *data)
+{
+    // Release all resources.
+}
+
+static void
+ui_app_lang_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LANGUAGE_CHANGED
+    char *locale = NULL;
+    system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale);
+    elm_language_set(locale);
+    free(locale);
+    return;
+}
+
+static void
+ui_app_orient_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_DEVICE_ORIENTATION_CHANGED
+    return;
+}
+
+static void
+ui_app_region_changed(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_REGION_FORMAT_CHANGED
+}
+
+static void
+ui_app_low_battery(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_BATTERY
+}
+
+static void
+ui_app_low_memory(app_event_info_h event_info, void *user_data)
+{
+    // APP_EVENT_LOW_MEMORY
+}
+
+int
+main(int argc, char *argv[])
+{
+    appdata_s ad = {0,};
+    int ret = 0;
+
+    ui_app_lifecycle_callback_s event_callback = {0,};
+    app_event_handler_h handlers[5] = {NULL, };
+
+    event_callback.create = app_create;
+    event_callback.terminate = app_terminate;
+    event_callback.pause = app_pause;
+    event_callback.resume = app_resume;
+    event_callback.app_control = app_control;
+
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY,
+                             ui_app_low_battery, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY,
+                             ui_app_low_memory, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED],
+                             APP_EVENT_DEVICE_ORIENTATION_CHANGED,
+                             ui_app_orient_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED],
+                             APP_EVENT_LANGUAGE_CHANGED,
+                             ui_app_lang_changed, &ad);
+    ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED],
+                             APP_EVENT_REGION_FORMAT_CHANGED,
+                             ui_app_region_changed, &ad);
+    ui_app_remove_event_handler(handlers[APP_EVENT_LOW_MEMORY]);
+
+    ret = ui_app_main(argc, argv, &event_callback, &ad);
+    if (APP_ERROR_NONE != ret)
+    {
+        dlog_print(DLOG_ERROR, LOG_TAG, "app_main() is failed. err = %d", ret);
+    }
+    return ret;
+}
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/src/tmutil.cpp b/service/things-manager/sampleapp/tizen/TMSampleApp/src/tmutil.cpp
new file mode 100644 (file)
index 0000000..1b9f3b9
--- /dev/null
@@ -0,0 +1,130 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "tmutil.h"
+
+// Utility function to return the string equivalent of OCStackResult for the given integer value
+std::string getOCStackResultStringFromInt(int result)
+{
+    string ocresultstr;
+
+    switch (result)
+    {
+        case 0 :
+            ocresultstr = "OC_STACK_OK";
+            break;
+        case 1 :
+            ocresultstr = "OC_STACK_RESOURCE_CREATED";
+            break;
+        case 2 :
+            ocresultstr = "OC_STACK_RESOURCE_DELETED";
+            break;
+        case 3 :
+            ocresultstr = "OC_STACK_CONTINUE";
+            break;
+        case 20 :
+            ocresultstr = "OC_STACK_INVALID_URI";
+            break;
+        case 21 :
+            ocresultstr = "OC_STACK_INVALID_QUERY";
+            break;
+        case 22 :
+            ocresultstr = "OC_STACK_INVALID_QUERY";
+            break;
+        case 23 :
+            ocresultstr = "OC_STACK_INVALID_PORT";
+            break;
+        case 24 :
+            ocresultstr = "OC_STACK_INVALID_CALLBACK";
+            break;
+        case 25 :
+            ocresultstr = "OC_STACK_INVALID_METHOD";
+            break;
+        case 26 :
+            ocresultstr = "OC_STACK_INVALID_PARAM";
+            break;
+        case 27 :
+            ocresultstr = "OC_STACK_INVALID_OBSERVE_PARAM";
+            break;
+        case 28 :
+            ocresultstr = "OC_STACK_NO_MEMORY";
+            break;
+        case 29 :
+            ocresultstr = "OC_STACK_COMM_ERROR";
+            break;
+        case 30 :
+            ocresultstr = "OC_STACK_NOTIMPL";
+            break;
+        case 31 :
+            ocresultstr = "OC_STACK_NO_RESOURCE";
+            break;
+        case 32 :
+            ocresultstr = "OC_STACK_RESOURCE_ERROR";
+            break;
+        case 33 :
+            ocresultstr = "OC_STACK_SLOW_RESOURCE";
+            break;
+        case 34 :
+            ocresultstr = "OC_STACK_DUPLICATE_REQUEST";
+            break;
+        case 35 :
+            ocresultstr = "OC_STACK_NO_OBSERVERS";
+            break;
+        case 36 :
+            ocresultstr = "OC_STACK_OBSERVER_NOT_FOUND";
+            break;
+        case 37 :
+            ocresultstr = "OC_STACK_VIRTUAL_DO_NOT_HANDLE";
+            break;
+        case 38 :
+            ocresultstr = "OC_STACK_INVALID_OPTION";
+            break;
+        case 39 :
+            ocresultstr = "OC_STACK_MALFORMED_RESPONSE";
+            break;
+        case 40 :
+            ocresultstr = "OC_STACK_PERSISTENT_BUFFER_REQUIRED";
+            break;
+        case 41 :
+            ocresultstr = "OC_STACK_INVALID_REQUEST_HANDLE";
+            break;
+        case 42 :
+            ocresultstr = "OC_STACK_INVALID_DEVICE_INFO";
+            break;
+        case 43 :
+            ocresultstr = "OC_STACK_INVALID_JSON";
+            break;
+        case 128 :
+            ocresultstr = "OC_STACK_PRESENCE_STOPPED";
+            break;
+        case 129 :
+            ocresultstr = "OC_STACK_PRESENCE_TIMEOUT";
+            break;
+        case 130 :
+            ocresultstr = "OC_STACK_PRESENCE_DO_NOT_HANDLE";
+            break;
+        case 255 :
+            ocresultstr = "OC_STACK_ERROR";
+            break;
+        default :
+            ocresultstr = "OC_STACK_ERROR";
+    }
+    return ocresultstr;
+}
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/tizen/TMSampleApp/tizen-manifest.xml b/service/things-manager/sampleapp/tizen/TMSampleApp/tizen-manifest.xml
new file mode 100644 (file)
index 0000000..10d65fd
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="2.3" package="org.tizen.tmsampleapp" version="1.0.0">
+    <profile name="mobile"/>
+    <ui-application appid="org.tizen.tmsampleapp" exec="tmsampleapp" multiple="false" nodisplay="false" taskmanage="true" type="capp">
+        <label>tmsampleapp</label>
+        <icon>tmsampleapp.png</icon>
+    </ui-application>
+    <privileges>
+        <privilege>http://tizen.org/privilege/network.get</privilege>
+        <privilege>http://tizen.org/privilege/internet</privilege>
+    </privileges>
+    <feature name="http://tizen.org/feature/network.wifi">true</feature>
+</manifest>
diff --git a/service/things-manager/sdk/build/linux/Makefile b/service/things-manager/sdk/build/linux/Makefile
deleted file mode 100644 (file)
index 0e5ec03..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-
-
-#OIC_ROOT=../../../resource/
-IOT_BASE=../../../../../resource
-#BOOST=${BOOST_DIR}
-RST_NAME=.
-
-
-# Insert your project name.
-TARGET=libTGMSDKLibrary.a
-EXCLUDE_LIST=
-
-# C++ type Compile Flag define.
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
-
-
-CXX_INC        := -I../../ -I../../inc/ -I../../src/
-CXX_INC        += -I${IOT_BASE}/include/ 
-CXX_INC += -I${IOT_BASE}/oc_logger/include
-CXX_INC        += -I${IOT_BASE}/csdk/stack/include 
-CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include 
-CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include 
-CXX_INC        += -I${IOT_BASE}/csdk/logger/include 
-CXX_INC        += -I${IOT_BASE}/dependencies/cereal/include
-
-CXX_LIB=-L""
-
-CXX_SRCPATH=${wildcard ../../src/*.cpp}
-CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
-CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
-CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
-
-
-
-
-
-
-# Linker FLAGS define.
-# LIBS=-lajdaemon -lalljoyn -lssl -lcrypto -ldl -llog -lz -lm -lc -lstdc++  -lgcc -lgnustl_static
-# LD_FLAGS=-std=c++11 -Wall -shared -lpthread -ldl
-GAR=ar
-#LD_LIB=${IOT_BASE}/OCLib.a ${IOT_BASE}/csdk/liboctbstack.a $(JSONLIB)/libjsoncpp.a
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: pre_job ${TARGET} post_job  
-
-pre_job:
-       @echo " " 
-       @echo "Build Begin." 
-       @echo " "
-       
-${TARGET}: ${CXX_OBJLIST}
-       #$(CXX) $(LD_FLAGS) -o ./${RST_NAME}/$@ $^ ${LD_LIB}            // shared object.
-       @for sublib in ${LD_LIB} ; do \
-       echo "${GAR} -x $${sublib}" ; \
-       cd ./${RST_NAME} ; \
-       ${GAR} -x ../$${sublib} ; \
-       cd ../ ; \
-       done
-       ${GAR} -r ./${RST_NAME}/$@  ./${RST_NAME}/*.o
-       @echo " "
-
-
-
-               
-%.o : ../../src/%.cpp 
-       ${CXX} ${CXX_FLAGS} -c $< ${CXX_INC} -o ./${RST_NAME}/$@
-       @echo " " 
-       
-post_job:
-       @echo " " 
-       @echo "Build Successful."
-       @echo " " 
-
-
-clean:
-       rm -f -v *.o ${TARGET}
-       
diff --git a/service/things-manager/sdk/inc/ActionSet.h b/service/things-manager/sdk/inc/ActionSet.h
new file mode 100644 (file)
index 0000000..7c95953
--- /dev/null
@@ -0,0 +1,146 @@
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef __OC_ACTIONSET__
+#define __OC_ACTIONSET__
+
+#include <string>
+#include <vector>
+#include <cstdio>
+#include <iostream>
+
+#include <ctime>
+
+#include <timer.h>
+
+using namespace std;
+
+namespace OIC
+{
+enum ACTIONSET_TYPE
+{
+    NONE = 0, SCHEDULED, RECURSIVE
+};
+
+typedef tm OCTime;
+
+/**
+ * @class      Time
+ * @brief      This class provides time-related information used for scheduled/recursive group action
+ *          features. Along with time-related variables, it also provides various useful functionality
+ *          including translating time to second unit
+ */
+class Time
+{
+public:
+    /**
+     * Constructor for Time
+     */
+    Time();
+    /**
+     * Virtual destructor for Time
+     */
+    ~Time();
+
+    /** @brief a unit of second.*/
+    long int mDelay;
+    /** @brief time information in structure tm.*/
+    OCTime mTime;
+    /** @brief flag to indicate group action type(NONE, SCHEDULED, RECURSIVE).*/
+    ACTIONSET_TYPE type;
+
+    void setTime(OCTime t);
+    void setTime(unsigned int yy, unsigned int mm, unsigned int dd,
+            unsigned int h, unsigned int m, unsigned int s,
+            int dayoftheweek);
+    void setDayOfWeekForRecursive(int day);
+    unsigned int getYear();
+    unsigned int getMonth();
+    unsigned int getDay();
+    unsigned int getHour();
+    unsigned int getMin();
+    unsigned int getSec();
+    long int getSecondsFromAbsoluteTime();
+    long int getSecAbsTime();
+    long int getSecondsForWeeklySchedule();
+    void setDelay(long int seconds);
+    std::string toString() const;
+};
+
+/**
+ * @class      Capability
+ * @brief      This class provides a structure to help developers to easily specify a unit of attribute
+ *          key-value pair which corresponds to action.
+ */
+class Capability
+{
+public:
+    /** @brief This corresponds with attribute key.*/
+    std::string capability;
+    /** @brief This corresponds with attribute value.*/
+    std::string status;
+};
+
+/**
+ * @class      Action
+ * @brief      This class provides a structure to help developers to easily specify an action which a
+ *          target resource have to do for.
+ */
+class Action
+{
+public:
+    /**
+     * Constructor for Action
+     */
+    Action();
+    /**
+     * Virtual destructor for Action
+     */
+    ~Action();
+
+    /** @brief This is a target URL of this action. It includes IP address, port, and resource URI.*/
+    std::string target;
+    /** @brief This is a list of capabilites.*/
+    std::vector<Capability*> listOfCapability;
+};
+
+/**
+ * @class      ActionSet
+ * @brief      This class provides a structure to help developers to easily specify group action.
+ */
+class ActionSet: public Time
+{
+public:
+    /**
+     * Constructor for ActionSet
+     */
+    ActionSet();
+    /**
+     * Virtual destructor for ActionSet
+     */
+    ~ActionSet();
+
+    /** @brief a name of group action */
+    std::string actionsetName;
+    /** @brief a list of actions composing group action */
+    std::vector<Action*> listOfAction;
+};
+}
+#endif
index de7c365..1aa9465 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file   ThingsManager.h
-///
-/// @brief  This file contains the declaration of  ThingsManager class
-///         and its members related to ThingsManager.
+/**
+ * @file
+ *
+ * This file contains the declaration of  ThingsManager class and its
+ * members related to ThingsManager.
+ */
 
 #ifndef __OC_THINGSMANAGER__
 #define __OC_THINGSMANAGER__
@@ -30,6 +32,7 @@
 #include <vector>
 #include <map>
 #include <cstdlib>
+#include <ActionSet.h>
 #include "OCPlatform.h"
 #include "OCApi.h"
 #include "GroupManager.h"
@@ -71,7 +74,7 @@ namespace OIC
          */
         OCStackResult findCandidateResources(std::vector< std::string > resourceTypes,
                 std::function< void(std::vector< std::shared_ptr< OCResource > >) > callback,
-                int waitsec = -1);
+                int waitsec);
 
         /**
          * API for subscribing child's state.
@@ -88,10 +91,10 @@ namespace OIC
                 std::function< void(std::string, OCStackResult) > callback);
 
         /**
-         * API for register and bind resource to group.
+         * API for registering and binding resource to group.
          *
          * @param childHandle - child resource handle. It will be filled from resource param.
-         * @param resource - resource for register and bind to group. It has all data.
+         * @param resource - resource for registering and binding to group. It has all data.
          * @param collectionHandle - collection resource handle. It will be added child resource.
          *
          * @return OCStackResult - return value of this API.
@@ -116,7 +119,9 @@ namespace OIC
          * @return OCStackResult - return value of this API.
          *                         It returns OC_STACK_OK if success.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * NOTE: It return OC_STACK ERROR when it is already finding a group.
+         *       You should call this api after the group finding process has stopped.
+         *       OCStackResult is defined in ocstack.h.
          */
         OCStackResult findGroup(std::vector< std::string > collectionResourceTypes,
                 FindCallback callback);
@@ -143,7 +148,10 @@ namespace OIC
          * @return OCStackResult - return value of this API.
          *                         It returns OC_STACK_OK if success.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * NOTE: If you want to join the resource in the remote(other) process,
+         *       use joinGroup(const std::shared_ptr< OCResource >, OCResourceHandle)
+         *       instead of this.
+         *       OCStackResult is defined in ocstack.h.
          */
         OCStackResult joinGroup(std::string collectionResourceType,
                 OCResourceHandle resourceHandle);
@@ -159,7 +167,10 @@ namespace OIC
          * @return OCStackResult - return value of this API.
          *                         It returns OC_STACK_OK if success.
          *
-         * NOTE: OCStackResult is defined in ocstack.h.
+         * NOTE: NOTE: If you want to join the resource in the same process,
+         *       use joinGroup(std::string, OCResourceHandle)
+         *       instead of this.
+         *       OCStackResult is defined in ocstack.h.
          */
         OCStackResult joinGroup(const std::shared_ptr< OCResource > resource,
                 OCResourceHandle resourceHandle);
@@ -179,6 +190,24 @@ namespace OIC
                 OCResourceHandle resourceHandle);
 
         /**
+         * API for leaving a joined group.
+         *
+         * @param resource - group resource pointer to join.
+         *                   It can be the callback result of findGroup().
+         *
+         * @param collectionResourceType - resource type of a group to leave.
+         * @param resourceHandle - resource handle to leave a group.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult leaveGroup(const std::shared_ptr< OCResource > resource,
+                        std::string collectionResourceType,
+                        OCResourceHandle resourceHandle);
+
+        /**
          * API for deleting a group.
          *
          * @param collectionResourceType - resource type of a group to delete.
@@ -190,12 +219,10 @@ namespace OIC
         /**
          * API for getting a list of joined groups.
          *
-         * @param void
-         *
          * @return std::map - return value of this API.
          *                  It returns group resource type and group resource handle as a map type.
          */
-        std::map< std::string, OCResourceHandle > getGroupList(void);
+        std::map< std::string, OCResourceHandle > getGroupList();
 
         // Things Configuration
 
@@ -215,8 +242,8 @@ namespace OIC
          * function, which provides the list in JSON format.
          *
          * @param resource - resource pointer representing the target group or the single thing.
-         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
-         *                         (e.g., installedlocation, currency, (IP)address)
+         * @param configurations - ConfigurationUnit: an attribute key of target resource.
+         *                         (e.g., loc, st, c, r)
          *                         Value : a value to be updated
          * @param callback - callback for updateConfigurations.
          *
@@ -237,7 +264,7 @@ namespace OIC
          * Callback is called when a response arrives.
          *
          * @param resource - resource pointer representing the target group or the single thing.
-         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource.
+         * @param configurations - ConfigurationUnit: an attribute key of target resource.
          * @param callback - callback for getConfigurations.
          *
          * @return OCStackResult - return value of this API.
@@ -252,7 +279,7 @@ namespace OIC
                                 const int eCode) > callback);
 
         /**
-         * API for showing the list of supported configuration units (configurable parameters)
+         * API for showing the list of supported configuration units (attribute keys)
          * Callback is called when a response arrives.
          *
          * @param void
@@ -263,7 +290,7 @@ namespace OIC
 
         /**
          * API for boostrapping system configuration parameters from a bootstrap server.
-         * Callback call when a response from the bootstrap server arrives.
+         * Callback is called when a response from the bootstrap server arrives.
          *
          * @param callback - callback for doBootstrap.
          *
@@ -318,21 +345,21 @@ namespace OIC
         // Group Action.
 
         /**
-         * API for extracting Action Set string from the Action Set class instance
+         * API for extracting an action set string from the ActionSet class instance
          *
-         * @param newActionSet - pointer of Action Set
+         * @param newActionSet - pointer of ActionSet class instance
          *
          * @return std::string - return value of this API.
-         *                                          It returns Action Set String.
+         *                                          It returns an action set String.
          *
          * NOTE: OCStackResult is defined in ocstack.h.
          */
         std::string getStringFromActionSet(const ActionSet *newActionSet);
 
         /**
-         * API for extrracting Action Set class instance from Action Set String.
+         * API for extrracting ActionSet class instance from an action set string.
          *
-         * @param desc - description of Action set
+         * @param desc - description of an action set string
          *
          * @return ActionSet* - return value of this API.
          *                      It returns pointer of ActionSet.
@@ -340,11 +367,11 @@ namespace OIC
         ActionSet* getActionSetfromString(std::string desc);
 
         /**
-         * API for adding an Action Set.
+         * API for adding an action set.
          * Callback is called when the response of PUT operation arrives.
          *
          * @param resource - resource pointer of the group resource
-         * @param newActionSet - pointer of Action Set
+         * @param newActionSet - pointer of ActionSet class instance
          * @param callback - callback for PUT operation.
          *
          * @return OCStackResult - return value of this API.
@@ -356,11 +383,11 @@ namespace OIC
                 const ActionSet* newActionSet, PutCallback cb);
 
         /**
-         * API for executing the Action Set.
+         * API for executing an existing action set.
          * Callback is called when the response of  POST operation arrives.
          *
          * @param resource - resource pointer of the group resource
-         * @param actionsetName - Action Set name for executing the Action set
+         * @param actionsetName - the action set name for executing the action set
          * @param callback - callback for POST operation.
          *
          * @return OCStackResult - return value of this API.
@@ -372,11 +399,43 @@ namespace OIC
                 std::string actionsetName, PostCallback cb);
 
         /**
-         * API for reading the Action Set.
-         * Callback is called when the response of  GET operation arrives.
+         * API for executing an existing action set.
+         * Callback is called when the response of  POST operation arrives.
+         *
+         * @param resource - resource pointer of the group resource
+         * @param actionsetName - the action set name for executing the action set
+         * @param delay - waiting time for until the action set run.
+         * @param callback - callback for POST operation.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult executeActionSet(std::shared_ptr< OCResource > resource,
+                std::string actionsetName, long int delay, PostCallback cb);
+
+        /**
+         * API for canceling an existing action set.
+         * Callback is called when the response of POST operation arrives.
+         *
+         * @param resource - resource pointer of the group resource
+         * @param actionsetName - the action set name for executing the action set
+         * @param callback - callback for POST operation.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult cancelActionSet(std::shared_ptr< OCResource > resource,
+                std::string actionsetName, PostCallback cb);
+        /**
+         * API for reading an existing action set.
+         * Callback is called when the response of GET operation arrives.
          *
          * @param resource - resource pointer of the group resource
-         * @param actionsetName - Action Set name for reading the Action set
+         * @param actionsetName - the action set name for reading the action set
          * @param callback - callback for GET operation.
          *
          * @return OCStackResult - return value of this API.
@@ -388,11 +447,11 @@ namespace OIC
                 std::string actionsetName, GetCallback cb);
 
         /**
-         * API for removing the Action Set.
+         * API for removing an existing action set.
          * Callback is called when the response of  POST operation arrives.
          *
          * @param resource - resource pointer of the group resource
-         * @param actionsetName - Action Set name for removing the Action set
+         * @param actionsetName - the action set name for removing the action set
          * @param callback - callback for POST operation.
          *
          * @return OCStackResult - return value of this API.
diff --git a/service/things-manager/sdk/java/AndroidManifest.xml b/service/things-manager/sdk/java/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..44f808b
--- /dev/null
@@ -0,0 +1,8 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.iotivity.service.tm"
+    android:versionCode="1"
+    android:versionName="1.0" >
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="21" />
+</manifest>
diff --git a/service/things-manager/sdk/java/jni/Android.mk b/service/things-manager/sdk/java/jni/Android.mk
new file mode 100644 (file)
index 0000000..395d11f
--- /dev/null
@@ -0,0 +1,56 @@
+LOCAL_PATH := $(call my-dir)
+
+ifeq ($(strip $(ANDROID_NDK)),)
+$(error ANDROID_NDK is not set!)
+endif
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../dep/android/$(TARGET_ARCH_ABI)/usr/lib
+LOCAL_MODULE := libandroid-boost_system
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libboost_system.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := libandroid-thingsmanager
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libTGMSDKLibrary.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release
+BASE_LIB_PATH := ../../../../android/android_api/base/libs/$(TARGET_ARCH_ABI)
+OIC_RESOURCE_PATH := ../../../../resource
+OIC_SERVICE_PATH := ../../../../service
+OIC_OUT_PATH := ../../../../out
+LOCAL_MODULE    := things-manager-jni
+
+LOCAL_C_INCLUDES := $(OIC_RESOURCE_PATH)/include \
+                    $(OIC_RESOURCE_PATH)/csdk/stack/include \
+                    $(OIC_RESOURCE_PATH)/csdk/ocsocket/include \
+                    $(OIC_RESOURCE_PATH)/oc_logger/include \
+                    $(OIC_RESOURCE_PATH)/android/include \
+                    $(OIC_RESOURCE_PATH)/dependencies/cereal/include \
+                    $(OIC_RESOURCE_PATH)/../extlibs/boost/boost_1_58_0 \
+                    $(OIC_RESOURCE_PATH)/../extlibs/timer \
+                    $(OIC_SERVICE_PATH)/things-manager/sdk/inc \
+                    $(OIC_SERVICE_PATH)/things-manager/sdk/src \
+                    $(OIC_SERVICE_PATH)/../android/android_api/base/jni \
+                    $(OIC_SERVICE_PATH)/../build_common/android/compatibility \
+                    $(LOCAL_PATH)/jniutil/inc \
+                    $(LOCAL_PATH)/tm/inc \
+                    $(LOCAL_PATH)/tm/src \
+                    $(LOCAL_PATH)/tm/src/base \
+                    $(ANDROID_NDK)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/include \
+                    $(ANDROID_NDK)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)/include \
+
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jniutil/src/*.cpp))
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/tm/src/*.cpp))
+
+LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
+
+LOCAL_LDLIBS := -llog -L$(BASE_LIB_PATH) -locstack-jni -L$(OIC_LIB_PATH) -loc -loctbstack -lcoap -loc_logger
+LOCAL_LDLIBS += -L$(ANDROID_NDK)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI) -lgnustl_shared
+LOCAL_SHARED_LIBRARIES := android-thingsmanager
+LOCAL_STATIC_LIBRARIES := android-boost_system
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/service/things-manager/sdk/java/jni/Application.mk b/service/things-manager/sdk/java/jni/Application.mk
new file mode 100644 (file)
index 0000000..d02cd64
--- /dev/null
@@ -0,0 +1,2 @@
+NDK_TOOLCHAIN_VERSION := 4.9
+#APP_STL               := gnustl_shared
diff --git a/service/things-manager/sdk/java/jni/SConscript b/service/things-manager/sdk/java/jni/SConscript
new file mode 100644 (file)
index 0000000..bad2e0b
--- /dev/null
@@ -0,0 +1,39 @@
+##
+# Things manager service JNI build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env')
+
+tm_jni_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+tm_sdk = env.get('SRC_DIR') + '/service/things-manager/sdk'
+base_jni = env.get('SRC_DIR') + '/android/android_api/base/jni'
+
+######################################################################
+# Build flags
+######################################################################
+tm_jni_env.AppendUnique(CXXFLAGS = ['-Wall', '-DLINUX', '-DNDEBUG'])
+tm_jni_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+tm_jni_env.AppendUnique(LIBPATH = [base_jni+'/../libs/'+env.get('TARGET_ARCH')])
+tm_jni_env.PrependUnique(LIBS = ['ocstack-jni', 'TGMSDKLibrary', 'oc', 'octbstack', 'boost_system', 'gnustl_shared', 'compatibility', 'log'])
+
+tm_jni_env.AppendUnique(CPPPATH = [tm_sdk+'/inc', tm_sdk+'/src'])
+tm_jni_env.AppendUnique(CPPPATH = [base_jni])
+tm_jni_env.AppendUnique(CPPPATH = ['tm/inc', 'tm/src', 'jniutil/inc', 'jniutil/src', '../../../../../extlibs/timer/'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+tm_jni_src = [env.Glob('tm/src/*.cpp'), env.Glob('jniutil/src/*.cpp')]
+tm_jni = tm_jni_env.SharedLibrary('things-manager-jni', tm_jni_src)
+
+tm_jni_env.InstallTarget(tm_jni, 'libthings-manager-jni')
+
+# Install the libraries to /libs/<TARGET_ARCH> directory
+tm_jni_env.Install(tm_sdk+'/java/libs/'+env.get('TARGET_ARCH'),env.get('BUILD_DIR')+'/libTGMSDKLibrary.so')
+tm_jni_env.Install(tm_sdk+'/java/libs/'+env.get('TARGET_ARCH'),tm_jni)
+
diff --git a/service/things-manager/sdk/java/jni/jniutil/inc/jni_getter.h b/service/things-manager/sdk/java/jni/jniutil/inc/jni_getter.h
new file mode 100644 (file)
index 0000000..4a6ff39
--- /dev/null
@@ -0,0 +1,112 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_getter.h
+  *
+  * @brief  This file contains the JGetter class  declarations and its functions required
+  *            for getting and setting basic data types in C++ and Java
+  */
+
+#ifndef __JNI_GETTER_H_
+#define __JNI_GETTER_H_
+
+
+#include <string>
+#include <jni.h>
+
+/**
+ * @class   JGetter
+ * @brief  This class provide utility for get/set basic data types in C++ and Java
+ *
+ */
+class JGetter
+{
+    public:
+        /**
+         * This function is called to get String field from the C++ object
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject from which string field is expected
+         * @param fieldName
+         *           Name of the field to be extracted from JObject
+         * @param value
+         *         reference to string value mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool getJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+                                    std::string &value);
+
+        /**
+         * This function is called to get Boolean field from the C++ object
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject from which boolean field is expected
+         * @param fieldName
+         *           Name of the field to be extracted from JObject
+         * @param value
+         *         reference to boolean value mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool getJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
+                                  bool &value);
+
+        /**
+         * This function is called to get Integer field from the C++ object
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject from which integer field is expected
+         * @param fieldName
+         *           Name of the field to be extracted from JObject
+         * @param value
+         *         reference to integer value mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool getJIntField(JNIEnv *env, jobject &object, const char *fieldName, int &value);
+
+        /**
+         * This function is called to get Object reference from the C++ object
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject from which Object reference is expected
+         * @param fieldName
+         *           Name of the field to be extracted from JObject
+         * @param fieldType
+         *           Type of the field to be extracted from JObject
+         * @param value
+         *         reference to Object reference mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool getJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+                                    const char *fieldType, jobject &value);
+};
+#endif //__JNI_GETTER_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/jniutil/inc/jni_object.h b/service/things-manager/sdk/java/jni/jniutil/inc/jni_object.h
new file mode 100644 (file)
index 0000000..b1a5f7f
--- /dev/null
@@ -0,0 +1,98 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_object.h
+  *
+  * @brief  This file contains the JObject class  declarations and its functions required
+  *            for getting and setting basic data types in C++ and Java
+  */
+
+#ifndef __JNI_OBJECT_H_
+#define __JNI_OBJECT_H_
+
+
+#include <jni.h>
+#include "JniOcResource.h"
+
+/**
+ * @class   JObject
+ * @brief   This class provides a set of functions for JNI object.
+ *
+ */
+class JObject
+{
+    public:
+        /**
+         * @brief constructor
+         */
+        JObject(JNIEnv *env);
+
+        /**
+         * @brief constructor
+         */
+        JObject(JNIEnv *env, jobject obj);
+
+        /**
+         * @brief constructor
+         */
+        JObject(JNIEnv *env, const char *classPath);
+
+        /**
+         * @brief destructor
+         *
+         */
+        virtual ~JObject();
+
+        /**
+         * Function to get the jobject.
+         *
+         * @return jobject, returns a new JNI object or NULL otherwise.
+         *
+         */
+        virtual jobject getObject() const;
+
+        /**
+         * Function to detach the jobject.
+         *
+         * @return void
+         *
+         */
+        void detachObject();
+
+    protected:
+        /**
+         *  JNI Environment Pointer
+         */
+        JNIEnv *m_pEnv;
+        /**
+         *  Java Object
+         */
+        jobject m_pObject;
+        /**
+         *  Java Class
+         */
+        jclass  m_pClazz;
+        /**
+         *  Boolean variable to check if an object is new
+         */
+        bool m_fIsNewObject;
+};
+#endif //__JNI_OBJECT_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/jniutil/inc/jni_setter.h b/service/things-manager/sdk/java/jni/jniutil/inc/jni_setter.h
new file mode 100644 (file)
index 0000000..3d58cfd
--- /dev/null
@@ -0,0 +1,128 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_setter.h
+  *
+  * @brief  This file contains the JSetter class declarations and and its functions required
+  *            to set data types in C++ object from Java object
+*/
+
+#ifndef __JNI_SETTER_H_
+#define __JNI_SETTER_H_
+
+
+#include <jni.h>
+
+/**
+ * @class   JSetter
+ * @brief  This class provide utility to set data types in C++ object from Java object
+ *
+ */
+class JSetter
+{
+    public:
+
+        /**
+         * This function is called to set Integer field in to C++ object.
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject to which integer field will be set.
+         * @param fieldName
+         *           Name of the field to be set in JObject
+         * @param value
+         *         integer value mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool setJIntField(JNIEnv *env, jobject &object, const char *fieldName, int value);
+
+        /**
+         * This function is called to set Long field in to C++ object.
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject to which Long field will be set.
+         * @param fieldName
+         *           Name of the field to be set in JObject
+         * @param value
+         *         Long value mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool setJLongField(JNIEnv *env, jobject &object, const char *fieldName,
+                                  jlong value);
+
+        /**
+         * This function is called to Set Boolean field to C++ object
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject to which boolean field has to be set
+         * @param fieldName
+         *           Name of the field to be set in JObject
+         * @param value
+         *         boolean value mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool setJBoolField(JNIEnv *env, jobject &object, const char *fieldName, bool value);
+        /**
+         * This function is called to Set String field from the C++ object
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject in which string value has to be set
+         * @param fieldName
+         *           Name of the field to be set in JObject
+         * @param value
+         *         string value mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool setJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+                                    const char *value);
+
+        /**
+         * This function is called to set Object reference in C++ object.
+         *
+         * @param env
+         *           JNI Environment reference
+         * @param object
+         *           JObject to which Object reference is to be set.
+         * @param fieldName
+         *           Name of the field to be set in JObject
+         * @param fieldType
+         *           Type of the field to be set in JObject
+         * @param value
+         *         value of Object mentioned in fieldName
+         *
+         * @return returns true on success and false on failer.
+         */
+        static bool setJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+                                    const char *fieldType, const jobject value);
+};
+
+#endif //__JNI_SETTER_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/jniutil/inc/jni_string.h b/service/things-manager/sdk/java/jni/jniutil/inc/jni_string.h
new file mode 100644 (file)
index 0000000..ed1c102
--- /dev/null
@@ -0,0 +1,82 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_string.h
+  *
+  * @brief  This file contains the declaration of JString class and its members related to JString.
+  *
+*/
+
+#ifndef __JNI_STRING_H_
+#define __JNI_STRING_H_
+
+
+#include <string>
+
+#include "jni_object.h"
+
+/**
+ * @class   JString
+ * @brief   This class inherits JObject class and provides a set of functions for JNI String.
+ *
+ */
+class JString : public JObject
+{
+    public:
+        /**
+         * @brief constructor
+         */
+        JString(JNIEnv *env, jstring value);
+        /**
+         * @brief constructor
+         */
+        JString(JNIEnv *env, const char *value);
+        /**
+         * @brief constructor
+         */
+        JString(JNIEnv *env, const std::string &value);
+        /**
+         * @brief destructor
+         */
+        ~JString();
+
+        /**
+         * Function to get the string value and set it.
+         *
+         * @param value - String value to set to a private member variable.
+         *
+         * @return bool - true on success
+         *
+         */
+        bool getValue(std::string &value);
+
+        /**
+         * Function to get the private string value.
+         *
+         * @return  C String value.
+         *
+         */
+        const char *c_str();
+
+    private:
+        std::string m_cstr;
+};
+#endif //__JNI_STRING_H_
diff --git a/service/things-manager/sdk/java/jni/jniutil/inc/jni_things_manager_jvm.h b/service/things-manager/sdk/java/jni/jniutil/inc/jni_things_manager_jvm.h
new file mode 100644 (file)
index 0000000..8caa476
--- /dev/null
@@ -0,0 +1,125 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_things_manager_jvm.h
+  *
+  * @brief  This file contains the essential declarations and functions required
+  *            for JNI implementation
+  */
+
+#ifndef __JNI_THINGS_MANAGER_JVM_H_
+#define __JNI_THINGS_MANAGER_JVM_H_
+
+
+#include <jni.h>
+#include <thread>
+#include <mutex>
+
+#define TM_SERVICE_NATIVE_API_CLASS_PATH    "org/iotivity/service/tm/ThingsManagerNativeInterface"
+#define TM_SERVICE_NATIVE_API_CLASS_TYPE    "Lorg/iotivity/service/tm/ThingsManagerNativeInterface;"
+
+#define TM_SERVICE_CALLBACK_CLASS_PATH    "org/iotivity/service/tm/ThingsManagerCallback"
+#define TM_SERVICE_CALLBACK_CLASS_TYPE    "Lorg/iotivity/service/tm/ThingsManagerCallback;"
+
+#define TM_SERVICE_PLATFORM_CLASS_PATH    "org/iotivity/base/OcPlatform"
+#define TM_SERVICE_PLATFORM_CLASS_TYPE    "Lorg/iotivity/base/OcPlatform;"
+
+#define TM_SERVICE_PLATFORM_CONFIG_CLASS_PATH    "org/iotivity/base/PlatformConfig"
+#define TM_SERVICE_PLATFORM_CONFIG_CLASS_TYPE    "Lorg/iotivity/base/PlatformConfig;"
+
+#define TM_SERVICE_CAPABILITY_PATH    "org/iotivity/service/tm/Capability"
+#define TM_SERVICE_CAPABILITY_TYPE    "Lorg/iotivity/service/tm/Capability;"
+
+#define TM_SERVICE_ACTION_PATH    "org/iotivity/service/tm/Action"
+#define TM_SERVICE_ACTION_TYPE    "Lorg/iotivity/service/tm/Action;"
+
+#define TM_SERVICE_ACTIONSET_PATH    "org/iotivity/service/tm/ActionSet"
+#define TM_SERVICE_ACTIONSET_TYPE    "Lorg/iotivity/service/tm/ActionSet;"
+
+#define TM_SERVICE_OCRESOURCE_PATH    "org/iotivity/base/OcResource"
+#define TM_SERVICE_OCRESOURCE_TYPE    "Lorg/iotivity/base/OcResource;"
+
+#define TM_SERVICE_HEADER_OPTION_PATH    "org/iotivity/base/OcHeaderOption"
+#define TM_SERVICE_HEADER_OPTION_TYPE    "Lorg/iotivity/base/OcHeaderOption;"
+
+#define TM_SERVICE_OCREPRESENTATION_PATH    "org/iotivity/base/OcRepresentation"
+#define TM_SERVICE_OCREPRESENTATION_TYPE    "Lorg/iotivity/base/OcRepresentation;"
+
+#define TM_SERVICE_OCRESOURCEHANDLE_PATH    "org/iotivity/base/OcResourceHandle"
+#define TM_SERVICE_OCRESOURCEHANDLE_TYPE    "Lorg/iotivity/base/OcResourceHandle;"
+
+#define TM_SERVICE_TIME_PATH    "org/iotivity/service/tm/Time"
+
+#define TM_JAVA_VECTOR_CLASS_PATH "java/util/Vector"
+#define TM_JAVA_VECTOR_TYPE "Ljava/util/Vector;"
+
+#define TM_JAVA_STRING_TYPE "Ljava/lang/String;"
+
+/**
+ * @class   ThingsManagerJVM
+ * @brief   This class provides functions related to JNI Environment.
+ *
+ */
+class ThingsManagerJVM
+{
+    public:
+        /**
+         * @brief destructor
+         */
+        ~ThingsManagerJVM() {};
+
+        /**
+         * @brief  Get JVM instance
+         */
+        static JNIEnv *getEnv();
+
+        /**
+         * @brief  Release aquired JVM instance
+         */
+        static void releaseEnv();
+
+    public:
+        /**
+         *  Java VM pointer
+         */
+        static JavaVM *m_jvm;
+
+    private:
+        /**
+         * @brief constructor
+         */
+        ThingsManagerJVM();
+
+        /**
+         *  Mutex for thread synchronization
+         */
+        static std::mutex m_currentThreadMutex;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+jclass GetJClass(const char *szClassPath);
+jobject GetJObjectInstance(const char *szClassPath);
+#ifdef __cplusplus
+}
+#endif
+#endif //__JNI_THINGS_MANAGER_JVM_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/jniutil/src/jni_getter.cpp b/service/things-manager/sdk/java/jni/jniutil/src/jni_getter.cpp
new file mode 100644 (file)
index 0000000..7021905
--- /dev/null
@@ -0,0 +1,177 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_getter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JGetter"
+
+
+bool JGetter::getJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+                              std::string &value)
+{
+    if (NULL == env ||
+        NULL == object ||
+        NULL == fieldName)
+    {
+        LOGE("getJStringField invalid parameters");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed [%s]", fieldName);
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Ljava/lang/String;" );
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s]", fieldName);
+        env->DeleteLocalRef(clazz);
+        return false;
+    }
+
+    jstring jValue = (jstring)env->GetObjectField( object, fieldID );
+    if (NULL == jValue)
+    {
+        LOGE("GetObjectField failed [%s]", fieldName);
+        env->DeleteLocalRef(clazz);
+        return false;
+    }
+
+    const char *cstr = env->GetStringUTFChars(jValue, 0);
+    if (cstr == NULL)
+    {
+        LOGE("GetStringUTFChars failed");
+    }
+    else
+    {
+        value = cstr;
+        env->ReleaseStringUTFChars(jValue, cstr);
+    }
+
+    env->DeleteLocalRef(clazz);
+    env->DeleteLocalRef(jValue);
+
+    return true;
+}
+
+
+bool JGetter::getJBoolField(JNIEnv *env, jobject &object, const char *fieldName, bool &value)
+{
+    if (NULL == env ||
+        NULL == object ||
+        NULL == fieldName)
+    {
+        LOGE("getJBoolField invalid parameters");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed");
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Z" );
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s]", fieldName);
+        env->DeleteLocalRef( clazz );
+        return false;
+    }
+
+    value = env->GetBooleanField( object, fieldID );
+
+    env->DeleteLocalRef(clazz);
+
+    return true;
+}
+
+bool JGetter::getJIntField(JNIEnv *env, jobject &object, const char *fieldName, int &value)
+{
+    if (NULL == env ||
+        NULL == object ||
+        NULL == fieldName)
+    {
+        LOGE("getJIntField invalid parameters");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed");
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, "I" );
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s]", fieldName);
+        env->DeleteLocalRef( clazz );
+        return false;
+    }
+
+    value = env->GetIntField( object, fieldID );
+
+    env->DeleteLocalRef(clazz);
+
+    return true;
+}
+
+bool JGetter::getJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+                              const char *fieldType, jobject &value)
+{
+    if (NULL == env ||
+        NULL == object ||
+        NULL == fieldName)
+    {
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, fieldType );
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s][%s]", fieldName, fieldType);
+        return false;
+    }
+
+    value = env->GetObjectField( object, fieldID );
+    if (NULL == value)
+    {
+        return false;
+    }
+
+    env->DeleteLocalRef(clazz);
+
+    return true;
+}
diff --git a/service/things-manager/sdk/java/jni/jniutil/src/jni_object.cpp b/service/things-manager/sdk/java/jni/jniutil/src/jni_object.cpp
new file mode 100644 (file)
index 0000000..94a7b27
--- /dev/null
@@ -0,0 +1,90 @@
+#include "jni_object.h"
+
+//#define NULL 0
+#define LOG_TAG "TM_JObject"
+
+
+
+JObject::JObject(JNIEnv *env) : m_pEnv( env ),
+    m_pObject(NULL),
+    m_pClazz( NULL ),
+    m_fIsNewObject(true)
+{
+}
+
+JObject::JObject(JNIEnv *env, jobject obj) : m_pEnv(NULL),
+    m_pObject(NULL),
+    m_pClazz(NULL),
+    m_fIsNewObject(false)
+{
+    if ( NULL == env || NULL == obj)
+    {
+        return;
+    }
+
+    m_pEnv = env;
+    m_pObject = obj;
+    m_pClazz = m_pEnv->GetObjectClass( obj );
+}
+
+JObject::JObject(JNIEnv *env, const char *classPath) : m_pEnv(NULL),
+    m_pObject(NULL),
+    m_pClazz(NULL),
+    m_fIsNewObject(true)
+{
+    if ( NULL == env || NULL == classPath)
+    {
+        LOGI("JObject Invalid parameters");
+        return;
+    }
+
+    m_pEnv = env;
+    //m_pClazz = GetJClass( classPath );
+
+    if (NULL == m_pClazz)
+    {
+        LOGE( "GetJClass failed [%s]" , classPath);
+        return;
+    }
+
+    jmethodID mid = env->GetMethodID(m_pClazz, "<init>", "()V");
+    if (NULL == mid)
+    {
+        LOGE( "GetMethodID failed [%s]" , classPath);
+        return;
+    }
+
+    m_pObject = env->NewObject(m_pClazz, mid);
+}
+
+JObject::~JObject()
+{
+    if (m_pEnv)
+    {
+        if (m_pObject && m_fIsNewObject)
+        {
+            m_pEnv->DeleteLocalRef( m_pObject );
+        }
+
+        if (m_pClazz && !m_fIsNewObject)
+        {
+            m_pEnv->DeleteLocalRef( m_pClazz );
+        }
+    }
+}
+
+jobject JObject::getObject() const
+{
+    return m_pObject;
+}
+
+
+void JObject::detachObject()
+{
+    if (m_fIsNewObject)
+    {
+        m_fIsNewObject = false;
+        m_pClazz = NULL;
+    }
+}
+
diff --git a/service/things-manager/sdk/java/jni/jniutil/src/jni_setter.cpp b/service/things-manager/sdk/java/jni/jniutil/src/jni_setter.cpp
new file mode 100644 (file)
index 0000000..ee23c1d
--- /dev/null
@@ -0,0 +1,199 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_setter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JSetter"
+
+
+bool JSetter::setJStringField(JNIEnv *env, jobject &object, const char *fieldName,
+                              const char *value)
+{
+    if (NULL == env || NULL == fieldName)
+    {
+        LOGE("setJStringField invalid parameters");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed");
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Ljava/lang/String;");
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s]", fieldName);
+        env->DeleteLocalRef( clazz );
+        return false;
+    }
+
+    jstring jvalue ;
+    if (value != NULL && strlen(value) > 0)
+    {
+        jclass strClass = env->FindClass("java/lang/String");
+        jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
+        jbyteArray bytes = env->NewByteArray(strlen(value));
+        env->SetByteArrayRegion(bytes, 0, strlen(value), (jbyte *)value);
+        jstring encoding = env->NewStringUTF("utf-8");
+        jvalue = (jstring)env->NewObject(strClass, ctorID, bytes, encoding);
+        env->DeleteLocalRef(strClass);
+        env->DeleteLocalRef(bytes);
+        env->DeleteLocalRef(encoding);
+    }
+    else
+    {
+        jvalue = env->NewStringUTF("");
+    }
+
+    env->SetObjectField(object, fieldID, jvalue);
+
+    env->DeleteLocalRef(jvalue);
+    env->DeleteLocalRef( clazz );
+
+    return true;
+}
+
+
+bool JSetter::setJIntField(JNIEnv *env, jobject &object, const char *fieldName, int value)
+{
+    if (NULL == env || NULL == fieldName)
+    {
+        LOGE("setJIntField invalid paramter");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed");
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, "I");
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s]", fieldName);
+        env->DeleteLocalRef( clazz );
+        return false;
+    }
+    env->SetIntField(object, fieldID, value);
+
+    env->DeleteLocalRef( clazz );
+
+    return true;
+}
+
+
+bool JSetter::setJLongField(JNIEnv *env, jobject &object, const char *fieldName, jlong value)
+{
+    if (NULL == env || NULL == fieldName)
+    {
+        LOGE("setJLongField invalid parameters");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed");
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, "J");
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s]", fieldName);
+        env->DeleteLocalRef( clazz );
+        return false;
+    }
+    env->SetLongField(object, fieldID, value);
+
+    env->DeleteLocalRef( clazz );
+
+    return true;
+}
+
+
+bool JSetter::setJBoolField(JNIEnv *env, jobject &object, const char *fieldName, bool value)
+{
+    if (NULL == env || NULL == fieldName)
+    {
+        LOGE("setJBoolField invalid parameters");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed");
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, "Z");
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s]", fieldName);
+        env->DeleteLocalRef( clazz );
+        return false;
+    }
+    env->SetBooleanField(object, fieldID, value);
+
+    env->DeleteLocalRef( clazz );
+
+    return true;
+}
+
+
+bool JSetter::setJObjectField(JNIEnv *env, jobject &object, const char *fieldName,
+                              const char *fieldType, const jobject value)
+{
+    if (NULL == env || NULL == fieldName)
+    {
+        LOGE("setJBoolField invalid parameters");
+        return false;
+    }
+
+    jclass clazz = env->GetObjectClass( object );
+    if (NULL == clazz)
+    {
+        LOGE("GetObjectClass failed");
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID( clazz, fieldName, fieldType);
+    if (0 == fieldID)
+    {
+        LOGE("GetFieldID failed [%s] [%s]", fieldName, fieldType);
+        env->DeleteLocalRef( clazz );
+        return false;
+    }
+    env->SetObjectField(object, fieldID, value);
+
+    env->DeleteLocalRef( clazz );
+
+    return true;
+}
+
diff --git a/service/things-manager/sdk/java/jni/jniutil/src/jni_string.cpp b/service/things-manager/sdk/java/jni/jniutil/src/jni_string.cpp
new file mode 100644 (file)
index 0000000..7710507
--- /dev/null
@@ -0,0 +1,68 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_string.h"
+
+#define LOG_TAG "TM_JString"
+
+JString::JString(JNIEnv *env, jstring value) : JObject(env, value)
+{
+    const char *buff = env->GetStringUTFChars(value, 0);
+
+    m_cstr = buff;
+
+    env->ReleaseStringUTFChars(value, buff);
+}
+
+JString::JString(JNIEnv *env, const char *value) : JObject(env)
+{
+    m_cstr = value;
+
+    if (env)
+    {
+        m_pObject = env->NewStringUTF( value );
+    }
+}
+
+JString::JString(JNIEnv *env, const std::string &value) : JObject(env)
+{
+    m_cstr = value;
+
+    if (env)
+    {
+        m_pObject = env->NewStringUTF( value.c_str() );
+    }
+}
+
+JString::~JString()
+{
+}
+
+bool JString::getValue(std::string &value)
+{
+    value = m_cstr;
+    return true;
+}
+
+const char *JString::c_str()
+{
+    return m_cstr.c_str();
+}
+
+
diff --git a/service/things-manager/sdk/java/jni/jniutil/src/jni_things_manager_jvm.cpp b/service/things-manager/sdk/java/jni/jniutil/src/jni_things_manager_jvm.cpp
new file mode 100644 (file)
index 0000000..f0b69e7
--- /dev/null
@@ -0,0 +1,386 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_things_manager_jvm.h"
+#include <string>
+#include "jni_things_manager.h"
+#include "jni_things_manager_util.h"
+#include "JniOcResource.h"
+
+#define TM_ERROR_JNI_FOUND_CLASS_FAILED -2005
+
+/**
+ * @class   JClassMap
+ * @brief   This class provides functions for initializing the Java class path and Java class.
+ *
+ */
+class JClassMap
+{
+    public:
+        /**
+              *  Java Class
+              */
+        jclass classRef;
+        /**
+              *  Java Class Path
+              */
+        const char *szClassPath;
+
+        /**
+             * @brief constructor
+             */
+        JClassMap(const char *path)
+            : classRef(NULL)
+        {
+            szClassPath = path;
+        }
+};
+
+/**
+ * @class   JObjectMap
+ * @brief   This class provides functins for initializing the Java Class path and Java Class
+ * Object.
+ *
+ */
+class JObjectMap
+{
+    public:
+        /**
+            *  Java Object
+            */
+        jobject object;
+        /**
+             *  Java Class Path
+             */
+        const char *szClassPath;
+
+        /**
+             * @brief constructor
+             */
+        JObjectMap(const char *path)
+            : object(NULL)
+        {
+            szClassPath = path;
+        }
+};
+
+static JClassMap gJClassMapArray[] =
+{
+    JClassMap(TM_SERVICE_NATIVE_API_CLASS_PATH),
+    JClassMap(TM_SERVICE_CALLBACK_CLASS_PATH),
+    JClassMap(TM_SERVICE_OCRESOURCE_PATH),
+    JClassMap(TM_SERVICE_OCREPRESENTATION_PATH),
+    JClassMap(TM_SERVICE_HEADER_OPTION_PATH),
+    JClassMap(TM_SERVICE_ACTIONSET_PATH),
+    JClassMap(TM_SERVICE_CAPABILITY_PATH),
+    JClassMap(TM_SERVICE_ACTION_PATH),
+    JClassMap(TM_SERVICE_PLATFORM_CLASS_PATH),
+    JClassMap(TM_SERVICE_PLATFORM_CONFIG_CLASS_PATH),
+    JClassMap(TM_SERVICE_OCRESOURCEHANDLE_PATH)
+};
+
+static JObjectMap gJObjectMapArray[] =
+{
+    JObjectMap(TM_SERVICE_CALLBACK_CLASS_PATH)
+};
+
+static JNINativeMethod gThingsManagerMethodTable[] =
+{
+    { "findCandidateResources", "(Ljava/util/Vector;I)I", (void *) JNIThingsManagerFindCandidateResource},
+    { "subscribeCollectionPresence", "(Lorg/iotivity/base/OcResource;)I", (void *) JNIThingsManagerSubscribeCollectionPresence},
+    { "bindResourceToGroup", "(Lorg/iotivity/base/OcResource;Lorg/iotivity/base/OcResourceHandle;)Lorg/iotivity/base/OcResourceHandle;", (void *) JNIThingsManagerBindResourceToGroup},
+    { "findGroup", "(Ljava/util/Vector;)I", (void *) JNIThingsManagerFindGroup},
+    { "createGroup", "(Ljava/lang/String;)I", (void *) JNIThingsManagerCreateGroup},
+    { "joinGroup", "(Ljava/lang/String;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerJoinGroupString},
+    { "joinGroup", "(Lorg/iotivity/base/OcResource;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerJoinGroupObject},
+    { "leaveGroup", "(Ljava/lang/String;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerLeaveGroup},
+    { "leaveGroup", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;Lorg/iotivity/base/OcResourceHandle;)I", (void *) JNIThingsManagerLeaveGroupForResource},
+    { "deleteGroup", "(Ljava/lang/String;)V", (void *) JNIThingsManagerDeleteGroup},
+    { "getGroupList", "()Ljava/util/Map;", (void *) JNIThingsManagerGetGroupList},
+    { "updateConfigurations", "(Lorg/iotivity/base/OcResource;Ljava/util/Map;)I", (void *) JNIThingsManagerUpdateConfigurations},
+    { "getConfigurations", "(Lorg/iotivity/base/OcResource;Ljava/util/Vector;)I", (void *) JNIThingsManagerGetConfigurations},
+    { "getListOfSupportedConfigurationUnits", "()Ljava/lang/String;", (void *) JNIThingsManagerGetListOfSupportedConfigurationUnits},
+    { "doBootstrap", "()I", (void *) JNIThingsManagerDoBootstrap},
+    { "reboot", "(Lorg/iotivity/base/OcResource;)I", (void *) JNIThingsManagerReboot},
+    { "factoryReset", "(Lorg/iotivity/base/OcResource;)I", (void *) JNIThingsManagerFactoryReset},
+    { "addActionSet", "(Lorg/iotivity/base/OcResource;Lorg/iotivity/service/tm/ActionSet;)I", (void *) JNIThingsManagerAddActionSet},
+    { "executeActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerExecuteActionSet},
+    { "executeActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;J)I", (void *) JNIThingsManagerExecuteActionSetWithDelay},
+    { "cancelActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerCancelActionSet},
+    { "getActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerGetActionSet},
+    { "deleteActionSet", "(Lorg/iotivity/base/OcResource;Ljava/lang/String;)I", (void *) JNIThingsManagerDeleteActionSet},
+};
+
+static int gThingsManagerMethodTableSize = sizeof(gThingsManagerMethodTable) / sizeof(
+            gThingsManagerMethodTable[0]);
+
+
+int InitializeJClassMapArray(JNIEnv *env)
+{
+    LOGI("InitializeJClassMapArray: Enter");
+
+    unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+
+    for (unsigned int i = 0; i < nLen; i++)
+    {
+        jclass classRef = env->FindClass(gJClassMapArray[i].szClassPath);
+        if (NULL == classRef)
+        {
+            LOGE("FindClass failed for [%s]", gJClassMapArray[i].szClassPath);
+            return -1;
+        }
+        gJClassMapArray[i].classRef = (jclass)env->NewGlobalRef(classRef);
+        env->DeleteLocalRef(classRef);
+    }
+
+    LOGI("InitializeJClassMapArray: Exit");
+    return 0;
+}
+
+jclass GetJClass(const char *szClassPath)
+{
+    unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+
+    jclass classRef = NULL;
+
+    for (unsigned int i = 0; i < nLen; i++)
+    {
+        if (0 == strcmp(gJClassMapArray[i].szClassPath, szClassPath))
+        {
+            classRef = gJClassMapArray[i].classRef;
+            break;
+        }
+    }
+
+    return classRef;
+}
+
+void DeleteClassMapArray(JNIEnv *env)
+{
+    LOGI("DeleteClassMapArray: Enter");
+
+    unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+    for (unsigned int i = 0; i < nLen; i++)
+    {
+        if (NULL != gJClassMapArray[i].classRef)
+        {
+            env->DeleteGlobalRef(gJClassMapArray[i].classRef);
+            gJClassMapArray[i].classRef = NULL;
+        }
+    }
+
+    LOGI("DeleteClassMapArray: Exit");
+}
+
+int InitializeJObjectMapArray(JNIEnv *env)
+{
+    LOGI("InitializeJObjectMapArray: Enter");
+
+    unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+
+    for (unsigned int i = 0; i < nLen; i++)
+    {
+        jclass classRef = env->FindClass(gJObjectMapArray[i].szClassPath);
+        if (NULL == classRef)
+        {
+            LOGE("InitializeJObjectMapArray: FindClass failed for [%s]", gJObjectMapArray[i].szClassPath);
+            return -1;
+        }
+
+        std::string methodSignature = "()L";
+        methodSignature.append(gJObjectMapArray[i].szClassPath);
+        methodSignature.append(";");
+
+        // Get the object form "getInstance"
+        jmethodID methodid = env->GetStaticMethodID(classRef, "getInstance", methodSignature.c_str());
+        if (NULL == methodid)
+        {
+            LOGE("InitializeJObjectMapArray: GetStaticMethodID failed for [%s]",
+                 gJObjectMapArray[i].szClassPath);
+            return -1;
+        }
+
+        // Get the singleton object
+        jobject objectRef = (jobject)env->CallStaticObjectMethod(classRef, methodid);
+        if (NULL == objectRef)
+        {
+            LOGE("InitializeJObjectMapArray: CallStaticObjectMethod failed for [%s]",
+                 gJObjectMapArray[i].szClassPath);
+            return -1;
+        }
+
+        gJObjectMapArray[i].object = (jobject)env->NewGlobalRef(objectRef);
+        env->DeleteLocalRef(classRef);
+    }
+
+    LOGI("InitializeJObjectMapArray: Exit");
+    return 0;
+}
+
+jobject GetJObjectInstance(const char *szClassPath)
+{
+    unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+
+    jobject object = NULL;
+
+    for (unsigned int i = 0; i < nLen; i++)
+    {
+        if (0 == strcmp(gJObjectMapArray[i].szClassPath, szClassPath))
+        {
+            object = gJObjectMapArray[i].object;
+            break;
+        }
+    }
+
+    return object;
+}
+
+void DeleteObjectMapArray(JNIEnv *env)
+{
+    LOGI("DeleteObjectMapArray: Enter");
+
+    unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+    for (unsigned int i = 0; i < nLen; i++)
+    {
+        if (NULL != gJObjectMapArray[i].object)
+        {
+            env->DeleteGlobalRef(gJObjectMapArray[i].object);
+            gJObjectMapArray[i].object = NULL;
+        }
+    }
+
+    LOGI("DeleteObjectMapArray: Exit");
+}
+
+JavaVM *ThingsManagerJVM::m_jvm = NULL;
+std::mutex ThingsManagerJVM::m_currentThreadMutex;
+JNIEnv *ThingsManagerJVM::getEnv()
+{
+    std::unique_lock<std::mutex> scoped_lock(m_currentThreadMutex);
+
+    if (NULL == m_jvm)
+    {
+        LOGE("Failed to get JVM");
+        return NULL;
+    }
+
+    JNIEnv *env = NULL;
+    jint ret = m_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION);
+    switch (ret)
+    {
+        case JNI_OK:
+            return env;
+        case JNI_EDETACHED:
+            if (0 > m_jvm->AttachCurrentThread(&env, NULL))
+            {
+                LOGE("Failed to attach current thread to env");
+                return NULL;
+            }
+            return env;
+        case JNI_EVERSION:
+            LOGE("JNI version not supported");
+        default:
+            LOGE("Failed to get the environment");
+            return NULL;
+    }
+}
+
+void ThingsManagerJVM::releaseEnv()
+{
+    std::unique_lock<std::mutex> scoped_lock(m_currentThreadMutex);
+
+    if (0 == m_jvm)
+    {
+        LOGE("Failed to release JVM");
+        return;
+    }
+
+    m_jvm->DetachCurrentThread();
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
+{
+    LOGD("JNI_OnLoad: Enter");
+
+    if (!vm)
+    {
+        LOGE("JNI_OnLoad: vm is invalid");
+        return JNI_ERR;
+    }
+
+    JNIEnv *env = NULL;
+    if (JNI_OK != vm->GetEnv((void **) &env, JNI_CURRENT_VERSION))
+    {
+        LOGE("JNI_OnLoad: Version check is failed!");
+        return JNI_ERR;
+    }
+
+    if (0 != InitializeJClassMapArray(env))
+    {
+        LOGE("JNI_OnLoad: Initialize JClass Array failed!");
+        return JNI_ERR;
+    }
+
+    if (0 != InitializeJObjectMapArray(env))
+    {
+        LOGE("JNI_OnLoad: Initialize JObject Array failed!");
+        return JNI_ERR;
+    }
+
+    jclass thingsManagerClassRef = GetJClass(TM_SERVICE_NATIVE_API_CLASS_PATH);
+    if (NULL == thingsManagerClassRef)
+    {
+        LOGE("JNI_OnLoad: GetJClass gThingsManagerClass failed !");
+        return JNI_ERR;
+    }
+    env->RegisterNatives(thingsManagerClassRef, gThingsManagerMethodTable,
+                         gThingsManagerMethodTableSize);
+
+    ThingsManagerJVM::m_jvm = vm;
+
+    LOGI("JNI_OnLoad: Exit");
+    return JNI_CURRENT_VERSION;
+}
+
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
+{
+    LOGD("JNI_OnUnload: Enter");
+
+    JNIEnv *env = NULL;
+    if (JNI_OK != vm->GetEnv((void **)&env, JNI_CURRENT_VERSION))
+    {
+        LOGE("JNI_OnLoad: Version check is failed!");
+        return;
+    }
+
+    // delete all class references
+    DeleteClassMapArray(env);
+
+    // delete all jobject
+    DeleteObjectMapArray(env);
+
+    LOGD("JNI_OnUnload: Exit");
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/service/things-manager/sdk/java/jni/tm/inc/jni_action.h b/service/things-manager/sdk/java/jni/tm/inc/jni_action.h
new file mode 100644 (file)
index 0000000..e26ab83
--- /dev/null
@@ -0,0 +1,91 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_action.h
+  *
+  * @brief  This file contains the declaration of JniAction class and its members related to JniAction.
+  */
+
+#ifndef __JNI_ACTION_H_
+#define __JNI_ACTION_H_
+
+
+#include <vector>
+#include <string>
+
+#include "jni_object.h"
+#include "jni_capability.h"
+
+/**
+ * @class   JniAction
+ * @brief   This class provides a set of functions to get and set Action Class member variables
+ *
+ */
+class JniAction : public JObject
+{
+    public:
+        /**
+         * @brief constructor
+         */
+        JniAction(JNIEnv *env, jobject obj);
+
+        /**
+         * @brief constructor
+         */
+        JniAction(JNIEnv *env);
+
+        /**
+         * @brief destructor
+         *
+         */
+        ~JniAction();
+
+        /**
+         * Retrieves target value from JniAction class object
+         *
+         * @param target - target value
+         *
+         * @return Boolean, true on success, otherwise false
+         *
+         */
+        bool getTarget(std::string &target);
+
+        /**
+         * Sets target value of JniAction class object
+         *
+         * @param target - target value
+         *
+         * @return Boolean, true on success, otherwise false
+         *
+         */
+        bool setTarget(const std::string target);
+
+        /**
+         * Retrieves capability values from JniAction class object
+         *
+         * @param capabilityList - capability list
+         *
+         * @return Boolean, true on success, otherwise false
+         */
+        bool getJniCapabilityValues(std::vector<OIC::Capability *> &capabilityList);
+
+};
+#endif //__JNI_ACTION_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/tm/inc/jni_action_set.h b/service/things-manager/sdk/java/jni/tm/inc/jni_action_set.h
new file mode 100644 (file)
index 0000000..07afd7c
--- /dev/null
@@ -0,0 +1,118 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_action_set.h
+  *
+  * @brief  This file contains the declaration of  JniActionSet class
+  *            and its members related to JniActionSet.
+  */
+
+#ifndef __JNI_ACTIONSET_H_
+#define __JNI_ACTIONSET_H_
+
+
+#include <vector>
+#include <string>
+
+#include "ThingsManager.h"
+#include "ActionSet.h"
+#include "jni_object.h"
+#include "jni_action.h"
+
+using namespace OC;
+using namespace OIC;
+
+/**
+ * @class   JniActionSet
+ * @brief   This class provides a set of functions to get and set ActionSet Class member variables
+ *
+ */
+class JniActionSet : public JObject
+{
+    public:
+        /**
+         * @brief constructor
+         */
+        JniActionSet(JNIEnv *env, jobject obj);
+
+        /**
+         * @brief constructor
+         */
+        JniActionSet(JNIEnv *env);
+
+        /**
+         * @brief destructor
+         *
+         */
+        ~JniActionSet();
+
+        /**
+         * Retrieves target value from JniActionSet class object
+         *
+         * @param name - ActionSet Name
+         *
+         * @return  Boolean, true on success, otherwise false
+         *
+         */
+        bool getJniActionSetName(std::string &name);
+
+        /**
+         * Sets target value of JniActionSet class object
+         *
+         * @param name - ActionSet Name
+         *
+         * @return  Boolean, true on success, otherwise false
+         *
+         */
+        bool setJniActionSetName(const std::string name);
+
+        /**
+         * Retrieves capability values from JniActionSet class object
+         *
+         * @param actionList - List of Actions
+         *
+         * @return  Boolean, true on success, otherwise false
+         */
+        bool getJniListOfActions(std::vector<OIC::Action *> &actionList);
+
+        /**
+         * Converts actionSet class from java to CPP
+         *
+         * @param env - Default JNI Environment Pointer
+         * @param jnewActionSet - action set
+         *
+         * @return  OIC CPP ActionSet
+         */
+        ActionSet *getActionSet(JNIEnv *env, jobject jnewActionSet);
+
+        /**
+         * Converts Time class from java to CPP
+         *
+         * @param env - Default JNI Environment Pointer
+         * @param jnewActionSet - Java action set
+         * @param pActionSet - CPP action set
+         *
+         * @return  Boolean, true on success, otherwise false
+         */
+        bool setTimeInfo(JNIEnv *env, jobject jnewActionSet, OIC::ActionSet *pActionSet);
+};
+#endif  //__JNI_ACTIONSET_H_
+
diff --git a/service/things-manager/sdk/java/jni/tm/inc/jni_capability.h b/service/things-manager/sdk/java/jni/tm/inc/jni_capability.h
new file mode 100644 (file)
index 0000000..c355ec7
--- /dev/null
@@ -0,0 +1,105 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_capability.h
+  *
+  * @brief  This file contains the utility functions for conversions from java to CPP
+  * and viceversa
+  */
+
+#ifndef __JNI_CAPABILITY_H_
+#define __JNI_CAPABILITY_H_
+
+
+#include <string>
+
+#include <ActionSet.h>
+#include "jni_object.h"
+
+/**
+ * @class   JniCapability
+ * @brief   This class provides a set of functions to get and set Capability Class member variables
+ *
+ */
+class JniCapability : public JObject
+{
+    public:
+        /**
+         * @brief constructor
+         */
+        JniCapability(JNIEnv *env, jobject obj);
+
+        /**
+         * @brief constructor
+         */
+        JniCapability(JNIEnv *env);
+
+        /**
+         * @brief destructor
+         *
+         */
+        ~JniCapability();
+
+        /**
+         * Retrieves Capability value from JniCapability class object
+         *
+         * @param   capability
+         *              [OUT] capability value
+         *
+         * @return  Boolean, true on success, otherwise false
+         *
+         */
+        bool getJniCapabilityValue(std::string &capability);
+
+        /**
+         * Sets Capability value of JniCapability class object
+         *
+         * @param   capability
+         *              [IN] capability value
+         *
+         * @return  Boolean, true on success, otherwise false
+         *
+         */
+        bool setJniCapabilityValue(const std::string capability);
+
+        /**
+         * Retrieves status of JniCapability class object
+         *
+         * @param   status
+         *              [OUT] status
+         *
+         * @return  Boolean, true on success, otherwise false
+         *
+         */
+        bool getJniCapabilityStatus(std::string &status);
+
+        /**
+         * Sets status of JniCapability class object
+         *
+         * @param   status
+         *              [IN] status
+         *
+         * @return  Boolean, true on success, otherwise false
+         *
+         */
+        bool setJniCapabilityStatus(const std::string status);
+};
+#endif  //__JNI_CAPABILITY_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/tm/inc/jni_things_manager.h b/service/things-manager/sdk/java/jni/tm/inc/jni_things_manager.h
new file mode 100644 (file)
index 0000000..042de70
--- /dev/null
@@ -0,0 +1,372 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/** @file   jni_things_manager.h
+ *
+ *   @brief  This file contains the declaration of Things Manager service API's
+ *              for JNI implementation
+ */
+
+#ifndef __JNI_THINGS_MANAGER_H_
+#define __JNI_THINGS_MANAGER_H_
+
+
+#include <stdio.h>
+#include <string.h>
+
+#include <jni.h>
+#include <jni_string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * API for discoverying candidate resources.
+ *
+ * @param resourceTypes - required resource types(called "candidate")
+ * @param waitSec - Delay time in seconds to add before starting to find the resources in network.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerFindCandidateResource
+(JNIEnv *env, jobject interfaceObject, jobject resourceTypes, jint waitSec);
+
+/**
+ * API for subscribing child's state.
+ *
+ * @param resource - collection resource for subscribing presence of all child resources.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerSubscribeCollectionPresence
+(JNIEnv *env, jobject interfaceObject, jobject resource);
+
+/**
+ * API for register and bind resource to group.
+ *
+ * @param resource - resource for register and bind to group. It has all data.
+ * @param collectionHandle - collection resource handle. It will be added child resource.
+ *
+ * @return childHandle - child resource handle.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jobject JNICALL JNIThingsManagerBindResourceToGroup
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject collectionHandle);
+
+/**
+ * API for finding a specific remote group when a resource tries to join a group.
+ * Callback is called when a group is found or not.
+ *
+ * @param resourceTypes - resource types of a group to find and join
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: It return OC_STACK ERROR when It was finding a group.
+ *       You should call this api when the group finding process has stopped.
+ *       OCStackResult is defined in ocstack.h.
+ */
+
+JNIEXPORT jint JNICALL JNIThingsManagerFindGroup
+(JNIEnv *env, jobject interfaceObject, jobject resourceTypes);
+
+/**
+ * API for creating a new group.
+ *
+ * @param resourceType - resource type of a group to create
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerCreateGroup
+(JNIEnv *env, jobject interfaceObject, jstring resourceType);
+
+/**
+ * API for joining a group. This API is used when a resource that has a group tries
+ * to find a specific remote resource and makes it join a group
+ *
+ * @param resourceType - resource type of a group to join.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: If you want to join the resource in the remote(other) process, use the API
+ *       jniThingsManagerJoinGroupObject instead of this.
+ *       OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupString
+(JNIEnv *env, jobject interfaceObject, jstring resourceType, jobject resourceHandle);
+
+/**
+ * API for joining a group. This API is used when a resource that
+ * doesn't have a group tries to find and join a specific remote group.
+ *
+ * @param resource - group resource pointer to join.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: NOTE: If you want to join the resource in the same process, use the API
+ *       jniThingsManagerJoinGroupString instead of this.
+ *       OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupObject
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject resourceHandle);
+
+/**
+ * API for leaving a joined group.
+ *
+ * @param resourceType - resource type of a group to leave.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroup
+(JNIEnv *env, jobject interfaceObject, jstring resourceType, jobject resourceHandle);
+
+/**
+ * API for leaving a joined group.
+ *
+ * @param resource - resource of a group to leave.
+ * @param resourceType - resource type of a group to leave.
+ * @param resourceHandle - resource handle to join a group.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroupForResource
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring resourceType,
+ jobject resourceHandle);
+/**
+ * API for deleting a group.
+ *
+ * @param collectionResourceType - resource type of a group to delete.
+ *
+ * @return void
+ */
+JNIEXPORT void JNICALL JNIThingsManagerDeleteGroup
+(JNIEnv *env, jobject interfaceObject, jstring collectionResourceType);
+
+/**
+ * API for getting a list of joined groups.
+ *
+ * @return std::map - return value of this API.
+ *                  It returns group resource type and group resource handle as a map type.
+ */
+JNIEXPORT jobject JNICALL JNIThingsManagerGetGroupList
+(JNIEnv *env, jobject interfaceObject);
+
+/**
+ * API for updating configuration value of multiple things of a target group
+ * or a single thing.
+ * Before using the below function, a developer should acquire a resource pointer of
+ * (collection) resource that he wants to send a request by calling findResource() function
+ * provided in OCPlatform. And he should also notice a "Configuration Name" term which
+ * represents a nickname of a target attribute of a resource that he wants to update.
+ * The base motivation to introduce the term is to avoid a usage of URI to access a resource
+ * from a developer. Thus, a developer should know which configuration names are supported
+ * by Things Configuration class and what the configuration name means.
+ * To get a list of supported configuration names,  use getListOfSupportedConfigurationUnits()
+ * function, which provides the list in JSON format.
+ *
+ * @param resource - resource pointer representing the target group or the single thing.
+ * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
+ *                         (e.g., installedlocation, currency, (IP)address)
+ *                         Value : a value to be updated
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerUpdateConfigurations
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject configurations);
+
+/**
+ * API for getting configuration value of multiple things of a target group
+ * or a single thing.
+ *
+ * @param resource - resource pointer representing the target group or the single thing.
+ * @param configurations - ConfigurationUnit: a nickname of attribute of target resource.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerGetConfigurations
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject configurations);
+
+/**
+ * API for showing the list of supported configuration units (configurable parameters)
+ *
+ * @return std::string - return value of this API.
+ *                       It returns the list in JSON format
+ */
+JNIEXPORT jstring JNICALL JNIThingsManagerGetListOfSupportedConfigurationUnits
+(JNIEnv *env, jobject interfaceObject);
+
+/**
+ * API for boostrapping system configuration parameters from a bootstrap server.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerDoBootstrap
+(JNIEnv *env, jobject interfaceObject);
+
+/**
+ * API to let thing(device) reboot.
+ * The target thing could be a group of multiple things or a single thing.
+ *
+ * @param resource - resource type representing the target group
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerReboot
+(JNIEnv *env, jobject interfaceObject, jobject resource);
+
+/**
+ * API for factory reset on thing(device).
+ * The target thing could be a group of multiple things or a single thing.
+ *
+ * @param resource - resource type representing the target group
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerFactoryReset
+(JNIEnv *env, jobject interfaceObject, jobject resource);
+
+/**
+ * API for adding an Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param newActionSet - list of Action Set to be added
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+
+JNIEXPORT jint JNICALL JNIThingsManagerAddActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jobject newActionSet);
+
+/**
+ * API for executing the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for executing the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+/**
+ * API for executing the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for executing the Action set
+ * @param delay - waiting time for until action set run.
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSetWithDelay
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName, jlong delay);
+
+/**
+ * API for cancelling the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for cancelling the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerCancelActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+
+/**
+ * API for reading the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for reading the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerGetActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+/**
+ * API for removing the Action Set.
+ *
+ * @param resource - resource type representing the target group
+ * @param actionSetName - Action Set name for removing the Action set
+ *
+ * @return OCStackResult - return value of this API.
+ *                         It returns OC_STACK_OK if success.
+ *
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */
+JNIEXPORT jint JNICALL JNIThingsManagerDeleteActionSet
+(JNIEnv *env, jobject interfaceObject, jobject resource, jstring actionSetName);
+
+#ifdef __cplusplus
+}
+#endif
+#endif //__JNI_THINGS_MANAGER_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/tm/inc/jni_things_manager_callbacks.h b/service/things-manager/sdk/java/jni/tm/inc/jni_things_manager_callbacks.h
new file mode 100644 (file)
index 0000000..42cdc44
--- /dev/null
@@ -0,0 +1,208 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/** @file   jni_things_manager_callbacks.h
+  *
+  *  @brief  This file contains the declaration of ThingsManagerCallbacks class
+  *         and its members related to ThingsManagerCallbacks.
+  */
+
+#ifndef __JNI_THINGS_MANAGER_CALLBACKS_H_
+#define __JNI_THINGS_MANAGER_CALLBACKS_H_
+
+#include <string>
+
+#include "ThingsManager.h"
+
+/**
+ * @class   ThingsManagerCallbacks
+ * @brief   This class provides a set of callback functions for group management,
+ *          synchronization of group, configuration of things, and diagnostics about things.
+ *
+ */
+class ThingsManagerCallbacks
+{
+
+    public:
+        ThingsManagerCallbacks() {}
+        virtual ~ThingsManagerCallbacks() {}
+
+        /**
+         * This callback method is called when resources are discovered in network.
+         *
+         * @param resourceVector - List of resources discovered in the network
+         *
+         * @return void
+         */
+        static void onFoundCandidateResource(std::vector< std::shared_ptr<OC::OCResource > >
+                                             resourceVector);
+
+        /**
+         * This callback method is called to notify whether group is found or not.
+         *
+         * @param resource - Resource URI
+         *
+         * @return void
+         */
+        static void onFoundGroup(std::shared_ptr<OC::OCResource> resource);
+
+        /**
+         * This callback method is called for child resource presence status.
+         *
+         * @param resource - URI of resource.
+         * @param result - error code.
+         *
+         * @return void
+         */
+        static void onSubscribePresence(std::string resource, OCStackResult result);
+
+        /**
+         * This callback method is called when a response for the updateConfigurations request
+         * just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onUpdateConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+                const OC::OCRepresentation &rep, const int eCode);
+
+        /**
+         * This callback method is called when a response for the getConfigurations request
+         * just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onGetConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+                                                const OC::OCRepresentation &rep, const int eCode);
+
+        /**
+         * This callback method is called when a response for the doBootstrap request
+         * just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onBootStrapResponse(const OC::HeaderOptions &headerOptions,
+                                        const OC::OCRepresentation &rep,
+                                        const int eCode);
+
+        /**
+         * This callback method is called when a response for the reboot request
+         * just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onRebootResponse(const OC::HeaderOptions &headerOptions,
+                                     const OC::OCRepresentation &rep,
+                                     const int eCode);
+
+        /**
+         * This callback method is called when a response for the factoryReset request
+         * just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onFactoryResetResponse(const OC::HeaderOptions &headerOptions,
+                                           const OC::OCRepresentation &rep,
+                                           const int eCode);
+
+        /**
+         * This callback method is called when a response for the executeActionSet
+         * or deleteActionSet request just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onPostResponse(const OC::HeaderOptions &headerOptions,
+                                   const OC::OCRepresentation &rep, const int eCode);
+
+        /**
+         * This callback method is called when a response for the addActionSet request
+         * just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onPutResponse(const OC::HeaderOptions &headerOptions,
+                                  const OC::OCRepresentation &rep, const int eCode);
+
+        /**
+         * This callback method is called when a response for the getActionSet request
+         * just arrives.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         *
+         * @return void
+         */
+        static void onGetResponse(const OC::HeaderOptions &headerOptions,
+                                  const OC::OCRepresentation &rep, const int eCode);
+
+        /**
+         * This method invokes the Callback function with particular name and signature.
+         *
+         * @param headerOptions - It comprises of optionID and optionData as members.
+         * @param rep - Configuration parameters are carried as a pair of attribute key and value
+         *                      in a form of OCRepresentation instance.
+         * @param eCode - error code.
+         * @param callbackName - callbackName to be invoked.
+         * @param signature - Signature of the callback method to be called.
+         *
+         * @return void
+         */
+        static void invokeCallback(const OC::HeaderOptions &headerOptions,
+                                   const OC::OCRepresentation &rep, const int eCode,
+                                   const char *callbackName, const char *signature);
+
+};
+#endif  //__JNI_THINGS_MANAGER_CALLBACKS_H_
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/tm/inc/jni_things_manager_util.h b/service/things-manager/sdk/java/jni/tm/inc/jni_things_manager_util.h
new file mode 100644 (file)
index 0000000..cf89df8
--- /dev/null
@@ -0,0 +1,56 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   jni_things_manager_util.h
+  *
+  * @brief  This file contains the utility functions for conversions from java to CPP
+  * and viceversa
+  */
+
+#ifndef __JNI_THINGS_MANAGER_UTILS_H_
+#define __JNI_THINGS_MANAGER_UTILS_H_
+
+
+#include <vector>
+#include <map>
+#include "jni_things_manager_jvm.h"
+
+/**
+  * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
+  *
+  * @param env - Default JNI Environment pointer
+  * @param jVectorString - Java Vector of Strings
+  *
+  * @return void
+  */
+std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString);
+
+/**
+  * Utility function for converting a Hash Map of Strings to CPP Map of Strings
+  *
+  * @param env - Default JNI Environment pointer
+  * @param jMapString - Java Map of Strings
+  *
+  * @return void
+  */
+std::map<std::string, std::string> convertStringMap(JNIEnv *env, jobject jMapString);
+#endif //__JNI_THINGS_MANAGER_UTILS_H_
+
diff --git a/service/things-manager/sdk/java/jni/tm/src/jni_action.cpp b/service/things-manager/sdk/java/jni/tm/src/jni_action.cpp
new file mode 100644 (file)
index 0000000..45ea379
--- /dev/null
@@ -0,0 +1,83 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_action.h"
+
+#include <ActionSet.h>
+#include "jni_things_manager_jvm.h"
+#include "jni_getter.h"
+#include "jni_setter.h"
+
+#define JACTION_TARGET              ("target")
+#define JACTION_LISTOF_CAPABILITY   ("listOfCapability")
+
+
+JniAction::JniAction(JNIEnv *env, jobject obj) : JObject(env, obj)
+{
+}
+
+JniAction::JniAction(JNIEnv *env) : JObject(env, TM_SERVICE_ACTION_PATH)
+{
+}
+
+JniAction::~JniAction()
+{
+}
+
+bool JniAction::getTarget(std::string &target)
+{
+    //Retrieves target value from JniAction class object
+    return JGetter::getJStringField(m_pEnv, m_pObject, JACTION_TARGET, target);
+}
+
+bool JniAction::setTarget(const std::string target)
+{
+    //Sets target value of JniAction class object
+    return JSetter::setJStringField(m_pEnv, m_pObject, JACTION_TARGET, target.c_str());
+}
+
+bool JniAction::getJniCapabilityValues(std::vector<OIC::Capability *> &capabilityList)
+{
+    jclass jvectorClass = m_pEnv->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+    jmethodID vectorMethodID = m_pEnv->GetMethodID(jvectorClass, "get", "(I)Ljava/lang/Object;");
+    jmethodID vectorSizeMethodID = m_pEnv->GetMethodID(jvectorClass, "size", "()I");
+
+    jobject jAttrList = NULL;
+    bool res = JGetter::getJObjectField(m_pEnv, m_pObject,
+                                        JACTION_LISTOF_CAPABILITY, TM_JAVA_VECTOR_TYPE, jAttrList);
+
+    if (res == true)
+    {
+        capabilityList.clear();
+        int attrCount = m_pEnv->CallIntMethod(jAttrList, vectorSizeMethodID);
+        for (int i = 0; i < attrCount; i++)
+        {
+            JniCapability *attr_var = new JniCapability(m_pEnv,
+                    m_pEnv->CallObjectMethod(jAttrList, vectorMethodID, i));
+
+            OIC::Capability *cap = new OIC::Capability();
+            attr_var->getJniCapabilityValue(cap->capability);
+            attr_var->getJniCapabilityStatus(cap->status);
+            delete attr_var;
+            capabilityList.push_back(cap);
+        }
+    }
+    m_pEnv->DeleteLocalRef(jvectorClass);
+    return res;
+}
diff --git a/service/things-manager/sdk/java/jni/tm/src/jni_action_set.cpp b/service/things-manager/sdk/java/jni/tm/src/jni_action_set.cpp
new file mode 100644 (file)
index 0000000..d952f81
--- /dev/null
@@ -0,0 +1,186 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_action_set.h"
+
+#include "jni_things_manager_jvm.h"
+#include "jni_getter.h"
+#include "jni_setter.h"
+#include "JniOcResource.h"
+
+#define JACTIONSET_NAME             ("actionsetName")
+#define JACTIONSET_LISTOF_ACTION    ("listOfAction")
+
+JniActionSet::JniActionSet(JNIEnv *env, jobject obj) : JObject(env, obj)
+{
+}
+
+JniActionSet::JniActionSet(JNIEnv *env) : JObject(env, TM_SERVICE_ACTIONSET_PATH)
+{
+}
+
+JniActionSet::~JniActionSet()
+{
+}
+
+bool JniActionSet::getJniActionSetName(std::string &name)
+{
+    //Retrieves target value from JniActionSet class object
+    return JGetter::getJStringField(m_pEnv, m_pObject, JACTIONSET_NAME, name);
+}
+
+bool JniActionSet::setJniActionSetName(const std::string name)
+{
+    //Sets target value of JniActionSet class object
+    return JSetter::setJStringField(m_pEnv, m_pObject, JACTIONSET_NAME, name.c_str());
+}
+
+bool JniActionSet::getJniListOfActions(std::vector<OIC::Action *> &actionList)
+{
+    jclass jvectorClass = m_pEnv->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+    jmethodID vectorMethodID = m_pEnv->GetMethodID(jvectorClass, "get", "(I)Ljava/lang/Object;");
+    jmethodID vectorSizeMethodID = m_pEnv->GetMethodID(jvectorClass, "size", "()I");
+    jobject jAttrList = NULL;
+    bool res = JGetter::getJObjectField(m_pEnv, m_pObject,
+                                        JACTIONSET_LISTOF_ACTION, TM_JAVA_VECTOR_TYPE, jAttrList);
+
+    if (res == true)
+    {
+        actionList.clear();
+        int attrCount = m_pEnv->CallIntMethod(jAttrList, vectorSizeMethodID);
+        for (int i = 0; i < attrCount; i++)
+        {
+            JniAction *attr_var = new JniAction(m_pEnv,
+                                                m_pEnv->CallObjectMethod(jAttrList, vectorMethodID, i));
+            OIC::Action *actionName = new OIC::Action();
+            attr_var->getTarget(actionName->target);
+            attr_var->getJniCapabilityValues(actionName->listOfCapability);
+            delete attr_var;
+            actionList.push_back(actionName);
+        }
+    }
+    m_pEnv->DeleteLocalRef(jvectorClass);
+    return true;
+}
+ActionSet *JniActionSet::getActionSet(JNIEnv *env, jobject jnewActionSet)
+{
+    LOGI("getActionSet: Enter");
+
+    if (NULL == jnewActionSet)
+    {
+        LOGE("getActionSet: jnewActionSet is NULL");
+        return NULL;
+    }
+
+    std::string actionsetName;
+    getJniActionSetName(actionsetName);
+
+    std::vector<Action *> actionVector;
+    getJniListOfActions(actionVector);
+
+    OIC::ActionSet *pActionSet = new OIC::ActionSet();
+    if (NULL == pActionSet)
+    {
+        LOGE("getActionSet: Failed to create newActionSet");
+        return NULL;
+    }
+
+    pActionSet->actionsetName = actionsetName;
+    pActionSet->listOfAction = actionVector;
+    if (false == setTimeInfo(env, jnewActionSet, pActionSet))
+    {
+        LOGE("getActionSet: setTimeInfo failed!");
+        delete pActionSet;
+        return NULL;
+    }
+
+    LOGI("getActionSet: Exit");
+    return pActionSet;
+}
+
+bool JniActionSet::setTimeInfo(JNIEnv *env, jobject jnewActionSet, OIC::ActionSet *pActionSet)
+{
+    LOGI("setTimeInfo: Entry");
+    if (NULL == jnewActionSet)
+    {
+        LOGE("setTimeInfo: jnewActionSet is NULL");
+        return NULL;
+    }
+
+    jclass classTime = env->FindClass(TM_SERVICE_TIME_PATH);
+    if (NULL == classTime)
+    {
+        LOGE("FindClass failed for [%s]", TM_SERVICE_TIME_PATH);
+        return false;
+    }
+
+    jfieldID fieldID = env->GetFieldID(classTime, "mYear", "I");
+    int year = env->GetIntField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mMonth", "I");
+    int month = env->GetIntField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mDay", "I");
+    int day = env->GetIntField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mHour", "I");
+    int hour = env->GetIntField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mMin", "I");
+    int min = env->GetIntField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mSec", "I");
+    int sec = env->GetIntField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mDayOfWeek", "I");
+    int wday = env->GetIntField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mDelay", "J");
+    long delay = env->GetLongField(jnewActionSet, fieldID);
+
+    fieldID = env->GetFieldID(classTime, "mType", "Lorg/iotivity/service/tm/Time$ActionSetType;");
+    jobject actionSetTypeObj = env->GetObjectField(jnewActionSet, fieldID);
+    if (NULL == actionSetTypeObj)
+    {
+        LOGE("setTimeInfo: actionSetTypeObj is NULL");
+        return false;
+    }
+
+    jclass actionSetTypeClass = env->GetObjectClass(actionSetTypeObj);
+    if (NULL == actionSetTypeClass)
+    {
+        LOGE("setTimeInfo: actionSetTypeClass is NULL");
+        return false;
+    }
+
+    jmethodID actionSetTypeMethod = env->GetMethodID(actionSetTypeClass, "ordinal", "()I");
+    if (NULL == actionSetTypeMethod)
+    {
+        LOGE("setTimeInfo: actionSetTypeMethod is NULL");
+        return false;
+    }
+
+    int type = (int) env->CallIntMethod(actionSetTypeObj, actionSetTypeMethod);
+    pActionSet->setTime(year, month, day, hour, min, sec, wday);
+    pActionSet->type = static_cast<OIC::ACTIONSET_TYPE>(type);
+    pActionSet->setDelay(delay);
+
+    LOGI("setTimeInfo: Exit");
+    return true;
+}
diff --git a/service/things-manager/sdk/java/jni/tm/src/jni_capability.cpp b/service/things-manager/sdk/java/jni/tm/src/jni_capability.cpp
new file mode 100644 (file)
index 0000000..9a15496
--- /dev/null
@@ -0,0 +1,63 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_capability.h"
+
+#include "jni_things_manager_jvm.h"
+#include "jni_getter.h"
+#include "jni_setter.h"
+
+#define JCAPABILITY_STATUS         ("status")
+#define JCAPABILITY_CAPABILITY  ("capability")
+
+JniCapability::JniCapability(JNIEnv *env, jobject obj) : JObject(env, obj)
+{
+}
+
+JniCapability::JniCapability(JNIEnv *env) : JObject(env, TM_SERVICE_CAPABILITY_PATH)
+{
+}
+
+JniCapability::~JniCapability()
+{
+}
+
+bool JniCapability::getJniCapabilityValue(std::string &capability)
+{
+    //Retrieves capability value from JniCapability class object
+    return JGetter::getJStringField(m_pEnv, m_pObject, JCAPABILITY_CAPABILITY, capability);
+}
+
+bool JniCapability::setJniCapabilityValue(const std::string capability)
+{
+    //Sets capability value of JniCapability class object
+    return JSetter::setJStringField(m_pEnv, m_pObject, JCAPABILITY_CAPABILITY, capability.c_str());
+}
+
+bool JniCapability::getJniCapabilityStatus(std::string &status)
+{
+    //Retrieves status from JniCapability class object
+    return JGetter::getJStringField(m_pEnv, m_pObject, JCAPABILITY_STATUS, status);
+}
+
+bool JniCapability::setJniCapabilityStatus(const std::string status)
+{
+    //Sets status of JniCapability class object
+    return JSetter::setJStringField(m_pEnv, m_pObject, JCAPABILITY_STATUS, status.c_str());
+}
diff --git a/service/things-manager/sdk/java/jni/tm/src/jni_things_manager.cpp b/service/things-manager/sdk/java/jni/tm/src/jni_things_manager.cpp
new file mode 100644 (file)
index 0000000..6e66c54
--- /dev/null
@@ -0,0 +1,1013 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_things_manager.h"
+
+#include "JniOcResource.h"
+#include "JniOcResourceHandle.h"
+#include "ThingsManager.h"
+#include "ActionSet.h"
+#include "jni_things_manager_jvm.h"
+#include "jni_things_manager_util.h"
+#include "jni_things_manager_callbacks.h"
+#include "jni_action_set.h"
+
+using namespace OC;
+using namespace OIC;
+
+/**
+ * @var g_ThingsManager
+ * @brief ThingsManager static object
+ */
+static ThingsManager g_ThingsManager;
+
+jobject ocResourceHandleToJava(JNIEnv *env, jlong resourceHandle);
+
+JNIEXPORT jint JNICALL JNIThingsManagerFindCandidateResource(JNIEnv *env, jobject interfaceObject,
+        jobject jResourceTypes, jint waitSec)
+{
+    LOGI("JNIThingsManagerFindCandidateResource: Enter");
+
+    if (!jResourceTypes)
+    {
+        LOGE("JNIThingsManagerFindCandidateResource: jResourceTypes is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+    try
+    {
+        ocResult = g_ThingsManager.findCandidateResources(convertStringVector(env, jResourceTypes),
+                   &ThingsManagerCallbacks::onFoundCandidateResource, (int)waitSec);
+
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerFindCandidateResource: findCandidateResources failed!");
+            return ocResult;
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerFindCandidateResource: Exception occurred! %s, %d", e.reason().c_str(),
+             e.code());
+        return ocResult;
+    }
+
+    LOGI("JNIThingsManagerFindCandidateResource: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerSubscribeCollectionPresence(JNIEnv *env,
+        jobject interfaceObject,
+        jobject jResource)
+{
+    LOGI("JNIThingsManagerSubscribeCollectionPresence: Enter");
+
+    if (!jResource)
+    {
+        LOGE("JNIThingsManagerSubscribeCollectionPresence: jResource is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+    if (NULL == jniOcResource)
+    {
+        LOGE("JNIThingsManagerSubscribeCollectionPresence: Failed to get jni OcResource!");
+        return ocResult;
+    }
+
+    std::shared_ptr<OCResource> ocResource = jniOcResource->getOCResource();
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerSubscribeCollectionPresence: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    ocResult = g_ThingsManager.subscribeCollectionPresence(ocResource,
+               &ThingsManagerCallbacks::onSubscribePresence);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerSubscribeCollectionPresence: subscribeCollectionPresence failed!");
+        return ocResult;
+    }
+
+    LOGI("JNIThingsManagerSubscribeCollectionPresence: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jobject JNICALL JNIThingsManagerBindResourceToGroup(JNIEnv *env, jobject interfaceObject,
+        jobject jResource, jobject jCollectionHandle)
+{
+    LOGI("JNIThingsManagerBindResourceToGroup: Enter");
+
+    if (!jResource || !jCollectionHandle)
+    {
+        LOGE("JNIThingsManagerBindResourceToGroup: Invalid parameter!");
+        return NULL;
+    }
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerBindResourceToGroup: Failed to get OCResource object!");
+        return NULL;
+    }
+
+    JniOcResourceHandle *jniOcCollectionHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+            jCollectionHandle);
+    if (NULL == jniOcCollectionHandle)
+    {
+        LOGE("JNIThingsManagerBindResourceToGroup: collection handle is null!");
+        return NULL;
+    }
+
+    jobject jResourceHandle = NULL;
+    try
+    {
+        OCResourceHandle ocChildHandle = NULL;
+        OCResourceHandle ocCollectionHandle = jniOcCollectionHandle->getOCResourceHandle();
+        OCStackResult ocResult = g_ThingsManager.bindResourceToGroup(ocChildHandle, ocResource, ocCollectionHandle);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerBindResourceToGroup: bindResourceToGroup failed!");
+            return NULL;
+        }
+
+        // Convert OCResourceHandle to java type
+        JniOcResourceHandle* jniHandle = new JniOcResourceHandle(ocChildHandle);
+        jlong handle = reinterpret_cast<jlong>(jniHandle);
+        jResourceHandle = env->NewObject(g_cls_OcResourceHandle, g_mid_OcResourceHandle_N_ctor, handle);
+        if (env->ExceptionCheck())
+        {
+            LOGE("JNIThingsManagerBindResourceToGroup: Failed to create OcResourceHandle");
+            delete jniHandle;
+            return NULL;
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerBindResourceToGroup: Exception occurred! %s, %d", e.reason().c_str(),
+             e.code());
+        return NULL;
+    }
+
+    LOGI("JNIThingsManagerBindResourceToGroup: Exit");
+    return jResourceHandle;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerFindGroup(JNIEnv *env, jobject interfaceObject,
+        jobject jResourceTypes)
+{
+    LOGI("JNIThingsManagerFindGroup: Enter");
+
+    if (!jResourceTypes)
+    {
+        LOGE("JNIThingsManagerFindGroup: jResourceTypes is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+    try
+    {
+        ocResult = g_ThingsManager.findGroup((convertStringVector(env, jResourceTypes)),
+                                             &ThingsManagerCallbacks::onFoundGroup);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerFindGroup: findGroup failed!");
+            return ocResult;
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerFindGroup: Exception occurred! %s, %d", e.reason().c_str(),
+            e.code());
+        return ocResult;
+    }
+    LOGI("JNIThingsManagerFindGroup: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerCreateGroup(JNIEnv *env, jobject interfaceObject,
+        jstring jResourceType)
+{
+    LOGI("JNIThingsManagerCreateGroup: Enter");
+
+    if (!jResourceType)
+    {
+        LOGE("JNIThingsManagerCreateGroup: jResourceType is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+    if (NULL == resourceTypePointer)
+    {
+        LOGE("JNIThingsManagerCreateGroup: Failed to convert jstring to char string!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    std::string resourceType(resourceTypePointer);
+    try
+    {
+        ocResult =  g_ThingsManager.createGroup(resourceType);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerCreateGroup: CreateGroup failed!");
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerCreateGroup: Exception occurred! %s, %d", e.reason().c_str(),
+            e.code());
+    }
+    env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+    LOGI("JNIThingsManagerCreateGroup: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupString(JNIEnv *env, jobject interfaceObject,
+        jstring jResourceType, jobject jResourceHandle)
+{
+    LOGI("JNIThingsManagerJoinGroupString: Enter");
+
+    if ((!jResourceType) || (!jResourceHandle))
+    {
+        LOGE("JNIThingsManagerJoinGroupString: jResourceType or jResourceHandle is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+    if (NULL == resourceTypePointer)
+    {
+        LOGE("JNIThingsManagerJoinGroupString: Failed to convert jstring to char string!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    std::string resourceType(resourceTypePointer);
+
+    JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+            jResourceHandle);
+    try
+    {
+        OCResourceHandle ocResourceHandle = jniOcResourceHandle->getOCResourceHandle();
+        ocResult = g_ThingsManager.joinGroup(resourceType, ocResourceHandle);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerJoinGroupString: joinGroup failed!");
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerJoinGroupString: Exception occurred! %s, %d", e.reason().c_str(),
+             e.code());
+    }
+    env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+    LOGI("JNIThingsManagerJoinGroupString: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerJoinGroupObject(JNIEnv *env, jobject interfaceObject,
+        jobject jResource, jobject jResourceHandle)
+{
+    LOGI("JNIThingsManagerJoinGroupObject: Enter");
+
+    if ((!jResource) || (!jResourceHandle))
+    {
+        LOGE("JNIThingsManagerJoinGroupObject: jResource or jResourceHandle is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerJoinGroupObject: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+            jResourceHandle);
+
+    try
+    {
+        OCResourceHandle resHandle = jniOcResourceHandle->getOCResourceHandle();
+
+        ocResult = g_ThingsManager.joinGroup(ocResource, resHandle);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerJoinGroupObject: joinGroup failed!");
+            return ocResult;
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerJoinGroupObject: Exception occurred! %s, %d", e.reason().c_str(),
+             e.code());
+        return ocResult;
+    }
+    LOGI("JNIThingsManagerJoinGroupObject: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroup(JNIEnv *env, jobject interfaceObject,
+        jstring jResourceType,
+        jobject jResourceHandle)
+{
+    LOGI("JNIThingsManagerLeaveGroup: Enter");
+
+    if ((!jResourceType) || (!jResourceHandle))
+    {
+        LOGE("JNIThingsManagerLeaveGroup: jResourceType or jResourceHandle is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+    if (NULL == resourceTypePointer)
+    {
+        LOGE("JNIThingsManagerLeaveGroup: Failed to convert jstring to char string!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    std::string resourceType(resourceTypePointer);
+    JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+            jResourceHandle);
+
+    try
+    {
+        OCResourceHandle ocResourceHandle = jniOcResourceHandle->getOCResourceHandle();
+
+        ocResult = g_ThingsManager.leaveGroup(resourceType, ocResourceHandle);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerLeaveGroup: leaveGroup failed!");
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerLeaveGroup: Exception occurred! %s, %d", e.reason().c_str(),
+            e.code());
+    }
+    env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+    LOGI("JNIThingsManagerLeaveGroup: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerLeaveGroupForResource(JNIEnv *env, jobject interfaceObject,
+        jobject jResource,
+        jstring jResourceType,
+        jobject jResourceHandle)
+{
+    LOGI("JNIThingsManagerLeaveGroupForResource: Enter");
+
+    if ((!jResource) || (!jResourceType) || (!jResourceHandle))
+    {
+        LOGE("JNIThingsManagerLeaveGroupForResource: jResourceType or jResourceHandle is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
+    if (NULL == jniOcResource)
+    {
+        LOGE("JNIThingsManagerLeaveGroupForResource: Failed to get jni OcResource!");
+        return ocResult;
+    }
+
+    std::shared_ptr<OCResource> ocResource = jniOcResource->getOCResource();
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerLeaveGroupForResource: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    const char *resourceTypePointer = env->GetStringUTFChars(jResourceType, NULL);
+    if (NULL == resourceTypePointer)
+    {
+        LOGE("JNIThingsManagerLeaveGroupForResource: Failed to convert jstring to char string!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    std::string resourceType(resourceTypePointer);
+    JniOcResourceHandle *jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env,
+            jResourceHandle);
+
+    try
+    {
+        OCResourceHandle ocResourceHandle = jniOcResourceHandle->getOCResourceHandle();
+
+        ocResult = g_ThingsManager.leaveGroup(ocResource, resourceType, ocResourceHandle);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerLeaveGroupForResource: leaveGroup failed!");
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerLeaveGroupForResource: Exception occurred! %s, %d", e.reason().c_str(),
+             e.code());
+    }
+
+    env->ReleaseStringUTFChars(jResourceType, resourceTypePointer);
+    LOGI("JNIThingsManagerLeaveGroupForResource: Exit");
+    return ocResult;
+}
+
+JNIEXPORT void JNICALL JNIThingsManagerDeleteGroup(JNIEnv *env, jobject interfaceObject,
+        jstring jcollectionResourceType)
+{
+    LOGI("JNIThingsManagerDeleteGroup: Enter");
+
+    if (!jcollectionResourceType)
+    {
+        LOGE("JNIThingsManagerDeleteGroup: jcollectionResourceType is NULL!");
+        return;
+    }
+
+    const char *collectionResourceTypePointer = env->GetStringUTFChars(jcollectionResourceType, NULL);
+    if (NULL == collectionResourceTypePointer)
+    {
+        LOGE("JNIThingsManagerDeleteGroup: Failed to convert jstring to char string!");
+        return;
+    }
+
+    std::string collectionResourceType(collectionResourceTypePointer);
+    try
+    {
+        g_ThingsManager.deleteGroup(collectionResourceType);
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerDeleteGroup: Exception occurred! %s, %d", e.reason().c_str(),
+            e.code());
+    }
+
+    env->ReleaseStringUTFChars(jcollectionResourceType, collectionResourceTypePointer);
+    LOGI("JNIThingsManagerDeleteGroup: Exit");
+}
+
+JNIEXPORT jobject JNICALL JNIThingsManagerGetGroupList(JNIEnv *env, jobject interfaceObject)
+{
+    LOGI("JNIThingsManagerGetGroupList: Enter");
+
+    std::map< std::string, OCResourceHandle> groupListMap;
+    jobject jGroupListMap;
+
+    groupListMap = g_ThingsManager.getGroupList();
+    if (groupListMap.empty())
+    {
+        LOGD("getGroupList Map is empty");
+        return NULL;
+    }
+
+    jclass clazz = env->FindClass("java/util/HashMap");
+    jmethodID init = env->GetMethodID(clazz, "<init>", "()V");
+    jGroupListMap = env->NewObject(clazz, init);
+    jmethodID putMethod = env->GetMethodID(clazz, "put",
+                                           "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+
+    for (auto it = groupListMap.begin(); it != groupListMap.end(); ++it)
+    {
+        jstring key = (*env).NewStringUTF( (*it).first.c_str() );
+        JniOcResourceHandle *jniOcResourceHandle = new JniOcResourceHandle(((*it).second));
+        jobject value = ocResourceHandleToJava(env, reinterpret_cast<jlong>(jniOcResourceHandle));
+        env->CallObjectMethod(jGroupListMap, putMethod, key, value);
+    }
+
+    LOGI("JNIThingsManagerGetGroupList: Exit");
+    return jGroupListMap;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerUpdateConfigurations(JNIEnv *env, jobject interfaceObject,
+        jobject resource, jobject configurations)
+{
+    LOGI("JNIThingsManagerUpdateConfigurations: Enter");
+
+    if ((!resource) || (!configurations))
+    {
+        LOGE("JNIThingsManagerUpdateConfigurations: resource or configurations is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerUpdateConfigurations: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    std::map<std::string, std::string> configurationsMap;
+    configurationsMap = convertStringMap(env, configurations);
+    ocResult =  g_ThingsManager.updateConfigurations(ocResource, configurationsMap,
+                &ThingsManagerCallbacks::onUpdateConfigurationsResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerUpdateConfigurations: updateConfigurations failed!");
+        return ocResult;
+    }
+
+    LOGI("JNIThingsManagerUpdateConfigurations: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerGetConfigurations(JNIEnv *env, jobject interfaceObject,
+        jobject resource, jobject configurations)
+{
+    LOGI("JNIThingsManagerGetConfigurations: Enter");
+
+    if ((!resource) || (!configurations))
+    {
+        LOGE("JNIThingsManagerGetConfigurations: resource or configurations is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerGetConfigurations: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    ocResult = g_ThingsManager.getConfigurations(ocResource,
+               (convertStringVector(env, configurations)),
+               &ThingsManagerCallbacks::onGetConfigurationsResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerGetConfigurations: getConfigurations failed!");
+        return ocResult;
+    }
+
+    LOGI("JNIThingsManagerGetConfigurations: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jstring JNICALL JNIThingsManagerGetListOfSupportedConfigurationUnits(JNIEnv *env,
+        jobject interfaceObject)
+{
+    LOGI("JNIThingsManagerGetListOfSupportedConfigurationUnits: Enter");
+
+    std::string configListString = g_ThingsManager.getListOfSupportedConfigurationUnits();
+    jstring jConfigListString =  env->NewStringUTF(configListString.c_str());
+
+    LOGI("JNIThingsManagerGetListOfSupportedConfigurationUnits: Exit");
+    return jConfigListString;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerDoBootstrap(JNIEnv *env, jobject interfaceObject)
+{
+    LOGI("JNIThingsManagerDoBootstrap: Enter");
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+    try
+    {
+        ocResult  = g_ThingsManager.doBootstrap(&ThingsManagerCallbacks::onBootStrapResponse);
+        if (OC_STACK_OK != ocResult)
+        {
+            LOGE("JNIThingsManagerDoBootstrap: doBootstrap failed!");
+            return ocResult;
+        }
+    }
+    catch (InitializeException &e)
+    {
+        LOGE("JNIThingsManagerDoBootstrap: Exception occurred! %s, %d", e.reason().c_str(),
+            e.code());
+        return ocResult;
+    }
+
+    LOGI("JNIThingsManagerDoBootstrap: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerReboot(JNIEnv *env, jobject interfaceObject,
+        jobject resource)
+{
+    LOGI("JNIThingsManagerReboot: Enter");
+
+    if (!resource)
+    {
+        LOGE("JNIThingsManagerReboot: resource is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerReboot: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    ocResult = g_ThingsManager.reboot(ocResource, &ThingsManagerCallbacks::onRebootResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerReboot: reboot failed!");
+        return ocResult;
+    }
+
+    LOGI("JNIThingsManagerReboot: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerFactoryReset(JNIEnv *env, jobject interfaceObject,
+        jobject resource)
+{
+    LOGI("JNIThingsManagerFactoryReset: Enter");
+
+    if (!resource)
+    {
+        LOGE("JNIThingsManagerFactoryReset: resource is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerFactoryReset: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    ocResult = g_ThingsManager.factoryReset(ocResource,
+                                            &ThingsManagerCallbacks::onFactoryResetResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerFactoryReset: factoryReset failed!");
+        return ocResult;
+    }
+
+    LOGI("JNIThingsManagerFactoryReset: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerAddActionSet(JNIEnv *env, jobject interfaceObject,
+        jobject resource,
+        jobject newActionSet)
+{
+    LOGI("JNIThingsManagerAddActionSet: Entry");
+
+    if ((!resource) || (!newActionSet))
+    {
+        LOGE("JNIThingsManagerAddActionSet: resource or newActionSet is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManageraAdActionSet: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    JniActionSet *jActionSet = new JniActionSet(env, newActionSet);
+    ActionSet *pActionSet = jActionSet->getActionSet(env, newActionSet);
+    if (NULL == pActionSet)
+    {
+        LOGE("JNIThingsManageraAdActionSet: Failed to convert ActionSet!");
+        return ocResult;
+    }
+
+    ocResult = g_ThingsManager.addActionSet(ocResource, pActionSet,
+                                            &ThingsManagerCallbacks::onPutResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerAddActionSet: addActionSet is failed!");
+    }
+
+    delete pActionSet;
+    LOGI("JNIThingsManagerAddActionSet: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSet(JNIEnv *env, jobject interfaceObject,
+        jobject resource, jstring jActionSetName)
+{
+    LOGI("JNIThingsManagerExecuteActionSet: Entry");
+
+    if ((!resource) || (!jActionSetName))
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: resource or jActionSetName is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+    if (NULL == actionSetNamePointer)
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: Failed to convert jstring to char string!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    std::string actionSetName(actionSetNamePointer);
+
+    ocResult = g_ThingsManager.executeActionSet(ocResource, actionSetName,
+               &ThingsManagerCallbacks::onPostResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: executeActionSet is failed!");
+    }
+
+    env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+    LOGI("JNIThingsManagerExecuteActionSet: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerExecuteActionSetWithDelay(JNIEnv *env,
+        jobject interfaceObject,
+        jobject resource, jstring jActionSetName, jlong delay)
+{
+    LOGI("JNIThingsManagerExecuteActionSet: Entry");
+
+    if ((!resource) || (!jActionSetName))
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: resource or jActionSetName is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+    if (NULL == actionSetNamePointer)
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: Failed to convert jstring to char string!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    std::string actionSetName(actionSetNamePointer);
+    if (0 == delay)
+    {
+        ocResult = g_ThingsManager.executeActionSet(ocResource, actionSetName,
+                   &ThingsManagerCallbacks::onPostResponse);
+    }
+    else
+    {
+        ocResult = g_ThingsManager.executeActionSet(ocResource, actionSetName,
+                   (long int)delay,
+                   &ThingsManagerCallbacks::onPostResponse);
+    }
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerExecuteActionSet: executeActionSet is failed!");
+    }
+
+    env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+    LOGI("JNIThingsManagerExecuteActionSet: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerCancelActionSet(JNIEnv *env, jobject interfaceObject,
+        jobject resource, jstring jActionSetName)
+{
+    LOGI("JNIThingsManagerCancelActionSet: Entry");
+
+    if ((!resource) || (!jActionSetName))
+    {
+        LOGE("JNIThingsManagerCancelActionSet: resource or jActionSetName is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerCancelActionSet: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+    if (NULL == actionSetNamePointer)
+    {
+        LOGE("JNIThingsManagerCancelActionSet: Failed to get character sequence from jstring!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    std::string actionSetName(actionSetNamePointer);
+
+    ocResult = g_ThingsManager.cancelActionSet(ocResource, actionSetName,
+               &ThingsManagerCallbacks::onPostResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerCancelActionSet: cancelActionSet is failed!");
+    }
+
+    env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+    LOGI("JNIThingsManagerCancelActionSet: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerGetActionSet(JNIEnv *env, jobject interfaceObject,
+        jobject resource,
+        jstring jActionSetName)
+{
+    LOGI("JNIThingsManagerGetActionSet: Entry");
+
+    if ((!resource) || (!jActionSetName))
+    {
+        LOGE("JNIThingsManagerGetActionSet: resource or jActionSetName is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerGetActionSet: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+    std::string actionSetName(actionSetNamePointer);
+
+    ocResult = g_ThingsManager.getActionSet(ocResource, actionSetName,
+                                            &ThingsManagerCallbacks::onGetResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerGetActionSet: getActionSet is failed!");
+    }
+
+    env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+    LOGI("JNIThingsManagerGetActionSet: Exit");
+    return ocResult;
+}
+
+JNIEXPORT jint JNICALL JNIThingsManagerDeleteActionSet(JNIEnv *env, jobject interfaceObject,
+        jobject resource,
+        jstring jActionSetName)
+{
+    LOGI("JNIThingsManagerDeleteActionSet: Entry");
+
+    if ((!resource) || (!jActionSetName))
+    {
+        LOGE("JNIThingsManagerDeleteActionSet: resource or jActionSetName is NULL!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCStackResult ocResult = OC_STACK_ERROR;
+
+    std::shared_ptr<OCResource> ocResource;
+    JniOcResource *jniOcResource = JniOcResource::getJniOcResourcePtr(env, resource);
+    if (jniOcResource)
+    {
+        ocResource = jniOcResource->getOCResource();
+    }
+
+    if (NULL == ocResource.get())
+    {
+        LOGE("JNIThingsManagerDeleteActionSet: Failed to get OCResource object!");
+        return ocResult;
+    }
+
+    const char *actionSetNamePointer = env->GetStringUTFChars(jActionSetName, 0);
+    std::string actionSetName(actionSetNamePointer);
+
+    ocResult = g_ThingsManager.deleteActionSet(ocResource, actionSetName,
+               &ThingsManagerCallbacks::onPutResponse);
+    if (OC_STACK_OK != ocResult)
+    {
+        LOGE("JNIThingsManagerDeleteActionSet: deleteActionSet is failed!");
+    }
+
+    env->ReleaseStringUTFChars(jActionSetName, actionSetNamePointer);
+    LOGI("JNIThingsManagerDeleteActionSet: Exit");
+    return ocResult;
+}
+
+jobject ocResourceHandleToJava(JNIEnv *env, jlong resourceHandle)
+{
+    jclass resourceClass = GetJClass(TM_SERVICE_OCRESOURCEHANDLE_PATH);
+    if (NULL == resourceClass)
+    {
+        LOGE("ocResourceHandleToJava : failed to find OCResourceHandle java class!");
+        return NULL;
+    }
+
+    jmethodID constructor = env->GetMethodID(resourceClass, "<init>", "(J)V");
+    if (NULL == constructor)
+    {
+        LOGE("ocResourceHandleToJava: Failed to get constructor method!");
+        return NULL;
+    }
+
+    jobject resourceObj = (jobject) env->NewObject(resourceClass, constructor, resourceHandle);
+    if (NULL == resourceObj)
+    {
+        LOGE("ocResourceHandleToJava: Failed to create OCResouceHandle java object!");
+        return NULL;
+    }
+
+    return resourceObj;
+}
diff --git a/service/things-manager/sdk/java/jni/tm/src/jni_things_manager_callbacks.cpp b/service/things-manager/sdk/java/jni/tm/src/jni_things_manager_callbacks.cpp
new file mode 100644 (file)
index 0000000..b24b2eb
--- /dev/null
@@ -0,0 +1,594 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_things_manager_callbacks.h"
+#include "JniOcResource.h"
+#include "ThingsManager.h"
+#include "jni_things_manager_jvm.h"
+#include "jni_string.h"
+
+#define LOG_TAG "ThingsManagerCallbacks"
+
+#define METHOD_ONRESOURCE_CALLBACK    "(" TM_JAVA_VECTOR_TYPE")V"
+#define METHOD_ONGROUP_FIND_CALLBACK    "(" TM_SERVICE_OCRESOURCE_TYPE")V"
+#define METHOD_ONPRESENCE_CALLBACK    "(" TM_JAVA_STRING_TYPE"I)V"
+#define METHOD_ONUPDATE_CONF_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONGET_CONF_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONBOOT_STRAP_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONFACTORY_RESET_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONREBOOT_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONPOST_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONPUT_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_ONGET_CALLBACK    "(" TM_JAVA_VECTOR_TYPE TM_SERVICE_OCREPRESENTATION_TYPE"I)V"
+#define METHOD_TMCALLBACK_GETINSTANCE    "()" TM_SERVICE_CALLBACK_CLASS_TYPE
+
+jobject OcResourceToJava(JNIEnv *env, jlong resource)
+{
+    jclass resourceClass = GetJClass(TM_SERVICE_OCRESOURCE_PATH);
+    if (NULL == resourceClass)
+    {
+        LOGE("OcResourceToJava : failed to find OCResouce java class!");
+        return NULL;
+    }
+
+    jmethodID constructor = env->GetMethodID(resourceClass, "<init>", "(J)V");
+    if (NULL == constructor)
+    {
+        LOGE("OcResourceToJava: Failed to get constructor method!");
+        return NULL;
+    }
+
+    jobject resourceObj = (jobject) env->NewObject(resourceClass, constructor, resource);
+    if (NULL == resourceObj)
+    {
+        LOGE("OcResourceToJava: Failed to create OCResouce java object!");
+        return NULL;
+    }
+
+    return resourceObj;
+}
+
+jobject OcHeaderOptionToJava(JNIEnv *env, OC::HeaderOption::OCHeaderOption headerOption)
+{
+    JString *optionData = new JString(env, headerOption.getOptionData());
+    if (!optionData)
+    {
+        LOGE("OcHeaderOptionToJava : failed to get JString!");
+        return NULL;
+    }
+
+    jclass headerOptionClass = GetJClass(TM_SERVICE_HEADER_OPTION_PATH);
+    if (NULL == headerOptionClass)
+    {
+        LOGE("OcHeaderOptionToJava : failed to find OCRepresentation java class!");
+        return NULL;
+    }
+
+    jmethodID constructor = env->GetMethodID(headerOptionClass, "<init>", "(JLjava/lang/String;)V");
+    if (NULL == constructor)
+    {
+        LOGE("OcHeaderOptionToJava: Failed to get constructor method!");
+        return NULL;
+    }
+
+    jobject headerOptionObj = (jobject) env->NewObject(headerOptionClass, constructor,
+                              (jlong)headerOption.getOptionID(), optionData);
+    if (NULL == headerOptionObj)
+    {
+        LOGE("OcHeaderOptionToJava: Failed to create OCRepresentation java object!");
+        return NULL;
+    }
+
+    return headerOptionObj;
+}
+
+jobject OcRepresentationToJava(JNIEnv *env, jlong ocRepresentation)
+{
+    jclass ocRepresentationClass = GetJClass(TM_SERVICE_OCREPRESENTATION_PATH);
+    if (NULL == ocRepresentationClass)
+    {
+        LOGE("OcRepresentationToJava : failed to find OCRepresentation java class!");
+        return NULL;
+    }
+
+    jmethodID constructor = env->GetMethodID(ocRepresentationClass, "<init>", "(J)V");
+    if (NULL == constructor)
+    {
+        LOGE("OcRepresentationToJava: Failed to get constructor method!");
+        return NULL;
+    }
+
+    jobject ocRepresentationObj = (jobject) env->NewObject(ocRepresentationClass, constructor,
+                                  ocRepresentation);
+    if (NULL == ocRepresentationObj)
+    {
+        LOGE("OcRepresentationToJava: Failed to create OCRepresentation java object!");
+        return NULL;
+    }
+
+    return ocRepresentationObj;
+}
+
+void ThingsManagerCallbacks::onFoundCandidateResource(
+    std::vector< std::shared_ptr<OC::OCResource>> resources)
+{
+    LOGI("findCandidateResource : Enter");
+
+    if (resources.size() == 0)
+    {
+        LOGE("findCandidateResource : found resources zero");
+        return;
+    }
+
+    JNIEnv *env = ThingsManagerJVM::getEnv();
+    if (env == NULL)
+    {
+        LOGE("findCandidateResource : Getting JNIEnv failed");
+        return;
+    }
+
+    // Get ThingsManagerCallback class reference
+    jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+    if (NULL == thingsManagerCallbacks)
+    {
+        LOGE("findCandidateResource : GetJClass TMServiceCallbackInterface failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Get the ThingsManagerCallback class instance
+    jobject jobjectCallback = GetJObjectInstance(TM_SERVICE_CALLBACK_CLASS_PATH);
+    if (NULL == jobjectCallback)
+    {
+        LOGE("getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Get onResourceCallback method reference
+    jmethodID method_id = env->GetMethodID(thingsManagerCallbacks,
+                                           "onResourceCallback", METHOD_ONRESOURCE_CALLBACK);
+    if (NULL == method_id)
+    {
+        LOGE("findCandidateResource: onResourceCallback : GetMethodID failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("findCandidateResource : ExceptionCheck failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jclass vectorCls = env->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+    if (!vectorCls)
+    {
+        LOGE("findCandidateResource: failed to get %s class reference", TM_JAVA_VECTOR_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jmethodID constr = env->GetMethodID(vectorCls, "<init>", "()V");
+    if (!constr)
+    {
+        LOGE("findCandidateResource: failed to get %s constructor", TM_JAVA_VECTOR_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jobject vectorObj = env->NewObject(vectorCls, constr);
+    if (!vectorObj)
+    {
+        LOGE("findCandidateResource: failed to create a %s object", TM_JAVA_VECTOR_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jmethodID addElement = env->GetMethodID(vectorCls, "addElement", "(Ljava/lang/Object;)V");
+    if (NULL == addElement)
+    {
+        LOGE("findCandidateResource: failed to create a addElement method");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Convert to java OCResource object
+    for (int i = 0; i < resources.size(); i++)
+    {
+        JniOcResource *jniOcResource = new JniOcResource(resources[i]);
+        if (!jniOcResource)
+        {
+            LOGE("findCandidateResource: failed to create a JniOcResource");
+            ThingsManagerJVM::releaseEnv();
+            return;
+        }
+
+        jobject resource = OcResourceToJava(env, reinterpret_cast<jlong>(jniOcResource));
+        env->CallVoidMethod(vectorObj, addElement, resource);
+    }
+
+    env->CallVoidMethod(jobjectCallback, method_id, vectorObj);
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("findCandidateResource : CallVoidMethod failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    ThingsManagerJVM::releaseEnv();
+    LOGI("findCandidateResource : Exit");
+}
+
+void ThingsManagerCallbacks::onFoundGroup(std::shared_ptr<OC::OCResource> groupResource)
+{
+    LOGI("FindGroup : Enter");
+
+    if (NULL == groupResource.get())
+    {
+        LOGE("FindGroup : Invalid received GroupResource!");
+        return;
+    }
+
+    JNIEnv *env = ThingsManagerJVM::getEnv();
+    if (env == NULL)
+    {
+        LOGE("FindGroup : Getting JNIEnv failed");
+        return;
+    }
+
+    // Get ThingsManagerCallback class reference
+    jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+    if (NULL == thingsManagerCallbacks)
+    {
+        LOGE("FindGroup : GetJClass TMServiceCallbackInterface failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Get the ThingsManagerCallback class instance
+    jobject jobjectCallback = GetJObjectInstance(TM_SERVICE_CALLBACK_CLASS_PATH);
+    if (NULL == jobjectCallback)
+    {
+        LOGE("FindGroup: getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Get onGroupFindCallback method reference
+    jmethodID method_id = env->GetMethodID(thingsManagerCallbacks,
+                                           "onGroupFindCallback",
+                                           METHOD_ONGROUP_FIND_CALLBACK);
+    if (NULL == method_id)
+    {
+        LOGE("FindGroup : GetMethodID failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("FindGroup : ExceptionCheck failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    JniOcResource *jniOcResource = new JniOcResource(groupResource);
+    if (!jniOcResource)
+    {
+        LOGE("FindGroup : groupResource is invalid!");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jobject resource = OcResourceToJava(env, reinterpret_cast<jlong>(jniOcResource));
+
+    env->CallVoidMethod(jobjectCallback, method_id, resource);
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("FindGroup : CallVoidMethod failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    ThingsManagerJVM::releaseEnv();
+    LOGI("FindGroup : Exit");
+}
+
+void ThingsManagerCallbacks::onSubscribePresence(std::string resource, OCStackResult result)
+{
+    LOGI("SubscribePresence : Entry");
+
+    JNIEnv *env = ThingsManagerJVM::getEnv();
+    if (env == NULL)
+    {
+        LOGE("SubscribePresence : Getting JNIEnv failed");
+        return;
+    }
+
+    // Get ThingsManagerCallback class reference
+    jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+    if (NULL == thingsManagerCallbacks)
+    {
+        LOGE("findCandidateResource : GetJClass TMServiceCallbackInterface failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Get getInstance method reference
+    jmethodID getinstance_method_id = env->GetStaticMethodID(thingsManagerCallbacks,
+                                      "getInstance", METHOD_TMCALLBACK_GETINSTANCE);
+    if (NULL == getinstance_method_id)
+    {
+        LOGE("getInstance : GetMethodID failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Get the ThingsManagerCallback class instance
+    jobject jobjectCallback = env->CallStaticObjectMethod(thingsManagerCallbacks,
+                              getinstance_method_id);
+    if (NULL == jobjectCallback)
+    {
+        LOGE("getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jmethodID method_id = env->GetMethodID(thingsManagerCallbacks,
+                                           "onPresenceCallback",
+                                           METHOD_ONPRESENCE_CALLBACK);
+    if (NULL == method_id)
+    {
+        LOGE("SubscribePresence : GetMethodID failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("SubscribePresence : ExceptionCheck failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    JString *jresource = new JString(env, resource);
+    if (jresource == NULL)
+    {
+        LOGE("resource value is invalid");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    env->CallVoidMethod(jobjectCallback, method_id, jresource->getObject(), (jint)result);
+
+    delete jresource;
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("SubscribePresence : CallVoidMethod failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    LOGI("SubscribePresence : Exit");
+
+//METHOD_FAILURE:
+    ThingsManagerJVM::releaseEnv();
+}
+
+void ThingsManagerCallbacks::onUpdateConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("UpdateConfigurations : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onUpdateConfigurationsCallback",
+                                           METHOD_ONUPDATE_CONF_CALLBACK);
+
+    LOGI("UpdateConfigurations : Exit");
+}
+
+void ThingsManagerCallbacks::onGetConfigurationsResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("GetConfigurations : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onGetConfigurationsCallback",
+                                           METHOD_ONGET_CONF_CALLBACK);
+
+    LOGI("GetConfigurations : Exit");
+}
+
+void ThingsManagerCallbacks::onBootStrapResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("BootStrap : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onBootStrapCallback",
+                                           METHOD_ONBOOT_STRAP_CALLBACK);
+
+    LOGI("BootStrap : Exit");
+}
+
+void ThingsManagerCallbacks::onRebootResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("OnReboot : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onRebootCallback",
+                                           METHOD_ONREBOOT_CALLBACK);
+
+    LOGI("OnReboot : Exit");
+}
+
+void ThingsManagerCallbacks::onFactoryResetResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("OnFactoryReset : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onFactoryResetCallback",
+                                           METHOD_ONFACTORY_RESET_CALLBACK);
+
+    LOGI("OnFactoryReset : Exit");
+}
+
+void ThingsManagerCallbacks::onPostResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("PostResponse : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onPostResponseCallback",
+                                           METHOD_ONPOST_CALLBACK);
+
+    LOGI("PostResponse : Exit");
+}
+
+void ThingsManagerCallbacks::onPutResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("OnPutResponse : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onPutResponseCallback",
+                                           METHOD_ONPUT_CALLBACK);
+
+    LOGI("OnPutResponse : Exit");
+}
+
+
+void ThingsManagerCallbacks::onGetResponse(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode)
+{
+    LOGI("OnGetResponse : Enter");
+
+    ThingsManagerCallbacks::invokeCallback(headerOptions, rep, eCode, "onGetResponseCallback",
+                                           METHOD_ONGET_CALLBACK);
+
+    LOGI("OnGetResponse : Exit");
+}
+
+void ThingsManagerCallbacks::invokeCallback(const OC::HeaderOptions &headerOptions,
+        const OC::OCRepresentation &rep, const int eCode, const char  *callbackName,
+        const char *signature)
+{
+    LOGI("InvokeCallback : Enter %s", callbackName);
+
+    JNIEnv *env = ThingsManagerJVM::getEnv();
+    if (env == NULL)
+    {
+        LOGE("InvokeCallback : Getting JNIEnv failed");
+        return;
+    }
+
+    // Get ThingsManagerCallback class reference
+    jclass thingsManagerCallbacks = GetJClass(TM_SERVICE_CALLBACK_CLASS_PATH);
+    if (NULL == thingsManagerCallbacks)
+    {
+        LOGE("InvokeCallback : GetJClass TMServiceCallbackInterface failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Get the ThingsManagerCallback class instance
+    jobject jobjectCallback = GetJObjectInstance(TM_SERVICE_CALLBACK_CLASS_PATH);
+    if (NULL == jobjectCallback)
+    {
+        LOGE("InvokeCallback: getInstance( %s) failed!", TM_SERVICE_CALLBACK_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jmethodID method_id = env->GetMethodID(thingsManagerCallbacks, callbackName, signature);
+    if (!method_id)
+    {
+        LOGE("InvokeCallback : GetMethodID failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("InvokeCallback : ExceptionCheck failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    // Convert vector<OC:HeaderOption::OCHeaderOption> to java type
+    jclass vectorCls = env->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+    if (!vectorCls)
+    {
+        LOGE("InvokeCallback: failed to get %s class reference", TM_JAVA_VECTOR_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jmethodID constr = env->GetMethodID(vectorCls, "<init>", "()V");
+    if (!constr)
+    {
+        LOGE("InvokeCallback: failed to get %s constructor", TM_JAVA_VECTOR_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jobject vectorObj = env->NewObject(vectorCls, constr);
+    if (!vectorObj)
+    {
+        LOGE("InvokeCallback: failed to create a %s object", TM_JAVA_VECTOR_CLASS_PATH);
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jmethodID addElement = env->GetMethodID(vectorCls, "addElement", "(Ljava/lang/Object;)V");
+    if (NULL == addElement)
+    {
+        LOGE("InvokeCallback: failed to create a addElement method");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    jobject headerOptionTemp;
+    for (int i = 0; i < headerOptions.size(); i++)
+    {
+        headerOptionTemp = OcHeaderOptionToJava(env, headerOptions[i]);
+        env->CallVoidMethod(vectorObj, addElement, headerOptionTemp);
+    }
+
+    // Convert OCRepresentation to java type
+    jobject jrepresentation = OcRepresentationToJava(env, (jlong) reinterpret_cast<jlong>(&rep));
+    if (!jrepresentation)
+    {
+        LOGE("InvokeCallback : cannot create OCRepresentation class");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    env->CallVoidMethod(jobjectCallback, method_id, vectorObj, jrepresentation, (jint)eCode);
+
+    if ((env)->ExceptionCheck())
+    {
+        LOGE("InvokeCallback : CallVoidMethod failed");
+        ThingsManagerJVM::releaseEnv();
+        return;
+    }
+
+    ThingsManagerJVM::releaseEnv();
+    LOGI("InvokeCallback : Exit %s", callbackName);
+}
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/jni/tm/src/jni_things_manager_util.cpp b/service/things-manager/sdk/java/jni/tm/src/jni_things_manager_util.cpp
new file mode 100644 (file)
index 0000000..5adb8c6
--- /dev/null
@@ -0,0 +1,131 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "jni_things_manager_util.h"
+#include "JniOcResource.h"
+
+std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString)
+{
+    std::vector<std::string> vectorString;
+
+    jclass vectorClass = env->FindClass(TM_JAVA_VECTOR_CLASS_PATH);
+    if (!vectorClass)
+    {
+        LOGE("convertStringVector: Not able to find class %s", TM_JAVA_VECTOR_CLASS_PATH);
+        return vectorString;
+    }
+
+    jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
+    if (NULL == size)
+    {
+        LOGE("convertStringVector: Failed to get method id for size");
+        return vectorString;
+    }
+
+    jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
+    if (NULL == get)
+    {
+        LOGE("convertStringVector: Failed to get method id for get");
+        return vectorString;
+    }
+
+    jint jSize = env->CallIntMethod(jVectorString, size);
+    int sizeOfVector = jSize;
+
+    for (int index = 0; index < sizeOfVector; index++)
+    {
+        jint jIndex = index;
+        jstring jContactInfoObj = (jstring)env->CallObjectMethod(jVectorString, get, jIndex);
+        if (jContactInfoObj == NULL)
+        {
+            LOGE("convertStringVector: Failed on CallObjectMethod");
+            return vectorString;
+        }
+        const char *buff = env->GetStringUTFChars(jContactInfoObj, 0);
+        if (NULL != buff)
+        {
+            std::string tempString = buff;
+            vectorString.push_back(tempString);
+        }
+
+        env->ReleaseStringUTFChars(jContactInfoObj, buff);
+    }
+
+    return vectorString;
+}
+
+std::map<std::string, std::string> convertStringMap(JNIEnv *env, jobject jMapString)
+{
+    // Get reference to java/util/Map class
+    jclass mapClass = env->GetObjectClass(jMapString);
+    jmethodID sizeMethodId = env->GetMethodID(mapClass, "size", "()I");
+    jmethodID entrySetMethodId = env->GetMethodID(mapClass, "entrySet", "()Ljava/util/Set;");
+
+    // Get reference to java/util/Set class
+    jclass setClass = env->FindClass("java/util/Set");
+    jmethodID iteratorMethodId = env->GetMethodID(setClass, "iterator", "()Ljava/util/Iterator;");
+
+    // Get reference to java/util/Iterator class
+    jclass iteratorClass = env->FindClass("java/util/Iterator");
+    jmethodID hasNextMethodId = env->GetMethodID(iteratorClass, "hasNext", "()Z");
+    jmethodID nextMethodId = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
+
+    // Get reference to java/util/Map/Entry class
+    jclass mapEntryClass = env->FindClass("java/util/Map$Entry");
+    jmethodID getKeyMethodId = env->GetMethodID(mapEntryClass, "getKey", "()Ljava/lang/Object;");
+    jmethodID getValueMethodId = env->GetMethodID(mapEntryClass, "getValue", "()Ljava/lang/Object;");
+
+    std::map<std::string, std::string> mapString;
+    // Get entry set from map
+    jobject entrySet = env->CallObjectMethod(jMapString, entrySetMethodId);
+    if (!entrySet)
+    {
+        LOGE("convertStringMap: Failed to get entrySet");
+        return mapString;
+    }
+
+    // Get iterator from set
+    jobject iterator = env->CallObjectMethod(entrySet, iteratorMethodId);
+    if (!iterator)
+    {
+        LOGE("convertStringMap: Failed to get iterator from set");
+        return mapString;
+    }
+
+    if (JNI_TRUE == env->CallBooleanMethod(iterator, hasNextMethodId))
+    {
+        jobject entry = env->CallObjectMethod(iterator, nextMethodId);
+        jstring jMapKeyStr = (jstring)env->CallObjectMethod(entry, getKeyMethodId);
+        jstring jMapValueStr = (jstring)env->CallObjectMethod(entry, getValueMethodId);
+
+        const char *key = env->GetStringUTFChars(jMapKeyStr, 0);
+        const char *value = env->GetStringUTFChars(jMapValueStr, 0);
+
+        if ((NULL != key) && (NULL != value))
+        {
+            std::string keyStr = key;
+            std::string valueStr = value;
+            mapString.insert(std::make_pair(keyStr, valueStr));
+        }
+        env->ReleaseStringUTFChars(jMapKeyStr, key);
+        env->ReleaseStringUTFChars(jMapValueStr, value);
+    }
+
+    return mapString;
+}
diff --git a/service/things-manager/sdk/java/project.properties b/service/things-manager/sdk/java/project.properties
new file mode 100644 (file)
index 0000000..7e2ca64
--- /dev/null
@@ -0,0 +1,15 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-20
+android.library=true
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/Action.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/Action.java
new file mode 100644 (file)
index 0000000..15cf5c1
--- /dev/null
@@ -0,0 +1,118 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   Action.java
+ *
+ * @brief  This file contains class which provides functions to retrieve the Action details from a
+ *            Segment.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import android.util.Log;
+
+/**
+ * This class provides functions to retrieve the Action details from a
+ *  Segment.
+ *
+ */
+public class Action {
+    private static final String LOG_TAG          = "Action";
+    /**
+     * Sub Segment Value
+     */
+    public String               target;
+
+    /**
+     * Capability instance stored in listOfCapability vector variable.
+     */
+    public Vector<Capability>   listOfCapability = new Vector<Capability>();
+
+    /**
+     * This function generates an Action String (Example:
+     * uri=coap://10.251.44.228:49858/a/light|power=10)
+     *
+     * @return String for a specific action.
+     *
+     */
+    public String toString() {
+        StringBuilder result = new StringBuilder();
+
+        result.append("uri=" + target + "|");
+        for (int i = 0; i < listOfCapability.size(); i++) {
+            if (i != 0)
+                result.append('|');
+            result.append(listOfCapability.elementAt(i).toString());
+        }
+
+        return result.toString();
+    }
+
+    /**
+     * This function parses the Segment value to retrieve sub segments separated
+     * by a vertical bar(|): URI and a pair of attribute key and value
+     *
+     * @param actionString
+     *            Segment String
+     *
+     * @return Action needed by remote devices as members of a specific group
+     *
+     */
+    public static Action toAction(String actionString) {
+        Action result = new Action();
+        StringTokenizer tokenizer = new StringTokenizer(actionString, "|");
+
+        boolean actionFlag = false;
+        while (tokenizer.hasMoreTokens()) {
+            String segment = tokenizer.nextToken();
+            if (false == actionFlag) {
+                // Parse the action string
+                StringTokenizer targetTokenizer = new StringTokenizer(segment,
+                        "=");
+                if (2 != targetTokenizer.countTokens()
+                        || false == targetTokenizer.nextToken()
+                                .equalsIgnoreCase("uri")) {
+                    Log.e(LOG_TAG, "Invalid action segment = " + segment);
+                    return null;
+                }
+
+                result.target = targetTokenizer.nextToken();
+                actionFlag = true;
+            } else {
+                // Parse the capability string
+                Capability capability = Capability.toCapability(segment);
+                if (null == capability) {
+                    Log.e(LOG_TAG,
+                            "Failed to convert string to Capability class!");
+                    return null;
+                }
+
+                // Add the parsed capability to list
+                result.listOfCapability.add(capability);
+            }
+        }
+
+        return result;
+    }
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/ActionSet.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/ActionSet.java
new file mode 100644 (file)
index 0000000..c234210
--- /dev/null
@@ -0,0 +1,147 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file   ActionSet.java
+ *
+ * @brief  This file contains class which provides functions to retrieve ActionSet from plain text.
+ *
+ */
+package org.iotivity.service.tm;
+
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import android.util.Log;
+
+/**
+ * This class provides functions to retrieve ActionSet from plain text.
+ * An ActionSet is a set of descriptions of actions needed by remote
+ * devices as members of a specific group. To create an ActionSet, one
+ * needs to know the Delimeter serialization.
+ *
+ */
+public class ActionSet extends Time {
+    /**
+     * String Tag for Logging
+     */
+    private static final String LOG_TAG      = "ActionSet";
+    /**
+     * A first segment before the first asterisk(*) in ActionSet string is an
+     * actionset name
+     */
+    public String               actionsetName;
+    /**
+     * Action instance stored in listOfAction vector variable.
+     */
+    public Vector<Action>       listOfAction = new Vector<Action>();
+
+    /**
+     * This function generates an ActionSet String which contains ActionSet
+     * name, delay in seconds, ActionSetType which can be 0(NONE), 1(SCHEDULED)
+     * or 2(RECURSIVE) and a list of actions. (Example: movieTime*10
+     * 1*uri=coap://10.251.44.228:49858/a/light|power=
+     * OFF*uri=coap://10.251.44.228:49858). The first segment before the first
+     * asterisk(*) is an ActionSet name. The second segment goes before the next
+     * asterisk. In the above example, 10 is the second segment which signifies
+     * time delay in seconds followed by a space and ActionSetType which
+     * signifies whether an ActionSet has to be triggered Recursively(2) or
+     * Scheduled manner(1) or immediately(0).
+     * "uri=coap://10.251.44.228:49858/a/light|power=10" is the third segment.
+     * This can be also divided into two sub segments by a vertical bar(|): URI
+     * and a pair of attribute key and value.
+     *
+     * @return String for a specific action.
+     *
+     */
+    @Override
+    public String toString() {
+        StringBuilder result = new StringBuilder();
+
+        // Append action name
+        result.append(actionsetName + "*");
+
+        // Append delay and type
+        result.append(getDelay() + " " + getType().ordinal() + "*");
+
+        // Append list of actions
+        for (int i = 0; i < listOfAction.size(); i++) {
+            if (i != 0)
+                result.append('*');
+            result.append(listOfAction.elementAt(i).toString());
+        }
+
+        return result.toString();
+    }
+
+    /**
+     * This function extracts a list of Actions from plain text and constructs
+     * an ActionSet.
+     *
+     * @param actionsetString
+     *            ActionSet in String format. (Example: movieTime*10
+     *            1*uri=coap://10.251.44.228:49858/a/light|power=
+     *            OFF*uri=coap://10.251.44.228:49858). The first segment before
+     *            the first asterisk(*) is an ActionSet name. The second segment
+     *            goes before the next asterisk. In the above example, 10 is the
+     *            second segment which signifies time delay in seconds followed
+     *            by a space and ActionSetType which signifies whether an
+     *            ActionSet has to be triggered Recursively(2) or Scheduled
+     *            manner(1) or immediately(0).
+     *            "uri=coap://10.251.44.228:49858/a/light|power=10" is the third
+     *            segment. This can be also divided into two sub segments by a
+     *            vertical bar(|): URI and a pair of attribute key and value).
+     *
+     * @return ActionSet which is a set of descriptions of actions needed by
+     *         remote devices as members of a specific group.
+     *
+     */
+    public static ActionSet toActionSet(String actionsetString) {
+        if (0 == actionsetString.length()) {
+            return null;
+        }
+
+        ActionSet result = new ActionSet();
+        StringTokenizer tokenizer = new StringTokenizer(actionsetString, "*");
+        boolean actionNameFlag = false;
+        while (tokenizer.hasMoreTokens()) {
+            String segment = tokenizer.nextToken();
+            if (false == actionNameFlag) {
+                if (true == segment.contains("|")
+                        || true == segment.contains("=")) {
+                    Log.e(LOG_TAG, "Invalid actionset name string!");
+                    return null;
+                }
+
+                result.actionsetName = segment;
+                actionNameFlag = true;
+            } else {
+                Action action = Action.toAction(segment);
+                if (null == action) {
+                    Log.e(LOG_TAG, "Failed to convert string to Action class!");
+                    return null;
+                }
+
+                result.listOfAction.add(action);
+            }
+        }
+
+        return result;
+    }
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/Capability.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/Capability.java
new file mode 100644 (file)
index 0000000..850fee9
--- /dev/null
@@ -0,0 +1,90 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    Capability.java
+ *
+ * @brief   This file contains class which provides functions  to specify an attribute key and value
+ *                of the target resource
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.StringTokenizer;
+
+import android.util.Log;
+
+/**
+ * This class needs to be created to specify an attribute key and value
+ * of the target resource. The attribute key and value are written in
+ * capability and status variables of Capability instance class,
+ * respectively. After filling the Capability instance, store it to
+ * listOfCapability vector variable of Action instance.
+ *
+ */
+public class Capability {
+    /**
+     * String Tag for Logging
+     */
+    private static final String LOG_TAG = "Capability";
+    /**
+     * Attribute Key of target resource
+     */
+    public String               capability;
+    /**
+     * Attribute Value of target resource
+     */
+    public String               status;
+
+    /**
+     * This function generates a Capability String.
+     *
+     * @return String for a specific Capability.
+     *
+     */
+    public String toString() {
+        StringBuilder result = new StringBuilder();
+        result.append(capability + "=" + status);
+        return result.toString();
+    }
+
+    /**
+     * This function parses the Capability String.
+     *
+     * @param capabilityString
+     *            Capability in String format.
+     *
+     * @return Capability class.
+     *
+     */
+    public static Capability toCapability(String capabilityString) {
+        StringTokenizer tokenizer = new StringTokenizer(capabilityString, "=");
+        if (2 != tokenizer.countTokens()) {
+            Log.e(LOG_TAG, "Invalid capability string = " + capabilityString);
+            return null;
+        }
+
+        Capability result = new Capability();
+
+        result.capability = tokenizer.nextToken();
+        result.status = tokenizer.nextToken();
+        return result;
+    }
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/IActionListener.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/IActionListener.java
new file mode 100644 (file)
index 0000000..974dfee
--- /dev/null
@@ -0,0 +1,88 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   IActionListener.java
+ *
+ * @brief  This file provides interface for receiving the callback for the GET, PUT and POST requested
+ *        actions.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * Provides interface for receiving the callback for the GET, PUT and
+ * POST requested actions.
+ */
+public interface IActionListener {
+    /**
+     * This callback method is called when a asynchronous response for the getActionSet
+     * request is received.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onGetResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue);
+
+    /**
+     * This callback method is called when a asynchronous response for the addActionSet
+     * request is received.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onPutResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue);
+
+    /**
+     * This callback method is called when a asynchronous response for the executeActionSet
+     * or deleteActionSet request is received.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onPostResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue);
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/IConfigurationListener.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/IConfigurationListener.java
new file mode 100644 (file)
index 0000000..49d91dc
--- /dev/null
@@ -0,0 +1,60 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   IConfigurationListener.java
+ *
+ * @brief  This file provides interface for receiving asynchronous response for
+ *        configuration APIs.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * Provides interface for receiving asynchronous response for
+ * configuration APIs.
+ */
+public interface IConfigurationListener {
+    /**
+     * Asynchronous response callback for ThingsManager::doBootstrap API.
+     */
+    public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue);
+
+    /**
+     * Asynchronous response callback for ThingsManager::updateConfigurations
+     * API.
+     */
+    public void onUpdateConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue);
+
+    /**
+     * Asynchronous response callback for ThingsManager::getConfigurations API.
+     */
+    public void onGetConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue);
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/IDiagnosticsListener.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/IDiagnosticsListener.java
new file mode 100644 (file)
index 0000000..499b111
--- /dev/null
@@ -0,0 +1,51 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   IDiagnosticsListener.java
+ *
+ * @brief  This file provides interface for receiving asynchronous response for
+ *        diagnostic feature APIs.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * Provides interface for receiving asynchronous response for diagnostic
+ * feature APIs.
+ */
+public interface IDiagnosticsListener {
+    /**
+     * Asynchronous response callback for ThingsManager::reboot API.
+     */
+    public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue);
+
+    /**
+     * Asynchronous response callback for ThingsManager::factoryReset API.
+     */
+    public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue);
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/IFindCandidateResourceListener.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/IFindCandidateResourceListener.java
new file mode 100644 (file)
index 0000000..74472b6
--- /dev/null
@@ -0,0 +1,46 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    IFindCandidateResourceListener.java
+ *
+ * @brief   This file provides interface for getting notification when resources are
+ *        discovered in network.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcResource;
+
+/**
+ * Provides interface for getting notification when resources are
+ * discovered in network.
+ */
+public interface IFindCandidateResourceListener {
+    /**
+     * This callback method will be called whenever resource is discovered in
+     * the network.
+     *
+     * @param resources
+     *            List of resources discovered in the network
+     */
+    public void onResourceCallback(Vector<OcResource> resources);
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/IFindGroupListener.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/IFindGroupListener.java
new file mode 100644 (file)
index 0000000..232cf57
--- /dev/null
@@ -0,0 +1,43 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    IFindGroupListener.java
+ *
+ * @brief   This file provides interface for getting group discovery status.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import org.iotivity.base.OcResource;
+
+/**
+ * Provides interface for getting group discovery status.
+ */
+public interface IFindGroupListener {
+    /**
+     * This callback method will be called to notify whether group is found or
+     * not.
+     *
+     * @param resource
+     *            URI of resource.
+     */
+    public void onGroupFindCallback(OcResource resource);
+}
\ No newline at end of file
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/ISubscribePresenceListener.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/ISubscribePresenceListener.java
new file mode 100644 (file)
index 0000000..a1e2541
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    ISubscribePresenceListener.java
+ *
+ * @brief   This file provides interface for getting child resource presence status.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+/**
+ * Provides interface for getting child resource presence status.
+ */
+public interface ISubscribePresenceListener {
+    /**
+     * This callback method will be called for child resource presence status.
+     *
+     * @param resource
+     *            URI of resource.
+     * @param result
+     *            error code.
+     */
+    public void onPresenceCallback(String resource, int result);
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/OCStackResult.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/OCStackResult.java
new file mode 100644 (file)
index 0000000..241eb11
--- /dev/null
@@ -0,0 +1,138 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    OCStackResult.java
+ *
+ * @brief     This file provides a Enum which contains Status codes for Success and Errors
+ *
+ */
+
+package org.iotivity.service.tm;
+
+/**
+ * This Enum contains Status codes for Success and Errors
+ */
+public enum OCStackResult {
+    OC_STACK_OK,
+    OC_STACK_RESOURCE_CREATED,
+    OC_STACK_RESOURCE_DELETED,
+    OC_STACK_CONTINUE,
+    OC_STACK_INVALID_URI,
+    OC_STACK_INVALID_QUERY,
+    OC_STACK_INVALID_IP,
+    OC_STACK_INVALID_PORT,
+    OC_STACK_INVALID_CALLBACK,
+    OC_STACK_INVALID_METHOD,
+    OC_STACK_INVALID_PARAM,
+    OC_STACK_INVALID_OBSERVE_PARAM,
+    OC_STACK_NO_MEMORY,
+    OC_STACK_COMM_ERROR,
+    OC_STACK_NOTIMPL,
+    OC_STACK_NO_RESOURCE,
+    OC_STACK_RESOURCE_ERROR,
+    OC_STACK_SLOW_RESOURCE,
+    OC_STACK_REPEATED_REQUEST,
+    OC_STACK_NO_OBSERVERS,
+    OC_STACK_OBSERVER_NOT_FOUND,
+    OC_STACK_VIRTUAL_DO_NOT_HANDLE,
+    OC_STACK_INVALID_OPTION,
+    OC_STACK_MALFORMED_RESPONSE,
+    OC_STACK_PERSISTENT_BUFFER_REQUIRED,
+    OC_STACK_INVALID_REQUEST_HANDLE,
+    OC_STACK_INVALID_DEVICE_INFO,
+    OC_STACK_INVALID_JSON,
+    OC_STACK_PRESENCE_STOPPED,
+    OC_STACK_PRESENCE_TIMEOUT,
+    OC_STACK_PRESENCE_DO_NOT_HANDLE,
+    OC_STACK_ERROR,
+    OC_STACK_LISTENER_NOT_SET;
+
+    public static OCStackResult conversion(int ordinal) {
+
+        OCStackResult result = OCStackResult.values()[31];
+
+        if (ordinal == 0)
+            result = OCStackResult.values()[0];
+        else if (ordinal == 1)
+            result = OCStackResult.values()[1];
+        else if (ordinal == 2)
+            result = OCStackResult.values()[2];
+        else if (ordinal == 3)
+            result = OCStackResult.values()[3];
+
+        else if (ordinal == 20)
+            result = OCStackResult.values()[4];
+        else if (ordinal == 21)
+            result = OCStackResult.values()[5];
+        else if (ordinal == 22)
+            result = OCStackResult.values()[6];
+        else if (ordinal == 23)
+            result = OCStackResult.values()[7];
+        else if (ordinal == 24)
+            result = OCStackResult.values()[8];
+        else if (ordinal == 25)
+            result = OCStackResult.values()[9];
+        else if (ordinal == 26)
+            result = OCStackResult.values()[10];
+        else if (ordinal == 27)
+            result = OCStackResult.values()[11];
+        else if (ordinal == 28)
+            result = OCStackResult.values()[12];
+        else if (ordinal == 29)
+            result = OCStackResult.values()[13];
+        else if (ordinal == 30)
+            result = OCStackResult.values()[14];
+        else if (ordinal == 31)
+            result = OCStackResult.values()[15];
+        else if (ordinal == 32)
+            result = OCStackResult.values()[16];
+        else if (ordinal == 33)
+            result = OCStackResult.values()[17];
+        else if (ordinal == 34)
+            result = OCStackResult.values()[18];
+        else if (ordinal == 35)
+            result = OCStackResult.values()[19];
+        else if (ordinal == 36)
+            result = OCStackResult.values()[20];
+        else if (ordinal == 37)
+            result = OCStackResult.values()[21];
+        else if (ordinal == 38)
+            result = OCStackResult.values()[22];
+        else if (ordinal == 39)
+            result = OCStackResult.values()[23];
+        else if (ordinal == 40)
+            result = OCStackResult.values()[24];
+        else if (ordinal == 41)
+            result = OCStackResult.values()[25];
+        else if (ordinal == 42)
+            result = OCStackResult.values()[26];
+        else if (ordinal == 43)
+            result = OCStackResult.values()[27];
+
+        else if (ordinal == 128)
+            result = OCStackResult.values()[28];
+        else if (ordinal == 129)
+            result = OCStackResult.values()[29];
+        else if (ordinal == 130)
+            result = OCStackResult.values()[30];
+
+        return result;
+    }
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManager.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManager.java
new file mode 100644 (file)
index 0000000..a506305
--- /dev/null
@@ -0,0 +1,819 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    ThingsManager.java
+ *
+ * @brief    This file provides a class for a set of APIs relating to group management,
+ *        synchronization of group, configuration of things, and diagnostics
+ *        about things.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+
+import android.util.Log;
+
+/**
+ * This class provides a set of APIs relating to group management,
+ * synchronization of group, configuration of things, and diagnostics
+ * about things.
+ *
+ */
+public class ThingsManager {
+
+    private IFindCandidateResourceListener resourceListener;
+    private ISubscribePresenceListener     presenceListener;
+    private IFindGroupListener             groupListener;
+    private IConfigurationListener         configurationListener;
+    private IDiagnosticsListener           diagnosticsListener;
+    private IActionListener                actionListener;
+    private final String                   LOG_TAG = this.getClass()
+                                                           .getSimpleName();
+
+    private final ThingsManagerCallback    thingsManagerCallbackInterfaceObj;
+    private final ThingsManagerInterface   thingsManagerInterfaceObj;
+
+    static {
+        System.loadLibrary("gnustl_shared");
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("connectivity_abstraction");
+        System.loadLibrary("ca-interface");
+        System.loadLibrary("octbstack");
+        System.loadLibrary("oc");
+        System.loadLibrary("TGMSDKLibrary");
+        System.loadLibrary("ocstack-jni");
+        System.loadLibrary("things-manager-jni");
+    }
+
+    /**
+     * Constructor for ThingsManager. Constructs a new ThingsManager.
+     */
+    public ThingsManager() {
+        thingsManagerCallbackInterfaceObj = ThingsManagerCallback.getInstance();
+        thingsManagerInterfaceObj = ThingsManagerInterface.getInstance();
+    }
+
+    /**
+     * Set listener for receiving notification of resource discovery.
+     *
+     * @param listener
+     *            IFindCandidateResourceListener to receive the
+     *            discovered resources.
+     */
+    public void setFindCandidateResourceListener(
+            IFindCandidateResourceListener listener) {
+        resourceListener = listener;
+        thingsManagerCallbackInterfaceObj
+                .registerFindCandidateResourceListener(listener);
+        thingsManagerInterfaceObj
+                .registerFindCandidateResourceListener(listener);
+    }
+
+    /**
+     * Set listener for receiving child resource presence notifications.
+     *
+     * @param listener
+     *            ISubscribePresenceListener to receive child resource
+     *            presence state.
+     */
+    public void setSubscribePresenceListener(ISubscribePresenceListener listener) {
+        presenceListener = listener;
+        thingsManagerCallbackInterfaceObj
+                .registerSubscribePresenceListener(listener);
+        thingsManagerInterfaceObj.registerSubscribePresenceListener(listener);
+    }
+
+    /**
+     * Set listener for receiving notification on whether the requested group is
+     * found or not.
+     *
+     * @param listener
+     *            IFindGroupListener to receive group discovery status.
+     */
+    public void setGroupListener(IFindGroupListener listener) {
+        groupListener = listener;
+        thingsManagerCallbackInterfaceObj.registerGroupListener(listener);
+        thingsManagerInterfaceObj.registerGroupListener(listener);
+    }
+
+    /**
+     * Set listener for receiving asynchronous response for configuration APIs.
+     *
+     * @param listener
+     *            IConfigurationListener to receive asynchronous response
+     *            for configuration APIs.
+     */
+    public void setConfigurationListener(IConfigurationListener listener) {
+        configurationListener = listener;
+        thingsManagerCallbackInterfaceObj
+                .registerConfigurationListener(listener);
+        thingsManagerInterfaceObj.registerConfigurationListener(listener);
+    }
+
+    /**
+     * Set listener for receiving asynchronous response for diagnostic feature
+     * APIs.
+     *
+     * @param listener
+     *            IDiagnosticsListener to receive asynchronous response
+     *            for diagnostic feature APIs.
+     */
+    public void setDiagnosticsListener(IDiagnosticsListener listener) {
+        diagnosticsListener = listener;
+        thingsManagerCallbackInterfaceObj.registerDiagnosticsListener(listener);
+    }
+
+    /**
+     * Set listener for receiving responses of Get, PUT and POST requests.
+     *
+     * @param listener
+     *            IActionListener to receive Get, PUT and POST request
+     *            responses.
+     */
+    public void setActionListener(IActionListener listener) {
+        actionListener = listener;
+        thingsManagerCallbackInterfaceObj.registerActionListener(listener);
+    }
+
+    /**
+     * API for discovering candidate resources with waiting delay. This
+     * operation returns all resources of given type on the network service.
+     * This operation is sent via multicast to all services. However, the filter
+     * limits the responders to just those that support the resource type in the
+     * query. Currently only exact matches are supported.
+     * <p>
+     * Listener should be set using setFindCandidateResourceListener API
+     * <p>
+     * Listener IFindCandidateResourceListener::onResourceCallback
+     *       will be notified when resource is discovered in network.
+     *
+     * @param resourceTypes
+     *            required resource types(called "candidate")
+     * @param waitTime
+     *            Delay time to add in seconds before starting to find the
+     *            resources in network.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult findCandidateResources(Vector<String> resourceTypes,
+            int waitTime) {
+        if (null == resourceListener) {
+            Log.e(LOG_TAG,"findCandidateResources: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.findCandidateResources(
+                              resourceTypes, waitTime);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "findCandidateResources: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for subscribing child's state. It subscribes the presence state of
+     * the resource. By making this subscription, every time a server
+     * adds/removes/alters a resource, starts or is intentionally stopped, a
+     * notification is sent to subscriber.
+     *
+     * <p>
+     * Listener should be set using setSubscribePresenceListener API.
+     * <p>
+     * Listener ISubscribePresenceListener::onPresenceCallback will
+     *       be notified for resource presence status
+     *
+     * @param resource
+     *            collection resource for subscribing presence of all child
+     *            resources
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult subscribeCollectionPresence(OcResource resource)
+            throws OcException {
+        if (null == presenceListener) {
+            Log.e(LOG_TAG,"subscribeCollectionPresence: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj
+                              .subscribeCollectionPresence(resource);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "subscribeCollectionPresence: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for finding a specific remote group when a resource tries to join a
+     * group.
+     * <p>
+     * Listener should be set using setGroupListener API
+     * <p>
+     * Listener IFindGroupListener::onGroupFindCallback will be
+     *       called to notify whenever a requested group is found.
+     *
+     * @param collectionResourceTypes
+     *            resource types of a group to find and join
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     *
+     */
+    public OCStackResult findGroup(Vector<String> collectionResourceTypes) {
+        if (null == groupListener) {
+            Log.e(LOG_TAG,"findGroup: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = result = thingsManagerInterfaceObj.findGroup(collectionResourceTypes);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "findGroup: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for creating a new group.
+     *
+     * @param collectionResourceType
+     *            resource type of a group to create
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     */
+    public OCStackResult createGroup(String collectionResourceType) {
+        OCStackResult result = thingsManagerInterfaceObj.createGroup(collectionResourceType);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "createGroup: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for joining a group. This API is used for joining the resource
+     * to local group which is created using @createGroup API.
+     *
+     * @param collectionResourceType
+     *            resource type of a group to join.
+     * @param resourceHandle
+     *            resource handle to join a group.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult joinGroup(String collectionResourceType,
+            OcResourceHandle resourceHandle) {
+        OCStackResult result = thingsManagerInterfaceObj.joinGroup(collectionResourceType,
+                              resourceHandle);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "joinGroup: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for joining a group. This API is used for joining the resource to
+     * remote group.
+     *
+     * @param resource
+     *            group resource to join.
+     * @param resourceHandle
+     *            resource handle to join a group.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult joinGroup(OcResource resource,
+            OcResourceHandle resourceHandle) throws OcException {
+        OCStackResult result = thingsManagerInterfaceObj.joinGroup(resource, resourceHandle);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "joinGroup: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for leaving a joined local group.
+     *
+     * @param collectionResourceType
+     *            resource type of a group to leave.
+     * @param resourceHandle
+     *            resource handle to leave a group.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult leaveGroup(String collectionResourceType,
+            OcResourceHandle resourceHandle) {
+        OCStackResult result = thingsManagerInterfaceObj.leaveGroup(collectionResourceType,
+                              resourceHandle);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "leaveGroup: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for leaving a joined remote group.
+     *
+     * @param resource
+     *            resource of a group to leave.
+     * @param collectionResourceType
+     *            resource type of a group to leave.
+     * @param resourceHandle
+     *            resource handle to leave a group.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult leaveGroup(OcResource resource, String collectionResourceType,
+            OcResourceHandle resourceHandle) {
+        OCStackResult result = thingsManagerInterfaceObj.leaveGroup(resource, collectionResourceType,
+                              resourceHandle);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "leaveGroup: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for deleting a created group.
+     *
+     * @param collectionResourceType
+     *            resource type of a group to delete.
+     *
+     */
+    public void deleteGroup(String collectionResourceType) {
+        thingsManagerInterfaceObj.deleteGroup(collectionResourceType);
+    }
+
+    /**
+     * API for getting a list of local groups.
+     *
+     * @return Returns the map with the group resource type and group
+     *         resource handle on successs otherwise null.
+     *
+     */
+    public Map<String, OcResourceHandle> getGroupList() {
+       return thingsManagerInterfaceObj.getGroupList();
+    }
+
+    /**
+     * API for registering and binding a resource to group.
+     *
+     * @param resource
+     *            resource for register and bind to group. It has all data.
+     * @param collectionHandle
+     *            collection resource handle. It will be the added child
+     *            resource.
+     *
+     * @return OcResourceHandle - Child resource handle.
+     *
+     */
+    public OcResourceHandle bindResourceToGroup(OcResource resource,
+            OcResourceHandle collectionHandle)
+            throws OcException {
+        return thingsManagerInterfaceObj.bindResourceToGroup(resource,
+                              collectionHandle);
+    }
+
+    /**
+     * API for updating configuration value of multiple things of a target group
+     * or a single thing to a resource server(s).
+     *
+     * <p>
+     * Listener should be set using setConfigurationListener API.
+     * <p>
+     * Listener IConfigurationListener::onUpdateConfigurationsCallback will be
+     * notified when the response of update configuration arrives.
+     *
+     * @param resource
+     *            resource representing the target group or the single thing.
+     *            It is a pointer of resource instance of Configuration
+     *            resource. The resource pointer can be acquired by performing
+     *            findResource() function with a dedicated resource type,
+     *            "oic.con". Note that, the resource pointer represents not only
+     *            a single simple resource but also a collection resource
+     *            composing multiple simple resources. In other words, using
+     *            these APIs, developers can send a series of requests to
+     *            multiple things by calling the corresponding function at once.
+     * @param configurations
+     *            ConfigurationUnit: a nickname of attribute of target
+     *            resource (e.g., installed location, currency, (IP)address)
+     *            Value : a value to be updated. It represents an indicator of
+     *            which resource developers want to access and which value
+     *            developers want to update. Basically, developers could use a
+     *            resource URI to access a specific resource but a resource URI
+     *            might be hard for all developers to memorize lots of URIs,
+     *            especially in the case of long URIs. To relieve the problem,
+     *            Things Configuration introduces a easy-memorizing name, called
+     *            ConfigurationName, instead of URI. And ConfigurationValue used
+     *            in updateConfiguration() function indicates a value to be
+     *            updated. Note that, only one configuration parameter is
+     *            supported in this release. Multiple configuration parameters
+     *            will be supported in future release.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult updateConfigurations(OcResource resource,
+            Map<String, String> configurations) throws OcException {
+        if (null == configurationListener) {
+            Log.e(LOG_TAG,"updateConfigurations: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.updateConfigurations(resource,
+                              configurations);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "updateConfigurations: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for getting configuration value of multiple things of a target group
+     * or a single thing.To get a value, users need to know a Configuration Name
+     * indicating the target resource. In this release, the Configuration Name
+     * is "configuration".An update value is not needed. After that, users store
+     * them in form of a Vector and then use a getConfigurations() function.
+     *
+     * @param resource
+     *            resource representing the target group or the single thing.
+     * @param configurations
+     *            ConfigurationUnit: a nickname of attribute of target
+     *            resource.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult getConfigurations(OcResource resource,
+            Vector<String> configurations) throws OcException {
+        if (null == configurationListener) {
+            Log.e(LOG_TAG,"getConfigurations: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.getConfigurations(resource,
+                              configurations);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "getConfigurations: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for getting the list of supported configuration units (configurable
+     * parameters). It shows which Configuration Names are supported and their
+     * brief descriptions. This information is provided in JSON format.
+     *
+     * @return Returns the configuration list in JSON format.
+     *
+     */
+    public String getListOfSupportedConfigurationUnits() {
+        return thingsManagerInterfaceObj.getListOfSupportedConfigurationUnits();
+    }
+
+    /**
+     * API for bootstrapping system configuration parameters from a bootstrap
+     * server.
+     * <p>
+     * Listener should be set using setConfigurationListener API.
+     * <p>
+     * Listener IConfigurationListener::onBootStrapCallback will be
+     * notified when the response arrives.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult doBootstrap() {
+        if (null == configurationListener) {
+            Log.e(LOG_TAG,"doBootstrap: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.doBootstrap();
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "doBootstrap: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API to is used to send a request to a server(thing or device) to be
+     * rebooted. On receiving the request, the server attempts to reboot itself
+     * in a deterministic time. The target thing could be a group of multiple
+     * things or a single thing.
+     * <p>
+     * Listener should be set using setDiagnosticsListener API.
+     * <p>
+     * Listener IDiagnosticsListener::onRebootCallback will be
+     * notified when the response arrives.
+     * @param resource
+     *            resource pointer representing the target group
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult reboot(OcResource resource) throws OcException {
+        if (null == diagnosticsListener) {
+            Log.e(LOG_TAG,"reboot: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.reboot(resource);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "reboot: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API to restore all configuration parameters to default one on
+     * thing(device). All configuration parameters refers Configuration
+     * resource, which they could have been modified for various reasons (e.g.,
+     * for a request to update a value). If developers on the client want to
+     * restore the parameters, just use the factoryReset function.The target
+     * thing could be a group of multiple things or a single thing.
+     *
+     * <p>
+     * Listener should be set using setDiagnosticsListener API.
+     * <p>
+     * Listener IDiagnosticsListener::onFactoryResetCallback will be
+     * notified when the response arrives.
+     *
+     * @param resource
+     *            resource pointer representing the target group
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult factoryReset(OcResource resource) throws OcException {
+        if (null == diagnosticsListener) {
+            Log.e(LOG_TAG,"factoryReset: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.factoryReset(resource);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "factoryReset: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for adding a new ActionSet onto a specific resource.
+     *
+     * <p>
+     * Listener should be set using setActionListener API.
+     * <p>
+     * Listener IActionListener::onPutResponseCallback will be
+     * notified when the response of PUT operation arrives.
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionSet
+     *            pointer of ActionSet
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult addActionSet(OcResource resource, ActionSet actionSet)
+            throws OcException {
+        if (null == actionListener) {
+            Log.e(LOG_TAG,"addActionSet: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj
+                                  .addActionSet(resource, actionSet);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "addActionSet: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for executing a specific ActionSet belonging to a specific resource.
+     *
+     * <p>
+     * Listener should be set using setActionListener API.
+     * <p>
+     * Listener IActionListener::onPostResponseCallback will be
+     * notified when the response of POST operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            ActionSet name for removing the ActionSet
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult executeActionSet(OcResource resource,
+            String actionsetName) throws OcException {
+        if (null == actionListener) {
+            Log.e(LOG_TAG,"executeActionSet: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj
+                                  .executeActionSet(resource, actionsetName);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "executeActionSet: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API for executing a specific ActionSet belonging to a specific resource.
+     *
+     * <p>
+     * Listener should be set using setActionListener API.
+     * <p>
+     * Listener IActionListener::onPostResponseCallback will be
+     * notified when the response of POST operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            ActionSet name for removing the ActionSet
+     * @param delay
+     *            Wait time for the ActionSet execution
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult executeActionSet(OcResource resource,
+            String actionsetName, long delay) throws OcException {
+        if (null == actionListener) {
+            Log.e(LOG_TAG,"executeActionSet: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj
+                                  .executeActionSet(resource, actionsetName, delay);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "executeActionSet: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API to cancel the existing ActionSet.
+     *
+     * <p>
+     * Listener should be set using setActionListener API.
+     * <p>
+     * Listener IActionListener::onPostResponseCallback will be
+     *       notified when the response of POST operation arrives.
+     * @param resource
+     *            resource pointer of the group resource.
+     * @param actionsetName
+     *            ActionSet name that has to be cancelled.
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+
+    public OCStackResult cancelActionSet(OcResource resource,
+            String actionsetName) throws OcException {
+        if (null == actionListener) {
+            Log.e(LOG_TAG,"cancelActionSet: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.cancelActionSet(resource,
+                              actionsetName);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "cancelActionSet: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API to to get an existing ActionSet belonging to a specific resource.
+     *
+     * <p>
+     * Listener should be set using setActionListener API.
+     * <p>
+     * Listener IActionListener::onPostResponseCallback will be
+     * notified when the response of POST operation arrives.
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            ActionSet name for removing the ActionSet
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult getActionSet(OcResource resource, String actionsetName)
+            throws OcException {
+        if (null == actionListener) {
+            Log.e(LOG_TAG,"getActionSet: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.getActionSet(resource,
+                                  actionsetName);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "getActionSet: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+    /**
+     * API to delete an existing ActionSet belonging to a specific resource.
+     *
+     * <p>
+     * Listener should be set using setActionListener API.
+     * <p>
+     * Listener IActionListener::onPutResponseCallback will be
+     * notified when the response of PUT operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            ActionSet name for removing the ActionSet
+     *
+     * @return OCStackResult - OC_STACK_OK on success, otherwise a failure error
+     *         code.
+     *
+     */
+    public OCStackResult deleteActionSet(OcResource resource,
+            String actionsetName) throws OcException {
+        if (null == actionListener) {
+            Log.e(LOG_TAG,"deleteActionSet: listener not set!");
+            return OCStackResult.OC_STACK_LISTENER_NOT_SET;
+        }
+
+        OCStackResult result = thingsManagerInterfaceObj.deleteActionSet(resource,
+                                  actionsetName);
+        if (OCStackResult.OC_STACK_OK != result) {
+            Log.e(LOG_TAG, "deleteActionSet: returned error: " + result.name());
+        }
+
+        return result;
+    }
+
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerCallback.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerCallback.java
new file mode 100644 (file)
index 0000000..36456dc
--- /dev/null
@@ -0,0 +1,415 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file    ThingsManagerCallback.java
+ *
+ * @brief    This file provides a class for a set of callback functions for group management,
+ *        synchronization of group, configuration of things, and diagnostics
+ *        about things.
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Vector;
+
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import android.util.Log;
+
+/**
+ * This class provides a set of callback functions for group management,
+ * synchronization of group, configuration of things, and diagnostics
+ * about things.
+ *
+ */
+class ThingsManagerCallback {
+
+    private IFindCandidateResourceListener resourceListener;
+    private ISubscribePresenceListener     presenceListener;
+    private IFindGroupListener             groupListener;
+    private IConfigurationListener         configurationListener;
+    private IDiagnosticsListener           diagnosticsListener;
+    private IActionListener                actionListener;
+    private static ThingsManagerCallback   thingsManagerCallbackInterfaceObj;
+
+    private ThingsManagerCallback() {
+    }
+
+    /**
+     * Function for Getting instance of ThingsManagerCallback object.
+     *
+     * @return ThingsManagerCallback instance.
+     *
+     */
+    public static synchronized ThingsManagerCallback getInstance() {
+        if (null == thingsManagerCallbackInterfaceObj) {
+            thingsManagerCallbackInterfaceObj = new ThingsManagerCallback();
+        }
+        return thingsManagerCallbackInterfaceObj;
+    }
+
+    /**
+     * Register listener for findCandidateResource callback.
+     *
+     * @param listener
+     *            interface for getting notification when resources are
+     *            discovered in network.
+     *
+     */
+    public void registerFindCandidateResourceListener(
+            IFindCandidateResourceListener listener) {
+        resourceListener = listener;
+    }
+
+    /**
+     * Register listener for subscribeCollectionPresence callback.
+     *
+     * @param listener
+     *            interface for getting notification regarding child resource
+     *            presence status.
+     *
+     */
+    public void registerSubscribePresenceListener(
+            ISubscribePresenceListener listener) {
+        presenceListener = listener;
+    }
+
+    /**
+     * Register listener for find group callback.
+     *
+     * @param listener
+     *            interface for getting notification on whether the group is
+     *            found or not.
+     *
+     */
+    public void registerGroupListener(IFindGroupListener listener) {
+        groupListener = listener;
+    }
+
+    /**
+     * Register listener for updateConfigurations and getConfigurations
+     * callback.
+     *
+     * @param listener
+     *            interface for getting notification on configuration values
+     *            information or when configuration value is updated for
+     *            multiple things of a target group or a single thing.
+     *
+     */
+    public void registerConfigurationListener(IConfigurationListener listener) {
+        configurationListener = listener;
+    }
+
+    /**
+     * Register listener for doBootstrap, reboot and factoryReset callbacks.
+     *
+     * @param listener
+     *            interface for receiving asynchronous response for diagnostic
+     *            feature APIs.
+     *
+     */
+    public void registerDiagnosticsListener(IDiagnosticsListener listener) {
+        diagnosticsListener = listener;
+    }
+
+    /**
+     * Register listener for getActionSet, executeActionSet and deleteActionSet
+     * callback.
+     *
+     * @param listener
+     *            interface for receiving the callback for the GET, PUT and
+     *            POST requested actions.
+     *
+     */
+    public void registerActionListener(IActionListener listener) {
+        actionListener = listener;
+    }
+
+    /**
+     * Unregister listener for findCandidateResource callback.
+     *
+     */
+    public void unregisterFindCandidateResourceListener() {
+        resourceListener = null;
+    }
+
+    /**
+     * Unregister listener for subscribeCollectionPresence callback.
+     *
+     */
+    public void unregisterSubscribePresenceListener() {
+        presenceListener = null;
+    }
+
+    /**
+     * Unregister listener for find group callback.
+     *
+     */
+    public void unregisterGroupListener() {
+        groupListener = null;
+    }
+
+    /**
+     * Unregister listener for updateConfigurations and getConfigurations
+     * callback.
+     *
+     */
+    public void unregisterConfigurationListener() {
+        configurationListener = null;
+    }
+
+    /**
+     * Unregister listener for doBootstrap, reboot and factoryReset callbacks.
+     *
+     */
+    public void unregisterDiagnosticsListener() {
+        diagnosticsListener = null;
+    }
+
+    /**
+     * Unregister listener for getActionSet, executeActionSet and
+     * deleteActionSet callback.
+     *
+     */
+    public void unregisterActionListener() {
+        actionListener = null;
+    }
+
+    /**
+     * This callback method will be called whenever resource is discovered in
+     * the network.
+     *
+     * @param resources
+     *            List of resources discovered in the network
+     *
+     */
+    public void onResourceCallback(Vector<OcResource> resources) {
+        if (null != resourceListener)
+            resourceListener.onResourceCallback(resources);
+    }
+
+    /**
+     * This callback method is called when a response for the executeActionSet
+     * or deleteActionSet request just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onPostResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        if (null != actionListener)
+            actionListener.onPostResponseCallback(headerOptions, rep,
+                    errorValue);
+    }
+
+    /**
+     * This callback method is called when a response for the addActionSet
+     * request just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onPutResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        if (null != actionListener)
+            actionListener
+                    .onPutResponseCallback(headerOptions, rep, errorValue);
+    }
+
+    /**
+     * This callback method is called when a response for the getActionSet
+     * request just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onGetResponseCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        if (null != actionListener)
+            actionListener
+                    .onGetResponseCallback(headerOptions, rep, errorValue);
+    }
+
+    /**
+     * This callback method is called when a response for the
+     * updateConfigurations request just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onUpdateConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue) {
+        if (null != configurationListener)
+            configurationListener.onUpdateConfigurationsCallback(headerOptions,
+                    rep, errorValue);
+    }
+
+    /**
+     * This callback method is called when a response for the getConfigurations
+     * request just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onGetConfigurationsCallback(
+            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
+            int errorValue) {
+        if (null != configurationListener)
+            configurationListener.onGetConfigurationsCallback(headerOptions,
+                    rep, errorValue);
+    }
+
+    /**
+     * This callback method is called when a response for the doBootstrap
+     * request just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        if (null != configurationListener) {
+            Log.i("ThingsManagerCallback : onBootStrapCallback",
+                    "Received Callback from JNI");
+            configurationListener.onBootStrapCallback(headerOptions, rep,
+                    errorValue);
+        }
+    }
+
+    /**
+     * This callback method is called when a response for the reboot request
+     * just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onRebootCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        if (null != diagnosticsListener) {
+            Log.i("ThingsManagerCallback : onRebootCallback",
+                    "Received Callback from JNI");
+            diagnosticsListener
+                    .onRebootCallback(headerOptions, rep, errorValue);
+        }
+    }
+
+    /**
+     * This callback method is called when a response for the factoryReset
+     * request just arrives.
+     *
+     * @param headerOptions
+     *            It comprises of optionID and optionData as members.
+     * @param rep
+     *            Configuration parameters are carried as a pair of attribute
+     *            key and value in a form of OCRepresentation instance.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onFactoryResetCallback(Vector<OcHeaderOption> headerOptions,
+            OcRepresentation rep, int errorValue) {
+        if (null != diagnosticsListener) {
+            Log.i("ThingsManagerCallback : onFactoryResetCallback",
+                    "Received Callback from JNI");
+            diagnosticsListener.onFactoryResetCallback(headerOptions, rep,
+                    errorValue);
+        }
+    }
+
+    /**
+     * This callback method is called to notify whether group is found or not.
+     *
+     * @param resource
+     *            Resource URI
+     *
+     */
+    public void onGroupFindCallback(OcResource resource) {
+        if (null != groupListener) {
+            Log.i("ThingsManagerCallback : onGroupFindCallback",
+                    "Received Callback from JNI");
+            groupListener.onGroupFindCallback(resource);
+        }
+    }
+
+    /**
+     * This callback method is called for child resource presence status.
+     *
+     * @param resource
+     *            URI of resource.
+     * @param errorValue
+     *            error code.
+     *
+     */
+    public void onPresenceCallback(String resource, int errorValue) {
+        if (null != presenceListener) {
+            Log.i("ThingsManagerCallback : onPresenceCallback",
+                    "Received Callback from JNI");
+            presenceListener.onPresenceCallback(resource, errorValue);
+        }
+    }
+
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerInterface.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerInterface.java
new file mode 100644 (file)
index 0000000..0f1d2cd
--- /dev/null
@@ -0,0 +1,652 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file   ThingsManagerInterface.java
+ *
+ * @brief    This file provides a class which acts as an interface for Things Manager API calls between
+ *        ThingsManager and ThingsManagerNativeInterface
+ *
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Vector;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+
+import android.util.Log;
+
+/**
+ * This class acts as an interface for Things Manager API calls between
+ * ThingsManager and ThingsManagerNativeInterface
+ *
+ */
+class ThingsManagerInterface {
+
+    private IFindCandidateResourceListener resourceListener;
+    private ISubscribePresenceListener     presenceListener;
+    private IFindGroupListener             groupListener;
+    private IConfigurationListener         configurationListener;
+    private static ThingsManagerInterface  thingsManagerInterfaceObj;
+
+    private ThingsManagerInterface() {
+    }
+
+    /**
+     * Function for Getting instance of ThingsManagerInterface object.
+     *
+     * @return ThingsManagerInterface instance.
+     *
+     */
+    public static synchronized ThingsManagerInterface getInstance() {
+        if (null == thingsManagerInterfaceObj) {
+            thingsManagerInterfaceObj = new ThingsManagerInterface();
+        }
+        return thingsManagerInterfaceObj;
+    }
+
+    /**
+     * Register listener for findCandidateResource callback.
+     *
+     * @param listener
+     *            interface for getting notification when resources are
+     *            discovered in network.
+     *
+     */
+    public void registerFindCandidateResourceListener(
+            IFindCandidateResourceListener listener) {
+        resourceListener = listener;
+    }
+
+    /**
+     * Register listener for subscribeCollectionPresence callback.
+     *
+     * @param listener
+     *            interface for getting notification regarding child resource
+     *            presence status.
+     *
+     */
+    public void registerSubscribePresenceListener(
+            ISubscribePresenceListener listener) {
+        presenceListener = listener;
+    }
+
+    /**
+     * Register listener for register group and find group callback.
+     *
+     * @param listener
+     *            interface for getting notification on whether the group is
+     *            found or not.
+     *
+     */
+    public void registerGroupListener(IFindGroupListener listener) {
+        groupListener = listener;
+    }
+
+    /**
+     * Register listener for updateConfigurations and getConfigurations
+     * callback.
+     *
+     * @param listener
+     *            interface for getting notification on configuration values
+     *            information or when configuration value is updated for
+     *            multiple things of a target group or a single thing.
+     *
+     */
+    public void registerConfigurationListener(IConfigurationListener listener) {
+        configurationListener = listener;
+    }
+
+    /**
+     * Unregister listener for findCandidateResource callback.
+     *
+     */
+    public void unregisterFindCandidateResourceListener() {
+        resourceListener = null;
+    }
+
+    /**
+     * Unregister listener for subscribeCollectionPresence callback.
+     *
+     */
+    public void unregisterSubscribePresenceListener() {
+        presenceListener = null;
+    }
+
+    /**
+     * Unregister listener for registerGroup and findGroup callback.
+     *
+     */
+    public void unregisterGroupListener() {
+        groupListener = null;
+    }
+
+    /**
+     * Unregister listener for updateConfigurations and getConfigurations
+     * callback.
+     *
+     */
+    public void unregisterConfigurationListener() {
+        configurationListener = null;
+    }
+
+    /**
+     * API for discovering candidate resources with waiting delay. Listener
+     * <p>
+     * IFindCandidateResourceListener::onResourceCallback will be notified
+     *      when resource is discovered in network.
+     * </p>
+     *
+     * @param resourceTypes
+     *            required resource types(called "candidate")
+     * @param waitTime
+     *            Time duration in seconds to find the resources in network
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult findCandidateResources(Vector<String> resourceTypes,
+            int waitTime) {
+        OCStackResult result;
+        if (null == resourceListener) {
+            result = OCStackResult.OC_STACK_ERROR;
+        } else {
+            int ordinal = ThingsManagerNativeInterface.findCandidateResources(
+                    resourceTypes, waitTime);
+            result = OCStackResult.conversion(ordinal);
+        }
+        return result;
+    }
+
+    /**
+     * API for subscribing child's state. Listener
+     * <p>
+     * ISubscribePresenceListener::onPresenceCallback will be notified for
+     *      resource presence status
+     * </p>
+     *
+     * @param resource
+     *            collection resource for subscribing presence of all child
+     *            resources
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult subscribeCollectionPresence(OcResource resource)
+            throws OcException {
+        String LOG_TAG = this.getClass().getSimpleName();
+
+        OCStackResult result;
+        if (null == presenceListener) {
+            result = OCStackResult.OC_STACK_ERROR;
+        } else {
+
+            int ordinal = ThingsManagerNativeInterface
+                    .subscribeCollectionPresence(resource);
+            Log.i(LOG_TAG, "Ordinal value = : " + ordinal);
+            result = OCStackResult.conversion(ordinal);
+        }
+        return result;
+    }
+
+    /**
+     * API for finding a specific remote group when a resource tries to join a
+     * group.
+     * <p>
+     * IFindGroupListener::onGroupFindCallback will be called to notify
+     *      whether requested group found or not.
+     * </p>
+     *
+     * @param resourceTypes
+     *            resource types of a group to find and join
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult findGroup(Vector<String> resourceTypes) {
+        OCStackResult result;
+        if (null == groupListener) {
+            result = OCStackResult.OC_STACK_ERROR;
+        } else {
+            int ordinal = ThingsManagerNativeInterface.findGroup(resourceTypes);
+            result = OCStackResult.conversion(ordinal);
+        }
+        return result;
+    }
+
+    /**
+     * API for creating a new group.
+     *
+     * @param resourceType
+     *            resource type of a group to create
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult createGroup(String resourceType) {
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.createGroup(resourceType);
+        result = OCStackResult.conversion(ordinal);
+        return result;
+    }
+
+    /**
+     * API for joining a group. This API is used when a resource that has a
+     * group tries to find a specific remote resource and makes it join a group.
+     *
+     * @param resourceType
+     *            resource type of a group to join.
+     * @param resourceHandle
+     *            resource handle to join a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult joinGroup(String resourceType,
+            OcResourceHandle resourceHandle) {
+        OCStackResult result;
+
+        int ordinal = ThingsManagerNativeInterface.joinGroup(resourceType,
+                resourceHandle);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for joining a group. This API is used when a resource that doesn't
+     * have a group tries to find and join a specific remote group.
+     *
+     * @param resource
+     *            group resource to join.
+     * @param resourceHandle
+     *            resource handle to join a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult joinGroup(OcResource resource,
+            OcResourceHandle resourceHandle) throws OcException {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.joinGroup(resource,
+                resourceHandle);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for leaving a joined group.
+     *
+     * @param resourceType
+     *            resource type of a group to leave.
+     * @param resourceHandle
+     *            resource handle to leave a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult leaveGroup(String resourceType,
+            OcResourceHandle resourceHandle) {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.leaveGroup(resourceType,
+                resourceHandle);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for leaving a joined group.
+     *
+     * @param resource
+     *            resource of a group to leave.
+     * @param resourceType
+     *            resource type of a group to leave.
+     * @param resourceHandle
+     *            resource handle to leave a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult leaveGroup(OcResource resource, String resourceType,
+            OcResourceHandle resourceHandle) {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.leaveGroup(resource,
+                resourceType, resourceHandle);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for deleting a group.
+     *
+     * @param collectionResourceType
+     *            resource type of a group to delete.
+     *
+     */
+    public void deleteGroup(String collectionResourceType) {
+        ThingsManagerNativeInterface.deleteGroup(collectionResourceType);
+    }
+
+    /**
+     * API for getting a list of joined groups.
+     *
+     * @return Returns group resource type and group resource handle as a map
+     *         table.
+     *
+     */
+    public Map<String, OcResourceHandle> getGroupList() {
+        return ThingsManagerNativeInterface.getGroupList();
+    }
+
+    /**
+     * API for register and bind resource to group.
+     *
+     * @param resource
+     *            resource for register and bind to group. It has all data.
+     * @param collectionHandle
+     *            collection resource handle. It will be added child resource.
+     *
+     * @return OcResourceHandle - Child resource handle.
+     */
+    public OcResourceHandle bindResourceToGroup(OcResource resource,
+            OcResourceHandle collectionHandle)
+            throws OcException {
+        return ThingsManagerNativeInterface.bindResourceToGroup(
+                resource, collectionHandle);
+    }
+
+    /**
+     * API for updating configuration value of multiple things of a target group
+     * or a single thing.
+     *
+     * @param resource
+     *            resource representing the target group or the single thing.
+     * @param configurations
+     *            ConfigurationUnit: a nickname of attribute of target
+     *            resource (e.g., installed location, currency, (IP)address)
+     *            Value : a value to be updated
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult updateConfigurations(OcResource resource,
+            Map<String, String> configurations) throws OcException {
+        OCStackResult result;
+        if (null == configurationListener) {
+            result = OCStackResult.OC_STACK_ERROR;
+        } else {
+            int ordinal = ThingsManagerNativeInterface.updateConfigurations(
+                    resource, configurations);
+            result = OCStackResult.conversion(ordinal);
+        }
+        return result;
+
+    }
+
+    /**
+     * API for getting configuration value of multiple things of a target group
+     * or a single thing.
+     *
+     * @param resource
+     *            resource representing the target group or the single thing.
+     * @param configurations
+     *            ConfigurationUnit: a nickname of attribute of target
+     *            resource.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public OCStackResult getConfigurations(OcResource resource,
+            Vector<String> configurations) throws OcException {
+        OCStackResult result;
+        if (null == configurationListener) {
+            result = OCStackResult.OC_STACK_ERROR;
+        } else {
+            int ordinal = ThingsManagerNativeInterface.getConfigurations(
+                    resource, configurations);
+            result = OCStackResult.conversion(ordinal);
+        }
+        return result;
+    }
+
+    /**
+     * API for showing the list of supported configuration units (configurable
+     * parameters)
+     *
+     * @return Returns the configuration list in JSON format.
+     *
+     */
+    public String getListOfSupportedConfigurationUnits() {
+
+        return ThingsManagerNativeInterface
+                .getListOfSupportedConfigurationUnits();
+    }
+
+    /**
+     * API for bootstrapping system configuration parameters from a bootstrap
+     * server.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult doBootstrap() {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.doBootstrap();
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API to let thing(device) reboot. The target thing could be a group of
+     * multiple things or a single thing.
+     *
+     * @param resource
+     *            resource pointer representing the target group
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success
+     */
+    public OCStackResult reboot(OcResource resource) throws OcException {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.reboot(resource);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for factory reset on thing(device). The target thing could be a group
+     * of multiple things or a single thing.
+     *
+     * @param resource
+     *            resource pointer representing the target group
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult factoryReset(OcResource resource) throws OcException {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.factoryReset(resource);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for adding an Action Set. Callback is called when the response of PUT
+     * operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionSet
+     *            pointer of Action Set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult addActionSet(OcResource resource, ActionSet actionSet)
+            throws OcException {
+
+        int ordinal = ThingsManagerNativeInterface.addActionSet(resource,
+                actionSet);
+
+        return OCStackResult.conversion(ordinal);
+    }
+
+    /**
+     * API for executing the Action Set. Callback is called when the response of
+     * POST operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult executeActionSet(OcResource resource,
+            String actionsetName) throws OcException {
+
+        int ordinal = ThingsManagerNativeInterface.executeActionSet(resource,
+                actionsetName);
+
+        return OCStackResult.conversion(ordinal);
+    }
+
+    /**
+     * API for executing the Action Set. Callback is called when the response of
+     * POST operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            Action Set name for removing the Action set
+     * @param delay
+     *            waiting time for until action set run.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult executeActionSet(OcResource resource,
+            String actionsetName, long delay) throws OcException {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.executeActionSet(resource,
+                actionsetName, delay);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for cancelling the Action Set. Callback is called when the response
+     * of POST operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult cancelActionSet(OcResource resource,
+            String actionsetName) throws OcException {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.cancelActionSet(resource,
+                actionsetName);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for reading the Action Set. Callback is called when the response of
+     * GET operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult getActionSet(OcResource resource, String actionsetName)
+            throws OcException {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.getActionSet(resource,
+                actionsetName);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+
+    /**
+     * API for removing the action set. Callback is called when the response of
+     * POST operation arrives.
+     *
+     * @param resource
+     *            resource pointer of the group resource
+     * @param actionsetName
+     *            Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public OCStackResult deleteActionSet(OcResource resource,
+            String actionsetName) throws OcException {
+
+        OCStackResult result;
+        int ordinal = ThingsManagerNativeInterface.deleteActionSet(resource,
+                actionsetName);
+        result = OCStackResult.conversion(ordinal);
+
+        return result;
+    }
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerNativeInterface.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/ThingsManagerNativeInterface.java
new file mode 100644 (file)
index 0000000..cd598c0
--- /dev/null
@@ -0,0 +1,362 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+/**
+ * @file    ThingsManagerNativeInterface.java
+ *
+ * @brief     This file provides a class which provides a set of native functions relating to group
+ *        management, synchronization of group, configuration of things, and
+ *        diagnostics about things.
+ */
+
+package org.iotivity.service.tm;
+
+import java.util.Map;
+import java.util.Vector;
+
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+
+/**
+ * This class provides a set of native functions relating to group
+ * management, synchronization of group, configuration of things, and
+ * diagnostics about things.
+ *
+ */
+class ThingsManagerNativeInterface {
+    /**
+     * Native function for discoverying candidate resources.
+     *
+     * @param resourceTypes
+     *            - required resource types(called "candidate")
+     * @param waitTime
+     *            - Delay time in seconds to add before starting to find the
+     *            resources in network.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int findCandidateResources(
+            Vector<String> resourceTypes, int waitTime);
+
+    /**
+     * Native function for subscribing child's state.
+     *
+     * @param resource
+     *            - collection resource for subscribing presence of all child
+     *            resources.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int subscribeCollectionPresence(OcResource resource);
+
+    /**
+     * Native function for register and bind resource to group.
+     *
+     * @param resource
+     *            - resource for register and bind to group. It has all data.
+     * @param collectionHandle
+     *            - collection resource handle. It will be added child resource.
+     *
+     * @return OcResourceHandle - Child resource handle.
+     *
+     */
+    public static native OcResourceHandle bindResourceToGroup(OcResource resource,
+            OcResourceHandle collectionHandle);
+
+    /**
+     * Native function for finding a specific remote group when a resource tries
+     * to join a group. Callback is called when a group is found or not.
+     *
+     * @param collectionResourceTypes
+     *            - resource types of a group to find and join
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int findGroup(Vector<String> collectionResourceTypes);
+
+    /**
+     * Native function for creating a new group.
+     *
+     * @param collectionResourceType
+     *            - resource type of a group to create
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int createGroup(String collectionResourceType);
+
+    /**
+     * Native function for joining a group. This API is used when a resource
+     * that has a group tries to find a specific remote resource and makes it
+     * join a group.
+     *
+     * @param collectionResourceType
+     *            - resource type of a group to join.
+     * @param resourceHandle
+     *            - resource handle to join a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int joinGroup(String collectionResourceType,
+            OcResourceHandle resourceHandle);
+
+    /**
+     * Native function for joining a group. This is used when a resource that
+     * doesn't have a group tries to find and join a specific remote group.
+     *
+     * @param resource
+     *            - group resource to join.
+     * @param resourceHandle
+     *            - resource handle to join a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int joinGroup(OcResource resource,
+            OcResourceHandle resourceHandle);
+
+    /**
+     * Native function for leaving a joined group.
+     *
+     * @param collectionResourceType
+     *            - resource type of a group to leave.
+     * @param resourceHandle
+     *            - resource handle to leave a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int leaveGroup(String collectionResourceType,
+            OcResourceHandle resourceHandle);
+
+    /**
+     * Native function for leaving a joined group.
+     *
+     * @param resource
+     *            - resource of a group to leave.
+     * @param collectionResourceType
+     *            - resource type of a group to leave.
+     * @param resourceHandle
+     *            - resource handle to leave a group.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int leaveGroup(OcResource resource,
+            String collectionResourceType, OcResourceHandle resourceHandle);
+
+    /**
+     * Native function for deleting a group.
+     *
+     * @param collectionResourceType
+     *            - resource type of a group to delete.
+     *
+     *
+     */
+    public static native void deleteGroup(String collectionResourceType);
+
+    /**
+     * Native function for getting a list of joined groups.
+     *
+     * @return Returns group resource type and group resource handle as a map
+     *         table.
+     *
+     */
+    public static native Map<String, OcResourceHandle> getGroupList();
+
+    /**
+     * Native function for updating configuration value of multiple things of a
+     * target group or a single thing.
+     *
+     * @param resource
+     *            - resource representing the target group or the single thing.
+     * @param configurations
+     *            - ConfigurationUnit: a nickname of attribute of target
+     *            resource (e.g., installed location, currency, (IP)address)
+     *            Value : a value to be updated
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int updateConfigurations(OcResource resource,
+            Map<String, String> configurations);
+
+    /**
+     * Native function for getting configuration value of multiple things of a
+     * target group or a single thing.
+     *
+     * @param resource
+     *            - resource representing the target group or the single thing.
+     * @param configurations
+     *            - ConfigurationUnit: a nickname of attribute of target
+     *            resource.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     *
+     */
+    public static native int getConfigurations(OcResource resource,
+            Vector<String> configurations);
+
+    /**
+     * Native function for showing the list of supported configuration units
+     * (configurable parameters)
+     *
+     * @return Returns the configuration list in JSON format.
+     *
+     */
+    public static native String getListOfSupportedConfigurationUnits();
+
+    /**
+     * Native function for bootstrapping system configuration parameters from a
+     * bootstrap server.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int doBootstrap();
+
+    /**
+     * Native function to let thing(device) reboot. The target thing could be a
+     * group of multiple things or a single thing.
+     *
+     * @param resource
+     *            - resource pointer representing the target group
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success
+     */
+    public static native int reboot(OcResource resource);
+
+    /**
+     * Native function for factory reset on thing(device). The target thing
+     * could be a group of multiple things or a single thing.
+     *
+     * @param resource
+     *            - resource pointer representing the target group
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int factoryReset(OcResource resource);
+
+    /**
+     * Native function for adding an Action Set. Callback is called when the
+     * response of PUT operation arrives.
+     *
+     * @param resource
+     *            - resource pointer of the group resource
+     * @param actionSet
+     *            - pointer of Action Set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int addActionSet(OcResource resource,
+            ActionSet actionSet);
+
+    /**
+     * Native function for executing the Action Set. Callback is called when the
+     * response of POST operation arrives.
+     *
+     * @param resource
+     *            - resource pointer of the group resource
+     * @param actionsetName
+     *            - Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int executeActionSet(OcResource resource,
+            String actionsetName);
+
+    /**
+     * Native function for executing the Action Set. Callback is called when the
+     * response of POST operation arrives.
+     *
+     * @param resource
+     *            - resource pointer of the group resource
+     * @param actionsetName
+     *            - Action Set name for removing the Action set
+     * @param delay
+     *            - waiting time for until action set run.
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int executeActionSet(OcResource resource,
+            String actionsetName, long delay);
+
+    /**
+     * Native function for cancelling the Action Set. Callback is called when
+     * the response of POST operation arrives.
+     *
+     * @param resource
+     *            - resource pointer of the group resource
+     * @param actionsetName
+     *            - Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int cancelActionSet(OcResource resource,
+            String actionsetName);
+
+    /**
+     * Native function for reading the Action Set. Callback is called when the
+     * response of GET operation arrives.
+     *
+     * @param resource
+     *            - resource pointer of the group resource
+     * @param actionsetName
+     *            - Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int getActionSet(OcResource resource,
+            String actionsetName);
+
+    /**
+     * Native function for removing the action set. Callback is called when the
+     * response of POST operation arrives.
+     *
+     * @param resource
+     *            - resource pointer of the group resource
+     * @param actionsetName
+     *            - Action Set name for removing the Action set
+     *
+     * @return OCStackResult - return value of this API. It returns OC_STACK_OK
+     *         if success.
+     */
+    public static native int deleteActionSet(OcResource resource,
+            String actionsetName);
+}
diff --git a/service/things-manager/sdk/java/src/org/iotivity/service/tm/Time.java b/service/things-manager/sdk/java/src/org/iotivity/service/tm/Time.java
new file mode 100644 (file)
index 0000000..dc28d8b
--- /dev/null
@@ -0,0 +1,142 @@
+package org.iotivity.service.tm;
+
+import android.util.Log;
+
+/**
+ * This class provides time-related information used for
+ * scheduled/recursive group action features. Along with time-related
+ * variables, it also provides various useful functionality including
+ * translating time to second unit
+ */
+public class Time {
+
+    public enum ActionSetType {
+        NONE, SCHEDULED, RECURSIVE
+    }
+
+    public int            mYear      = 0;
+    public int            mMonth     = 0;
+    public int            mDay       = 0;
+    public int            mHour      = 0;
+    public int            mMin       = 0;
+    public int            mSec       = 0;
+    public int            mDayOfWeek = 0;
+
+    private ActionSetType mType      = ActionSetType.NONE;
+    private long          mDelay     = 0;
+
+    private final String  LOG_TAG    = this.getClass().getSimpleName();
+
+    /**
+     * Set the time for executing ActionSet.
+     *
+     * @param year
+     *            Year to be set
+     * @param month
+     *            Month of the year to be set
+     * @param day
+     *            Day of the month to be set
+     * @param hour
+     *            Hour to be set
+     * @param min
+     *            Minute to be set
+     * @param sec
+     *            Second to be set
+     * @param dayOfTheWeek
+     *            Day of the week to be set
+     *
+     */
+    public void setTime(int year, int month, int day, int hour, int min,
+            int sec, int dayOfTheWeek) {
+        if (year < 0 || month < 0 || day < 0 || hour < 0 || min < 0 || sec < 0
+                || dayOfTheWeek < 0) {
+            Log.e(LOG_TAG, "Input time is invalid");
+            return;
+        }
+
+        year -= 1900;
+        month -= 1;
+
+        mDelay = 0;
+        mYear = year;
+        mMonth = month;
+        mDay = day;
+        mHour = hour;
+        mMin = month;
+        mSec = sec;
+        mDayOfWeek = dayOfTheWeek;
+        mType = ActionSetType.NONE;
+    }
+
+    /**
+     * Set type of ActionSet.
+     *
+     * @param type
+     *            Type of ActionSet
+     */
+    public void setType(ActionSetType type) {
+        mType = type;
+    }
+
+    /**
+     * Set day of the week for recursively executing ActionSet.
+     *
+     * @param day
+     *            day of the week
+     */
+    public void setDayOfWeekForRecursive(int day) {
+        if (day != -1) {
+            mType = ActionSetType.RECURSIVE;
+            setTime(0, 0, 0, 0, 0, 0, day);
+        }
+    }
+
+    /**
+     * Set the time delay in seconds for executing ActionSet.
+     *
+     * @param seconds
+     *            time delay in seconds
+     *
+     */
+    public void setDelay(long seconds) {
+        if (mType != ActionSetType.NONE) {
+            mDelay = seconds;
+        }
+    }
+
+    /**
+     * Get absolute time in seconds.
+     *
+     * @return long - Absolute time in seconds.
+     *
+     */
+    public long getSecAbsTime() {
+        long interval;
+
+        interval = (mHour * 60 * 60);
+        interval += (mMin * 60);
+        interval += (mSec * 1);
+
+        return interval;
+    }
+
+    /**
+     * Get the type of ActionSet.
+     *
+     * @return ActionSetType - Type of ActionSet.
+     *
+     */
+    public ActionSetType getType() {
+        return mType;
+    }
+
+    /**
+     * Get the time delay in seconds set in the ActionSet.
+     *
+     * @return long - Delay in seconds.
+     *
+     */
+    public long getDelay() {
+        return mDelay;
+    }
+}
diff --git a/service/things-manager/sdk/src/ActionSet.cpp b/service/things-manager/sdk/src/ActionSet.cpp
new file mode 100644 (file)
index 0000000..910a5e6
--- /dev/null
@@ -0,0 +1,165 @@
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "ActionSet.h"
+using namespace std;
+
+namespace OIC
+{
+Time::Time()
+{
+    setTime(0, 0, 0, 0, 0, 0, 0);
+}
+
+Time::~Time()
+{
+}
+
+void Time::setTime(OCTime t)
+{
+    mTime = t;
+}
+void Time::setTime(unsigned int yy, unsigned int mm, unsigned int dd,
+        unsigned int h, unsigned int m, unsigned int s,
+        int dayoftheweek = 0)
+{
+    yy -= 1900;
+    mm -= 1;
+
+    mDelay = 0;
+    mTime.tm_year = yy;
+    mTime.tm_mon = mm;
+    mTime.tm_mday = dd;
+
+    mTime.tm_hour = h;
+    mTime.tm_min = m;
+    mTime.tm_sec = s;
+
+    mTime.tm_wday = (unsigned int) dayoftheweek;
+    type = NONE;
+}
+void Time::setDayOfWeekForRecursive(int day)
+{
+    if (day != -1)
+        type = RECURSIVE;
+    else
+        return;
+
+    setTime(0, 0, 0, 0, 0, 0, day);
+}
+unsigned int Time::getYear()
+{
+    return mTime.tm_year;
+}
+unsigned int Time::getMonth()
+{
+    return mTime.tm_mon;
+}
+unsigned int Time::getDay()
+{
+    return mTime.tm_mday;
+}
+unsigned int Time::getHour()
+{
+    return mTime.tm_hour;
+}
+unsigned int Time::getMin()
+{
+    return mTime.tm_min;
+}
+unsigned int Time::getSec()
+{
+    return mTime.tm_sec;
+}
+long int Time::getSecondsFromAbsoluteTime()
+{
+    if(mTime.tm_year > 1900)
+        mTime.tm_year -= 1900;
+
+    mTime.tm_mon -= 1;
+
+    return getSecondsFromAbsTime(&mTime);
+}
+long int Time::getSecAbsTime()
+{
+    return getSeconds(&mTime);
+}
+long int Time::getSecondsForWeeklySchedule()
+{
+    if(mTime.tm_year > 1900)
+        mTime.tm_year -= 1900;
+
+    mTime.tm_mon -= 1;
+    return getRelativeIntervalOfWeek(&mTime);
+}
+
+void Time::setDelay(long int seconds)
+{
+    if(type != NONE)
+    {
+        mDelay = seconds;
+    }
+}
+
+std::string Time::toString() const
+{
+    char temp[25] = { 0 };
+    // It is shown format which required of scheduled/recursive group action time.
+    // " [delay] [type of actionset] "
+    snprintf(temp, sizeof(temp) / sizeof(char),
+            "%ld %d", mDelay, (unsigned int) type);
+    return std::string(temp);
+}
+
+
+
+
+
+
+
+
+
+
+Action::Action() :
+        target("")
+{
+}
+Action::~Action()
+{
+    listOfCapability.clear();
+}
+
+
+
+
+
+
+
+
+
+ActionSet::ActionSet() :
+        actionsetName("")
+{
+}
+ActionSet::~ActionSet()
+{
+    listOfAction.clear();
+}
+}
index d3ddab4..cbcc4d0 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file    GroupManager.cpp
-///  @brief
+/**
+ * @file
+ *
+ */
 
 #include "GroupManager.h"
 #include <algorithm>
 #define ATTR_DELIMITER "="
 
 using namespace OC;
+using namespace OIC;
 
-namespace OIC
-{
 std::map< std::vector< std::string >, CandidateCallback > candidateRequest;
 std::map< std::vector< std::string >, CandidateCallback > candidateRequestForTimer;
 std::map< std::string, std::map< std::string, std::shared_ptr< OCResource > > > rtForResourceList;
 std::vector< std::string > allFoundResourceTypes;
+std::mutex callbackLock;
+
 
 template< typename T >
 bool IsSubset(std::vector< T > full, std::vector< T > sub)
@@ -150,6 +153,7 @@ GroupManager::~GroupManager(void)
 void GroupManager::findPreparedRequest(
         std::map< std::vector< std::string >, CandidateCallback > &request)
 {
+    std::lock_guard<std::mutex> lock(callbackLock);
     std::vector< std::shared_ptr< OCResource > > resources;
 
     for (auto it = request.begin(); it != request.end();)
@@ -157,14 +161,13 @@ void GroupManager::findPreparedRequest(
 
         if (IsSubset(allFoundResourceTypes, it->first))
         {
-            //std::cout << "IS SUBSET !!! \n";
-
             for (unsigned int i = 0; i < it->first.size(); ++i)
             {
 
                 for (auto secondIt = rtForResourceList[it->first.at(i)].begin();
                         secondIt != rtForResourceList[it->first.at(i)].end(); ++secondIt)
                 {
+                    //insert resource related to request
                     resources.push_back(secondIt->second);
                 }
             }
@@ -190,19 +193,24 @@ void GroupManager::lazyCallback(int second)
 
 }
 
-OCStackResult GroupManager::findCandidateResources(std::vector< std::string > resourceTypes,
+OCStackResult GroupManager::findCandidateResources(
+        std::vector< std::string > resourceTypes,
         CandidateCallback callback, int waitsec)
 {
     if (resourceTypes.size() < 1)
     {
         return OC_STACK_ERROR;
     }
+    if(callback == NULL)
+    {
+        return OC_STACK_ERROR;
+    }
 
     std::sort(resourceTypes.begin(), resourceTypes.end());
     resourceTypes.erase(std::unique(resourceTypes.begin(), resourceTypes.end()),
             resourceTypes.end());
 
-    if (waitsec != -1)
+    if (waitsec >= 0)
     {
         candidateRequestForTimer.insert(std::make_pair(resourceTypes, callback));
     }
@@ -213,16 +221,21 @@ OCStackResult GroupManager::findCandidateResources(std::vector< std::string > re
 
     for (unsigned int i = 0; i < resourceTypes.size(); ++i)
     {
-        std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;
-        std::string query = "coap://224.0.1.187/oc/core?rt=";
+        // std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;
+
+        std::string query = OC_MULTICAST_DISCOVERY_URI;
+        query.append("?rt=");
         query.append(resourceTypes.at(i));
-        OCPlatform::findResource("", query.c_str(),
+
+        OCPlatform::findResource("",
+                query,
+                OC_ALL,
                 std::function < void(std::shared_ptr < OCResource > resource)
-                        > (std::bind(&GroupManager::onFoundResource, this,
-                                std::placeholders::_1, waitsec)));
+                        > (std::bind(&GroupManager::onFoundResource, this, std::placeholders::_1,
+                                waitsec)));
     }
 
-    if (waitsec != -1)
+    if (waitsec >= 0)
     {
         std::thread exec(
                 std::function< void(int second) >(
@@ -234,6 +247,28 @@ OCStackResult GroupManager::findCandidateResources(std::vector< std::string > re
     return OC_STACK_OK;
 }
 
+
+OCStackResult GroupManager::bindResourceToGroup(OCResourceHandle& childHandle, std::shared_ptr< OCResource > resource, OCResourceHandle& collectionHandle)
+{
+
+    OCStackResult result = OCPlatform::registerResource(childHandle, resource);
+
+    cout << "\tresource registed!" << endl;
+
+    if(result == OC_STACK_OK)
+    {
+        OCPlatform::bindResource(collectionHandle, childHandle);
+    }
+    else
+    {
+        cout << "\tresource Error!" << endl;
+    }
+
+    return result;
+ }
+
+
+
 /*
  Presence Check
  */
@@ -277,17 +312,23 @@ void GroupManager::checkCollectionRepresentation(const OCRepresentation& rep,
 {
     std::cout << "\tResource URI: " << rep.getUri() << std::endl;
 
-    /* //bug not found
-     if(rep.hasAttribute("name"))
-     {
-     std::cout << "\tRoom name: " << rep.getValue<std::string>("name") << std::endl;
-     }
-     */
     std::vector< OCRepresentation > children = rep.getChildren();
+    if(children.size() == 0 )
+    {
+        callback("", OC_STACK_ERROR);
+        return;
+    }
 
     for (auto oit = children.begin(); oit != children.end(); ++oit)
     {
-        std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+        if(oit->getUri().find("coap://") == std::string::npos)
+        {
+            std::cout << "The resource with a URI " << oit->getUri() << " is not a remote resource."
+                << " Thus, we ignore to send a request for presence check to the resource.\n";
+
+            continue;
+        }
+
         std::vector< std::string > hostAddressVector = str_split(oit->getUri(), '/');
         std::string hostAddress = "";
         for (unsigned int i = 0; i < hostAddressVector.size(); ++i)
@@ -303,35 +344,44 @@ void GroupManager::checkCollectionRepresentation(const OCRepresentation& rep,
         }
 
         std::vector< std::string > resourceTypes = oit->getResourceTypes();
-        for (unsigned int i = 0; i < resourceTypes.size(); ++i)
+        // for (unsigned int i = 0; i < resourceTypes.size(); ++i)
+        // {
+        //     std::cout << "\t\t\tresourcetype :" << resourceTypes.at(i) << std::endl;
+        // }
+
+        // std::string resourceType = "core.";
+        // resourceType.append(str_split(oit->getUri(), '/').at(4));
+        // std::cout << "\t\tconvertRT : " << resourceType << std::endl;
+        // std::cout << "\t\tresource type front : " << resourceTypes.front() << endl;
+        // std::cout << "\t\thost : " << hostAddress << std::endl;
+        OCPlatform::OCPresenceHandle presenceHandle;
+        OCStackResult result = OC_STACK_ERROR;
+
+        try
+        {
+            result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
+                    // resourceType,
+                    resourceTypes.front(),
+                    OC_ALL,
+                    std::function<
+                            void(OCStackResult result, const unsigned int nonce,
+                                    const std::string& hostAddress) >(
+                            std::bind(&GroupManager::collectionPresenceHandler, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, hostAddress, oit->getUri())));
+        }catch(OCException& e)
         {
-            std::cout << "\t\t\tresourcetype :" << resourceTypes.at(i) << std::endl;
+            std::cout<< "Exception in subscribePresence: "<< e.what() << std::endl;
         }
 
-        std::string resourceType = "core.";
-        resourceType.append(str_split(oit->getUri(), '/').at(4));
-        std::cout << "\t\tconvertRT : " << resourceType << std::endl;
-        std::cout << "\t\thost : " << hostAddress << std::endl;
-        OCPlatform::OCPresenceHandle presenceHandle;
-        OCStackResult result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
-                resourceType,
-                std::function<
-                        void(OCStackResult result, const unsigned int nonce,
-                                const std::string& hostAddress) >(
-                        std::bind(&GroupManager::collectionPresenceHandler, this,
-                                std::placeholders::_1, std::placeholders::_2,
-                                std::placeholders::_3, hostAddress, oit->getUri())));
-
         if (result == OC_STACK_OK)
         {
-            std::cout << "\t\tOK!" << std::endl;
             presenceCallbacks.insert(std::make_pair(oit->getUri(), callback));
         }
         else
         {
             callback("", OC_STACK_ERROR);
         }
-
     }
 }
 
@@ -350,13 +400,17 @@ void GroupManager::onGetForPresence(const HeaderOptions& headerOptions,
     {
         std::cout << "onGET Response error: " << eCode << std::endl;
         callback("", OC_STACK_ERROR);
-        std::exit(-1);
     }
 }
 
 OCStackResult GroupManager::subscribeCollectionPresence(
         std::shared_ptr< OCResource > collectionResource, CollectionPresenceCallback callback)
 {
+    if(callback == NULL || collectionResource == NULL)
+    {
+        return OC_STACK_ERROR;
+    }
+
     OCStackResult result = OC_STACK_OK;
     //callback("core.room",OC_STACK_OK);
 
@@ -381,8 +435,13 @@ std::string GroupManager::getStringFromActionSet(const ActionSet *newActionSet)
 {
     std::string message = "";
 
+    if(newActionSet == NULL)
+        return message;
+
     message = newActionSet->actionsetName;
     message.append("*");
+    message.append(newActionSet->toString());
+    message.append("*");
     for (auto iterAction = newActionSet->listOfAction.begin();
             iterAction != newActionSet->listOfAction.end(); iterAction++)
     {
@@ -410,35 +469,74 @@ std::string GroupManager::getStringFromActionSet(const ActionSet *newActionSet)
     return message;
 }
 
-ActionSet* GroupManager::getActionSetfromString(std::string desc)
-{
+#define DELETE(p) { \
+    delete p; \
+    p = NULL; \
+}
 
+#define DELETEARRAY(p) { \
+    delete[] p; \
+    p = NULL; \
+}
+
+ActionSet* GroupManager::getActionSetfromString(std::string description)
+{
     char *token = NULL;
     char *plainText = NULL;
     char *plainPtr = NULL;
+    char *attr = NULL, *desc = NULL;
 
+    Capability *capa = NULL;
     ActionSet *actionset = new ActionSet();
-    plainText = new char[(desc.length() + 1)];
-    strcpy(plainText, desc.c_str());
+
+    if(actionset == NULL)
+    {
+        goto exit;
+    }
+
+    if(description.empty())
+    {
+        goto exit;
+    }
+    else if(description.at(0) == '*')
+    {
+        goto exit;
+    }
+
+    plainText = new char[(description.length() + 1)];
+    strcpy(plainText, description.c_str());
 
     token = strtok_r(plainText, ACTION_DELIMITER, &plainPtr);
 
     if (token != NULL)
     {
         actionset->actionsetName = std::string(token);
+
+        if((actionset->actionsetName).empty())
+            goto exit;
+
+        token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
+    }
+    else
+    {
+        goto exit;
+    }
+
+    if (token != NULL)
+    {
+        sscanf(token, "%ld %d", &actionset->mDelay, (int*)&actionset->type);
+
         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
     }
     else
     {
-        delete actionset;
-        delete[] plainText;
-        return NULL;
+        goto exit;
     }
 
     while (token)
     {
         char *descPtr = NULL;
-        char *desc = new char[(strlen(token) + 1)];
+        desc = new char[(strlen(token) + 1)];
 
         if (desc != NULL)
         {
@@ -446,83 +544,84 @@ ActionSet* GroupManager::getActionSetfromString(std::string desc)
             strcpy(desc, token);
             token = strtok_r(desc, DESC_DELIMITER, &descPtr);
 
-            // cout << "desc :: " << token << endl;
             while (token != NULL)
             {
                 char *attrPtr = NULL;
-                char *attr = new char[(strlen(token) + 1)];
+                attr = new char[(strlen(token) + 1)];
 
                 strcpy(attr, token);
 
-                // cout << "attr :: " << attr << endl;
-
                 token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
                 while (token != NULL)
                 {
                     if (strcmp(token, "uri") == 0)
                     {
                         token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
-                        action = new Action();
+                        if(token == NULL)
+                        {
+                            goto exit;
+                        }
 
+                        action = new Action();
                         if (action != NULL)
                         {
                             action->target = std::string(token);
                         }
                         else
                         {
-                            delete actionset;
-                            delete[] attr;
-                            delete desc;
-                            delete[] plainText;
-                            return NULL;
+                            goto exit;
                         }
                     }
                     else
                     {
-                        Capability *capa = new Capability();
+                        capa = new Capability();
                         capa->capability = std::string(token);
                         token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
+
+                        if( token == NULL )
+                            goto exit;
+
                         capa->status = std::string(token);
 
                         if (action != NULL)
-                        {
                             action->listOfCapability.push_back(capa);
-                        }
                         else
-                        {
-                            delete capa;
-                            delete actionset;
-                            delete[] attr;
-                            delete[] plainText;
-                            delete desc;
-                            return NULL;
-                        }
+                            goto exit;
                     }
 
                     token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
                 }
-
-                delete[] attr;
+                DELETEARRAY(attr);
                 token = strtok_r(NULL, DESC_DELIMITER, &descPtr);
             }
 
-            actionset->listOfAction.push_back(action);
+            if( action != NULL )
+                actionset->listOfAction.push_back(action);
+            else
+                goto exit;
             //delete action;
         }
         else
         {
-            delete actionset;
-            delete[] plainText;
-            return NULL;
+            goto exit;
+
         }
 
-        delete[] desc;
+        DELETEARRAY(desc);
 
         token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
     }
 
-    delete plainText;
+    DELETE(plainText);
     return actionset;
+
+exit:
+    DELETE(capa)
+    DELETE(actionset)
+    DELETEARRAY(attr);
+    DELETEARRAY(plainText);
+    DELETEARRAY(desc);
+    return NULL;
 }
 
 OCStackResult GroupManager::addActionSet(std::shared_ptr< OCResource > resource,
@@ -531,11 +630,15 @@ OCStackResult GroupManager::addActionSet(std::shared_ptr< OCResource > resource,
     // BUILD message of ActionSet which it is included delimiter.
     if ((resource != NULL) && (newActionSet != NULL))
     {
+        if(newActionSet->mDelay < 0)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+
         std::string message = getStringFromActionSet(newActionSet);
-        OCRepresentation rep;
 
+        OCRepresentation rep;
         rep.setValue("ActionSet", message);
-
         return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
                 QueryParamsMap(), cb);
     }
@@ -562,6 +665,47 @@ OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resou
     }
 }
 
+OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
+        std::string actionsetName, long int delay, PostCallback cb)
+{
+    if(delay <= 0 )
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (resource != NULL)
+    {
+        std::string value = actionsetName;
+        value.append("*");
+        value.append(std::to_string(delay));
+
+        OCRepresentation rep;
+        rep.setValue("DoScheduledAction", value);
+        return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
+                QueryParamsMap(), cb);
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+}
+
+OCStackResult GroupManager::cancelActionSet(std::shared_ptr< OCResource > resource,
+        std::string actionsetName, PostCallback cb)
+{
+    if (resource != NULL)
+    {
+        OCRepresentation rep;
+
+        rep.setValue("CancelAction", actionsetName);
+        return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
+                QueryParamsMap(), cb);
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+}
+
 OCStackResult GroupManager::getActionSet(std::shared_ptr< OCResource > resource,
         std::string actionsetName, PostCallback cb)
 {
@@ -597,4 +741,3 @@ OCStackResult GroupManager::deleteActionSet(std::shared_ptr< OCResource > resour
         return OC_STACK_ERROR;
     }
 }
-}
index d0dad45..c8a8f9d 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file   GroupManager.h
-
-/// @brief  This file contains the declaration of classes and its members related to GroupManager
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * GroupManager.
+ */
 
 #ifndef __OC_GROUPMANAGER__
 #define __OC_GROUPMANAGER__
@@ -29,6 +32,7 @@
 #include <vector>
 #include <map>
 #include <cstdlib>
+#include <ActionSet.h>
 #include "OCPlatform.h"
 #include "OCApi.h"
 
@@ -43,45 +47,6 @@ typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const
 typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const int) > PostCallback;
 typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const int) > PutCallback;
 
-class Capability
-{
-public:
-    std::string capability;
-    std::string status;
-};
-
-class Action
-{
-public:
-    Action() :
-            target("")
-    {
-    }
-    ~Action()
-    {
-        listOfCapability.clear();
-    }
-    std::string target;
-
-    std::vector< Capability* > listOfCapability;
-};
-
-class ActionSet
-{
-public:
-    ActionSet() :
-            actionsetName("")
-    {
-    }
-    ~ActionSet()
-    {
-        listOfAction.clear();
-    }
-    std::string actionsetName;
-
-    std::vector< Action* > listOfAction;
-};
-
 class GroupManager
 {
 public:
@@ -117,6 +82,9 @@ public:
     OCStackResult subscribeCollectionPresence(std::shared_ptr< OCResource > resource,
             CollectionPresenceCallback);
 
+    OCStackResult bindResourceToGroup(OCResourceHandle& childHandle,
+            std::shared_ptr< OCResource > resource, OCResourceHandle& collectionHandle);
+
 private:
 
     void onFoundResource(std::shared_ptr< OCResource > resource, int waitsec);
@@ -142,6 +110,10 @@ public:
             const ActionSet* newActionSet, PutCallback cb);
     OCStackResult executeActionSet(std::shared_ptr< OCResource > resource,
             std::string actionsetName, PostCallback cb);
+    OCStackResult executeActionSet(std::shared_ptr< OCResource > resource,
+            std::string actionsetName, long int delay, PostCallback cb);
+    OCStackResult cancelActionSet(std::shared_ptr< OCResource > resource,
+            std::string actionsetName, PostCallback cb);
     OCStackResult getActionSet(std::shared_ptr< OCResource > resource, std::string actionsetName,
             PostCallback cb);
     OCStackResult deleteActionSet(std::shared_ptr< OCResource > resource, std::string actionsetName,
index dd2c96c..b60c045 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file    GroupSynchronization.cpp
-/// @brief
-
 #include "GroupSynchronization.h"
+#include "logger.h"
 
 using namespace OC;
+using namespace std;
+
+#define TAG "GROUP_SYNC"
 
 namespace OIC
 {
+    GroupSynchronization* GroupSynchronization::groupSyncnstance = NULL;
+    bool GroupSynchronization::bIsFinding = false;
 
-GroupSynchronization* GroupSynchronization::groupSyncnstance = NULL;
-
-GroupSynchronization* GroupSynchronization::getInstance()
-{
-    if (groupSyncnstance == NULL)
+    GroupSynchronization* GroupSynchronization::getInstance()
     {
-        groupSyncnstance = new GroupSynchronization();
+        if (groupSyncnstance == NULL)
+        {
+            groupSyncnstance = new GroupSynchronization();
+        }
+        return groupSyncnstance;
     }
-    return groupSyncnstance;
-}
 
-void GroupSynchronization::deleteInstance()
-{
-    if (groupSyncnstance)
+    void GroupSynchronization::deleteInstance()
     {
-        delete groupSyncnstance;
-        groupSyncnstance = NULL;
+        if (groupSyncnstance)
+        {
+            delete groupSyncnstance;
+            groupSyncnstance = NULL;
+        }
     }
-}
 
-OCStackResult GroupSynchronization::findGroup(
-        std::vector< std::string > collectionResourceTypes, FindCallback callback)
-{
-    cout << "GroupSynchronization::findGroup" << endl;
+    OCStackResult GroupSynchronization::findGroup(
+            std::vector< std::string > collectionResourceTypes, FindCallback callback)
+    {
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::findGroup");
 
-    foundGroupResourceList.clear();
+        if(bIsFinding)
+        {
+            OC_LOG(DEBUG, TAG, "It was searching already.");
+            return OC_STACK_ERROR;
+        }
 
-    findCallback = callback;
+        std::lock_guard < std::mutex > guard(foundGroupMutex);
+        foundGroupResourceList.clear();
+        findCallback = callback;
 
-    for (unsigned int i = 0; i < collectionResourceTypes.size(); ++i)
-    {
-        std::string query = "coap://224.0.1.187/oc/core?rt=";
-        query.append(collectionResourceTypes.at(i));
-        cout << "GroupSynchronization::findGroup - " << query << endl;
+        if (findCallback == NULL)
+        {
+            OC_LOG(DEBUG, TAG, "Find callback is NULL.");
+            return OC_STACK_ERROR;
+        }
 
-        OCPlatform::findResource("", query,
-                std::bind(&GroupSynchronization::onFindGroup, this, std::placeholders::_1));
-    }
+        for (unsigned int i = 0; i < collectionResourceTypes.size(); ++i)
+        {
 
-    // thread to check if GroupSynchronization::onFoundGroup is called or not.
-    std::thread t(std::bind(&GroupSynchronization::checkFindGroup, this));
-    t.detach();
+            std::string query = OC_MULTICAST_DISCOVERY_URI;
+            query.append("?rt=");
+            query.append(collectionResourceTypes.at(i));
 
-    return OC_STACK_OK;
-}
+            OCPlatform::findResource("", query,
+                    OC_ALL,
+                    std::bind(&GroupSynchronization::onFindGroup, this,
+                        std::placeholders::_1));
+        }
 
-OCStackResult GroupSynchronization::createGroup(std::string collectionResourceType)
-{
-    foundGroupResourceList.clear();
+        bIsFinding = true;
 
-    OCResourceHandle collectionResHandle = NULL;
-    OCResourceHandle groupSyncResHandle = NULL;
+        // thread to check if GroupSynchronization::onFoundGroup is called or not.
+        std::thread t(std::bind(&GroupSynchronization::checkFindGroup, this));
+        t.detach();
+
+        return OC_STACK_OK;
+    }
 
-    if (0 != collectionResourceType.length())
+    OCStackResult GroupSynchronization::createGroup(std::string collectionResourceType)
     {
-        cout << "GroupSynchronization::createGroup - The created group is added." << endl;
+        std::lock_guard < std::mutex > guard(foundGroupMutex);
+        foundGroupResourceList.clear();
+
+        OCResourceHandle collectionResHandle = NULL;
+        OCResourceHandle groupSyncResHandle = NULL;
+
+        if (0 == collectionResourceType.length())
+        {
+            OC_LOG(DEBUG, TAG,
+                "GroupSynchronization::createGroup : Error! Input params are wrong.");
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::createGroup - The created group is added.");
 
         OCStackResult result;
 
         // creating master collection resource
         std::string collectionUri = "/" + collectionResourceType;
-        int i;
+        std::size_t i;
         while ((i = collectionUri.find(".")) != std::string::npos)
         {
             collectionUri.replace(i, 1, "/");
         }
-        cout << "GroupSynchronization::createGroup : collection uri - " << collectionUri
-                << ", type - " << collectionResourceType << endl;
+
+        OC_LOG_V(DEBUG, TAG, "GroupSynchronization::createGroup : collection uri - %s, type - %s",
+            collectionUri.c_str(), collectionResourceType.c_str());
 
         std::string resourceInterface = DEFAULT_INTERFACE;
 
         result = OCPlatform::registerResource(collectionResHandle, collectionUri,
-                collectionResourceType, resourceInterface, NULL,
-                OC_DISCOVERABLE | OC_OBSERVABLE);
+                collectionResourceType, resourceInterface, NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
         if (result != OC_STACK_OK)
         {
-            cout << "To register resource (" << collectionUri << ") was unsuccessful. result - "
-                    << result << endl;
+            OC_LOG_V(DEBUG, TAG, "To register resource (%s) was unsuccessful. result - %d",
+                collectionUri.c_str(), result);
             goto Error;
         }
 
-        OCPlatform::bindInterfaceToResource(collectionResHandle, GROUP_INTERFACE);
-        if (result != OC_STACK_OK)
         {
-            cout << "To bind Interface (collection) was unsuccessful. result - " << result
-                    << endl;
-        }
-
-        collectionResourceHandleList[collectionResourceType] = collectionResHandle;
+            OCPlatform::bindInterfaceToResource(collectionResHandle, GROUP_INTERFACE);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, TAG,
+                    "To bind Interface (collection) was unsuccessful. result - %d",
+                    result);
+            }
 
-        // creating master group sync resource
-        std::string groupSyncUri = collectionUri + "/groupsync";
-        std::string groupSyncResType = collectionResourceType + ".groupsync";
+            collectionResourceHandleList[collectionResourceType] = collectionResHandle;
 
-//        cout << "GroupSynchronization::createGroup : groupSync uri - " << groupSyncUri
-//                << ", type - " << collectionResourceType << endl;
+            // creating master group sync resource
+            std::string groupSyncUri = collectionUri + "/groupsync";
+            std::string groupSyncResType = collectionResourceType + ".groupsync";
 
-        result = OCPlatform::registerResource(groupSyncResHandle, groupSyncUri,
-                groupSyncResType, resourceInterface,
-                std::bind(&GroupSynchronization::groupEntityHandler, this,
-                        std::placeholders::_1), OC_DISCOVERABLE | OC_OBSERVABLE);
-        if (result != OC_STACK_OK)
-        {
-            cout << "To register resource (groupsync) was unsuccessful. result - " << result
-                    << endl;
-            goto Error;
-        }
+            result = OCPlatform::registerResource(groupSyncResHandle, groupSyncUri,
+                    groupSyncResType, resourceInterface,
+                    std::bind(&GroupSynchronization::groupEntityHandler, this,
+                            std::placeholders::_1), OC_DISCOVERABLE | OC_OBSERVABLE);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, TAG,
+                    "To register resource (groupsync) was unsuccessful. result - %d", result);
+                goto Error;
+            }
 
-        groupSyncResourceHandleList[collectionResourceType] = groupSyncResHandle;
+            groupSyncResourceHandleList[collectionResourceType] = groupSyncResHandle;
 
-        return OC_STACK_OK;
-    }
-    else
-    {
-        cout << "GroupSynchronization::createGroup : Error! Input params are wrong." << endl;
-        return OC_STACK_INVALID_PARAM;
-    }
+            return OC_STACK_OK;
+        }
+        Error:
 
-    Error:
+        if (collectionResHandle)
+        {
+            OCPlatform::unregisterResource(collectionResHandle);
+            auto iterator = collectionResourceHandleList.find(collectionResourceType);
+            if (iterator != collectionResourceHandleList.end())
+            {
+                collectionResourceHandleList.erase(iterator);
+            }
+        }
 
-    if (collectionResHandle)
-    {
-        OCPlatform::unregisterResource(collectionResHandle);
-        auto iterator = collectionResourceHandleList.find(collectionResourceType);
-        if (iterator != collectionResourceHandleList.end())
+        if (groupSyncResHandle)
         {
-            collectionResourceHandleList.erase(iterator);
+            OCPlatform::unregisterResource(groupSyncResHandle);
+            auto iterator = groupSyncResourceHandleList.find(collectionResourceType);
+            if (iterator != groupSyncResourceHandleList.end())
+            {
+                groupSyncResourceHandleList.erase(iterator);
+            }
         }
+
+        return OC_STACK_NO_RESOURCE;
     }
 
-    if (groupSyncResHandle)
+    OCStackResult GroupSynchronization::joinGroup(std::string collectionResourceType,
+            OCResourceHandle resourceHandle)
     {
-        OCPlatform::unregisterResource(groupSyncResHandle);
-        auto iterator = groupSyncResourceHandleList.find(collectionResourceType);
-        if (iterator != groupSyncResourceHandleList.end())
+        std::lock_guard < std::mutex > guard(foundGroupMutex);
+        if ((0 == collectionResourceType.length()) || (!resourceHandle))
         {
-            groupSyncResourceHandleList.erase(iterator);
+            OC_LOG(DEBUG, TAG,
+                "GroupSynchronization::joinGroup : Error! input params are wrong.");
+            return OC_STACK_INVALID_PARAM;
         }
-    }
-
-    return OC_STACK_NO_RESOURCE;
-}
 
-OCStackResult GroupSynchronization::joinGroup(std::string collectionResourceType,
-        OCResourceHandle resourceHandle)
-{
-    if ((0 != collectionResourceType.length()) && (resourceHandle))
-    {
         auto resIt = collectionResourceHandleList.find(collectionResourceType);
-        if (resIt == groupSyncResourceHandleList.end())
+        if (resIt == collectionResourceHandleList.end())
         {
-            cout << "GroupSynchronization::joinGroup : error! There is no collection to join"
-                    << endl;
+            OC_LOG(DEBUG, TAG,
+                "GroupSynchronization::joinGroup : error! There is no collection to join");
             return OC_STACK_INVALID_PARAM;
         }
 
         OCResourceHandle collectionResHandle = resIt->second;
-
-        OCStackResult result = OCPlatform::bindResource(collectionResHandle, resourceHandle);
-        if (result != OC_STACK_OK)
-        {
-            cout << "GroupSynchronization::joinGroup : To bind resource was unsuccessful."
-                    << "result - " << result << endl;
-            return OC_STACK_ERROR;
+        try{
+            OCStackResult result = OCPlatform::bindResource(collectionResHandle, resourceHandle);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, TAG,
+                    "GroupSynchronization::joinGroup : To bind resource was unsuccessful." \
+                    " result - %d", result);
+                return OC_STACK_ERROR;
+            }
+        } catch(OCException &e) {
+            return OC_STACK_INVALID_PARAM;
         }
-        cout << "GroupSynchronization::joinGroup : "
-                << "To bind collectionResHandle and resourceHandle" << endl;
+
+        OC_LOG(DEBUG, TAG,
+            "GroupSynchronization::joinGroup : To bind collectionResHandle and resourceHandle");
 
         std::vector< OCResourceHandle > childHandleList;
 
@@ -210,22 +238,21 @@ OCStackResult GroupSynchronization::joinGroup(std::string collectionResourceType
         deviceResourceHandleList.push_back(resourceHandle);
 
         debugGroupSync();
-    }
-    else
-    {
-        cout << "GroupSynchronization::joinGroup : Error! input params are wrong." << endl;
-        return OC_STACK_INVALID_PARAM;
-    }
 
-    return OC_STACK_OK;
-}
+        return OC_STACK_OK;
+    }
 
-OCStackResult GroupSynchronization::joinGroup(const std::shared_ptr< OCResource > resource,
-        OCResourceHandle resourceHandle)
-{
-    if ((resource) && (resourceHandle))
+    OCStackResult GroupSynchronization::joinGroup(const std::shared_ptr< OCResource > resource,
+            OCResourceHandle resourceHandle)
     {
-        cout << "GroupSynchronization::joinGroup" << endl;
+        std::lock_guard < std::mutex > guard(foundGroupMutex);
+        if ((!resource) || (!resourceHandle))
+        {
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::joinGroup : Error! Input params are wrong.");
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::joinGroup");
 
         // making representation to join group
         std::string method = "joinGroup";
@@ -238,9 +265,9 @@ OCStackResult GroupSynchronization::joinGroup(const std::shared_ptr< OCResource
         rep.setValue("collectionResourceType", type[0]);
         rep.setValue("resourceType", resourceType);
 
-        cout << "\tmethod - " << method << endl;
-        cout << "\tcollectionResourceType - " << type[0] << endl;
-        cout << "\tresourceType - " << resourceType << endl;
+        OC_LOG_V(DEBUG, TAG, "\tmethod - %s", method.c_str());
+        OC_LOG_V(DEBUG, TAG, "\tcollectionResourceType - %s", type[0].c_str());
+        OC_LOG_V(DEBUG, TAG, "\tresourceType - %s", resourceType.c_str());
 
         // creating group sync resource with the received collection resource.
         // entity handler of group sync is used to join group.
@@ -258,11 +285,18 @@ OCStackResult GroupSynchronization::joinGroup(const std::shared_ptr< OCResource
         std::vector< std::string > resourceInterface;
         resourceInterface.push_back(DEFAULT_INTERFACE);
 
-        OCResource::Ptr groupSyncResource = OCPlatform::constructResourceObject(host, uri, 1,
-                resourceTypes, resourceInterface);
+        OCResource::Ptr groupSyncResource =
+                        OCPlatform::constructResourceObject(host, uri,
+
+                            OC_ALL, false,
+                            resourceTypes, resourceInterface);
+
+        // OCResource::Ptr groupSyncResource = OCPlatform::constructResourceObject(host, uri,
+        //         OC_WIFI, false, resourceTypes, resourceInterface);
+
         groupSyncResourceList[type[0]] = groupSyncResource;
 
-        cout << "GroupSynchronization::joinGroup : creating groupSyncResource." << endl;
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::joinGroup : creating groupSyncResource.");
 
         // Create QueryParameters Map and add query params (if any)
         QueryParamsMap queryParamsMap;
@@ -273,13 +307,14 @@ OCStackResult GroupSynchronization::joinGroup(const std::shared_ptr< OCResource
                         std::placeholders::_2, std::placeholders::_3));
         if (OC_STACK_OK == result)
         {
-            cout << "GroupSynchronization::joinGroup : groupSyncResource->put was successful."
-                    << endl;
+            OC_LOG(DEBUG, TAG,
+                "GroupSynchronization::joinGroup : groupSyncResource->put was successful.");
         }
         else
         {
-            cout << "GroupSynchronization::joinGroup : "
-                    << "groupSyncResource->put was unsuccessful. result - " << result << endl;
+            OC_LOG_V(DEBUG, TAG,
+                "GroupSynchronization::joinGroup : groupSyncResource->put was unsuccessful." \
+                "result - %d", result);
         }
 
         // saving the remote collection resource.
@@ -291,23 +326,22 @@ OCStackResult GroupSynchronization::joinGroup(const std::shared_ptr< OCResource
 
         return OC_STACK_OK;
     }
-    else
-    {
-        cout << "GroupSynchronization::joinGroup : Error! Input params are wrong." << endl;
-        return OC_STACK_INVALID_PARAM;
-    }
-}
 
-OCStackResult GroupSynchronization::leaveGroup(std::string collectionResourceType,
-        OCResourceHandle resourceHandle)
-{
-    if ((0 != collectionResourceType.length()) && (resourceHandle))
+    OCStackResult GroupSynchronization::leaveGroup(std::string collectionResourceType,
+            OCResourceHandle resourceHandle)
     {
-        cout << "GroupSynchronization::leaveGroup : collectionResourceType - "
-                << collectionResourceType << endl;
+        if ((0 == collectionResourceType.length()) || (!resourceHandle))
+        {
+            OC_LOG(DEBUG, TAG,
+                "GroupSynchronization::leaveGroup : Error! Input params are wrong.");
+            return OC_STACK_INVALID_PARAM;
+        }
 
-        OCResourceHandle collectionResHandle;
+        OC_LOG_V(DEBUG, TAG,
+            "GroupSynchronization::leaveGroup : collectionResourceType - %s",
+            collectionResourceType.c_str());
 
+        OCResourceHandle collectionResHandle;
         auto handleIt = groupSyncResourceHandleList.find(collectionResourceType);
 
         // if groupSyncResourceHandleList has resourceType,
@@ -317,57 +351,71 @@ OCStackResult GroupSynchronization::leaveGroup(std::string collectionResourceTyp
             handleIt = collectionResourceHandleList.find(collectionResourceType);
             if (handleIt == collectionResourceHandleList.end())
             {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "Error! There is no collection resource handle to leave." << endl;
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::leaveGroup : Error!" \
+                    "There is no collection resource handle to leave.");
                 return OC_STACK_INVALID_PARAM;
             }
 
             collectionResHandle = handleIt->second;
-//            cout << "GroupSynchronization::leaveGroup : collection handle uri - "
-//                    << OCGetResourceUri(collectionResHandle) << endl;
+            if(collectionResHandle == NULL)
+                return OC_STACK_INVALID_PARAM;
 
-            OCStackResult result = OCPlatform::unbindResource(collectionResHandle,
-                    resourceHandle);
-            if (OC_STACK_OK == result)
+            OCStackResult result;
+            try
             {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "To unbind resource was successful." << endl;
-            }
-            else
-            {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "To unbind resource was unsuccessful. result - " << result << endl;
+                result = OCPlatform::unbindResource(collectionResHandle, resourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    OC_LOG(DEBUG, TAG,
+                        "GroupSynchronization::leaveGroup : To unbind resource was successful.");
+                }
+                else
+                {
+                    OC_LOG_V(DEBUG, TAG, "GroupSynchronization::leaveGroup : " \
+                            "To unbind resource was unsuccessful. result - %d", result);
+                    return result;
+                }
+            } catch(OCException &e) {
+                OC_LOG_V(DEBUG, TAG, "ERROR : %s", e.reason().c_str());
+                return OC_STACK_NO_RESOURCE;
             }
 
-            auto It = std::find(deviceResourceHandleList.begin(),
-                    deviceResourceHandleList.end(), resourceHandle);
+            auto It = std::find(deviceResourceHandleList.begin(), deviceResourceHandleList.end(),
+                    resourceHandle);
             if (It == deviceResourceHandleList.end()) // there is no resource handle to find
             {
-                result = OCPlatform::unregisterResource(resourceHandle);
-                if (OC_STACK_OK == result)
+                try
                 {
-                    cout << "GroupSynchronization::leaveGroup : "
-                            << "To unregister resource was successful." << endl;
-                }
-                else
+                    result = OCPlatform::unregisterResource(resourceHandle);
+                    if (OC_STACK_OK == result)
+                    {
+                        OC_LOG(DEBUG, TAG, "GroupSynchronization::leaveGroup : " \
+                                "To unregister resource was successful.");
+                    }
+                    else
+                    {
+                        OC_LOG_V(DEBUG, TAG, "GroupSynchronization::leaveGroup : " \
+                            "To unregister resource was unsuccessful. result - %d", result);
+                        return result;
+                    }
+                } catch(OCException &e)
                 {
-                    cout << "GroupSynchronization::leaveGroup : "
-                            << "To unregister resource was unsuccessful. result - " << result
-                            << endl;
+                    OC_LOG_V(DEBUG, TAG, "ERROR : %s", e.reason().c_str());
+                    return OC_STACK_NO_RESOURCE;
                 }
             }
             else
             {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "This resource cannot be unregistered." << endl;
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::leaveGroup : " \
+                    "This resource cannot be unregistered.");
                 deviceResourceHandleList.erase(It);
             }
 
             auto handleListIt = childResourceHandleList.find(collectionResHandle);
             if (handleListIt == childResourceHandleList.end())
             {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "Error! There is no child resource list to delete." << endl;
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::leaveGroup : " \
+                    "Error! There is no child resource list to delete.");
                 return OC_STACK_INVALID_PARAM;
             }
 
@@ -375,8 +423,8 @@ OCStackResult GroupSynchronization::leaveGroup(std::string collectionResourceTyp
             auto childIt = std::find(childList.begin(), childList.end(), resourceHandle);
             if (childIt != childList.end())
             {
-                cout << "GroupSynchronization::groupEntityHandler : "
-                        << "Found! The resource to leave is found." << endl;
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::groupEntityHandler : " \
+                    "Found! The resource to leave is found.");
                 childList.erase(childIt);
             }
 
@@ -384,90 +432,127 @@ OCStackResult GroupSynchronization::leaveGroup(std::string collectionResourceTyp
 
             debugGroupSync();
         }
-        else // requesting to unbind this resourceHandle to the remote collection resource
+
+        return OC_STACK_OK;
+    }
+
+OCStackResult GroupSynchronization::leaveGroup(
+        const std::shared_ptr<OCResource> resource,
+        std::string collectionResourceType, OCResourceHandle resourceHandle)
+    {
+        if ((!resource) || (!resourceHandle))
         {
-            auto resourceIt = groupSyncResourceList.find(collectionResourceType);
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::joinGroup : Error! Input params are wrong.");
+            return OC_STACK_INVALID_PARAM;
+        }
 
-            if (resourceIt == groupSyncResourceList.end())
-            {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "Error! There is no collectin resource type to leave." << endl;
-                return OC_STACK_INVALID_PARAM;
-            }
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::joinGroup");
 
-            std::shared_ptr< OCResource > resource = resourceIt->second;
-//            cout << "GroupSynchronization::leaveGroup : group sync resource uri - "
-//                    << resource->uri() << endl;
+        // making representation to join group
+        std::vector< std::string > type = resource->getResourceTypes();
+        std::string host = resource->host();
+        std::string uri = resource->uri() + "/groupsync";
 
-            handleIt = collectionResourceHandleList.find(collectionResourceType);
-            if (handleIt == collectionResourceHandleList.end())
-            {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "Error! There is no collection resource handle to leave." << endl;
-                return OC_STACK_INVALID_PARAM;
-            }
+        std::vector< std::string > resourceTypes;
+        std::string temp;
+        for (unsigned int i = 0; i < type.size(); ++i)
+        {
+            temp = type[0] + ".groupsync";
+            resourceTypes.push_back(temp);
+        }
 
-            collectionResHandle = handleIt->second;
+        std::vector< std::string > resourceInterface;
+        resourceInterface.push_back(DEFAULT_INTERFACE);
+
+        OCResource::Ptr groupSyncResource;
+        groupSyncResource = OCPlatform::constructResourceObject(host, uri,
+                OC_ALL, false,
+                resourceTypes, resourceInterface);
+        // groupSyncResource = OCPlatform::constructResourceObject(host, uri,
+        //         OC_WIFI, false, resourceTypes, resourceInterface);
+
+        // making representation to leave group
+        std::string method = "leaveGroup";
+//        std::string type = OCGetResourceTypeName(collectionResourceType, 0);
+        std::string resourceType;
+        resourceType.append(OCGetResourceTypeName(resourceHandle, 0));
+
+        OCRepresentation rep;
+        rep.setValue("method", method);
+        rep.setValue("collectionResourceType", collectionResourceType);
+        rep.setValue("resourceType", resourceType);
+
+        OC_LOG_V(DEBUG, TAG, "\tmethod - %s", method.c_str());
+        OC_LOG_V(DEBUG, TAG, "\tcollectionResourceType - %s", collectionResourceType.c_str());
+        OC_LOG_V(DEBUG, TAG, "\tresourceType - %s", resourceType.c_str());
+
+        QueryParamsMap queryParamsMap;
+
+        // request to leave group to the remote group sync resource
+        OCStackResult result = groupSyncResource->put(rep, queryParamsMap,
+                std::bind(&GroupSynchronization::onLeaveGroup, this, std::placeholders::_1,
+                        std::placeholders::_2, std::placeholders::_3));
+        if (OC_STACK_OK == result)
+        {
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::leaveGroup : " \
+                "groupSyncResource->put was successful.");
+        }
+        else
+        {
+            OC_LOG_V(DEBUG, TAG, "GroupSynchronization::leaveGroup : " \
+                "groupSyncResource->put was unsuccessful. result - %d", result);
+        }
+        return result;
+    }
 
-            // making representation to leave group
-            std::string method = "leaveGroup";
-            std::string type = OCGetResourceTypeName(collectionResHandle, 0);
-            std::string resourceType;
-            resourceType.append(OCGetResourceTypeName(resourceHandle, 0));
+    void GroupSynchronization::deleteGroup(std::string collectionResourceType)
+    {
+        if (0 == collectionResourceType.length())
+        {
+            OC_LOG(DEBUG, TAG,
+                "GroupSynchronization::deleteGroup : Error! Input params are wrong.");
+            return;
+        }
 
-            OCRepresentation rep;
-            rep.setValue("method", method);
-            rep.setValue("collectionResourceType", type);
-            rep.setValue("resourceType", resourceType);
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::deleteGroup");
 
-            cout << "\tmethod - " << method << endl;
-            cout << "\tcollectionResourceType - " << type << endl;
-            cout << "\tresourceType - " << resourceType << endl;
+        OCStackResult result;
+        OCResourceHandle resourceHandle;
 
-            QueryParamsMap queryParamsMap;
+        auto handleIt = groupSyncResourceHandleList.find(collectionResourceType);
 
-            // request to leave group to the remote group sync resource
-            OCStackResult result = resource->put(rep, queryParamsMap,
-                    std::bind(&GroupSynchronization::onLeaveGroup, this, std::placeholders::_1,
-                            std::placeholders::_2, std::placeholders::_3));
+        // if groupSyncResourceHandleList has resourceType,
+        // group sync of this app created collection resource.
+        if (handleIt != groupSyncResourceHandleList.end())
+        {
+            resourceHandle = handleIt->second; // group sync resource handle
+            result = OCPlatform::unregisterResource(resourceHandle);
             if (OC_STACK_OK == result)
             {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "groupSyncResource->put was successful." << endl;
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                    "To unregister group sync resource handle was successful.");
             }
             else
             {
-                cout << "GroupSynchronization::leaveGroup : "
-                        << "groupSyncResource->put was unsuccessful. result - " << result
-                        << endl;
+                OC_LOG_V(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                        "To unregister group sync resource handle was unsuccessful. " \
+                        "result - %d", result);
             }
 
-            // deleting all remote resources. These are copied in onGetJoinedRemoteChild()
-            deleteGroup(collectionResourceType);
+            groupSyncResourceHandleList.erase(handleIt);
         }
-    }
-    else
-    {
-        cout << "GroupSynchronization::leaveGroup : Error! Input params are wrong." << endl;
-        return OC_STACK_INVALID_PARAM;
-    }
-
-    return OC_STACK_OK;
-}
-
-void GroupSynchronization::deleteGroup(std::string collectionResourceType)
-{
-    if (0 != collectionResourceType.length())
-    {
-        cout << "GroupSynchronization::deleteGroup" << endl;
 
-        OCStackResult result;
+        auto resourceIt = groupSyncResourceList.find(collectionResourceType);
+        if (resourceIt != groupSyncResourceList.end())
+        {
+            groupSyncResourceList.erase(resourceIt);
+        }
 
-        auto handleIt = collectionResourceHandleList.find(collectionResourceType);
+        handleIt = collectionResourceHandleList.find(collectionResourceType);
         if (handleIt == collectionResourceHandleList.end())
         {
-            cout << "GroupSynchronization::deleteGroup : "
-                    << "Error! There is no collection resource handle to delete." << endl;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                "Error! There is no collection resource handle to delete.");
             return;
         }
         OCResourceHandle collectionResHandle = handleIt->second;
@@ -477,10 +562,26 @@ void GroupSynchronization::deleteGroup(std::string collectionResourceType)
         auto handleListIt = childResourceHandleList.find(collectionResHandle);
         if (handleListIt == childResourceHandleList.end())
         {
-            cout << "GroupSynchronization::deleteGroup : "
-                    << "Error! There is no child resource list to delete." << endl;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                "There is no child resource list to delete.");
+
+            result = OCPlatform::unregisterResource(collectionResHandle);
+            if (result == OC_STACK_OK)
+            {
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                     "To unregister collection resource handle was successful.");
+            }
+            else
+            {
+                OC_LOG_V(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                    " To unregister collection resource handle was unsuccessful. result - %d",
+                    result);
+            }
+
+            debugGroupSync();
             return;
         }
+
         std::vector< OCResourceHandle > childList = handleListIt->second;
 
         childResourceHandleList.erase(handleListIt);
@@ -488,29 +589,28 @@ void GroupSynchronization::deleteGroup(std::string collectionResourceType)
         result = OCPlatform::unbindResources(collectionResHandle, childList);
         if (OC_STACK_OK == result)
         {
-            cout << "GroupSynchronization::deleteGroup : "
-                    << "To unbind resources was successful." << endl;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                "To unbind resources was successful.");
         }
         else
         {
-            cout << "GroupSynchronization::deleteGroup : "
-                    << "To unbind resources was unsuccessful. result - " << result << endl;
+            OC_LOG_V(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                "To unbind resources was unsuccessful. result - %d", result);
         }
 
         result = OCPlatform::unregisterResource(collectionResHandle);
-        if (result != OC_STACK_OK)
+        if (result == OC_STACK_OK)
         {
-            cout << "GroupSynchronization::deleteGroup : "
-                    << "To unregister collection resource handle was successful." << endl;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                "To unregister collection resource handle was successful.");
         }
         else
         {
-            cout << "GroupSynchronization::deleteGroup : "
-                    << " To unregister collection resource handle was unsuccessful. result - "
-                    << result << endl;
+            OC_LOG_V(DEBUG, TAG, "GroupSynchronization::deleteGroup : " \
+                " To unregister collection resource handle was unsuccessful. result - %d",
+                result);
         }
 
-        OCResourceHandle resourceHandle;
         std::vector< OCResourceHandle >::iterator It;
 
         for (unsigned int i = 0; i < childList.size(); i++)
@@ -528,556 +628,513 @@ void GroupSynchronization::deleteGroup(std::string collectionResourceType)
                 result = OCPlatform::unregisterResource(resourceHandle);
                 if (OC_STACK_OK == result)
                 {
-                    cout << "GroupSynchronization::deleteGroup : UnregisterResource(" << i + 1
-                            << ") was successful." << endl;
+                    OC_LOG_V(DEBUG, TAG,
+                        "GroupSynchronization::deleteGroup : UnregisterResource(%d)" \
+                        " was successful.", i + 1);
                 }
                 else
                 {
-                    cout << "GroupSynchronization::deleteGroup : UnregisterResource(" << i + 1
-                            << ") was unsuccessful. result - " << result << endl;
+                    OC_LOG_V(DEBUG, TAG,
+                        "GroupSynchronization::deleteGroup : UnregisterResource(%d)" \
+                        " was unsuccessful. result - ", i + 1, result);
                 }
             }
         }
 
-        handleIt = groupSyncResourceHandleList.find(collectionResourceType);
-
-        // if groupSyncResourceHandleList has resourceType,
-        // group sync of this app created collection resource.
-        if (handleIt != groupSyncResourceHandleList.end())
-        {
-            resourceHandle = handleIt->second; // group sync resource handle
-            result = OCPlatform::unregisterResource(resourceHandle);
-            if (OC_STACK_OK == result)
-            {
-                cout << "GroupSynchronization::deleteGroup : "
-                        << "To unregister group sync resource handle was successful." << endl;
-            }
-            else
-            {
-                cout << "GroupSynchronization::deleteGroup : "
-                        << "To unregister group sync resource handle was unsuccessful. "
-                        << "result - " << result << endl;
-            }
-
-            groupSyncResourceHandleList.erase(handleIt);
-        }
-
-        auto resourceIt = groupSyncResourceList.find(collectionResourceType);
-        if (resourceIt != groupSyncResourceList.end())
-        {
-            groupSyncResourceList.erase(resourceIt);
-        }
-
         debugGroupSync();
     }
-    else
+
+    std::map< std::string, OCResourceHandle > GroupSynchronization::getGroupList()
     {
-        cout << "GroupSynchronization::deleteGroup : Error! Input params are wrong." << endl;
+        return collectionResourceHandleList;
     }
-}
 
-std::map< std::string, OCResourceHandle > GroupSynchronization::getGroupList()
-{
-    return collectionResourceHandleList;
-}
-
-OCEntityHandlerResult GroupSynchronization::groupEntityHandler(
-        const std::shared_ptr< OCResourceRequest > request)
-{
-    cout << "GroupSynchronization::groupEntityHandler\n";
-
-    if (request)
+    OCEntityHandlerResult GroupSynchronization::groupEntityHandler(
+            const std::shared_ptr< OCResourceRequest > request)
     {
-        // Get the request type and request flag
-        std::string requestType = request->getRequestType();
-        int requestFlag = request->getRequestHandlerFlag();
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::groupEntityHandler");
 
-        if (requestFlag == RequestHandlerFlag::InitFlag)
+        if (request)
         {
-            cout << "\trequestFlag : Init\n";
+            // Get the request type and request flag
+            std::string requestType = request->getRequestType();
+            int requestFlag = request->getRequestHandlerFlag();
 
-            // entity handler to perform resource initialization operations
-        }
-        else if (requestFlag == RequestHandlerFlag::RequestFlag)
-        {
-            cout << "\trequestFlag : Request\n";
-
-            // If the request type is GET
-            if (requestType == "GET")
-            {
-                cout << "\t\trequestType : GET\n";
-            }
-            else if (requestType == "PUT")
+            if (requestFlag == RequestHandlerFlag::RequestFlag)
             {
-                cout << "\t\trequestType : PUT\n";
-
-                //get method name, group resource type and resource type to join group
-                OCRepresentation rp = request->getResourceRepresentation();
-                std::string methodType = rp.getValue< std::string >("method");
-                std::string collectionResourceType = rp.getValue< std::string >(
-                        "collectionResourceType");
-                std::string resourceType = rp.getValue< std::string >("resourceType");
-
-                cout << "\t\t\tmethod : " << methodType << endl;
-                cout << "\t\t\tcollection resourceType : " << collectionResourceType << endl;
-                cout << "\t\t\tresourceType : " << resourceType << endl;
-
-                auto handleIt = collectionResourceHandleList.find(collectionResourceType);
-                if (handleIt == collectionResourceHandleList.end())
-                {
-                    cout << "GroupSynchronization::groupEntityHandler : "
-                            << "Error! There is no collection resource handle to delete."
-                            << endl;
-                    return OC_EH_ERROR;
-                }
-                collectionResourceHandle = handleIt->second;
-                // in case of join group it is used in onFindResource()
+                OC_LOG(DEBUG, TAG, "\trequestFlag : Request");
 
-                if (methodType == "joinGroup")
+                // If the request type is GET
+                if (requestType == "GET")
                 {
-                    std::string resourceName = "coap://224.0.1.187/oc/core?rt=";
-                    resourceName += resourceType;
-                    cout << "\t\t\tresourceName : " << resourceName << endl;
-
-                    resourceRequest = request;
-
-                    OCPlatform::findResource("", resourceName,
-                            std::bind(&GroupSynchronization::onFindResource, this,
-                                    std::placeholders::_1));
+                    OC_LOG(DEBUG, TAG, "\t\trequestType : GET");
                 }
-                else if (methodType == "leaveGroup")
+                else if (requestType == "PUT")
                 {
-                    auto it = childResourceHandleList.find(collectionResourceHandle);
-                    if (it == childResourceHandleList.end())
+                    OC_LOG(DEBUG, TAG, "\t\trequestType : PUT");
+
+                    //get method name, group resource type and resource type to join group
+                    OCRepresentation rp = request->getResourceRepresentation();
+                    std::string methodType = rp.getValue< std::string >("method");
+                    std::string collectionResourceType = rp.getValue< std::string >(
+                            "collectionResourceType");
+                    std::string resourceType = rp.getValue< std::string >("resourceType");
+
+                    OC_LOG_V(DEBUG, TAG, "\t\t\tmethod : %s", methodType.c_str());
+                    OC_LOG_V(DEBUG, TAG, "\t\t\tcollection resourceType : %s",
+                        collectionResourceType.c_str());
+                    OC_LOG_V(DEBUG, TAG, "\t\t\tresourceType : %s", resourceType.c_str());
+
+                    auto handleIt = collectionResourceHandleList.find(collectionResourceType);
+                    if (handleIt == collectionResourceHandleList.end())
                     {
-                        cout << "GroupSynchronization::groupEntityHandler : "
-                                << "Error! There is no child resource list." << endl;
+                        OC_LOG(DEBUG, TAG, "GroupSynchronization::groupEntityHandler : " \
+                            "Error! There is no collection resource handle to delete.");
                         return OC_EH_ERROR;
                     }
+                    collectionResourceHandle = handleIt->second;
+                    // in case of join group it is used in onFindResource()
 
-                    std::vector< OCResourceHandle > childList = it->second;
-                    OCResourceHandle resourceHandle;
-                    for (auto childIt = childList.begin(); childIt != childList.end();)
+                    if (methodType == "joinGroup")
                     {
-                        resourceHandle = (*childIt);
-                        char* type = (char*) OCGetResourceTypeName(resourceHandle, 0);
+                        std::string resourceName = OC_MULTICAST_DISCOVERY_URI;
+                        resourceName.append("?rt=");
+                        resourceName.append(resourceType);
+                        OC_LOG_V(DEBUG, TAG, "\t\t\tresourceName : %s", resourceName.c_str());
 
-                        if (0 == resourceType.compare(type))
-                        {
-                            cout << "GroupSynchronization::groupEntityHandler : "
-                                    << "Found! The resource to leave is found. - " << type
-                                    << endl;
+                        resourceRequest = request;
 
-                            childIt = childList.erase(childIt++);
+                        OCPlatform::findResource("", resourceName,
+                            OC_ALL,
+                            std::bind(&GroupSynchronization::onFindResource, this,
+                                std::placeholders::_1));
 
-                            OCStackResult result = OCPlatform::unbindResource(
-                                    collectionResourceHandle, resourceHandle);
-                            if (OC_STACK_OK == result)
-                            {
-                                cout << "GroupSynchronization::groupEntityHandler : "
-                                        << "To unbind resource was successful." << endl;
-                            }
-                            else
-                            {
-                                cout << "GroupSynchronization::groupEntityHandler : "
-                                        << "To unbind resource was unsuccessful. result - "
-                                        << result << endl;
-                            }
+                        return OC_EH_SLOW;
+                    }
+                    else if (methodType == "leaveGroup")
+                    {
+                        auto it = childResourceHandleList.find(collectionResourceHandle);
+                        if (it == childResourceHandleList.end())
+                        {
+                            OC_LOG(DEBUG, TAG, "GroupSynchronization::groupEntityHandler : " \
+                                "Error! There is no child resource list.");
+                            return OC_EH_ERROR;
+                        }
 
-                            result = OCPlatform::unregisterResource(resourceHandle);
-                            if (OC_STACK_OK == result)
+                        std::vector< OCResourceHandle > childList = it->second;
+                        OCResourceHandle resourceHandle;
+                        for (auto childIt = childList.begin(); childIt != childList.end();)
+                        {
+                            resourceHandle = (*childIt);
+                            char* type = (char*) OCGetResourceTypeName(resourceHandle, 0);
+
+                            if (0 == resourceType.compare(type))
                             {
-                                cout << "GroupSynchronization::groupEntityHandler : "
-                                        << "To unregister resource was successful." << endl;
+                                OC_LOG_V(DEBUG, TAG,
+                                    "GroupSynchronization::groupEntityHandler : " \
+                                    "Found! The resource to leave is found. - %s", type);
+
+                                childIt = childList.erase(childIt++);
+
+                                OCStackResult result = OCPlatform::unbindResource(
+                                        collectionResourceHandle, resourceHandle);
+                                if (OC_STACK_OK == result)
+                                {
+                                    OC_LOG(DEBUG, TAG,
+                                        "GroupSynchronization::groupEntityHandler : " \
+                                        "To unbind resource was successful.");
+                                }
+                                else
+                                {
+                                    OC_LOG_V(DEBUG, TAG,
+                                        "GroupSynchronization::groupEntityHandler : " \
+                                        "To unbind resource was unsuccessful. result - %d",
+                                        result);
+                                }
+
+                                result = OCPlatform::unregisterResource(resourceHandle);
+                                if (OC_STACK_OK == result)
+                                {
+                                    OC_LOG(DEBUG, TAG,
+                                        "GroupSynchronization::groupEntityHandler : " \
+                                        "To unregister resource was successful.");
+                                }
+                                else
+                                {
+                                    OC_LOG_V(DEBUG, TAG,
+                                        "GroupSynchronization::groupEntityHandler : "
+                                        "To unregister resource was unsuccessful. result - %d",
+                                        result);
+                                }
                             }
                             else
                             {
-                                cout << "GroupSynchronization::groupEntityHandler : "
-                                        << "To unregister resource was unsuccessful. result - "
-                                        << result << endl;
+                                ++childIt;
                             }
 
-//                            break;
-                        }
-                        else
-                        {
-                            ++childIt;
                         }
 
-                    }
+                        childResourceHandleList[collectionResourceHandle] = childList;
 
-                    childResourceHandleList[collectionResourceHandle] = childList;
+                        debugGroupSync();
 
-                    debugGroupSync();
+                        auto pResponse = std::make_shared< OC::OCResourceResponse >();
+                        pResponse->setRequestHandle(request->getRequestHandle());
+                        pResponse->setResourceHandle(request->getResourceHandle());
+                        pResponse->setErrorCode(200);
+                        pResponse->setResponseResult(OC_EH_OK);
 
-                    auto pResponse = std::make_shared< OC::OCResourceResponse >();
-                    pResponse->setRequestHandle(request->getRequestHandle());
-                    pResponse->setResourceHandle(request->getResourceHandle());
-                    pResponse->setErrorCode(200);
-                    pResponse->setResponseResult(OC_EH_OK);
+                        OCRepresentation rep = request->getResourceRepresentation();
+                        pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+                        if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                        {
+                            OC_LOG(DEBUG, TAG, "GroupSynchronization::groupEntityHandler : " \
+                                "sendResponse is successful.");
+                        }
+                    }
 
-                    OCRepresentation rep = request->getResourceRepresentation();
-                    pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
-                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    if (methodType != "") //TODO: Check groupmethodtype NULL
                     {
-                        cout << "GroupSynchronization::groupEntityHandler : "
-                                << "sendResponse is successful." << endl;
                     }
                 }
-
-                if (methodType != "") //TODO: Check groupmethodtype NULL
+                else if (requestType == "POST")
                 {
+                    // POST request operations
+                }
+                else if (requestType == "DELETE")
+                {
+                    // DELETE request operations
                 }
             }
-            else if (requestType == "POST")
-            {
-                // POST request operations
-            }
-            else if (requestType == "DELETE")
+            else if (requestFlag == RequestHandlerFlag::ObserverFlag)
             {
-                // DELETE request operations
+                OC_LOG(DEBUG, TAG, "\trequestFlag : Observer");
             }
         }
-        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+        else
         {
-            cout << "\trequestFlag : Observer\n";
+            OC_LOG(DEBUG, TAG, "Request invalid");
         }
-    }
-    else
-    {
-        std::cout << "Request invalid" << std::endl;
-    }
 
-    return OC_EH_OK;
-}
-
-void GroupSynchronization::onFindGroup(std::shared_ptr< OCResource > resource)
-{
-    cout << "GroupSynchronization::onFindGroup" << endl;
+        return OC_EH_OK;
+    }
 
-    try
+    void GroupSynchronization::onFindGroup(std::shared_ptr< OCResource > resource)
     {
-        if (resource)
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::onFindGroup");
+
+        try
         {
-//////////////////////////////////////////////////////////////////////////////////////////////////
-////////////debugging
-            std::string resourceURI;
-            std::string hostAddress;
+            if (resource)
+            {
+                // Debugging
+                std::string resourceURI;
+                std::string hostAddress;
 
-            // Get the resource URI
-            resourceURI = resource->uri();
-            cout << "\tURI of the resource: " << resourceURI << endl;
+                // Get the resource URI
+                resourceURI = resource->uri();
+                OC_LOG_V(DEBUG, TAG, "\tURI of the resource: %s", resourceURI.c_str());
 
-            // Get the resource host address
-            hostAddress = resource->host();
-            cout << "\tHost address of the resource: " << hostAddress << endl;
+                // Get the resource host address
+                hostAddress = resource->host();
+                OC_LOG_V(DEBUG, TAG, "\tHost address of the resource: %s", hostAddress.c_str());
 
-            hostAddress.append(resourceURI);
+                hostAddress.append(resourceURI);
 
-            // Get the resource types
-            cout << "\tList of resource types: " << endl;
+#ifndef NDEBUG
+                // Get the resource types
+                OC_LOG(DEBUG, TAG, "\tList of resource types: ");
+                for (auto &resourceTypes : resource->getResourceTypes())
+                {
+                    OC_LOG_V(DEBUG, TAG, "\t\t", resourceTypes.c_str());
+                }
 
-            for (auto &resourceTypes : resource->getResourceTypes())
-            {
-                cout << "\t\t" << resourceTypes << endl;
-            }
+                // Get the resource interfaces
+                OC_LOG(DEBUG, TAG, "\tList of resource interfaces: ");
+                for (auto &resourceInterfaces : resource->getResourceInterfaces())
+                {
+                    OC_LOG_V(DEBUG, TAG, "\t\t", resourceInterfaces.c_str());
+                }
+#endif
 
-            // Get the resource interfaces
-            cout << "\tList of resource interfaces: " << endl;
-            for (auto &resourceInterfaces : resource->getResourceInterfaces())
-            {
-                cout << "\t\t" << resourceInterfaces << endl;
+                if (false == IsSameGroup(resource))
+                {
+                    saveGroup(resource);
+                    findCallback(resource);
+                }
             }
-//////////////////////////////////////////////////////////////////////////////////////////////////
-
-            if (false == IsSameGroup(resource))
+            else
             {
-                saveGroup(resource);
-                findCallback(resource);
+                // Resource is invalid
+                OC_LOG(DEBUG, TAG, "Resource is invalid");
+                findCallback(NULL);
             }
+
+            bIsFinding = false;
         }
-        else
+        catch (std::exception& e)
         {
-            // Resource is invalid
-            cout << "Resource is invalid" << endl;
-            findCallback(NULL);
+            //log(e.what());
         }
-
     }
-    catch (std::exception& e)
+
+    void GroupSynchronization::checkFindGroup(void)
     {
-        //log(e.what());
-    }
-}
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::checkFindGroup");
 
-void GroupSynchronization::checkFindGroup(void)
-{
-    cout << "GroupSynchronization::checkFindGroup" << endl;
+        for (int i = 0; i < 15; i++)
+        {
+            std::chrono::milliseconds workTime(300);
+            std::this_thread::sleep_for(workTime);
 
-    for (int i = 0; i < 15; i++)
-    {
-        std::chrono::milliseconds workTime(300);
-        std::this_thread::sleep_for(workTime);
+            std::lock_guard < std::mutex > guard(foundGroupMutex);
+
+            if (false == foundGroupResourceList.empty())
+            {
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::checkFoundGroup : " \
+                    "Some group is received.");
+                return;
+            }
+        }
 
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::checkFoundGroup : " \
+            "It is failed to find resource within 3s.");
+
+        onFindGroup(NULL);
+        return;
+    }
+
+    bool GroupSynchronization::IsSameGroup(std::shared_ptr< OCResource > resource)
+    {
         std::lock_guard < std::mutex > guard(foundGroupMutex);
 
-        if (false == foundGroupResourceList.empty())
+        if (true == foundGroupResourceList.empty())
         {
-            cout << "GroupSynchronization::checkFoundGroup : " << "Some group is received."
-                    << endl;
-            return;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::IsSameGroup : There is no found group.");
+            return false;
         }
-    }
 
-    cout << "GroupSynchronization::checkFoundGroup : "
-            << "It is failed to find resource within 3s." << endl;
+        std::string foundHostAddress, savedHostAddress;
+        std::string foundHostUri, savedHostUri;
+        foundHostAddress = resource->host();
+        foundHostUri = resource->uri();
 
-    onFindGroup(NULL);
-    return;
-}
+        for (unsigned int i = 0; i < foundGroupResourceList.size(); ++i)
+        {
+            savedHostAddress = (foundGroupResourceList.at(i))->host();
+            savedHostUri = (foundGroupResourceList.at(i))->uri();
 
-bool GroupSynchronization::IsSameGroup(std::shared_ptr< OCResource > resource)
-{
-    std::lock_guard < std::mutex > guard(foundGroupMutex);
+            if (0 == foundHostAddress.compare(savedHostAddress.c_str()))
+            {
+                if( 0 == foundHostUri.compare(savedHostAddress) )
+                {
+                    OC_LOG(DEBUG, TAG,
+                        "GroupSynchronization::IsSameGroup : Found! The same group is found.");
+                    return true;
+                }
+            }
+        }
 
-    if (true == foundGroupResourceList.empty())
-    {
-        cout << "GroupSynchronization::IsSameGroup : There is no found group." << endl;
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::IsSameGroup :  There is no same group.");
         return false;
     }
 
-    std::string foundHostAddress, savedHostAddress;
-    foundHostAddress = resource->host();
-//    foundHostAddress.append (resource->uri());
-
-    for (unsigned int i = 0; i < foundGroupResourceList.size(); ++i)
+    void GroupSynchronization::saveGroup(std::shared_ptr< OCResource > resource)
     {
-        savedHostAddress = (foundGroupResourceList.at(i))->host();
-//        savedHostAddress.append ((foundGroupResourceList.at(i))->uri());
-//        cout << "GroupSynchronization::IsSameGroup : foundHostAddress - " << foundHostAddress
-//                << ", savedHostAddress - " << savedHostAddress << endl;
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::saveGroup");
 
-        if (0 == foundHostAddress.compare(savedHostAddress.c_str()))
+        std::lock_guard < std::mutex > guard(foundGroupMutex);
+
+        foundGroupResourceList.push_back(resource);
+    }
+
+    void GroupSynchronization::onJoinGroup(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode)
+    {
+        if (eCode != OC_STACK_OK)
         {
-            cout << "GroupSynchronization::IsSameGroup : Found! The same group is found."
-                    << endl;
-            return true;
+            OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onJoinGroup : error - %d", eCode);
+            return;
         }
     }
 
-    cout << "GroupSynchronization::IsSameGroup :  There is no same group." << endl;
-    return false;
-}
+    void GroupSynchronization::onFindResource(std::shared_ptr< OCResource > resource)
+    {
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::onFindResource");
 
-void GroupSynchronization::saveGroup(std::shared_ptr< OCResource > resource)
-{
-    cout << "GroupSynchronization::saveGroup" << endl;
+        if (resource)
+        {
+            if(NULL == collectionResourceHandle)
+                return;
 
-    std::lock_guard < std::mutex > guard(foundGroupMutex);
+            // start of debugging
+            std::string resourceURI;
+            std::string hostAddress;
 
-    foundGroupResourceList.push_back(resource);
-}
+            // Get the resource URI
+            resourceURI = resource->uri();
+            OC_LOG_V(DEBUG, TAG, "\tURI of the resource: %s", resourceURI.c_str());
 
-void GroupSynchronization::onJoinGroup(const HeaderOptions& headerOptions,
-        const OCRepresentation& rep, const int eCode)
-{
-    if (eCode == OC_STACK_OK)
-    {
-        cout << "GroupSynchronization::onJoinGroup : " << endl;
+            // Get the resource host address
+            hostAddress = resource->host();
+            OC_LOG_V(DEBUG, TAG, "\tHost address of the resource: %s", hostAddress.c_str());
 
-        if (remoteCollectionResource)
-        {
-            std::string resourceInterface = DEFAULT_INTERFACE;
-            QueryParamsMap queryParamsMap;
-
-            OCStackResult result = remoteCollectionResource->get("", resourceInterface,
-                    queryParamsMap,
-                    std::bind(&GroupSynchronization::onGetJoinedRemoteChild, this,
-                            std::placeholders::_1, std::placeholders::_2,
-                            std::placeholders::_3));
-            if (OC_STACK_OK == result)
+            hostAddress.append(resourceURI);
+
+#ifndef NDEBUG
+            // Get the resource types
+            OC_LOG(DEBUG, TAG, "\tList of resource types: ");
+            for (auto &resourceTypes : resource->getResourceTypes())
             {
-                cout << "GroupSynchronization::onJoinGroup : "
-                        << "remoteCollectionResource->get was successful." << endl;
+                OC_LOG_V(DEBUG, TAG, "\t\t%s", resourceTypes.c_str());
             }
-            else
+
+            // Get the resource interfaces
+            OC_LOG(DEBUG, TAG, "\tList of resource interfaces: ");
+            for (auto &resourceInterfaces : resource->getResourceInterfaces())
             {
-                cout << "GroupSynchronization::onJoinGroup : "
-                        << "remoteCollectionResource->get was unsuccessful. result - " << result
-                        << endl;
+                OC_LOG_V(DEBUG, TAG, "\t\t%s", resourceInterfaces.c_str());
             }
-        }
-    }
-    else
-    {
-        cout << "GroupSynchronization::onJoinGroup : error - " << eCode << endl;
-    }
-}
+            // end of debugging
+#endif
 
-void GroupSynchronization::onFindResource(std::shared_ptr< OCResource > resource)
-{
-    cout << "GroupSynchronization::onFindResource" << endl;
+            OCResourceHandle resourceHandle;
+            OCStackResult result = OCPlatform::registerResource(resourceHandle, resource);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, TAG, "GroupSynchronization::" \
+                    "onFindResource - Resource to join creation was unsuccessful. result - %d",
+                    result);
+                return;
+            }
 
-    if (resource)
-    {
-//////////////////////////////////////////////////////////////////////////////////////////////////
-////////// debugging
-        std::string resourceURI;
-        std::string hostAddress;
+            result = OCPlatform::bindResource(collectionResourceHandle, resourceHandle);
+            if (result != OC_STACK_OK)
+            {
+                OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onFindResource : " \
+                    "To bind resource was unsuccessful. result - %d", result);
+                return;
+            }
 
-        // Get the resource URI
-        resourceURI = resource->uri();
-        cout << "\tURI of the resource: " << resourceURI << endl;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::onFindResource : " \
+                    "To bind joinGroupHandle and resourceHandle was successful.");
 
-        // Get the resource host address
-        hostAddress = resource->host();
-        cout << "\tHost address of the resource: " << hostAddress << endl;
+            auto it = childResourceHandleList.find(collectionResourceHandle);
+            std::vector< OCResourceHandle > childHandleList;
+            if (it != childResourceHandleList.end())
+            {
+                childHandleList = it->second;
+            }
 
-        hostAddress.append(resourceURI);
+            childHandleList.push_back(resourceHandle);
+            childResourceHandleList[collectionResourceHandle] = childHandleList;
 
-        // Get the resource types
-        cout << "\tList of resource types: " << endl;
+            auto pResponse = std::make_shared< OC::OCResourceResponse >();
+            pResponse->setRequestHandle(resourceRequest->getRequestHandle());
+            pResponse->setResourceHandle(resourceRequest->getResourceHandle());
+            pResponse->setErrorCode(200);
+            pResponse->setResponseResult(OC_EH_OK);
 
-        for (auto &resourceTypes : resource->getResourceTypes())
-        {
-            cout << "\t\t" << resourceTypes << endl;
+            OCRepresentation rep = resourceRequest->getResourceRepresentation();
+            pResponse->setResourceRepresentation(rep);
+            try{
+                if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    OC_LOG(DEBUG, TAG,
+                        "GroupSynchronization::onFindResource : sendResponse is successful.");
+                }
+            }
+            catch( OCException &e )
+            {
+                // OC_LOG(DEBUG, TAG, e.what);
+                return;
+            }
         }
-
-        // Get the resource interfaces
-        cout << "\tList of resource interfaces: " << endl;
-        for (auto &resourceInterfaces : resource->getResourceInterfaces())
+        else
         {
-            cout << "\t\t" << resourceInterfaces << endl;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::onFindResource : " \
+                "Resource is invalid. So a new Group Resource has to be created.");
         }
-//////////////////////////////////////////////////////////////////////////////////////////////////
 
-        OCResourceHandle resourceHandle;
-        OCStackResult result = OCPlatform::registerResource(resourceHandle, resource);
-        if (result != OC_STACK_OK)
-        {
-            cout << "GroupSynchronization::"
-                    << "onFindResource - Resource to join creation was unsuccessful. result - "
-                    << result << endl;
-            return;
-        }
-//        cout << "GroupSynchronization::onFindResource : creating resourceHandle. resource type - "
-//                << OCGetResourceTypeName(resourceHandle, 0) << endl;
+        debugGroupSync();
+    }
 
-        result = OCPlatform::bindResource(collectionResourceHandle, resourceHandle);
-        if (result != OC_STACK_OK)
+    void GroupSynchronization::onGetJoinedRemoteChild(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode)
+    {
+        if (eCode != OC_STACK_OK)
         {
-            cout << "GroupSynchronization::onFindResource : "
-                    << "To bind resource was unsuccessful. result - " << result << endl;
+            OC_LOG_V(DEBUG, TAG,
+                "GroupSynchronization::onGetJoinedRemoteChild : error - %d", eCode);
             return;
         }
-        cout << "GroupSynchronization::onFindResource : "
-                << "To bind joinGroupHandle and resourceHandle was successful." << endl;
-
-        auto it = childResourceHandleList.find(collectionResourceHandle);
-        std::vector< OCResourceHandle > childHandleList;
-        if (it != childResourceHandleList.end())
-        {
-            childHandleList = it->second;
-        }
 
-        childHandleList.push_back(resourceHandle);
-        childResourceHandleList[collectionResourceHandle] = childHandleList;
-
-        auto pResponse = std::make_shared< OC::OCResourceResponse >();
-        pResponse->setRequestHandle(resourceRequest->getRequestHandle());
-        pResponse->setResourceHandle(resourceRequest->getResourceHandle());
-        pResponse->setErrorCode(200);
-        pResponse->setResponseResult(OC_EH_OK);
-
-        OCRepresentation rep = resourceRequest->getResourceRepresentation();
-        pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
-        if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
-        {
-            cout << "GroupSynchronization::onFindResource : sendResponse is successful."
-                    << endl;
-        }
-    }
-    else
-    {
-        cout << "GroupSynchronization::onFindResource : "
-                << "Resource is invalid. So a new Group Resource has to be created." << endl;
-    }
-
-    debugGroupSync();
-}
-
-void GroupSynchronization::onGetJoinedRemoteChild(const HeaderOptions& headerOptions,
-        const OCRepresentation& rep, const int eCode)
-{
-    if (eCode == OC_STACK_OK)
-    {
-        cout << "GroupSynchronization::onGetJoinedRemoteChild" << endl;
-
-//////////////////////////////////////////////////////////////////////////////////////////////////
-////////// debugging
         std::string resourceURI;
+        std::vector< OCRepresentation > childList;
+        OCRepresentation child;
 
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild");
+#ifndef NDEBUG
+        // debugging
         // Get the resource URI
         resourceURI = rep.getUri();
-        cout << "\tURI of the resource: " << resourceURI << endl;
+        OC_LOG_V(DEBUG, TAG, "\tURI of the resource: %s", resourceURI.c_str());
 
         // Get the resource types
-        cout << "\tList of resource types: " << endl;
+        OC_LOG(DEBUG, TAG, "\tList of resource types: ");
 
         for (auto &resourceTypes : rep.getResourceTypes())
         {
-            cout << "\t\t" << resourceTypes << endl;
+            OC_LOG_V(DEBUG, TAG, "\t\t%s", resourceTypes.c_str());
         }
 
         // Get the resource interfaces
-        cout << "\tList of resource interfaces: " << endl;
+        OC_LOG(DEBUG, TAG, "\tList of resource interfaces: ");
         for (auto &resourceInterfaces : rep.getResourceInterfaces())
         {
-            cout << "\t\t" << resourceInterfaces << endl;
+            OC_LOG_V(DEBUG, TAG, "\t\t%s", resourceInterfaces.c_str());
         }
 
-        std::vector< OCRepresentation > childList = rep.getChildren();
-        OCRepresentation child;
+        childList = rep.getChildren();
         for (unsigned int i = 0; i < childList.size(); ++i)
         {
-            cout << "\n\tchild resource - " << i + 1 << endl;
+            OC_LOG_V(DEBUG, TAG, "\tchild resource - %d", i + 1);
 
             child = childList.at(i);
             resourceURI = child.getUri();
-            cout << "\t\tURI of the resource: " << resourceURI << endl;
+            OC_LOG_V(DEBUG, TAG, "\t\tURI of the resource: %s", resourceURI.c_str());
 
-            cout << "\t\tList of resource types: " << endl;
+            OC_LOG_V(DEBUG, TAG, "\t\tList of resource types: ");
             for (auto &types : child.getResourceTypes())
             {
-                cout << "\t\t\t" << types << endl;
+                OC_LOG_V(DEBUG, TAG, "\t\t\t%s", types.c_str());
             }
 
-            cout << "\tList of resource interfaces: " << endl;
+            OC_LOG(DEBUG, TAG, "\tList of resource interfaces: ");
             for (auto &interfaces : child.getResourceInterfaces())
             {
-                cout << "\t\t\t" << interfaces << endl;
+                OC_LOG_V(DEBUG, TAG, "\t\t\t%s", interfaces.c_str());
             }
         }
-//////////////////////////////////////////////////////////////////////////////////////////////////
+#endif
 
         // creating remote collection resource handle
         OCResourceHandle remoteCollectionResourceHandle;
         resourceURI = remoteCollectionResource->uri();
         std::vector< std::string > types = remoteCollectionResource->getResourceTypes();
-        std::vector< std::string > interfaces =
-                remoteCollectionResource->getResourceInterfaces();
+        std::vector< std::string > interfaces = remoteCollectionResource->getResourceInterfaces();
 
         OCStackResult result = OCPlatform::registerResource(remoteCollectionResourceHandle,
                 resourceURI, types[0], interfaces[0], NULL, OC_OBSERVABLE);
         if (result != OC_STACK_OK)
         {
-            cout << "GroupSynchronization::onGetJoinedRemoteChild - "
-                    << "To register remoteCollectionResourceHandle"
-                    << " was unsuccessful. result - " << result << endl;
+            OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild - " \
+                "To register remoteCollectionResourceHandle" \
+                " was unsuccessful. result - %d", result);
             return;
         }
-        cout << "GroupSynchronization::onGetJoinedRemoteChild : "
-                "To register remoteCollectionResourceHandle was successful." << endl;
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild : " \
+                "To register remoteCollectionResourceHandle was successful.");
 
         // binding remote collection resource handle and resource handle to join
         collectionResourceHandleList[types[0]] = remoteCollectionResourceHandle;
@@ -1085,15 +1142,14 @@ void GroupSynchronization::onGetJoinedRemoteChild(const HeaderOptions& headerOpt
         result = OCPlatform::bindResource(remoteCollectionResourceHandle, deviceResourceHandle);
         if (OC_STACK_OK == result)
         {
-            cout << "GroupSynchronization::onGetJoinedRemoteChild : "
-                    << "binding remoteCollectionResourceHandle and deviceResourceHandle"
-                    << endl;
+            OC_LOG(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild : " \
+                "binding remoteCollectionResourceHandle and deviceResourceHandle");
         }
         else
         {
-            cout << "GroupSynchronization::onGetJoinedRemoteChild - "
-                    << "To bind remoteCollectionResourceHandle and deviceResourceHandle "
-                    << "was unsuccessful. result - " << result << endl;
+            OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild - " \
+                "To bind remoteCollectionResourceHandle and deviceResourceHandle " \
+                "was unsuccessful. result - %d", result);
         }
 
         std::vector< OCResourceHandle > childHandleList;
@@ -1104,7 +1160,7 @@ void GroupSynchronization::onGetJoinedRemoteChild(const HeaderOptions& headerOpt
         OCResourceHandle resourceHandle;
         for (unsigned int i = 0; i < childList.size(); ++i)
         {
-            cout << "\tremote resource - " << i + 1 << endl;
+            OC_LOG_V(DEBUG, TAG, "\tremote resource - %d", i + 1);
 
             child = childList.at(i);
             resourceURI = child.getUri();
@@ -1113,8 +1169,8 @@ void GroupSynchronization::onGetJoinedRemoteChild(const HeaderOptions& headerOpt
 
             if (0 == types[0].compare(OCGetResourceTypeName(deviceResourceHandle, 0)))
             {
-                cout << "GroupSynchronization::onGetJoinedRemoteChild : " << types[0]
-                        << " is bind already." << endl;
+                OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild : %s" \
+                    " is bind already.", types[0].c_str());
                 continue;
             }
 
@@ -1122,156 +1178,151 @@ void GroupSynchronization::onGetJoinedRemoteChild(const HeaderOptions& headerOpt
                     interfaces[0], NULL, OC_OBSERVABLE);
             if (OC_STACK_OK == result)
             {
-                result = OCPlatform::bindResource(remoteCollectionResourceHandle,
-                        resourceHandle);
+                result = OCPlatform::bindResource(remoteCollectionResourceHandle, resourceHandle);
                 if (result != OC_STACK_OK)
                 {
-                    cout << "GroupSynchronization::onGetJoinedRemoteChild - "
-                            << "binding remoteCollectionResourceHandle and resourceHandle "
-                            << "was unsuccessful. result - " << result << endl;
+                    OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild - " \
+                        "binding remoteCollectionResourceHandle and resourceHandle " \
+                        "was unsuccessful. result - %d", result);
                     OCPlatform::unregisterResource(resourceHandle);
                 }
 
                 childHandleList.push_back(resourceHandle);
-                cout << "GroupSynchronization::onGetJoinedRemoteChild : "
-                        << "binding remoteCollectionResourceHandle and resourceHandle" << endl;
+                OC_LOG(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild : " \
+                    "binding remoteCollectionResourceHandle and resourceHandle");
             }
             else
             {
-                cout << "GroupSynchronization::onGetJoinedRemoteChild - "
-                        << "To register remoteCollectionResourceHandle was unsuccessful."
-                        << " result - " << result << endl;
+                OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onGetJoinedRemoteChild - " \
+                    "To register remoteCollectionResourceHandle was unsuccessful." \
+                    " result - %d", result);
             }
         }
 
         childResourceHandleList[remoteCollectionResourceHandle] = childHandleList;
         // this handle list is used to leave group
-    }
-    else
-    {
-        cout << "GroupSynchronization::onGetJoinedRemoteChild : error - " << eCode << endl;
-    }
-
-    debugGroupSync();
-}
 
-void GroupSynchronization::onLeaveGroup(const HeaderOptions& headerOptions,
-        const OCRepresentation& rep, const int eCode)
-{
-    if (eCode == OC_STACK_OK)
-    {
-        cout << "GroupSynchronization::onLeaveGroup" << endl;
-    }
-    else
-    {
-        cout << "GroupSynchronization::onLeaveGroup : error - " << eCode << endl;
+        debugGroupSync();
     }
-    debugGroupSync();
-}
 
-void GroupSynchronization::debugGroupSync(void)
-{
-    cout << "GroupSynchronization::debugGroupSync" << endl;
-
-    unsigned int i;
-    std::map< std::string, OCResourceHandle >::iterator handleIt;
-    std::map< OCResourceHandle, std::vector< OCResourceHandle > >::iterator childIt;
-    std::string type;
-    OCResourceHandle resourceHandle;
-    std::vector< OCResourceHandle > handleList;
-    std::shared_ptr< OCResource > resource;
-
-    cout << "Resource Handle Created by App" << endl;
-    for (i = 0; i < deviceResourceHandleList.size(); i++)
+    void GroupSynchronization::onLeaveGroup(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode)
     {
-        resourceHandle = deviceResourceHandleList.at(i);
+        if (eCode != OC_STACK_OK)
+        {
+            OC_LOG_V(DEBUG, TAG, "GroupSynchronization::onLeaveGroup : error - %d", eCode);
+            return;
+        }
 
-        cout << i + 1 << ". details" << endl;
-        cout << "  uri - " << OCGetResourceUri(resourceHandle) << endl;
-        cout << "  resource type - " << OCGetResourceTypeName(resourceHandle, 0) << endl;
-        cout << "  resource interface - " << OCGetResourceInterfaceName(resourceHandle, 0)
-                << endl << endl;
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::onLeaveGroup");
+        debugGroupSync();
     }
 
-    cout << "\nGroup Sync Resource Handle List. The number is "
-            << groupSyncResourceHandleList.size() << endl;
-    i = 1;
-    for (handleIt = groupSyncResourceHandleList.begin();
-            handleIt != groupSyncResourceHandleList.end(); ++handleIt)
+    void GroupSynchronization::debugGroupSync(void)
     {
-        type = handleIt->first;
-        cout << "\t" << i << ". group sync resource type - " << type << endl;
-        cout << "\t  details" << endl;
-
-        resourceHandle = handleIt->second;
-        cout << "\t  uri - " << OCGetResourceUri(resourceHandle) << endl;
-        cout << "\t  resource type - " << OCGetResourceTypeName(resourceHandle, 0) << endl;
-        cout << "\t  resource interface - " << OCGetResourceInterfaceName(resourceHandle, 0)
-                << endl << endl;
-        ;
-        i++;
-    }
+#ifndef NDEBUG
+        OC_LOG(DEBUG, TAG, "GroupSynchronization::debugGroupSync");
 
-    cout << "Copied Remote Group Sync Resource List. The number is "
-            << groupSyncResourceList.size() << endl;
-    std::vector< std::string > list;
-    i = 1;
-    for (auto resourceIt = groupSyncResourceList.begin();
-            resourceIt != groupSyncResourceList.end(); ++resourceIt)
-    {
-        type = resourceIt->first;
-        cout << "\t" << i << ". group sync resource type - " << type << endl;
-        cout << "\t details" << endl;
-
-        resource = resourceIt->second;
-        cout << "\t  host - " << resource->host() << endl;
-        cout << "\t  uri - " << resource->uri() << endl;
-        list = resource->getResourceTypes();
-        cout << "\t  resource type - " << list[0] << endl;
-        list = resource->getResourceInterfaces();
-        cout << "\t  resource interface - " << list[0] << endl << endl;
-        i++;
-    }
+        unsigned int i;
+        std::map< std::string, OCResourceHandle >::iterator handleIt;
+        std::map< OCResourceHandle, std::vector< OCResourceHandle > >::iterator childIt;
+        std::string type;
+        OCResourceHandle resourceHandle;
+        std::vector< OCResourceHandle > handleList;
+        std::shared_ptr< OCResource > resource;
 
-//    cout << "The number of collection Resource Handle is " << collectionResourceHandleList.size()
-//            << endl;
-//    cout << "The number of child resource handle list is " << childResourceHandleList.size()
-//            << endl;
+        OC_LOG(DEBUG, TAG, "Resource Handle Created by App");
+        for (i = 0; i < deviceResourceHandleList.size(); i++)
+        {
+            resourceHandle = deviceResourceHandleList.at(i);
+
+            OC_LOG_V(DEBUG, TAG, "%d. details", i + 1);
+            OC_LOG_V(DEBUG, TAG, "\turi - %s", OCGetResourceUri(resourceHandle));
+            OC_LOG_V(DEBUG, TAG, "\tresource type - %s",
+                OCGetResourceTypeName(resourceHandle, 0));
+            OC_LOG_V(DEBUG, TAG, "\tresource interface - %s",
+                OCGetResourceInterfaceName(resourceHandle, 0));
+        }
 
-    cout << "Collection Resource Handle List" << endl;
-    i = 1;
-    for (handleIt = collectionResourceHandleList.begin();
-            handleIt != collectionResourceHandleList.end(); ++handleIt)
-    {
-        type = handleIt->first;
-        cout << "\t" << i << ". collection resource type - " << type << endl;
-        cout << "\t  details" << endl;
+        OC_LOG_V(DEBUG, TAG, "Group Sync Resource Handle List. The number is %d",
+            groupSyncResourceHandleList.size());
 
-        resourceHandle = handleIt->second;
-        cout << "\t  uri - " << OCGetResourceUri(resourceHandle) << endl;
-        cout << "\t  resource type - " << OCGetResourceTypeName(resourceHandle, 0) << endl;
-        cout << "\t  resource interface - " << OCGetResourceInterfaceName(resourceHandle, 0)
-                << endl << endl;
+        i = 1;
+        for (handleIt = groupSyncResourceHandleList.begin();
+                handleIt != groupSyncResourceHandleList.end(); ++handleIt)
+        {
+            type = handleIt->first;
+            OC_LOG_V(DEBUG, TAG, "\t%d. group sync resource type - %s", i, type.c_str());
+            OC_LOG(DEBUG, TAG, "\tdetails");
+
+            resourceHandle = handleIt->second;
+            OC_LOG_V(DEBUG, TAG, "\turi - %s",
+                OCGetResourceUri(resourceHandle));
+            OC_LOG_V(DEBUG, TAG, "\tresource type - %s",
+                OCGetResourceTypeName(resourceHandle, 0));
+            OC_LOG_V(DEBUG, TAG, "\tresource interface - %s",
+                OCGetResourceInterfaceName(resourceHandle, 0));
+
+            i++;
+        }
 
-        childIt = childResourceHandleList.find(resourceHandle);
-        if (childIt != childResourceHandleList.end())
+        OC_LOG_V(DEBUG, TAG, "Copied Remote Group Sync Resource List. The number is %d",
+            groupSyncResourceList.size());
+        std::vector< std::string > list;
+        i = 1;
+        for (auto resourceIt = groupSyncResourceList.begin();
+                resourceIt != groupSyncResourceList.end(); ++resourceIt)
         {
-            handleList = childIt->second;
-            for (unsigned int j = 0; j < handleList.size(); j++)
+            type = resourceIt->first;
+            OC_LOG_V(DEBUG, TAG, "\t%d. group sync resource type - %s", i, type.c_str());
+            OC_LOG(DEBUG, TAG, "\tdetails");
+
+            resource = resourceIt->second;
+            OC_LOG_V(DEBUG, TAG, "\thost - %s", resource->host().c_str());
+            OC_LOG_V(DEBUG, TAG, "\turi - %s", resource->uri().c_str());
+            list = resource->getResourceTypes();
+            OC_LOG_V(DEBUG, TAG, "\tresource type - %s", list[0].c_str());
+            list = resource->getResourceInterfaces();
+            OC_LOG_V(DEBUG, TAG, "\tresource interface - %s", list[0].c_str());
+            i++;
+        }
+
+        OC_LOG(DEBUG, TAG, "Collection Resource Handle List");
+        i = 1;
+        for (handleIt = collectionResourceHandleList.begin();
+                handleIt != collectionResourceHandleList.end(); ++handleIt)
+        {
+            type = handleIt->first;
+            OC_LOG_V(DEBUG, TAG, "\t%d. collection resource type - %s", i, type.c_str());
+            OC_LOG(DEBUG, TAG, "\tdetails");
+
+            resourceHandle = handleIt->second;
+            OC_LOG_V(DEBUG, TAG, "\turi - %s", OCGetResourceUri(resourceHandle));
+            OC_LOG_V(DEBUG, TAG, "\tresource type - %s",
+                OCGetResourceTypeName(resourceHandle, 0));
+            OC_LOG_V(DEBUG, TAG, "\tresource interface - %s",
+                OCGetResourceInterfaceName(resourceHandle, 0));
+
+            childIt = childResourceHandleList.find(resourceHandle);
+            if (childIt != childResourceHandleList.end())
             {
+                handleList = childIt->second;
+                for (unsigned int j = 0; j < handleList.size(); j++)
+                {
 
-                cout << "\t\t" << j + 1 << ". child resource details" << endl;
+                    OC_LOG_V(DEBUG, TAG, "\t\t%d. child resource details", j + 1);
 
-                resourceHandle = handleList.at(j);
-                cout << "\t\t  uri - " << OCGetResourceUri(resourceHandle) << endl;
-                cout << "\t\t  resource type - " << OCGetResourceTypeName(resourceHandle, 0)
-                        << endl;
-                cout << "\t\t  resource interface - "
-                        << OCGetResourceInterfaceName(resourceHandle, 0) << endl << endl;
+                    resourceHandle = handleList.at(j);
+                    OC_LOG_V(DEBUG, TAG, "\t\turi - %s",
+                        OCGetResourceUri(resourceHandle));
+                    OC_LOG_V(DEBUG, TAG, "\t\tresource type - %s",
+                        OCGetResourceTypeName(resourceHandle, 0));
+                    OC_LOG_V(DEBUG, TAG, "\t\tresource interface - %s",
+                        OCGetResourceInterfaceName(resourceHandle, 0));
+                }
             }
+            i++;
         }
-
-        i++;
+#endif
     }
 }
-}
index da5f153..6c0252b 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file   GroupSynchronization.h
-
-/// @brief  This file contains the declaration of classes and
-///its members related to GroupSynchronization.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * GroupSynchronization.
+ */
 
 #ifndef __OC_GROUPSYNCHRONIZATION__
 #define __OC_GROUPSYNCHRONIZATION__
@@ -66,6 +68,7 @@ private:
     std::shared_ptr< OCResourceRequest > resourceRequest; // this is used for slow response
 
     static GroupSynchronization* groupSyncnstance;
+    static bool bIsFinding;
 
     GroupSynchronization()
     {
@@ -107,6 +110,9 @@ public:
             OCResourceHandle resourceHandle);
     OCStackResult leaveGroup(std::string collectionResourceType,
             OCResourceHandle resourceHandle);
+    OCStackResult leaveGroup(const std::shared_ptr< OCResource > resource,
+                std::string collectionResourceType,
+                OCResourceHandle resourceHandle);
     void deleteGroup(std::string collectionResourceType);
 
     std::map< std::string, OCResourceHandle > getGroupList();
old mode 100755 (executable)
new mode 100644 (file)
index 5a4777f..4ea8804
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file    ThingsConfiguration.cpp
-/// @brief
+/**
+ * @file
+ *
+ */
 
 #include <OCApi.h>
 #include <OCPlatform.h>
@@ -31,15 +33,62 @@ using namespace OC;
 
 namespace OIC
 {
-    const int SUCCESS_RESPONSE = 0;
     int cnt = 0;
 
     std::map< std::string, ConfigurationRequestEntry > configurationRequestTable;
-
     ThingsConfiguration* ThingsConfiguration::thingsConfigurationInstance = NULL;
-
     ConfigurationCallback g_bootstrapCallback;
 
+    ConfigurationRequestEntry::ConfigurationRequestEntry(std::string ID,
+                                                        ConfigurationCallback callback,
+                                                        std::shared_ptr< OCResource > resource,
+                                                        std::string updateVal)
+    {
+        m_ID = ID;
+        m_callback = callback;
+        m_resource = resource;
+        m_updateVal = updateVal;
+    }
+
+    ConfigurationUnitInfo::ConfigurationUnitInfo(std::string name,
+                                                std::string attribute,
+                                                std::string uri)
+    {
+        m_name = name;
+        m_attribute = attribute;
+        m_uri = uri;
+    }
+
+    std::string ConfigurationUnitInfo::getJSON()
+    {
+        std::string res;
+
+        res = "{\"name\":\"" + m_name + "\",\"property\":\"" + m_attribute + "\"}";
+
+        return res;
+    }
+
+    ThingsConfiguration::ThingsConfiguration(void)
+    {
+        ConfigurationUnitInfo unit[] =
+        {
+        { "all", "All attributes", "/oic/con" },
+        { "r", "Region", "/oic/con" },
+        { "st", "System Time", "/oic/con"},
+        { "loc", "Location", "/oic/con"},
+        { "c","Currency", "/oic/con" } };
+
+        for (int i = 0; i < NUMCONFUNIT; i++)
+            ConfigurationUnitTable.push_back(unit[i]);
+    }
+
+    ThingsConfiguration::~ThingsConfiguration(void){}
+
+    void ThingsConfiguration::setGroupManager(GroupManager *groupmanager)
+    {
+        g_groupmanager = groupmanager;
+    }
+
     ThingsConfiguration* ThingsConfiguration::getInstance()
     {
         if (thingsConfigurationInstance == NULL)
@@ -154,8 +203,6 @@ namespace OIC
     {
         std::shared_ptr < OCResource > resource = getResource(conf);
 
-        std::cout << __func__ << std::endl;
-
         if (resource)
         {
             QueryParamsMap query;
@@ -170,7 +217,6 @@ namespace OIC
                             std::bind(&ThingsConfiguration::onGetChildInfoForUpdate, this,
                                     std::placeholders::_1, std::placeholders::_2,
                                     std::placeholders::_3, conf)));
-
         }
 
     }
@@ -178,186 +224,173 @@ namespace OIC
     void ThingsConfiguration::onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode, std::string conf)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "GET request was successful" << std::endl;
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            getCallback(conf)(headerOptions, rep, eCode);
+            return ;
+        }
 
-            std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+        std::cout << "GET request was successful" << std::endl;
 
-            std::vector < OCRepresentation > children = rep.getChildren();
-            for (auto oit = children.begin(); oit != children.end(); ++oit)
-            {
-                std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
-            }
+        std::cout << "\tResource URI: " << rep.getUri() << std::endl;
 
-            // Get information by using configuration name(conf)
-            std::shared_ptr < OCResource > resource = getResource(conf);
-            std::string actionstring = conf;
-            std::string uri = getUriByConfigurationName(conf);
-            std::string attr = getAttributeByConfigurationName(conf);
+        std::vector < OCRepresentation > children = rep.getChildren();
+        for (auto oit = children.begin(); oit != children.end(); ++oit)
+        {
+            std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+        }
 
-            if (uri == "")
-                return;
+        // Get information by using configuration name(conf)
+        std::shared_ptr < OCResource > resource = getResource(conf);
+        std::string actionstring = conf;
+        std::string uri = getUriByConfigurationName(conf);
+        std::string attrKey = conf;
 
-            if (resource)
-            {
-                // In this nest, we create a new action set of which name is the configuration name.
-                // Required information consists of a host address, URI, attribute key, and
-                // attribute value.
-                ActionSet *newActionSet = new ActionSet();
-                newActionSet->actionsetName = conf;
+        if (uri == "")
+            return;
 
-                for (auto oit = children.begin(); oit != children.end(); ++oit)
-                {
-                    Action *newAction = new Action();
-
-                    // oit->getUri() includes a host address as well as URI.
-                    // We should split these to each other and only use the host address to create
-                    // a child resource's URI. Note that the collection resource and its child
-                    // resource are located in same host.
-                    newAction->target = getHostFromURI(oit->getUri()) + uri;
+        if (resource)
+        {
+            // In this nest, we create a new action set of which name is the configuration name.
+            // Required information consists of a host address, URI, attribute key, and
+            // attribute value.
+            ActionSet *newActionSet = new ActionSet();
+            newActionSet->actionsetName = conf;
 
-                    Capability *newCapability = new Capability();
-                    newCapability->capability = attr;
-                    newCapability->status = getUpdateVal(conf);
+            for (auto oit = children.begin(); oit != children.end(); ++oit)
+            {
+                Action *newAction = new Action();
 
-                    newAction->listOfCapability.push_back(newCapability);
-                    newActionSet->listOfAction.push_back(newAction);
-                }
+                // oit->getUri() includes a host address as well as URI.
+                // We should split these to each other and only use the host address to create
+                // a child resource's URI. Note that the collection resource and its child
+                // resource are located in same host.
+                newAction->target = getHostFromURI(oit->getUri()) + uri;
 
-                // Request to create a new action set by using the above actionSet
-                g_groupmanager->addActionSet(resource, newActionSet,
-                        std::function<
-                                void(const HeaderOptions& headerOptions,
-                                        const OCRepresentation& rep, const int eCode) >(
-                                std::bind(&ThingsConfiguration::onCreateActionSet, this,
-                                        std::placeholders::_1, std::placeholders::_2,
-                                        std::placeholders::_3, conf)));
+                Capability *newCapability = new Capability();
+                newCapability->capability = attrKey;
+                newCapability->status = getUpdateVal(conf);
 
-                free(newActionSet);
+                newAction->listOfCapability.push_back(newCapability);
+                newActionSet->listOfAction.push_back(newAction);
             }
 
-        }
-        else
-        {
-            std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
+            // Request to create a new action set by using the above actionSet
+            g_groupmanager->addActionSet(resource, newActionSet,
+                    std::function<
+                            void(const HeaderOptions& headerOptions,
+                                    const OCRepresentation& rep, const int eCode) >(
+                            std::bind(&ThingsConfiguration::onCreateActionSet, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, conf)));
+
+            free(newActionSet);
         }
     }
 
     void ThingsConfiguration::onGetChildInfoForGet(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode, std::string conf)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "GET request was successful" << std::endl;
-            std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+            std::cout << "onGet Response error: " << eCode << std::endl;
+            getCallback(conf)(headerOptions, rep, eCode);
+            return ;
+        }
 
-            std::shared_ptr< OCResource > resource, tempResource;
-            std::vector < std::shared_ptr< OCResource > > p_resources;
-            std::vector < std::string > m_if;
-            std::string uri = getUriByConfigurationName(conf);
+        std::cout << "GET request was successful" << std::endl;
+        std::cout << "\tResource URI: " << rep.getUri() << std::endl;
 
-            if (uri == "")
-                return;
+        std::shared_ptr< OCResource > resource, tempResource;
+        std::vector < std::shared_ptr< OCResource > > p_resources;
+        std::vector < std::string > m_if;
+        std::string uri = getUriByConfigurationName(conf);
 
-            if (uri == "/oic/con" || uri == "/factoryset" || uri == "/factoryset/oic/con")
-                m_if.push_back(BATCH_INTERFACE);
-            else
-                m_if.push_back(DEFAULT_INTERFACE);
+        if (uri == "")
+            return;
 
-            std::vector < OCRepresentation > children = rep.getChildren();
-            for (auto oit = children.begin(); oit != children.end(); ++oit)
-            {
-                std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+        if (uri == "/factoryset" || uri == "/factoryset/oic/con")
+            m_if.push_back(BATCH_INTERFACE);
+        else
+            m_if.push_back(DEFAULT_INTERFACE);
+
+        std::vector < OCRepresentation > children = rep.getChildren();
+        for (auto oit = children.begin(); oit != children.end(); ++oit)
+        {
+            std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
 
-                // Using a host address and child URIs, we can dynamically create resource objects.
-                // Note that the child resources have not found before, we have no resource objects.
-                // For this reason, we create the resource objects.
+            // Using a host address and child URIs, we can dynamically create resource objects.
+            // Note that the child resources have not found before, we have no resource objects.
+            // For this reason, we create the resource objects.
 
-                std::string host = getHostFromURI(oit->getUri());
-                tempResource = OCPlatform::constructResourceObject(host, uri, true,
-                        oit->getResourceTypes(), m_if);
+            std::string host = getHostFromURI(oit->getUri());
 
-                p_resources.push_back(tempResource);
-            }
+            tempResource = OCPlatform::constructResourceObject(host, uri, OC_IPV4, true,
+                    oit->getResourceTypes(), m_if);
+
+            p_resources.push_back(tempResource);
+        }
 
-            // Send GET messages to the child resources in turn.
-            for (unsigned int i = 0; i < p_resources.size(); ++i)
+        // Send GET messages to the child resources in turn.
+        for (unsigned int i = 0; i < p_resources.size(); ++i)
+        {
+            resource = p_resources.at(i);
+            if (resource)
             {
-                resource = p_resources.at(i);
-                if (resource)
+                try
                 {
-                    try
-                    {
-                        if (isSimpleResource(resource))
-                        {
-                            QueryParamsMap test;
-                            resource->get(test, getCallback(conf));
-                        }
-                        else
-                        {
-                            QueryParamsMap test;
-                            resource->get(resource->getResourceTypes().at(0), BATCH_INTERFACE, test,
-                                    getCallback(conf));
-                        }
-                    }
-                    catch (OCException& e)
-                    {
-                        std::cout << e.reason() << std::endl;
-                    }
-
+                    QueryParamsMap test;
+                    resource->get(test, getCallback(conf));
                 }
+                catch (OCException& e)
+                {
+                    std::cout << e.reason() << std::endl;
+                }
+
             }
         }
-        else
-        {
-            std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
-        }
     }
 
     void ThingsConfiguration::onCreateActionSet(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode, std::string conf)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "PUT request was successful" << std::endl;
-
-            std::shared_ptr < OCResource > resource = getResource(conf);
-            if (resource)
-            {
-                // Now, it is time to execute the action set.
-                g_groupmanager->executeActionSet(resource, conf,
-                        std::function<
-                                void(const HeaderOptions& headerOptions,
-                                        const OCRepresentation& rep, const int eCode) >(
-                                std::bind(&ThingsConfiguration::onExecuteForGroupAction, this,
-                                        std::placeholders::_1, std::placeholders::_2,
-                                        std::placeholders::_3, conf)));
-            }
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            getCallback(conf)(headerOptions, rep, eCode);
+            return ;
         }
-        else
+
+        std::cout << "PUT request was successful" << std::endl;
+
+        std::shared_ptr < OCResource > resource = getResource(conf);
+        if (resource)
         {
-            std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
+            // Now, it is time to execute the action set.
+            g_groupmanager->executeActionSet(resource, conf,
+                    std::function<
+                            void(const HeaderOptions& headerOptions,
+                                    const OCRepresentation& rep, const int eCode) >(
+                            std::bind(&ThingsConfiguration::onExecuteForGroupAction, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, conf)));
         }
     }
 
     void ThingsConfiguration::onExecuteForGroupAction(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode, std::string conf)
     {
-        if (eCode == SUCCESS_RESPONSE)
-        {
-            std::cout << "PUT request was successful" << std::endl;
-
-            getCallback(conf)(headerOptions, rep, eCode);
-        }
-        else
+        if (eCode != OC_STACK_OK)
         {
             std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
+            getCallback(conf)(headerOptions, rep, eCode);
+            return ;
         }
+
+        std::cout << "PUT request was successful" << std::endl;
+
+        getCallback(conf)(headerOptions, rep, eCode);
     }
 
     bool ThingsConfiguration::isSimpleResource(std::shared_ptr< OCResource > resource)
@@ -386,34 +419,31 @@ namespace OIC
     void ThingsConfiguration::onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
             const int eCode, std::string conf)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "Get request was successful" << std::endl;
-
+            std::cout << "onGet Response error: " << eCode << std::endl;
             getCallback(conf)(headerOptions, rep, eCode);
+            return ;
         }
-        else
-        {
-            std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
-        }
+
+        std::cout << "Get request was successful" << std::endl;
+
+        getCallback(conf)(headerOptions, rep, eCode);
     }
 
     void ThingsConfiguration::onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
             const int eCode, std::string conf)
     {
-        if (eCode == SUCCESS_RESPONSE)
-        {
-            std::cout << "PUT request was successful" << std::endl;
-
-            // Callback
-            getCallback(conf)(headerOptions, rep, eCode);
-        }
-        else
+        if (eCode != OC_STACK_OK)
         {
             std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
+            getCallback(conf)(headerOptions, rep, eCode);
+            return;
         }
+
+        std::cout << "PUT request was successful" << std::endl;
+
+        getCallback(conf)(headerOptions, rep, eCode);
     }
 
     OCStackResult ThingsConfiguration::updateConfigurations(std::shared_ptr< OCResource > resource,
@@ -453,7 +483,7 @@ namespace OIC
         if (isSimpleResource(resource))
         {
             // This resource does not need to use a group manager. Just send a PUT message
-            rep.setValue(getAttributeByConfigurationName(conf), getUpdateVal(conf));
+            rep.setValue(conf, getUpdateVal(conf));
             return resource->put(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, rep, query,
                     std::function<
                             void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
@@ -546,16 +576,14 @@ namespace OIC
     void ThingsConfiguration::onGetBootstrapInformation(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
+            std::cout << "onGET Response error: " << eCode << std::endl;
             g_bootstrapCallback(headerOptions, rep, eCode);
+            return;
         }
 
-        else
-        {
-            std::cout << "onGET Response error: " << eCode << std::endl;
-            std::exit(-1);
-        }
+        g_bootstrapCallback(headerOptions, rep, eCode);
     }
 
     void ThingsConfiguration::onFoundBootstrapServer(
@@ -610,3 +638,4 @@ namespace OIC
         return g_groupmanager->findCandidateResources(type, &onFoundBootstrapServer);
     }
 }
+
index 79e2579..ccf90d4 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file   ThingsConfiguration.h
-
-/// @brief  This file contains the declaration of classes and its members related to
-///         ThingsConfiguration.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * ThingsConfiguration.
+ */
 
 #ifndef __OC_THINGSCONFIGURATION__
 #define __OC_THINGSCONFIGURATION__
@@ -59,11 +61,7 @@ namespace OIC
     {
     public:
         ConfigurationRequestEntry(std::string ID, ConfigurationCallback callback,
-                std::shared_ptr< OCResource > resource, std::string updateVal):
-                m_ID(ID), m_callback(callback), m_resource(resource), m_updateVal(updateVal)
-        {
-        }
-        ;
+                std::shared_ptr< OCResource > resource, std::string updateVal);
 
         // Configuration Name (used in key value in std::map structure)
         // e.g., time, network, security, and so on
@@ -90,29 +88,16 @@ namespace OIC
     public:
 
         std::string m_name;
-        std::string m_description;
-        std::string m_uri;
         std::string m_attribute;
+        std::string m_uri;
 
-        ConfigurationUnitInfo(std::string name, std::string description, std::string uri,
-                std::string attribute) :
-                m_name(name), m_description(description), m_uri(uri), m_attribute(attribute)
-        {
-        }
-        ;
+        ConfigurationUnitInfo(std::string name, std::string attribute, std::string uri);
 
         // If a developer wants to know a list of configuration names, gives it in JSON format.
-        std::string getJSON()
-        {
-            std::string res;
-
-            res = "{\"name\":\"" + m_name + "\",\"description\":\"" + m_description + "\"}";
-
-            return res;
-        }
+        std::string getJSON();
     };
 
-#define NUMCONFUNIT 6
+#define NUMCONFUNIT 5
     typedef std::string ConfigurationName;
     typedef std::string ConfigurationValue;
 
@@ -122,44 +107,18 @@ namespace OIC
         /**
          * Constructor for ThingsConfiguration. Constructs a new ThingsConfiguration
          */
-        ThingsConfiguration(void)
-        {
-            ConfigurationUnitInfo unit[] =
-            {
-            { "configuration", "Configuration Collection's value and its child resource's value",
-                    "/oic/con", "value" },
-            { "region", "the current region in which the device is located geographically",
-                    "/oic/con/0/region", "value" },
-            { "timelink", "link of time collection.", "/oic/con/0/time", "link" },
-            { "ipaddress", "IP Address", "/oic/con/network/0/IPAddress", "value" },
-            { "securitymode",
-                    "Resource for security information (credentials, access control list etc.)",
-                    "/oic/con/security/0/mode", "value" },
-                    { "getfactoryset", "get all default configuration value", "/factoryset/oic/con",
-                            "value" } };
-
-            for (int i = 0; i < NUMCONFUNIT; i++)
-                ConfigurationUnitTable.push_back(unit[i]);
-        }
-        ;
+        ThingsConfiguration(void);
 
         /**
          * Virtual destructor
          */
-        ~ThingsConfiguration(void)
-        {
-        }
-        ;
+        ~ThingsConfiguration(void);
 
         static ThingsConfiguration *thingsConfigurationInstance;
         static ThingsConfiguration* getInstance();
         void deleteInstance();
 
-        void setGroupManager(GroupManager *groupmanager)
-        {
-            g_groupmanager = groupmanager;
-        }
-        ;
+        void setGroupManager(GroupManager *groupmanager);
 
         /**
          * API for updating configuration value of multiple things of a target group or a single
@@ -182,8 +141,8 @@ namespace OIC
          * updateConfiguration()->...(CoAP msg. is transmitted)->OnPut()->callback function in APP.
          *
          * @param resource - resource pointer representing the target group or the single thing.
-         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
-         *                         (e.g., installedlocation, currency, (IP)address)
+         * @param configurations - ConfigurationUnit: an attribute key of target resource
+         *                         (e.g., loc, st, c, r)
          *                         Value : a value to be updated
          * @param callback - callback.
          *
@@ -207,7 +166,7 @@ namespace OIC
          * getConfigurations()->...(CoAP msg. is transmitted)->onGet()->callback function in APP.
          *
          * @param resource - resource pointer representing the target group or the single thing.
-         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource.
+         * @param configurations - ConfigurationUnit: an attribute key of target resource.
          * @param callback - callback.
          *
          * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
@@ -263,271 +222,6 @@ namespace OIC
         static void onFoundBootstrapServer(std::vector< std::shared_ptr< OCResource > > resources);
         static void onGetBootstrapInformation(const HeaderOptions& headerOptions,
                 const OCRepresentation& rep, const int eCode);
-        // Copyright 2014 Samsung Electronics All Rights Reserved.
-
-        /// @file   ThingsConfiguration.h
-
-        /// @brief  This file contains the declaration of classes and its members related to
-        ///         ThingsConfiguration.
-
-#ifndef __OC_THINGSCONFIGURATION__
-#define __OC_THINGSCONFIGURATION__
-
-#include <string>
-#include <vector>
-#include <map>
-#include <cstdlib>
-#include "GroupManager.h"
-#include "OCPlatform.h"
-#include "OCApi.h"
-
-        using namespace OC;
-
-/// Declearation of Configuation Callback funtion type
-        typedef std::function<
-        void(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode) > ConfigurationCallback;
-
-        typedef std::string ConfigurationName;
-        typedef std::string ConfigurationValue;
-
-        /**
-         * @brief
-         * The following class is used as a item stacking in request queue. The class stores a
-         * request and referential information (e.g., a configuration name, a target resource
-         * object, a callback function passed from the applications, and a update value). When the
-         * function for updating/getting configuration value is called from applications, this class
-         * instance is created and stored in the request queue. The queue is maintained in
-         * a std::map structure so if desiring to find a specific request, you can find it
-         * by querying a configuration name.
-         */
-        class ConfigurationRequestEntry
-        {
-        public:
-            ConfigurationRequestEntry(std::string ID, ConfigurationCallback callback,
-                    std::shared_ptr< OCResource > resource, std::string updateVal) :
-            m_ID(ID), m_callback(callback), m_resource(resource), m_updateVal(updateVal)
-            {
-            }
-            ;
-
-            // Configuration Name (used in key value in std::map structure)
-            // e.g., time, network, security, and so on
-            std::string m_ID;
-            // Reference callback pointer
-            ConfigurationCallback m_callback;
-            // Reference resource object
-            std::shared_ptr< OCResource > m_resource;
-            // Update value only used for configuration update
-            std::string m_updateVal;
-        };
-
-        /**
-         * @brief
-         * The following class is used to store providing configuration name and its relevant
-         * information. The relevant information includes a brief description, uri, and attribute
-         * key. Note that a developer only specifies a configuration name, not URI nor attribute
-         * key, to update/get a value to a remote. Thus, using configuration name, we convert it to
-         * more specific information (i.e. uri and attribute key) to send a request. This class is
-         * reponsible to storing these information.
-         */
-        class ConfigurationUnitInfo
-        {
-        public:
-
-            std::string m_name;
-            std::string m_description;
-            std::string m_uri;
-            std::string m_attribute;
-
-            ConfigurationUnitInfo(std::string name, std::string description, std::string uri,
-                    std::string attribute) :
-            m_name(name), m_description(description), m_uri(uri), m_attribute(attribute)
-            {
-            }
-            ;
-
-            // If a developer wants to know a list of configuration names, gives it in JSON format.
-            std::string getJSON()
-            {
-                std::string res;
-
-                res = "{\"name\":\"" + m_name + "\",\"description\":\"" + m_description + "\"}";
-
-                return res;
-            }
-        };
-
-#define NUMCONFUNIT 6
-        typedef std::string ConfigurationName;
-        typedef std::string ConfigurationValue;
-
-        class ThingsConfiguration
-        {
-        public:
-            /**
-             * Constructor for ThingsConfiguration. Constructs a new ThingsConfiguration
-             */
-            ThingsConfiguration(void)
-            {
-                ConfigurationUnitInfo unit[] =
-                {
-                    {   "configuration", "Configuration value and its child resource's value",
-                            "/oic/con", "value"},
-                    {   "region", "the current region in which the Thing is located geographically",
-                        "/oic/con/0/region", "value"},
-                    {   "timelink", "link of time collection.", "/oic/con/0/time", "link"},
-                    {   "ipaddress", "IP Address", "/oic/con/network/0/IPAddress", "value"},
-                    {   "securitymode",
-                        "Resource for security information (credentials, access control list etc.)",
-                        "/oic/con/security/0/mode", "value"},
-                    {   "getfactoryset", "get all default configuration value",
-                        "/factoryset/oic/con", "value"}};
-
-                for (int i = 0; i < NUMCONFUNIT; i++)
-                ConfigurationUnitTable.push_back(unit[i]);
-            }
-            ;
-
-            /**
-             * Virtual destructor
-             */
-            ~ThingsConfiguration(void)
-            {
-            }
-            ;
-
-            static ThingsConfiguration *thingsConfigurationInstance;
-            static ThingsConfiguration* getInstance();
-            void deleteInstance();
-
-            void setGroupManager(GroupManager *groupmanager)
-            {
-                g_groupmanager = groupmanager;
-            }
-            ;
-
-            /**
-             * API for updating configuration value of multiple things of a target group or a single
-             * thing.
-             * Callback is called when a response arrives.
-             * Before using the below function, a developer should acquire a resource pointer of
-             * (collection) resource that he want to send a request by calling findResource()
-             * function provided in OCPlatform. And he should also notice a "Configuration Name"
-             * term which represents a nickname of a target attribute of a resource that he wants to
-             * update.
-             * The base motivation to introduce the term is to avoid a usage of URI to access
-             * a resource from a developer. Thus, a developer should know which configuration names
-             * are supported by Things Configuration class and what the configuration name means.
-             * To get a list of supported configuration names, use getListOfSupportedConfigurationU-
-             * nits() function, which provides the list in JSON format.
-             * NOTICE: A series of callback functions is called from updateConfigurations() function
-             * (1) For a collection resource
-             * updateConfiguration()->onDeleteActionSet()->onGetChildInfoForUpdate()->onCreateActio-
-             * nSet()->...(CoAP msg. is transmitted)->OnExecuteForGroupAction()->callback function
-             * in APP.
-             * (2) For a simple resource
-             * updateConfiguration()->...(CoAP msg. is transmitted)->OnPut()->callback function in
-             * APP.
-             *
-             * @param resource - resource pointer representing the target group or the single thing.
-             * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
-             *                         (e.g., installedlocation, currency, (IP)address)
-             *                         Value : a value to be updated
-             * @param callback - callback.
-             *
-             * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-             *
-             * NOTE: OCStackResult is defined in ocstack.h.
-             */
-            OCStackResult updateConfigurations(std::shared_ptr< OCResource > resource,
-                    std::map< ConfigurationName, ConfigurationValue > configurations,
-                    ConfigurationCallback callback);
-
-            /**
-             * API for getting configuration value of multiple things of a target group or a single
-             * thing.
-             * Callback is called when a response arrives.
-             * NOTICE: A series of callback functions is called from getConfigurations() function:
-             * (1) For a collection resource
-             * getConfigurations()->onGetChildInfoForGet()->...(CoAP msg. is transmitted)
-             * ->callback function in APP.
-             * (2) For a simple resource
-             * getConfigurations()->...(CoAP msg. is transmitted)->onGet()->callback function in APP
-             *
-             * @param resource - resource pointer representing the target group or the single thing.
-             * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
-             * @param callback - callback.
-             *
-             * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-             *
-             * NOTE: OCStackResult is defined in ocstack.h.
-             */
-            OCStackResult getConfigurations(std::shared_ptr< OCResource > resource,
-                    std::vector< ConfigurationName > configurations, ConfigurationCallback callback);
-
-            /**
-             * API to show a list of supported configuration units (configurable parameters)
-             * Callback call when a response arrives.
-             *
-             * @return the list in JSON format
-             */
-            std::string getListOfSupportedConfigurationUnits();
-
-            /**
-             * API for bootstrapping functionality. Find a bootstrap server and get configuration
-             * information from the bootstrap server. With the information, make a configuration
-             * resource.
-             *
-             * @param callback - callback.
-             *
-             * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-             *
-             * NOTE: OCStackResult is defined in ocstack.h.
-             */
-            OCStackResult doBootstrap(ConfigurationCallback callback);
-
-        private:
-
-            GroupManager *g_groupmanager;
-
-            std::vector< ConfigurationUnitInfo > ConfigurationUnitTable;
-
-            void onExecuteForGroupAction(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            void onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            void onGetChildInfoForGet(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            void onCreateActionSet(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            void onGetActionSet(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            void onDeleteActionSet(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            void onGet(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            void onPut(const HeaderOptions& headerOptions,
-                const OCRepresentation& rep, const int eCode, std::string conf);
-            static void onFoundBootstrapServer(std::vector< std::shared_ptr< OCResource >
-                > resources);
-            static void onGetBootstrapInformation(const HeaderOptions& headerOptions,
-                    const OCRepresentation& rep, const int eCode);
-
-            std::shared_ptr< OCResource > getResource(std::string conf);
-            ConfigurationCallback getCallback(std::string conf);
-            std::string getUpdateVal(std::string conf);
-            std::string getAttributeByConfigurationName(ConfigurationName name);
-            std::string getUriByConfigurationName(ConfigurationName name);
-
-            std::string getHostFromURI(std::string oldUri);
-
-            bool isSimpleResource(std::shared_ptr< OCResource > resource);
-            bool hasBatchInterface(std::shared_ptr< OCResource > resource);
-
-        };
-
-#endif  /* __OC_THINGSCONFIGURATION__*/
 
         std::shared_ptr< OCResource > getResource(std::string conf);
         ConfigurationCallback getCallback(std::string conf);
index 7eccc62..03ca932 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file    ThingsDiagnostics.cpp
-///  @brief
+/**
+ * @file
+ *
+ */
 
 #include <OCApi.h>
 #include <OCPlatform.h>
@@ -31,12 +33,57 @@ using namespace OC;
 
 namespace OIC
 {
-    const int SUCCESS_RESPONSE = 0;
-
     std::map< std::string, DiagnosticsRequestEntry > diagnosticsRequestTable;
-
     ThingsDiagnostics* ThingsDiagnostics::thingsDiagnosticsInstance = NULL;
 
+    DiagnosticsRequestEntry::DiagnosticsRequestEntry(std::string ID, DiagnosticsCallback callback,
+                std::shared_ptr< OCResource > resource, std::string updateVal)
+    {
+        m_ID = ID;
+        m_callback = callback;
+        m_resource = resource;
+        m_updateVal = updateVal;
+    }
+
+    DiagnosticsUnitInfo::DiagnosticsUnitInfo(std::string name,
+                                            std::string attribute,
+                                            std::string uri)
+    {
+        m_name = name;
+        m_attribute = attribute;
+        m_uri = uri;
+    }
+
+    std::string DiagnosticsUnitInfo::getJSON()
+    {
+        std::string res;
+
+        res = "{\"name\":\"" + m_name + "\",\"attribute\":\"" + m_attribute + "\"}";
+
+        return res;
+    }
+
+    ThingsDiagnostics::ThingsDiagnostics()
+    {
+        DiagnosticsUnitInfo unit[] =
+                {
+                { "rb", "Reboot", "/oic/diag"},
+                { "ssc", "StartStatCollection", "/oic/diag"},
+                { "fr", "Factory Reset", "/oic/diag" } };
+
+        for (int i = 0; i < NUMDIAGUNIT; i++)
+            DiagnosticsUnitTable.push_back(unit[i]);
+    }
+
+    ThingsDiagnostics::~ThingsDiagnostics()
+    {
+    }
+
+    void ThingsDiagnostics::setGroupManager(GroupManager *groupmanager)
+    {
+        g_groupmanager = groupmanager;
+    }
+
     ThingsDiagnostics* ThingsDiagnostics::getInstance()
     {
         if (thingsDiagnosticsInstance == NULL)
@@ -149,131 +196,151 @@ namespace OIC
     void ThingsDiagnostics::onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode, std::string diag)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "GET request was successful" << std::endl;
+            std::cout << "onGet Response error: " << eCode << std::endl;
+            getCallback(diag)(headerOptions, rep, eCode);
+            return ;
+        }
 
-            std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+        std::cout << "GET request was successful" << std::endl;
 
-            std::vector < OCRepresentation > children = rep.getChildren();
-            for (auto oit = children.begin(); oit != children.end(); ++oit)
-            {
-                std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
-            }
+        std::cout << "\tResource URI: " << rep.getUri() << std::endl;
 
-            // Get information by using diagnostics name(diag)
-            std::shared_ptr < OCResource > resource = getResource(diag);
-            std::string actionstring = diag;
-            std::string uri = getUriByDiagnosticsName(diag);
-            std::string attr = getAttributeByDiagnosticsName(diag);
+        std::vector < OCRepresentation > children = rep.getChildren();
+        for (auto oit = children.begin(); oit != children.end(); ++oit)
+        {
+            std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+        }
 
-            if (uri == "")
-                return;
+        // Get information by using diagnostics name(diag)
+        std::shared_ptr < OCResource > resource = getResource(diag);
+        std::string actionstring = diag;
+        std::string uri = getUriByDiagnosticsName(diag);
+        std::string attrKey = diag;
 
-            if (resource)
-            {
-                // In this nest, we create a new action set of which name is the dignostics name.
-                // Required information consists of a host address, URI, attribute key, and
-                // attribute value.
-                ActionSet *newActionSet = new ActionSet();
-                newActionSet->actionsetName = diag;
+        if (uri == "")
+            return;
 
-                for (auto oit = children.begin(); oit != children.end(); ++oit)
-                {
-                    Action *newAction = new Action();
+        if (resource)
+        {
+            // In this nest, we create a new action set of which name is the dignostics name.
+            // Required information consists of a host address, URI, attribute key, and
+            // attribute value.
+            ActionSet *newActionSet = new ActionSet();
+            newActionSet->actionsetName = diag;
 
-                    // oit->getUri() includes a host address as well as URI.
-                    // We should split these to each other and only use the host address to create
-                    // a child resource's URI. Note that the collection resource and its child
-                    // resource are located in same host.
-                    newAction->target = getHostFromURI(oit->getUri()) + uri;
+            for (auto oit = children.begin(); oit != children.end(); ++oit)
+            {
+                Action *newAction = new Action();
 
-                    Capability *newCapability = new Capability();
-                    newCapability->capability = attr;
-                    newCapability->status = getUpdateVal(diag);
+                // oit->getUri() includes a host address as well as URI.
+                // We should split these to each other and only use the host address to create
+                // a child resource's URI. Note that the collection resource and its child
+                // resource are located in same host.
+                newAction->target = getHostFromURI(oit->getUri()) + uri;
 
-                    newAction->listOfCapability.push_back(newCapability);
-                    newActionSet->listOfAction.push_back(newAction);
-                }
+                Capability *newCapability = new Capability();
+                newCapability->capability = attrKey;
+                newCapability->status = getUpdateVal(diag);
 
-                // Request to create a new action set by using the above actionSet
-                g_groupmanager->addActionSet(resource, newActionSet,
-                        std::function<
-                                void(const HeaderOptions& headerOptions,
-                                        const OCRepresentation& rep, const int eCode) >(
-                                std::bind(&ThingsDiagnostics::onCreateActionSet, this,
-                                        std::placeholders::_1, std::placeholders::_2,
-                                        std::placeholders::_3, diag)));
+                newAction->listOfCapability.push_back(newCapability);
+                newActionSet->listOfAction.push_back(newAction);
+            }
 
-                free(newActionSet);
+            // Request to create a new action set by using the above actionSet
+            g_groupmanager->addActionSet(resource, newActionSet,
+                    std::function<
+                            void(const HeaderOptions& headerOptions,
+                                    const OCRepresentation& rep, const int eCode) >(
+                            std::bind(&ThingsDiagnostics::onCreateActionSet, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, diag)));
 
-            }
+            free(newActionSet);
 
         }
-        else
-        {
-            std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
-        }
     }
 
     void ThingsDiagnostics::onCreateActionSet(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode, std::string diag)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "PUT request was successful" << std::endl;
-
-            std::shared_ptr < OCResource > resource = getResource(diag);
-            if (resource)
-            {
-                // Now, it is time to execute the action set.
-                g_groupmanager->executeActionSet(resource, diag,
-                        std::function<
-                                void(const HeaderOptions& headerOptions,
-                                        const OCRepresentation& rep, const int eCode) >(
-                                std::bind(&ThingsDiagnostics::onExecuteForGroupAction, this,
-                                        std::placeholders::_1, std::placeholders::_2,
-                                        std::placeholders::_3, diag)));
-            }
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            getCallback(diag)(headerOptions, rep, eCode);
+            return ;
         }
-        else
+
+        std::cout << "PUT request was successful" << std::endl;
+
+        std::shared_ptr < OCResource > resource = getResource(diag);
+        if (resource)
         {
-            std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
+            // Now, it is time to execute the action set.
+            g_groupmanager->executeActionSet(resource, diag,
+                    std::function<
+                            void(const HeaderOptions& headerOptions,
+                                    const OCRepresentation& rep, const int eCode) >(
+                            std::bind(&ThingsDiagnostics::onExecuteForGroupAction, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, diag)));
         }
     }
 
     void ThingsDiagnostics::onExecuteForGroupAction(const HeaderOptions& headerOptions,
             const OCRepresentation& rep, const int eCode, std::string diag)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "PUT request was successful" << std::endl;
-
+            std::cout << "onPut Response error: " << eCode << std::endl;
             getCallback(diag)(headerOptions, rep, eCode);
+            return ;
         }
-        else
+
+        std::cout << "PUT request was successful" << std::endl;
+        getCallback(diag)(headerOptions, rep, eCode);
+
+        // Delete the created actionset
+        std::shared_ptr < OCResource > resource = getResource(diag);
+        if (resource)
         {
-            std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
+            g_groupmanager->deleteActionSet(resource, diag,
+                    std::function<
+                            void(const HeaderOptions& headerOptions,
+                                    const OCRepresentation& rep, const int eCode) >(
+                            std::bind(&ThingsDiagnostics::onDeleteGroupAction, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, diag)));
         }
     }
 
-    void ThingsDiagnostics::onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
-            const int eCode, std::string diag)
+    void ThingsDiagnostics::onDeleteGroupAction(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string diag)
     {
-        if (eCode == SUCCESS_RESPONSE)
+        if (eCode != OC_STACK_OK)
         {
-            std::cout << "PUT request was successful" << std::endl;
-
-            getCallback(diag)(headerOptions, rep, eCode);
+            std::cout << "Delete actionset returned with error: " << eCode << diag << std::endl;
+            return;
         }
-        else
+
+        std::cout << "Deleted the actionset created!" << diag<< std::endl;
+    }
+
+    void ThingsDiagnostics::onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode, std::string diag)
+    {
+        if (eCode != OC_STACK_OK)
         {
             std::cout << "onPut Response error: " << eCode << std::endl;
-            std::exit(-1);
+            getCallback(diag)(headerOptions, rep, eCode);
+            return ;
         }
+
+        std::cout << "PUT request was successful" << std::endl;
+
+        getCallback(diag)(headerOptions, rep, eCode);
+
     }
 
     bool ThingsDiagnostics::isSimpleResource(std::shared_ptr< OCResource > resource)
@@ -296,7 +363,7 @@ namespace OIC
             return OC_STACK_ERROR;
         }
 
-        std::string diag = "reboot";
+        std::string diag = "rb";
 
         // Check the request queue if a previous request is still left. If so, remove it.
         std::map< std::string, DiagnosticsRequestEntry >::iterator iter =
@@ -349,7 +416,7 @@ namespace OIC
             return OC_STACK_ERROR;
         }
 
-        std::string diag = "factoryreset";
+        std::string diag = "fr";
 
         // Check the request queue if a previous request is still left. If so, remove it.
         std::map< std::string, DiagnosticsRequestEntry >::iterator iter =
@@ -393,3 +460,4 @@ namespace OIC
         }
     }
 }
+
index dda9362..a144470 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file   ThingsDiagnostics.h
-
-/// @brief  This file contains the declaration of classes and its members related to
-///         ThingsDiagnostics.
+/**
+ * @file
+ *
+ * This file contains the declaration of classes and its members related to
+ * ThingsDiagnostics.
+ */
 
 #ifndef __OC_THINGSDIAGNOSTICS__
 #define __OC_THINGSDIAGNOSTICS__
@@ -37,7 +39,6 @@
 using namespace OC;
 namespace OIC
 {
-
     /// Declearation of Diagnostics Callback funtion type
     typedef std::function<
             void(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
@@ -56,11 +57,7 @@ namespace OIC
     {
     public:
         DiagnosticsRequestEntry(std::string ID, DiagnosticsCallback callback,
-                std::shared_ptr< OCResource > resource, std::string updateVal) :
-                m_ID(ID), m_callback(callback), m_resource(resource), m_updateVal(updateVal)
-        {
-        }
-        ;
+                std::shared_ptr< OCResource > resource, std::string updateVal);
 
         // Diagnostics Name (used in key value in std::map structure)
         // e.g., reboot and factoryset
@@ -88,27 +85,14 @@ namespace OIC
     class DiagnosticsUnitInfo
     {
     public:
-        DiagnosticsUnitInfo(std::string name, std::string description, std::string uri,
-                std::string attribute) :
-                m_name(name), m_description(description), m_uri(uri), m_attribute(attribute)
-        {
-        }
-        ;
-
         std::string m_name;
-        std::string m_description;
-        std::string m_uri;
         std::string m_attribute;
+        std::string m_uri;
 
-        // If a developer wants to know a list of diagnostics names, gives it in JSON format.
-        std::string getJSON()
-        {
-            std::string res;
-
-            res = "{\"name\":\"" + m_name + "\",\"description\":\"" + m_description + "\"}";
+        DiagnosticsUnitInfo(std::string name, std::string attribute, std::string uri);
 
-            return res;
-        }
+        // If a developer wants to know a list of configuration names, gives it in JSON format.
+        std::string getJSON();
     };
 
 #define NUMDIAGUNIT 3
@@ -121,39 +105,18 @@ namespace OIC
         /**
          * Constructor for ThingsDiagnostics. Constructs a new ThingsDiagnostics
          */
-        ThingsDiagnostics(void)
-        {
-            DiagnosticsUnitInfo unit[] =
-                    {
-                    { "reboot", "reboot", "/oic/diag/0/reboot", "value" },
-                            { "value",
-                                    "Collecting any device statistics",
-                                    "/oic/diag/0/startCollection", "value" },
-                            { "factoryreset", "restore all configuration values to default values",
-                                    "/oic/diag/0/factoryReset", "value" } };
-
-            for (int i = 0; i < NUMDIAGUNIT; i++)
-                DiagnosticsUnitTable.push_back(unit[i]);
-        }
-        ;
+        ThingsDiagnostics(void);
 
         /**
          * Virtual destructor
          */
-        ~ThingsDiagnostics(void)
-        {
-        }
-        ;
+        ~ThingsDiagnostics(void);
 
         static ThingsDiagnostics *thingsDiagnosticsInstance;
         static ThingsDiagnostics* getInstance();
         void deleteInstance();
 
-        void setGroupManager(GroupManager *groupmanager)
-        {
-            g_groupmanager = groupmanager;
-        }
-        ;
+        void setGroupManager(GroupManager *groupmanager);
 
         /**
          * API to make things reboot
@@ -199,6 +162,8 @@ namespace OIC
 
         void onExecuteForGroupAction(const HeaderOptions& headerOptions,
                 const OCRepresentation& rep, const int eCode, std::string conf);
+        void onDeleteGroupAction(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
         void onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
                 const OCRepresentation& rep, const int eCode, std::string conf);
         void onCreateActionSet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
index a65b987..3c0178f 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-/// @file    ThingsManager.cpp
+/**
+ * @file
+ *
+ */
 
 #include "ThingsManager.h"
 #include "GroupManager.h"
@@ -76,6 +79,13 @@ namespace OIC
         return result;
     }
 
+    OCStackResult ThingsManager::bindResourceToGroup(OCResourceHandle& childHandle, std::shared_ptr< OCResource > resource, OCResourceHandle& collectionHandle)
+    {
+        OCStackResult result = g_groupManager->bindResourceToGroup(childHandle,resource,collectionHandle);
+
+        return result;
+    }
+
     OCStackResult ThingsManager::findGroup(std::vector< std::string > collectionResourceTypes,
             FindCallback callback)
     {
@@ -115,6 +125,13 @@ namespace OIC
         return result;
     }
 
+    OCStackResult ThingsManager::leaveGroup(const std::shared_ptr< OCResource > resource,
+                            std::string collectionResourceType,
+                            OCResourceHandle resourceHandle)
+    {
+        return g_groupSync->leaveGroup(resource, collectionResourceType, resourceHandle);
+    }
+
     void ThingsManager::deleteGroup(std::string collectionResourceType)
     {
         g_groupSync->deleteGroup(collectionResourceType);
@@ -175,6 +192,16 @@ namespace OIC
     {
         return g_groupManager->executeActionSet(resource, actionsetName, cb);
     }
+    OCStackResult ThingsManager::executeActionSet(std::shared_ptr< OCResource > resource,
+                    std::string actionsetName, long int delay, PostCallback cb)
+    {
+        return g_groupManager->executeActionSet(resource, actionsetName, delay, cb);
+    }
+    OCStackResult ThingsManager::cancelActionSet(std::shared_ptr< OCResource > resource,
+                    std::string actionsetName, PostCallback cb)
+    {
+        return g_groupManager->cancelActionSet(resource, actionsetName, cb);
+    }
     OCStackResult ThingsManager::getActionSet(std::shared_ptr< OCResource > resource,
             std::string actionsetName, GetCallback cb)
     {
index ac543d2..6ddeebc 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
 #
@@ -29,15 +49,15 @@ if target_os in ['linux', 'tizen']:
 
                conf = Configure(lib_env)
 
-               if not conf.CheckLib('boost_thread'):
+               if target_os not in ['tizen'] and not conf.CheckLib('boost_thread', language='C++'):
                        print 'Did not find boost_thread, exiting!'
                        Exit(1)
 
-               if not conf.CheckLib('boost_system'):
+               if target_os not in ['tizen'] and not conf.CheckLib('boost_system', language='C++'):
                        print 'Did not find boost_system, exiting!'
                        Exit(1)
 
-               conf.Finish()
+               lib_env = conf.Finish()
 
 ######################################################################
 # The 'include' path of external libraries
@@ -47,7 +67,6 @@ lib_env.AppendUnique(CPPPATH = [
                resource_path + '/include' ,
                resource_path + '/oc_logger/include',
                resource_path + '/csdk/stack/include',
-               resource_path + '/csdk/ocsocket/include',
                resource_path + '/csdk/ocrandom/include',
                resource_path + '/csdk/logger/include'
                ])
@@ -78,3 +97,4 @@ elif target_os == 'darwin':
 
 Import('env')
 lib_env.AppendUnique(LIBPATH = env.get('BUILD_DIR'))
+
diff --git a/tools/Readme.scons.txt b/tools/Readme.scons.txt
deleted file mode 100644 (file)
index 2129efe..0000000
+++ /dev/null
@@ -1,191 +0,0 @@
-== How to build IoTivity projects ==
-
-IoTivity includes a series of projects. You can find all these projects here:
-    https://gerrit.iotivity.org/gerrit/#/admin/projects/
-
-You can build IoTivity project on Linux / Windows / MAC OSX for various OS(
-Linux, Tizen, Android, Arduino, Windows, MAC OSX, IOS ...).
-The output of the build is in:
-  <top directory of the project>/out/<target_os>/<target_arch>/<build_type>/
-e.g.
-       oic-resource/out/android/armeabi-v7a/release/.
-
-This document takes 'iotivity' project as example, the way to build other
-projects is almost the same.
-
-=== IoTivity project build tool scons ===
-
-Scons is a cross-platform build tool, its usage is quite similar to GNU make.
-To build a project, you just require to run following command at the directory
-where a SConstruct file exists(SConstruct is the entrance of scons build, it's
-equivalent to Makefile of 'make') :
-      $ scons [options] [target]
-
-In additional, usually the scons build script of a project provides useful help
-information(include build options). To see the help information:
-      $ scons [options] -h
-
-Note: If no value is specified for an option, the default value will be used.
-The change of options value may impact the output.
-
-
-=== Prerequites ===
-
-* 1. Scons
-
-Please refer to the following page to install scons:
-   http://www.scons.org/doc/production/HTML/scons-user.html#chap-build-install
-(Note: on Windows, install Python 2.x before installing scons)
-
-* 2. IDE/SDK Prerequites
-To build for some OS (Android / Arduino / IOS ...), an IDE/SDK may be required,
-please go to the relative page to download and install the required IDE/SDK.
-
-Android:
-To build for Android, Andorid NDK and SDK are required.
-  Android NDK: http://developer.android.com/tools/sdk/ndk/index.html
-  Android SDK: http://developer.android.com/sdk/index.html
-(Note: as in some IoTivity projects, C++11 features are used, recommend Android
- NDK >= r10, according to our test result r10c is the best one currently)
-
-Arduino:
-To build for Arduino, Arduino IDE is required.
-  Arduino IDE: http://arduino.cc/en/Main/Software
-  (Note: recommend install Arduino IDE >=1.5.7)
-
-Arduino builds are dependent on latest Time library. Download it from here:
-    http://www.pjrc.com/teensy/td_libs_Time.html
-and extract to <arduino_ide_root>/libraries/
-
-(Note: If you are using Arduino IDE 1.5.8 BETA on Windows, it may pop up some
-dll isn't found. please copy relative dll from the IDE directory to
-C:\Windows\SysWOW64. IDE 1.5.7 doesn't have this issue. Other version IDE isn't
-tested.)
-
-Apple:
-To build for Mac OSX or IOS, Xcode is required.
-  Xcode: https://developer.apple.com/xcode/downloads/
-
-Java:
-To build the Java code, JDK is required.
-  JDK: http://www.oracle.com/technetwork/java/javase/downloads/index.html
-(If the project doesn't include Java code or you wouldn't like build the
-Java codes, this isn't required)
-
-(Note: for convenience, suggest add the IDE/SDK path in environment variable,
-so you don't need to add it in command line each time. The build script will
-guide you to do that.)
-
-* 3. External libraries
-For Android and IOS build, most of the external libraries are provided as
-binary in oic-utilities project (https://oic-review.01.org/gerrit/oic-utilities).
-Please download it in the same directory as other IoTivity projects. If it's
-in different directory, an additional option (OIC_UITLS) will be required. The
-build command should be:
-      $ scons OIC_UITLS=<path to oic-utilities> [other options] [target]
-
-(Note: for convenience, you can also add it in environment variable. So you
-don't need to add this option in command line each time.)
-  e.g.:
-      $ export OIC_UITLS=<path to oic-utilities project>
-
-
-=== Build IoTivity project on Linux(Ubuntu) ===
-
-Generally, it's required to specify the target OS and target ARCH, that's to say
-tell Scons which OS and which ARCH you'd like build this project for. By default,
-the target OS and ARCH is the same as the host.
-
-Some more options may be required, please care the 'error' notification when build.
-For help about how to set an option, please run:
-       $ scons TARGET_OS=xxx TARGET_ARCH=yyy [XXX=zzz ...] -h
-
-1. Build IoTivity project for Linux
-      $ cd <top directory of the project>
-      $ sudo apt-get install libboost-dev libboost-program-options-dev libexpat1-dev
-      $ scons
-
-2. Build IoTivity project for Android
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=android TARGET_ARCH=xxx
-(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard. To see all of its
-allowed value, please execute command 'scons TARGET_OS=android -Q -h')
-
-Note: Currently as x86_64/arm64_v8a external library binaries aren't provided,
-you may meet link problem if build executable binary which depends on external
-library for x86_64/arm64_v8a.
-
-3. Build IoTivity project for Arduino
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy
-(xxx can be avr, arm; yyy is the name of the board, to get its allowed value
-run: scons TARGET_OS=arduino TARGET_ARCH=xxx -h. You may see a option 'CPU' in
-the output of above command line, that's due to some boards have different
-processors, to specify the processor, add 'CPU=zzz' in the command line. If no
-'CPU' option exists, that means the board only support one kind of processor,
-it's unnecessary to specify it)
-
-4. Build Iotivity project for Tizen
-      $ cd <top directory of the project>
-      $ gbs build -A xxx --packaging-dir tools/tizen/
-(xxx can be i586 or armv7l, we provide the spec file required by gbs tool at
-toools/tizen directory. gbs is default build tool for Tizen platfrom, we can
-refer the following wiki to setup Tizen development environment:
-https://source.tizen.org/documentation/developer-guide/getting-started-guide)
-
-=== Build IoTivity project on Windows ===
-
-1. Build IoTivity project for Android(It's the same as on Ubuntu)
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=android TARGET_ARCH=xxx
-(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard ...)
-
-2. Build IoTivity project for Arduino(It's the same as on Ubuntu)
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy
-(xxx can be avr, arm; yyy is the name of the board, to get its allowed value
-run: scons TARGET_OS=arduino TARGET_ARCH=xxx -h. You may see a option 'CPU' in
-the output of above command line, that's due to some boards have different
-processor, to specify the processor, add 'CPU=zzz' in the command line. If no
-'CPU' option exists, that means the board only support one kind of processor,
-it's unnecessary to specify it)
-
-
-Note: Currently most IoTivity project doesn't support Windows, so you can't set
-TARGET_OS to 'windows' except the project support Windows.
-
-That's to say if the project doesn't support Windows, run:
-      $ scons TARGET_OS=windows ....
-or run on Windows
-      $ scons
-may always fail.
-
-
-=== Build IoTivity project on Mac OSX ===
-
-1. Build IoTivity project for Mac OSX
-      $ cd <top directory of the project>
-      $ scons SYS_VERSION=yyy
-(yyy is the OSX version, e.g. 10.9)
-
-2. Build IoTivity project for Android(It's the same as on Ubuntu)
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=android TARGET_ARCH=xxx
-(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard)
-
-3. Build IoTivity project for IOS
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=ios TARGET_ARCH=xxx SYS_VERSION=yyy
-(xxx can be i386, x86_64, armv7, armv7s, arm64, yyy is IOS version, e.g. 7.0)
-
-Note:
-1) for convenience, a script (auto_build.sh) is provided to run possible build
-at once. Following is the usage:
-
-To build:
-     $ auto_build.sh <path-to-android-ndk> <path-to-arduino-home>
-To clean:
-     $ auto_build.sh -c
-
-2) For Arduino build, the Time library should >=1.3. The old can only be built
-with Arduino IDE 1.0.x
diff --git a/tools/SConstruct b/tools/SConstruct
deleted file mode 100644 (file)
index 92eac38..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-##
-# The main build script
-#
-##
-
-# Load common build config
-SConscript('build_common/SConscript')
-
-# Load extra options
-SConscript('extra_options.scons')
-Import('env')
-
-target_os = env.get('TARGET_OS')
-if target_os == 'arduino':
-       SConscript('arduino.scons')
-# By default, src_dir is current dir, the build_dir is:
-#     ./out/<target_os>/<target_arch>/<release or debug>/
-#
-# The build_dir is a variant directory of the source directory(You can
-# consider build_dir as a soft link to src_dir, for detail please refer to:
-#     http://www.scons.org/doc/production/HTML/scons-user.html#f-VariantDir
-#
-# Any way, to make the output is in build_dir, when load scripts, the path should
-# be relevant to build_dir.
-build_dir = env.get('BUILD_DIR')
-
-# Build 'resource' sub-project
-SConscript(build_dir + 'resource/SConscript')
-
-# Build 'service' sub-project
-SConscript(build_dir + 'service/SConscript')
-
-# Append targets information to the help information, to see help info, execute command line:
-#     $ scon [options] -h
-env.PrintTargets()
-
-# Print bin upload command line (arduino only)
-if target_os == 'arduino':
-       env.UploadHelp()
diff --git a/tools/arduino.scons b/tools/arduino.scons
deleted file mode 100644 (file)
index 4ab2aff..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-##
-# This script includes arduino specific config for oic-resource
-##
-Import('env')
-
-env.ImportLib('Time')
-if env.get('NET') == 'Ethernet':
-       env.ImportLib('Ethernet')
-else:
-       env.ImportLib('WiFi')
-env.ImportLib('SPI')
\ No newline at end of file
diff --git a/tools/auto_build.sh b/tools/auto_build.sh
deleted file mode 100755 (executable)
index 536331c..0000000
+++ /dev/null
@@ -1,103 +0,0 @@
-#! /bin/bash
-
-# Ideally we will capture the exit code of each step and try them all before failing
-# the build script.  For now, use set -e and fail the build at first failure.
-set -e
-
-function clean()
-{
-       echo "*********** Clean build *************"
-       scons -c
-       rm -rf out
-}
-
-function build()
-{
-       if [ $(uname -s) = "Linux" ]
-        then
-               echo "*********** Build for linux *************"
-               scons RELEASE=$3
-       fi
-
-       # Note: for android, as oic-resource uses C++11 feature stoi and to_string,
-       # it requires gcc-4.9, currently only android-ndk-r10(for linux)
-       # and windows android-ndk-r10(64bit target version) support these features.
-       if [ "$BUILD_FOR_ANDROID" = "true" ]
-               then
-
-               echo "*********** Build Boost for android ***********"
-               pushd extlibs
-               ./buildDependencies.sh
-               popd
-
-               echo "*********** Build for android x86 *************"
-               scons TARGET_OS=android TARGET_ARCH=x86 ANDROID_NDK=$1 RELEASE=$3
-
-               echo "*********** Build for android armeabi *************"
-               scons TARGET_OS=android TARGET_ARCH=armeabi ANDROID_NDK=$1 RELEASE=$3
-
-               echo "*********** Build for android armeabi-v7a *************"
-               scons TARGET_OS=android TARGET_ARCH=armeabi-v7a ANDROID_NDK=$1 RELEASE=$3
-
-               echo "*********** Build for android armeabi-v7a-hard *************"
-               scons TARGET_OS=android TARGET_ARCH=armeabi-v7a-hard ANDROID_NDK=$1 RELEASE=$3
-       fi
-       
-       echo "*********** Build for arduino avr *************"
-       scons TARGET_OS=arduino TARGET_ARCH=avr ARDUINO_HOME=$2 RELEASE=$3
-
-       echo "*********** Build for arduino arm *************"
-       scons TARGET_OS=arduino TARGET_ARCH=arm ARDUINO_HOME=$2 RELEASE=$3
-
-       if [ $(uname -s) = "Darwin" ]
-       then
-               echo "*********** Build for OSX *************"
-               scons TARGET_OS=darwin SYS_VERSION=10.9 RELEASE=$3
-
-               echo "*********** Build for IOS i386 *************"
-               scons TARGET_OS=ios TARGET_ARCH=i386 SYS_VERSION=7.0 RELEASE=$3
-
-               echo "*********** Build for IOS x86_64 *************"
-               scons TARGET_OS=ios TARGET_ARCH=x86_64 SYS_VERSION=7.0 RELEASE=$3
-
-               echo "*********** Build for IOS armv7 *************"
-               scons TARGET_OS=ios TARGET_ARCH=armv7 SYS_VERSION=7.0 RELEASE=$3
-
-               echo "*********** Build for IOS armv7s *************"
-               scons TARGET_OS=ios TARGET_ARCH=armv7s SYS_VERSION=7.0 RELEASE=$3
-
-               echo "*********** Build for IOS arm64 *************"
-               scons TARGET_OS=ios TARGET_ARCH=arm64 SYS_VERSION=7.0 RELEASE=$3
-       fi
-}
-
-function  help()
-{
-       echo "Usage:"
-        echo "  build:"
-        echo "     `basename $0` <path-to-android-ndk> <path-to-arduino-home>"
-        echo "  clean:"
-        echo "     `basename $0` -c"
-}
-
-if [ $# -eq 1 ]
-then
-       if [ $1 = '-c' ]
-       then
-               clean
-               exit 0
-       else
-               help
-               exit -1
-       fi
-elif [ $# -ne 2 ]
-then
-       help
-       exit -1
-fi
-
-# Suppress "Reading ..." message and enable parallel build
-export SCONSFLAGS="-Q -j 4"
-build $1 $2 true
-build $1 $2 false
-echo "===================== done ====================="
diff --git a/tools/darwin/build-ios.sh b/tools/darwin/build-ios.sh
new file mode 100755 (executable)
index 0000000..edde6fe
--- /dev/null
@@ -0,0 +1,10 @@
+#!/bin/bash
+
+# change this to what version of Xcode you have installed
+SDKVER=8.2
+
+scons TARGET_OS=ios TARGET_ARCH=armv7 SYS_VERSION=$SDKVER RELEASE=false
+scons TARGET_OS=ios TARGET_ARCH=armv7s SYS_VERSION=$SDKVER RELEASE=false
+scons TARGET_OS=ios TARGET_ARCH=arm64 SYS_VERSION=$SDKVER RELEASE=false
+scons TARGET_OS=ios TARGET_ARCH=i386 SYS_VERSION=$SDKVER RELEASE=false
+scons TARGET_OS=ios TARGET_ARCH=x86_64 SYS_VERSION=$SDKVER RELEASE=false
diff --git a/tools/darwin/mkfwk_ios.sh b/tools/darwin/mkfwk_ios.sh
new file mode 100755 (executable)
index 0000000..0eb86b7
--- /dev/null
@@ -0,0 +1,113 @@
+#!/bin/sh
+
+
+#VERSION_IOS="${MAJOR_VERSION}.${MINOR_VERSION}.${RELEASE_NUMBER}.${BUILD_NUMBER}"
+VERSION_IOS="0.9.0.1"
+
+
+OUTDIR=$PWD/out/ios
+BUILD=debug
+LIBCOAP=libcoap
+SDKLIB=liboctbstack
+LIPO="xcrun -sdk iphoneos lipo"
+
+
+VERSION_TYPE=Alpha
+FRAMEWORK_NAME=iotivity-csdk
+FRAMEWORK_VERSION=A
+FRAMEWORK_CURRENT_VERSION=${VERSION_IOS}
+FRAMEWORK_COMPATIBILITY_VERSION=${VERSION_IOS}
+FRAMEWORKDIR=out/ios
+
+FRAMEWORK_BUNDLE=$FRAMEWORKDIR/$FRAMEWORK_NAME.framework
+rm -rf $FRAMEWORK_BUNDLE
+
+echo "Framework: Setting up directories..."
+mkdir -p $FRAMEWORK_BUNDLE
+mkdir -p $FRAMEWORK_BUNDLE/Versions
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Resources
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Headers
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Documentation
+
+echo "Framework: Creating symlinks..."
+ln  -s $FRAMEWORK_VERSION               $FRAMEWORK_BUNDLE/Versions/Current
+ln  -s Versions/Current/Headers         $FRAMEWORK_BUNDLE/Headers
+ln  -s Versions/Current/Resources       $FRAMEWORK_BUNDLE/Resources
+ln  -s Versions/Current/Documentation   $FRAMEWORK_BUNDLE/Documentation
+ln  -s Versions/Current/$FRAMEWORK_NAME $FRAMEWORK_BUNDLE/$FRAMEWORK_NAME
+FRAMEWORK_INSTALL_NAME=$FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/$FRAMEWORK_NAME
+
+lipolite()
+{
+   PREV="$PWD" 
+   cd "$1"
+   ar -x "$2"
+   cd "$PREV"
+}
+
+
+echo "Extracting libraries..."
+mkdir $OUTDIR/objs
+
+ARCHS="armv7 armv7s arm64 i386 x86_64"
+FATFILE=""
+
+for ARCH in $ARCHS
+do
+    echo "extracting $ARCH"
+       mkdir $OUTDIR/objs/$ARCH
+       lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$LIBCOAP.a" 
+       lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$SDKLIB.a" 
+       ar -r $OUTDIR/objs/$ARCH.a $OUTDIR/objs/$ARCH/*.o
+done
+
+
+echo "Lipoing library into $FRAMEWORK_INSTALL_NAME..."
+$LIPO \
+       -create \
+        -arch armv7 "$OUTDIR/objs/armv7.a" \
+        -arch armv7s "$OUTDIR/objs/armv7s.a" \
+        -arch arm64 "$OUTDIR/objs/arm64.a" \
+        -arch i386 "$OUTDIR/objs/i386.a" \
+        -arch x86_64  "$OUTDIR/objs/x86_64.a" \
+        -output "$FRAMEWORK_INSTALL_NAME" \
+    || abort "Lipo $1 failed"
+
+echo rm -rf objs
+find $OUTDIR/objs -name "*.o" | xargs rm 
+
+echo "Framework: Copying includes..."
+cp -r  resource/csdk/stack/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/csdk/ocsocket/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/csdk/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/csdk/ocmalloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
+
+echo "Framework: Creating plist..."
+cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+        <key>CFBundleDevelopmentRegion</key>
+        <string>English</string>
+        <key>CFBundleExecutable</key>
+        <string>${FRAMEWORK_NAME}</string>
+        <key>CFBundleIdentifier</key>
+        <string>org.iotivity</string>
+        <key>CFBundleInfoDictionaryVersion</key>
+        <string>6.0</string>
+        <key>CFBundlePackageType</key>
+        <string>FMWK</string>
+        <key>CFBundleSignature</key>
+        <string>????</string>
+        <key>CFBundleVersion</key>
+        <string>${FRAMEWORK_CURRENT_VERSION}</string>
+</dict>
+</plist>
+EOF
+
+echo
+echo "    ================================================================="
+echo "    Done"
+echo
diff --git a/tools/darwin/mkfwk_osx.sh b/tools/darwin/mkfwk_osx.sh
new file mode 100755 (executable)
index 0000000..f0ede46
--- /dev/null
@@ -0,0 +1,115 @@
+#!/bin/sh
+
+
+#VERSION_IOS="${MAJOR_VERSION}.${MINOR_VERSION}.${RELEASE_NUMBER}.${BUILD_NUMBER}"
+VERSION_IOS="0.9.0.1"
+
+
+OUTDIR=$PWD/out/darwin
+BUILD=debug
+LIBCOAP=libcoap
+SDKLIB=liboctbstack
+LIPO="xcrun -sdk iphoneos lipo"
+
+
+VERSION_TYPE=Alpha
+FRAMEWORK_NAME=iotivity-csdk
+FRAMEWORK_VERSION=A
+FRAMEWORK_CURRENT_VERSION=${VERSION_IOS}
+FRAMEWORK_COMPATIBILITY_VERSION=${VERSION_IOS}
+FRAMEWORKDIR=out/darwin
+
+FRAMEWORK_BUNDLE=$FRAMEWORKDIR/$FRAMEWORK_NAME.framework
+rm -rf $FRAMEWORK_BUNDLE
+
+echo "Framework: Setting up directories..."
+mkdir -p $FRAMEWORK_BUNDLE
+mkdir -p $FRAMEWORK_BUNDLE/Versions
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Resources
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Headers
+mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Documentation
+
+echo "Framework: Creating symlinks..."
+ln  -s $FRAMEWORK_VERSION               $FRAMEWORK_BUNDLE/Versions/Current
+ln  -s Versions/Current/Headers         $FRAMEWORK_BUNDLE/Headers
+ln  -s Versions/Current/Resources       $FRAMEWORK_BUNDLE/Resources
+ln  -s Versions/Current/Documentation   $FRAMEWORK_BUNDLE/Documentation
+ln  -s Versions/Current/$FRAMEWORK_NAME $FRAMEWORK_BUNDLE/$FRAMEWORK_NAME
+FRAMEWORK_INSTALL_NAME=$FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/$FRAMEWORK_NAME
+
+lipolite()
+{
+   PREV="$PWD" 
+   cd "$1"
+   ar -x "$2"
+   cd "$PREV"
+}
+
+
+echo "Extracting libraries..."
+mkdir $OUTDIR/objs
+
+ARCHS="x86_64"
+FATFILE=""
+
+for ARCH in $ARCHS
+do
+    echo "extracting $ARCH"
+       mkdir $OUTDIR/objs/$ARCH
+       lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$LIBCOAP.a" 
+       lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$SDKLIB.a" 
+       ar -r $OUTDIR/objs/$ARCH.a $OUTDIR/objs/$ARCH/*.o
+done
+
+
+echo "Lipoing library into $FRAMEWORK_INSTALL_NAME..."
+cp $OUTDIR/objs/x86_64.a "$FRAMEWORK_INSTALL_NAME"
+
+#$LIPO \
+#      -create \
+#        -arch armv7 "$OUTDIR/objs/armv7.a" \
+#        -arch armv7s "$OUTDIR/objs/armv7s.a" \
+#        -arch arm64 "$OUTDIR/objs/arm64.a" \
+#        -arch i386 "$OUTDIR/objs/i386.a" \
+#        -arch x86_64  "$OUTDIR/objs/x86_64.a" \
+#        -output "$FRAMEWORK_INSTALL_NAME" \
+#    || abort "Lipo $1 failed"
+
+echo rm -rf objs
+find $OUTDIR/objs -name "*.o" | xargs rm 
+
+echo "Framework: Copying includes..."
+cp -r  resource/csdk/stack/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/csdk/ocsocket/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/csdk/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/csdk/ocmalloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
+
+echo "Framework: Creating plist..."
+cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+        <key>CFBundleDevelopmentRegion</key>
+        <string>English</string>
+        <key>CFBundleExecutable</key>
+        <string>${FRAMEWORK_NAME}</string>
+        <key>CFBundleIdentifier</key>
+        <string>org.iotivity</string>
+        <key>CFBundleInfoDictionaryVersion</key>
+        <string>6.0</string>
+        <key>CFBundlePackageType</key>
+        <string>FMWK</string>
+        <key>CFBundleSignature</key>
+        <string>????</string>
+        <key>CFBundleVersion</key>
+        <string>${FRAMEWORK_CURRENT_VERSION}</string>
+</dict>
+</plist>
+EOF
+
+echo
+echo "    ================================================================="
+echo "    Done"
+echo
diff --git a/tools/extra_options.scons b/tools/extra_options.scons
deleted file mode 100644 (file)
index dc2e48e..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-######################################################################
-# This script manages extra build options
-#
-######################################################################
-import os
-import platform
-
-Import('env')
-
-target_os = env.get('TARGET_OS')
-target_arch = env.get('TARGET_ARCH')
-src_dir = env.get('SRC_DIR')
-
-if target_os == 'arduino':
-       # Add 'NET' build option, let user select board network connection type
-       vars = Variables()
-       vars.Add(EnumVariable('NET', 'Network connection type', 'Ethernet', ['Ethernet', 'Wifi']))
-       vars.Update(env)
-       Help(vars.GenerateHelpText(env))
-
-# check 'cereal' library, temporarily put it here
-if not os.path.exists(src_dir + '/extlibs/cereal'):
-       print '''
-*********************************** Error: **************************************
-*  'Cereal' library doesn't exist. please download cereal to extlibs directory  *
-* add apply the patch as following:                                             *
-*     $ git clone https://github.com/USCiLab/cereal.git <src_dir>/extlibs/cereal*
-*     $ cd <src_dir>/extlibs/cereal                                             *
-*     $ git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245               *
-*     $ git apply ../../resource/patches/cereal_gcc46.patch                     *
-*********************************************************************************
-'''
-       Exit(1)
-else:
-       env.AppendUnique(CPPPATH = [src_dir + '/extlibs/cereal/include'])
diff --git a/tools/scons/BoostBootstrap.py b/tools/scons/BoostBootstrap.py
new file mode 100644 (file)
index 0000000..d1f722b
--- /dev/null
@@ -0,0 +1,89 @@
+# -*- coding: utf-8 -*-\r
+\r
+# *********************************************************************\r
+#\r
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.\r
+#\r
+# *********************************************************************\r
+#\r
+# Licensed under the Apache License, Version 2.0 (the "License");\r
+# you may not use this file except in compliance with the License.\r
+# You may obtain a copy of the License at\r
+#\r
+#      http:#www.apache.org/licenses/LICENSE-2.0\r
+#\r
+# Unless required by applicable law or agreed to in writing, software\r
+# distributed under the License is distributed on an "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# See the License for the specific language governing permissions and\r
+# limitations under the License.\r
+#\r
+# *********************************************************************\r
+\r
+# This SCONS builder executes the boost bootstrap function which\r
+# is needed to create their build utility called 'b2'\r
+\r
+import os, subprocess\r
+import SCons.Builder, SCons.Node, SCons.Errors\r
+\r
+# creates the downloading output message\r
+# @param s original message\r
+# @param target target name\r
+# @param source source name\r
+# @param env environment object\r
+def __message( s, target, source, env ) :\r
+    print 'bootstrapping using [%s] ...' % (source[0])\r
+\r
+\r
+# Create the builder action which executes the bootstrap script\r
+#\r
+# @param target target file on the local drive\r
+# @param source URL for download\r
+# @param env environment object\r
+def __action( target, source, env ) :\r
+    cmd = None\r
+\r
+    # Windows...\r
+    if env['PLATFORM'] in ['win32'] :\r
+        if env.WhereIs('cmd') :\r
+            # TODO: Add Windows Support\r
+            cmd = None\r
+\r
+    # read the tools on *nix systems and sets the default parameters\r
+    elif env['PLATFORM'] in ['darwin', 'linux', 'posix'] :\r
+        if env.WhereIs('sh') :\r
+            cmd = './bootstrap.sh'\r
+\r
+    if not cmd :\r
+        raise SCons.Errors.StopError('Bootstrapping shell on this platform [%s] unkown' % (env['PLATFORM']))\r
+\r
+    # We need to be in the target's directory\r
+    cwd = os.path.dirname(os.path.realpath(target[0].path))\r
+\r
+    # build it now (we need the shell, because some programs need it)\r
+    devnull = open(os.devnull, 'wb')\r
+    handle  = subprocess.Popen( cmd, shell=True, cwd=cwd, stdout=devnull )\r
+\r
+    if handle.wait() <> 0 :\r
+        raise SCons.Errors.BuildError( 'Bootstrapping script [%s] on the source [%s]' % (cmd, source[0])  )\r
+\r
+# Define the emitter of the builder\r
+#\r
+# @param target target file on the local drive\r
+# @param source\r
+# @param env environment object\r
+def __emitter( target, source, env ) :\r
+    return target, source\r
+\r
+# Generate function which adds the builder to the environment,\r
+#\r
+# @param env environment object\r
+def generate( env ) :\r
+    env['BUILDERS']['BoostBootstrap'] = SCons.Builder.Builder( action = __action,  emitter = __emitter,  target_factory = SCons.Node.FS.File,  source_factory = SCons.Node.FS.File,  single_source = True,  PRINT_CMD_LINE_FUNC = __message )\r
+\r
+# Exist function of the builder\r
+# @param env environment object\r
+# @return true\r
+def exists( env ) :\r
+    return 1\r
+\r
diff --git a/tools/scons/BoostBuild.py b/tools/scons/BoostBuild.py
new file mode 100644 (file)
index 0000000..2d43d33
--- /dev/null
@@ -0,0 +1,156 @@
+# -*- coding: utf-8 -*-\r
+\r
+# *********************************************************************\r
+#\r
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.\r
+#\r
+# *********************************************************************\r
+#\r
+# Licensed under the Apache License, Version 2.0 (the "License");\r
+# you may not use this file except in compliance with the License.\r
+# You may obtain a copy of the License at\r
+#\r
+#      http:#www.apache.org/licenses/LICENSE-2.0\r
+#\r
+# Unless required by applicable law or agreed to in writing, software\r
+# distributed under the License is distributed on an "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# See the License for the specific language governing permissions and\r
+# limitations under the License.\r
+#\r
+# *********************************************************************\r
+\r
+# This builder executes the boost builder ('b2') for the toolchain\r
+# defined currently in the SCONS environment. This builder was created\r
+# to create cross-compiled version of boost. In particular, it has\r
+# created to create boost binaries for Android's various architectures.\r
+\r
+import os, subprocess\r
+import SCons.Builder, SCons.Node, SCons.Errors\r
+\r
+# Creates the building message\r
+#\r
+# @param s original message\r
+# @param target target name\r
+# @param source source name\r
+# @param env environment object\r
+def __message( s, target, source, env ) :\r
+    print "building boost from [%s] for ..." % (source[0])\r
+\r
+\r
+# Create the builder action which constructs a user-config.jam based\r
+# on the current toolchain and executes the boost build system ('b2')\r
+#\r
+# @param target target file on the local drive\r
+# @param source URL for download\r
+# @@param env environment object\r
+def __action( target, source, env ) :\r
+    cmd = None\r
+\r
+    # Windows...\r
+    if env["PLATFORM"] in ["win32"] :\r
+        if env.WhereIs("cmd") :\r
+            # TODO: Add Windows Support\r
+            cmd = None\r
+\r
+    # read the tools on *nix systems and sets the default parameters\r
+    elif env["PLATFORM"] in ["darwin", "linux", "posix"] :\r
+        if env.WhereIs("sh") :\r
+            cmd = ['./b2']\r
+\r
+    if not cmd :\r
+        raise SCons.Errors.StopError("Boost build system not supported on this platform [%s]" % (env["PLATFORM"]))\r
+\r
+    # We need to be in the target's directory\r
+    cwd = os.path.dirname(os.path.realpath(source[0].path))\r
+\r
+    # Gather all of the path, bin and flags\r
+    version     = env.get('VERSION','')\r
+    target_os   = env['TARGET_OS']\r
+    target_arch = env['TARGET_ARCH']\r
+    tool_path   = os.path.dirname(env['CXX'])\r
+    cxx_bin     = os.path.basename(env['CXX'])\r
+    ar_bin      = os.path.basename(env['AR'])\r
+    ranlib_bin  = os.path.basename(env['RANLIB'])\r
+    ccflags     = list(env['CFLAGS'])\r
+    cxxflags    = list(env['CXXFLAGS'])\r
+\r
+    try:\r
+        cxxflags.remove('-fno-rtti')\r
+    except ValueError:\r
+        pass\r
+    try:\r
+        cxxflags.remove('-fno-exceptions')\r
+    except ValueError:\r
+        pass\r
+\r
+    # Write a user-config for this variant\r
+    user_config_name = cwd+os.sep+'tools'+os.sep+'build'+os.sep+'src'+os.sep+'user-config.jam'\r
+    user_config_file = open(user_config_name, 'w')\r
+    user_config_file.write('import os ;\n')\r
+    user_config_file.write('using gcc :')\r
+    user_config_file.write(' '+version+' :')\r
+    #user_config_file.write(' :')\r
+    #user_config_file.write(' '+os.path.basename(toolchain['CXX']['BIN'])+' :\n')\r
+    user_config_file.write(' '+cxx_bin+' :\n')\r
+    user_config_file.write('    <archiver>'+ar_bin+'\n')\r
+    user_config_file.write('    <ranlib>'+ranlib_bin+'\n')\r
+    for value in env['CPPDEFINES'] :\r
+        if len(value) > 1 :\r
+            user_config_file.write('    <compileflags>-D'+value[0]+'='+value[1]+'\n')\r
+        else :\r
+            user_config_file.write('    <compileflags>-D'+value[0]+'\n')\r
+    for value in env['CPPPATH'] :\r
+        user_config_file.write('    <compileflags>-I'+value+'\n')\r
+    for flag in ccflags :\r
+        user_config_file.write('    <compileflags>'+flag+'\n')\r
+    for flag in cxxflags :\r
+        user_config_file.write('    <cxxflags>'+flag+'\n')\r
+    user_config_file.write('    ;\n')\r
+    user_config_file.close();\r
+\r
+    # Ensure that the toolchain is in the PATH\r
+    penv = os.environ.copy()\r
+    penv["PATH"] = tool_path+":" + penv["PATH"]\r
+\r
+    build_path = 'build' + os.sep + target_os + os.sep + target_arch\r
+\r
+    cmd.append('-q')\r
+    cmd.append('target-os=linux')\r
+    cmd.append('link=static')\r
+    cmd.append('threading=multi')\r
+    cmd.append('--layout=system')\r
+    cmd.append('--build-type=minimal')\r
+    cmd.append('--prefix='+env['PREFIX'])\r
+    cmd.append('--build-dir='+build_path)\r
+    for module in env.get('MODULES',[]) :\r
+        cmd.append('--with-'+module)\r
+    cmd.append('headers')\r
+    cmd.append('install')\r
+\r
+    # build it now (we need the shell, because some programs need it)\r
+    devnull = open(os.devnull, "wb")\r
+    handle  = subprocess.Popen( cmd, env=penv, cwd=cwd ) #, stdout=devnull )\r
+\r
+    if handle.wait() <> 0 :\r
+        raise SCons.Errors.BuildError( "Building boost [%s] on the source [%s]" % (cmd, source[0])  )\r
+\r
+# Define the emitter of the builder\r
+#\r
+# @param target target file on the local drive\r
+# @param source\r
+# @param env environment object\r
+def __emitter( target, source, env ) :\r
+    return target, source\r
+\r
+# Generate function which adds the builder to the environment\r
+#\r
+# @param env environment object\r
+def generate( env ) :\r
+    env["BUILDERS"]["BoostBuild"] = SCons.Builder.Builder( action = __action,  emitter = __emitter,  target_factory = SCons.Node.FS.Entry,  source_factory = SCons.Node.FS.File,  single_source = True,  PRINT_CMD_LINE_FUNC = __message )\r
+\r
+# Exist function of the builder\r
+# @param env environment object\r
+# @return true\r
+def exists( env ) :\r
+    return 1\r
diff --git a/tools/scons/Configure.py b/tools/scons/Configure.py
new file mode 100644 (file)
index 0000000..88c184a
--- /dev/null
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-\r
+\r
+# *********************************************************************\r
+#\r
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.\r
+#\r
+# *********************************************************************\r
+#\r
+# Licensed under the Apache License, Version 2.0 (the "License");\r
+# you may not use this file except in compliance with the License.\r
+# You may obtain a copy of the License at\r
+#\r
+#      http:#www.apache.org/licenses/LICENSE-2.0\r
+#\r
+# Unless required by applicable law or agreed to in writing, software\r
+# distributed under the License is distributed on an "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# See the License for the specific language governing permissions and\r
+# limitations under the License.\r
+#\r
+# *********************************************************************\r
+\r
+# This builder executes configure\r
+\r
+import os, subprocess\r
+import SCons.Builder, SCons.Node, SCons.Errors\r
+\r
+# Create the output message\r
+#\r
+# @param s original message\r
+# @param target target name\r
+# @param source source name\r
+# @param env environment object\r
+def __message( s, target, source, env ) :\r
+    print "Configuring using [%s] ..." % (source[0])\r
+\r
+# Create the action\r
+#\r
+# @param target target file on the local drive\r
+# @param source URL for download\r
+# @@param env environment object\r
+def __action( target, source, env ) :\r
+    cmd = None\r
+\r
+    # Windows...\r
+    if env["PLATFORM"] in ["win32"] :\r
+        if env.WhereIs("cmd") :\r
+            # TODO: Add Windows Support\r
+            cmd = None\r
+\r
+    # read the tools on *nix systems and sets the default parameters\r
+    elif env["PLATFORM"] in ["darwin", "linux", "posix"] :\r
+        if env.WhereIs("sh") :\r
+            cmd = "./configure"\r
+\r
+    if not cmd :\r
+        raise SCons.Errors.StopError("Configure shell on this platform [%s] unkown" % (env["PLATFORM"]))\r
+\r
+    # We need to be in the target's directory\r
+    cwd = os.path.dirname(os.path.realpath(target[0].path))\r
+\r
+    # build it now (we need the shell, because some programs need it)\r
+    devnull = open(os.devnull, "wb")\r
+    handle  = subprocess.Popen( cmd, shell=True, cwd=cwd, stdout=devnull )\r
+\r
+    if handle.wait() <> 0 :\r
+        raise SCons.Errors.BuildError( "Configuring script [%s] on the source [%s]" % (cmd, source[0])  )\r
+\r
+# Define the builder's emitter\r
+#\r
+# @param target target file on the local drive\r
+# @param source \r
+# @param env environment object\r
+def __emitter( target, source, env ) :\r
+    return target, source\r
+\r
+# Generate function which adds the builder to the environment,\r
+#\r
+# @param env environment object\r
+def generate( env ) :\r
+    env["BUILDERS"]["Configure"] = SCons.Builder.Builder( action = __action,  emitter = __emitter,  target_factory = SCons.Node.FS.File,  source_factory = SCons.Node.FS.File,  single_source = True,  PRINT_CMD_LINE_FUNC = __message )\r
+\r
+# Exist function for the builder\r
+#\r
+# @param env environment object\r
+# @return true\r
+def exists( env ) :\r
+    return 1\r
diff --git a/tools/scons/URLDownload.py b/tools/scons/URLDownload.py
new file mode 100644 (file)
index 0000000..724ad4d
--- /dev/null
@@ -0,0 +1,147 @@
+# -*- coding: utf-8 -*-\r
+\r
+############################################################################\r
+# GPL License                                                              #\r
+#                                                                          #\r
+# This file is a SCons (http://www.scons.org/) builder                     #\r
+# Copyright (c) 2012-14, Philipp Kraus, <philipp.kraus@flashpixx.de>       #\r
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.     #\r
+# This program is free software: you can redistribute it and/or modify     #\r
+# it under the terms of the GNU General Public License as                  #\r
+# published by the Free Software Foundation, either version 3 of the       #\r
+# License, or (at your option) any later version.                          #\r
+#                                                                          #\r
+# This program is distributed in the hope that it will be useful,          #\r
+# but WITHOUT ANY WARRANTY; without even the implied warranty of           #\r
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #\r
+# GNU General Public License for more details.                             #\r
+#                                                                          #\r
+# You should have received a copy of the GNU General Public License        #\r
+# along with this program. If not, see <http://www.gnu.org/licenses/>.     #\r
+############################################################################\r
+\r
+# the URLDownload-Builder can download any data from an URL into a target\r
+# file. The target name is used are the file name of the downloaded file.\r
+\r
+# This builder originated from work by Philipp Kraus and flashpixx project\r
+# (see https://github.com/flashpixx). It has been modified to leverage\r
+# the HTTP ETag header to be used as the csig. This allows the download\r
+# builder to determine if the file should be downloaded again when the\r
+# ETag header is supported\r
+\r
+import os, time\r
+import urllib2, urlparse\r
+import SCons.Builder, SCons.Node, SCons.Errors\r
+\r
+# Define a source node to represent the remote file. The construction of the\r
+# node will query the hosting site to get the ETag, size and last-modified\r
+# date.  This node also defines the method by which we will determine if\r
+# the file should be downloaded again.\r
+#\r
+# This node derives from the Python.Value node\r
+#\r
+class URLNode(SCons.Node.Python.Value) :\r
+    def make_ready(self) :\r
+        try :\r
+            stream = urllib2.urlopen( str(self.value) )\r
+            info = stream.info()\r
+\r
+            self.url_etag = None\r
+            self.url_last_modified = None\r
+            self.url_content_length = None\r
+\r
+            if 'ETag' in info :\r
+                self.url_etag = info['ETag']\r
+            if 'Last-Modified' in info :\r
+                self.url_last_modified = time.mktime(time.strptime(info['Last-Modified'], '%a, %d %b %Y %H:%M:%S GMT'))\r
+            if 'Content-Length' in info :\r
+                self.url_content_legth = info['Content-Length']\r
+        except Exception, e :\r
+            raise SCons.Errors.StopError( '%s [%s]' % (e, self.value) )\r
+\r
+    def visited(self) :\r
+        ninfo = self.get_ninfo()\r
+\r
+        if self.url_etag :\r
+            ninfo.csig = self.url_etag\r
+        if self.url_last_modified :\r
+            ninfo.timestamp = self.url_last_modified\r
+        if self.url_content_length :\r
+            ninfo.size = self.url_content_length\r
+        SCons.Node.Node.visited(self);\r
+\r
+    def changed_since_last_build(self, target, prev_ni):\r
+        if prev_ni :\r
+            if self.url_etag :\r
+                if prev_ni.csig == self.url_etag :\r
+                    # print 'Matched on ETag:'+prev_ni.csig\r
+                    return False\r
+\r
+            if not self.url_last_modified :\r
+                # print 'Last modified date is not available'\r
+                return True\r
+            if not self.url_content_length :\r
+                # print 'Content length is not available'\r
+                return True\r
+            if prev_ni.timestamp != self.url_last_modified :\r
+                # print 'Modified since last build'\r
+                return True\r
+            if prev_ni.size != self.url_content_length :\r
+                # print 'Content length has changed'\r
+                return True\r
+\r
+            return False\r
+\r
+        # print 'Not previous built'\r
+        return True\r
+\r
+# Creates the output message\r
+# @param s original message\r
+# @param target target name\r
+# @param source source name\r
+# @param env environment object\r
+def __message( s, target, source, env ) :\r
+    print 'downloading [%s] from [%s] ...' % (target[0], source[0])\r
+\r
+# Creates the action ie. the download function.\r
+# This reads the data from the URL and writes it down to the file\r
+# @param target target file on the local drive\r
+# @param source URL for download\r
+# @@param env environment object\r
+def __action( target, source, env ) :\r
+    try :\r
+        source_name = str(source[0])\r
+        target_name = str(target[0])\r
+        stream = urllib2.urlopen(source_name)\r
+        file = open( target_name, 'wb' )\r
+        file.write(stream.read())\r
+        file.close()\r
+\r
+        # Change the access/modified time to match\r
+        # the date on the downloaded file, if available\r
+        ninfo = source[0].get_ninfo()\r
+        if hasattr(ninfo, 'timestamp') :\r
+            mtime = ninfo.timestamp\r
+            if mtime :\r
+                os.utime(target_name, (mtime, mtime))\r
+    except Exception, e :\r
+        raise SCons.Errors.StopError( '%s [%s]' % (e, source[0]) )\r
+\r
+\r
+# Defines the emitter of the builder\r
+# @param target target file on the local drive\r
+# @param source URL for download\r
+# @param env environment object\r
+def __emitter( target, source, env ) :\r
+    return target, source\r
+\r
+# generate function, that adds the builder to the environment,\r
+# @param env environment object\r
+def generate( env ) :\r
+    env['BUILDERS']['URLDownload'] = SCons.Builder.Builder( action = __action,  emitter = __emitter,  target_factory = SCons.Node.FS.File,  source_factory = URLNode,  single_source = True,  PRINT_CMD_LINE_FUNC = __message )\r
+\r
+# existing function of the builder\r
+# @param env environment object\r
+# @return true\r
+def exists(env) :\r
+    return 1\r
diff --git a/tools/scons/UnpackAll.py b/tools/scons/UnpackAll.py
new file mode 100644 (file)
index 0000000..409f980
--- /dev/null
@@ -0,0 +1,399 @@
+# -*- coding: utf-8 -*-\r
+\r
+############################################################################\r
+# GPL License                                                              #\r
+#                                                                          #\r
+# This file is a SCons (http://www.scons.org/) builder                     #\r
+# Copyright (c) 2012-14, Philipp Kraus, <philipp.kraus@flashpixx.de>       #\r
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.     #\r
+# This program is free software: you can redistribute it and/or modify     #\r
+# it under the terms of the GNU General Public License as                  #\r
+# published by the Free Software Foundation, either version 3 of the       #\r
+# License, or (at your option) any later version.                          #\r
+#                                                                          #\r
+# This program is distributed in the hope that it will be useful,          #\r
+# but WITHOUT ANY WARRANTY; without even the implied warranty of           #\r
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #\r
+# GNU General Public License for more details.                             #\r
+#                                                                          #\r
+# You should have received a copy of the GNU General Public License        #\r
+# along with this program. If not, see <http://www.gnu.org/licenses/>.     #\r
+############################################################################\r
+\r
+# This builder originated from work by Philipp Kraus and flashpixx project\r
+# (see https://github.com/flashpixx). Based on the Unpack.py, it only\r
+# contains changes to allow a complete unpacking of the archive.\r
+# It is assumed that the target represents a file in the archive after it\r
+# is unpacked.\r
+\r
+# The Unpack Builder can be used for unpacking archives (eg Zip, TGZ, BZ, ... ).\r
+# The emitter of the Builder reads the archive data and creates a returning\r
+# file list the builder extract the archive. The environment variable\r
+# stores a dictionary "UNPACK" for set different extractions (subdict "EXTRACTOR"):\r
+# {\r
+#   PRIORITY         => a value for setting the extractor order (lower numbers = extractor is used earlier)\r
+#   SUFFIX           => defines a list with file suffixes, which should be handled with this extractor\r
+#   EXTRACTSUFFIX    => suffix of the extract command\r
+#   EXTRACTFLAGS     => a string parameter for the RUN command for extracting the data\r
+#   EXTRACTCMD       => full extract command of the builder\r
+#   RUN              => the main program which will be started (if the parameter is empty, the extractor will be ignored)\r
+#   LISTCMD          => the listing command for the emitter\r
+#   LISTFLAGS        => the string options for the RUN command for showing a list of files\r
+#   LISTSUFFIX       => suffix of the list command\r
+#   LISTEXTRACTOR    => a optional Python function, that is called on each output line of the\r
+#                       LISTCMD for extracting file & dir names, the function need two parameters (first line number,\r
+#                       second line content) and must return a string with the file / dir path (other value types\r
+#                       will be ignored)\r
+# }\r
+# Other options in the UNPACK dictionary are:\r
+#   STOPONEMPTYFILE  => bool variable for stoping if the file has empty size (default True)\r
+#   VIWEXTRACTOUTPUT => shows the output messages of the extraction command (default False)\r
+#   EXTRACTDIR       => path in that the data will be extracted (default #)\r
+#\r
+# The file which is handled by the first suffix match of the extractor, the extractor list can be append for other files.\r
+# The order of the extractor dictionary creates the listing & extractor command eg file extension .tar.gz should be\r
+# before .gz, because the tar.gz is extract in one shoot.\r
+#\r
+# Under *nix system these tools are supported: tar, bzip2, gzip, unzip\r
+# Under Windows only 7-Zip (http://www.7-zip.org/) is supported\r
+\r
+\r
+import subprocess, os\r
+import SCons.Errors, SCons.Warnings, SCons.Util\r
+\r
+# enables Scons warning for this builder\r
+class UnpackWarning(SCons.Warnings.Warning) :\r
+    pass\r
+\r
+SCons.Warnings.enableWarningClass(UnpackWarning)\r
+\r
+# extractor function for Tar output\r
+# @param env environment object\r
+# @param count number of returning lines\r
+# @param no number of the output line\r
+# @param i line content\r
+def __fileextractor_nix_tar( env, count, no, i ) :\r
+    return i.split()[-1]\r
+\r
+# extractor function for GZip output,\r
+# ignore the first line\r
+# @param env environment object\r
+# @param count number of returning lines\r
+# @param no number of the output line\r
+# @param i line content\r
+def __fileextractor_nix_gzip( env, count, no, i ) :\r
+    if no == 0 :\r
+        return None\r
+    return i.split()[-1]\r
+\r
+# extractor function for Unzip output,\r
+# ignore the first & last two lines\r
+# @param env environment object\r
+# @param count number of returning lines\r
+# @param no number of the output line\r
+# @param i line content\r
+def __fileextractor_nix_unzip( env, count, no, i ) :\r
+    if no < 3 or no >= count - 2 :\r
+        return None\r
+    return i.split()[-1]\r
+\r
+# extractor function for 7-Zip\r
+# @param env environment object\r
+# @param count number of returning lines\r
+# @param no number of the output line\r
+# @param i line content\r
+def __fileextractor_win_7zip( env, count, no, i ) :\r
+    item = i.split()\r
+    if no > 8 and no < count - 2 :\r
+        return item[-1]\r
+    return None\r
+\r
+\r
+\r
+# returns the extractor item for handling the source file\r
+# @param source input source file\r
+# @param env environment object\r
+# @return extractor entry or None on non existing\r
+def __getExtractor( source, env ) :\r
+    # we check each unpacker and get the correct list command first, run the command and\r
+    # replace the target filelist with the list values, we sorte the extractors by their priority\r
+    for unpackername, extractor in sorted(env["UNPACK"]["EXTRACTOR"].iteritems(), key = lambda (k,v) : (v["PRIORITY"],k)):\r
+\r
+        if not SCons.Util.is_String(extractor["RUN"]) :\r
+            raise SCons.Errors.StopError("list command of the unpack builder for [%s] archives is not a string" % (unpackername))\r
+        if not len(extractor["RUN"]) :\r
+            raise SCons.Errors.StopError("run command of the unpack builder for [%s] archives is not set - can not extract files" % (unpackername))\r
+\r
+\r
+        if not SCons.Util.is_String(extractor["LISTFLAGS"]) :\r
+            raise SCons.Errors.StopError("list flags of the unpack builder for [%s] archives is not a string" % (unpackername))\r
+        if not SCons.Util.is_String(extractor["LISTCMD"]) :\r
+            raise SCons.Errors.StopError("list command of the unpack builder for [%s] archives is not a string" % (unpackername))\r
+\r
+        if not SCons.Util.is_String(extractor["EXTRACTFLAGS"]) :\r
+            raise SCons.Errors.StopError("extract flags of the unpack builder for [%s] archives is not a string" % (unpackername))\r
+        if not SCons.Util.is_String(extractor["EXTRACTCMD"]) :\r
+            raise SCons.Errors.StopError("extract command of the unpack builder for [%s] archives is not a string" % (unpackername))\r
+\r
+\r
+        # check the source file suffix and if the first is found, run the list command\r
+        if not SCons.Util.is_List(extractor["SUFFIX"]) :\r
+            raise SCons.Errors.StopError("suffix list of the unpack builder for [%s] archives is not a list" % (unpackername))\r
+\r
+        for suffix in extractor["SUFFIX"] :\r
+            if str(source[0]).lower()[-len(suffix):] == suffix.lower() :\r
+                return extractor\r
+\r
+    return None\r
+\r
+\r
+# creates the extracter output message\r
+# @param s original message\r
+# @param target target name\r
+# @param source source name\r
+# @param env environment object\r
+def __message( s, target, source, env ) :\r
+    print "extract [%s] ..." % (source[0])\r
+\r
+\r
+# action function for extracting of the data\r
+# @param target target packed file\r
+# @param source extracted files\r
+# @param env environment object\r
+def __action( target, source, env ) :\r
+    extractor = __getExtractor(source, env)\r
+    if not extractor :\r
+        raise SCons.Errors.StopError( "can not find any extractor value for the source file [%s]" % (source[0]) )\r
+\r
+    extractor_cmd = extractor["EXTRACTCMD"]\r
+\r
+    # if the extract command is empty, we create an error\r
+    if len(extractor_cmd) == 0 :\r
+        raise SCons.Errors.StopError( "the extractor command for the source file [%s] is empty" % (source[0]) )\r
+\r
+    # build it now (we need the shell, because some programs need it)\r
+    handle = None\r
+\r
+    source_path = os.path.realpath(source[0].path)\r
+    target_path = os.path.realpath(target[0].path)\r
+\r
+    cmd = env.subst(extractor_cmd, source=source_path, target=target)\r
+    cwd = os.path.dirname(source_path)\r
+\r
+    if env["UNPACK"]["VIWEXTRACTOUTPUT"] :\r
+        handle  = subprocess.Popen( cmd, shell=True )\r
+    else :\r
+        devnull = open(os.devnull, "wb")\r
+        handle  = subprocess.Popen( cmd, shell=True, stdout=devnull, cwd=cwd)\r
+\r
+    if handle.wait() <> 0 :\r
+        raise SCons.Errors.BuildError( "error running extractor [%s] on the source [%s]" % (cmd, source[0]) )\r
+\r
+    fhandle = open(target_path, 'a')\r
+    try:\r
+        os.utime(target_path, None)\r
+    finally:\r
+        fhandle.close()\r
+\r
+\r
+# emitter function for getting the files\r
+# within the archive\r
+# @param target target packed file\r
+# @param source extracted files\r
+# @param env environment object\r
+def __emitter( target, source, env ) :\r
+    return target, source\r
+\r
+\r
+# generate function, that adds the builder to the environment\r
+# @param env environment object\r
+def generate( env ) :\r
+    # setup environment variable\r
+    toolset = {\r
+        "STOPONEMPTYFILE"  : True,\r
+        "VIWEXTRACTOUTPUT" : False,\r
+        "EXTRACTDIR"       : os.curdir,\r
+        "EXTRACTOR" : {\r
+            "TARGZ" : {\r
+                "PRIORITY"       : 0,\r
+                "SUFFIX"         : [".tar.gz", ".tgz", ".tar.gzip"],\r
+                "EXTRACTSUFFIX"  : "",\r
+                "EXTRACTFLAGS"   : "",\r
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['TARGZ']['RUN']} ${UNPACK['EXTRACTOR']['TARGZ']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARGZ']['EXTRACTSUFFIX']}",\r
+                "RUN"            : "",\r
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['TARGZ']['RUN']} ${UNPACK['EXTRACTOR']['TARGZ']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARGZ']['LISTSUFFIX']}",\r
+                "LISTSUFFIX"     : "",\r
+                "LISTFLAGS"      : "",\r
+                "LISTEXTRACTOR"  : None\r
+            },\r
+\r
+            "TARBZ" : {\r
+                "PRIORITY"       : 0,\r
+                "SUFFIX"         : [".tar.bz", ".tbz", ".tar.bz2", ".tar.bzip2", ".tar.bzip"],\r
+                "EXTRACTSUFFIX"  : "",\r
+                "EXTRACTFLAGS"   : "",\r
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['TARBZ']['RUN']} ${UNPACK['EXTRACTOR']['TARBZ']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARBZ']['EXTRACTSUFFIX']}",\r
+                "RUN"            : "",\r
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['TARBZ']['RUN']} ${UNPACK['EXTRACTOR']['TARBZ']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TARBZ']['LISTSUFFIX']}",\r
+                "LISTSUFFIX"     : "",\r
+                "LISTFLAGS"      : "",\r
+                "LISTEXTRACTOR"  : None\r
+            },\r
+\r
+            "BZIP" : {\r
+                "PRIORITY"       : 1,\r
+                "SUFFIX"         : [".bz", "bzip", ".bz2", ".bzip2"],\r
+                "EXTRACTSUFFIX"  : "",\r
+                "EXTRACTFLAGS"   : "",\r
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['BZIP']['RUN']} ${UNPACK['EXTRACTOR']['BZIP']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['BZIP']['EXTRACTSUFFIX']}",\r
+                "RUN"            : "",\r
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['BZIP']['RUN']} ${UNPACK['EXTRACTOR']['BZIP']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['BZIP']['LISTSUFFIX']}",\r
+                "LISTSUFFIX"     : "",\r
+                "LISTFLAGS"      : "",\r
+                "LISTEXTRACTOR"  : None\r
+            },\r
+\r
+            "GZIP" : {\r
+                "PRIORITY"       : 1,\r
+                "SUFFIX"         : [".gz", ".gzip"],\r
+                "EXTRACTSUFFIX"  : "",\r
+                "EXTRACTFLAGS"   : "",\r
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['GZIP']['RUN']} ${UNPACK['EXTRACTOR']['GZIP']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['GZIP']['EXTRACTSUFFIX']}",\r
+                "RUN"            : "",\r
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['GZIP']['RUN']} ${UNPACK['EXTRACTOR']['GZIP']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['GZIP']['LISTSUFFIX']}",\r
+                "LISTSUFFIX"     : "",\r
+                "LISTFLAGS"      : "",\r
+                "LISTEXTRACTOR"  : None\r
+            },\r
+\r
+            "TAR" : {\r
+                "PRIORITY"       : 1,\r
+                "SUFFIX"         : [".tar"],\r
+                "EXTRACTSUFFIX"  : "",\r
+                "EXTRACTFLAGS"   : "",\r
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['TAR']['RUN']} ${UNPACK['EXTRACTOR']['TAR']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TAR']['EXTRACTSUFFIX']}",\r
+                "RUN"            : "",\r
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['TAR']['RUN']} ${UNPACK['EXTRACTOR']['TAR']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['TAR']['LISTSUFFIX']}",\r
+                "LISTSUFFIX"     : "",\r
+                "LISTFLAGS"      : "",\r
+                "LISTEXTRACTOR"  : None\r
+            },\r
+\r
+            "ZIP" : {\r
+                "PRIORITY"       : 1,\r
+                "SUFFIX"         : [".zip"],\r
+                "EXTRACTSUFFIX"  : "",\r
+                "EXTRACTFLAGS"   : "",\r
+                "EXTRACTCMD"     : "${UNPACK['EXTRACTOR']['ZIP']['RUN']} ${UNPACK['EXTRACTOR']['ZIP']['EXTRACTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['ZIP']['EXTRACTSUFFIX']}",\r
+                "RUN"            : "",\r
+                "LISTCMD"        : "${UNPACK['EXTRACTOR']['ZIP']['RUN']} ${UNPACK['EXTRACTOR']['ZIP']['LISTFLAGS']} $SOURCE ${UNPACK['EXTRACTOR']['ZIP']['LISTSUFFIX']}",\r
+                "LISTSUFFIX"     : "",\r
+                "LISTFLAGS"      : "",\r
+                "LISTEXTRACTOR"  : None\r
+            }\r
+        }\r
+    }\r
+\r
+    # read tools for Windows system\r
+    if env["PLATFORM"] <> "darwin" and "win" in env["PLATFORM"] :\r
+\r
+        if env.WhereIs("7z") :\r
+            toolset["EXTRACTOR"]["TARGZ"]["RUN"]           = "7z"\r
+            toolset["EXTRACTOR"]["TARGZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip\r
+            toolset["EXTRACTOR"]["TARGZ"]["LISTFLAGS"]     = "x"\r
+            toolset["EXTRACTOR"]["TARGZ"]["LISTSUFFIX"]    = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"\r
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTFLAGS"]  = "x"\r
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"\r
+\r
+            toolset["EXTRACTOR"]["TARBZ"]["RUN"]           = "7z"\r
+            toolset["EXTRACTOR"]["TARBZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip\r
+            toolset["EXTRACTOR"]["TARBZ"]["LISTFLAGS"]     = "x"\r
+            toolset["EXTRACTOR"]["TARBZ"]["LISTSUFFIX"]    = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"\r
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTFLAGS"]  = "x"\r
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"\r
+\r
+            toolset["EXTRACTOR"]["BZIP"]["RUN"]            = "7z"\r
+            toolset["EXTRACTOR"]["BZIP"]["LISTEXTRACTOR"]  = __fileextractor_win_7zip\r
+            toolset["EXTRACTOR"]["BZIP"]["LISTFLAGS"]      = "l"\r
+            toolset["EXTRACTOR"]["BZIP"]["LISTSUFFIX"]     = "-y -so"\r
+            toolset["EXTRACTOR"]["BZIP"]["EXTRACTFLAGS"]   = "x"\r
+            toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"]  = "-y -oc:${UNPACK['EXTRACTDIR']}"\r
+\r
+            toolset["EXTRACTOR"]["GZIP"]["RUN"]            = "7z"\r
+            toolset["EXTRACTOR"]["GZIP"]["LISTEXTRACTOR"]  = __fileextractor_win_7zip\r
+            toolset["EXTRACTOR"]["GZIP"]["LISTFLAGS"]      = "l"\r
+            toolset["EXTRACTOR"]["GZIP"]["LISTSUFFIX"]     = "-y -so"\r
+            toolset["EXTRACTOR"]["GZIP"]["EXTRACTFLAGS"]   = "x"\r
+            toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"]  = "-y -oc:${UNPACK['EXTRACTDIR']}"\r
+\r
+            toolset["EXTRACTOR"]["ZIP"]["RUN"]             = "7z"\r
+            toolset["EXTRACTOR"]["ZIP"]["LISTEXTRACTOR"]   = __fileextractor_win_7zip\r
+            toolset["EXTRACTOR"]["ZIP"]["LISTFLAGS"]       = "l"\r
+            toolset["EXTRACTOR"]["ZIP"]["LISTSUFFIX"]      = "-y -so"\r
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTFLAGS"]    = "x"\r
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"]   = "-y -oc:${UNPACK['EXTRACTDIR']}"\r
+\r
+            toolset["EXTRACTOR"]["TAR"]["RUN"]             = "7z"\r
+            toolset["EXTRACTOR"]["TAR"]["LISTEXTRACTOR"]   = __fileextractor_win_7zip\r
+            toolset["EXTRACTOR"]["TAR"]["LISTFLAGS"]       = "l"\r
+            toolset["EXTRACTOR"]["TAR"]["LISTSUFFIX"]      = "-y -ttar -so"\r
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTFLAGS"]    = "x"\r
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"]   = "-y -ttar -oc:${UNPACK['EXTRACTDIR']}"\r
+\r
+        # here can add some other Windows tools, that can handle the archive files\r
+        # but I don't know which ones can handle all file types\r
+\r
+\r
+\r
+    # read the tools on *nix systems and sets the default parameters\r
+    elif env["PLATFORM"] in ["darwin", "linux", "posix"] :\r
+\r
+        if env.WhereIs("unzip") :\r
+            toolset["EXTRACTOR"]["ZIP"]["RUN"]             = "unzip"\r
+            toolset["EXTRACTOR"]["ZIP"]["LISTEXTRACTOR"]   = __fileextractor_nix_unzip\r
+            toolset["EXTRACTOR"]["ZIP"]["LISTFLAGS"]       = "-l"\r
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTFLAGS"]    = "-oqq"\r
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"]   = "-d ${UNPACK['EXTRACTDIR']}"\r
+\r
+        if env.WhereIs("tar") :\r
+            toolset["EXTRACTOR"]["TAR"]["RUN"]             = "tar"\r
+            toolset["EXTRACTOR"]["TAR"]["LISTEXTRACTOR"]   = __fileextractor_nix_tar\r
+            toolset["EXTRACTOR"]["TAR"]["LISTFLAGS"]       = "tvf"\r
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTFLAGS"]    = "xf"\r
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"]   = "-C ${UNPACK['EXTRACTDIR']}"\r
+\r
+            toolset["EXTRACTOR"]["TARGZ"]["RUN"]           = "tar"\r
+            toolset["EXTRACTOR"]["TARGZ"]["LISTEXTRACTOR"] = __fileextractor_nix_tar\r
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTFLAGS"]  = "xfz"\r
+            toolset["EXTRACTOR"]["TARGZ"]["LISTFLAGS"]     = "tvfz"\r
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-C ${UNPACK['EXTRACTDIR']}"\r
+\r
+            toolset["EXTRACTOR"]["TARBZ"]["RUN"]           = "tar"\r
+            toolset["EXTRACTOR"]["TARBZ"]["LISTEXTRACTOR"] = __fileextractor_nix_tar\r
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTFLAGS"]  = "xfj"\r
+            toolset["EXTRACTOR"]["TARBZ"]["LISTFLAGS"]     = "tvfj"\r
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-C ${UNPACK['EXTRACTDIR']}"\r
+\r
+        if env.WhereIs("bzip2") :\r
+            toolset["EXTRACTOR"]["BZIP"]["RUN"]            = "bzip2"\r
+            toolset["EXTRACTOR"]["BZIP"]["EXTRACTFLAGS"]   = "-df"\r
+\r
+        if env.WhereIs("gzip") :\r
+            toolset["EXTRACTOR"]["GZIP"]["RUN"]            = "gzip"\r
+            toolset["EXTRACTOR"]["GZIP"]["LISTEXTRACTOR"]  = __fileextractor_nix_gzip\r
+            toolset["EXTRACTOR"]["GZIP"]["LISTFLAGS"]      = "-l"\r
+            toolset["EXTRACTOR"]["GZIP"]["EXTRACTFLAGS"]   = "-df"\r
+\r
+    else :\r
+        raise SCons.Errors.StopError("Unpack tool detection on this platform [%s] unkown" % (env["PLATFORM"]))\r
+\r
+    # the target_factory must be a "Entry", because the target list can be files and dirs, so we can not specified the targetfactory explicite\r
+    env.Replace(UNPACK = toolset)\r
+    env["BUILDERS"]["UnpackAll"] = SCons.Builder.Builder( action = __action,  emitter = __emitter,  target_factory = SCons.Node.FS.Entry,  source_factory = SCons.Node.FS.File,  single_source = True,  PRINT_CMD_LINE_FUNC = __message )\r
+\r
+\r
+# existing function of the builder\r
+# @param env environment object\r
+# @return true\r
+def exists(env) :\r
+    return 1\r
diff --git a/tools/scons_script_how_to.txt b/tools/scons_script_how_to.txt
deleted file mode 100644 (file)
index 5c49533..0000000
+++ /dev/null
@@ -1,240 +0,0 @@
-== How to write IoTivity build script ==
-
-IoTivity projects are built with Scons. Scons is a cross-platform build tool,
-it's quite similar to 'make'. 'SConstruct' is the entrance of scons build, it's
-equivalent to 'Makefile' to 'make'.
-
-This document only a brief reference. Detail about how to write scons script,
-please refer to:
-       http://www.scons.org/doc/production/HTML/scons-user.html#
-
-== Background: How to control source code compiling ==
-
-Environment is a base conception of Scons. An environment is a collection of
-values that can affect how a program is built.
-
-e.g. There is a C file named hello.c, enter the following into a file named
-SConstruct:
-       env = Environment()
-       env.Program('H', 'hello.c')
-
-When run Scons in console, following will be executed:
-cc -o hello.o -c hello.c
-cc -o H hello.o
-
-If you would like keep debug information in the binary, '-g' flag should be added
-when build the source code. To do this, append a C compiler flags as following:
-       env = Environment()
-       env.AppendUnique(CFLAGS = ['-g'])
-       env.Program('H', 'hello.c')
-
-When run Scons, following will be executed:
-cc -o hello.o -c -g hello.c
-cc -o H hello.o
-
-In above example, 'CFLAGS' is changed. Following list the frequently used keys:
-
-CFLAGS: General options that are passed to the C compiler
-CCFLAGS: General options that are passed to the C & C++ compiler
-CXXFLAGS: General options that are passed to the C++ compiler
-CPPPATH: The directories that the preprocessor will search for include headers.
-CPPDEFINES: Platform independent specification of C preprocessor definitions.
-
-Note: CPPPATH and CPPDEFINES is common for all compiler. But others are
-compiler specific, when change the key value, it may requried to specify the
-target platform(actually the compiler).
-
-e.g.
-       env.AppendUnique(CPPPATH = ['.', 'include'])
-       env.AppendUnique(CPPDEFINES = ['NDEBUG', 'VER_TEST'])
-Above two lines are fine for all target platform. but below line:
-       env.AppenUnique(CXXFLAGS = ['-g'])
-is only fine for gcc compiler, as '-g' is a gcc flag, other compiler may don't
-understand it. so it may should be:
-       if target_os not in ['windows', 'winrt']:
-               env.AppenUnique(CXXFLAGS = ['-g'])
-
-Still take the hello.c as example. Assume hello.h is in ./include/ directory,
-#include "hello.h"
-int main(int argc, char** argv)
-{
-#ifdef LANG_FR
-    printf("Bonjour\n");
-#else
-       printf("Hello\n");
-#endif
-}
-
-The Scons configure file should as following:
-       env = Environment()
-       env.AppendUnique(CFLAGS = ['-g'])
-       env.AppendUnique(CPPPATH = ['include'])
-       env.AppendUnique(CPPDEFINES = ['LANG_FR'])
-       env.Program('H', 'hello.c')
-
-When run Scons, following will be executed:
-cc -o hello.o -c -g -Iinclude -DLANG_FR hello.c
-cc -o H hello.o
-
-=== Get extra information ===
-
-In above example, 'target_os' is used. How to get it?
-
-User can build IoTivity project on Linux / Windows / MAC OSX for various
-targets(Linux, Tizen, Android, Arduino, Windows, MAC OSX, IOS ...). Most
-platform specific configures have been done in the common scripts which are in
-build_common. The common scripts prepare an environment named 'env' with
-target platform specific configuration.
-
-When write IoTivity project build script, you can get this environment as
-following:
-       Import('env')
-
-You can use 'env' directly after import it. You can also clone a new environment
-and update its keys.
-
-       new_env1 = Clone('env')
-       new_env2 = Clone('env')
-       new_env1.AppendUnqiue(xxx = [...])
-       new_env2.AppendUnqiue(xxx = [...])
-
-The 'env' environment contains platform specific configuration, besides, there is
-some common information. You can get the information with following line:
-       env.get('XXX')
-or
-       env['XXX']
-
-XXX is the information name, below are the extra information added by IoTivity
-common scrirpts:
-BUILD_DIR: the path of the build directory, all output are in this directory
-SRC_DIR: the path of the top directory of the source code
-OIC_UTILS: the path of oic-utilities project
-RELEASE: build type, boolean. True - release build, False - debug build
-TARGET_OS: the name of the target OS. The possible value depends on the host
-       platform. Bellow is the list of host and possible target OS. (darwin means
-       MAC OSX)
-               linux: linux / android / arduino / tizen
-(the line means on Linux, you can build the project for Linux/Android/Arduino/Tizen)
-               windows: windows / winrt / android / arduino
-               darwin: darwin / ios / android / arduino
-
-TARGET_ARCH: the target CPU arch. Its possible value depend on the target OS.
-       Bellow list the target OS and allowed CPU architecture.
-               linux: x86 / x86_64 / arm / arm64
-(above line means if the target OS is Linux, the CPU arch can be x86/x86_64/arm/arm64)
-               android: x86 / x86_64 / armeabi / armeabi-v7a / armeabi-v7a-hard / arm64-v8a
-               windows: x86 / amd64 / arm
-               winrt: arm
-               darwin: i386 / x86_64
-               ios: i386 / x86_64 / armv7 / armv7s / arm64,
-               arduino: avr / arm
-
-=== Extra functions ===
-
-For convenience, in the common scripts, some extra functions are added.
-
-PrintTargets(): print all targets in the help information.
-AppendTarget(target): add 'target' into targets list, when use PrintTargets,
-       the 'target' will be print.
-InstallTarget(files, name): it takes the same action as AppendTarget, besides,
-       it installs the 'files' to BUILD_DIR.
-
-Following functions are only for Arduino:
-ImportLib(lib): Arduino IDE includes many libraries. By default, no library is
-compiled. If your project use some libraries, you can import the library by
-this function. 'lib' is the name of the library to import. The 'include' path
-will be auto added to the environment and the library will be built and linked
-into the final binary.
-
-CreateBin('bin', src): For Arduino, after build the program, it's required to
-be converted into specific format (e.g .hex). This function will genearate the
-required .hex (and .eep if target arch is avr) file.
-
-UploadHelp(): For different board, the upload command line is different, this
-function print the recommended upload command line. You can see the recommended
-upload command line in the help information(the output of command "scons
-[options] -h")
-
-==== Scripts Hierarchy ====
-
-Scons provides a function 'SConscript(scripts, [exports, variant_dir, duplicate])'
-It tells scons to execute one or more subsidiary configuration files(A script,
-usually named SConscript). Take below project hierarchy as example to show how
-to organize the scripts.
-
-               prj
-               |-------prj_1
-               |               |--------sub_prj_11
-               |               |--------sub_prj_..
-               |               |--------sub_prj_1n
-               |-------prj_2
-               |
-               | ... ...
-               |
-               |-------prj_n
-
-As above project hierarchy, in 'SConstruct' file in the 'prj' directory, there
-should include some lines like these:
-
-#Please change this part according to the organization of your projects.
-#Note: To make the output is in build_dir, the path of the scripts should
-#be relevant to build_dir
-SConscript(build_dir + 'prj_1/SConscript')
-SConscript(build_dir + 'prj_2/SConscript')
-... ...
-SConscript(build_dir + 'prj_n/SConscript')
-
-
-It's the same, in the 'prj_1/SConscript', there should include lines like
-these:
-SConscript('sub_prj_11/SConscript')
-... ...
-SConscript('sub_prj_1n/SConscript')
-
-The path is relevant to 'prj_1/SConscript'. You can also use the full path
-build_dir + 'prj_1/sub_prj_1x/SConscript', but it's not recommended.
-
-Above just to show a recommended way to manage subsidiary scripts. You don't
-need restrictly follow it.
-
-==== The content of a typical script ====
-
-After run the scripts in build_common (usally it's done at the beginning of
-SConstruct), an global environment 'env' is exported, 'env' has include the
-default configuration of the target OS and arch. 'env' is used in all projects,
-should avoid to change its keys. To avoid change 'env', usually clone 'env' and
-update it accroding to the requirement of cuurent sub project. Then specify the
-target(usually binary) to build.
-
-Below is an example:
-       # import the global enviroment 'env'
-       Import('env')
-
-       # Clone a new enviroment from 'env'
-       new_env = env.Clone()
-
-       # Update the new enviroment, usally include add header file paths,
-       # library path, libs to link and other compiler flags. This part is
-       # optional. If not present, the default configuration will be used
-       new_env.AppeneUnique(xxx = [ .... ])
-
-       # Specify the target(application, library, object or others) to build
-       ts = new_env.Program('progam_name', [source_list])
-
-       # Install the target (optional)
-       # If it's an important library or daemon to be published
-       new_env.InstallTarget(ts, 'target_name')
-or
-       # If is't examples or test program or others will not be published
-       new_env.Alias('target_name', ts)
-       new_env.AppendTarget('target_name')
-
-==== Tips ====
-1. library order: if A lib use B lib, both A and B are linked to target T, the
-       when specify libraries, A should in front of B, otherwise there may be link
-       error.
-2. On android:
-       (1)'pthread' is in libc. So don't use '-lpthread' for android
-       (2)By default 'rtti' and 'exception' is disabled, to enable it, you need
-       add flags '-frtti' and '-fexceptions'
-       (3)If STL is used, need link 'gnustl_static' library
diff --git a/tools/style/astyle-clean-cpp-format.sh b/tools/style/astyle-clean-cpp-format.sh
new file mode 100755 (executable)
index 0000000..d03a71f
--- /dev/null
@@ -0,0 +1,95 @@
+#!/bin/bash
+# copy or move Artistic Style backup files to a backup directory
+
+# CHANGE THE FOLLOWING 4 VARIABLES
+# $indir is the input top level directory containing the .orig files
+# $outdir is the output top level directory containing the moved files
+# $fileext is the backup file extension
+# $copyfiles is COPY (cp) or MOVE (mv) the files
+# spaces ARE allowed in directory and file name (for Cygwin on Windows)
+
+indir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)"
+outdir="astyle_backup"
+fileext=".orig"
+fileext=".orig"
+# USE ONE OF THE FOLLOWING TO COPY OR MOVE THE FILES
+#copyfiles=cp
+copyfiles=mv
+
+# display the variables
+echo
+echo "\"$copyfiles\" Artistic Style backup files"
+echo "FROM $indir"
+echo "TO   $outdir"
+echo
+
+# validate input directory
+if [ ! -d "$indir" ] ; then
+       echo "Input directory does not exist!"
+       echo
+       exit
+fi
+if [ "$indir" == "$outdir" ]; then
+       echo "Input and output directories are the same!"
+       echo
+       exit
+fi
+
+# optional statement to run Artistic Style
+# astyle  -R  "%indir%\*.cpp"  "%indir%\*.h"
+# if [ $? -ne 0 ] ; then  read -sn1 -p "Error executing astyle!"; fi
+
+# variables for fle processing
+#echo "processing files..."
+fileHasSpaces=false         # a file or directory name has spaces
+extLength=${#fileext}       # length of the file extension
+
+# loop thru the input directory to find the .orig files
+# then move the .orig file to the new directory
+for file in `find  "$indir"  -type f  -name "*$fileext" ` ; do
+
+       # allow spaces in file names for Cygwiin on Windows
+       # test if this is a continuation line and build $infile
+       if [ $fileHasSpaces = true ] ; then
+               infile+=' '$file
+       else
+               infile=$file
+       fi
+       # test end of string for no file extension
+       if [ ! "${infile:(-$extLength)}" = $fileext ] ; then    
+               fileHasSpaces=true
+               continue
+       fi
+
+       fileHasSpaces=false
+#      echo $infile
+
+       # replace input file directory with output directory
+       # ${string/substring/replacement}
+       outfile=${infile/$indir/$outdir}
+#      echo $outfile
+
+       # strip filename from back of the output file
+       # ${string%substring} - /* strips from last '/' to end
+       outpath=${outfile%/*}
+#      echo $outpath
+
+       # create output directory
+       [ ! -d  "$outpath" ] && mkdir  -p  "$outpath"
+
+       #  copy or move the files
+       $copyfiles  -f  "$infile"  "$outpath"
+       if [ $? -ne 0 ] ; then  
+               read -sn1 -p "press any key to continue!"
+               echo
+       fi
+
+       # echo for every 100 files processed
+       let count++
+       let mod=count%100
+       [ $mod -eq 0 ] && echo $count files processed
+done
+
+echo $count files processed
+echo
diff --git a/tools/style/astyle-cpp-format.sh b/tools/style/astyle-cpp-format.sh
new file mode 100755 (executable)
index 0000000..48f95a8
--- /dev/null
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+astyle --style=allman --indent=spaces=4 --min-conditional-indent=0 --align-pointer=name --align-reference=name --indent-classes --indent-switches --indent-cases --indent-namespaces --pad-oper --pad-header --keep-one-line-blocks --keep-one-line-statements --convert-tabs --mode=c --max-code-length=100 --recursive *.cpp *.h
+
+
+
diff --git a/tools/style/iotivity_cpp_astyle.cfg b/tools/style/iotivity_cpp_astyle.cfg
new file mode 100644 (file)
index 0000000..aacca83
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<AStyleSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">\r
+  <CppFormatOnSave>false</CppFormatOnSave>\r
+  <CsFormatOnSave>false</CsFormatOnSave>\r
+  <CppCommandLine>--style=allman --indent=spaces=4 --min-conditional-indent=0 --align-pointer=name --align-reference=name --indent-classes --indent-switches --indent-cases --indent-namespaces --pad-oper --pad-header --keep-one-line-blocks --keep-one-line-statements --convert-tabs --mode=c --max-code-length=100</CppCommandLine>\r
+  <CsCommandLine />\r
+  <Version>2.1.0.0</Version>\r
+</AStyleSettings>\r
diff --git a/tools/style/iotivity_cpp_style.xml b/tools/style/iotivity_cpp_style.xml
new file mode 100644 (file)
index 0000000..514f3fb
--- /dev/null
@@ -0,0 +1,167 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>\r
+<profiles version="1">\r
+<profile kind="CodeFormatterProfile" name="IoTivity C/C++ Style" version="1">\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.lineSplit" value="100"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_member_access" value="0"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_base_types" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.keep_else_statement_on_same_line" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_constructor_initializer_list" value="0"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_exception_specification" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_base_types" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_exception_specification" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_arguments" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.comment.min_distance_between_code_and_line_comment" value="1"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_declarator_list" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_bracket" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.tabulation.size" value="4"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_before_else_in_if_statement" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_enumerator_list" value="48"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_declarator_list" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_empty_lines" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.put_empty_statement_on_new_line" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.brace_position_for_method_declaration" value="next_line"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_arguments" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_colon_in_base_clause" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.join_wrapped_lines" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_declarator_list" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.comment.never_indent_line_comments_on_first_column" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_between_empty_brackets" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_bracket" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.brace_position_for_block" value="next_line"/>\r
+<setting id="org.eclipse.cdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.brace_position_for_type_declaration" value="next_line"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_expression_list" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_parameters" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.continuation_indentation" value="2"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_expression_list" value="0"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_binary_operator" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_conditional_expression" value="34"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_access_specifier_extra_spaces" value="0"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_namespace_header" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_compact_if" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_assignment" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_conditional_expression_chain" value="18"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_parameters" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_expression_list" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_exception_specification" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_binary_operator" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_before_identifier_in_function_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_base_clause_in_type_declaration" value="80"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_exception_specification" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_declaration_compare_to_template_header" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_statements_compare_to_body" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_binary_expression" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indent_statements_compare_to_block" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.tabulation.char" value="space"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_parameters" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_before_colon_in_constructor_initializer_list" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.brace_position_for_block_in_case" value="next_line"/>\r
+<setting id="org.eclipse.cdt.core.formatter.compact_else_if" value="true"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_after_template_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_colon_in_base_clause" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.keep_then_statement_on_same_line" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.brace_position_for_switch" value="next_line"/>\r
+<setting id="org.eclipse.cdt.core.formatter.alignment_for_overloaded_left_shift_chain" value="16"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.keep_imple_if_on_one_line" value="false"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.indentation.size" value="4"/>\r
+<setting id="org.eclipse.cdt.core.formatter.brace_position_for_namespace_declaration" value="next_line"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_arguments" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.brace_position_for_array_initializer" value="next_line"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_namespace_declaration" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_closing_bracket" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_parameters" value="insert"/>\r
+<setting id="org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_arguments" value="insert"/>\r
+</profile>\r
+</profiles>\r
diff --git a/tools/style/iotivity_java_style.xml b/tools/style/iotivity_java_style.xml
new file mode 100644 (file)
index 0000000..e7dd02a
--- /dev/null
@@ -0,0 +1,291 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>\r
+<profiles version="12">\r
+<profile kind="CodeFormatterProfile" name="IoTivity Java Style" version="12">\r
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>\r
+<setting id="org.eclipse.jdt.core.compiler.source" value="1.7"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="80"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="8"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>\r
+<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>\r
+<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7"/>\r
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.7"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>\r
+<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="80"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>\r
+<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>\r
+<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>\r
+</profile>\r
+</profiles>\r
diff --git a/tools/tizen/.gbs.conf b/tools/tizen/.gbs.conf
new file mode 100644 (file)
index 0000000..37128eb
--- /dev/null
@@ -0,0 +1,39 @@
+[general]
+#Current profile name which should match a profile section name
+profile = profile.tizen
+
+[profile.tizen]
+#Common authentication info for whole profile
+#user =
+#CAUTION: please use the key name "passwd" to reset plaintext password
+#passwd =
+obs = obs.tizen
+#Comma separated list of repositories
+repos = repo.tizen_latest
+#repos = repo.tizen_main, repo.tizen_base
+#Build config for gbs build
+#buildconf = <patch/to/build-config-file>
+#Comma separated list of additional packages be excluded building
+#exclude_packages = libtool,gettext
+
+
+[obs.tizen]
+#OBS API URL pointing to a remote OBS.
+url = https://api.tizen.org
+#Optional user and password, set if differ from profile's user and password
+#user =
+#passwd =
+
+#Repo section example
+[repo.tizen_latest]
+#Build against repo's URL
+url = http://download.tizen.org/releases/2.3/2.3-mobile/tizen-2.3-mobile_20150206.1/repos/target/packages/
+#Optional user and password, set if differ from profile's user and password
+#user =
+#passwd =
+
+#Individual repo is also supported
+#[repo.tizen_base]
+#url = http://download.tizen.org/releases/daily/trunk/ivi/latest/repos/base/ia32/packages/
+#[repo.tizen_main]
+#url = http://download.tizen.org/releases/daily/trunk/ivi/latest/repos/ivi/ia32/packages/
index 7f4358c..e23930f 100644 (file)
@@ -1,5 +1,5 @@
 Name: iotivity
-Version: 0.9
+Version: 0.9.1
 Release: 0
 Summary: IoTivity Base Stack & IoTivity Services
 Group: System Environment/Libraries
@@ -12,6 +12,14 @@ BuildRequires:       python, libcurl-devel
 BuildRequires: scons
 BuildRequires: openssl-devel
 BuildRequires:  boost-devel
+BuildRequires:  boost-thread
+BuildRequires:  boost-system
+BuildRequires:  boost-filesystem
+BuildRequires:  pkgconfig(dlog)
+BuildRequires:  pkgconfig(uuid)
+BuildRequires:  pkgconfig(capi-network-wifi)
+BuildRequires:  pkgconfig(capi-network-bluetooth)
+BuildRequires:  pkgconfig(capi-appfw-app-common)
 Requires(postun): /sbin/ldconfig
 Requires(post): /sbin/ldconfig
 
@@ -32,24 +40,49 @@ developing applications that use %{name}.
 %setup -q -n %{name}-%{version}
 
 %build
+%ifarch armv7l
+export RPM_ARCH=armeabi-v7a
+%else
 %ifarch %arm
 export RPM_ARCH=arm
 %else
+%ifarch aarch64
+export RPM_ARCH=arm64
+%else
+%ifarch i586 i686 %{ix86}
 export RPM_ARCH=x86
+%else
+export RPM_ARCH=%{_arch}
+%endif
 %endif
+%endif
+%endif
+
 
-scons -j 4 TARGET_ARCH=$RPM_ARCH
+scons -j 4 TARGET_OS=tizen TARGET_ARCH=$RPM_ARCH TARGET_TRANSPORT=IP
 
 %install
 rm -rf %{buildroot}
 mkdir -p %{buildroot}%{_includedir}
+mkdir -p %{buildroot}%{_includedir}/targets
 mkdir -p %{buildroot}%{_libdir}
 mkdir -p %{buildroot}%{_sbindir}
 
-cp out/linux/*/release/lib*.so %{buildroot}%{_libdir}
-cp out/linux/*/release/lib*.a %{buildroot}%{_libdir}
+cp out/tizen/*/release/lib*.so %{buildroot}%{_libdir}
+cp out/tizen/*/release/libSSMSDK.a %{buildroot}%{_libdir}
+cp out/tizen/*/release/libppm.a %{buildroot}%{_libdir}
+cp out/tizen/*/release/service/protocol-plugin/plugins/mqtt-fan/*.so %{buildroot}%{_libdir}
+cp out/tizen/*/release/service/protocol-plugin/plugins/mqtt-light/*.so %{buildroot}%{_libdir}
+cp /usr/lib/libuuid.so %{buildroot}%{_libdir}
 
 cp resource/csdk/stack/include/ocstack.h %{buildroot}%{_includedir}
+cp resource/csdk/stack/include/ocstackconfig.h %{buildroot}%{_includedir}
+cp resource/oc_logger/include/oc_logger.hpp %{buildroot}%{_includedir}
+cp resource/oc_logger/include/oc_log_stream.hpp %{buildroot}%{_includedir}
+cp resource/oc_logger/include/oc_logger.h %{buildroot}%{_includedir}
+cp resource/oc_logger/include/oc_logger_types.h %{buildroot}%{_includedir}
+cp resource/oc_logger/include/targets/oc_console_logger.h %{buildroot}%{_includedir}/targets
+cp resource/oc_logger/include/targets/oc_ostream_logger.h %{buildroot}%{_includedir}/targets
 cp resource/include/*.h %{buildroot}%{_includedir}
 
 cp service/things-manager/sdk/inc/*.h %{buildroot}%{_includedir}
@@ -67,7 +100,9 @@ rm -rf %{buildroot}
 %defattr(-,root,root,-)
 %{_libdir}/lib*.so
 %{_libdir}/lib*.a
+%{_libdir}/fanserver*.so
+%{_libdir}/lightserver*.so
 
 %files devel
 %defattr(-,root,root,-)
-%{_includedir}/*.h
+%{_includedir}/*
diff --git a/tools/tizen/scons-2.1.0-3.1.slp.noarch.rpm b/tools/tizen/scons-2.1.0-3.1.slp.noarch.rpm
new file mode 100644 (file)
index 0000000..4c2d8a0
Binary files /dev/null and b/tools/tizen/scons-2.1.0-3.1.slp.noarch.rpm differ
diff --git a/tools/vagrant/README.md b/tools/vagrant/README.md
new file mode 100644 (file)
index 0000000..4de319f
--- /dev/null
@@ -0,0 +1,57 @@
+IoTivity Build VM from Vagrant
+==============================
+
+Vagrant can use the files in this directory to provision an Ubuntu 12.04
+development environment for IoTivity.  To create a new VM type
+
+    % vagrant up
+
+in the current directory.  You can then connect to the VM with
+
+    % vagrant ssh
+
+On the newly provisioned VM, the IoTivity repo will be checked out in 
+the `iotivity` directory in the vagrant user's home directory and
+configured to use the Arduino SDKs which are automatically downloaded
+and installed in the home directory and patched when the VM is provisioned.
+
+Using Vagrant to build a VM might be useful for:
+
+* Testing the build process on a clean install to make sure all dependencies
+  are captured
+
+* Configuring a Linux build environment for Windows or Mac users
+
+* Configuring build VMs for build automation
+
+The bootstrap.sh and iotivity-setup.sh files can be used independent of
+Vagrant to configure a existing Ubuntu environment.  How to do so is left
+as an exercise for the reader.  (Hint: try `sudo bootstrap.sh && 
+iotivity-setup.sh`.)
+
+For more information about Vagrant, please see https://docs.vagrantup.com/v2/
+
+Assumptions
+===========
+
+* The ${HOME}/.ssh/ directory contains config, id_rsa, id_rsa.pub, and
+  known_hosts, that when copied to the VM will allow connection to the
+  git repo.  (And that you don't mind those files being copied to the VM.)
+
+* If a USER environment variable, it has the user name to use for git
+  otherwise, USERNAME has the user ID for git.  USER should work for
+  Linux and USERNAME works inside Git bash on Windows.
+
+To Do
+=====
+
+* Everything is dumped into the top-level directory.  A cleaner layout
+  would be better (e.g., move the Arduino libraries to iotivity/extlibs).
+
+* Verify on more configurations (tested on Git bash under Windows)
+
+* Try with Ubuntu 14.04
+
+* Have a more flexible way to determine the git user name
+
+* Install Android NDK
diff --git a/tools/vagrant/Vagrantfile b/tools/vagrant/Vagrantfile
new file mode 100644 (file)
index 0000000..d4fc989
--- /dev/null
@@ -0,0 +1,48 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
+VAGRANTFILE_API_VERSION = "2"
+
+Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
+  # Every Vagrant virtual environment requires a box to build off of.
+  config.vm.box = "hashicorp/precise64"
+
+  # Disable automatic box update checking. If you disable this, then
+  # boxes will only be checked for updates when the user runs
+  # `vagrant box outdated`. This is not recommended.
+  # config.vm.box_check_update = false
+
+  # Create a forwarded port mapping which allows access to a specific port
+  # within the machine from a port on the host machine. In the example below,
+  # accessing "localhost:8080" will access port 80 on the guest machine.
+  # config.vm.network "forwarded_port", guest: 80, host: 8080
+
+  # Create a private network, which allows host-only access to the machine
+  # using a specific IP.
+  # config.vm.network "private_network", ip: "192.168.33.10"
+
+  # Create a public network, which generally matched to bridged network.
+  # Bridged networks make the machine appear as another physical device on
+  # your network.
+  # config.vm.network "public_network"
+
+  config.vm.provision :file, source: "~/.gitconfig", destination: ".gitconfig"
+  # maybe should have a separate key for Vagrant
+  config.vm.provision :file, source: "~/.ssh/id_rsa", destination: ".ssh/id_rsa"
+  config.vm.provision :file, source: "~/.ssh/id_rsa.pub", destination: ".ssh/id_rsa.pub"
+  config.vm.provision :file, source: "~/.ssh/known_hosts", destination: ".ssh/known_hosts"
+  config.vm.provision :file, source: "~/.ssh/config", destination: ".ssh/config"
+
+  # Simple script configuration
+  config.vm.provision :shell, path: "bootstrap.sh"
+  config.vm.provision :shell do |shell|
+    shell.path = "iotivity-setup.sh"
+    user = ENV['USER']
+    if (user.empty?)
+      user = ENV['USERNAME']
+    end
+    shell.args = "#{user}"
+    shell.privileged = false
+  end
+end
diff --git a/tools/vagrant/bootstrap.sh b/tools/vagrant/bootstrap.sh
new file mode 100644 (file)
index 0000000..13602cc
--- /dev/null
@@ -0,0 +1,10 @@
+apt-get update
+apt-get install -y git build-essential ia32-libs scons make g++ unzip 
+apt-get install -y libboost-dev libboost-program-options-dev libcurl4-nss-dev
+
+# for Android development
+apt-get install -y openjdk-6-jdk
+apt-get install -y icedtea-plugin
+
+# for more pleasant development UX in the VM
+apt-get install -y vim
diff --git a/tools/vagrant/iotivity-setup.sh b/tools/vagrant/iotivity-setup.sh
new file mode 100644 (file)
index 0000000..1de6847
--- /dev/null
@@ -0,0 +1,117 @@
+#!/bin/bash
+
+# User ID to use with git
+GIT_USER=$1
+
+function die {
+       echo $1
+       exit 255
+}
+
+# if file $1 does not exist, call wget on $2
+function wget_if_not_exists {
+       test -f $1 || wget -q $2 || die "$1 does not exist and wget failed for $2"
+}
+
+# If you are behind a proxy, add all the environment variables required to
+# set the proxy appropriately for your environment.
+#source /vagrant/proxy_config
+
+# Protect the private key for better security (and so that ssh will work)
+chmod 600 .ssh/id_rsa
+
+# Cannot use repo directory on host if host is Windows, because
+# Windows does not handle symlinks properly
+if [ ! -d "iotivity" ]
+then
+       git clone ssh://${GIT_USER}@gerrit.iotivity.org/iotivity || die "git failed"
+       scp -p -P 29418 ${GIT_USER}@gerrit.iotivity.org:hooks/commit-msg iotivity/.git/hooks/
+fi
+
+export CEREAL_DIR=iotivity/extlibs/cereal
+if [ ! -d ${CEREAL_DIR} ]
+then
+       git clone https://github.com/USCiLab/cereal.git ${CEREAL_DIR}
+       pushd ${CEREAL_DIR}
+       git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245
+       git apply ../../resource/patches/cereal_gcc46.patch
+       popd
+fi
+
+#######################################
+# Android 
+#######################################
+
+echo "Set up Android NDK"
+export ANDROID_NDK=${PWD}/iotivity/tools/android-ndk
+if [ ! -d ${ANDROID_NDK} ]
+then
+       mkdir -p ${ANDROID_NDK}
+       pushd ${ANDROID_NDK}
+       wget_if_not_exists "android-ndk-r10d-linux-x86_64.bin" http://dl.google.com/android/ndk/android-ndk-r10d-linux-x86_64.bin
+       chmod a+x android-ndk-r10d-linux-x86_64.bin
+       ./android-ndk-r10d-linux-x86_64.bin
+       popd
+fi
+
+echo "Set up Android NDK"
+export ANDROID_SDK=${PWD}/iotivity/tools/android-sdk-linux
+if [ ! -d ${ANDROID_SDK} ]
+then
+       pushd iotivity/tools
+       cd ..
+       wget_if_not_exists "android-sdk_r24.0.2-linux.tgz" http://dl.google.com/android/android-sdk_r24.0.2-linux.tgz
+       tar -xzf http://dl.google.com/android/android-sdk_r24.0.2-linux.tgz
+       popd
+fi
+
+#######################################
+# Arduino Dependencies
+#######################################
+
+# Arduino Mega
+echo "Set up Arduino Mega"
+export ARDUINO_MEGA_DIR=${PWD}/arduino-1.0.5
+if [ ! -d ${ARDUINO_MEGA_DIR} ]
+then
+       wget_if_not_exists "arduino-1.0.5-linux64.tgz" http://arduino.googlecode.com/files/arduino-1.0.5-linux64.tgz
+       tar -xzf arduino-1.0.5-linux64.tgz
+       wget_if_not_exists "Time-1.0.5.zip" http://playground.arduino.cc/uploads/Code/Time.zip
+       mv Time.zip Time-1.0.5.zip
+       mkdir -p ${ARDUINO_MEGA_DIR}/libraries/Time
+       pushd ${ARDUINO_MEGA_DIR}/libraries/Time
+       unzip ../../../Time-1.0.5.zip
+       cd ../..
+       patch -p5 < ../iotivity/tools/arduino/patches/arduino-1.0.5_linux.patch
+       popd
+fi
+
+# Arduino Due
+echo "Set up Arduino Due"
+ARDUINO_DUE_DIR=${PWD}/arduino-1.5.7
+if [ ! -d ${ARDUINO_DUE_DIR} ]
+then
+       wget_if_not_exists "download.php?f=%2Farduino-1.5.7-linux64.tgz" http://arduino.cc/download.php?f=/arduino-1.5.7-linux64.tgz
+       tar -xzf "download.php?f=%2Farduino-1.5.7-linux64.tgz"
+       wget_if_not_exists "Time-1.5.7.zip" http://www.pjrc.com/teensy/arduino_libraries/Time.zip
+       mv Time.zip Time-1.5.7.zip
+       mkdir -p ${ARDUINO_DUE_DIR}/libraries/Time
+       pushd ${ARDUINO_DUE_DIR}/libraries/Time
+       unzip ../../../Time-1.5.7.zip
+       cd ../..
+       patch -p5 < ../iotivity/tools/arduino/patches/arduino-1.5.7_linux.patch
+       popd
+fi
+
+# local.properties
+cat > iotivity/resource/csdk/local.properties <<EOF
+ifeq (\$(PLATFORM), arduinomega)
+       #Location of arduino sdk for Arduino Mega
+       ARDUINO_DIR := ${ARDUINO_MEGA_DIR}
+       ARDUINO_TOOLS_DIR := \$(ARDUINO_DIR)/hardware/tools/avr/bin
+else
+       #Location of arduino sdk for Arduino Due
+       ARDUINO_DIR := ${ARDUINO_DUE_DIR}
+       ARDUINO_TOOLS_DIR := \$(ARDUINO_DIR)/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin
+endif
+EOF